]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/t4_main.c
cxgbe(4): Fix "set but not used [-Wunused-but-set-variable]" warnings.
[FreeBSD/FreeBSD.git] / sys / dev / cxgbe / t4_main.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_ddb.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_kern_tls.h"
37 #include "opt_ratelimit.h"
38 #include "opt_rss.h"
39
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/priv.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/eventhandler.h>
46 #include <sys/module.h>
47 #include <sys/malloc.h>
48 #include <sys/queue.h>
49 #include <sys/taskqueue.h>
50 #include <sys/pciio.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pci_private.h>
54 #include <sys/firmware.h>
55 #include <sys/sbuf.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/sysctl.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/if_dl.h>
64 #include <net/if_vlan_var.h>
65 #ifdef RSS
66 #include <net/rss_config.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #ifdef KERN_TLS
71 #include <netinet/tcp_seq.h>
72 #endif
73 #if defined(__i386__) || defined(__amd64__)
74 #include <machine/md_var.h>
75 #include <machine/cputypes.h>
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #endif
79 #ifdef DDB
80 #include <ddb/ddb.h>
81 #include <ddb/db_lex.h>
82 #endif
83
84 #include "common/common.h"
85 #include "common/t4_msg.h"
86 #include "common/t4_regs.h"
87 #include "common/t4_regs_values.h"
88 #include "cudbg/cudbg.h"
89 #include "t4_clip.h"
90 #include "t4_ioctl.h"
91 #include "t4_l2t.h"
92 #include "t4_mp_ring.h"
93 #include "t4_if.h"
94 #include "t4_smt.h"
95
96 /* T4 bus driver interface */
97 static int t4_probe(device_t);
98 static int t4_attach(device_t);
99 static int t4_detach(device_t);
100 static int t4_child_location(device_t, device_t, struct sbuf *);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static int t4_suspend(device_t);
104 static int t4_resume(device_t);
105 static int t4_reset_prepare(device_t, device_t);
106 static int t4_reset_post(device_t, device_t);
107 static device_method_t t4_methods[] = {
108         DEVMETHOD(device_probe,         t4_probe),
109         DEVMETHOD(device_attach,        t4_attach),
110         DEVMETHOD(device_detach,        t4_detach),
111         DEVMETHOD(device_suspend,       t4_suspend),
112         DEVMETHOD(device_resume,        t4_resume),
113
114         DEVMETHOD(bus_child_location,   t4_child_location),
115         DEVMETHOD(bus_reset_prepare,    t4_reset_prepare),
116         DEVMETHOD(bus_reset_post,       t4_reset_post),
117
118         DEVMETHOD(t4_is_main_ready,     t4_ready),
119         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
120
121         DEVMETHOD_END
122 };
123 static driver_t t4_driver = {
124         "t4nex",
125         t4_methods,
126         sizeof(struct adapter)
127 };
128
129
130 /* T4 port (cxgbe) interface */
131 static int cxgbe_probe(device_t);
132 static int cxgbe_attach(device_t);
133 static int cxgbe_detach(device_t);
134 device_method_t cxgbe_methods[] = {
135         DEVMETHOD(device_probe,         cxgbe_probe),
136         DEVMETHOD(device_attach,        cxgbe_attach),
137         DEVMETHOD(device_detach,        cxgbe_detach),
138         { 0, 0 }
139 };
140 static driver_t cxgbe_driver = {
141         "cxgbe",
142         cxgbe_methods,
143         sizeof(struct port_info)
144 };
145
146 /* T4 VI (vcxgbe) interface */
147 static int vcxgbe_probe(device_t);
148 static int vcxgbe_attach(device_t);
149 static int vcxgbe_detach(device_t);
150 static device_method_t vcxgbe_methods[] = {
151         DEVMETHOD(device_probe,         vcxgbe_probe),
152         DEVMETHOD(device_attach,        vcxgbe_attach),
153         DEVMETHOD(device_detach,        vcxgbe_detach),
154         { 0, 0 }
155 };
156 static driver_t vcxgbe_driver = {
157         "vcxgbe",
158         vcxgbe_methods,
159         sizeof(struct vi_info)
160 };
161
162 static d_ioctl_t t4_ioctl;
163
164 static struct cdevsw t4_cdevsw = {
165        .d_version = D_VERSION,
166        .d_ioctl = t4_ioctl,
167        .d_name = "t4nex",
168 };
169
170 /* T5 bus driver interface */
171 static int t5_probe(device_t);
172 static device_method_t t5_methods[] = {
173         DEVMETHOD(device_probe,         t5_probe),
174         DEVMETHOD(device_attach,        t4_attach),
175         DEVMETHOD(device_detach,        t4_detach),
176         DEVMETHOD(device_suspend,       t4_suspend),
177         DEVMETHOD(device_resume,        t4_resume),
178
179         DEVMETHOD(bus_child_location,   t4_child_location),
180         DEVMETHOD(bus_reset_prepare,    t4_reset_prepare),
181         DEVMETHOD(bus_reset_post,       t4_reset_post),
182
183         DEVMETHOD(t4_is_main_ready,     t4_ready),
184         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
185
186         DEVMETHOD_END
187 };
188 static driver_t t5_driver = {
189         "t5nex",
190         t5_methods,
191         sizeof(struct adapter)
192 };
193
194
195 /* T5 port (cxl) interface */
196 static driver_t cxl_driver = {
197         "cxl",
198         cxgbe_methods,
199         sizeof(struct port_info)
200 };
201
202 /* T5 VI (vcxl) interface */
203 static driver_t vcxl_driver = {
204         "vcxl",
205         vcxgbe_methods,
206         sizeof(struct vi_info)
207 };
208
209 /* T6 bus driver interface */
210 static int t6_probe(device_t);
211 static device_method_t t6_methods[] = {
212         DEVMETHOD(device_probe,         t6_probe),
213         DEVMETHOD(device_attach,        t4_attach),
214         DEVMETHOD(device_detach,        t4_detach),
215         DEVMETHOD(device_suspend,       t4_suspend),
216         DEVMETHOD(device_resume,        t4_resume),
217
218         DEVMETHOD(bus_child_location,   t4_child_location),
219         DEVMETHOD(bus_reset_prepare,    t4_reset_prepare),
220         DEVMETHOD(bus_reset_post,       t4_reset_post),
221
222         DEVMETHOD(t4_is_main_ready,     t4_ready),
223         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
224
225         DEVMETHOD_END
226 };
227 static driver_t t6_driver = {
228         "t6nex",
229         t6_methods,
230         sizeof(struct adapter)
231 };
232
233
234 /* T6 port (cc) interface */
235 static driver_t cc_driver = {
236         "cc",
237         cxgbe_methods,
238         sizeof(struct port_info)
239 };
240
241 /* T6 VI (vcc) interface */
242 static driver_t vcc_driver = {
243         "vcc",
244         vcxgbe_methods,
245         sizeof(struct vi_info)
246 };
247
248 /* ifnet interface */
249 static void cxgbe_init(void *);
250 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
251 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
252 static void cxgbe_qflush(struct ifnet *);
253 #if defined(KERN_TLS) || defined(RATELIMIT)
254 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
255     struct m_snd_tag **);
256 #endif
257
258 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
259
260 /*
261  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
262  * then ADAPTER_LOCK, then t4_uld_list_lock.
263  */
264 static struct sx t4_list_lock;
265 SLIST_HEAD(, adapter) t4_list;
266 #ifdef TCP_OFFLOAD
267 static struct sx t4_uld_list_lock;
268 SLIST_HEAD(, uld_info) t4_uld_list;
269 #endif
270
271 /*
272  * Tunables.  See tweak_tunables() too.
273  *
274  * Each tunable is set to a default value here if it's known at compile-time.
275  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
276  * provide a reasonable default (upto n) when the driver is loaded.
277  *
278  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
279  * T5 are under hw.cxl.
280  */
281 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) parameters");
283 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) T5+ parameters");
285 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
286     "cxgbe(4) TOE parameters");
287
288 /*
289  * Number of queues for tx and rx, NIC and offload.
290  */
291 #define NTXQ 16
292 int t4_ntxq = -NTXQ;
293 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
294     "Number of TX queues per port");
295 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);      /* Old name, undocumented */
296
297 #define NRXQ 8
298 int t4_nrxq = -NRXQ;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
300     "Number of RX queues per port");
301 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);      /* Old name, undocumented */
302
303 #define NTXQ_VI 1
304 static int t4_ntxq_vi = -NTXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
306     "Number of TX queues per VI");
307
308 #define NRXQ_VI 1
309 static int t4_nrxq_vi = -NRXQ_VI;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
311     "Number of RX queues per VI");
312
313 static int t4_rsrv_noflowq = 0;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
315     0, "Reserve TX queue 0 of each VI for non-flowid packets");
316
317 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
318 #define NOFLDTXQ 8
319 static int t4_nofldtxq = -NOFLDTXQ;
320 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
321     "Number of offload TX queues per port");
322
323 #define NOFLDRXQ 2
324 static int t4_nofldrxq = -NOFLDRXQ;
325 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
326     "Number of offload RX queues per port");
327
328 #define NOFLDTXQ_VI 1
329 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
330 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
331     "Number of offload TX queues per VI");
332
333 #define NOFLDRXQ_VI 1
334 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
335 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
336     "Number of offload RX queues per VI");
337
338 #define TMR_IDX_OFLD 1
339 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
341     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
342
343 #define PKTC_IDX_OFLD (-1)
344 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
346     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
347
348 /* 0 means chip/fw default, non-zero number is value in microseconds */
349 static u_long t4_toe_keepalive_idle = 0;
350 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
351     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
352
353 /* 0 means chip/fw default, non-zero number is value in microseconds */
354 static u_long t4_toe_keepalive_interval = 0;
355 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
356     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
357
358 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
359 static int t4_toe_keepalive_count = 0;
360 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
361     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
362
363 /* 0 means chip/fw default, non-zero number is value in microseconds */
364 static u_long t4_toe_rexmt_min = 0;
365 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
366     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
367
368 /* 0 means chip/fw default, non-zero number is value in microseconds */
369 static u_long t4_toe_rexmt_max = 0;
370 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
372
373 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
374 static int t4_toe_rexmt_count = 0;
375 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
376     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
377
378 /* -1 means chip/fw default, other values are raw backoff values to use */
379 static int t4_toe_rexmt_backoff[16] = {
380         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
381 };
382 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
383     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
384     "cxgbe(4) TOE retransmit backoff values");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[0], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[1], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[2], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[3], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[4], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[5], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[6], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[7], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[8], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[9], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[10], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[11], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[12], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[13], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[14], 0, "");
415 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
416     &t4_toe_rexmt_backoff[15], 0, "");
417
418 static int t4_toe_tls_rx_timeout = 5;
419 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, tls_rx_timeout, CTLFLAG_RDTUN,
420     &t4_toe_tls_rx_timeout, 0,
421     "Timeout in seconds to downgrade TLS sockets to plain TOE");
422 #endif
423
424 #ifdef DEV_NETMAP
425 #define NN_MAIN_VI      (1 << 0)        /* Native netmap on the main VI */
426 #define NN_EXTRA_VI     (1 << 1)        /* Native netmap on the extra VI(s) */
427 static int t4_native_netmap = NN_EXTRA_VI;
428 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
429     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
430
431 #define NNMTXQ 8
432 static int t4_nnmtxq = -NNMTXQ;
433 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
434     "Number of netmap TX queues");
435
436 #define NNMRXQ 8
437 static int t4_nnmrxq = -NNMRXQ;
438 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
439     "Number of netmap RX queues");
440
441 #define NNMTXQ_VI 2
442 static int t4_nnmtxq_vi = -NNMTXQ_VI;
443 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
444     "Number of netmap TX queues per VI");
445
446 #define NNMRXQ_VI 2
447 static int t4_nnmrxq_vi = -NNMRXQ_VI;
448 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
449     "Number of netmap RX queues per VI");
450 #endif
451
452 /*
453  * Holdoff parameters for ports.
454  */
455 #define TMR_IDX 1
456 int t4_tmr_idx = TMR_IDX;
457 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
458     0, "Holdoff timer index");
459 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);     /* Old name */
460
461 #define PKTC_IDX (-1)
462 int t4_pktc_idx = PKTC_IDX;
463 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
464     0, "Holdoff packet counter index");
465 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);     /* Old name */
466
467 /*
468  * Size (# of entries) of each tx and rx queue.
469  */
470 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
471 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
472     "Number of descriptors in each TX queue");
473
474 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
476     "Number of descriptors in each RX queue");
477
478 /*
479  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
480  */
481 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
482 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
483     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
484
485 /*
486  * Configuration file.  All the _CF names here are special.
487  */
488 #define DEFAULT_CF      "default"
489 #define BUILTIN_CF      "built-in"
490 #define FLASH_CF        "flash"
491 #define UWIRE_CF        "uwire"
492 #define FPGA_CF         "fpga"
493 static char t4_cfg_file[32] = DEFAULT_CF;
494 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
495     sizeof(t4_cfg_file), "Firmware configuration file");
496
497 /*
498  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
499  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
500  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
501  *            mark or when signalled to do so, 0 to never emit PAUSE.
502  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
503  *                 negotiated settings will override rx_pause/tx_pause.
504  *                 Otherwise rx_pause/tx_pause are applied forcibly.
505  */
506 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
507 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
508     &t4_pause_settings, 0,
509     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
510
511 /*
512  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
513  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
514  *  0 to disable FEC.
515  */
516 static int t4_fec = -1;
517 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
518     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
519
520 /*
521  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
522  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
523  * driver runs as if this is set to 0.
524  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
525  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
526  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
527  *    the firmware anyway (may result in l1cfg errors with old firmwares).
528  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
529  *    means set all FEC bits that are valid for the speed.
530  */
531 static int t4_force_fec = -1;
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
533     "Controls the use of FORCE_FEC bit in L1 configuration.");
534
535 /*
536  * Link autonegotiation.
537  * -1 to run with the firmware default.
538  *  0 to disable.
539  *  1 to enable.
540  */
541 static int t4_autoneg = -1;
542 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
543     "Link autonegotiation");
544
545 /*
546  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
547  * encouraged respectively).  '-n' is the same as 'n' except the firmware
548  * version used in the checks is read from the firmware bundled with the driver.
549  */
550 static int t4_fw_install = 1;
551 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
552     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
553
554 /*
555  * ASIC features that will be used.  Disable the ones you don't want so that the
556  * chip resources aren't wasted on features that will not be used.
557  */
558 static int t4_nbmcaps_allowed = 0;
559 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
560     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
561
562 static int t4_linkcaps_allowed = 0;     /* No DCBX, PPP, etc. by default */
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
564     &t4_linkcaps_allowed, 0, "Default link capabilities");
565
566 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
567     FW_CAPS_CONFIG_SWITCH_EGRESS;
568 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
569     &t4_switchcaps_allowed, 0, "Default switch capabilities");
570
571 #ifdef RATELIMIT
572 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
573         FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
574 #else
575 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
576         FW_CAPS_CONFIG_NIC_HASHFILTER;
577 #endif
578 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
579     &t4_niccaps_allowed, 0, "Default NIC capabilities");
580
581 static int t4_toecaps_allowed = -1;
582 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
583     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
584
585 static int t4_rdmacaps_allowed = -1;
586 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
587     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
588
589 static int t4_cryptocaps_allowed = -1;
590 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
591     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
592
593 static int t4_iscsicaps_allowed = -1;
594 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
595     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
596
597 static int t4_fcoecaps_allowed = 0;
598 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
599     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
600
601 static int t5_write_combine = 0;
602 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
603     0, "Use WC instead of UC for BAR2");
604
605 static int t4_num_vis = 1;
606 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
607     "Number of VIs per port");
608
609 /*
610  * PCIe Relaxed Ordering.
611  * -1: driver should figure out a good value.
612  * 0: disable RO.
613  * 1: enable RO.
614  * 2: leave RO alone.
615  */
616 static int pcie_relaxed_ordering = -1;
617 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
618     &pcie_relaxed_ordering, 0,
619     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
620
621 static int t4_panic_on_fatal_err = 0;
622 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
623     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
624
625 static int t4_reset_on_fatal_err = 0;
626 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
627     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
628
629 static int t4_tx_vm_wr = 0;
630 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
631     "Use VM work requests to transmit packets.");
632
633 /*
634  * Set to non-zero to enable the attack filter.  A packet that matches any of
635  * these conditions will get dropped on ingress:
636  * 1) IP && source address == destination address.
637  * 2) TCP/IP && source address is not a unicast address.
638  * 3) TCP/IP && destination address is not a unicast address.
639  * 4) IP && source address is loopback (127.x.y.z).
640  * 5) IP && destination address is loopback (127.x.y.z).
641  * 6) IPv6 && source address == destination address.
642  * 7) IPv6 && source address is not a unicast address.
643  * 8) IPv6 && source address is loopback (::1/128).
644  * 9) IPv6 && destination address is loopback (::1/128).
645  * 10) IPv6 && source address is unspecified (::/128).
646  * 11) IPv6 && destination address is unspecified (::/128).
647  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
648  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
649  */
650 static int t4_attack_filter = 0;
651 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
652     &t4_attack_filter, 0, "Drop suspicious traffic");
653
654 static int t4_drop_ip_fragments = 0;
655 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
656     &t4_drop_ip_fragments, 0, "Drop IP fragments");
657
658 static int t4_drop_pkts_with_l2_errors = 1;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
660     &t4_drop_pkts_with_l2_errors, 0,
661     "Drop all frames with Layer 2 length or checksum errors");
662
663 static int t4_drop_pkts_with_l3_errors = 0;
664 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
665     &t4_drop_pkts_with_l3_errors, 0,
666     "Drop all frames with IP version, length, or checksum errors");
667
668 static int t4_drop_pkts_with_l4_errors = 0;
669 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
670     &t4_drop_pkts_with_l4_errors, 0,
671     "Drop all frames with Layer 4 length, checksum, or other errors");
672
673 #ifdef TCP_OFFLOAD
674 /*
675  * TOE tunables.
676  */
677 static int t4_cop_managed_offloading = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
679     &t4_cop_managed_offloading, 0,
680     "COP (Connection Offload Policy) controls all TOE offload");
681 #endif
682
683 #ifdef KERN_TLS
684 /*
685  * This enables KERN_TLS for all adapters if set.
686  */
687 static int t4_kern_tls = 0;
688 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
689     "Enable KERN_TLS mode for all supported adapters");
690
691 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
692     "cxgbe(4) KERN_TLS parameters");
693
694 static int t4_tls_inline_keys = 0;
695 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
696     &t4_tls_inline_keys, 0,
697     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
698     "in card memory.");
699
700 static int t4_tls_combo_wrs = 0;
701 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
702     0, "Attempt to combine TCB field updates with TLS record work requests.");
703 #endif
704
705 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
706 static int vi_mac_funcs[] = {
707         FW_VI_FUNC_ETH,
708         FW_VI_FUNC_OFLD,
709         FW_VI_FUNC_IWARP,
710         FW_VI_FUNC_OPENISCSI,
711         FW_VI_FUNC_OPENFCOE,
712         FW_VI_FUNC_FOISCSI,
713         FW_VI_FUNC_FOFCOE,
714 };
715
716 struct intrs_and_queues {
717         uint16_t intr_type;     /* INTx, MSI, or MSI-X */
718         uint16_t num_vis;       /* number of VIs for each port */
719         uint16_t nirq;          /* Total # of vectors */
720         uint16_t ntxq;          /* # of NIC txq's for each port */
721         uint16_t nrxq;          /* # of NIC rxq's for each port */
722         uint16_t nofldtxq;      /* # of TOE/ETHOFLD txq's for each port */
723         uint16_t nofldrxq;      /* # of TOE rxq's for each port */
724         uint16_t nnmtxq;        /* # of netmap txq's */
725         uint16_t nnmrxq;        /* # of netmap rxq's */
726
727         /* The vcxgbe/vcxl interfaces use these and not the ones above. */
728         uint16_t ntxq_vi;       /* # of NIC txq's */
729         uint16_t nrxq_vi;       /* # of NIC rxq's */
730         uint16_t nofldtxq_vi;   /* # of TOE txq's */
731         uint16_t nofldrxq_vi;   /* # of TOE rxq's */
732         uint16_t nnmtxq_vi;     /* # of netmap txq's */
733         uint16_t nnmrxq_vi;     /* # of netmap rxq's */
734 };
735
736 static void setup_memwin(struct adapter *);
737 static void position_memwin(struct adapter *, int, uint32_t);
738 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
739 static int fwmtype_to_hwmtype(int);
740 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
741     uint32_t *);
742 static int fixup_devlog_params(struct adapter *);
743 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
744 static int contact_firmware(struct adapter *);
745 static int partition_resources(struct adapter *);
746 static int get_params__pre_init(struct adapter *);
747 static int set_params__pre_init(struct adapter *);
748 static int get_params__post_init(struct adapter *);
749 static int set_params__post_init(struct adapter *);
750 static void t4_set_desc(struct adapter *);
751 static bool fixed_ifmedia(struct port_info *);
752 static void build_medialist(struct port_info *);
753 static void init_link_config(struct port_info *);
754 static int fixup_link_config(struct port_info *);
755 static int apply_link_config(struct port_info *);
756 static int cxgbe_init_synchronized(struct vi_info *);
757 static int cxgbe_uninit_synchronized(struct vi_info *);
758 static int adapter_full_init(struct adapter *);
759 static void adapter_full_uninit(struct adapter *);
760 static int vi_full_init(struct vi_info *);
761 static void vi_full_uninit(struct vi_info *);
762 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
763 static void quiesce_txq(struct sge_txq *);
764 static void quiesce_wrq(struct sge_wrq *);
765 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
766 static void quiesce_vi(struct vi_info *);
767 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
768     driver_intr_t *, void *, char *);
769 static int t4_free_irq(struct adapter *, struct irq *);
770 static void t4_init_atid_table(struct adapter *);
771 static void t4_free_atid_table(struct adapter *);
772 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
773 static void vi_refresh_stats(struct vi_info *);
774 static void cxgbe_refresh_stats(struct vi_info *);
775 static void cxgbe_tick(void *);
776 static void vi_tick(void *);
777 static void cxgbe_sysctls(struct port_info *);
778 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
779 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
780 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
781 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
782 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
783 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
784 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
785 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
786 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
787 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
788 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
789 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
790 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
791 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
792 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
793 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
794 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
795 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
796 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
797 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
798 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
799 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
800 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
802 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
803 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
804 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
805 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
806 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
808 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
809 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
810 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
811 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
812 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
813 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
814 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
815 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
816 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
817 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
824 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
826 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
827 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
828 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
829 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
830 #ifdef TCP_OFFLOAD
831 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
839 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
840 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
841 #endif
842 static int get_sge_context(struct adapter *, struct t4_sge_context *);
843 static int load_fw(struct adapter *, struct t4_data *);
844 static int load_cfg(struct adapter *, struct t4_data *);
845 static int load_boot(struct adapter *, struct t4_bootrom *);
846 static int load_bootcfg(struct adapter *, struct t4_data *);
847 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
848 static void free_offload_policy(struct t4_offload_policy *);
849 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
850 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
851 static int read_i2c(struct adapter *, struct t4_i2c_data *);
852 static int clear_stats(struct adapter *, u_int);
853 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
854 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
855 #ifdef TCP_OFFLOAD
856 static int toe_capability(struct vi_info *, bool);
857 static void t4_async_event(void *, int);
858 #endif
859 #ifdef KERN_TLS
860 static int ktls_capability(struct adapter *, bool);
861 #endif
862 static int mod_event(module_t, int, void *);
863 static int notify_siblings(device_t, int);
864 static uint64_t vi_get_counter(struct ifnet *, ift_counter);
865 static uint64_t cxgbe_get_counter(struct ifnet *, ift_counter);
866 static void enable_vxlan_rx(struct adapter *);
867 static void reset_adapter(void *, int);
868
869 struct {
870         uint16_t device;
871         char *desc;
872 } t4_pciids[] = {
873         {0xa000, "Chelsio Terminator 4 FPGA"},
874         {0x4400, "Chelsio T440-dbg"},
875         {0x4401, "Chelsio T420-CR"},
876         {0x4402, "Chelsio T422-CR"},
877         {0x4403, "Chelsio T440-CR"},
878         {0x4404, "Chelsio T420-BCH"},
879         {0x4405, "Chelsio T440-BCH"},
880         {0x4406, "Chelsio T440-CH"},
881         {0x4407, "Chelsio T420-SO"},
882         {0x4408, "Chelsio T420-CX"},
883         {0x4409, "Chelsio T420-BT"},
884         {0x440a, "Chelsio T404-BT"},
885         {0x440e, "Chelsio T440-LP-CR"},
886 }, t5_pciids[] = {
887         {0xb000, "Chelsio Terminator 5 FPGA"},
888         {0x5400, "Chelsio T580-dbg"},
889         {0x5401,  "Chelsio T520-CR"},           /* 2 x 10G */
890         {0x5402,  "Chelsio T522-CR"},           /* 2 x 10G, 2 X 1G */
891         {0x5403,  "Chelsio T540-CR"},           /* 4 x 10G */
892         {0x5407,  "Chelsio T520-SO"},           /* 2 x 10G, nomem */
893         {0x5409,  "Chelsio T520-BT"},           /* 2 x 10GBaseT */
894         {0x540a,  "Chelsio T504-BT"},           /* 4 x 1G */
895         {0x540d,  "Chelsio T580-CR"},           /* 2 x 40G */
896         {0x540e,  "Chelsio T540-LP-CR"},        /* 4 x 10G */
897         {0x5410,  "Chelsio T580-LP-CR"},        /* 2 x 40G */
898         {0x5411,  "Chelsio T520-LL-CR"},        /* 2 x 10G */
899         {0x5412,  "Chelsio T560-CR"},           /* 1 x 40G, 2 x 10G */
900         {0x5414,  "Chelsio T580-LP-SO-CR"},     /* 2 x 40G, nomem */
901         {0x5415,  "Chelsio T502-BT"},           /* 2 x 1G */
902         {0x5418,  "Chelsio T540-BT"},           /* 4 x 10GBaseT */
903         {0x5419,  "Chelsio T540-LP-BT"},        /* 4 x 10GBaseT */
904         {0x541a,  "Chelsio T540-SO-BT"},        /* 4 x 10GBaseT, nomem */
905         {0x541b,  "Chelsio T540-SO-CR"},        /* 4 x 10G, nomem */
906
907         /* Custom */
908         {0x5483, "Custom T540-CR"},
909         {0x5484, "Custom T540-BT"},
910 }, t6_pciids[] = {
911         {0xc006, "Chelsio Terminator 6 FPGA"},  /* T6 PE10K6 FPGA (PF0) */
912         {0x6400, "Chelsio T6-DBG-25"},          /* 2 x 10/25G, debug */
913         {0x6401, "Chelsio T6225-CR"},           /* 2 x 10/25G */
914         {0x6402, "Chelsio T6225-SO-CR"},        /* 2 x 10/25G, nomem */
915         {0x6403, "Chelsio T6425-CR"},           /* 4 x 10/25G */
916         {0x6404, "Chelsio T6425-SO-CR"},        /* 4 x 10/25G, nomem */
917         {0x6405, "Chelsio T6225-OCP-SO"},       /* 2 x 10/25G, nomem */
918         {0x6406, "Chelsio T62100-OCP-SO"},      /* 2 x 40/50/100G, nomem */
919         {0x6407, "Chelsio T62100-LP-CR"},       /* 2 x 40/50/100G */
920         {0x6408, "Chelsio T62100-SO-CR"},       /* 2 x 40/50/100G, nomem */
921         {0x6409, "Chelsio T6210-BT"},           /* 2 x 10GBASE-T */
922         {0x640d, "Chelsio T62100-CR"},          /* 2 x 40/50/100G */
923         {0x6410, "Chelsio T6-DBG-100"},         /* 2 x 40/50/100G, debug */
924         {0x6411, "Chelsio T6225-LL-CR"},        /* 2 x 10/25G */
925         {0x6414, "Chelsio T61100-OCP-SO"},      /* 1 x 40/50/100G, nomem */
926         {0x6415, "Chelsio T6201-BT"},           /* 2 x 1000BASE-T */
927
928         /* Custom */
929         {0x6480, "Custom T6225-CR"},
930         {0x6481, "Custom T62100-CR"},
931         {0x6482, "Custom T6225-CR"},
932         {0x6483, "Custom T62100-CR"},
933         {0x6484, "Custom T64100-CR"},
934         {0x6485, "Custom T6240-SO"},
935         {0x6486, "Custom T6225-SO-CR"},
936         {0x6487, "Custom T6225-CR"},
937 };
938
939 #ifdef TCP_OFFLOAD
940 /*
941  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
942  * be exactly the same for both rxq and ofld_rxq.
943  */
944 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
945 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
946 #endif
947 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
948
949 static int
950 t4_probe(device_t dev)
951 {
952         int i;
953         uint16_t v = pci_get_vendor(dev);
954         uint16_t d = pci_get_device(dev);
955         uint8_t f = pci_get_function(dev);
956
957         if (v != PCI_VENDOR_ID_CHELSIO)
958                 return (ENXIO);
959
960         /* Attach only to PF0 of the FPGA */
961         if (d == 0xa000 && f != 0)
962                 return (ENXIO);
963
964         for (i = 0; i < nitems(t4_pciids); i++) {
965                 if (d == t4_pciids[i].device) {
966                         device_set_desc(dev, t4_pciids[i].desc);
967                         return (BUS_PROBE_DEFAULT);
968                 }
969         }
970
971         return (ENXIO);
972 }
973
974 static int
975 t5_probe(device_t dev)
976 {
977         int i;
978         uint16_t v = pci_get_vendor(dev);
979         uint16_t d = pci_get_device(dev);
980         uint8_t f = pci_get_function(dev);
981
982         if (v != PCI_VENDOR_ID_CHELSIO)
983                 return (ENXIO);
984
985         /* Attach only to PF0 of the FPGA */
986         if (d == 0xb000 && f != 0)
987                 return (ENXIO);
988
989         for (i = 0; i < nitems(t5_pciids); i++) {
990                 if (d == t5_pciids[i].device) {
991                         device_set_desc(dev, t5_pciids[i].desc);
992                         return (BUS_PROBE_DEFAULT);
993                 }
994         }
995
996         return (ENXIO);
997 }
998
999 static int
1000 t6_probe(device_t dev)
1001 {
1002         int i;
1003         uint16_t v = pci_get_vendor(dev);
1004         uint16_t d = pci_get_device(dev);
1005
1006         if (v != PCI_VENDOR_ID_CHELSIO)
1007                 return (ENXIO);
1008
1009         for (i = 0; i < nitems(t6_pciids); i++) {
1010                 if (d == t6_pciids[i].device) {
1011                         device_set_desc(dev, t6_pciids[i].desc);
1012                         return (BUS_PROBE_DEFAULT);
1013                 }
1014         }
1015
1016         return (ENXIO);
1017 }
1018
1019 static void
1020 t5_attribute_workaround(device_t dev)
1021 {
1022         device_t root_port;
1023         uint32_t v;
1024
1025         /*
1026          * The T5 chips do not properly echo the No Snoop and Relaxed
1027          * Ordering attributes when replying to a TLP from a Root
1028          * Port.  As a workaround, find the parent Root Port and
1029          * disable No Snoop and Relaxed Ordering.  Note that this
1030          * affects all devices under this root port.
1031          */
1032         root_port = pci_find_pcie_root_port(dev);
1033         if (root_port == NULL) {
1034                 device_printf(dev, "Unable to find parent root port\n");
1035                 return;
1036         }
1037
1038         v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1039             PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1040         if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1041             0)
1042                 device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1043                     device_get_nameunit(root_port));
1044 }
1045
1046 static const struct devnames devnames[] = {
1047         {
1048                 .nexus_name = "t4nex",
1049                 .ifnet_name = "cxgbe",
1050                 .vi_ifnet_name = "vcxgbe",
1051                 .pf03_drv_name = "t4iov",
1052                 .vf_nexus_name = "t4vf",
1053                 .vf_ifnet_name = "cxgbev"
1054         }, {
1055                 .nexus_name = "t5nex",
1056                 .ifnet_name = "cxl",
1057                 .vi_ifnet_name = "vcxl",
1058                 .pf03_drv_name = "t5iov",
1059                 .vf_nexus_name = "t5vf",
1060                 .vf_ifnet_name = "cxlv"
1061         }, {
1062                 .nexus_name = "t6nex",
1063                 .ifnet_name = "cc",
1064                 .vi_ifnet_name = "vcc",
1065                 .pf03_drv_name = "t6iov",
1066                 .vf_nexus_name = "t6vf",
1067                 .vf_ifnet_name = "ccv"
1068         }
1069 };
1070
1071 void
1072 t4_init_devnames(struct adapter *sc)
1073 {
1074         int id;
1075
1076         id = chip_id(sc);
1077         if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1078                 sc->names = &devnames[id - CHELSIO_T4];
1079         else {
1080                 device_printf(sc->dev, "chip id %d is not supported.\n", id);
1081                 sc->names = NULL;
1082         }
1083 }
1084
1085 static int
1086 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1087 {
1088         const char *parent, *name;
1089         long value;
1090         int line, unit;
1091
1092         line = 0;
1093         parent = device_get_nameunit(sc->dev);
1094         name = sc->names->ifnet_name;
1095         while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1096                 if (resource_long_value(name, unit, "port", &value) == 0 &&
1097                     value == pi->port_id)
1098                         return (unit);
1099         }
1100         return (-1);
1101 }
1102
1103 static int
1104 t4_attach(device_t dev)
1105 {
1106         struct adapter *sc;
1107         int rc = 0, i, j, rqidx, tqidx, nports;
1108         struct make_dev_args mda;
1109         struct intrs_and_queues iaq;
1110         struct sge *s;
1111         uint32_t *buf;
1112 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1113         int ofld_tqidx;
1114 #endif
1115 #ifdef TCP_OFFLOAD
1116         int ofld_rqidx;
1117 #endif
1118 #ifdef DEV_NETMAP
1119         int nm_rqidx, nm_tqidx;
1120 #endif
1121         int num_vis;
1122
1123         sc = device_get_softc(dev);
1124         sc->dev = dev;
1125         TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1126
1127         if ((pci_get_device(dev) & 0xff00) == 0x5400)
1128                 t5_attribute_workaround(dev);
1129         pci_enable_busmaster(dev);
1130         if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1131                 uint32_t v;
1132
1133                 pci_set_max_read_req(dev, 4096);
1134                 v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1135                 sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1136                 if (pcie_relaxed_ordering == 0 &&
1137                     (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1138                         v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1139                         pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1140                 } else if (pcie_relaxed_ordering == 1 &&
1141                     (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1142                         v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1143                         pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1144                 }
1145         }
1146
1147         sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1148         sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1149         sc->traceq = -1;
1150         mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1151         snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1152             device_get_nameunit(dev));
1153
1154         snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1155             device_get_nameunit(dev));
1156         mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1157         t4_add_adapter(sc);
1158
1159         mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1160         TAILQ_INIT(&sc->sfl);
1161         callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1162
1163         mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1164
1165         sc->policy = NULL;
1166         rw_init(&sc->policy_lock, "connection offload policy");
1167
1168         callout_init(&sc->ktls_tick, 1);
1169
1170 #ifdef TCP_OFFLOAD
1171         TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1172 #endif
1173
1174         refcount_init(&sc->vxlan_refcount, 0);
1175
1176         TASK_INIT(&sc->reset_task, 0, reset_adapter, sc);
1177
1178         sc->ctrlq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1179             SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1180             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1181         sc->fwq_oid = SYSCTL_ADD_NODE(device_get_sysctl_ctx(sc->dev),
1182             SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1183             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1184
1185         rc = t4_map_bars_0_and_4(sc);
1186         if (rc != 0)
1187                 goto done; /* error message displayed already */
1188
1189         memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1190
1191         /* Prepare the adapter for operation. */
1192         buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1193         rc = -t4_prep_adapter(sc, buf);
1194         free(buf, M_CXGBE);
1195         if (rc != 0) {
1196                 device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1197                 goto done;
1198         }
1199
1200         /*
1201          * This is the real PF# to which we're attaching.  Works from within PCI
1202          * passthrough environments too, where pci_get_function() could return a
1203          * different PF# depending on the passthrough configuration.  We need to
1204          * use the real PF# in all our communication with the firmware.
1205          */
1206         j = t4_read_reg(sc, A_PL_WHOAMI);
1207         sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1208         sc->mbox = sc->pf;
1209
1210         t4_init_devnames(sc);
1211         if (sc->names == NULL) {
1212                 rc = ENOTSUP;
1213                 goto done; /* error message displayed already */
1214         }
1215
1216         /*
1217          * Do this really early, with the memory windows set up even before the
1218          * character device.  The userland tool's register i/o and mem read
1219          * will work even in "recovery mode".
1220          */
1221         setup_memwin(sc);
1222         if (t4_init_devlog_params(sc, 0) == 0)
1223                 fixup_devlog_params(sc);
1224         make_dev_args_init(&mda);
1225         mda.mda_devsw = &t4_cdevsw;
1226         mda.mda_uid = UID_ROOT;
1227         mda.mda_gid = GID_WHEEL;
1228         mda.mda_mode = 0600;
1229         mda.mda_si_drv1 = sc;
1230         rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1231         if (rc != 0)
1232                 device_printf(dev, "failed to create nexus char device: %d.\n",
1233                     rc);
1234
1235         /* Go no further if recovery mode has been requested. */
1236         if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1237                 device_printf(dev, "recovery mode.\n");
1238                 goto done;
1239         }
1240
1241 #if defined(__i386__)
1242         if ((cpu_feature & CPUID_CX8) == 0) {
1243                 device_printf(dev, "64 bit atomics not available.\n");
1244                 rc = ENOTSUP;
1245                 goto done;
1246         }
1247 #endif
1248
1249         /* Contact the firmware and try to become the master driver. */
1250         rc = contact_firmware(sc);
1251         if (rc != 0)
1252                 goto done; /* error message displayed already */
1253         MPASS(sc->flags & FW_OK);
1254
1255         rc = get_params__pre_init(sc);
1256         if (rc != 0)
1257                 goto done; /* error message displayed already */
1258
1259         if (sc->flags & MASTER_PF) {
1260                 rc = partition_resources(sc);
1261                 if (rc != 0)
1262                         goto done; /* error message displayed already */
1263                 t4_intr_clear(sc);
1264         }
1265
1266         rc = get_params__post_init(sc);
1267         if (rc != 0)
1268                 goto done; /* error message displayed already */
1269
1270         rc = set_params__post_init(sc);
1271         if (rc != 0)
1272                 goto done; /* error message displayed already */
1273
1274         rc = t4_map_bar_2(sc);
1275         if (rc != 0)
1276                 goto done; /* error message displayed already */
1277
1278         rc = t4_create_dma_tag(sc);
1279         if (rc != 0)
1280                 goto done; /* error message displayed already */
1281
1282         /*
1283          * First pass over all the ports - allocate VIs and initialize some
1284          * basic parameters like mac address, port type, etc.
1285          */
1286         for_each_port(sc, i) {
1287                 struct port_info *pi;
1288
1289                 pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1290                 sc->port[i] = pi;
1291
1292                 /* These must be set before t4_port_init */
1293                 pi->adapter = sc;
1294                 pi->port_id = i;
1295                 /*
1296                  * XXX: vi[0] is special so we can't delay this allocation until
1297                  * pi->nvi's final value is known.
1298                  */
1299                 pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1300                     M_ZERO | M_WAITOK);
1301
1302                 /*
1303                  * Allocate the "main" VI and initialize parameters
1304                  * like mac addr.
1305                  */
1306                 rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1307                 if (rc != 0) {
1308                         device_printf(dev, "unable to initialize port %d: %d\n",
1309                             i, rc);
1310                         free(pi->vi, M_CXGBE);
1311                         free(pi, M_CXGBE);
1312                         sc->port[i] = NULL;
1313                         goto done;
1314                 }
1315
1316                 if (is_bt(pi->port_type))
1317                         setbit(&sc->bt_map, pi->tx_chan);
1318                 else
1319                         MPASS(!isset(&sc->bt_map, pi->tx_chan));
1320
1321                 snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1322                     device_get_nameunit(dev), i);
1323                 mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1324                 sc->chan_map[pi->tx_chan] = i;
1325
1326                 /*
1327                  * The MPS counter for FCS errors doesn't work correctly on the
1328                  * T6 so we use the MAC counter here.  Which MAC is in use
1329                  * depends on the link settings which will be known when the
1330                  * link comes up.
1331                  */
1332                 if (is_t6(sc)) {
1333                         pi->fcs_reg = -1;
1334                 } else if (is_t4(sc)) {
1335                         pi->fcs_reg = PORT_REG(pi->tx_chan,
1336                             A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1337                 } else {
1338                         pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1339                             A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1340                 }
1341                 pi->fcs_base = 0;
1342
1343                 /* All VIs on this port share this media. */
1344                 ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1345                     cxgbe_media_status);
1346
1347                 PORT_LOCK(pi);
1348                 init_link_config(pi);
1349                 fixup_link_config(pi);
1350                 build_medialist(pi);
1351                 if (fixed_ifmedia(pi))
1352                         pi->flags |= FIXED_IFMEDIA;
1353                 PORT_UNLOCK(pi);
1354
1355                 pi->dev = device_add_child(dev, sc->names->ifnet_name,
1356                     t4_ifnet_unit(sc, pi));
1357                 if (pi->dev == NULL) {
1358                         device_printf(dev,
1359                             "failed to add device for port %d.\n", i);
1360                         rc = ENXIO;
1361                         goto done;
1362                 }
1363                 pi->vi[0].dev = pi->dev;
1364                 device_set_softc(pi->dev, pi);
1365         }
1366
1367         /*
1368          * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1369          */
1370         nports = sc->params.nports;
1371         rc = cfg_itype_and_nqueues(sc, &iaq);
1372         if (rc != 0)
1373                 goto done; /* error message displayed already */
1374
1375         num_vis = iaq.num_vis;
1376         sc->intr_type = iaq.intr_type;
1377         sc->intr_count = iaq.nirq;
1378
1379         s = &sc->sge;
1380         s->nrxq = nports * iaq.nrxq;
1381         s->ntxq = nports * iaq.ntxq;
1382         if (num_vis > 1) {
1383                 s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1384                 s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1385         }
1386         s->neq = s->ntxq + s->nrxq;     /* the free list in an rxq is an eq */
1387         s->neq += nports;               /* ctrl queues: 1 per port */
1388         s->niq = s->nrxq + 1;           /* 1 extra for firmware event queue */
1389 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1390         if (is_offload(sc) || is_ethoffload(sc)) {
1391                 s->nofldtxq = nports * iaq.nofldtxq;
1392                 if (num_vis > 1)
1393                         s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1394                 s->neq += s->nofldtxq;
1395
1396                 s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1397                     M_CXGBE, M_ZERO | M_WAITOK);
1398         }
1399 #endif
1400 #ifdef TCP_OFFLOAD
1401         if (is_offload(sc)) {
1402                 s->nofldrxq = nports * iaq.nofldrxq;
1403                 if (num_vis > 1)
1404                         s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1405                 s->neq += s->nofldrxq;  /* free list */
1406                 s->niq += s->nofldrxq;
1407
1408                 s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1409                     M_CXGBE, M_ZERO | M_WAITOK);
1410         }
1411 #endif
1412 #ifdef DEV_NETMAP
1413         s->nnmrxq = 0;
1414         s->nnmtxq = 0;
1415         if (t4_native_netmap & NN_MAIN_VI) {
1416                 s->nnmrxq += nports * iaq.nnmrxq;
1417                 s->nnmtxq += nports * iaq.nnmtxq;
1418         }
1419         if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1420                 s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1421                 s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1422         }
1423         s->neq += s->nnmtxq + s->nnmrxq;
1424         s->niq += s->nnmrxq;
1425
1426         s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1427             M_CXGBE, M_ZERO | M_WAITOK);
1428         s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1429             M_CXGBE, M_ZERO | M_WAITOK);
1430 #endif
1431         MPASS(s->niq <= s->iqmap_sz);
1432         MPASS(s->neq <= s->eqmap_sz);
1433
1434         s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1435             M_ZERO | M_WAITOK);
1436         s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1437             M_ZERO | M_WAITOK);
1438         s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1439             M_ZERO | M_WAITOK);
1440         s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1441             M_ZERO | M_WAITOK);
1442         s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1443             M_ZERO | M_WAITOK);
1444
1445         sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1446             M_ZERO | M_WAITOK);
1447
1448         t4_init_l2t(sc, M_WAITOK);
1449         t4_init_smt(sc, M_WAITOK);
1450         t4_init_tx_sched(sc);
1451         t4_init_atid_table(sc);
1452 #ifdef RATELIMIT
1453         t4_init_etid_table(sc);
1454 #endif
1455 #ifdef INET6
1456         t4_init_clip_table(sc);
1457 #endif
1458         if (sc->vres.key.size != 0)
1459                 sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1460                     sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1461
1462         /*
1463          * Second pass over the ports.  This time we know the number of rx and
1464          * tx queues that each port should get.
1465          */
1466         rqidx = tqidx = 0;
1467 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1468         ofld_tqidx = 0;
1469 #endif
1470 #ifdef TCP_OFFLOAD
1471         ofld_rqidx = 0;
1472 #endif
1473 #ifdef DEV_NETMAP
1474         nm_rqidx = nm_tqidx = 0;
1475 #endif
1476         for_each_port(sc, i) {
1477                 struct port_info *pi = sc->port[i];
1478                 struct vi_info *vi;
1479
1480                 if (pi == NULL)
1481                         continue;
1482
1483                 pi->nvi = num_vis;
1484                 for_each_vi(pi, j, vi) {
1485                         vi->pi = pi;
1486                         vi->adapter = sc;
1487                         vi->first_intr = -1;
1488                         vi->qsize_rxq = t4_qsize_rxq;
1489                         vi->qsize_txq = t4_qsize_txq;
1490
1491                         vi->first_rxq = rqidx;
1492                         vi->first_txq = tqidx;
1493                         vi->tmr_idx = t4_tmr_idx;
1494                         vi->pktc_idx = t4_pktc_idx;
1495                         vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1496                         vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1497
1498                         rqidx += vi->nrxq;
1499                         tqidx += vi->ntxq;
1500
1501                         if (j == 0 && vi->ntxq > 1)
1502                                 vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1503                         else
1504                                 vi->rsrv_noflowq = 0;
1505
1506 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1507                         vi->first_ofld_txq = ofld_tqidx;
1508                         vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1509                         ofld_tqidx += vi->nofldtxq;
1510 #endif
1511 #ifdef TCP_OFFLOAD
1512                         vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1513                         vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1514                         vi->first_ofld_rxq = ofld_rqidx;
1515                         vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1516
1517                         ofld_rqidx += vi->nofldrxq;
1518 #endif
1519 #ifdef DEV_NETMAP
1520                         vi->first_nm_rxq = nm_rqidx;
1521                         vi->first_nm_txq = nm_tqidx;
1522                         if (j == 0) {
1523                                 vi->nnmrxq = iaq.nnmrxq;
1524                                 vi->nnmtxq = iaq.nnmtxq;
1525                         } else {
1526                                 vi->nnmrxq = iaq.nnmrxq_vi;
1527                                 vi->nnmtxq = iaq.nnmtxq_vi;
1528                         }
1529                         nm_rqidx += vi->nnmrxq;
1530                         nm_tqidx += vi->nnmtxq;
1531 #endif
1532                 }
1533         }
1534
1535         rc = t4_setup_intr_handlers(sc);
1536         if (rc != 0) {
1537                 device_printf(dev,
1538                     "failed to setup interrupt handlers: %d\n", rc);
1539                 goto done;
1540         }
1541
1542         rc = bus_generic_probe(dev);
1543         if (rc != 0) {
1544                 device_printf(dev, "failed to probe child drivers: %d\n", rc);
1545                 goto done;
1546         }
1547
1548         /*
1549          * Ensure thread-safe mailbox access (in debug builds).
1550          *
1551          * So far this was the only thread accessing the mailbox but various
1552          * ifnets and sysctls are about to be created and their handlers/ioctls
1553          * will access the mailbox from different threads.
1554          */
1555         sc->flags |= CHK_MBOX_ACCESS;
1556
1557         rc = bus_generic_attach(dev);
1558         if (rc != 0) {
1559                 device_printf(dev,
1560                     "failed to attach all child ports: %d\n", rc);
1561                 goto done;
1562         }
1563
1564         device_printf(dev,
1565             "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1566             sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1567             sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1568             (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1569             sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1570
1571         t4_set_desc(sc);
1572
1573         notify_siblings(dev, 0);
1574
1575 done:
1576         if (rc != 0 && sc->cdev) {
1577                 /* cdev was created and so cxgbetool works; recover that way. */
1578                 device_printf(dev,
1579                     "error during attach, adapter is now in recovery mode.\n");
1580                 rc = 0;
1581         }
1582
1583         if (rc != 0)
1584                 t4_detach_common(dev);
1585         else
1586                 t4_sysctls(sc);
1587
1588         return (rc);
1589 }
1590
1591 static int
1592 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1593 {
1594         struct adapter *sc;
1595         struct port_info *pi;
1596         int i;
1597
1598         sc = device_get_softc(bus);
1599         for_each_port(sc, i) {
1600                 pi = sc->port[i];
1601                 if (pi != NULL && pi->dev == dev) {
1602                         sbuf_printf(sb, "port=%d", pi->port_id);
1603                         break;
1604                 }
1605         }
1606         return (0);
1607 }
1608
1609 static int
1610 t4_ready(device_t dev)
1611 {
1612         struct adapter *sc;
1613
1614         sc = device_get_softc(dev);
1615         if (sc->flags & FW_OK)
1616                 return (0);
1617         return (ENXIO);
1618 }
1619
1620 static int
1621 t4_read_port_device(device_t dev, int port, device_t *child)
1622 {
1623         struct adapter *sc;
1624         struct port_info *pi;
1625
1626         sc = device_get_softc(dev);
1627         if (port < 0 || port >= MAX_NPORTS)
1628                 return (EINVAL);
1629         pi = sc->port[port];
1630         if (pi == NULL || pi->dev == NULL)
1631                 return (ENXIO);
1632         *child = pi->dev;
1633         return (0);
1634 }
1635
1636 static int
1637 notify_siblings(device_t dev, int detaching)
1638 {
1639         device_t sibling;
1640         int error, i;
1641
1642         error = 0;
1643         for (i = 0; i < PCI_FUNCMAX; i++) {
1644                 if (i == pci_get_function(dev))
1645                         continue;
1646                 sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1647                     pci_get_slot(dev), i);
1648                 if (sibling == NULL || !device_is_attached(sibling))
1649                         continue;
1650                 if (detaching)
1651                         error = T4_DETACH_CHILD(sibling);
1652                 else
1653                         (void)T4_ATTACH_CHILD(sibling);
1654                 if (error)
1655                         break;
1656         }
1657         return (error);
1658 }
1659
1660 /*
1661  * Idempotent
1662  */
1663 static int
1664 t4_detach(device_t dev)
1665 {
1666         int rc;
1667
1668         rc = notify_siblings(dev, 1);
1669         if (rc) {
1670                 device_printf(dev,
1671                     "failed to detach sibling devices: %d\n", rc);
1672                 return (rc);
1673         }
1674
1675         return (t4_detach_common(dev));
1676 }
1677
1678 int
1679 t4_detach_common(device_t dev)
1680 {
1681         struct adapter *sc;
1682         struct port_info *pi;
1683         int i, rc;
1684
1685         sc = device_get_softc(dev);
1686
1687         if (sc->cdev) {
1688                 destroy_dev(sc->cdev);
1689                 sc->cdev = NULL;
1690         }
1691
1692         sx_xlock(&t4_list_lock);
1693         SLIST_REMOVE(&t4_list, sc, adapter, link);
1694         sx_xunlock(&t4_list_lock);
1695
1696         sc->flags &= ~CHK_MBOX_ACCESS;
1697         if (sc->flags & FULL_INIT_DONE) {
1698                 if (!(sc->flags & IS_VF))
1699                         t4_intr_disable(sc);
1700         }
1701
1702         if (device_is_attached(dev)) {
1703                 rc = bus_generic_detach(dev);
1704                 if (rc) {
1705                         device_printf(dev,
1706                             "failed to detach child devices: %d\n", rc);
1707                         return (rc);
1708                 }
1709         }
1710
1711 #ifdef TCP_OFFLOAD
1712         taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1713 #endif
1714
1715         for (i = 0; i < sc->intr_count; i++)
1716                 t4_free_irq(sc, &sc->irq[i]);
1717
1718         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1719                 t4_free_tx_sched(sc);
1720
1721         for (i = 0; i < MAX_NPORTS; i++) {
1722                 pi = sc->port[i];
1723                 if (pi) {
1724                         t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1725                         if (pi->dev)
1726                                 device_delete_child(dev, pi->dev);
1727
1728                         mtx_destroy(&pi->pi_lock);
1729                         free(pi->vi, M_CXGBE);
1730                         free(pi, M_CXGBE);
1731                 }
1732         }
1733
1734         device_delete_children(dev);
1735         adapter_full_uninit(sc);
1736
1737         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1738                 t4_fw_bye(sc, sc->mbox);
1739
1740         if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1741                 pci_release_msi(dev);
1742
1743         if (sc->regs_res)
1744                 bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1745                     sc->regs_res);
1746
1747         if (sc->udbs_res)
1748                 bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1749                     sc->udbs_res);
1750
1751         if (sc->msix_res)
1752                 bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1753                     sc->msix_res);
1754
1755         if (sc->l2t)
1756                 t4_free_l2t(sc->l2t);
1757         if (sc->smt)
1758                 t4_free_smt(sc->smt);
1759         t4_free_atid_table(sc);
1760 #ifdef RATELIMIT
1761         t4_free_etid_table(sc);
1762 #endif
1763         if (sc->key_map)
1764                 vmem_destroy(sc->key_map);
1765 #ifdef INET6
1766         t4_destroy_clip_table(sc);
1767 #endif
1768
1769 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1770         free(sc->sge.ofld_txq, M_CXGBE);
1771 #endif
1772 #ifdef TCP_OFFLOAD
1773         free(sc->sge.ofld_rxq, M_CXGBE);
1774 #endif
1775 #ifdef DEV_NETMAP
1776         free(sc->sge.nm_rxq, M_CXGBE);
1777         free(sc->sge.nm_txq, M_CXGBE);
1778 #endif
1779         free(sc->irq, M_CXGBE);
1780         free(sc->sge.rxq, M_CXGBE);
1781         free(sc->sge.txq, M_CXGBE);
1782         free(sc->sge.ctrlq, M_CXGBE);
1783         free(sc->sge.iqmap, M_CXGBE);
1784         free(sc->sge.eqmap, M_CXGBE);
1785         free(sc->tids.ftid_tab, M_CXGBE);
1786         free(sc->tids.hpftid_tab, M_CXGBE);
1787         free_hftid_hash(&sc->tids);
1788         free(sc->tids.tid_tab, M_CXGBE);
1789         free(sc->tt.tls_rx_ports, M_CXGBE);
1790         t4_destroy_dma_tag(sc);
1791
1792         callout_drain(&sc->ktls_tick);
1793         callout_drain(&sc->sfl_callout);
1794         if (mtx_initialized(&sc->tids.ftid_lock)) {
1795                 mtx_destroy(&sc->tids.ftid_lock);
1796                 cv_destroy(&sc->tids.ftid_cv);
1797         }
1798         if (mtx_initialized(&sc->tids.atid_lock))
1799                 mtx_destroy(&sc->tids.atid_lock);
1800         if (mtx_initialized(&sc->ifp_lock))
1801                 mtx_destroy(&sc->ifp_lock);
1802
1803         if (rw_initialized(&sc->policy_lock)) {
1804                 rw_destroy(&sc->policy_lock);
1805 #ifdef TCP_OFFLOAD
1806                 if (sc->policy != NULL)
1807                         free_offload_policy(sc->policy);
1808 #endif
1809         }
1810
1811         for (i = 0; i < NUM_MEMWIN; i++) {
1812                 struct memwin *mw = &sc->memwin[i];
1813
1814                 if (rw_initialized(&mw->mw_lock))
1815                         rw_destroy(&mw->mw_lock);
1816         }
1817
1818         mtx_destroy(&sc->sfl_lock);
1819         mtx_destroy(&sc->reg_lock);
1820         mtx_destroy(&sc->sc_lock);
1821
1822         bzero(sc, sizeof(*sc));
1823
1824         return (0);
1825 }
1826
1827 static inline bool
1828 ok_to_reset(struct adapter *sc)
1829 {
1830         struct tid_info *t = &sc->tids;
1831         struct port_info *pi;
1832         struct vi_info *vi;
1833         int i, j;
1834         const int caps = IFCAP_TOE | IFCAP_TXTLS | IFCAP_NETMAP | IFCAP_TXRTLMT;
1835
1836         ASSERT_SYNCHRONIZED_OP(sc);
1837         MPASS(!(sc->flags & IS_VF));
1838
1839         for_each_port(sc, i) {
1840                 pi = sc->port[i];
1841                 for_each_vi(pi, j, vi) {
1842                         if (vi->ifp->if_capenable & caps)
1843                                 return (false);
1844                 }
1845         }
1846
1847         if (atomic_load_int(&t->tids_in_use) > 0)
1848                 return (false);
1849         if (atomic_load_int(&t->stids_in_use) > 0)
1850                 return (false);
1851         if (atomic_load_int(&t->atids_in_use) > 0)
1852                 return (false);
1853         if (atomic_load_int(&t->ftids_in_use) > 0)
1854                 return (false);
1855         if (atomic_load_int(&t->hpftids_in_use) > 0)
1856                 return (false);
1857         if (atomic_load_int(&t->etids_in_use) > 0)
1858                 return (false);
1859
1860         return (true);
1861 }
1862
1863 static int
1864 t4_suspend(device_t dev)
1865 {
1866         struct adapter *sc = device_get_softc(dev);
1867         struct port_info *pi;
1868         struct vi_info *vi;
1869         struct ifnet *ifp;
1870         struct sge_rxq *rxq;
1871         struct sge_txq *txq;
1872         struct sge_wrq *wrq;
1873 #ifdef TCP_OFFLOAD
1874         struct sge_ofld_rxq *ofld_rxq;
1875 #endif
1876 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1877         struct sge_ofld_txq *ofld_txq;
1878 #endif
1879         int rc, i, j, k;
1880
1881         CH_ALERT(sc, "suspend requested\n");
1882
1883         rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1884         if (rc != 0)
1885                 return (ENXIO);
1886
1887         /* XXX: Can the kernel call suspend repeatedly without resume? */
1888         MPASS(!hw_off_limits(sc));
1889
1890         if (!ok_to_reset(sc)) {
1891                 /* XXX: should list what resource is preventing suspend. */
1892                 CH_ERR(sc, "not safe to suspend.\n");
1893                 rc = EBUSY;
1894                 goto done;
1895         }
1896
1897         /* No more DMA or interrupts. */
1898         t4_shutdown_adapter(sc);
1899
1900         /* Quiesce all activity. */
1901         for_each_port(sc, i) {
1902                 pi = sc->port[i];
1903                 pi->vxlan_tcam_entry = false;
1904
1905                 PORT_LOCK(pi);
1906                 if (pi->up_vis > 0) {
1907                         /*
1908                          * t4_shutdown_adapter has already shut down all the
1909                          * PHYs but it also disables interrupts and DMA so there
1910                          * won't be a link interrupt.  So we update the state
1911                          * manually and inform the kernel.
1912                          */
1913                         pi->link_cfg.link_ok = false;
1914                         t4_os_link_changed(pi);
1915                 }
1916                 PORT_UNLOCK(pi);
1917
1918                 for_each_vi(pi, j, vi) {
1919                         vi->xact_addr_filt = -1;
1920                         if (!(vi->flags & VI_INIT_DONE))
1921                                 continue;
1922
1923                         ifp = vi->ifp;
1924                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1925                                 mtx_lock(&vi->tick_mtx);
1926                                 vi->flags |= VI_SKIP_STATS;
1927                                 callout_stop(&vi->tick);
1928                                 mtx_unlock(&vi->tick_mtx);
1929                                 callout_drain(&vi->tick);
1930                         }
1931
1932                         /*
1933                          * Note that the HW is not available.
1934                          */
1935                         for_each_txq(vi, k, txq) {
1936                                 TXQ_LOCK(txq);
1937                                 txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
1938                                 TXQ_UNLOCK(txq);
1939                         }
1940 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1941                         for_each_ofld_txq(vi, k, ofld_txq) {
1942                                 ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
1943                         }
1944 #endif
1945                         for_each_rxq(vi, k, rxq) {
1946                                 rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1947                         }
1948 #if defined(TCP_OFFLOAD)
1949                         for_each_ofld_rxq(vi, k, ofld_rxq) {
1950                                 ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
1951                         }
1952 #endif
1953
1954                         quiesce_vi(vi);
1955                 }
1956
1957                 if (sc->flags & FULL_INIT_DONE) {
1958                         /* Control queue */
1959                         wrq = &sc->sge.ctrlq[i];
1960                         wrq->eq.flags &= ~EQ_HW_ALLOCATED;
1961                         quiesce_wrq(wrq);
1962                 }
1963         }
1964         if (sc->flags & FULL_INIT_DONE) {
1965                 /* Firmware event queue */
1966                 sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
1967                 quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
1968         }
1969
1970         /* Mark the adapter totally off limits. */
1971         mtx_lock(&sc->reg_lock);
1972         sc->flags |= HW_OFF_LIMITS;
1973         sc->flags &= ~(FW_OK | MASTER_PF);
1974         sc->reset_thread = NULL;
1975         mtx_unlock(&sc->reg_lock);
1976
1977         sc->num_resets++;
1978         CH_ALERT(sc, "suspend completed.\n");
1979 done:
1980         end_synchronized_op(sc, 0);
1981         return (rc);
1982 }
1983
1984 struct adapter_pre_reset_state {
1985         u_int flags;
1986         uint16_t nbmcaps;
1987         uint16_t linkcaps;
1988         uint16_t switchcaps;
1989         uint16_t niccaps;
1990         uint16_t toecaps;
1991         uint16_t rdmacaps;
1992         uint16_t cryptocaps;
1993         uint16_t iscsicaps;
1994         uint16_t fcoecaps;
1995
1996         u_int cfcsum;
1997         char cfg_file[32];
1998
1999         struct adapter_params params;
2000         struct t4_virt_res vres;
2001         struct tid_info tids;
2002         struct sge sge;
2003
2004         int rawf_base;
2005         int nrawf;
2006
2007 };
2008
2009 static void
2010 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2011 {
2012
2013         ASSERT_SYNCHRONIZED_OP(sc);
2014
2015         o->flags = sc->flags;
2016
2017         o->nbmcaps =  sc->nbmcaps;
2018         o->linkcaps = sc->linkcaps;
2019         o->switchcaps = sc->switchcaps;
2020         o->niccaps = sc->niccaps;
2021         o->toecaps = sc->toecaps;
2022         o->rdmacaps = sc->rdmacaps;
2023         o->cryptocaps = sc->cryptocaps;
2024         o->iscsicaps = sc->iscsicaps;
2025         o->fcoecaps = sc->fcoecaps;
2026
2027         o->cfcsum = sc->cfcsum;
2028         MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2029         memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2030
2031         o->params = sc->params;
2032         o->vres = sc->vres;
2033         o->tids = sc->tids;
2034         o->sge = sc->sge;
2035
2036         o->rawf_base = sc->rawf_base;
2037         o->nrawf = sc->nrawf;
2038 }
2039
2040 static int
2041 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2042 {
2043         int rc = 0;
2044
2045         ASSERT_SYNCHRONIZED_OP(sc);
2046
2047         /* Capabilities */
2048 #define COMPARE_CAPS(c) do { \
2049         if (o->c##caps != sc->c##caps) { \
2050                 CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2051                     sc->c##caps); \
2052                 rc = EINVAL; \
2053         } \
2054 } while (0)
2055         COMPARE_CAPS(nbm);
2056         COMPARE_CAPS(link);
2057         COMPARE_CAPS(switch);
2058         COMPARE_CAPS(nic);
2059         COMPARE_CAPS(toe);
2060         COMPARE_CAPS(rdma);
2061         COMPARE_CAPS(crypto);
2062         COMPARE_CAPS(iscsi);
2063         COMPARE_CAPS(fcoe);
2064 #undef COMPARE_CAPS
2065
2066         /* Firmware config file */
2067         if (o->cfcsum != sc->cfcsum) {
2068                 CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2069                     o->cfcsum, sc->cfg_file, sc->cfcsum);
2070                 rc = EINVAL;
2071         }
2072
2073 #define COMPARE_PARAM(p, name) do { \
2074         if (o->p != sc->p) { \
2075                 CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2076                 rc = EINVAL; \
2077         } \
2078 } while (0)
2079         COMPARE_PARAM(sge.iq_start, iq_start);
2080         COMPARE_PARAM(sge.eq_start, eq_start);
2081         COMPARE_PARAM(tids.ftid_base, ftid_base);
2082         COMPARE_PARAM(tids.ftid_end, ftid_end);
2083         COMPARE_PARAM(tids.nftids, nftids);
2084         COMPARE_PARAM(vres.l2t.start, l2t_start);
2085         COMPARE_PARAM(vres.l2t.size, l2t_size);
2086         COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2087         COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2088         COMPARE_PARAM(tids.tid_base, tid_base);
2089         COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2090         COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2091         COMPARE_PARAM(tids.nhpftids, nhpftids);
2092         COMPARE_PARAM(rawf_base, rawf_base);
2093         COMPARE_PARAM(nrawf, nrawf);
2094         COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2095         COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2096         COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2097         COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2098         COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2099         COMPARE_PARAM(tids.ntids, ntids);
2100         COMPARE_PARAM(tids.etid_base, etid_base);
2101         COMPARE_PARAM(tids.etid_end, etid_end);
2102         COMPARE_PARAM(tids.netids, netids);
2103         COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2104         COMPARE_PARAM(params.ethoffload, ethoffload);
2105         COMPARE_PARAM(tids.natids, natids);
2106         COMPARE_PARAM(tids.stid_base, stid_base);
2107         COMPARE_PARAM(vres.ddp.start, ddp_start);
2108         COMPARE_PARAM(vres.ddp.size, ddp_size);
2109         COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2110         COMPARE_PARAM(vres.stag.start, stag_start);
2111         COMPARE_PARAM(vres.stag.size, stag_size);
2112         COMPARE_PARAM(vres.rq.start, rq_start);
2113         COMPARE_PARAM(vres.rq.size, rq_size);
2114         COMPARE_PARAM(vres.pbl.start, pbl_start);
2115         COMPARE_PARAM(vres.pbl.size, pbl_size);
2116         COMPARE_PARAM(vres.qp.start, qp_start);
2117         COMPARE_PARAM(vres.qp.size, qp_size);
2118         COMPARE_PARAM(vres.cq.start, cq_start);
2119         COMPARE_PARAM(vres.cq.size, cq_size);
2120         COMPARE_PARAM(vres.ocq.start, ocq_start);
2121         COMPARE_PARAM(vres.ocq.size, ocq_size);
2122         COMPARE_PARAM(vres.srq.start, srq_start);
2123         COMPARE_PARAM(vres.srq.size, srq_size);
2124         COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2125         COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2126         COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2127         COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2128         COMPARE_PARAM(vres.key.start, key_start);
2129         COMPARE_PARAM(vres.key.size, key_size);
2130 #undef COMPARE_PARAM
2131
2132         return (rc);
2133 }
2134
2135 static int
2136 t4_resume(device_t dev)
2137 {
2138         struct adapter *sc = device_get_softc(dev);
2139         struct adapter_pre_reset_state *old_state = NULL;
2140         struct port_info *pi;
2141         struct vi_info *vi;
2142         struct ifnet *ifp;
2143         struct sge_txq *txq;
2144         int rc, i, j, k;
2145
2146         CH_ALERT(sc, "resume requested.\n");
2147
2148         rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2149         if (rc != 0)
2150                 return (ENXIO);
2151         MPASS(hw_off_limits(sc));
2152         MPASS((sc->flags & FW_OK) == 0);
2153         MPASS((sc->flags & MASTER_PF) == 0);
2154         MPASS(sc->reset_thread == NULL);
2155         sc->reset_thread = curthread;
2156
2157         /* Register access is expected to work by the time we're here. */
2158         if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2159                 CH_ERR(sc, "%s: can't read device registers\n", __func__);
2160                 rc = ENXIO;
2161                 goto done;
2162         }
2163
2164         /* Restore memory window. */
2165         setup_memwin(sc);
2166
2167         /* Go no further if recovery mode has been requested. */
2168         if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2169                 CH_ALERT(sc, "recovery mode on resume.\n");
2170                 rc = 0;
2171                 mtx_lock(&sc->reg_lock);
2172                 sc->flags &= ~HW_OFF_LIMITS;
2173                 mtx_unlock(&sc->reg_lock);
2174                 goto done;
2175         }
2176
2177         old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2178         save_caps_and_params(sc, old_state);
2179
2180         /* Reestablish contact with firmware and become the primary PF. */
2181         rc = contact_firmware(sc);
2182         if (rc != 0)
2183                 goto done; /* error message displayed already */
2184         MPASS(sc->flags & FW_OK);
2185
2186         if (sc->flags & MASTER_PF) {
2187                 rc = partition_resources(sc);
2188                 if (rc != 0)
2189                         goto done; /* error message displayed already */
2190                 t4_intr_clear(sc);
2191         }
2192
2193         rc = get_params__post_init(sc);
2194         if (rc != 0)
2195                 goto done; /* error message displayed already */
2196
2197         rc = set_params__post_init(sc);
2198         if (rc != 0)
2199                 goto done; /* error message displayed already */
2200
2201         rc = compare_caps_and_params(sc, old_state);
2202         if (rc != 0)
2203                 goto done; /* error message displayed already */
2204
2205         for_each_port(sc, i) {
2206                 pi = sc->port[i];
2207                 MPASS(pi != NULL);
2208                 MPASS(pi->vi != NULL);
2209                 MPASS(pi->vi[0].dev == pi->dev);
2210
2211                 rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2212                 if (rc != 0) {
2213                         CH_ERR(sc,
2214                             "failed to re-initialize port %d: %d\n", i, rc);
2215                         goto done;
2216                 }
2217                 MPASS(sc->chan_map[pi->tx_chan] == i);
2218
2219                 PORT_LOCK(pi);
2220                 fixup_link_config(pi);
2221                 build_medialist(pi);
2222                 PORT_UNLOCK(pi);
2223                 for_each_vi(pi, j, vi) {
2224                         if (IS_MAIN_VI(vi))
2225                                 continue;
2226                         rc = alloc_extra_vi(sc, pi, vi);
2227                         if (rc != 0) {
2228                                 CH_ERR(vi,
2229                                     "failed to re-allocate extra VI: %d\n", rc);
2230                                 goto done;
2231                         }
2232                 }
2233         }
2234
2235         /*
2236          * Interrupts and queues are about to be enabled and other threads will
2237          * want to access the hardware too.  It is safe to do so.  Note that
2238          * this thread is still in the middle of a synchronized_op.
2239          */
2240         mtx_lock(&sc->reg_lock);
2241         sc->flags &= ~HW_OFF_LIMITS;
2242         mtx_unlock(&sc->reg_lock);
2243
2244         if (sc->flags & FULL_INIT_DONE) {
2245                 rc = adapter_full_init(sc);
2246                 if (rc != 0) {
2247                         CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2248                         goto done;
2249                 }
2250
2251                 if (sc->vxlan_refcount > 0)
2252                         enable_vxlan_rx(sc);
2253
2254                 for_each_port(sc, i) {
2255                         pi = sc->port[i];
2256                         for_each_vi(pi, j, vi) {
2257                                 if (!(vi->flags & VI_INIT_DONE))
2258                                         continue;
2259                                 rc = vi_full_init(vi);
2260                                 if (rc != 0) {
2261                                         CH_ERR(vi, "failed to re-initialize "
2262                                             "interface: %d\n", rc);
2263                                         goto done;
2264                                 }
2265
2266                                 ifp = vi->ifp;
2267                                 if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2268                                         continue;
2269                                 /*
2270                                  * Note that we do not setup multicast addresses
2271                                  * in the first pass.  This ensures that the
2272                                  * unicast DMACs for all VIs on all ports get an
2273                                  * MPS TCAM entry.
2274                                  */
2275                                 rc = update_mac_settings(ifp, XGMAC_ALL &
2276                                     ~XGMAC_MCADDRS);
2277                                 if (rc != 0) {
2278                                         CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2279                                         goto done;
2280                                 }
2281                                 rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2282                                     true);
2283                                 if (rc != 0) {
2284                                         CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2285                                         goto done;
2286                                 }
2287                                 for_each_txq(vi, k, txq) {
2288                                         TXQ_LOCK(txq);
2289                                         txq->eq.flags |= EQ_ENABLED;
2290                                         TXQ_UNLOCK(txq);
2291                                 }
2292                                 mtx_lock(&vi->tick_mtx);
2293                                 vi->flags &= ~VI_SKIP_STATS;
2294                                 callout_schedule(&vi->tick, hz);
2295                                 mtx_unlock(&vi->tick_mtx);
2296                         }
2297                         PORT_LOCK(pi);
2298                         if (pi->up_vis > 0) {
2299                                 t4_update_port_info(pi);
2300                                 fixup_link_config(pi);
2301                                 build_medialist(pi);
2302                                 apply_link_config(pi);
2303                                 if (pi->link_cfg.link_ok)
2304                                         t4_os_link_changed(pi);
2305                         }
2306                         PORT_UNLOCK(pi);
2307                 }
2308
2309                 /* Now reprogram the L2 multicast addresses. */
2310                 for_each_port(sc, i) {
2311                         pi = sc->port[i];
2312                         for_each_vi(pi, j, vi) {
2313                                 if (!(vi->flags & VI_INIT_DONE))
2314                                         continue;
2315                                 ifp = vi->ifp;
2316                                 if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2317                                         continue;
2318                                 rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2319                                 if (rc != 0) {
2320                                         CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2321                                         rc = 0; /* carry on */
2322                                 }
2323                         }
2324                 }
2325         }
2326 done:
2327         if (rc == 0) {
2328                 sc->incarnation++;
2329                 CH_ALERT(sc, "resume completed.\n");
2330         }
2331         end_synchronized_op(sc, 0);
2332         free(old_state, M_CXGBE);
2333         return (rc);
2334 }
2335
2336 static int
2337 t4_reset_prepare(device_t dev, device_t child)
2338 {
2339         struct adapter *sc = device_get_softc(dev);
2340
2341         CH_ALERT(sc, "reset_prepare.\n");
2342         return (0);
2343 }
2344
2345 static int
2346 t4_reset_post(device_t dev, device_t child)
2347 {
2348         struct adapter *sc = device_get_softc(dev);
2349
2350         CH_ALERT(sc, "reset_post.\n");
2351         return (0);
2352 }
2353
2354 static void
2355 reset_adapter(void *arg, int pending)
2356 {
2357         struct adapter *sc = arg;
2358         int rc;
2359
2360         CH_ALERT(sc, "reset requested.\n");
2361
2362         rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2363         if (rc != 0)
2364                 return;
2365
2366         if (hw_off_limits(sc)) {
2367                 CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2368                 rc = ENXIO;
2369                 goto done;
2370         }
2371
2372         if (!ok_to_reset(sc)) {
2373                 /* XXX: should list what resource is preventing reset. */
2374                 CH_ERR(sc, "not safe to reset.\n");
2375                 rc = EBUSY;
2376                 goto done;
2377         }
2378
2379 done:
2380         end_synchronized_op(sc, 0);
2381         if (rc != 0)
2382                 return; /* Error logged already. */
2383
2384         mtx_lock(&Giant);
2385         rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2386         mtx_unlock(&Giant);
2387         if (rc != 0)
2388                 CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2389         else
2390                 CH_ALERT(sc, "bus_reset_child succeeded.\n");
2391 }
2392
2393 static int
2394 cxgbe_probe(device_t dev)
2395 {
2396         char buf[128];
2397         struct port_info *pi = device_get_softc(dev);
2398
2399         snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2400         device_set_desc_copy(dev, buf);
2401
2402         return (BUS_PROBE_DEFAULT);
2403 }
2404
2405 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2406     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2407     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2408     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2409 #define T4_CAP_ENABLE (T4_CAP)
2410
2411 static int
2412 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2413 {
2414         struct ifnet *ifp;
2415         struct sbuf *sb;
2416         struct sysctl_ctx_list *ctx;
2417         struct sysctl_oid_list *children;
2418         struct pfil_head_args pa;
2419         struct adapter *sc = vi->adapter;
2420
2421         ctx = device_get_sysctl_ctx(vi->dev);
2422         children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2423         vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2424             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2425         vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2426             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2427 #ifdef DEV_NETMAP
2428         vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2429             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2430         vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2431             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2432 #endif
2433 #ifdef TCP_OFFLOAD
2434         vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2435             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2436 #endif
2437 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2438         vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2439             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2440 #endif
2441
2442         vi->xact_addr_filt = -1;
2443         mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2444         callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2445         if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2446                 vi->flags |= TX_USES_VM_WR;
2447
2448         /* Allocate an ifnet and set it up */
2449         ifp = if_alloc_dev(IFT_ETHER, dev);
2450         if (ifp == NULL) {
2451                 device_printf(dev, "Cannot allocate ifnet\n");
2452                 return (ENOMEM);
2453         }
2454         vi->ifp = ifp;
2455         ifp->if_softc = vi;
2456
2457         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2458         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2459
2460         ifp->if_init = cxgbe_init;
2461         ifp->if_ioctl = cxgbe_ioctl;
2462         ifp->if_transmit = cxgbe_transmit;
2463         ifp->if_qflush = cxgbe_qflush;
2464         if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2465                 ifp->if_get_counter = vi_get_counter;
2466         else
2467                 ifp->if_get_counter = cxgbe_get_counter;
2468 #if defined(KERN_TLS) || defined(RATELIMIT)
2469         ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
2470 #endif
2471 #ifdef RATELIMIT
2472         ifp->if_ratelimit_query = cxgbe_ratelimit_query;
2473 #endif
2474
2475         ifp->if_capabilities = T4_CAP;
2476         ifp->if_capenable = T4_CAP_ENABLE;
2477         ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2478             CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
2479         if (chip_id(sc) >= CHELSIO_T6) {
2480                 ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2481                 ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
2482                 ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2483                     CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2484                     CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
2485         }
2486
2487 #ifdef TCP_OFFLOAD
2488         if (vi->nofldrxq != 0)
2489                 ifp->if_capabilities |= IFCAP_TOE;
2490 #endif
2491 #ifdef RATELIMIT
2492         if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2493                 ifp->if_capabilities |= IFCAP_TXRTLMT;
2494                 ifp->if_capenable |= IFCAP_TXRTLMT;
2495         }
2496 #endif
2497
2498         ifp->if_hw_tsomax = IP_MAXPACKET;
2499         if (vi->flags & TX_USES_VM_WR)
2500                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
2501         else
2502                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
2503 #ifdef RATELIMIT
2504         if (is_ethoffload(sc) && vi->nofldtxq != 0)
2505                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
2506 #endif
2507         ifp->if_hw_tsomaxsegsize = 65536;
2508 #ifdef KERN_TLS
2509         if (is_ktls(sc)) {
2510                 ifp->if_capabilities |= IFCAP_TXTLS;
2511                 if (sc->flags & KERN_TLS_ON)
2512                         ifp->if_capenable |= IFCAP_TXTLS;
2513         }
2514 #endif
2515
2516         ether_ifattach(ifp, vi->hw_addr);
2517 #ifdef DEV_NETMAP
2518         if (vi->nnmrxq != 0)
2519                 cxgbe_nm_attach(vi);
2520 #endif
2521         sb = sbuf_new_auto();
2522         sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2523 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2524         switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2525         case IFCAP_TOE:
2526                 sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2527                 break;
2528         case IFCAP_TOE | IFCAP_TXRTLMT:
2529                 sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2530                 break;
2531         case IFCAP_TXRTLMT:
2532                 sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2533                 break;
2534         }
2535 #endif
2536 #ifdef TCP_OFFLOAD
2537         if (ifp->if_capabilities & IFCAP_TOE)
2538                 sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2539 #endif
2540 #ifdef DEV_NETMAP
2541         if (ifp->if_capabilities & IFCAP_NETMAP)
2542                 sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2543                     vi->nnmtxq, vi->nnmrxq);
2544 #endif
2545         sbuf_finish(sb);
2546         device_printf(dev, "%s\n", sbuf_data(sb));
2547         sbuf_delete(sb);
2548
2549         vi_sysctls(vi);
2550
2551         pa.pa_version = PFIL_VERSION;
2552         pa.pa_flags = PFIL_IN;
2553         pa.pa_type = PFIL_TYPE_ETHERNET;
2554         pa.pa_headname = ifp->if_xname;
2555         vi->pfil = pfil_head_register(&pa);
2556
2557         return (0);
2558 }
2559
2560 static int
2561 cxgbe_attach(device_t dev)
2562 {
2563         struct port_info *pi = device_get_softc(dev);
2564         struct adapter *sc = pi->adapter;
2565         struct vi_info *vi;
2566         int i, rc;
2567
2568         rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2569         if (rc)
2570                 return (rc);
2571
2572         for_each_vi(pi, i, vi) {
2573                 if (i == 0)
2574                         continue;
2575                 vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2576                 if (vi->dev == NULL) {
2577                         device_printf(dev, "failed to add VI %d\n", i);
2578                         continue;
2579                 }
2580                 device_set_softc(vi->dev, vi);
2581         }
2582
2583         cxgbe_sysctls(pi);
2584
2585         bus_generic_attach(dev);
2586
2587         return (0);
2588 }
2589
2590 static void
2591 cxgbe_vi_detach(struct vi_info *vi)
2592 {
2593         struct ifnet *ifp = vi->ifp;
2594
2595         if (vi->pfil != NULL) {
2596                 pfil_head_unregister(vi->pfil);
2597                 vi->pfil = NULL;
2598         }
2599
2600         ether_ifdetach(ifp);
2601
2602         /* Let detach proceed even if these fail. */
2603 #ifdef DEV_NETMAP
2604         if (ifp->if_capabilities & IFCAP_NETMAP)
2605                 cxgbe_nm_detach(vi);
2606 #endif
2607         cxgbe_uninit_synchronized(vi);
2608         callout_drain(&vi->tick);
2609         vi_full_uninit(vi);
2610
2611         if_free(vi->ifp);
2612         vi->ifp = NULL;
2613 }
2614
2615 static int
2616 cxgbe_detach(device_t dev)
2617 {
2618         struct port_info *pi = device_get_softc(dev);
2619         struct adapter *sc = pi->adapter;
2620         int rc;
2621
2622         /* Detach the extra VIs first. */
2623         rc = bus_generic_detach(dev);
2624         if (rc)
2625                 return (rc);
2626         device_delete_children(dev);
2627
2628         doom_vi(sc, &pi->vi[0]);
2629
2630         if (pi->flags & HAS_TRACEQ) {
2631                 sc->traceq = -1;        /* cloner should not create ifnet */
2632                 t4_tracer_port_detach(sc);
2633         }
2634
2635         cxgbe_vi_detach(&pi->vi[0]);
2636         ifmedia_removeall(&pi->media);
2637
2638         end_synchronized_op(sc, 0);
2639
2640         return (0);
2641 }
2642
2643 static void
2644 cxgbe_init(void *arg)
2645 {
2646         struct vi_info *vi = arg;
2647         struct adapter *sc = vi->adapter;
2648
2649         if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2650                 return;
2651         cxgbe_init_synchronized(vi);
2652         end_synchronized_op(sc, 0);
2653 }
2654
2655 static int
2656 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2657 {
2658         int rc = 0, mtu, flags;
2659         struct vi_info *vi = ifp->if_softc;
2660         struct port_info *pi = vi->pi;
2661         struct adapter *sc = pi->adapter;
2662         struct ifreq *ifr = (struct ifreq *)data;
2663         uint32_t mask;
2664
2665         switch (cmd) {
2666         case SIOCSIFMTU:
2667                 mtu = ifr->ifr_mtu;
2668                 if (mtu < ETHERMIN || mtu > MAX_MTU)
2669                         return (EINVAL);
2670
2671                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2672                 if (rc)
2673                         return (rc);
2674                 ifp->if_mtu = mtu;
2675                 if (vi->flags & VI_INIT_DONE) {
2676                         t4_update_fl_bufsize(ifp);
2677                         if (!hw_off_limits(sc) &&
2678                             ifp->if_drv_flags & IFF_DRV_RUNNING)
2679                                 rc = update_mac_settings(ifp, XGMAC_MTU);
2680                 }
2681                 end_synchronized_op(sc, 0);
2682                 break;
2683
2684         case SIOCSIFFLAGS:
2685                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2686                 if (rc)
2687                         return (rc);
2688
2689                 if (hw_off_limits(sc)) {
2690                         rc = ENXIO;
2691                         goto fail;
2692                 }
2693
2694                 if (ifp->if_flags & IFF_UP) {
2695                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2696                                 flags = vi->if_flags;
2697                                 if ((ifp->if_flags ^ flags) &
2698                                     (IFF_PROMISC | IFF_ALLMULTI)) {
2699                                         rc = update_mac_settings(ifp,
2700                                             XGMAC_PROMISC | XGMAC_ALLMULTI);
2701                                 }
2702                         } else {
2703                                 rc = cxgbe_init_synchronized(vi);
2704                         }
2705                         vi->if_flags = ifp->if_flags;
2706                 } else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2707                         rc = cxgbe_uninit_synchronized(vi);
2708                 }
2709                 end_synchronized_op(sc, 0);
2710                 break;
2711
2712         case SIOCADDMULTI:
2713         case SIOCDELMULTI:
2714                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2715                 if (rc)
2716                         return (rc);
2717                 if (!hw_off_limits(sc) && ifp->if_drv_flags & IFF_DRV_RUNNING)
2718                         rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2719                 end_synchronized_op(sc, 0);
2720                 break;
2721
2722         case SIOCSIFCAP:
2723                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2724                 if (rc)
2725                         return (rc);
2726
2727                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2728                 if (mask & IFCAP_TXCSUM) {
2729                         ifp->if_capenable ^= IFCAP_TXCSUM;
2730                         ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2731
2732                         if (IFCAP_TSO4 & ifp->if_capenable &&
2733                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
2734                                 mask &= ~IFCAP_TSO4;
2735                                 ifp->if_capenable &= ~IFCAP_TSO4;
2736                                 if_printf(ifp,
2737                                     "tso4 disabled due to -txcsum.\n");
2738                         }
2739                 }
2740                 if (mask & IFCAP_TXCSUM_IPV6) {
2741                         ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2742                         ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2743
2744                         if (IFCAP_TSO6 & ifp->if_capenable &&
2745                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2746                                 mask &= ~IFCAP_TSO6;
2747                                 ifp->if_capenable &= ~IFCAP_TSO6;
2748                                 if_printf(ifp,
2749                                     "tso6 disabled due to -txcsum6.\n");
2750                         }
2751                 }
2752                 if (mask & IFCAP_RXCSUM)
2753                         ifp->if_capenable ^= IFCAP_RXCSUM;
2754                 if (mask & IFCAP_RXCSUM_IPV6)
2755                         ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2756
2757                 /*
2758                  * Note that we leave CSUM_TSO alone (it is always set).  The
2759                  * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2760                  * sending a TSO request our way, so it's sufficient to toggle
2761                  * IFCAP_TSOx only.
2762                  */
2763                 if (mask & IFCAP_TSO4) {
2764                         if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2765                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
2766                                 if_printf(ifp, "enable txcsum first.\n");
2767                                 rc = EAGAIN;
2768                                 goto fail;
2769                         }
2770                         ifp->if_capenable ^= IFCAP_TSO4;
2771                 }
2772                 if (mask & IFCAP_TSO6) {
2773                         if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2774                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2775                                 if_printf(ifp, "enable txcsum6 first.\n");
2776                                 rc = EAGAIN;
2777                                 goto fail;
2778                         }
2779                         ifp->if_capenable ^= IFCAP_TSO6;
2780                 }
2781                 if (mask & IFCAP_LRO) {
2782 #if defined(INET) || defined(INET6)
2783                         int i;
2784                         struct sge_rxq *rxq;
2785
2786                         ifp->if_capenable ^= IFCAP_LRO;
2787                         for_each_rxq(vi, i, rxq) {
2788                                 if (ifp->if_capenable & IFCAP_LRO)
2789                                         rxq->iq.flags |= IQ_LRO_ENABLED;
2790                                 else
2791                                         rxq->iq.flags &= ~IQ_LRO_ENABLED;
2792                         }
2793 #endif
2794                 }
2795 #ifdef TCP_OFFLOAD
2796                 if (mask & IFCAP_TOE) {
2797                         int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2798
2799                         rc = toe_capability(vi, enable);
2800                         if (rc != 0)
2801                                 goto fail;
2802
2803                         ifp->if_capenable ^= mask;
2804                 }
2805 #endif
2806                 if (mask & IFCAP_VLAN_HWTAGGING) {
2807                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2808                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2809                                 rc = update_mac_settings(ifp, XGMAC_VLANEX);
2810                 }
2811                 if (mask & IFCAP_VLAN_MTU) {
2812                         ifp->if_capenable ^= IFCAP_VLAN_MTU;
2813
2814                         /* Need to find out how to disable auto-mtu-inflation */
2815                 }
2816                 if (mask & IFCAP_VLAN_HWTSO)
2817                         ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2818                 if (mask & IFCAP_VLAN_HWCSUM)
2819                         ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2820 #ifdef RATELIMIT
2821                 if (mask & IFCAP_TXRTLMT)
2822                         ifp->if_capenable ^= IFCAP_TXRTLMT;
2823 #endif
2824                 if (mask & IFCAP_HWRXTSTMP) {
2825                         int i;
2826                         struct sge_rxq *rxq;
2827
2828                         ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2829                         for_each_rxq(vi, i, rxq) {
2830                                 if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2831                                         rxq->iq.flags |= IQ_RX_TIMESTAMP;
2832                                 else
2833                                         rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2834                         }
2835                 }
2836                 if (mask & IFCAP_MEXTPG)
2837                         ifp->if_capenable ^= IFCAP_MEXTPG;
2838
2839 #ifdef KERN_TLS
2840                 if (mask & IFCAP_TXTLS) {
2841                         int enable = (ifp->if_capenable ^ mask) & IFCAP_TXTLS;
2842
2843                         rc = ktls_capability(sc, enable);
2844                         if (rc != 0)
2845                                 goto fail;
2846
2847                         ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2848                 }
2849 #endif
2850                 if (mask & IFCAP_VXLAN_HWCSUM) {
2851                         ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2852                         ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2853                             CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2854                             CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2855                 }
2856                 if (mask & IFCAP_VXLAN_HWTSO) {
2857                         ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2858                         ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2859                             CSUM_INNER_IP_TSO;
2860                 }
2861
2862 #ifdef VLAN_CAPABILITIES
2863                 VLAN_CAPABILITIES(ifp);
2864 #endif
2865 fail:
2866                 end_synchronized_op(sc, 0);
2867                 break;
2868
2869         case SIOCSIFMEDIA:
2870         case SIOCGIFMEDIA:
2871         case SIOCGIFXMEDIA:
2872                 ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2873                 break;
2874
2875         case SIOCGI2C: {
2876                 struct ifi2creq i2c;
2877
2878                 rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2879                 if (rc != 0)
2880                         break;
2881                 if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2882                         rc = EPERM;
2883                         break;
2884                 }
2885                 if (i2c.len > sizeof(i2c.data)) {
2886                         rc = EINVAL;
2887                         break;
2888                 }
2889                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2890                 if (rc)
2891                         return (rc);
2892                 if (hw_off_limits(sc))
2893                         rc = ENXIO;
2894                 else
2895                         rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2896                             i2c.offset, i2c.len, &i2c.data[0]);
2897                 end_synchronized_op(sc, 0);
2898                 if (rc == 0)
2899                         rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2900                 break;
2901         }
2902
2903         default:
2904                 rc = ether_ioctl(ifp, cmd, data);
2905         }
2906
2907         return (rc);
2908 }
2909
2910 static int
2911 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2912 {
2913         struct vi_info *vi = ifp->if_softc;
2914         struct port_info *pi = vi->pi;
2915         struct adapter *sc;
2916         struct sge_txq *txq;
2917         void *items[1];
2918         int rc;
2919
2920         M_ASSERTPKTHDR(m);
2921         MPASS(m->m_nextpkt == NULL);    /* not quite ready for this yet */
2922 #if defined(KERN_TLS) || defined(RATELIMIT)
2923         if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2924                 MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2925 #endif
2926
2927         if (__predict_false(pi->link_cfg.link_ok == false)) {
2928                 m_freem(m);
2929                 return (ENETDOWN);
2930         }
2931
2932         rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2933         if (__predict_false(rc != 0)) {
2934                 MPASS(m == NULL);                       /* was freed already */
2935                 atomic_add_int(&pi->tx_parse_error, 1); /* rare, atomic is ok */
2936                 return (rc);
2937         }
2938 #ifdef RATELIMIT
2939         if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2940                 if (m->m_pkthdr.snd_tag->sw->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2941                         return (ethofld_transmit(ifp, m));
2942         }
2943 #endif
2944
2945         /* Select a txq. */
2946         sc = vi->adapter;
2947         txq = &sc->sge.txq[vi->first_txq];
2948         if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2949                 txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2950                     vi->rsrv_noflowq);
2951
2952         items[0] = m;
2953         rc = mp_ring_enqueue(txq->r, items, 1, 256);
2954         if (__predict_false(rc != 0))
2955                 m_freem(m);
2956
2957         return (rc);
2958 }
2959
2960 static void
2961 cxgbe_qflush(struct ifnet *ifp)
2962 {
2963         struct vi_info *vi = ifp->if_softc;
2964         struct sge_txq *txq;
2965         int i;
2966
2967         /* queues do not exist if !VI_INIT_DONE. */
2968         if (vi->flags & VI_INIT_DONE) {
2969                 for_each_txq(vi, i, txq) {
2970                         TXQ_LOCK(txq);
2971                         txq->eq.flags |= EQ_QFLUSH;
2972                         TXQ_UNLOCK(txq);
2973                         while (!mp_ring_is_idle(txq->r)) {
2974                                 mp_ring_check_drainage(txq->r, 4096);
2975                                 pause("qflush", 1);
2976                         }
2977                         TXQ_LOCK(txq);
2978                         txq->eq.flags &= ~EQ_QFLUSH;
2979                         TXQ_UNLOCK(txq);
2980                 }
2981         }
2982         if_qflush(ifp);
2983 }
2984
2985 static uint64_t
2986 vi_get_counter(struct ifnet *ifp, ift_counter c)
2987 {
2988         struct vi_info *vi = ifp->if_softc;
2989         struct fw_vi_stats_vf *s = &vi->stats;
2990
2991         mtx_lock(&vi->tick_mtx);
2992         vi_refresh_stats(vi);
2993         mtx_unlock(&vi->tick_mtx);
2994
2995         switch (c) {
2996         case IFCOUNTER_IPACKETS:
2997                 return (s->rx_bcast_frames + s->rx_mcast_frames +
2998                     s->rx_ucast_frames);
2999         case IFCOUNTER_IERRORS:
3000                 return (s->rx_err_frames);
3001         case IFCOUNTER_OPACKETS:
3002                 return (s->tx_bcast_frames + s->tx_mcast_frames +
3003                     s->tx_ucast_frames + s->tx_offload_frames);
3004         case IFCOUNTER_OERRORS:
3005                 return (s->tx_drop_frames);
3006         case IFCOUNTER_IBYTES:
3007                 return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3008                     s->rx_ucast_bytes);
3009         case IFCOUNTER_OBYTES:
3010                 return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3011                     s->tx_ucast_bytes + s->tx_offload_bytes);
3012         case IFCOUNTER_IMCASTS:
3013                 return (s->rx_mcast_frames);
3014         case IFCOUNTER_OMCASTS:
3015                 return (s->tx_mcast_frames);
3016         case IFCOUNTER_OQDROPS: {
3017                 uint64_t drops;
3018
3019                 drops = 0;
3020                 if (vi->flags & VI_INIT_DONE) {
3021                         int i;
3022                         struct sge_txq *txq;
3023
3024                         for_each_txq(vi, i, txq)
3025                                 drops += counter_u64_fetch(txq->r->dropped);
3026                 }
3027
3028                 return (drops);
3029
3030         }
3031
3032         default:
3033                 return (if_get_counter_default(ifp, c));
3034         }
3035 }
3036
3037 static uint64_t
3038 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
3039 {
3040         struct vi_info *vi = ifp->if_softc;
3041         struct port_info *pi = vi->pi;
3042         struct port_stats *s = &pi->stats;
3043
3044         mtx_lock(&vi->tick_mtx);
3045         cxgbe_refresh_stats(vi);
3046         mtx_unlock(&vi->tick_mtx);
3047
3048         switch (c) {
3049         case IFCOUNTER_IPACKETS:
3050                 return (s->rx_frames);
3051
3052         case IFCOUNTER_IERRORS:
3053                 return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3054                     s->rx_fcs_err + s->rx_len_err);
3055
3056         case IFCOUNTER_OPACKETS:
3057                 return (s->tx_frames);
3058
3059         case IFCOUNTER_OERRORS:
3060                 return (s->tx_error_frames);
3061
3062         case IFCOUNTER_IBYTES:
3063                 return (s->rx_octets);
3064
3065         case IFCOUNTER_OBYTES:
3066                 return (s->tx_octets);
3067
3068         case IFCOUNTER_IMCASTS:
3069                 return (s->rx_mcast_frames);
3070
3071         case IFCOUNTER_OMCASTS:
3072                 return (s->tx_mcast_frames);
3073
3074         case IFCOUNTER_IQDROPS:
3075                 return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3076                     s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3077                     s->rx_trunc3 + pi->tnl_cong_drops);
3078
3079         case IFCOUNTER_OQDROPS: {
3080                 uint64_t drops;
3081
3082                 drops = s->tx_drop;
3083                 if (vi->flags & VI_INIT_DONE) {
3084                         int i;
3085                         struct sge_txq *txq;
3086
3087                         for_each_txq(vi, i, txq)
3088                                 drops += counter_u64_fetch(txq->r->dropped);
3089                 }
3090
3091                 return (drops);
3092
3093         }
3094
3095         default:
3096                 return (if_get_counter_default(ifp, c));
3097         }
3098 }
3099
3100 #if defined(KERN_TLS) || defined(RATELIMIT)
3101 static int
3102 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
3103     struct m_snd_tag **pt)
3104 {
3105         int error;
3106
3107         switch (params->hdr.type) {
3108 #ifdef RATELIMIT
3109         case IF_SND_TAG_TYPE_RATE_LIMIT:
3110                 error = cxgbe_rate_tag_alloc(ifp, params, pt);
3111                 break;
3112 #endif
3113 #ifdef KERN_TLS
3114         case IF_SND_TAG_TYPE_TLS:
3115                 error = cxgbe_tls_tag_alloc(ifp, params, pt);
3116                 break;
3117 #endif
3118         default:
3119                 error = EOPNOTSUPP;
3120         }
3121         return (error);
3122 }
3123 #endif
3124
3125 /*
3126  * The kernel picks a media from the list we had provided but we still validate
3127  * the requeste.
3128  */
3129 int
3130 cxgbe_media_change(struct ifnet *ifp)
3131 {
3132         struct vi_info *vi = ifp->if_softc;
3133         struct port_info *pi = vi->pi;
3134         struct ifmedia *ifm = &pi->media;
3135         struct link_config *lc = &pi->link_cfg;
3136         struct adapter *sc = pi->adapter;
3137         int rc;
3138
3139         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3140         if (rc != 0)
3141                 return (rc);
3142         PORT_LOCK(pi);
3143         if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3144                 /* ifconfig .. media autoselect */
3145                 if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3146                         rc = ENOTSUP; /* AN not supported by transceiver */
3147                         goto done;
3148                 }
3149                 lc->requested_aneg = AUTONEG_ENABLE;
3150                 lc->requested_speed = 0;
3151                 lc->requested_fc |= PAUSE_AUTONEG;
3152         } else {
3153                 lc->requested_aneg = AUTONEG_DISABLE;
3154                 lc->requested_speed =
3155                     ifmedia_baudrate(ifm->ifm_media) / 1000000;
3156                 lc->requested_fc = 0;
3157                 if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3158                         lc->requested_fc |= PAUSE_RX;
3159                 if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3160                         lc->requested_fc |= PAUSE_TX;
3161         }
3162         if (pi->up_vis > 0) {
3163                 fixup_link_config(pi);
3164                 rc = apply_link_config(pi);
3165         }
3166 done:
3167         PORT_UNLOCK(pi);
3168         end_synchronized_op(sc, 0);
3169         return (rc);
3170 }
3171
3172 /*
3173  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3174  * given speed.
3175  */
3176 static int
3177 port_mword(struct port_info *pi, uint32_t speed)
3178 {
3179
3180         MPASS(speed & M_FW_PORT_CAP32_SPEED);
3181         MPASS(powerof2(speed));
3182
3183         switch(pi->port_type) {
3184         case FW_PORT_TYPE_BT_SGMII:
3185         case FW_PORT_TYPE_BT_XFI:
3186         case FW_PORT_TYPE_BT_XAUI:
3187                 /* BaseT */
3188                 switch (speed) {
3189                 case FW_PORT_CAP32_SPEED_100M:
3190                         return (IFM_100_T);
3191                 case FW_PORT_CAP32_SPEED_1G:
3192                         return (IFM_1000_T);
3193                 case FW_PORT_CAP32_SPEED_10G:
3194                         return (IFM_10G_T);
3195                 }
3196                 break;
3197         case FW_PORT_TYPE_KX4:
3198                 if (speed == FW_PORT_CAP32_SPEED_10G)
3199                         return (IFM_10G_KX4);
3200                 break;
3201         case FW_PORT_TYPE_CX4:
3202                 if (speed == FW_PORT_CAP32_SPEED_10G)
3203                         return (IFM_10G_CX4);
3204                 break;
3205         case FW_PORT_TYPE_KX:
3206                 if (speed == FW_PORT_CAP32_SPEED_1G)
3207                         return (IFM_1000_KX);
3208                 break;
3209         case FW_PORT_TYPE_KR:
3210         case FW_PORT_TYPE_BP_AP:
3211         case FW_PORT_TYPE_BP4_AP:
3212         case FW_PORT_TYPE_BP40_BA:
3213         case FW_PORT_TYPE_KR4_100G:
3214         case FW_PORT_TYPE_KR_SFP28:
3215         case FW_PORT_TYPE_KR_XLAUI:
3216                 switch (speed) {
3217                 case FW_PORT_CAP32_SPEED_1G:
3218                         return (IFM_1000_KX);
3219                 case FW_PORT_CAP32_SPEED_10G:
3220                         return (IFM_10G_KR);
3221                 case FW_PORT_CAP32_SPEED_25G:
3222                         return (IFM_25G_KR);
3223                 case FW_PORT_CAP32_SPEED_40G:
3224                         return (IFM_40G_KR4);
3225                 case FW_PORT_CAP32_SPEED_50G:
3226                         return (IFM_50G_KR2);
3227                 case FW_PORT_CAP32_SPEED_100G:
3228                         return (IFM_100G_KR4);
3229                 }
3230                 break;
3231         case FW_PORT_TYPE_FIBER_XFI:
3232         case FW_PORT_TYPE_FIBER_XAUI:
3233         case FW_PORT_TYPE_SFP:
3234         case FW_PORT_TYPE_QSFP_10G:
3235         case FW_PORT_TYPE_QSA:
3236         case FW_PORT_TYPE_QSFP:
3237         case FW_PORT_TYPE_CR4_QSFP:
3238         case FW_PORT_TYPE_CR_QSFP:
3239         case FW_PORT_TYPE_CR2_QSFP:
3240         case FW_PORT_TYPE_SFP28:
3241                 /* Pluggable transceiver */
3242                 switch (pi->mod_type) {
3243                 case FW_PORT_MOD_TYPE_LR:
3244                         switch (speed) {
3245                         case FW_PORT_CAP32_SPEED_1G:
3246                                 return (IFM_1000_LX);
3247                         case FW_PORT_CAP32_SPEED_10G:
3248                                 return (IFM_10G_LR);
3249                         case FW_PORT_CAP32_SPEED_25G:
3250                                 return (IFM_25G_LR);
3251                         case FW_PORT_CAP32_SPEED_40G:
3252                                 return (IFM_40G_LR4);
3253                         case FW_PORT_CAP32_SPEED_50G:
3254                                 return (IFM_50G_LR2);
3255                         case FW_PORT_CAP32_SPEED_100G:
3256                                 return (IFM_100G_LR4);
3257                         }
3258                         break;
3259                 case FW_PORT_MOD_TYPE_SR:
3260                         switch (speed) {
3261                         case FW_PORT_CAP32_SPEED_1G:
3262                                 return (IFM_1000_SX);
3263                         case FW_PORT_CAP32_SPEED_10G:
3264                                 return (IFM_10G_SR);
3265                         case FW_PORT_CAP32_SPEED_25G:
3266                                 return (IFM_25G_SR);
3267                         case FW_PORT_CAP32_SPEED_40G:
3268                                 return (IFM_40G_SR4);
3269                         case FW_PORT_CAP32_SPEED_50G:
3270                                 return (IFM_50G_SR2);
3271                         case FW_PORT_CAP32_SPEED_100G:
3272                                 return (IFM_100G_SR4);
3273                         }
3274                         break;
3275                 case FW_PORT_MOD_TYPE_ER:
3276                         if (speed == FW_PORT_CAP32_SPEED_10G)
3277                                 return (IFM_10G_ER);
3278                         break;
3279                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3280                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3281                         switch (speed) {
3282                         case FW_PORT_CAP32_SPEED_1G:
3283                                 return (IFM_1000_CX);
3284                         case FW_PORT_CAP32_SPEED_10G:
3285                                 return (IFM_10G_TWINAX);
3286                         case FW_PORT_CAP32_SPEED_25G:
3287                                 return (IFM_25G_CR);
3288                         case FW_PORT_CAP32_SPEED_40G:
3289                                 return (IFM_40G_CR4);
3290                         case FW_PORT_CAP32_SPEED_50G:
3291                                 return (IFM_50G_CR2);
3292                         case FW_PORT_CAP32_SPEED_100G:
3293                                 return (IFM_100G_CR4);
3294                         }
3295                         break;
3296                 case FW_PORT_MOD_TYPE_LRM:
3297                         if (speed == FW_PORT_CAP32_SPEED_10G)
3298                                 return (IFM_10G_LRM);
3299                         break;
3300                 case FW_PORT_MOD_TYPE_NA:
3301                         MPASS(0);       /* Not pluggable? */
3302                         /* fall throough */
3303                 case FW_PORT_MOD_TYPE_ERROR:
3304                 case FW_PORT_MOD_TYPE_UNKNOWN:
3305                 case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3306                         break;
3307                 case FW_PORT_MOD_TYPE_NONE:
3308                         return (IFM_NONE);
3309                 }
3310                 break;
3311         case FW_PORT_TYPE_NONE:
3312                 return (IFM_NONE);
3313         }
3314
3315         return (IFM_UNKNOWN);
3316 }
3317
3318 void
3319 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3320 {
3321         struct vi_info *vi = ifp->if_softc;
3322         struct port_info *pi = vi->pi;
3323         struct adapter *sc = pi->adapter;
3324         struct link_config *lc = &pi->link_cfg;
3325
3326         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3327                 return;
3328         PORT_LOCK(pi);
3329
3330         if (pi->up_vis == 0) {
3331                 /*
3332                  * If all the interfaces are administratively down the firmware
3333                  * does not report transceiver changes.  Refresh port info here
3334                  * so that ifconfig displays accurate ifmedia at all times.
3335                  * This is the only reason we have a synchronized op in this
3336                  * function.  Just PORT_LOCK would have been enough otherwise.
3337                  */
3338                 t4_update_port_info(pi);
3339                 build_medialist(pi);
3340         }
3341
3342         /* ifm_status */
3343         ifmr->ifm_status = IFM_AVALID;
3344         if (lc->link_ok == false)
3345                 goto done;
3346         ifmr->ifm_status |= IFM_ACTIVE;
3347
3348         /* ifm_active */
3349         ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3350         ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3351         if (lc->fc & PAUSE_RX)
3352                 ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3353         if (lc->fc & PAUSE_TX)
3354                 ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3355         ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3356 done:
3357         PORT_UNLOCK(pi);
3358         end_synchronized_op(sc, 0);
3359 }
3360
3361 static int
3362 vcxgbe_probe(device_t dev)
3363 {
3364         char buf[128];
3365         struct vi_info *vi = device_get_softc(dev);
3366
3367         snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3368             vi - vi->pi->vi);
3369         device_set_desc_copy(dev, buf);
3370
3371         return (BUS_PROBE_DEFAULT);
3372 }
3373
3374 static int
3375 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3376 {
3377         int func, index, rc;
3378         uint32_t param, val;
3379
3380         ASSERT_SYNCHRONIZED_OP(sc);
3381
3382         index = vi - pi->vi;
3383         MPASS(index > 0);       /* This function deals with _extra_ VIs only */
3384         KASSERT(index < nitems(vi_mac_funcs),
3385             ("%s: VI %s doesn't have a MAC func", __func__,
3386             device_get_nameunit(vi->dev)));
3387         func = vi_mac_funcs[index];
3388         rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3389             vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3390         if (rc < 0) {
3391                 CH_ERR(vi, "failed to allocate virtual interface %d"
3392                     "for port %d: %d\n", index, pi->port_id, -rc);
3393                 return (-rc);
3394         }
3395         vi->viid = rc;
3396
3397         if (vi->rss_size == 1) {
3398                 /*
3399                  * This VI didn't get a slice of the RSS table.  Reduce the
3400                  * number of VIs being created (hw.cxgbe.num_vis) or modify the
3401                  * configuration file (nvi, rssnvi for this PF) if this is a
3402                  * problem.
3403                  */
3404                 device_printf(vi->dev, "RSS table not available.\n");
3405                 vi->rss_base = 0xffff;
3406
3407                 return (0);
3408         }
3409
3410         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3411             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3412             V_FW_PARAMS_PARAM_YZ(vi->viid);
3413         rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3414         if (rc)
3415                 vi->rss_base = 0xffff;
3416         else {
3417                 MPASS((val >> 16) == vi->rss_size);
3418                 vi->rss_base = val & 0xffff;
3419         }
3420
3421         return (0);
3422 }
3423
3424 static int
3425 vcxgbe_attach(device_t dev)
3426 {
3427         struct vi_info *vi;
3428         struct port_info *pi;
3429         struct adapter *sc;
3430         int rc;
3431
3432         vi = device_get_softc(dev);
3433         pi = vi->pi;
3434         sc = pi->adapter;
3435
3436         rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3437         if (rc)
3438                 return (rc);
3439         rc = alloc_extra_vi(sc, pi, vi);
3440         end_synchronized_op(sc, 0);
3441         if (rc)
3442                 return (rc);
3443
3444         rc = cxgbe_vi_attach(dev, vi);
3445         if (rc) {
3446                 t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3447                 return (rc);
3448         }
3449         return (0);
3450 }
3451
3452 static int
3453 vcxgbe_detach(device_t dev)
3454 {
3455         struct vi_info *vi;
3456         struct adapter *sc;
3457
3458         vi = device_get_softc(dev);
3459         sc = vi->adapter;
3460
3461         doom_vi(sc, vi);
3462
3463         cxgbe_vi_detach(vi);
3464         t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3465
3466         end_synchronized_op(sc, 0);
3467
3468         return (0);
3469 }
3470
3471 static struct callout fatal_callout;
3472 static struct taskqueue *reset_tq;
3473
3474 static void
3475 delayed_panic(void *arg)
3476 {
3477         struct adapter *sc = arg;
3478
3479         panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3480 }
3481
3482 void
3483 t4_fatal_err(struct adapter *sc, bool fw_error)
3484 {
3485
3486         t4_shutdown_adapter(sc);
3487         log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
3488             device_get_nameunit(sc->dev));
3489         if (fw_error) {
3490                 if (sc->flags & CHK_MBOX_ACCESS)
3491                         ASSERT_SYNCHRONIZED_OP(sc);
3492                 sc->flags |= ADAP_ERR;
3493         } else {
3494                 ADAPTER_LOCK(sc);
3495                 sc->flags |= ADAP_ERR;
3496                 ADAPTER_UNLOCK(sc);
3497         }
3498 #ifdef TCP_OFFLOAD
3499         taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
3500 #endif
3501
3502         if (t4_panic_on_fatal_err) {
3503                 CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3504                 callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3505         } else if (t4_reset_on_fatal_err) {
3506                 CH_ALERT(sc, "resetting on fatal error.\n");
3507                 taskqueue_enqueue(reset_tq, &sc->reset_task);
3508         }
3509 }
3510
3511 void
3512 t4_add_adapter(struct adapter *sc)
3513 {
3514         sx_xlock(&t4_list_lock);
3515         SLIST_INSERT_HEAD(&t4_list, sc, link);
3516         sx_xunlock(&t4_list_lock);
3517 }
3518
3519 int
3520 t4_map_bars_0_and_4(struct adapter *sc)
3521 {
3522         sc->regs_rid = PCIR_BAR(0);
3523         sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3524             &sc->regs_rid, RF_ACTIVE);
3525         if (sc->regs_res == NULL) {
3526                 device_printf(sc->dev, "cannot map registers.\n");
3527                 return (ENXIO);
3528         }
3529         sc->bt = rman_get_bustag(sc->regs_res);
3530         sc->bh = rman_get_bushandle(sc->regs_res);
3531         sc->mmio_len = rman_get_size(sc->regs_res);
3532         setbit(&sc->doorbells, DOORBELL_KDB);
3533
3534         sc->msix_rid = PCIR_BAR(4);
3535         sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3536             &sc->msix_rid, RF_ACTIVE);
3537         if (sc->msix_res == NULL) {
3538                 device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3539                 return (ENXIO);
3540         }
3541
3542         return (0);
3543 }
3544
3545 int
3546 t4_map_bar_2(struct adapter *sc)
3547 {
3548
3549         /*
3550          * T4: only iWARP driver uses the userspace doorbells.  There is no need
3551          * to map it if RDMA is disabled.
3552          */
3553         if (is_t4(sc) && sc->rdmacaps == 0)
3554                 return (0);
3555
3556         sc->udbs_rid = PCIR_BAR(2);
3557         sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3558             &sc->udbs_rid, RF_ACTIVE);
3559         if (sc->udbs_res == NULL) {
3560                 device_printf(sc->dev, "cannot map doorbell BAR.\n");
3561                 return (ENXIO);
3562         }
3563         sc->udbs_base = rman_get_virtual(sc->udbs_res);
3564
3565         if (chip_id(sc) >= CHELSIO_T5) {
3566                 setbit(&sc->doorbells, DOORBELL_UDB);
3567 #if defined(__i386__) || defined(__amd64__)
3568                 if (t5_write_combine) {
3569                         int rc, mode;
3570
3571                         /*
3572                          * Enable write combining on BAR2.  This is the
3573                          * userspace doorbell BAR and is split into 128B
3574                          * (UDBS_SEG_SIZE) doorbell regions, each associated
3575                          * with an egress queue.  The first 64B has the doorbell
3576                          * and the second 64B can be used to submit a tx work
3577                          * request with an implicit doorbell.
3578                          */
3579
3580                         rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3581                             rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3582                         if (rc == 0) {
3583                                 clrbit(&sc->doorbells, DOORBELL_UDB);
3584                                 setbit(&sc->doorbells, DOORBELL_WCWR);
3585                                 setbit(&sc->doorbells, DOORBELL_UDBWC);
3586                         } else {
3587                                 device_printf(sc->dev,
3588                                     "couldn't enable write combining: %d\n",
3589                                     rc);
3590                         }
3591
3592                         mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3593                         t4_write_reg(sc, A_SGE_STAT_CFG,
3594                             V_STATSOURCE_T5(7) | mode);
3595                 }
3596 #endif
3597         }
3598         sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3599
3600         return (0);
3601 }
3602
3603 struct memwin_init {
3604         uint32_t base;
3605         uint32_t aperture;
3606 };
3607
3608 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3609         { MEMWIN0_BASE, MEMWIN0_APERTURE },
3610         { MEMWIN1_BASE, MEMWIN1_APERTURE },
3611         { MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3612 };
3613
3614 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3615         { MEMWIN0_BASE, MEMWIN0_APERTURE },
3616         { MEMWIN1_BASE, MEMWIN1_APERTURE },
3617         { MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3618 };
3619
3620 static void
3621 setup_memwin(struct adapter *sc)
3622 {
3623         const struct memwin_init *mw_init;
3624         struct memwin *mw;
3625         int i;
3626         uint32_t bar0;
3627
3628         if (is_t4(sc)) {
3629                 /*
3630                  * Read low 32b of bar0 indirectly via the hardware backdoor
3631                  * mechanism.  Works from within PCI passthrough environments
3632                  * too, where rman_get_start() can return a different value.  We
3633                  * need to program the T4 memory window decoders with the actual
3634                  * addresses that will be coming across the PCIe link.
3635                  */
3636                 bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3637                 bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3638
3639                 mw_init = &t4_memwin[0];
3640         } else {
3641                 /* T5+ use the relative offset inside the PCIe BAR */
3642                 bar0 = 0;
3643
3644                 mw_init = &t5_memwin[0];
3645         }
3646
3647         for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3648                 if (!rw_initialized(&mw->mw_lock)) {
3649                         rw_init(&mw->mw_lock, "memory window access");
3650                         mw->mw_base = mw_init->base;
3651                         mw->mw_aperture = mw_init->aperture;
3652                         mw->mw_curpos = 0;
3653                 }
3654                 t4_write_reg(sc,
3655                     PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3656                     (mw->mw_base + bar0) | V_BIR(0) |
3657                     V_WINDOW(ilog2(mw->mw_aperture) - 10));
3658                 rw_wlock(&mw->mw_lock);
3659                 position_memwin(sc, i, mw->mw_curpos);
3660                 rw_wunlock(&mw->mw_lock);
3661         }
3662
3663         /* flush */
3664         t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3665 }
3666
3667 /*
3668  * Positions the memory window at the given address in the card's address space.
3669  * There are some alignment requirements and the actual position may be at an
3670  * address prior to the requested address.  mw->mw_curpos always has the actual
3671  * position of the window.
3672  */
3673 static void
3674 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3675 {
3676         struct memwin *mw;
3677         uint32_t pf;
3678         uint32_t reg;
3679
3680         MPASS(idx >= 0 && idx < NUM_MEMWIN);
3681         mw = &sc->memwin[idx];
3682         rw_assert(&mw->mw_lock, RA_WLOCKED);
3683
3684         if (is_t4(sc)) {
3685                 pf = 0;
3686                 mw->mw_curpos = addr & ~0xf;    /* start must be 16B aligned */
3687         } else {
3688                 pf = V_PFNUM(sc->pf);
3689                 mw->mw_curpos = addr & ~0x7f;   /* start must be 128B aligned */
3690         }
3691         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3692         t4_write_reg(sc, reg, mw->mw_curpos | pf);
3693         t4_read_reg(sc, reg);   /* flush */
3694 }
3695
3696 int
3697 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3698     int len, int rw)
3699 {
3700         struct memwin *mw;
3701         uint32_t mw_end, v;
3702
3703         MPASS(idx >= 0 && idx < NUM_MEMWIN);
3704
3705         /* Memory can only be accessed in naturally aligned 4 byte units */
3706         if (addr & 3 || len & 3 || len <= 0)
3707                 return (EINVAL);
3708
3709         mw = &sc->memwin[idx];
3710         while (len > 0) {
3711                 rw_rlock(&mw->mw_lock);
3712                 mw_end = mw->mw_curpos + mw->mw_aperture;
3713                 if (addr >= mw_end || addr < mw->mw_curpos) {
3714                         /* Will need to reposition the window */
3715                         if (!rw_try_upgrade(&mw->mw_lock)) {
3716                                 rw_runlock(&mw->mw_lock);
3717                                 rw_wlock(&mw->mw_lock);
3718                         }
3719                         rw_assert(&mw->mw_lock, RA_WLOCKED);
3720                         position_memwin(sc, idx, addr);
3721                         rw_downgrade(&mw->mw_lock);
3722                         mw_end = mw->mw_curpos + mw->mw_aperture;
3723                 }
3724                 rw_assert(&mw->mw_lock, RA_RLOCKED);
3725                 while (addr < mw_end && len > 0) {
3726                         if (rw == 0) {
3727                                 v = t4_read_reg(sc, mw->mw_base + addr -
3728                                     mw->mw_curpos);
3729                                 *val++ = le32toh(v);
3730                         } else {
3731                                 v = *val++;
3732                                 t4_write_reg(sc, mw->mw_base + addr -
3733                                     mw->mw_curpos, htole32(v));
3734                         }
3735                         addr += 4;
3736                         len -= 4;
3737                 }
3738                 rw_runlock(&mw->mw_lock);
3739         }
3740
3741         return (0);
3742 }
3743
3744 static void
3745 t4_init_atid_table(struct adapter *sc)
3746 {
3747         struct tid_info *t;
3748         int i;
3749
3750         t = &sc->tids;
3751         if (t->natids == 0)
3752                 return;
3753
3754         MPASS(t->atid_tab == NULL);
3755
3756         t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3757             M_ZERO | M_WAITOK);
3758         mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3759         t->afree = t->atid_tab;
3760         t->atids_in_use = 0;
3761         for (i = 1; i < t->natids; i++)
3762                 t->atid_tab[i - 1].next = &t->atid_tab[i];
3763         t->atid_tab[t->natids - 1].next = NULL;
3764 }
3765
3766 static void
3767 t4_free_atid_table(struct adapter *sc)
3768 {
3769         struct tid_info *t;
3770
3771         t = &sc->tids;
3772
3773         KASSERT(t->atids_in_use == 0,
3774             ("%s: %d atids still in use.", __func__, t->atids_in_use));
3775
3776         if (mtx_initialized(&t->atid_lock))
3777                 mtx_destroy(&t->atid_lock);
3778         free(t->atid_tab, M_CXGBE);
3779         t->atid_tab = NULL;
3780 }
3781
3782 int
3783 alloc_atid(struct adapter *sc, void *ctx)
3784 {
3785         struct tid_info *t = &sc->tids;
3786         int atid = -1;
3787
3788         mtx_lock(&t->atid_lock);
3789         if (t->afree) {
3790                 union aopen_entry *p = t->afree;
3791
3792                 atid = p - t->atid_tab;
3793                 MPASS(atid <= M_TID_TID);
3794                 t->afree = p->next;
3795                 p->data = ctx;
3796                 t->atids_in_use++;
3797         }
3798         mtx_unlock(&t->atid_lock);
3799         return (atid);
3800 }
3801
3802 void *
3803 lookup_atid(struct adapter *sc, int atid)
3804 {
3805         struct tid_info *t = &sc->tids;
3806
3807         return (t->atid_tab[atid].data);
3808 }
3809
3810 void
3811 free_atid(struct adapter *sc, int atid)
3812 {
3813         struct tid_info *t = &sc->tids;
3814         union aopen_entry *p = &t->atid_tab[atid];
3815
3816         mtx_lock(&t->atid_lock);
3817         p->next = t->afree;
3818         t->afree = p;
3819         t->atids_in_use--;
3820         mtx_unlock(&t->atid_lock);
3821 }
3822
3823 static void
3824 queue_tid_release(struct adapter *sc, int tid)
3825 {
3826
3827         CXGBE_UNIMPLEMENTED("deferred tid release");
3828 }
3829
3830 void
3831 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3832 {
3833         struct wrqe *wr;
3834         struct cpl_tid_release *req;
3835
3836         wr = alloc_wrqe(sizeof(*req), ctrlq);
3837         if (wr == NULL) {
3838                 queue_tid_release(sc, tid);     /* defer */
3839                 return;
3840         }
3841         req = wrtod(wr);
3842
3843         INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3844
3845         t4_wrq_tx(sc, wr);
3846 }
3847
3848 static int
3849 t4_range_cmp(const void *a, const void *b)
3850 {
3851         return ((const struct t4_range *)a)->start -
3852                ((const struct t4_range *)b)->start;
3853 }
3854
3855 /*
3856  * Verify that the memory range specified by the addr/len pair is valid within
3857  * the card's address space.
3858  */
3859 static int
3860 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3861 {
3862         struct t4_range mem_ranges[4], *r, *next;
3863         uint32_t em, addr_len;
3864         int i, n, remaining;
3865
3866         /* Memory can only be accessed in naturally aligned 4 byte units */
3867         if (addr & 3 || len & 3 || len == 0)
3868                 return (EINVAL);
3869
3870         /* Enabled memories */
3871         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3872
3873         r = &mem_ranges[0];
3874         n = 0;
3875         bzero(r, sizeof(mem_ranges));
3876         if (em & F_EDRAM0_ENABLE) {
3877                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3878                 r->size = G_EDRAM0_SIZE(addr_len) << 20;
3879                 if (r->size > 0) {
3880                         r->start = G_EDRAM0_BASE(addr_len) << 20;
3881                         if (addr >= r->start &&
3882                             addr + len <= r->start + r->size)
3883                                 return (0);
3884                         r++;
3885                         n++;
3886                 }
3887         }
3888         if (em & F_EDRAM1_ENABLE) {
3889                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3890                 r->size = G_EDRAM1_SIZE(addr_len) << 20;
3891                 if (r->size > 0) {
3892                         r->start = G_EDRAM1_BASE(addr_len) << 20;
3893                         if (addr >= r->start &&
3894                             addr + len <= r->start + r->size)
3895                                 return (0);
3896                         r++;
3897                         n++;
3898                 }
3899         }
3900         if (em & F_EXT_MEM_ENABLE) {
3901                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3902                 r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3903                 if (r->size > 0) {
3904                         r->start = G_EXT_MEM_BASE(addr_len) << 20;
3905                         if (addr >= r->start &&
3906                             addr + len <= r->start + r->size)
3907                                 return (0);
3908                         r++;
3909                         n++;
3910                 }
3911         }
3912         if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3913                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3914                 r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3915                 if (r->size > 0) {
3916                         r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3917                         if (addr >= r->start &&
3918                             addr + len <= r->start + r->size)
3919                                 return (0);
3920                         r++;
3921                         n++;
3922                 }
3923         }
3924         MPASS(n <= nitems(mem_ranges));
3925
3926         if (n > 1) {
3927                 /* Sort and merge the ranges. */
3928                 qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3929
3930                 /* Start from index 0 and examine the next n - 1 entries. */
3931                 r = &mem_ranges[0];
3932                 for (remaining = n - 1; remaining > 0; remaining--, r++) {
3933
3934                         MPASS(r->size > 0);     /* r is a valid entry. */
3935                         next = r + 1;
3936                         MPASS(next->size > 0);  /* and so is the next one. */
3937
3938                         while (r->start + r->size >= next->start) {
3939                                 /* Merge the next one into the current entry. */
3940                                 r->size = max(r->start + r->size,
3941                                     next->start + next->size) - r->start;
3942                                 n--;    /* One fewer entry in total. */
3943                                 if (--remaining == 0)
3944                                         goto done;      /* short circuit */
3945                                 next++;
3946                         }
3947                         if (next != r + 1) {
3948                                 /*
3949                                  * Some entries were merged into r and next
3950                                  * points to the first valid entry that couldn't
3951                                  * be merged.
3952                                  */
3953                                 MPASS(next->size > 0);  /* must be valid */
3954                                 memcpy(r + 1, next, remaining * sizeof(*r));
3955 #ifdef INVARIANTS
3956                                 /*
3957                                  * This so that the foo->size assertion in the
3958                                  * next iteration of the loop do the right
3959                                  * thing for entries that were pulled up and are
3960                                  * no longer valid.
3961                                  */
3962                                 MPASS(n < nitems(mem_ranges));
3963                                 bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3964                                     sizeof(struct t4_range));
3965 #endif
3966                         }
3967                 }
3968 done:
3969                 /* Done merging the ranges. */
3970                 MPASS(n > 0);
3971                 r = &mem_ranges[0];
3972                 for (i = 0; i < n; i++, r++) {
3973                         if (addr >= r->start &&
3974                             addr + len <= r->start + r->size)
3975                                 return (0);
3976                 }
3977         }
3978
3979         return (EFAULT);
3980 }
3981
3982 static int
3983 fwmtype_to_hwmtype(int mtype)
3984 {
3985
3986         switch (mtype) {
3987         case FW_MEMTYPE_EDC0:
3988                 return (MEM_EDC0);
3989         case FW_MEMTYPE_EDC1:
3990                 return (MEM_EDC1);
3991         case FW_MEMTYPE_EXTMEM:
3992                 return (MEM_MC0);
3993         case FW_MEMTYPE_EXTMEM1:
3994                 return (MEM_MC1);
3995         default:
3996                 panic("%s: cannot translate fw mtype %d.", __func__, mtype);
3997         }
3998 }
3999
4000 /*
4001  * Verify that the memory range specified by the memtype/offset/len pair is
4002  * valid and lies entirely within the memtype specified.  The global address of
4003  * the start of the range is returned in addr.
4004  */
4005 static int
4006 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4007     uint32_t *addr)
4008 {
4009         uint32_t em, addr_len, maddr;
4010
4011         /* Memory can only be accessed in naturally aligned 4 byte units */
4012         if (off & 3 || len & 3 || len == 0)
4013                 return (EINVAL);
4014
4015         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4016         switch (fwmtype_to_hwmtype(mtype)) {
4017         case MEM_EDC0:
4018                 if (!(em & F_EDRAM0_ENABLE))
4019                         return (EINVAL);
4020                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4021                 maddr = G_EDRAM0_BASE(addr_len) << 20;
4022                 break;
4023         case MEM_EDC1:
4024                 if (!(em & F_EDRAM1_ENABLE))
4025                         return (EINVAL);
4026                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4027                 maddr = G_EDRAM1_BASE(addr_len) << 20;
4028                 break;
4029         case MEM_MC:
4030                 if (!(em & F_EXT_MEM_ENABLE))
4031                         return (EINVAL);
4032                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4033                 maddr = G_EXT_MEM_BASE(addr_len) << 20;
4034                 break;
4035         case MEM_MC1:
4036                 if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4037                         return (EINVAL);
4038                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4039                 maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4040                 break;
4041         default:
4042                 return (EINVAL);
4043         }
4044
4045         *addr = maddr + off;    /* global address */
4046         return (validate_mem_range(sc, *addr, len));
4047 }
4048
4049 static int
4050 fixup_devlog_params(struct adapter *sc)
4051 {
4052         struct devlog_params *dparams = &sc->params.devlog;
4053         int rc;
4054
4055         rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4056             dparams->size, &dparams->addr);
4057
4058         return (rc);
4059 }
4060
4061 static void
4062 update_nirq(struct intrs_and_queues *iaq, int nports)
4063 {
4064
4065         iaq->nirq = T4_EXTRA_INTR;
4066         iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4067         iaq->nirq += nports * iaq->nofldrxq;
4068         iaq->nirq += nports * (iaq->num_vis - 1) *
4069             max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4070         iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4071 }
4072
4073 /*
4074  * Adjust requirements to fit the number of interrupts available.
4075  */
4076 static void
4077 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4078     int navail)
4079 {
4080         int old_nirq;
4081         const int nports = sc->params.nports;
4082
4083         MPASS(nports > 0);
4084         MPASS(navail > 0);
4085
4086         bzero(iaq, sizeof(*iaq));
4087         iaq->intr_type = itype;
4088         iaq->num_vis = t4_num_vis;
4089         iaq->ntxq = t4_ntxq;
4090         iaq->ntxq_vi = t4_ntxq_vi;
4091         iaq->nrxq = t4_nrxq;
4092         iaq->nrxq_vi = t4_nrxq_vi;
4093 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4094         if (is_offload(sc) || is_ethoffload(sc)) {
4095                 iaq->nofldtxq = t4_nofldtxq;
4096                 iaq->nofldtxq_vi = t4_nofldtxq_vi;
4097         }
4098 #endif
4099 #ifdef TCP_OFFLOAD
4100         if (is_offload(sc)) {
4101                 iaq->nofldrxq = t4_nofldrxq;
4102                 iaq->nofldrxq_vi = t4_nofldrxq_vi;
4103         }
4104 #endif
4105 #ifdef DEV_NETMAP
4106         if (t4_native_netmap & NN_MAIN_VI) {
4107                 iaq->nnmtxq = t4_nnmtxq;
4108                 iaq->nnmrxq = t4_nnmrxq;
4109         }
4110         if (t4_native_netmap & NN_EXTRA_VI) {
4111                 iaq->nnmtxq_vi = t4_nnmtxq_vi;
4112                 iaq->nnmrxq_vi = t4_nnmrxq_vi;
4113         }
4114 #endif
4115
4116         update_nirq(iaq, nports);
4117         if (iaq->nirq <= navail &&
4118             (itype != INTR_MSI || powerof2(iaq->nirq))) {
4119                 /*
4120                  * This is the normal case -- there are enough interrupts for
4121                  * everything.
4122                  */
4123                 goto done;
4124         }
4125
4126         /*
4127          * If extra VIs have been configured try reducing their count and see if
4128          * that works.
4129          */
4130         while (iaq->num_vis > 1) {
4131                 iaq->num_vis--;
4132                 update_nirq(iaq, nports);
4133                 if (iaq->nirq <= navail &&
4134                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
4135                         device_printf(sc->dev, "virtual interfaces per port "
4136                             "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4137                             "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4138                             "itype %d, navail %u, nirq %d.\n",
4139                             iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4140                             iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4141                             itype, navail, iaq->nirq);
4142                         goto done;
4143                 }
4144         }
4145
4146         /*
4147          * Extra VIs will not be created.  Log a message if they were requested.
4148          */
4149         MPASS(iaq->num_vis == 1);
4150         iaq->ntxq_vi = iaq->nrxq_vi = 0;
4151         iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4152         iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4153         if (iaq->num_vis != t4_num_vis) {
4154                 device_printf(sc->dev, "extra virtual interfaces disabled.  "
4155                     "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4156                     "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4157                     iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4158                     iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4159         }
4160
4161         /*
4162          * Keep reducing the number of NIC rx queues to the next lower power of
4163          * 2 (for even RSS distribution) and halving the TOE rx queues and see
4164          * if that works.
4165          */
4166         do {
4167                 if (iaq->nrxq > 1) {
4168                         do {
4169                                 iaq->nrxq--;
4170                         } while (!powerof2(iaq->nrxq));
4171                         if (iaq->nnmrxq > iaq->nrxq)
4172                                 iaq->nnmrxq = iaq->nrxq;
4173                 }
4174                 if (iaq->nofldrxq > 1)
4175                         iaq->nofldrxq >>= 1;
4176
4177                 old_nirq = iaq->nirq;
4178                 update_nirq(iaq, nports);
4179                 if (iaq->nirq <= navail &&
4180                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
4181                         device_printf(sc->dev, "running with reduced number of "
4182                             "rx queues because of shortage of interrupts.  "
4183                             "nrxq=%u, nofldrxq=%u.  "
4184                             "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4185                             iaq->nofldrxq, itype, navail, iaq->nirq);
4186                         goto done;
4187                 }
4188         } while (old_nirq != iaq->nirq);
4189
4190         /* One interrupt for everything.  Ugh. */
4191         device_printf(sc->dev, "running with minimal number of queues.  "
4192             "itype %d, navail %u.\n", itype, navail);
4193         iaq->nirq = 1;
4194         iaq->nrxq = 1;
4195         iaq->ntxq = 1;
4196         if (iaq->nofldrxq > 0) {
4197                 iaq->nofldrxq = 1;
4198                 iaq->nofldtxq = 1;
4199         }
4200         iaq->nnmtxq = 0;
4201         iaq->nnmrxq = 0;
4202 done:
4203         MPASS(iaq->num_vis > 0);
4204         if (iaq->num_vis > 1) {
4205                 MPASS(iaq->nrxq_vi > 0);
4206                 MPASS(iaq->ntxq_vi > 0);
4207         }
4208         MPASS(iaq->nirq > 0);
4209         MPASS(iaq->nrxq > 0);
4210         MPASS(iaq->ntxq > 0);
4211         if (itype == INTR_MSI) {
4212                 MPASS(powerof2(iaq->nirq));
4213         }
4214 }
4215
4216 static int
4217 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4218 {
4219         int rc, itype, navail, nalloc;
4220
4221         for (itype = INTR_MSIX; itype; itype >>= 1) {
4222
4223                 if ((itype & t4_intr_types) == 0)
4224                         continue;       /* not allowed */
4225
4226                 if (itype == INTR_MSIX)
4227                         navail = pci_msix_count(sc->dev);
4228                 else if (itype == INTR_MSI)
4229                         navail = pci_msi_count(sc->dev);
4230                 else
4231                         navail = 1;
4232 restart:
4233                 if (navail == 0)
4234                         continue;
4235
4236                 calculate_iaq(sc, iaq, itype, navail);
4237                 nalloc = iaq->nirq;
4238                 rc = 0;
4239                 if (itype == INTR_MSIX)
4240                         rc = pci_alloc_msix(sc->dev, &nalloc);
4241                 else if (itype == INTR_MSI)
4242                         rc = pci_alloc_msi(sc->dev, &nalloc);
4243
4244                 if (rc == 0 && nalloc > 0) {
4245                         if (nalloc == iaq->nirq)
4246                                 return (0);
4247
4248                         /*
4249                          * Didn't get the number requested.  Use whatever number
4250                          * the kernel is willing to allocate.
4251                          */
4252                         device_printf(sc->dev, "fewer vectors than requested, "
4253                             "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4254                             itype, iaq->nirq, nalloc);
4255                         pci_release_msi(sc->dev);
4256                         navail = nalloc;
4257                         goto restart;
4258                 }
4259
4260                 device_printf(sc->dev,
4261                     "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4262                     itype, rc, iaq->nirq, nalloc);
4263         }
4264
4265         device_printf(sc->dev,
4266             "failed to find a usable interrupt type.  "
4267             "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4268             pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4269
4270         return (ENXIO);
4271 }
4272
4273 #define FW_VERSION(chip) ( \
4274     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4275     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4276     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4277     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4278 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4279
4280 /* Just enough of fw_hdr to cover all version info. */
4281 struct fw_h {
4282         __u8    ver;
4283         __u8    chip;
4284         __be16  len512;
4285         __be32  fw_ver;
4286         __be32  tp_microcode_ver;
4287         __u8    intfver_nic;
4288         __u8    intfver_vnic;
4289         __u8    intfver_ofld;
4290         __u8    intfver_ri;
4291         __u8    intfver_iscsipdu;
4292         __u8    intfver_iscsi;
4293         __u8    intfver_fcoepdu;
4294         __u8    intfver_fcoe;
4295 };
4296 /* Spot check a couple of fields. */
4297 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4298 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4299 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4300
4301 struct fw_info {
4302         uint8_t chip;
4303         char *kld_name;
4304         char *fw_mod_name;
4305         struct fw_h fw_h;
4306 } fw_info[] = {
4307         {
4308                 .chip = CHELSIO_T4,
4309                 .kld_name = "t4fw_cfg",
4310                 .fw_mod_name = "t4fw",
4311                 .fw_h = {
4312                         .chip = FW_HDR_CHIP_T4,
4313                         .fw_ver = htobe32(FW_VERSION(T4)),
4314                         .intfver_nic = FW_INTFVER(T4, NIC),
4315                         .intfver_vnic = FW_INTFVER(T4, VNIC),
4316                         .intfver_ofld = FW_INTFVER(T4, OFLD),
4317                         .intfver_ri = FW_INTFVER(T4, RI),
4318                         .intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4319                         .intfver_iscsi = FW_INTFVER(T4, ISCSI),
4320                         .intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4321                         .intfver_fcoe = FW_INTFVER(T4, FCOE),
4322                 },
4323         }, {
4324                 .chip = CHELSIO_T5,
4325                 .kld_name = "t5fw_cfg",
4326                 .fw_mod_name = "t5fw",
4327                 .fw_h = {
4328                         .chip = FW_HDR_CHIP_T5,
4329                         .fw_ver = htobe32(FW_VERSION(T5)),
4330                         .intfver_nic = FW_INTFVER(T5, NIC),
4331                         .intfver_vnic = FW_INTFVER(T5, VNIC),
4332                         .intfver_ofld = FW_INTFVER(T5, OFLD),
4333                         .intfver_ri = FW_INTFVER(T5, RI),
4334                         .intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4335                         .intfver_iscsi = FW_INTFVER(T5, ISCSI),
4336                         .intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4337                         .intfver_fcoe = FW_INTFVER(T5, FCOE),
4338                 },
4339         }, {
4340                 .chip = CHELSIO_T6,
4341                 .kld_name = "t6fw_cfg",
4342                 .fw_mod_name = "t6fw",
4343                 .fw_h = {
4344                         .chip = FW_HDR_CHIP_T6,
4345                         .fw_ver = htobe32(FW_VERSION(T6)),
4346                         .intfver_nic = FW_INTFVER(T6, NIC),
4347                         .intfver_vnic = FW_INTFVER(T6, VNIC),
4348                         .intfver_ofld = FW_INTFVER(T6, OFLD),
4349                         .intfver_ri = FW_INTFVER(T6, RI),
4350                         .intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4351                         .intfver_iscsi = FW_INTFVER(T6, ISCSI),
4352                         .intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4353                         .intfver_fcoe = FW_INTFVER(T6, FCOE),
4354                 },
4355         }
4356 };
4357
4358 static struct fw_info *
4359 find_fw_info(int chip)
4360 {
4361         int i;
4362
4363         for (i = 0; i < nitems(fw_info); i++) {
4364                 if (fw_info[i].chip == chip)
4365                         return (&fw_info[i]);
4366         }
4367         return (NULL);
4368 }
4369
4370 /*
4371  * Is the given firmware API compatible with the one the driver was compiled
4372  * with?
4373  */
4374 static int
4375 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4376 {
4377
4378         /* short circuit if it's the exact same firmware version */
4379         if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4380                 return (1);
4381
4382         /*
4383          * XXX: Is this too conservative?  Perhaps I should limit this to the
4384          * features that are supported in the driver.
4385          */
4386 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4387         if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4388             SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4389             SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4390                 return (1);
4391 #undef SAME_INTF
4392
4393         return (0);
4394 }
4395
4396 static int
4397 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4398     const struct firmware **fw)
4399 {
4400         struct fw_info *fw_info;
4401
4402         *dcfg = NULL;
4403         if (fw != NULL)
4404                 *fw = NULL;
4405
4406         fw_info = find_fw_info(chip_id(sc));
4407         if (fw_info == NULL) {
4408                 device_printf(sc->dev,
4409                     "unable to look up firmware information for chip %d.\n",
4410                     chip_id(sc));
4411                 return (EINVAL);
4412         }
4413
4414         *dcfg = firmware_get(fw_info->kld_name);
4415         if (*dcfg != NULL) {
4416                 if (fw != NULL)
4417                         *fw = firmware_get(fw_info->fw_mod_name);
4418                 return (0);
4419         }
4420
4421         return (ENOENT);
4422 }
4423
4424 static void
4425 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4426     const struct firmware *fw)
4427 {
4428
4429         if (fw != NULL)
4430                 firmware_put(fw, FIRMWARE_UNLOAD);
4431         if (dcfg != NULL)
4432                 firmware_put(dcfg, FIRMWARE_UNLOAD);
4433 }
4434
4435 /*
4436  * Return values:
4437  * 0 means no firmware install attempted.
4438  * ERESTART means a firmware install was attempted and was successful.
4439  * +ve errno means a firmware install was attempted but failed.
4440  */
4441 static int
4442 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4443     const struct fw_h *drv_fw, const char *reason, int *already)
4444 {
4445         const struct firmware *cfg, *fw;
4446         const uint32_t c = be32toh(card_fw->fw_ver);
4447         uint32_t d, k;
4448         int rc, fw_install;
4449         struct fw_h bundled_fw;
4450         bool load_attempted;
4451
4452         cfg = fw = NULL;
4453         load_attempted = false;
4454         fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4455
4456         memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4457         if (t4_fw_install < 0) {
4458                 rc = load_fw_module(sc, &cfg, &fw);
4459                 if (rc != 0 || fw == NULL) {
4460                         device_printf(sc->dev,
4461                             "failed to load firmware module: %d. cfg %p, fw %p;"
4462                             " will use compiled-in firmware version for"
4463                             "hw.cxgbe.fw_install checks.\n",
4464                             rc, cfg, fw);
4465                 } else {
4466                         memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4467                 }
4468                 load_attempted = true;
4469         }
4470         d = be32toh(bundled_fw.fw_ver);
4471
4472         if (reason != NULL)
4473                 goto install;
4474
4475         if ((sc->flags & FW_OK) == 0) {
4476
4477                 if (c == 0xffffffff) {
4478                         reason = "missing";
4479                         goto install;
4480                 }
4481
4482                 rc = 0;
4483                 goto done;
4484         }
4485
4486         if (!fw_compatible(card_fw, &bundled_fw)) {
4487                 reason = "incompatible or unusable";
4488                 goto install;
4489         }
4490
4491         if (d > c) {
4492                 reason = "older than the version bundled with this driver";
4493                 goto install;
4494         }
4495
4496         if (fw_install == 2 && d != c) {
4497                 reason = "different than the version bundled with this driver";
4498                 goto install;
4499         }
4500
4501         /* No reason to do anything to the firmware already on the card. */
4502         rc = 0;
4503         goto done;
4504
4505 install:
4506         rc = 0;
4507         if ((*already)++)
4508                 goto done;
4509
4510         if (fw_install == 0) {
4511                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4512                     "but the driver is prohibited from installing a firmware "
4513                     "on the card.\n",
4514                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4515                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4516
4517                 goto done;
4518         }
4519
4520         /*
4521          * We'll attempt to install a firmware.  Load the module first (if it
4522          * hasn't been loaded already).
4523          */
4524         if (!load_attempted) {
4525                 rc = load_fw_module(sc, &cfg, &fw);
4526                 if (rc != 0 || fw == NULL) {
4527                         device_printf(sc->dev,
4528                             "failed to load firmware module: %d. cfg %p, fw %p\n",
4529                             rc, cfg, fw);
4530                         /* carry on */
4531                 }
4532         }
4533         if (fw == NULL) {
4534                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4535                     "but the driver cannot take corrective action because it "
4536                     "is unable to load the firmware module.\n",
4537                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4538                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4539                 rc = sc->flags & FW_OK ? 0 : ENOENT;
4540                 goto done;
4541         }
4542         k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4543         if (k != d) {
4544                 MPASS(t4_fw_install > 0);
4545                 device_printf(sc->dev,
4546                     "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4547                     "expecting (%u.%u.%u.%u) and will not be used.\n",
4548                     G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4549                     G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4550                     G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4551                     G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4552                 rc = sc->flags & FW_OK ? 0 : EINVAL;
4553                 goto done;
4554         }
4555
4556         device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4557             "installing firmware %u.%u.%u.%u on card.\n",
4558             G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4559             G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4560             G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4561             G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4562
4563         rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4564         if (rc != 0) {
4565                 device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4566         } else {
4567                 /* Installed successfully, update the cached header too. */
4568                 rc = ERESTART;
4569                 memcpy(card_fw, fw->data, sizeof(*card_fw));
4570         }
4571 done:
4572         unload_fw_module(sc, cfg, fw);
4573
4574         return (rc);
4575 }
4576
4577 /*
4578  * Establish contact with the firmware and attempt to become the master driver.
4579  *
4580  * A firmware will be installed to the card if needed (if the driver is allowed
4581  * to do so).
4582  */
4583 static int
4584 contact_firmware(struct adapter *sc)
4585 {
4586         int rc, already = 0;
4587         enum dev_state state;
4588         struct fw_info *fw_info;
4589         struct fw_hdr *card_fw;         /* fw on the card */
4590         const struct fw_h *drv_fw;
4591
4592         fw_info = find_fw_info(chip_id(sc));
4593         if (fw_info == NULL) {
4594                 device_printf(sc->dev,
4595                     "unable to look up firmware information for chip %d.\n",
4596                     chip_id(sc));
4597                 return (EINVAL);
4598         }
4599         drv_fw = &fw_info->fw_h;
4600
4601         /* Read the header of the firmware on the card */
4602         card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4603 restart:
4604         rc = -t4_get_fw_hdr(sc, card_fw);
4605         if (rc != 0) {
4606                 device_printf(sc->dev,
4607                     "unable to read firmware header from card's flash: %d\n",
4608                     rc);
4609                 goto done;
4610         }
4611
4612         rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4613             &already);
4614         if (rc == ERESTART)
4615                 goto restart;
4616         if (rc != 0)
4617                 goto done;
4618
4619         rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4620         if (rc < 0 || state == DEV_STATE_ERR) {
4621                 rc = -rc;
4622                 device_printf(sc->dev,
4623                     "failed to connect to the firmware: %d, %d.  "
4624                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4625 #if 0
4626                 if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4627                     "not responding properly to HELLO", &already) == ERESTART)
4628                         goto restart;
4629 #endif
4630                 goto done;
4631         }
4632         MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4633         sc->flags |= FW_OK;     /* The firmware responded to the FW_HELLO. */
4634
4635         if (rc == sc->pf) {
4636                 sc->flags |= MASTER_PF;
4637                 rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4638                     NULL, &already);
4639                 if (rc == ERESTART)
4640                         rc = 0;
4641                 else if (rc != 0)
4642                         goto done;
4643         } else if (state == DEV_STATE_UNINIT) {
4644                 /*
4645                  * We didn't get to be the master so we definitely won't be
4646                  * configuring the chip.  It's a bug if someone else hasn't
4647                  * configured it already.
4648                  */
4649                 device_printf(sc->dev, "couldn't be master(%d), "
4650                     "device not already initialized either(%d).  "
4651                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4652                 rc = EPROTO;
4653                 goto done;
4654         } else {
4655                 /*
4656                  * Some other PF is the master and has configured the chip.
4657                  * This is allowed but untested.
4658                  */
4659                 device_printf(sc->dev, "PF%d is master, device state %d.  "
4660                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4661                 snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4662                 sc->cfcsum = 0;
4663                 rc = 0;
4664         }
4665 done:
4666         if (rc != 0 && sc->flags & FW_OK) {
4667                 t4_fw_bye(sc, sc->mbox);
4668                 sc->flags &= ~FW_OK;
4669         }
4670         free(card_fw, M_CXGBE);
4671         return (rc);
4672 }
4673
4674 static int
4675 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4676     uint32_t mtype, uint32_t moff)
4677 {
4678         struct fw_info *fw_info;
4679         const struct firmware *dcfg, *rcfg = NULL;
4680         const uint32_t *cfdata;
4681         uint32_t cflen, addr;
4682         int rc;
4683
4684         load_fw_module(sc, &dcfg, NULL);
4685
4686         /* Card specific interpretation of "default". */
4687         if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4688                 if (pci_get_device(sc->dev) == 0x440a)
4689                         snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4690                 if (is_fpga(sc))
4691                         snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4692         }
4693
4694         if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4695                 if (dcfg == NULL) {
4696                         device_printf(sc->dev,
4697                             "KLD with default config is not available.\n");
4698                         rc = ENOENT;
4699                         goto done;
4700                 }
4701                 cfdata = dcfg->data;
4702                 cflen = dcfg->datasize & ~3;
4703         } else {
4704                 char s[32];
4705
4706                 fw_info = find_fw_info(chip_id(sc));
4707                 if (fw_info == NULL) {
4708                         device_printf(sc->dev,
4709                             "unable to look up firmware information for chip %d.\n",
4710                             chip_id(sc));
4711                         rc = EINVAL;
4712                         goto done;
4713                 }
4714                 snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4715
4716                 rcfg = firmware_get(s);
4717                 if (rcfg == NULL) {
4718                         device_printf(sc->dev,
4719                             "unable to load module \"%s\" for configuration "
4720                             "profile \"%s\".\n", s, cfg_file);
4721                         rc = ENOENT;
4722                         goto done;
4723                 }
4724                 cfdata = rcfg->data;
4725                 cflen = rcfg->datasize & ~3;
4726         }
4727
4728         if (cflen > FLASH_CFG_MAX_SIZE) {
4729                 device_printf(sc->dev,
4730                     "config file too long (%d, max allowed is %d).\n",
4731                     cflen, FLASH_CFG_MAX_SIZE);
4732                 rc = EINVAL;
4733                 goto done;
4734         }
4735
4736         rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4737         if (rc != 0) {
4738                 device_printf(sc->dev,
4739                     "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4740                     __func__, mtype, moff, cflen, rc);
4741                 rc = EINVAL;
4742                 goto done;
4743         }
4744         write_via_memwin(sc, 2, addr, cfdata, cflen);
4745 done:
4746         if (rcfg != NULL)
4747                 firmware_put(rcfg, FIRMWARE_UNLOAD);
4748         unload_fw_module(sc, dcfg, NULL);
4749         return (rc);
4750 }
4751
4752 struct caps_allowed {
4753         uint16_t nbmcaps;
4754         uint16_t linkcaps;
4755         uint16_t switchcaps;
4756         uint16_t niccaps;
4757         uint16_t toecaps;
4758         uint16_t rdmacaps;
4759         uint16_t cryptocaps;
4760         uint16_t iscsicaps;
4761         uint16_t fcoecaps;
4762 };
4763
4764 #define FW_PARAM_DEV(param) \
4765         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4766          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4767 #define FW_PARAM_PFVF(param) \
4768         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4769          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4770
4771 /*
4772  * Provide a configuration profile to the firmware and have it initialize the
4773  * chip accordingly.  This may involve uploading a configuration file to the
4774  * card.
4775  */
4776 static int
4777 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4778     const struct caps_allowed *caps_allowed)
4779 {
4780         int rc;
4781         struct fw_caps_config_cmd caps;
4782         uint32_t mtype, moff, finicsum, cfcsum, param, val;
4783
4784         rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4785         if (rc != 0) {
4786                 device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4787                 return (rc);
4788         }
4789
4790         bzero(&caps, sizeof(caps));
4791         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4792             F_FW_CMD_REQUEST | F_FW_CMD_READ);
4793         if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4794                 mtype = 0;
4795                 moff = 0;
4796                 caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4797         } else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4798                 mtype = FW_MEMTYPE_FLASH;
4799                 moff = t4_flash_cfg_addr(sc);
4800                 caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4801                     V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4802                     V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4803                     FW_LEN16(caps));
4804         } else {
4805                 /*
4806                  * Ask the firmware where it wants us to upload the config file.
4807                  */
4808                 param = FW_PARAM_DEV(CF);
4809                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4810                 if (rc != 0) {
4811                         /* No support for config file?  Shouldn't happen. */
4812                         device_printf(sc->dev,
4813                             "failed to query config file location: %d.\n", rc);
4814                         goto done;
4815                 }
4816                 mtype = G_FW_PARAMS_PARAM_Y(val);
4817                 moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4818                 caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4819                     V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4820                     V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4821                     FW_LEN16(caps));
4822
4823                 rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4824                 if (rc != 0) {
4825                         device_printf(sc->dev,
4826                             "failed to upload config file to card: %d.\n", rc);
4827                         goto done;
4828                 }
4829         }
4830         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4831         if (rc != 0) {
4832                 device_printf(sc->dev, "failed to pre-process config file: %d "
4833                     "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4834                 goto done;
4835         }
4836
4837         finicsum = be32toh(caps.finicsum);
4838         cfcsum = be32toh(caps.cfcsum);  /* actual */
4839         if (finicsum != cfcsum) {
4840                 device_printf(sc->dev,
4841                     "WARNING: config file checksum mismatch: %08x %08x\n",
4842                     finicsum, cfcsum);
4843         }
4844         sc->cfcsum = cfcsum;
4845         snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4846
4847         /*
4848          * Let the firmware know what features will (not) be used so it can tune
4849          * things accordingly.
4850          */
4851 #define LIMIT_CAPS(x) do { \
4852         caps.x##caps &= htobe16(caps_allowed->x##caps); \
4853 } while (0)
4854         LIMIT_CAPS(nbm);
4855         LIMIT_CAPS(link);
4856         LIMIT_CAPS(switch);
4857         LIMIT_CAPS(nic);
4858         LIMIT_CAPS(toe);
4859         LIMIT_CAPS(rdma);
4860         LIMIT_CAPS(crypto);
4861         LIMIT_CAPS(iscsi);
4862         LIMIT_CAPS(fcoe);
4863 #undef LIMIT_CAPS
4864         if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4865                 /*
4866                  * TOE and hashfilters are mutually exclusive.  It is a config
4867                  * file or firmware bug if both are reported as available.  Try
4868                  * to cope with the situation in non-debug builds by disabling
4869                  * TOE.
4870                  */
4871                 MPASS(caps.toecaps == 0);
4872
4873                 caps.toecaps = 0;
4874                 caps.rdmacaps = 0;
4875                 caps.iscsicaps = 0;
4876         }
4877
4878         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4879             F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4880         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4881         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4882         if (rc != 0) {
4883                 device_printf(sc->dev,
4884                     "failed to process config file: %d.\n", rc);
4885                 goto done;
4886         }
4887
4888         t4_tweak_chip_settings(sc);
4889         set_params__pre_init(sc);
4890
4891         /* get basic stuff going */
4892         rc = -t4_fw_initialize(sc, sc->mbox);
4893         if (rc != 0) {
4894                 device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4895                 goto done;
4896         }
4897 done:
4898         return (rc);
4899 }
4900
4901 /*
4902  * Partition chip resources for use between various PFs, VFs, etc.
4903  */
4904 static int
4905 partition_resources(struct adapter *sc)
4906 {
4907         char cfg_file[sizeof(t4_cfg_file)];
4908         struct caps_allowed caps_allowed;
4909         int rc;
4910         bool fallback;
4911
4912         /* Only the master driver gets to configure the chip resources. */
4913         MPASS(sc->flags & MASTER_PF);
4914
4915 #define COPY_CAPS(x) do { \
4916         caps_allowed.x##caps = t4_##x##caps_allowed; \
4917 } while (0)
4918         bzero(&caps_allowed, sizeof(caps_allowed));
4919         COPY_CAPS(nbm);
4920         COPY_CAPS(link);
4921         COPY_CAPS(switch);
4922         COPY_CAPS(nic);
4923         COPY_CAPS(toe);
4924         COPY_CAPS(rdma);
4925         COPY_CAPS(crypto);
4926         COPY_CAPS(iscsi);
4927         COPY_CAPS(fcoe);
4928         fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4929         snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4930 retry:
4931         rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4932         if (rc != 0 && fallback) {
4933                 device_printf(sc->dev,
4934                     "failed (%d) to configure card with \"%s\" profile, "
4935                     "will fall back to a basic configuration and retry.\n",
4936                     rc, cfg_file);
4937                 snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4938                 bzero(&caps_allowed, sizeof(caps_allowed));
4939                 COPY_CAPS(switch);
4940                 caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4941                 fallback = false;
4942                 goto retry;
4943         }
4944 #undef COPY_CAPS
4945         return (rc);
4946 }
4947
4948 /*
4949  * Retrieve parameters that are needed (or nice to have) very early.
4950  */
4951 static int
4952 get_params__pre_init(struct adapter *sc)
4953 {
4954         int rc;
4955         uint32_t param[2], val[2];
4956
4957         t4_get_version_info(sc);
4958
4959         snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4960             G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4961             G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
4962             G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
4963             G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
4964
4965         snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
4966             G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
4967             G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
4968             G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
4969             G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
4970
4971         snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
4972             G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4973             G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4974             G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4975             G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4976
4977         snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4978             G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4979             G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4980             G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4981             G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4982
4983         param[0] = FW_PARAM_DEV(PORTVEC);
4984         param[1] = FW_PARAM_DEV(CCLK);
4985         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4986         if (rc != 0) {
4987                 device_printf(sc->dev,
4988                     "failed to query parameters (pre_init): %d.\n", rc);
4989                 return (rc);
4990         }
4991
4992         sc->params.portvec = val[0];
4993         sc->params.nports = bitcount32(val[0]);
4994         sc->params.vpd.cclk = val[1];
4995
4996         /* Read device log parameters. */
4997         rc = -t4_init_devlog_params(sc, 1);
4998         if (rc == 0)
4999                 fixup_devlog_params(sc);
5000         else {
5001                 device_printf(sc->dev,
5002                     "failed to get devlog parameters: %d.\n", rc);
5003                 rc = 0; /* devlog isn't critical for device operation */
5004         }
5005
5006         return (rc);
5007 }
5008
5009 /*
5010  * Any params that need to be set before FW_INITIALIZE.
5011  */
5012 static int
5013 set_params__pre_init(struct adapter *sc)
5014 {
5015         int rc = 0;
5016         uint32_t param, val;
5017
5018         if (chip_id(sc) >= CHELSIO_T6) {
5019                 param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5020                 val = 1;
5021                 rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5022                 /* firmwares < 1.20.1.0 do not have this param. */
5023                 if (rc == FW_EINVAL &&
5024                     sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5025                         rc = 0;
5026                 }
5027                 if (rc != 0) {
5028                         device_printf(sc->dev,
5029                             "failed to enable high priority filters :%d.\n",
5030                             rc);
5031                 }
5032         }
5033
5034         /* Enable opaque VIIDs with firmwares that support it. */
5035         param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5036         val = 1;
5037         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5038         if (rc == 0 && val == 1)
5039                 sc->params.viid_smt_extn_support = true;
5040         else
5041                 sc->params.viid_smt_extn_support = false;
5042
5043         return (rc);
5044 }
5045
5046 /*
5047  * Retrieve various parameters that are of interest to the driver.  The device
5048  * has been initialized by the firmware at this point.
5049  */
5050 static int
5051 get_params__post_init(struct adapter *sc)
5052 {
5053         int rc;
5054         uint32_t param[7], val[7];
5055         struct fw_caps_config_cmd caps;
5056
5057         param[0] = FW_PARAM_PFVF(IQFLINT_START);
5058         param[1] = FW_PARAM_PFVF(EQ_START);
5059         param[2] = FW_PARAM_PFVF(FILTER_START);
5060         param[3] = FW_PARAM_PFVF(FILTER_END);
5061         param[4] = FW_PARAM_PFVF(L2T_START);
5062         param[5] = FW_PARAM_PFVF(L2T_END);
5063         param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5064             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5065             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5066         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5067         if (rc != 0) {
5068                 device_printf(sc->dev,
5069                     "failed to query parameters (post_init): %d.\n", rc);
5070                 return (rc);
5071         }
5072
5073         sc->sge.iq_start = val[0];
5074         sc->sge.eq_start = val[1];
5075         if ((int)val[3] > (int)val[2]) {
5076                 sc->tids.ftid_base = val[2];
5077                 sc->tids.ftid_end = val[3];
5078                 sc->tids.nftids = val[3] - val[2] + 1;
5079         }
5080         sc->vres.l2t.start = val[4];
5081         sc->vres.l2t.size = val[5] - val[4] + 1;
5082         KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5083             ("%s: L2 table size (%u) larger than expected (%u)",
5084             __func__, sc->vres.l2t.size, L2T_SIZE));
5085         sc->params.core_vdd = val[6];
5086
5087         param[0] = FW_PARAM_PFVF(IQFLINT_END);
5088         param[1] = FW_PARAM_PFVF(EQ_END);
5089         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5090         if (rc != 0) {
5091                 device_printf(sc->dev,
5092                     "failed to query parameters (post_init2): %d.\n", rc);
5093                 return (rc);
5094         }
5095         MPASS((int)val[0] >= sc->sge.iq_start);
5096         sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5097         MPASS((int)val[1] >= sc->sge.eq_start);
5098         sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5099
5100         if (chip_id(sc) >= CHELSIO_T6) {
5101
5102                 sc->tids.tid_base = t4_read_reg(sc,
5103                     A_LE_DB_ACTIVE_TABLE_START_INDEX);
5104
5105                 param[0] = FW_PARAM_PFVF(HPFILTER_START);
5106                 param[1] = FW_PARAM_PFVF(HPFILTER_END);
5107                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5108                 if (rc != 0) {
5109                         device_printf(sc->dev,
5110                            "failed to query hpfilter parameters: %d.\n", rc);
5111                         return (rc);
5112                 }
5113                 if ((int)val[1] > (int)val[0]) {
5114                         sc->tids.hpftid_base = val[0];
5115                         sc->tids.hpftid_end = val[1];
5116                         sc->tids.nhpftids = val[1] - val[0] + 1;
5117
5118                         /*
5119                          * These should go off if the layout changes and the
5120                          * driver needs to catch up.
5121                          */
5122                         MPASS(sc->tids.hpftid_base == 0);
5123                         MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5124                 }
5125
5126                 param[0] = FW_PARAM_PFVF(RAWF_START);
5127                 param[1] = FW_PARAM_PFVF(RAWF_END);
5128                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5129                 if (rc != 0) {
5130                         device_printf(sc->dev,
5131                            "failed to query rawf parameters: %d.\n", rc);
5132                         return (rc);
5133                 }
5134                 if ((int)val[1] > (int)val[0]) {
5135                         sc->rawf_base = val[0];
5136                         sc->nrawf = val[1] - val[0] + 1;
5137                 }
5138         }
5139
5140         /*
5141          * MPSBGMAP is queried separately because only recent firmwares support
5142          * it as a parameter and we don't want the compound query above to fail
5143          * on older firmwares.
5144          */
5145         param[0] = FW_PARAM_DEV(MPSBGMAP);
5146         val[0] = 0;
5147         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5148         if (rc == 0)
5149                 sc->params.mps_bg_map = val[0];
5150         else
5151                 sc->params.mps_bg_map = 0;
5152
5153         /*
5154          * Determine whether the firmware supports the filter2 work request.
5155          * This is queried separately for the same reason as MPSBGMAP above.
5156          */
5157         param[0] = FW_PARAM_DEV(FILTER2_WR);
5158         val[0] = 0;
5159         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5160         if (rc == 0)
5161                 sc->params.filter2_wr_support = val[0] != 0;
5162         else
5163                 sc->params.filter2_wr_support = 0;
5164
5165         /*
5166          * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5167          * This is queried separately for the same reason as other params above.
5168          */
5169         param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5170         val[0] = 0;
5171         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5172         if (rc == 0)
5173                 sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5174         else
5175                 sc->params.ulptx_memwrite_dsgl = false;
5176
5177         /* FW_RI_FR_NSMR_TPTE_WR support */
5178         param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5179         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5180         if (rc == 0)
5181                 sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5182         else
5183                 sc->params.fr_nsmr_tpte_wr_support = false;
5184
5185         /* Support for 512 SGL entries per FR MR. */
5186         param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5187         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5188         if (rc == 0)
5189                 sc->params.dev_512sgl_mr = val[0] != 0;
5190         else
5191                 sc->params.dev_512sgl_mr = false;
5192
5193         param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5194         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5195         if (rc == 0)
5196                 sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5197         else
5198                 sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5199
5200         param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5201         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5202         if (rc == 0) {
5203                 MPASS(val[0] > 0 && val[0] < 256);      /* nsched_cls is 8b */
5204                 sc->params.nsched_cls = val[0];
5205         } else
5206                 sc->params.nsched_cls = sc->chip_params->nsched_cls;
5207
5208         /* get capabilites */
5209         bzero(&caps, sizeof(caps));
5210         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5211             F_FW_CMD_REQUEST | F_FW_CMD_READ);
5212         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5213         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5214         if (rc != 0) {
5215                 device_printf(sc->dev,
5216                     "failed to get card capabilities: %d.\n", rc);
5217                 return (rc);
5218         }
5219
5220 #define READ_CAPS(x) do { \
5221         sc->x = htobe16(caps.x); \
5222 } while (0)
5223         READ_CAPS(nbmcaps);
5224         READ_CAPS(linkcaps);
5225         READ_CAPS(switchcaps);
5226         READ_CAPS(niccaps);
5227         READ_CAPS(toecaps);
5228         READ_CAPS(rdmacaps);
5229         READ_CAPS(cryptocaps);
5230         READ_CAPS(iscsicaps);
5231         READ_CAPS(fcoecaps);
5232
5233         if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5234                 MPASS(chip_id(sc) > CHELSIO_T4);
5235                 MPASS(sc->toecaps == 0);
5236                 sc->toecaps = 0;
5237
5238                 param[0] = FW_PARAM_DEV(NTID);
5239                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5240                 if (rc != 0) {
5241                         device_printf(sc->dev,
5242                             "failed to query HASHFILTER parameters: %d.\n", rc);
5243                         return (rc);
5244                 }
5245                 sc->tids.ntids = val[0];
5246                 if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5247                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5248                         sc->tids.ntids -= sc->tids.nhpftids;
5249                 }
5250                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5251                 sc->params.hash_filter = 1;
5252         }
5253         if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5254                 param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5255                 param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5256                 param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5257                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5258                 if (rc != 0) {
5259                         device_printf(sc->dev,
5260                             "failed to query NIC parameters: %d.\n", rc);
5261                         return (rc);
5262                 }
5263                 if ((int)val[1] > (int)val[0]) {
5264                         sc->tids.etid_base = val[0];
5265                         sc->tids.etid_end = val[1];
5266                         sc->tids.netids = val[1] - val[0] + 1;
5267                         sc->params.eo_wr_cred = val[2];
5268                         sc->params.ethoffload = 1;
5269                 }
5270         }
5271         if (sc->toecaps) {
5272                 /* query offload-related parameters */
5273                 param[0] = FW_PARAM_DEV(NTID);
5274                 param[1] = FW_PARAM_PFVF(SERVER_START);
5275                 param[2] = FW_PARAM_PFVF(SERVER_END);
5276                 param[3] = FW_PARAM_PFVF(TDDP_START);
5277                 param[4] = FW_PARAM_PFVF(TDDP_END);
5278                 param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5279                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5280                 if (rc != 0) {
5281                         device_printf(sc->dev,
5282                             "failed to query TOE parameters: %d.\n", rc);
5283                         return (rc);
5284                 }
5285                 sc->tids.ntids = val[0];
5286                 if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5287                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5288                         sc->tids.ntids -= sc->tids.nhpftids;
5289                 }
5290                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5291                 if ((int)val[2] > (int)val[1]) {
5292                         sc->tids.stid_base = val[1];
5293                         sc->tids.nstids = val[2] - val[1] + 1;
5294                 }
5295                 sc->vres.ddp.start = val[3];
5296                 sc->vres.ddp.size = val[4] - val[3] + 1;
5297                 sc->params.ofldq_wr_cred = val[5];
5298                 sc->params.offload = 1;
5299         } else {
5300                 /*
5301                  * The firmware attempts memfree TOE configuration for -SO cards
5302                  * and will report toecaps=0 if it runs out of resources (this
5303                  * depends on the config file).  It may not report 0 for other
5304                  * capabilities dependent on the TOE in this case.  Set them to
5305                  * 0 here so that the driver doesn't bother tracking resources
5306                  * that will never be used.
5307                  */
5308                 sc->iscsicaps = 0;
5309                 sc->rdmacaps = 0;
5310         }
5311         if (sc->rdmacaps) {
5312                 param[0] = FW_PARAM_PFVF(STAG_START);
5313                 param[1] = FW_PARAM_PFVF(STAG_END);
5314                 param[2] = FW_PARAM_PFVF(RQ_START);
5315                 param[3] = FW_PARAM_PFVF(RQ_END);
5316                 param[4] = FW_PARAM_PFVF(PBL_START);
5317                 param[5] = FW_PARAM_PFVF(PBL_END);
5318                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5319                 if (rc != 0) {
5320                         device_printf(sc->dev,
5321                             "failed to query RDMA parameters(1): %d.\n", rc);
5322                         return (rc);
5323                 }
5324                 sc->vres.stag.start = val[0];
5325                 sc->vres.stag.size = val[1] - val[0] + 1;
5326                 sc->vres.rq.start = val[2];
5327                 sc->vres.rq.size = val[3] - val[2] + 1;
5328                 sc->vres.pbl.start = val[4];
5329                 sc->vres.pbl.size = val[5] - val[4] + 1;
5330
5331                 param[0] = FW_PARAM_PFVF(SQRQ_START);
5332                 param[1] = FW_PARAM_PFVF(SQRQ_END);
5333                 param[2] = FW_PARAM_PFVF(CQ_START);
5334                 param[3] = FW_PARAM_PFVF(CQ_END);
5335                 param[4] = FW_PARAM_PFVF(OCQ_START);
5336                 param[5] = FW_PARAM_PFVF(OCQ_END);
5337                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5338                 if (rc != 0) {
5339                         device_printf(sc->dev,
5340                             "failed to query RDMA parameters(2): %d.\n", rc);
5341                         return (rc);
5342                 }
5343                 sc->vres.qp.start = val[0];
5344                 sc->vres.qp.size = val[1] - val[0] + 1;
5345                 sc->vres.cq.start = val[2];
5346                 sc->vres.cq.size = val[3] - val[2] + 1;
5347                 sc->vres.ocq.start = val[4];
5348                 sc->vres.ocq.size = val[5] - val[4] + 1;
5349
5350                 param[0] = FW_PARAM_PFVF(SRQ_START);
5351                 param[1] = FW_PARAM_PFVF(SRQ_END);
5352                 param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5353                 param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5354                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5355                 if (rc != 0) {
5356                         device_printf(sc->dev,
5357                             "failed to query RDMA parameters(3): %d.\n", rc);
5358                         return (rc);
5359                 }
5360                 sc->vres.srq.start = val[0];
5361                 sc->vres.srq.size = val[1] - val[0] + 1;
5362                 sc->params.max_ordird_qp = val[2];
5363                 sc->params.max_ird_adapter = val[3];
5364         }
5365         if (sc->iscsicaps) {
5366                 param[0] = FW_PARAM_PFVF(ISCSI_START);
5367                 param[1] = FW_PARAM_PFVF(ISCSI_END);
5368                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5369                 if (rc != 0) {
5370                         device_printf(sc->dev,
5371                             "failed to query iSCSI parameters: %d.\n", rc);
5372                         return (rc);
5373                 }
5374                 sc->vres.iscsi.start = val[0];
5375                 sc->vres.iscsi.size = val[1] - val[0] + 1;
5376         }
5377         if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5378                 param[0] = FW_PARAM_PFVF(TLS_START);
5379                 param[1] = FW_PARAM_PFVF(TLS_END);
5380                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5381                 if (rc != 0) {
5382                         device_printf(sc->dev,
5383                             "failed to query TLS parameters: %d.\n", rc);
5384                         return (rc);
5385                 }
5386                 sc->vres.key.start = val[0];
5387                 sc->vres.key.size = val[1] - val[0] + 1;
5388         }
5389
5390         /*
5391          * We've got the params we wanted to query directly from the firmware.
5392          * Grab some others via other means.
5393          */
5394         t4_init_sge_params(sc);
5395         t4_init_tp_params(sc);
5396         t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5397         t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5398
5399         rc = t4_verify_chip_settings(sc);
5400         if (rc != 0)
5401                 return (rc);
5402         t4_init_rx_buf_info(sc);
5403
5404         return (rc);
5405 }
5406
5407 #ifdef KERN_TLS
5408 static void
5409 ktls_tick(void *arg)
5410 {
5411         struct adapter *sc;
5412         uint32_t tstamp;
5413
5414         sc = arg;
5415         tstamp = tcp_ts_getticks();
5416         t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5417         t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5418         callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5419 }
5420
5421 static int
5422 t4_config_kern_tls(struct adapter *sc, bool enable)
5423 {
5424         int rc;
5425         uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5426             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5427             V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5428             V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5429
5430         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5431         if (rc != 0) {
5432                 CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5433                     enable ?  "enable" : "disable", rc);
5434                 return (rc);
5435         }
5436
5437         if (enable) {
5438                 sc->flags |= KERN_TLS_ON;
5439                 callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5440                     C_HARDCLOCK);
5441         } else {
5442                 sc->flags &= ~KERN_TLS_ON;
5443                 callout_stop(&sc->ktls_tick);
5444         }
5445
5446         return (rc);
5447 }
5448 #endif
5449
5450 static int
5451 set_params__post_init(struct adapter *sc)
5452 {
5453         uint32_t mask, param, val;
5454 #ifdef TCP_OFFLOAD
5455         int i, v, shift;
5456 #endif
5457
5458         /* ask for encapsulated CPLs */
5459         param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5460         val = 1;
5461         (void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5462
5463         /* Enable 32b port caps if the firmware supports it. */
5464         param = FW_PARAM_PFVF(PORT_CAPS32);
5465         val = 1;
5466         if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5467                 sc->params.port_caps32 = 1;
5468
5469         /* Let filter + maskhash steer to a part of the VI's RSS region. */
5470         val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5471         t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5472             V_MASKFILTER(val - 1));
5473
5474         mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5475             F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5476             F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5477             F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5478         val = 0;
5479         if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5480                 t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5481                     F_ATTACKFILTERENABLE);
5482                 val |= F_DROPERRORATTACK;
5483         }
5484         if (t4_drop_ip_fragments != 0) {
5485                 t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5486                     F_FRAGMENTDROP);
5487                 val |= F_DROPERRORFRAG;
5488         }
5489         if (t4_drop_pkts_with_l2_errors != 0)
5490                 val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5491         if (t4_drop_pkts_with_l3_errors != 0) {
5492                 val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5493                     F_DROPERRORCSUMIP;
5494         }
5495         if (t4_drop_pkts_with_l4_errors != 0) {
5496                 val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5497                     F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5498         }
5499         t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5500
5501 #ifdef TCP_OFFLOAD
5502         /*
5503          * Override the TOE timers with user provided tunables.  This is not the
5504          * recommended way to change the timers (the firmware config file is) so
5505          * these tunables are not documented.
5506          *
5507          * All the timer tunables are in microseconds.
5508          */
5509         if (t4_toe_keepalive_idle != 0) {
5510                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5511                 v &= M_KEEPALIVEIDLE;
5512                 t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5513                     V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5514         }
5515         if (t4_toe_keepalive_interval != 0) {
5516                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5517                 v &= M_KEEPALIVEINTVL;
5518                 t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5519                     V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5520         }
5521         if (t4_toe_keepalive_count != 0) {
5522                 v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5523                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5524                     V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5525                     V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5526                     V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5527         }
5528         if (t4_toe_rexmt_min != 0) {
5529                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5530                 v &= M_RXTMIN;
5531                 t4_set_reg_field(sc, A_TP_RXT_MIN,
5532                     V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5533         }
5534         if (t4_toe_rexmt_max != 0) {
5535                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5536                 v &= M_RXTMAX;
5537                 t4_set_reg_field(sc, A_TP_RXT_MAX,
5538                     V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5539         }
5540         if (t4_toe_rexmt_count != 0) {
5541                 v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5542                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5543                     V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5544                     V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5545                     V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5546         }
5547         for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5548                 if (t4_toe_rexmt_backoff[i] != -1) {
5549                         v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5550                         shift = (i & 3) << 3;
5551                         t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5552                             M_TIMERBACKOFFINDEX0 << shift, v << shift);
5553                 }
5554         }
5555 #endif
5556
5557 #ifdef KERN_TLS
5558         if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5559             sc->toecaps & FW_CAPS_CONFIG_TOE) {
5560                 /*
5561                  * Limit TOE connections to 2 reassembly "islands".  This is
5562                  * required for TOE TLS connections to downgrade to plain TOE
5563                  * connections if an unsupported TLS version or ciphersuite is
5564                  * used.
5565                  */
5566                 t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5567                     V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5568                 if (is_ktls(sc)) {
5569                         sc->tlst.inline_keys = t4_tls_inline_keys;
5570                         sc->tlst.combo_wrs = t4_tls_combo_wrs;
5571                         if (t4_kern_tls != 0)
5572                                 t4_config_kern_tls(sc, true);
5573                 }
5574         }
5575 #endif
5576         return (0);
5577 }
5578
5579 #undef FW_PARAM_PFVF
5580 #undef FW_PARAM_DEV
5581
5582 static void
5583 t4_set_desc(struct adapter *sc)
5584 {
5585         char buf[128];
5586         struct adapter_params *p = &sc->params;
5587
5588         snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5589
5590         device_set_desc_copy(sc->dev, buf);
5591 }
5592
5593 static inline void
5594 ifmedia_add4(struct ifmedia *ifm, int m)
5595 {
5596
5597         ifmedia_add(ifm, m, 0, NULL);
5598         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5599         ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5600         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5601 }
5602
5603 /*
5604  * This is the selected media, which is not quite the same as the active media.
5605  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5606  * and active are not the same, and "media: Ethernet selected" otherwise.
5607  */
5608 static void
5609 set_current_media(struct port_info *pi)
5610 {
5611         struct link_config *lc;
5612         struct ifmedia *ifm;
5613         int mword;
5614         u_int speed;
5615
5616         PORT_LOCK_ASSERT_OWNED(pi);
5617
5618         /* Leave current media alone if it's already set to IFM_NONE. */
5619         ifm = &pi->media;
5620         if (ifm->ifm_cur != NULL &&
5621             IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5622                 return;
5623
5624         lc = &pi->link_cfg;
5625         if (lc->requested_aneg != AUTONEG_DISABLE &&
5626             lc->pcaps & FW_PORT_CAP32_ANEG) {
5627                 ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5628                 return;
5629         }
5630         mword = IFM_ETHER | IFM_FDX;
5631         if (lc->requested_fc & PAUSE_TX)
5632                 mword |= IFM_ETH_TXPAUSE;
5633         if (lc->requested_fc & PAUSE_RX)
5634                 mword |= IFM_ETH_RXPAUSE;
5635         if (lc->requested_speed == 0)
5636                 speed = port_top_speed(pi) * 1000;      /* Gbps -> Mbps */
5637         else
5638                 speed = lc->requested_speed;
5639         mword |= port_mword(pi, speed_to_fwcap(speed));
5640         ifmedia_set(ifm, mword);
5641 }
5642
5643 /*
5644  * Returns true if the ifmedia list for the port cannot change.
5645  */
5646 static bool
5647 fixed_ifmedia(struct port_info *pi)
5648 {
5649
5650         return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5651             pi->port_type == FW_PORT_TYPE_BT_XFI ||
5652             pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5653             pi->port_type == FW_PORT_TYPE_KX4 ||
5654             pi->port_type == FW_PORT_TYPE_KX ||
5655             pi->port_type == FW_PORT_TYPE_KR ||
5656             pi->port_type == FW_PORT_TYPE_BP_AP ||
5657             pi->port_type == FW_PORT_TYPE_BP4_AP ||
5658             pi->port_type == FW_PORT_TYPE_BP40_BA ||
5659             pi->port_type == FW_PORT_TYPE_KR4_100G ||
5660             pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5661             pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5662 }
5663
5664 static void
5665 build_medialist(struct port_info *pi)
5666 {
5667         uint32_t ss, speed;
5668         int unknown, mword, bit;
5669         struct link_config *lc;
5670         struct ifmedia *ifm;
5671
5672         PORT_LOCK_ASSERT_OWNED(pi);
5673
5674         if (pi->flags & FIXED_IFMEDIA)
5675                 return;
5676
5677         /*
5678          * Rebuild the ifmedia list.
5679          */
5680         ifm = &pi->media;
5681         ifmedia_removeall(ifm);
5682         lc = &pi->link_cfg;
5683         ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5684         if (__predict_false(ss == 0)) { /* not supposed to happen. */
5685                 MPASS(ss != 0);
5686 no_media:
5687                 MPASS(LIST_EMPTY(&ifm->ifm_list));
5688                 ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5689                 ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5690                 return;
5691         }
5692
5693         unknown = 0;
5694         for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5695                 speed = 1 << bit;
5696                 MPASS(speed & M_FW_PORT_CAP32_SPEED);
5697                 if (ss & speed) {
5698                         mword = port_mword(pi, speed);
5699                         if (mword == IFM_NONE) {
5700                                 goto no_media;
5701                         } else if (mword == IFM_UNKNOWN)
5702                                 unknown++;
5703                         else
5704                                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5705                 }
5706         }
5707         if (unknown > 0) /* Add one unknown for all unknown media types. */
5708                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5709         if (lc->pcaps & FW_PORT_CAP32_ANEG)
5710                 ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5711
5712         set_current_media(pi);
5713 }
5714
5715 /*
5716  * Initialize the requested fields in the link config based on driver tunables.
5717  */
5718 static void
5719 init_link_config(struct port_info *pi)
5720 {
5721         struct link_config *lc = &pi->link_cfg;
5722
5723         PORT_LOCK_ASSERT_OWNED(pi);
5724         MPASS(lc->pcaps != 0);
5725
5726         lc->requested_caps = 0;
5727         lc->requested_speed = 0;
5728
5729         if (t4_autoneg == 0)
5730                 lc->requested_aneg = AUTONEG_DISABLE;
5731         else if (t4_autoneg == 1)
5732                 lc->requested_aneg = AUTONEG_ENABLE;
5733         else
5734                 lc->requested_aneg = AUTONEG_AUTO;
5735
5736         lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5737             PAUSE_AUTONEG);
5738
5739         if (t4_fec & FEC_AUTO)
5740                 lc->requested_fec = FEC_AUTO;
5741         else if (t4_fec == 0)
5742                 lc->requested_fec = FEC_NONE;
5743         else {
5744                 /* -1 is handled by the FEC_AUTO block above and not here. */
5745                 lc->requested_fec = t4_fec &
5746                     (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5747                 if (lc->requested_fec == 0)
5748                         lc->requested_fec = FEC_AUTO;
5749         }
5750         lc->force_fec = 0;
5751         if (lc->pcaps & FW_PORT_CAP32_FORCE_FEC) {
5752                 if (t4_force_fec < 0)
5753                         lc->force_fec = -1;
5754                 else if (t4_force_fec > 0)
5755                         lc->force_fec = 1;
5756         }
5757 }
5758
5759 /*
5760  * Makes sure that all requested settings comply with what's supported by the
5761  * port.  Returns the number of settings that were invalid and had to be fixed.
5762  */
5763 static int
5764 fixup_link_config(struct port_info *pi)
5765 {
5766         int n = 0;
5767         struct link_config *lc = &pi->link_cfg;
5768         uint32_t fwspeed;
5769
5770         PORT_LOCK_ASSERT_OWNED(pi);
5771
5772         /* Speed (when not autonegotiating) */
5773         if (lc->requested_speed != 0) {
5774                 fwspeed = speed_to_fwcap(lc->requested_speed);
5775                 if ((fwspeed & lc->pcaps) == 0) {
5776                         n++;
5777                         lc->requested_speed = 0;
5778                 }
5779         }
5780
5781         /* Link autonegotiation */
5782         MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5783             lc->requested_aneg == AUTONEG_DISABLE ||
5784             lc->requested_aneg == AUTONEG_AUTO);
5785         if (lc->requested_aneg == AUTONEG_ENABLE &&
5786             !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5787                 n++;
5788                 lc->requested_aneg = AUTONEG_AUTO;
5789         }
5790
5791         /* Flow control */
5792         MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5793         if (lc->requested_fc & PAUSE_TX &&
5794             !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5795                 n++;
5796                 lc->requested_fc &= ~PAUSE_TX;
5797         }
5798         if (lc->requested_fc & PAUSE_RX &&
5799             !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5800                 n++;
5801                 lc->requested_fc &= ~PAUSE_RX;
5802         }
5803         if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5804             !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5805                 n++;
5806                 lc->requested_fc |= PAUSE_AUTONEG;
5807         }
5808
5809         /* FEC */
5810         if ((lc->requested_fec & FEC_RS &&
5811             !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5812             (lc->requested_fec & FEC_BASER_RS &&
5813             !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5814                 n++;
5815                 lc->requested_fec = FEC_AUTO;
5816         }
5817
5818         return (n);
5819 }
5820
5821 /*
5822  * Apply the requested L1 settings, which are expected to be valid, to the
5823  * hardware.
5824  */
5825 static int
5826 apply_link_config(struct port_info *pi)
5827 {
5828         struct adapter *sc = pi->adapter;
5829         struct link_config *lc = &pi->link_cfg;
5830         int rc;
5831
5832 #ifdef INVARIANTS
5833         ASSERT_SYNCHRONIZED_OP(sc);
5834         PORT_LOCK_ASSERT_OWNED(pi);
5835
5836         if (lc->requested_aneg == AUTONEG_ENABLE)
5837                 MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5838         if (!(lc->requested_fc & PAUSE_AUTONEG))
5839                 MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5840         if (lc->requested_fc & PAUSE_TX)
5841                 MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5842         if (lc->requested_fc & PAUSE_RX)
5843                 MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5844         if (lc->requested_fec & FEC_RS)
5845                 MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5846         if (lc->requested_fec & FEC_BASER_RS)
5847                 MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5848 #endif
5849         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5850         if (rc != 0) {
5851                 /* Don't complain if the VF driver gets back an EPERM. */
5852                 if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5853                         device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5854         } else {
5855                 /*
5856                  * An L1_CFG will almost always result in a link-change event if
5857                  * the link is up, and the driver will refresh the actual
5858                  * fec/fc/etc. when the notification is processed.  If the link
5859                  * is down then the actual settings are meaningless.
5860                  *
5861                  * This takes care of the case where a change in the L1 settings
5862                  * may not result in a notification.
5863                  */
5864                 if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5865                         lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5866         }
5867         return (rc);
5868 }
5869
5870 #define FW_MAC_EXACT_CHUNK      7
5871 struct mcaddr_ctx {
5872         struct ifnet *ifp;
5873         const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5874         uint64_t hash;
5875         int i;
5876         int del;
5877         int rc;
5878 };
5879
5880 static u_int
5881 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5882 {
5883         struct mcaddr_ctx *ctx = arg;
5884         struct vi_info *vi = ctx->ifp->if_softc;
5885         struct port_info *pi = vi->pi;
5886         struct adapter *sc = pi->adapter;
5887
5888         if (ctx->rc < 0)
5889                 return (0);
5890
5891         ctx->mcaddr[ctx->i] = LLADDR(sdl);
5892         MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5893         ctx->i++;
5894
5895         if (ctx->i == FW_MAC_EXACT_CHUNK) {
5896                 ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5897                     ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5898                 if (ctx->rc < 0) {
5899                         int j;
5900
5901                         for (j = 0; j < ctx->i; j++) {
5902                                 if_printf(ctx->ifp,
5903                                     "failed to add mc address"
5904                                     " %02x:%02x:%02x:"
5905                                     "%02x:%02x:%02x rc=%d\n",
5906                                     ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5907                                     ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5908                                     ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5909                                     -ctx->rc);
5910                         }
5911                         return (0);
5912                 }
5913                 ctx->del = 0;
5914                 ctx->i = 0;
5915         }
5916
5917         return (1);
5918 }
5919
5920 /*
5921  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5922  * indicates which parameters should be programmed (the rest are left alone).
5923  */
5924 int
5925 update_mac_settings(struct ifnet *ifp, int flags)
5926 {
5927         int rc = 0;
5928         struct vi_info *vi = ifp->if_softc;
5929         struct port_info *pi = vi->pi;
5930         struct adapter *sc = pi->adapter;
5931         int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5932         uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5933
5934         ASSERT_SYNCHRONIZED_OP(sc);
5935         KASSERT(flags, ("%s: not told what to update.", __func__));
5936
5937         if (flags & XGMAC_MTU)
5938                 mtu = ifp->if_mtu;
5939
5940         if (flags & XGMAC_PROMISC)
5941                 promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5942
5943         if (flags & XGMAC_ALLMULTI)
5944                 allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5945
5946         if (flags & XGMAC_VLANEX)
5947                 vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5948
5949         if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5950                 rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5951                     allmulti, 1, vlanex, false);
5952                 if (rc) {
5953                         if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5954                             rc);
5955                         return (rc);
5956                 }
5957         }
5958
5959         if (flags & XGMAC_UCADDR) {
5960                 uint8_t ucaddr[ETHER_ADDR_LEN];
5961
5962                 bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5963                 rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5964                     ucaddr, true, &vi->smt_idx);
5965                 if (rc < 0) {
5966                         rc = -rc;
5967                         if_printf(ifp, "change_mac failed: %d\n", rc);
5968                         return (rc);
5969                 } else {
5970                         vi->xact_addr_filt = rc;
5971                         rc = 0;
5972                 }
5973         }
5974
5975         if (flags & XGMAC_MCADDRS) {
5976                 struct epoch_tracker et;
5977                 struct mcaddr_ctx ctx;
5978                 int j;
5979
5980                 ctx.ifp = ifp;
5981                 ctx.hash = 0;
5982                 ctx.i = 0;
5983                 ctx.del = 1;
5984                 ctx.rc = 0;
5985                 /*
5986                  * Unlike other drivers, we accumulate list of pointers into
5987                  * interface address lists and we need to keep it safe even
5988                  * after if_foreach_llmaddr() returns, thus we must enter the
5989                  * network epoch.
5990                  */
5991                 NET_EPOCH_ENTER(et);
5992                 if_foreach_llmaddr(ifp, add_maddr, &ctx);
5993                 if (ctx.rc < 0) {
5994                         NET_EPOCH_EXIT(et);
5995                         rc = -ctx.rc;
5996                         return (rc);
5997                 }
5998                 if (ctx.i > 0) {
5999                         rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6000                             ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6001                         NET_EPOCH_EXIT(et);
6002                         if (rc < 0) {
6003                                 rc = -rc;
6004                                 for (j = 0; j < ctx.i; j++) {
6005                                         if_printf(ifp,
6006                                             "failed to add mcast address"
6007                                             " %02x:%02x:%02x:"
6008                                             "%02x:%02x:%02x rc=%d\n",
6009                                             ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6010                                             ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6011                                             ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6012                                             rc);
6013                                 }
6014                                 return (rc);
6015                         }
6016                         ctx.del = 0;
6017                 } else
6018                         NET_EPOCH_EXIT(et);
6019
6020                 rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6021                 if (rc != 0)
6022                         if_printf(ifp, "failed to set mcast address hash: %d\n",
6023                             rc);
6024                 if (ctx.del == 0) {
6025                         /* We clobbered the VXLAN entry if there was one. */
6026                         pi->vxlan_tcam_entry = false;
6027                 }
6028         }
6029
6030         if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6031             pi->vxlan_tcam_entry == false) {
6032                 rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6033                     match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6034                     true);
6035                 if (rc < 0) {
6036                         rc = -rc;
6037                         if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6038                             rc);
6039                 } else {
6040                         MPASS(rc == sc->rawf_base + pi->port_id);
6041                         rc = 0;
6042                         pi->vxlan_tcam_entry = true;
6043                 }
6044         }
6045
6046         return (rc);
6047 }
6048
6049 /*
6050  * {begin|end}_synchronized_op must be called from the same thread.
6051  */
6052 int
6053 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6054     char *wmesg)
6055 {
6056         int rc, pri;
6057
6058 #ifdef WITNESS
6059         /* the caller thinks it's ok to sleep, but is it really? */
6060         if (flags & SLEEP_OK)
6061                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6062                     "begin_synchronized_op");
6063 #endif
6064
6065         if (INTR_OK)
6066                 pri = PCATCH;
6067         else
6068                 pri = 0;
6069
6070         ADAPTER_LOCK(sc);
6071         for (;;) {
6072
6073                 if (vi && IS_DOOMED(vi)) {
6074                         rc = ENXIO;
6075                         goto done;
6076                 }
6077
6078                 if (!IS_BUSY(sc)) {
6079                         rc = 0;
6080                         break;
6081                 }
6082
6083                 if (!(flags & SLEEP_OK)) {
6084                         rc = EBUSY;
6085                         goto done;
6086                 }
6087
6088                 if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6089                         rc = EINTR;
6090                         goto done;
6091                 }
6092         }
6093
6094         KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6095         SET_BUSY(sc);
6096 #ifdef INVARIANTS
6097         sc->last_op = wmesg;
6098         sc->last_op_thr = curthread;
6099         sc->last_op_flags = flags;
6100 #endif
6101
6102 done:
6103         if (!(flags & HOLD_LOCK) || rc)
6104                 ADAPTER_UNLOCK(sc);
6105
6106         return (rc);
6107 }
6108
6109 /*
6110  * Tell if_ioctl and if_init that the VI is going away.  This is
6111  * special variant of begin_synchronized_op and must be paired with a
6112  * call to end_synchronized_op.
6113  */
6114 void
6115 doom_vi(struct adapter *sc, struct vi_info *vi)
6116 {
6117
6118         ADAPTER_LOCK(sc);
6119         SET_DOOMED(vi);
6120         wakeup(&sc->flags);
6121         while (IS_BUSY(sc))
6122                 mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6123         SET_BUSY(sc);
6124 #ifdef INVARIANTS
6125         sc->last_op = "t4detach";
6126         sc->last_op_thr = curthread;
6127         sc->last_op_flags = 0;
6128 #endif
6129         ADAPTER_UNLOCK(sc);
6130 }
6131
6132 /*
6133  * {begin|end}_synchronized_op must be called from the same thread.
6134  */
6135 void
6136 end_synchronized_op(struct adapter *sc, int flags)
6137 {
6138
6139         if (flags & LOCK_HELD)
6140                 ADAPTER_LOCK_ASSERT_OWNED(sc);
6141         else
6142                 ADAPTER_LOCK(sc);
6143
6144         KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6145         CLR_BUSY(sc);
6146         wakeup(&sc->flags);
6147         ADAPTER_UNLOCK(sc);
6148 }
6149
6150 static int
6151 cxgbe_init_synchronized(struct vi_info *vi)
6152 {
6153         struct port_info *pi = vi->pi;
6154         struct adapter *sc = pi->adapter;
6155         struct ifnet *ifp = vi->ifp;
6156         int rc = 0, i;
6157         struct sge_txq *txq;
6158
6159         ASSERT_SYNCHRONIZED_OP(sc);
6160
6161         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
6162                 return (0);     /* already running */
6163
6164         if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6165                 return (rc);    /* error message displayed already */
6166
6167         if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6168                 return (rc); /* error message displayed already */
6169
6170         rc = update_mac_settings(ifp, XGMAC_ALL);
6171         if (rc)
6172                 goto done;      /* error message displayed already */
6173
6174         PORT_LOCK(pi);
6175         if (pi->up_vis == 0) {
6176                 t4_update_port_info(pi);
6177                 fixup_link_config(pi);
6178                 build_medialist(pi);
6179                 apply_link_config(pi);
6180         }
6181
6182         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6183         if (rc != 0) {
6184                 if_printf(ifp, "enable_vi failed: %d\n", rc);
6185                 PORT_UNLOCK(pi);
6186                 goto done;
6187         }
6188
6189         /*
6190          * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6191          * if this changes.
6192          */
6193
6194         for_each_txq(vi, i, txq) {
6195                 TXQ_LOCK(txq);
6196                 txq->eq.flags |= EQ_ENABLED;
6197                 TXQ_UNLOCK(txq);
6198         }
6199
6200         /*
6201          * The first iq of the first port to come up is used for tracing.
6202          */
6203         if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6204                 sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6205                 t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6206                     A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6207                     V_QUEUENUMBER(sc->traceq));
6208                 pi->flags |= HAS_TRACEQ;
6209         }
6210
6211         /* all ok */
6212         pi->up_vis++;
6213         ifp->if_drv_flags |= IFF_DRV_RUNNING;
6214         if (pi->link_cfg.link_ok)
6215                 t4_os_link_changed(pi);
6216         PORT_UNLOCK(pi);
6217
6218         mtx_lock(&vi->tick_mtx);
6219         if (ifp->if_get_counter == vi_get_counter)
6220                 callout_reset(&vi->tick, hz, vi_tick, vi);
6221         else
6222                 callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6223         mtx_unlock(&vi->tick_mtx);
6224 done:
6225         if (rc != 0)
6226                 cxgbe_uninit_synchronized(vi);
6227
6228         return (rc);
6229 }
6230
6231 /*
6232  * Idempotent.
6233  */
6234 static int
6235 cxgbe_uninit_synchronized(struct vi_info *vi)
6236 {
6237         struct port_info *pi = vi->pi;
6238         struct adapter *sc = pi->adapter;
6239         struct ifnet *ifp = vi->ifp;
6240         int rc, i;
6241         struct sge_txq *txq;
6242
6243         ASSERT_SYNCHRONIZED_OP(sc);
6244
6245         if (!(vi->flags & VI_INIT_DONE)) {
6246                 if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6247                         KASSERT(0, ("uninited VI is running"));
6248                         if_printf(ifp, "uninited VI with running ifnet.  "
6249                             "vi->flags 0x%016lx, if_flags 0x%08x, "
6250                             "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
6251                             ifp->if_drv_flags);
6252                 }
6253                 return (0);
6254         }
6255
6256         /*
6257          * Disable the VI so that all its data in either direction is discarded
6258          * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6259          * tick) intact as the TP can deliver negative advice or data that it's
6260          * holding in its RAM (for an offloaded connection) even after the VI is
6261          * disabled.
6262          */
6263         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6264         if (rc) {
6265                 if_printf(ifp, "disable_vi failed: %d\n", rc);
6266                 return (rc);
6267         }
6268
6269         for_each_txq(vi, i, txq) {
6270                 TXQ_LOCK(txq);
6271                 txq->eq.flags &= ~EQ_ENABLED;
6272                 TXQ_UNLOCK(txq);
6273         }
6274
6275         mtx_lock(&vi->tick_mtx);
6276         callout_stop(&vi->tick);
6277         mtx_unlock(&vi->tick_mtx);
6278
6279         PORT_LOCK(pi);
6280         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6281                 PORT_UNLOCK(pi);
6282                 return (0);
6283         }
6284         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
6285         pi->up_vis--;
6286         if (pi->up_vis > 0) {
6287                 PORT_UNLOCK(pi);
6288                 return (0);
6289         }
6290
6291         pi->link_cfg.link_ok = false;
6292         pi->link_cfg.speed = 0;
6293         pi->link_cfg.link_down_rc = 255;
6294         t4_os_link_changed(pi);
6295         PORT_UNLOCK(pi);
6296
6297         return (0);
6298 }
6299
6300 /*
6301  * It is ok for this function to fail midway and return right away.  t4_detach
6302  * will walk the entire sc->irq list and clean up whatever is valid.
6303  */
6304 int
6305 t4_setup_intr_handlers(struct adapter *sc)
6306 {
6307         int rc, rid, p, q, v;
6308         char s[8];
6309         struct irq *irq;
6310         struct port_info *pi;
6311         struct vi_info *vi;
6312         struct sge *sge = &sc->sge;
6313         struct sge_rxq *rxq;
6314 #ifdef TCP_OFFLOAD
6315         struct sge_ofld_rxq *ofld_rxq;
6316 #endif
6317 #ifdef DEV_NETMAP
6318         struct sge_nm_rxq *nm_rxq;
6319 #endif
6320 #ifdef RSS
6321         int nbuckets = rss_getnumbuckets();
6322 #endif
6323
6324         /*
6325          * Setup interrupts.
6326          */
6327         irq = &sc->irq[0];
6328         rid = sc->intr_type == INTR_INTX ? 0 : 1;
6329         if (forwarding_intr_to_fwq(sc))
6330                 return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6331
6332         /* Multiple interrupts. */
6333         if (sc->flags & IS_VF)
6334                 KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6335                     ("%s: too few intr.", __func__));
6336         else
6337                 KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6338                     ("%s: too few intr.", __func__));
6339
6340         /* The first one is always error intr on PFs */
6341         if (!(sc->flags & IS_VF)) {
6342                 rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6343                 if (rc != 0)
6344                         return (rc);
6345                 irq++;
6346                 rid++;
6347         }
6348
6349         /* The second one is always the firmware event queue (first on VFs) */
6350         rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6351         if (rc != 0)
6352                 return (rc);
6353         irq++;
6354         rid++;
6355
6356         for_each_port(sc, p) {
6357                 pi = sc->port[p];
6358                 for_each_vi(pi, v, vi) {
6359                         vi->first_intr = rid - 1;
6360
6361                         if (vi->nnmrxq > 0) {
6362                                 int n = max(vi->nrxq, vi->nnmrxq);
6363
6364                                 rxq = &sge->rxq[vi->first_rxq];
6365 #ifdef DEV_NETMAP
6366                                 nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6367 #endif
6368                                 for (q = 0; q < n; q++) {
6369                                         snprintf(s, sizeof(s), "%x%c%x", p,
6370                                             'a' + v, q);
6371                                         if (q < vi->nrxq)
6372                                                 irq->rxq = rxq++;
6373 #ifdef DEV_NETMAP
6374                                         if (q < vi->nnmrxq)
6375                                                 irq->nm_rxq = nm_rxq++;
6376
6377                                         if (irq->nm_rxq != NULL &&
6378                                             irq->rxq == NULL) {
6379                                                 /* Netmap rx only */
6380                                                 rc = t4_alloc_irq(sc, irq, rid,
6381                                                     t4_nm_intr, irq->nm_rxq, s);
6382                                         }
6383                                         if (irq->nm_rxq != NULL &&
6384                                             irq->rxq != NULL) {
6385                                                 /* NIC and Netmap rx */
6386                                                 rc = t4_alloc_irq(sc, irq, rid,
6387                                                     t4_vi_intr, irq, s);
6388                                         }
6389 #endif
6390                                         if (irq->rxq != NULL &&
6391                                             irq->nm_rxq == NULL) {
6392                                                 /* NIC rx only */
6393                                                 rc = t4_alloc_irq(sc, irq, rid,
6394                                                     t4_intr, irq->rxq, s);
6395                                         }
6396                                         if (rc != 0)
6397                                                 return (rc);
6398 #ifdef RSS
6399                                         if (q < vi->nrxq) {
6400                                                 bus_bind_intr(sc->dev, irq->res,
6401                                                     rss_getcpu(q % nbuckets));
6402                                         }
6403 #endif
6404                                         irq++;
6405                                         rid++;
6406                                         vi->nintr++;
6407                                 }
6408                         } else {
6409                                 for_each_rxq(vi, q, rxq) {
6410                                         snprintf(s, sizeof(s), "%x%c%x", p,
6411                                             'a' + v, q);
6412                                         rc = t4_alloc_irq(sc, irq, rid,
6413                                             t4_intr, rxq, s);
6414                                         if (rc != 0)
6415                                                 return (rc);
6416 #ifdef RSS
6417                                         bus_bind_intr(sc->dev, irq->res,
6418                                             rss_getcpu(q % nbuckets));
6419 #endif
6420                                         irq++;
6421                                         rid++;
6422                                         vi->nintr++;
6423                                 }
6424                         }
6425 #ifdef TCP_OFFLOAD
6426                         for_each_ofld_rxq(vi, q, ofld_rxq) {
6427                                 snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6428                                 rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6429                                     ofld_rxq, s);
6430                                 if (rc != 0)
6431                                         return (rc);
6432                                 irq++;
6433                                 rid++;
6434                                 vi->nintr++;
6435                         }
6436 #endif
6437                 }
6438         }
6439         MPASS(irq == &sc->irq[sc->intr_count]);
6440
6441         return (0);
6442 }
6443
6444 static void
6445 write_global_rss_key(struct adapter *sc)
6446 {
6447 #ifdef RSS
6448         int i;
6449         uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6450         uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6451
6452         CTASSERT(RSS_KEYSIZE == 40);
6453
6454         rss_getkey((void *)&raw_rss_key[0]);
6455         for (i = 0; i < nitems(rss_key); i++) {
6456                 rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6457         }
6458         t4_write_rss_key(sc, &rss_key[0], -1, 1);
6459 #endif
6460 }
6461
6462 /*
6463  * Idempotent.
6464  */
6465 static int
6466 adapter_full_init(struct adapter *sc)
6467 {
6468         int rc, i;
6469
6470         ASSERT_SYNCHRONIZED_OP(sc);
6471
6472         if (!(sc->flags & ADAP_SYSCTL_CTX)) {
6473                 sysctl_ctx_init(&sc->ctx);
6474                 sc->flags |= ADAP_SYSCTL_CTX;
6475         }
6476
6477         /*
6478          * queues that belong to the adapter (not any particular port).
6479          */
6480         rc = t4_setup_adapter_queues(sc);
6481         if (rc != 0)
6482                 return (rc);
6483
6484         for (i = 0; i < nitems(sc->tq); i++) {
6485                 if (sc->tq[i] != NULL)
6486                         continue;
6487                 sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6488                     taskqueue_thread_enqueue, &sc->tq[i]);
6489                 if (sc->tq[i] == NULL) {
6490                         CH_ERR(sc, "failed to allocate task queue %d\n", i);
6491                         return (ENOMEM);
6492                 }
6493                 taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6494                     device_get_nameunit(sc->dev), i);
6495         }
6496
6497         if (!(sc->flags & IS_VF)) {
6498                 write_global_rss_key(sc);
6499                 t4_intr_enable(sc);
6500         }
6501         return (0);
6502 }
6503
6504 int
6505 adapter_init(struct adapter *sc)
6506 {
6507         int rc;
6508
6509         ASSERT_SYNCHRONIZED_OP(sc);
6510         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6511         KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6512             ("%s: FULL_INIT_DONE already", __func__));
6513
6514         rc = adapter_full_init(sc);
6515         if (rc != 0)
6516                 adapter_full_uninit(sc);
6517         else
6518                 sc->flags |= FULL_INIT_DONE;
6519
6520         return (rc);
6521 }
6522
6523 /*
6524  * Idempotent.
6525  */
6526 static void
6527 adapter_full_uninit(struct adapter *sc)
6528 {
6529         int i;
6530
6531         /* Do this before freeing the adapter queues. */
6532         if (sc->flags & ADAP_SYSCTL_CTX) {
6533                 sysctl_ctx_free(&sc->ctx);
6534                 sc->flags &= ~ADAP_SYSCTL_CTX;
6535         }
6536
6537         t4_teardown_adapter_queues(sc);
6538
6539         for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6540                 taskqueue_free(sc->tq[i]);
6541                 sc->tq[i] = NULL;
6542         }
6543
6544         sc->flags &= ~FULL_INIT_DONE;
6545 }
6546
6547 #ifdef RSS
6548 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6549     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6550     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6551     RSS_HASHTYPE_RSS_UDP_IPV6)
6552
6553 /* Translates kernel hash types to hardware. */
6554 static int
6555 hashconfig_to_hashen(int hashconfig)
6556 {
6557         int hashen = 0;
6558
6559         if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6560                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6561         if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6562                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6563         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6564                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6565                     F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6566         }
6567         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6568                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6569                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6570         }
6571         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6572                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6573         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6574                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6575
6576         return (hashen);
6577 }
6578
6579 /* Translates hardware hash types to kernel. */
6580 static int
6581 hashen_to_hashconfig(int hashen)
6582 {
6583         int hashconfig = 0;
6584
6585         if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6586                 /*
6587                  * If UDP hashing was enabled it must have been enabled for
6588                  * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6589                  * enabling any 4-tuple hash is nonsense configuration.
6590                  */
6591                 MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6592                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6593
6594                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6595                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6596                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6597                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6598         }
6599         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6600                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6601         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6602                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6603         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6604                 hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6605         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6606                 hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6607
6608         return (hashconfig);
6609 }
6610 #endif
6611
6612 /*
6613  * Idempotent.
6614  */
6615 static int
6616 vi_full_init(struct vi_info *vi)
6617 {
6618         struct adapter *sc = vi->adapter;
6619         struct sge_rxq *rxq;
6620         int rc, i, j;
6621 #ifdef RSS
6622         int nbuckets = rss_getnumbuckets();
6623         int hashconfig = rss_gethashconfig();
6624         int extra;
6625 #endif
6626
6627         ASSERT_SYNCHRONIZED_OP(sc);
6628
6629         if (!(vi->flags & VI_SYSCTL_CTX)) {
6630                 sysctl_ctx_init(&vi->ctx);
6631                 vi->flags |= VI_SYSCTL_CTX;
6632         }
6633
6634         /*
6635          * Allocate tx/rx/fl queues for this VI.
6636          */
6637         rc = t4_setup_vi_queues(vi);
6638         if (rc != 0)
6639                 return (rc);
6640
6641         /*
6642          * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6643          */
6644         if (vi->nrxq > vi->rss_size) {
6645                 CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6646                     "some queues will never receive traffic.\n", vi->nrxq,
6647                     vi->rss_size);
6648         } else if (vi->rss_size % vi->nrxq) {
6649                 CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6650                     "expect uneven traffic distribution.\n", vi->nrxq,
6651                     vi->rss_size);
6652         }
6653 #ifdef RSS
6654         if (vi->nrxq != nbuckets) {
6655                 CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6656                     "performance will be impacted.\n", vi->nrxq, nbuckets);
6657         }
6658 #endif
6659         if (vi->rss == NULL)
6660                 vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6661                     M_ZERO | M_WAITOK);
6662         for (i = 0; i < vi->rss_size;) {
6663 #ifdef RSS
6664                 j = rss_get_indirection_to_bucket(i);
6665                 j %= vi->nrxq;
6666                 rxq = &sc->sge.rxq[vi->first_rxq + j];
6667                 vi->rss[i++] = rxq->iq.abs_id;
6668 #else
6669                 for_each_rxq(vi, j, rxq) {
6670                         vi->rss[i++] = rxq->iq.abs_id;
6671                         if (i == vi->rss_size)
6672                                 break;
6673                 }
6674 #endif
6675         }
6676
6677         rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6678             vi->rss, vi->rss_size);
6679         if (rc != 0) {
6680                 CH_ERR(vi, "rss_config failed: %d\n", rc);
6681                 return (rc);
6682         }
6683
6684 #ifdef RSS
6685         vi->hashen = hashconfig_to_hashen(hashconfig);
6686
6687         /*
6688          * We may have had to enable some hashes even though the global config
6689          * wants them disabled.  This is a potential problem that must be
6690          * reported to the user.
6691          */
6692         extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6693
6694         /*
6695          * If we consider only the supported hash types, then the enabled hashes
6696          * are a superset of the requested hashes.  In other words, there cannot
6697          * be any supported hash that was requested but not enabled, but there
6698          * can be hashes that were not requested but had to be enabled.
6699          */
6700         extra &= SUPPORTED_RSS_HASHTYPES;
6701         MPASS((extra & hashconfig) == 0);
6702
6703         if (extra) {
6704                 CH_ALERT(vi,
6705                     "global RSS config (0x%x) cannot be accommodated.\n",
6706                     hashconfig);
6707         }
6708         if (extra & RSS_HASHTYPE_RSS_IPV4)
6709                 CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6710         if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6711                 CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6712         if (extra & RSS_HASHTYPE_RSS_IPV6)
6713                 CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6714         if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6715                 CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6716         if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6717                 CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6718         if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6719                 CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6720 #else
6721         vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6722             F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6723             F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6724             F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6725 #endif
6726         rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6727             0, 0);
6728         if (rc != 0) {
6729                 CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6730                 return (rc);
6731         }
6732
6733         return (0);
6734 }
6735
6736 int
6737 vi_init(struct vi_info *vi)
6738 {
6739         int rc;
6740
6741         ASSERT_SYNCHRONIZED_OP(vi->adapter);
6742         KASSERT((vi->flags & VI_INIT_DONE) == 0,
6743             ("%s: VI_INIT_DONE already", __func__));
6744
6745         rc = vi_full_init(vi);
6746         if (rc != 0)
6747                 vi_full_uninit(vi);
6748         else
6749                 vi->flags |= VI_INIT_DONE;
6750
6751         return (rc);
6752 }
6753
6754 /*
6755  * Idempotent.
6756  */
6757 static void
6758 vi_full_uninit(struct vi_info *vi)
6759 {
6760
6761         if (vi->flags & VI_INIT_DONE) {
6762                 quiesce_vi(vi);
6763                 free(vi->rss, M_CXGBE);
6764                 free(vi->nm_rss, M_CXGBE);
6765         }
6766
6767         /* Do this before freeing the VI queues. */
6768         if (vi->flags & VI_SYSCTL_CTX) {
6769                 sysctl_ctx_free(&vi->ctx);
6770                 vi->flags &= ~VI_SYSCTL_CTX;
6771         }
6772
6773         t4_teardown_vi_queues(vi);
6774         vi->flags &= ~VI_INIT_DONE;
6775 }
6776
6777 static void
6778 quiesce_txq(struct sge_txq *txq)
6779 {
6780         struct sge_eq *eq = &txq->eq;
6781         struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6782
6783         MPASS(eq->flags & EQ_SW_ALLOCATED);
6784         MPASS(!(eq->flags & EQ_ENABLED));
6785
6786         /* Wait for the mp_ring to empty. */
6787         while (!mp_ring_is_idle(txq->r)) {
6788                 mp_ring_check_drainage(txq->r, 4096);
6789                 pause("rquiesce", 1);
6790         }
6791         MPASS(txq->txp.npkt == 0);
6792
6793         if (eq->flags & EQ_HW_ALLOCATED) {
6794                 /*
6795                  * Hardware is alive and working normally.  Wait for it to
6796                  * finish and then wait for the driver to catch up and reclaim
6797                  * all descriptors.
6798                  */
6799                 while (spg->cidx != htobe16(eq->pidx))
6800                         pause("equiesce", 1);
6801                 while (eq->cidx != eq->pidx)
6802                         pause("dquiesce", 1);
6803         } else {
6804                 /*
6805                  * Hardware is unavailable.  Discard all pending tx and reclaim
6806                  * descriptors directly.
6807                  */
6808                 TXQ_LOCK(txq);
6809                 while (eq->cidx != eq->pidx) {
6810                         struct mbuf *m, *nextpkt;
6811                         struct tx_sdesc *txsd;
6812
6813                         txsd = &txq->sdesc[eq->cidx];
6814                         for (m = txsd->m; m != NULL; m = nextpkt) {
6815                                 nextpkt = m->m_nextpkt;
6816                                 m->m_nextpkt = NULL;
6817                                 m_freem(m);
6818                         }
6819                         IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6820                 }
6821                 spg->pidx = spg->cidx = htobe16(eq->cidx);
6822                 TXQ_UNLOCK(txq);
6823         }
6824 }
6825
6826 static void
6827 quiesce_wrq(struct sge_wrq *wrq)
6828 {
6829
6830         /* XXXTX */
6831 }
6832
6833 static void
6834 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6835 {
6836         /* Synchronize with the interrupt handler */
6837         while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6838                 pause("iqfree", 1);
6839
6840         if (fl != NULL) {
6841                 MPASS(iq->flags & IQ_HAS_FL);
6842
6843                 mtx_lock(&sc->sfl_lock);
6844                 FL_LOCK(fl);
6845                 fl->flags |= FL_DOOMED;
6846                 FL_UNLOCK(fl);
6847                 callout_stop(&sc->sfl_callout);
6848                 mtx_unlock(&sc->sfl_lock);
6849
6850                 KASSERT((fl->flags & FL_STARVING) == 0,
6851                     ("%s: still starving", __func__));
6852
6853                 /* Release all buffers if hardware is no longer available. */
6854                 if (!(iq->flags & IQ_HW_ALLOCATED))
6855                         free_fl_buffers(sc, fl);
6856         }
6857 }
6858
6859 /*
6860  * Wait for all activity on all the queues of the VI to complete.  It is assumed
6861  * that no new work is being enqueued by the hardware or the driver.  That part
6862  * should be arranged before calling this function.
6863  */
6864 static void
6865 quiesce_vi(struct vi_info *vi)
6866 {
6867         int i;
6868         struct adapter *sc = vi->adapter;
6869         struct sge_rxq *rxq;
6870         struct sge_txq *txq;
6871 #ifdef TCP_OFFLOAD
6872         struct sge_ofld_rxq *ofld_rxq;
6873 #endif
6874 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6875         struct sge_ofld_txq *ofld_txq;
6876 #endif
6877
6878         if (!(vi->flags & VI_INIT_DONE))
6879                 return;
6880
6881         for_each_txq(vi, i, txq) {
6882                 quiesce_txq(txq);
6883         }
6884
6885 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6886         for_each_ofld_txq(vi, i, ofld_txq) {
6887                 quiesce_wrq(&ofld_txq->wrq);
6888         }
6889 #endif
6890
6891         for_each_rxq(vi, i, rxq) {
6892                 quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
6893         }
6894
6895 #ifdef TCP_OFFLOAD
6896         for_each_ofld_rxq(vi, i, ofld_rxq) {
6897                 quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
6898         }
6899 #endif
6900 }
6901
6902 static int
6903 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6904     driver_intr_t *handler, void *arg, char *name)
6905 {
6906         int rc;
6907
6908         irq->rid = rid;
6909         irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6910             RF_SHAREABLE | RF_ACTIVE);
6911         if (irq->res == NULL) {
6912                 device_printf(sc->dev,
6913                     "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6914                 return (ENOMEM);
6915         }
6916
6917         rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6918             NULL, handler, arg, &irq->tag);
6919         if (rc != 0) {
6920                 device_printf(sc->dev,
6921                     "failed to setup interrupt for rid %d, name %s: %d\n",
6922                     rid, name, rc);
6923         } else if (name)
6924                 bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6925
6926         return (rc);
6927 }
6928
6929 static int
6930 t4_free_irq(struct adapter *sc, struct irq *irq)
6931 {
6932         if (irq->tag)
6933                 bus_teardown_intr(sc->dev, irq->res, irq->tag);
6934         if (irq->res)
6935                 bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6936
6937         bzero(irq, sizeof(*irq));
6938
6939         return (0);
6940 }
6941
6942 static void
6943 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6944 {
6945
6946         regs->version = chip_id(sc) | chip_rev(sc) << 10;
6947         t4_get_regs(sc, buf, regs->len);
6948 }
6949
6950 #define A_PL_INDIR_CMD  0x1f8
6951
6952 #define S_PL_AUTOINC    31
6953 #define M_PL_AUTOINC    0x1U
6954 #define V_PL_AUTOINC(x) ((x) << S_PL_AUTOINC)
6955 #define G_PL_AUTOINC(x) (((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6956
6957 #define S_PL_VFID       20
6958 #define M_PL_VFID       0xffU
6959 #define V_PL_VFID(x)    ((x) << S_PL_VFID)
6960 #define G_PL_VFID(x)    (((x) >> S_PL_VFID) & M_PL_VFID)
6961
6962 #define S_PL_ADDR       0
6963 #define M_PL_ADDR       0xfffffU
6964 #define V_PL_ADDR(x)    ((x) << S_PL_ADDR)
6965 #define G_PL_ADDR(x)    (((x) >> S_PL_ADDR) & M_PL_ADDR)
6966
6967 #define A_PL_INDIR_DATA 0x1fc
6968
6969 static uint64_t
6970 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6971 {
6972         u32 stats[2];
6973
6974         if (sc->flags & IS_VF) {
6975                 stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6976                 stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6977         } else {
6978                 mtx_assert(&sc->reg_lock, MA_OWNED);
6979                 t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6980                     V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6981                 stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6982                 stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6983         }
6984         return (((uint64_t)stats[1]) << 32 | stats[0]);
6985 }
6986
6987 static void
6988 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6989 {
6990
6991 #define GET_STAT(name) \
6992         read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6993
6994         if (!(sc->flags & IS_VF))
6995                 mtx_lock(&sc->reg_lock);
6996         stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
6997         stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
6998         stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
6999         stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7000         stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7001         stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7002         stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7003         stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7004         stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7005         stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7006         stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7007         stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7008         stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7009         stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7010         stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7011         stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7012         if (!(sc->flags & IS_VF))
7013                 mtx_unlock(&sc->reg_lock);
7014
7015 #undef GET_STAT
7016 }
7017
7018 static void
7019 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7020 {
7021         int reg;
7022
7023         t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7024             V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7025         for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7026              reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7027                 t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7028 }
7029
7030 static void
7031 vi_refresh_stats(struct vi_info *vi)
7032 {
7033         struct timeval tv;
7034         const struct timeval interval = {0, 250000};    /* 250ms */
7035
7036         mtx_assert(&vi->tick_mtx, MA_OWNED);
7037
7038         if (!(vi->flags & VI_INIT_DONE) || vi->flags & VI_SKIP_STATS)
7039                 return;
7040
7041         getmicrotime(&tv);
7042         timevalsub(&tv, &interval);
7043         if (timevalcmp(&tv, &vi->last_refreshed, <))
7044                 return;
7045
7046         t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7047         getmicrotime(&vi->last_refreshed);
7048 }
7049
7050 static void
7051 cxgbe_refresh_stats(struct vi_info *vi)
7052 {
7053         u_int i, v, tnl_cong_drops, chan_map;
7054         struct timeval tv;
7055         const struct timeval interval = {0, 250000};    /* 250ms */
7056         struct port_info *pi;
7057         struct adapter *sc;
7058
7059         mtx_assert(&vi->tick_mtx, MA_OWNED);
7060
7061         if (vi->flags & VI_SKIP_STATS)
7062                 return;
7063
7064         getmicrotime(&tv);
7065         timevalsub(&tv, &interval);
7066         if (timevalcmp(&tv, &vi->last_refreshed, <))
7067                 return;
7068
7069         pi = vi->pi;
7070         sc = vi->adapter;
7071         tnl_cong_drops = 0;
7072         t4_get_port_stats(sc, pi->port_id, &pi->stats);
7073         chan_map = pi->rx_e_chan_map;
7074         while (chan_map) {
7075                 i = ffs(chan_map) - 1;
7076                 mtx_lock(&sc->reg_lock);
7077                 t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7078                     A_TP_MIB_TNL_CNG_DROP_0 + i);
7079                 mtx_unlock(&sc->reg_lock);
7080                 tnl_cong_drops += v;
7081                 chan_map &= ~(1 << i);
7082         }
7083         pi->tnl_cong_drops = tnl_cong_drops;
7084         getmicrotime(&vi->last_refreshed);
7085 }
7086
7087 static void
7088 cxgbe_tick(void *arg)
7089 {
7090         struct vi_info *vi = arg;
7091
7092         MPASS(IS_MAIN_VI(vi));
7093         mtx_assert(&vi->tick_mtx, MA_OWNED);
7094
7095         cxgbe_refresh_stats(vi);
7096         callout_schedule(&vi->tick, hz);
7097 }
7098
7099 static void
7100 vi_tick(void *arg)
7101 {
7102         struct vi_info *vi = arg;
7103
7104         mtx_assert(&vi->tick_mtx, MA_OWNED);
7105
7106         vi_refresh_stats(vi);
7107         callout_schedule(&vi->tick, hz);
7108 }
7109
7110 /*
7111  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7112  */
7113 static char *caps_decoder[] = {
7114         "\20\001IPMI\002NCSI",                          /* 0: NBM */
7115         "\20\001PPP\002QFC\003DCBX",                    /* 1: link */
7116         "\20\001INGRESS\002EGRESS",                     /* 2: switch */
7117         "\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"      /* 3: NIC */
7118             "\006HASHFILTER\007ETHOFLD",
7119         "\20\001TOE",                                   /* 4: TOE */
7120         "\20\001RDDP\002RDMAC",                         /* 5: RDMA */
7121         "\20\001INITIATOR_PDU\002TARGET_PDU"            /* 6: iSCSI */
7122             "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7123             "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7124             "\007T10DIF"
7125             "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7126         "\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"   /* 7: Crypto */
7127             "\004TLS_HW",
7128         "\20\001INITIATOR\002TARGET\003CTRL_OFLD"       /* 8: FCoE */
7129                     "\004PO_INITIATOR\005PO_TARGET",
7130 };
7131
7132 void
7133 t4_sysctls(struct adapter *sc)
7134 {
7135         struct sysctl_ctx_list *ctx;
7136         struct sysctl_oid *oid;
7137         struct sysctl_oid_list *children, *c0;
7138         static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7139
7140         ctx = device_get_sysctl_ctx(sc->dev);
7141
7142         /*
7143          * dev.t4nex.X.
7144          */
7145         oid = device_get_sysctl_tree(sc->dev);
7146         c0 = children = SYSCTL_CHILDREN(oid);
7147
7148         sc->sc_do_rxcopy = 1;
7149         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7150             &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7151
7152         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7153             sc->params.nports, "# of ports");
7154
7155         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7156             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7157             (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7158             "available doorbells");
7159
7160         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7161             sc->params.vpd.cclk, "core clock frequency (in KHz)");
7162
7163         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7164             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7165             sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7166             sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7167
7168         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7169             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7170             sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7171             sysctl_int_array, "A", "interrupt holdoff packet counter values");
7172
7173         t4_sge_sysctls(sc, ctx, children);
7174
7175         sc->lro_timeout = 100;
7176         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7177             &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7178
7179         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7180             &sc->debug_flags, 0, "flags to enable runtime debugging");
7181
7182         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7183             CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7184
7185         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7186             CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7187
7188         if (sc->flags & IS_VF)
7189                 return;
7190
7191         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7192             NULL, chip_rev(sc), "chip hardware revision");
7193
7194         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7195             CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7196
7197         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7198             CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7199
7200         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7201             CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7202
7203         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7204             CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7205
7206         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7207             CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7208
7209         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7210             sc->er_version, 0, "expansion ROM version");
7211
7212         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7213             sc->bs_version, 0, "bootstrap firmware version");
7214
7215         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7216             NULL, sc->params.scfg_vers, "serial config version");
7217
7218         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7219             NULL, sc->params.vpd_vers, "VPD version");
7220
7221         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7222             CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7223
7224         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7225             sc->cfcsum, "config file checksum");
7226
7227 #define SYSCTL_CAP(name, n, text) \
7228         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7229             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7230             (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7231             "available " text " capabilities")
7232
7233         SYSCTL_CAP(nbmcaps, 0, "NBM");
7234         SYSCTL_CAP(linkcaps, 1, "link");
7235         SYSCTL_CAP(switchcaps, 2, "switch");
7236         SYSCTL_CAP(niccaps, 3, "NIC");
7237         SYSCTL_CAP(toecaps, 4, "TCP offload");
7238         SYSCTL_CAP(rdmacaps, 5, "RDMA");
7239         SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7240         SYSCTL_CAP(cryptocaps, 7, "crypto");
7241         SYSCTL_CAP(fcoecaps, 8, "FCoE");
7242 #undef SYSCTL_CAP
7243
7244         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7245             NULL, sc->tids.nftids, "number of filters");
7246
7247         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7248             CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7249             sysctl_temperature, "I", "chip temperature (in Celsius)");
7250         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7251             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7252             sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7253
7254         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7255             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7256             sysctl_loadavg, "A",
7257             "microprocessor load averages (debug firmwares only)");
7258
7259         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7260             CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7261             "I", "core Vdd (in mV)");
7262
7263         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7264             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7265             sysctl_cpus, "A", "local CPUs");
7266
7267         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7268             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7269             sysctl_cpus, "A", "preferred CPUs for interrupts");
7270
7271         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7272             &sc->swintr, 0, "software triggered interrupts");
7273
7274         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7275             CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7276             "1 = reset adapter, 0 = zero reset counter");
7277
7278         /*
7279          * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7280          */
7281         oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7282             CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7283             "logs and miscellaneous information");
7284         children = SYSCTL_CHILDREN(oid);
7285
7286         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7287             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7288             sysctl_cctrl, "A", "congestion control");
7289
7290         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7291             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7292             sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7293
7294         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7295             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7296             sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7297
7298         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7299             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7300             sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7301
7302         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7303             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7304             sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7305
7306         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7307             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7308             sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7309
7310         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7311             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7312             sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7313
7314         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7315             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7316             sysctl_cim_la, "A", "CIM logic analyzer");
7317
7318         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7319             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7320             sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7321
7322         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7323             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7324             0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7325
7326         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7327             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7328             1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7329
7330         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7331             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7332             2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7333
7334         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7335             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7336             3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7337
7338         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7339             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7340             4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7341
7342         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7343             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7344             5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7345
7346         if (chip_id(sc) > CHELSIO_T4) {
7347                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7348                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7349                     6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7350                     "CIM OBQ 6 (SGE0-RX)");
7351
7352                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7353                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7354                     7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7355                     "CIM OBQ 7 (SGE1-RX)");
7356         }
7357
7358         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7359             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7360             sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7361
7362         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7363             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7364             sysctl_cim_qcfg, "A", "CIM queue configuration");
7365
7366         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7367             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7368             sysctl_cpl_stats, "A", "CPL statistics");
7369
7370         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7371             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7372             sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7373
7374         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7375             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7376             sysctl_tid_stats, "A", "tid stats");
7377
7378         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7379             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7380             sysctl_devlog, "A", "firmware's device log");
7381
7382         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7383             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7384             sysctl_fcoe_stats, "A", "FCoE statistics");
7385
7386         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7387             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7388             sysctl_hw_sched, "A", "hardware scheduler ");
7389
7390         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7391             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7392             sysctl_l2t, "A", "hardware L2 table");
7393
7394         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7395             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7396             sysctl_smt, "A", "hardware source MAC table");
7397
7398 #ifdef INET6
7399         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7400             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7401             sysctl_clip, "A", "active CLIP table entries");
7402 #endif
7403
7404         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7405             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7406             sysctl_lb_stats, "A", "loopback statistics");
7407
7408         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7409             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7410             sysctl_meminfo, "A", "memory regions");
7411
7412         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7413             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7414             chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7415             "A", "MPS TCAM entries");
7416
7417         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7418             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7419             sysctl_path_mtus, "A", "path MTUs");
7420
7421         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7422             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7423             sysctl_pm_stats, "A", "PM statistics");
7424
7425         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7426             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7427             sysctl_rdma_stats, "A", "RDMA statistics");
7428
7429         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7430             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7431             sysctl_tcp_stats, "A", "TCP statistics");
7432
7433         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7434             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7435             sysctl_tids, "A", "TID information");
7436
7437         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7438             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7439             sysctl_tp_err_stats, "A", "TP error statistics");
7440
7441         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7442             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7443             sysctl_tnl_stats, "A", "TP tunnel statistics");
7444
7445         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7446             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7447             sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7448
7449         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7450             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7451             sysctl_tp_la, "A", "TP logic analyzer");
7452
7453         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7454             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7455             sysctl_tx_rate, "A", "Tx rate");
7456
7457         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7458             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7459             sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7460
7461         if (chip_id(sc) >= CHELSIO_T5) {
7462                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7463                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7464                     sysctl_wcwr_stats, "A", "write combined work requests");
7465         }
7466
7467 #ifdef KERN_TLS
7468         if (is_ktls(sc)) {
7469                 /*
7470                  * dev.t4nex.0.tls.
7471                  */
7472                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7473                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7474                 children = SYSCTL_CHILDREN(oid);
7475
7476                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7477                     CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7478                     "keys in work requests (1) or attempt to store TLS keys "
7479                     "in card memory.");
7480                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7481                     CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
7482                     "TCB field updates with TLS record work requests.");
7483         }
7484 #endif
7485
7486 #ifdef TCP_OFFLOAD
7487         if (is_offload(sc)) {
7488                 int i;
7489                 char s[4];
7490
7491                 /*
7492                  * dev.t4nex.X.toe.
7493                  */
7494                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7495                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7496                 children = SYSCTL_CHILDREN(oid);
7497
7498                 sc->tt.cong_algorithm = -1;
7499                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7500                     CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7501                     "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7502                     "3 = highspeed)");
7503
7504                 sc->tt.sndbuf = -1;
7505                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7506                     &sc->tt.sndbuf, 0, "hardware send buffer");
7507
7508                 sc->tt.ddp = 0;
7509                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7510                     CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7511                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7512                     &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7513
7514                 sc->tt.rx_coalesce = -1;
7515                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7516                     CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7517
7518                 sc->tt.tls = 0;
7519                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7520                     CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7521                     "Inline TLS allowed");
7522
7523                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
7524                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7525                     sysctl_tls_rx_ports, "I",
7526                     "TCP ports that use inline TLS+TOE RX");
7527
7528                 sc->tt.tls_rx_timeout = t4_toe_tls_rx_timeout;
7529                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_timeout",
7530                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7531                     sysctl_tls_rx_timeout, "I",
7532                     "Timeout in seconds to downgrade TLS sockets to plain TOE");
7533
7534                 sc->tt.tx_align = -1;
7535                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7536                     CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7537
7538                 sc->tt.tx_zcopy = 0;
7539                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7540                     CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7541                     "Enable zero-copy aio_write(2)");
7542
7543                 sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7544                 SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7545                     "cop_managed_offloading", CTLFLAG_RW,
7546                     &sc->tt.cop_managed_offloading, 0,
7547                     "COP (Connection Offload Policy) controls all TOE offload");
7548
7549                 sc->tt.autorcvbuf_inc = 16 * 1024;
7550                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7551                     CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7552                     "autorcvbuf increment");
7553
7554                 sc->tt.update_hc_on_pmtu_change = 1;
7555                 SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7556                     "update_hc_on_pmtu_change", CTLFLAG_RW,
7557                     &sc->tt.update_hc_on_pmtu_change, 0,
7558                     "Update hostcache entry if the PMTU changes");
7559
7560                 sc->tt.iso = 1;
7561                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7562                     &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7563
7564                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7565                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7566                     sysctl_tp_tick, "A", "TP timer tick (us)");
7567
7568                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7569                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7570                     sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7571
7572                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7573                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7574                     sysctl_tp_tick, "A", "DACK tick (us)");
7575
7576                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7577                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7578                     sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7579
7580                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7581                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7582                     A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7583                     "Minimum retransmit interval (us)");
7584
7585                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7586                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7587                     A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7588                     "Maximum retransmit interval (us)");
7589
7590                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7591                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7592                     A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7593                     "Persist timer min (us)");
7594
7595                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7596                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7597                     A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7598                     "Persist timer max (us)");
7599
7600                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7601                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7602                     A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7603                     "Keepalive idle timer (us)");
7604
7605                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7606                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7607                     A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7608                     "Keepalive interval timer (us)");
7609
7610                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7611                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7612                     A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7613
7614                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7615                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7616                     A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7617                     "FINWAIT2 timer (us)");
7618
7619                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7620                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7621                     S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7622                     "Number of SYN retransmissions before abort");
7623
7624                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7625                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7626                     S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7627                     "Number of retransmissions before abort");
7628
7629                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7630                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7631                     S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7632                     "Number of keepalive probes before abort");
7633
7634                 oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7635                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7636                     "TOE retransmit backoffs");
7637                 children = SYSCTL_CHILDREN(oid);
7638                 for (i = 0; i < 16; i++) {
7639                         snprintf(s, sizeof(s), "%u", i);
7640                         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7641                             CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7642                             i, sysctl_tp_backoff, "IU",
7643                             "TOE retransmit backoff");
7644                 }
7645         }
7646 #endif
7647 }
7648
7649 void
7650 vi_sysctls(struct vi_info *vi)
7651 {
7652         struct sysctl_ctx_list *ctx;
7653         struct sysctl_oid *oid;
7654         struct sysctl_oid_list *children;
7655
7656         ctx = device_get_sysctl_ctx(vi->dev);
7657
7658         /*
7659          * dev.v?(cxgbe|cxl).X.
7660          */
7661         oid = device_get_sysctl_tree(vi->dev);
7662         children = SYSCTL_CHILDREN(oid);
7663
7664         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7665             vi->viid, "VI identifer");
7666         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7667             &vi->nrxq, 0, "# of rx queues");
7668         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7669             &vi->ntxq, 0, "# of tx queues");
7670         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7671             &vi->first_rxq, 0, "index of first rx queue");
7672         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7673             &vi->first_txq, 0, "index of first tx queue");
7674         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7675             vi->rss_base, "start of RSS indirection table");
7676         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7677             vi->rss_size, "size of RSS indirection table");
7678
7679         if (IS_MAIN_VI(vi)) {
7680                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7681                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7682                     sysctl_noflowq, "IU",
7683                     "Reserve queue 0 for non-flowid packets");
7684         }
7685
7686         if (vi->adapter->flags & IS_VF) {
7687                 MPASS(vi->flags & TX_USES_VM_WR);
7688                 SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7689                     NULL, 1, "use VM work requests for transmit");
7690         } else {
7691                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7692                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7693                     sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7694         }
7695
7696 #ifdef TCP_OFFLOAD
7697         if (vi->nofldrxq != 0) {
7698                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7699                     &vi->nofldrxq, 0,
7700                     "# of rx queues for offloaded TCP connections");
7701                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7702                     CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7703                     "index of first TOE rx queue");
7704                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7705                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7706                     sysctl_holdoff_tmr_idx_ofld, "I",
7707                     "holdoff timer index for TOE queues");
7708                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7709                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7710                     sysctl_holdoff_pktc_idx_ofld, "I",
7711                     "holdoff packet counter index for TOE queues");
7712         }
7713 #endif
7714 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7715         if (vi->nofldtxq != 0) {
7716                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7717                     &vi->nofldtxq, 0,
7718                     "# of tx queues for TOE/ETHOFLD");
7719                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7720                     CTLFLAG_RD, &vi->first_ofld_txq, 0,
7721                     "index of first TOE/ETHOFLD tx queue");
7722         }
7723 #endif
7724 #ifdef DEV_NETMAP
7725         if (vi->nnmrxq != 0) {
7726                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7727                     &vi->nnmrxq, 0, "# of netmap rx queues");
7728                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7729                     &vi->nnmtxq, 0, "# of netmap tx queues");
7730                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7731                     CTLFLAG_RD, &vi->first_nm_rxq, 0,
7732                     "index of first netmap rx queue");
7733                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7734                     CTLFLAG_RD, &vi->first_nm_txq, 0,
7735                     "index of first netmap tx queue");
7736         }
7737 #endif
7738
7739         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7740             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7741             sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7742         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7743             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7744             sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7745
7746         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7747             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7748             sysctl_qsize_rxq, "I", "rx queue size");
7749         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7750             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7751             sysctl_qsize_txq, "I", "tx queue size");
7752 }
7753
7754 static void
7755 cxgbe_sysctls(struct port_info *pi)
7756 {
7757         struct sysctl_ctx_list *ctx;
7758         struct sysctl_oid *oid;
7759         struct sysctl_oid_list *children, *children2;
7760         struct adapter *sc = pi->adapter;
7761         int i;
7762         char name[16];
7763         static char *tc_flags = {"\20\1USER"};
7764
7765         ctx = device_get_sysctl_ctx(pi->dev);
7766
7767         /*
7768          * dev.cxgbe.X.
7769          */
7770         oid = device_get_sysctl_tree(pi->dev);
7771         children = SYSCTL_CHILDREN(oid);
7772
7773         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7774             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7775             sysctl_linkdnrc, "A", "reason why link is down");
7776         if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7777                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7778                     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7779                     sysctl_btphy, "I", "PHY temperature (in Celsius)");
7780                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7781                     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7782                     sysctl_btphy, "I", "PHY firmware version");
7783         }
7784
7785         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7786             CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7787             sysctl_pause_settings, "A",
7788             "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7789         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7790             CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7791             "FEC in use on the link");
7792         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7793             CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7794             sysctl_requested_fec, "A",
7795             "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7796         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7797             CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7798             "FEC recommended by the cable/transceiver");
7799         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7800             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7801             sysctl_autoneg, "I",
7802             "autonegotiation (-1 = not supported)");
7803         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7804             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7805             sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7806
7807         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7808             &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7809         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7810             &pi->link_cfg.pcaps, 0, "port capabilities");
7811         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7812             &pi->link_cfg.acaps, 0, "advertised capabilities");
7813         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7814             &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7815
7816         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7817             port_top_speed(pi), "max speed (in Gbps)");
7818         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7819             pi->mps_bg_map, "MPS buffer group map");
7820         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7821             NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7822         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7823             pi->rx_c_chan, "TP rx c-channel");
7824
7825         if (sc->flags & IS_VF)
7826                 return;
7827
7828         /*
7829          * dev.(cxgbe|cxl).X.tc.
7830          */
7831         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7832             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7833             "Tx scheduler traffic classes (cl_rl)");
7834         children2 = SYSCTL_CHILDREN(oid);
7835         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7836             CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7837             "pktsize for per-flow cl-rl (0 means up to the driver )");
7838         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7839             CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7840             "burstsize for per-flow cl-rl (0 means up to the driver)");
7841         for (i = 0; i < sc->params.nsched_cls; i++) {
7842                 struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7843
7844                 snprintf(name, sizeof(name), "%d", i);
7845                 children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7846                     SYSCTL_CHILDREN(oid), OID_AUTO, name,
7847                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7848                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7849                     CTLFLAG_RD, &tc->state, 0, "current state");
7850                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7851                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7852                     (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7853                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7854                     CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7855                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7856                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7857                     (pi->port_id << 16) | i, sysctl_tc_params, "A",
7858                     "traffic class parameters");
7859         }
7860
7861         /*
7862          * dev.cxgbe.X.stats.
7863          */
7864         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7865             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7866         children = SYSCTL_CHILDREN(oid);
7867         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7868             &pi->tx_parse_error, 0,
7869             "# of tx packets with invalid length or # of segments");
7870
7871 #define T4_REGSTAT(name, stat, desc) \
7872     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7873         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7874         (is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7875         T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7876         sysctl_handle_t4_reg64, "QU", desc)
7877
7878 /* We get these from port_stats and they may be stale by up to 1s */
7879 #define T4_PORTSTAT(name, desc) \
7880         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7881             &pi->stats.name, desc)
7882
7883         T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7884         T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7885         T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7886         T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7887         T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7888         T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7889         T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7890         T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7891         T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7892         T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7893         T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7894         T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7895         T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7896         T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7897         T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7898         T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7899         T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7900         T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7901         T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7902         T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7903         T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7904         T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7905         T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7906
7907         T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7908         T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7909         T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7910         T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7911         T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7912         T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7913         T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7914         if (is_t6(sc)) {
7915                 T4_PORTSTAT(rx_fcs_err,
7916                     "# of frames received with bad FCS since last link up");
7917         } else {
7918                 T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7919                     "# of frames received with bad FCS");
7920         }
7921         T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7922         T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7923         T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7924         T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7925         T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7926         T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7927         T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7928         T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7929         T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7930         T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7931         T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7932         T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7933         T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7934         T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7935         T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7936         T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7937         T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7938         T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7939         T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7940
7941         T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7942         T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7943         T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7944         T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7945         T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7946         T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7947         T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7948         T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7949
7950 #undef T4_REGSTAT
7951 #undef T4_PORTSTAT
7952 }
7953
7954 static int
7955 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7956 {
7957         int rc, *i, space = 0;
7958         struct sbuf sb;
7959
7960         sbuf_new_for_sysctl(&sb, NULL, 64, req);
7961         for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7962                 if (space)
7963                         sbuf_printf(&sb, " ");
7964                 sbuf_printf(&sb, "%d", *i);
7965                 space = 1;
7966         }
7967         rc = sbuf_finish(&sb);
7968         sbuf_delete(&sb);
7969         return (rc);
7970 }
7971
7972 static int
7973 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7974 {
7975         int rc;
7976         struct sbuf *sb;
7977
7978         rc = sysctl_wire_old_buffer(req, 0);
7979         if (rc != 0)
7980                 return(rc);
7981
7982         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7983         if (sb == NULL)
7984                 return (ENOMEM);
7985
7986         sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7987         rc = sbuf_finish(sb);
7988         sbuf_delete(sb);
7989
7990         return (rc);
7991 }
7992
7993 static int
7994 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7995 {
7996         int rc;
7997         struct sbuf *sb;
7998
7999         rc = sysctl_wire_old_buffer(req, 0);
8000         if (rc != 0)
8001                 return(rc);
8002
8003         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8004         if (sb == NULL)
8005                 return (ENOMEM);
8006
8007         sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8008         rc = sbuf_finish(sb);
8009         sbuf_delete(sb);
8010
8011         return (rc);
8012 }
8013
8014 static int
8015 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8016 {
8017         struct port_info *pi = arg1;
8018         int op = arg2;
8019         struct adapter *sc = pi->adapter;
8020         u_int v;
8021         int rc;
8022
8023         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8024         if (rc)
8025                 return (rc);
8026         if (hw_off_limits(sc))
8027                 rc = ENXIO;
8028         else {
8029                 /* XXX: magic numbers */
8030                 rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8031                     op ? 0x20 : 0xc820, &v);
8032         }
8033         end_synchronized_op(sc, 0);
8034         if (rc)
8035                 return (rc);
8036         if (op == 0)
8037                 v /= 256;
8038
8039         rc = sysctl_handle_int(oidp, &v, 0, req);
8040         return (rc);
8041 }
8042
8043 static int
8044 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8045 {
8046         struct vi_info *vi = arg1;
8047         int rc, val;
8048
8049         val = vi->rsrv_noflowq;
8050         rc = sysctl_handle_int(oidp, &val, 0, req);
8051         if (rc != 0 || req->newptr == NULL)
8052                 return (rc);
8053
8054         if ((val >= 1) && (vi->ntxq > 1))
8055                 vi->rsrv_noflowq = 1;
8056         else
8057                 vi->rsrv_noflowq = 0;
8058
8059         return (rc);
8060 }
8061
8062 static int
8063 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8064 {
8065         struct vi_info *vi = arg1;
8066         struct adapter *sc = vi->adapter;
8067         int rc, val, i;
8068
8069         MPASS(!(sc->flags & IS_VF));
8070
8071         val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8072         rc = sysctl_handle_int(oidp, &val, 0, req);
8073         if (rc != 0 || req->newptr == NULL)
8074                 return (rc);
8075
8076         if (val != 0 && val != 1)
8077                 return (EINVAL);
8078
8079         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8080             "t4txvm");
8081         if (rc)
8082                 return (rc);
8083         if (hw_off_limits(sc))
8084                 rc = ENXIO;
8085         else if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
8086                 /*
8087                  * We don't want parse_pkt to run with one setting (VF or PF)
8088                  * and then eth_tx to see a different setting but still use
8089                  * stale information calculated by parse_pkt.
8090                  */
8091                 rc = EBUSY;
8092         } else {
8093                 struct port_info *pi = vi->pi;
8094                 struct sge_txq *txq;
8095                 uint32_t ctrl0;
8096                 uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8097
8098                 if (val) {
8099                         vi->flags |= TX_USES_VM_WR;
8100                         vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
8101                         ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8102                             V_TXPKT_INTF(pi->tx_chan));
8103                         if (!(sc->flags & IS_VF))
8104                                 npkt--;
8105                 } else {
8106                         vi->flags &= ~TX_USES_VM_WR;
8107                         vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
8108                         ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8109                             V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8110                             V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8111                 }
8112                 for_each_txq(vi, i, txq) {
8113                         txq->cpl_ctrl0 = ctrl0;
8114                         txq->txp.max_npkt = npkt;
8115                 }
8116         }
8117         end_synchronized_op(sc, LOCK_HELD);
8118         return (rc);
8119 }
8120
8121 static int
8122 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8123 {
8124         struct vi_info *vi = arg1;
8125         struct adapter *sc = vi->adapter;
8126         int idx, rc, i;
8127         struct sge_rxq *rxq;
8128         uint8_t v;
8129
8130         idx = vi->tmr_idx;
8131
8132         rc = sysctl_handle_int(oidp, &idx, 0, req);
8133         if (rc != 0 || req->newptr == NULL)
8134                 return (rc);
8135
8136         if (idx < 0 || idx >= SGE_NTIMERS)
8137                 return (EINVAL);
8138
8139         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8140             "t4tmr");
8141         if (rc)
8142                 return (rc);
8143
8144         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8145         for_each_rxq(vi, i, rxq) {
8146 #ifdef atomic_store_rel_8
8147                 atomic_store_rel_8(&rxq->iq.intr_params, v);
8148 #else
8149                 rxq->iq.intr_params = v;
8150 #endif
8151         }
8152         vi->tmr_idx = idx;
8153
8154         end_synchronized_op(sc, LOCK_HELD);
8155         return (0);
8156 }
8157
8158 static int
8159 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8160 {
8161         struct vi_info *vi = arg1;
8162         struct adapter *sc = vi->adapter;
8163         int idx, rc;
8164
8165         idx = vi->pktc_idx;
8166
8167         rc = sysctl_handle_int(oidp, &idx, 0, req);
8168         if (rc != 0 || req->newptr == NULL)
8169                 return (rc);
8170
8171         if (idx < -1 || idx >= SGE_NCOUNTERS)
8172                 return (EINVAL);
8173
8174         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8175             "t4pktc");
8176         if (rc)
8177                 return (rc);
8178
8179         if (vi->flags & VI_INIT_DONE)
8180                 rc = EBUSY; /* cannot be changed once the queues are created */
8181         else
8182                 vi->pktc_idx = idx;
8183
8184         end_synchronized_op(sc, LOCK_HELD);
8185         return (rc);
8186 }
8187
8188 static int
8189 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8190 {
8191         struct vi_info *vi = arg1;
8192         struct adapter *sc = vi->adapter;
8193         int qsize, rc;
8194
8195         qsize = vi->qsize_rxq;
8196
8197         rc = sysctl_handle_int(oidp, &qsize, 0, req);
8198         if (rc != 0 || req->newptr == NULL)
8199                 return (rc);
8200
8201         if (qsize < 128 || (qsize & 7))
8202                 return (EINVAL);
8203
8204         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8205             "t4rxqs");
8206         if (rc)
8207                 return (rc);
8208
8209         if (vi->flags & VI_INIT_DONE)
8210                 rc = EBUSY; /* cannot be changed once the queues are created */
8211         else
8212                 vi->qsize_rxq = qsize;
8213
8214         end_synchronized_op(sc, LOCK_HELD);
8215         return (rc);
8216 }
8217
8218 static int
8219 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8220 {
8221         struct vi_info *vi = arg1;
8222         struct adapter *sc = vi->adapter;
8223         int qsize, rc;
8224
8225         qsize = vi->qsize_txq;
8226
8227         rc = sysctl_handle_int(oidp, &qsize, 0, req);
8228         if (rc != 0 || req->newptr == NULL)
8229                 return (rc);
8230
8231         if (qsize < 128 || qsize > 65536)
8232                 return (EINVAL);
8233
8234         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8235             "t4txqs");
8236         if (rc)
8237                 return (rc);
8238
8239         if (vi->flags & VI_INIT_DONE)
8240                 rc = EBUSY; /* cannot be changed once the queues are created */
8241         else
8242                 vi->qsize_txq = qsize;
8243
8244         end_synchronized_op(sc, LOCK_HELD);
8245         return (rc);
8246 }
8247
8248 static int
8249 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8250 {
8251         struct port_info *pi = arg1;
8252         struct adapter *sc = pi->adapter;
8253         struct link_config *lc = &pi->link_cfg;
8254         int rc;
8255
8256         if (req->newptr == NULL) {
8257                 struct sbuf *sb;
8258                 static char *bits = "\20\1RX\2TX\3AUTO";
8259
8260                 rc = sysctl_wire_old_buffer(req, 0);
8261                 if (rc != 0)
8262                         return(rc);
8263
8264                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8265                 if (sb == NULL)
8266                         return (ENOMEM);
8267
8268                 if (lc->link_ok) {
8269                         sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8270                             (lc->requested_fc & PAUSE_AUTONEG), bits);
8271                 } else {
8272                         sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8273                             PAUSE_RX | PAUSE_AUTONEG), bits);
8274                 }
8275                 rc = sbuf_finish(sb);
8276                 sbuf_delete(sb);
8277         } else {
8278                 char s[2];
8279                 int n;
8280
8281                 s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8282                     PAUSE_AUTONEG));
8283                 s[1] = 0;
8284
8285                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8286                 if (rc != 0)
8287                         return(rc);
8288
8289                 if (s[1] != 0)
8290                         return (EINVAL);
8291                 if (s[0] < '0' || s[0] > '9')
8292                         return (EINVAL);        /* not a number */
8293                 n = s[0] - '0';
8294                 if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8295                         return (EINVAL);        /* some other bit is set too */
8296
8297                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8298                     "t4PAUSE");
8299                 if (rc)
8300                         return (rc);
8301                 if (!hw_off_limits(sc)) {
8302                         PORT_LOCK(pi);
8303                         lc->requested_fc = n;
8304                         fixup_link_config(pi);
8305                         if (pi->up_vis > 0)
8306                                 rc = apply_link_config(pi);
8307                         set_current_media(pi);
8308                         PORT_UNLOCK(pi);
8309                 }
8310                 end_synchronized_op(sc, 0);
8311         }
8312
8313         return (rc);
8314 }
8315
8316 static int
8317 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8318 {
8319         struct port_info *pi = arg1;
8320         struct link_config *lc = &pi->link_cfg;
8321         int rc;
8322         struct sbuf *sb;
8323         static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8324
8325         rc = sysctl_wire_old_buffer(req, 0);
8326         if (rc != 0)
8327                 return(rc);
8328
8329         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8330         if (sb == NULL)
8331                 return (ENOMEM);
8332         if (lc->link_ok)
8333                 sbuf_printf(sb, "%b", lc->fec, bits);
8334         else
8335                 sbuf_printf(sb, "no link");
8336         rc = sbuf_finish(sb);
8337         sbuf_delete(sb);
8338
8339         return (rc);
8340 }
8341
8342 static int
8343 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8344 {
8345         struct port_info *pi = arg1;
8346         struct adapter *sc = pi->adapter;
8347         struct link_config *lc = &pi->link_cfg;
8348         int rc;
8349         int8_t old;
8350
8351         if (req->newptr == NULL) {
8352                 struct sbuf *sb;
8353                 static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8354                     "\5RSVD3\6auto\7module";
8355
8356                 rc = sysctl_wire_old_buffer(req, 0);
8357                 if (rc != 0)
8358                         return(rc);
8359
8360                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8361                 if (sb == NULL)
8362                         return (ENOMEM);
8363
8364                 sbuf_printf(sb, "%b", lc->requested_fec, bits);
8365                 rc = sbuf_finish(sb);
8366                 sbuf_delete(sb);
8367         } else {
8368                 char s[8];
8369                 int n;
8370
8371                 snprintf(s, sizeof(s), "%d",
8372                     lc->requested_fec == FEC_AUTO ? -1 :
8373                     lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8374
8375                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8376                 if (rc != 0)
8377                         return(rc);
8378
8379                 n = strtol(&s[0], NULL, 0);
8380                 if (n < 0 || n & FEC_AUTO)
8381                         n = FEC_AUTO;
8382                 else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8383                         return (EINVAL);/* some other bit is set too */
8384
8385                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8386                     "t4reqf");
8387                 if (rc)
8388                         return (rc);
8389                 PORT_LOCK(pi);
8390                 old = lc->requested_fec;
8391                 if (n == FEC_AUTO)
8392                         lc->requested_fec = FEC_AUTO;
8393                 else if (n == 0 || n == FEC_NONE)
8394                         lc->requested_fec = FEC_NONE;
8395                 else {
8396                         if ((lc->pcaps |
8397                             V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8398                             lc->pcaps) {
8399                                 rc = ENOTSUP;
8400                                 goto done;
8401                         }
8402                         lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8403                             FEC_MODULE);
8404                 }
8405                 if (!hw_off_limits(sc)) {
8406                         fixup_link_config(pi);
8407                         if (pi->up_vis > 0) {
8408                                 rc = apply_link_config(pi);
8409                                 if (rc != 0) {
8410                                         lc->requested_fec = old;
8411                                         if (rc == FW_EPROTO)
8412                                                 rc = ENOTSUP;
8413                                 }
8414                         }
8415                 }
8416 done:
8417                 PORT_UNLOCK(pi);
8418                 end_synchronized_op(sc, 0);
8419         }
8420
8421         return (rc);
8422 }
8423
8424 static int
8425 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8426 {
8427         struct port_info *pi = arg1;
8428         struct adapter *sc = pi->adapter;
8429         struct link_config *lc = &pi->link_cfg;
8430         int rc;
8431         int8_t fec;
8432         struct sbuf *sb;
8433         static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8434
8435         rc = sysctl_wire_old_buffer(req, 0);
8436         if (rc != 0)
8437                 return (rc);
8438
8439         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8440         if (sb == NULL)
8441                 return (ENOMEM);
8442
8443         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8444                 rc = EBUSY;
8445                 goto done;
8446         }
8447         if (hw_off_limits(sc)) {
8448                 rc = ENXIO;
8449                 goto done;
8450         }
8451         PORT_LOCK(pi);
8452         if (pi->up_vis == 0) {
8453                 /*
8454                  * If all the interfaces are administratively down the firmware
8455                  * does not report transceiver changes.  Refresh port info here.
8456                  * This is the only reason we have a synchronized op in this
8457                  * function.  Just PORT_LOCK would have been enough otherwise.
8458                  */
8459                 t4_update_port_info(pi);
8460         }
8461
8462         fec = lc->fec_hint;
8463         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8464             !fec_supported(lc->pcaps)) {
8465                 sbuf_printf(sb, "n/a");
8466         } else {
8467                 if (fec == 0)
8468                         fec = FEC_NONE;
8469                 sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8470         }
8471         rc = sbuf_finish(sb);
8472         PORT_UNLOCK(pi);
8473 done:
8474         sbuf_delete(sb);
8475         end_synchronized_op(sc, 0);
8476
8477         return (rc);
8478 }
8479
8480 static int
8481 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8482 {
8483         struct port_info *pi = arg1;
8484         struct adapter *sc = pi->adapter;
8485         struct link_config *lc = &pi->link_cfg;
8486         int rc, val;
8487
8488         if (lc->pcaps & FW_PORT_CAP32_ANEG)
8489                 val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8490         else
8491                 val = -1;
8492         rc = sysctl_handle_int(oidp, &val, 0, req);
8493         if (rc != 0 || req->newptr == NULL)
8494                 return (rc);
8495         if (val == 0)
8496                 val = AUTONEG_DISABLE;
8497         else if (val == 1)
8498                 val = AUTONEG_ENABLE;
8499         else
8500                 val = AUTONEG_AUTO;
8501
8502         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8503             "t4aneg");
8504         if (rc)
8505                 return (rc);
8506         PORT_LOCK(pi);
8507         if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8508                 rc = ENOTSUP;
8509                 goto done;
8510         }
8511         lc->requested_aneg = val;
8512         if (!hw_off_limits(sc)) {
8513                 fixup_link_config(pi);
8514                 if (pi->up_vis > 0)
8515                         rc = apply_link_config(pi);
8516                 set_current_media(pi);
8517         }
8518 done:
8519         PORT_UNLOCK(pi);
8520         end_synchronized_op(sc, 0);
8521         return (rc);
8522 }
8523
8524 static int
8525 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8526 {
8527         struct port_info *pi = arg1;
8528         struct adapter *sc = pi->adapter;
8529         struct link_config *lc = &pi->link_cfg;
8530         int rc, val;
8531
8532         val = lc->force_fec;
8533         MPASS(val >= -1 && val <= 1);
8534         rc = sysctl_handle_int(oidp, &val, 0, req);
8535         if (rc != 0 || req->newptr == NULL)
8536                 return (rc);
8537         if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8538                 return (ENOTSUP);
8539         if (val < -1 || val > 1)
8540                 return (EINVAL);
8541
8542         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8543         if (rc)
8544                 return (rc);
8545         PORT_LOCK(pi);
8546         lc->force_fec = val;
8547         if (!hw_off_limits(sc)) {
8548                 fixup_link_config(pi);
8549                 if (pi->up_vis > 0)
8550                         rc = apply_link_config(pi);
8551         }
8552         PORT_UNLOCK(pi);
8553         end_synchronized_op(sc, 0);
8554         return (rc);
8555 }
8556
8557 static int
8558 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8559 {
8560         struct adapter *sc = arg1;
8561         int rc, reg = arg2;
8562         uint64_t val;
8563
8564         mtx_lock(&sc->reg_lock);
8565         if (hw_off_limits(sc))
8566                 rc = ENXIO;
8567         else {
8568                 rc = 0;
8569                 val = t4_read_reg64(sc, reg);
8570         }
8571         mtx_unlock(&sc->reg_lock);
8572         if (rc == 0)
8573                 rc = sysctl_handle_64(oidp, &val, 0, req);
8574         return (rc);
8575 }
8576
8577 static int
8578 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8579 {
8580         struct adapter *sc = arg1;
8581         int rc, t;
8582         uint32_t param, val;
8583
8584         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8585         if (rc)
8586                 return (rc);
8587         if (hw_off_limits(sc))
8588                 rc = ENXIO;
8589         else {
8590                 param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8591                     V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8592                     V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8593                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8594         }
8595         end_synchronized_op(sc, 0);
8596         if (rc)
8597                 return (rc);
8598
8599         /* unknown is returned as 0 but we display -1 in that case */
8600         t = val == 0 ? -1 : val;
8601
8602         rc = sysctl_handle_int(oidp, &t, 0, req);
8603         return (rc);
8604 }
8605
8606 static int
8607 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8608 {
8609         struct adapter *sc = arg1;
8610         int rc;
8611         uint32_t param, val;
8612
8613         if (sc->params.core_vdd == 0) {
8614                 rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8615                     "t4vdd");
8616                 if (rc)
8617                         return (rc);
8618                 if (hw_off_limits(sc))
8619                         rc = ENXIO;
8620                 else {
8621                         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8622                             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8623                             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8624                         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8625                             &param, &val);
8626                 }
8627                 end_synchronized_op(sc, 0);
8628                 if (rc)
8629                         return (rc);
8630                 sc->params.core_vdd = val;
8631         }
8632
8633         return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8634 }
8635
8636 static int
8637 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8638 {
8639         struct adapter *sc = arg1;
8640         int rc, v;
8641         uint32_t param, val;
8642
8643         v = sc->sensor_resets;
8644         rc = sysctl_handle_int(oidp, &v, 0, req);
8645         if (rc != 0 || req->newptr == NULL || v <= 0)
8646                 return (rc);
8647
8648         if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8649             chip_id(sc) < CHELSIO_T5)
8650                 return (ENOTSUP);
8651
8652         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8653         if (rc)
8654                 return (rc);
8655         if (hw_off_limits(sc))
8656                 rc = ENXIO;
8657         else {
8658                 param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8659                     V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8660                     V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8661                 val = 1;
8662                 rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8663         }
8664         end_synchronized_op(sc, 0);
8665         if (rc == 0)
8666                 sc->sensor_resets++;
8667         return (rc);
8668 }
8669
8670 static int
8671 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8672 {
8673         struct adapter *sc = arg1;
8674         struct sbuf *sb;
8675         int rc;
8676         uint32_t param, val;
8677
8678         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8679         if (rc)
8680                 return (rc);
8681         if (hw_off_limits(sc))
8682                 rc = ENXIO;
8683         else {
8684                 param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8685                     V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8686                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8687         }
8688         end_synchronized_op(sc, 0);
8689         if (rc)
8690                 return (rc);
8691
8692         rc = sysctl_wire_old_buffer(req, 0);
8693         if (rc != 0)
8694                 return (rc);
8695
8696         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8697         if (sb == NULL)
8698                 return (ENOMEM);
8699
8700         if (val == 0xffffffff) {
8701                 /* Only debug and custom firmwares report load averages. */
8702                 sbuf_printf(sb, "not available");
8703         } else {
8704                 sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8705                     (val >> 16) & 0xff);
8706         }
8707         rc = sbuf_finish(sb);
8708         sbuf_delete(sb);
8709
8710         return (rc);
8711 }
8712
8713 static int
8714 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8715 {
8716         struct adapter *sc = arg1;
8717         struct sbuf *sb;
8718         int rc, i;
8719         uint16_t incr[NMTUS][NCCTRL_WIN];
8720         static const char *dec_fac[] = {
8721                 "0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8722                 "0.9375"
8723         };
8724
8725         rc = sysctl_wire_old_buffer(req, 0);
8726         if (rc != 0)
8727                 return (rc);
8728
8729         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8730         if (sb == NULL)
8731                 return (ENOMEM);
8732
8733         mtx_lock(&sc->reg_lock);
8734         if (hw_off_limits(sc))
8735                 rc = ENXIO;
8736         else
8737                 t4_read_cong_tbl(sc, incr);
8738         mtx_unlock(&sc->reg_lock);
8739         if (rc)
8740                 goto done;
8741
8742         for (i = 0; i < NCCTRL_WIN; ++i) {
8743                 sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8744                     incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8745                     incr[5][i], incr[6][i], incr[7][i]);
8746                 sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8747                     incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8748                     incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8749                     sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8750         }
8751
8752         rc = sbuf_finish(sb);
8753 done:
8754         sbuf_delete(sb);
8755         return (rc);
8756 }
8757
8758 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8759         "TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",   /* ibq's */
8760         "ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", /* obq's */
8761         "SGE0-RX", "SGE1-RX"    /* additional obq's (T5 onwards) */
8762 };
8763
8764 static int
8765 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8766 {
8767         struct adapter *sc = arg1;
8768         struct sbuf *sb;
8769         int rc, i, n, qid = arg2;
8770         uint32_t *buf, *p;
8771         char *qtype;
8772         u_int cim_num_obq = sc->chip_params->cim_num_obq;
8773
8774         KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8775             ("%s: bad qid %d\n", __func__, qid));
8776
8777         if (qid < CIM_NUM_IBQ) {
8778                 /* inbound queue */
8779                 qtype = "IBQ";
8780                 n = 4 * CIM_IBQ_SIZE;
8781                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8782                 mtx_lock(&sc->reg_lock);
8783                 if (hw_off_limits(sc))
8784                         rc = -ENXIO;
8785                 else
8786                         rc = t4_read_cim_ibq(sc, qid, buf, n);
8787                 mtx_unlock(&sc->reg_lock);
8788         } else {
8789                 /* outbound queue */
8790                 qtype = "OBQ";
8791                 qid -= CIM_NUM_IBQ;
8792                 n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8793                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8794                 mtx_lock(&sc->reg_lock);
8795                 if (hw_off_limits(sc))
8796                         rc = -ENXIO;
8797                 else
8798                         rc = t4_read_cim_obq(sc, qid, buf, n);
8799                 mtx_unlock(&sc->reg_lock);
8800         }
8801
8802         if (rc < 0) {
8803                 rc = -rc;
8804                 goto done;
8805         }
8806         n = rc * sizeof(uint32_t);      /* rc has # of words actually read */
8807
8808         rc = sysctl_wire_old_buffer(req, 0);
8809         if (rc != 0)
8810                 goto done;
8811
8812         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8813         if (sb == NULL) {
8814                 rc = ENOMEM;
8815                 goto done;
8816         }
8817
8818         sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8819         for (i = 0, p = buf; i < n; i += 16, p += 4)
8820                 sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8821                     p[2], p[3]);
8822
8823         rc = sbuf_finish(sb);
8824         sbuf_delete(sb);
8825 done:
8826         free(buf, M_CXGBE);
8827         return (rc);
8828 }
8829
8830 static void
8831 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8832 {
8833         uint32_t *p;
8834
8835         sbuf_printf(sb, "Status   Data      PC%s",
8836             cfg & F_UPDBGLACAPTPCONLY ? "" :
8837             "     LS0Stat  LS0Addr             LS0Data");
8838
8839         for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8840                 if (cfg & F_UPDBGLACAPTPCONLY) {
8841                         sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8842                             p[6], p[7]);
8843                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8844                             (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8845                             p[4] & 0xff, p[5] >> 8);
8846                         sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8847                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8848                             p[1] & 0xf, p[2] >> 4);
8849                 } else {
8850                         sbuf_printf(sb,
8851                             "\n  %02x   %x%07x %x%07x %08x %08x "
8852                             "%08x%08x%08x%08x",
8853                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8854                             p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8855                             p[6], p[7]);
8856                 }
8857         }
8858 }
8859
8860 static void
8861 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8862 {
8863         uint32_t *p;
8864
8865         sbuf_printf(sb, "Status   Inst    Data      PC%s",
8866             cfg & F_UPDBGLACAPTPCONLY ? "" :
8867             "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8868
8869         for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8870                 if (cfg & F_UPDBGLACAPTPCONLY) {
8871                         sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8872                             p[3] & 0xff, p[2], p[1], p[0]);
8873                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8874                             (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8875                             p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8876                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8877                             (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8878                             p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8879                             p[6] >> 16);
8880                 } else {
8881                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8882                             "%08x %08x %08x %08x %08x %08x",
8883                             (p[9] >> 16) & 0xff,
8884                             p[9] & 0xffff, p[8] >> 16,
8885                             p[8] & 0xffff, p[7] >> 16,
8886                             p[7] & 0xffff, p[6] >> 16,
8887                             p[2], p[1], p[0], p[5], p[4], p[3]);
8888                 }
8889         }
8890 }
8891
8892 static int
8893 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8894 {
8895         uint32_t cfg, *buf;
8896         int rc;
8897
8898         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8899         buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8900             M_ZERO | flags);
8901         if (buf == NULL)
8902                 return (ENOMEM);
8903
8904         mtx_lock(&sc->reg_lock);
8905         if (hw_off_limits(sc))
8906                 rc = ENXIO;
8907         else {
8908                 rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8909                 if (rc == 0)
8910                         rc = -t4_cim_read_la(sc, buf, NULL);
8911         }
8912         mtx_unlock(&sc->reg_lock);
8913         if (rc == 0) {
8914                 if (chip_id(sc) < CHELSIO_T6)
8915                         sbuf_cim_la4(sc, sb, buf, cfg);
8916                 else
8917                         sbuf_cim_la6(sc, sb, buf, cfg);
8918         }
8919         free(buf, M_CXGBE);
8920         return (rc);
8921 }
8922
8923 static int
8924 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8925 {
8926         struct adapter *sc = arg1;
8927         struct sbuf *sb;
8928         int rc;
8929
8930         rc = sysctl_wire_old_buffer(req, 0);
8931         if (rc != 0)
8932                 return (rc);
8933         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8934         if (sb == NULL)
8935                 return (ENOMEM);
8936
8937         rc = sbuf_cim_la(sc, sb, M_WAITOK);
8938         if (rc == 0)
8939                 rc = sbuf_finish(sb);
8940         sbuf_delete(sb);
8941         return (rc);
8942 }
8943
8944 bool
8945 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8946 {
8947         struct sbuf sb;
8948         int rc;
8949
8950         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8951                 return (false);
8952         rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8953         if (rc == 0) {
8954                 rc = sbuf_finish(&sb);
8955                 if (rc == 0) {
8956                         log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8957                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
8958                 }
8959         }
8960         sbuf_delete(&sb);
8961         return (false);
8962 }
8963
8964 static int
8965 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8966 {
8967         struct adapter *sc = arg1;
8968         u_int i;
8969         struct sbuf *sb;
8970         uint32_t *buf, *p;
8971         int rc;
8972
8973         rc = sysctl_wire_old_buffer(req, 0);
8974         if (rc != 0)
8975                 return (rc);
8976
8977         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8978         if (sb == NULL)
8979                 return (ENOMEM);
8980
8981         buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8982             M_ZERO | M_WAITOK);
8983
8984         mtx_lock(&sc->reg_lock);
8985         if (hw_off_limits(sc))
8986                 rc = ENXIO;
8987         else
8988                 t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8989         mtx_unlock(&sc->reg_lock);
8990         if (rc)
8991                 goto done;
8992
8993         p = buf;
8994         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8995                 sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8996                     p[1], p[0]);
8997         }
8998
8999         sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9000         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9001                 sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9002                     (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9003                     (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9004                     (p[1] >> 2) | ((p[2] & 3) << 30),
9005                     (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9006                     p[0] & 1);
9007         }
9008         rc = sbuf_finish(sb);
9009 done:
9010         sbuf_delete(sb);
9011         free(buf, M_CXGBE);
9012         return (rc);
9013 }
9014
9015 static int
9016 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9017 {
9018         struct adapter *sc = arg1;
9019         u_int i;
9020         struct sbuf *sb;
9021         uint32_t *buf, *p;
9022         int rc;
9023
9024         rc = sysctl_wire_old_buffer(req, 0);
9025         if (rc != 0)
9026                 return (rc);
9027
9028         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9029         if (sb == NULL)
9030                 return (ENOMEM);
9031
9032         buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9033             M_ZERO | M_WAITOK);
9034
9035         mtx_lock(&sc->reg_lock);
9036         if (hw_off_limits(sc))
9037                 rc = ENXIO;
9038         else
9039                 t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9040         mtx_unlock(&sc->reg_lock);
9041         if (rc)
9042                 goto done;
9043
9044         p = buf;
9045         sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9046         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9047                 sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9048                     (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9049                     p[4], p[3], p[2], p[1], p[0]);
9050         }
9051
9052         sbuf_printf(sb, "\n\nCntl ID               Data");
9053         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9054                 sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9055                     (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9056         }
9057
9058         rc = sbuf_finish(sb);
9059 done:
9060         sbuf_delete(sb);
9061         free(buf, M_CXGBE);
9062         return (rc);
9063 }
9064
9065 static int
9066 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9067 {
9068         struct adapter *sc = arg1;
9069         struct sbuf *sb;
9070         int rc, i;
9071         uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9072         uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9073         uint16_t thres[CIM_NUM_IBQ];
9074         uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9075         uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9076         u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9077
9078         cim_num_obq = sc->chip_params->cim_num_obq;
9079         if (is_t4(sc)) {
9080                 ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9081                 obq_rdaddr = A_UP_OBQ_0_REALADDR;
9082         } else {
9083                 ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9084                 obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9085         }
9086         nq = CIM_NUM_IBQ + cim_num_obq;
9087
9088         mtx_lock(&sc->reg_lock);
9089         if (hw_off_limits(sc))
9090                 rc = ENXIO;
9091         else {
9092                 rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9093                 if (rc == 0) {
9094                         rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9095                             obq_wr);
9096                         if (rc == 0)
9097                                 t4_read_cimq_cfg(sc, base, size, thres);
9098                 }
9099         }
9100         mtx_unlock(&sc->reg_lock);
9101         if (rc)
9102                 return (rc);
9103
9104         rc = sysctl_wire_old_buffer(req, 0);
9105         if (rc != 0)
9106                 return (rc);
9107
9108         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9109         if (sb == NULL)
9110                 return (ENOMEM);
9111
9112         sbuf_printf(sb,
9113             "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9114
9115         for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9116                 sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9117                     qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9118                     G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9119                     G_QUEREMFLITS(p[2]) * 16);
9120         for ( ; i < nq; i++, p += 4, wr += 2)
9121                 sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9122                     base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9123                     wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9124                     G_QUEREMFLITS(p[2]) * 16);
9125
9126         rc = sbuf_finish(sb);
9127         sbuf_delete(sb);
9128
9129         return (rc);
9130 }
9131
9132 static int
9133 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9134 {
9135         struct adapter *sc = arg1;
9136         struct sbuf *sb;
9137         int rc;
9138         struct tp_cpl_stats stats;
9139
9140         rc = sysctl_wire_old_buffer(req, 0);
9141         if (rc != 0)
9142                 return (rc);
9143
9144         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9145         if (sb == NULL)
9146                 return (ENOMEM);
9147
9148         mtx_lock(&sc->reg_lock);
9149         if (hw_off_limits(sc))
9150                 rc = ENXIO;
9151         else
9152                 t4_tp_get_cpl_stats(sc, &stats, 0);
9153         mtx_unlock(&sc->reg_lock);
9154         if (rc)
9155                 goto done;
9156
9157         if (sc->chip_params->nchan > 2) {
9158                 sbuf_printf(sb, "                 channel 0  channel 1"
9159                     "  channel 2  channel 3");
9160                 sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9161                     stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9162                 sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9163                     stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9164         } else {
9165                 sbuf_printf(sb, "                 channel 0  channel 1");
9166                 sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9167                     stats.req[0], stats.req[1]);
9168                 sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9169                     stats.rsp[0], stats.rsp[1]);
9170         }
9171
9172         rc = sbuf_finish(sb);
9173 done:
9174         sbuf_delete(sb);
9175         return (rc);
9176 }
9177
9178 static int
9179 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9180 {
9181         struct adapter *sc = arg1;
9182         struct sbuf *sb;
9183         int rc;
9184         struct tp_usm_stats stats;
9185
9186         rc = sysctl_wire_old_buffer(req, 0);
9187         if (rc != 0)
9188                 return(rc);
9189
9190         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9191         if (sb == NULL)
9192                 return (ENOMEM);
9193
9194         mtx_lock(&sc->reg_lock);
9195         if (hw_off_limits(sc))
9196                 rc = ENXIO;
9197         else
9198                 t4_get_usm_stats(sc, &stats, 1);
9199         mtx_unlock(&sc->reg_lock);
9200         if (rc == 0) {
9201                 sbuf_printf(sb, "Frames: %u\n", stats.frames);
9202                 sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9203                 sbuf_printf(sb, "Drops:  %u", stats.drops);
9204                 rc = sbuf_finish(sb);
9205         }
9206         sbuf_delete(sb);
9207
9208         return (rc);
9209 }
9210
9211 static int
9212 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9213 {
9214         struct adapter *sc = arg1;
9215         struct sbuf *sb;
9216         int rc;
9217         struct tp_tid_stats stats;
9218
9219         rc = sysctl_wire_old_buffer(req, 0);
9220         if (rc != 0)
9221                 return(rc);
9222
9223         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9224         if (sb == NULL)
9225                 return (ENOMEM);
9226
9227         mtx_lock(&sc->reg_lock);
9228         if (hw_off_limits(sc))
9229                 rc = ENXIO;
9230         else
9231                 t4_tp_get_tid_stats(sc, &stats, 1);
9232         mtx_unlock(&sc->reg_lock);
9233         if (rc == 0) {
9234                 sbuf_printf(sb, "Delete:     %u\n", stats.del);
9235                 sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9236                 sbuf_printf(sb, "Active:     %u\n", stats.act);
9237                 sbuf_printf(sb, "Passive:    %u", stats.pas);
9238                 rc = sbuf_finish(sb);
9239         }
9240         sbuf_delete(sb);
9241
9242         return (rc);
9243 }
9244
9245 static const char * const devlog_level_strings[] = {
9246         [FW_DEVLOG_LEVEL_EMERG]         = "EMERG",
9247         [FW_DEVLOG_LEVEL_CRIT]          = "CRIT",
9248         [FW_DEVLOG_LEVEL_ERR]           = "ERR",
9249         [FW_DEVLOG_LEVEL_NOTICE]        = "NOTICE",
9250         [FW_DEVLOG_LEVEL_INFO]          = "INFO",
9251         [FW_DEVLOG_LEVEL_DEBUG]         = "DEBUG"
9252 };
9253
9254 static const char * const devlog_facility_strings[] = {
9255         [FW_DEVLOG_FACILITY_CORE]       = "CORE",
9256         [FW_DEVLOG_FACILITY_CF]         = "CF",
9257         [FW_DEVLOG_FACILITY_SCHED]      = "SCHED",
9258         [FW_DEVLOG_FACILITY_TIMER]      = "TIMER",
9259         [FW_DEVLOG_FACILITY_RES]        = "RES",
9260         [FW_DEVLOG_FACILITY_HW]         = "HW",
9261         [FW_DEVLOG_FACILITY_FLR]        = "FLR",
9262         [FW_DEVLOG_FACILITY_DMAQ]       = "DMAQ",
9263         [FW_DEVLOG_FACILITY_PHY]        = "PHY",
9264         [FW_DEVLOG_FACILITY_MAC]        = "MAC",
9265         [FW_DEVLOG_FACILITY_PORT]       = "PORT",
9266         [FW_DEVLOG_FACILITY_VI]         = "VI",
9267         [FW_DEVLOG_FACILITY_FILTER]     = "FILTER",
9268         [FW_DEVLOG_FACILITY_ACL]        = "ACL",
9269         [FW_DEVLOG_FACILITY_TM]         = "TM",
9270         [FW_DEVLOG_FACILITY_QFC]        = "QFC",
9271         [FW_DEVLOG_FACILITY_DCB]        = "DCB",
9272         [FW_DEVLOG_FACILITY_ETH]        = "ETH",
9273         [FW_DEVLOG_FACILITY_OFLD]       = "OFLD",
9274         [FW_DEVLOG_FACILITY_RI]         = "RI",
9275         [FW_DEVLOG_FACILITY_ISCSI]      = "ISCSI",
9276         [FW_DEVLOG_FACILITY_FCOE]       = "FCOE",
9277         [FW_DEVLOG_FACILITY_FOISCSI]    = "FOISCSI",
9278         [FW_DEVLOG_FACILITY_FOFCOE]     = "FOFCOE",
9279         [FW_DEVLOG_FACILITY_CHNET]      = "CHNET",
9280 };
9281
9282 static int
9283 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9284 {
9285         int i, j, rc, nentries, first = 0;
9286         struct devlog_params *dparams = &sc->params.devlog;
9287         struct fw_devlog_e *buf, *e;
9288         uint64_t ftstamp = UINT64_MAX;
9289
9290         if (dparams->addr == 0)
9291                 return (ENXIO);
9292
9293         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9294         buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9295         if (buf == NULL)
9296                 return (ENOMEM);
9297
9298         mtx_lock(&sc->reg_lock);
9299         if (hw_off_limits(sc))
9300                 rc = ENXIO;
9301         else
9302                 rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9303                     dparams->size);
9304         mtx_unlock(&sc->reg_lock);
9305         if (rc != 0)
9306                 goto done;
9307
9308         nentries = dparams->size / sizeof(struct fw_devlog_e);
9309         for (i = 0; i < nentries; i++) {
9310                 e = &buf[i];
9311
9312                 if (e->timestamp == 0)
9313                         break;  /* end */
9314
9315                 e->timestamp = be64toh(e->timestamp);
9316                 e->seqno = be32toh(e->seqno);
9317                 for (j = 0; j < 8; j++)
9318                         e->params[j] = be32toh(e->params[j]);
9319
9320                 if (e->timestamp < ftstamp) {
9321                         ftstamp = e->timestamp;
9322                         first = i;
9323                 }
9324         }
9325
9326         if (buf[first].timestamp == 0)
9327                 goto done;      /* nothing in the log */
9328
9329         sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9330             "Seq#", "Tstamp", "Level", "Facility", "Message");
9331
9332         i = first;
9333         do {
9334                 e = &buf[i];
9335                 if (e->timestamp == 0)
9336                         break;  /* end */
9337
9338                 sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9339                     e->seqno, e->timestamp,
9340                     (e->level < nitems(devlog_level_strings) ?
9341                         devlog_level_strings[e->level] : "UNKNOWN"),
9342                     (e->facility < nitems(devlog_facility_strings) ?
9343                         devlog_facility_strings[e->facility] : "UNKNOWN"));
9344                 sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9345                     e->params[2], e->params[3], e->params[4],
9346                     e->params[5], e->params[6], e->params[7]);
9347
9348                 if (++i == nentries)
9349                         i = 0;
9350         } while (i != first);
9351 done:
9352         free(buf, M_CXGBE);
9353         return (rc);
9354 }
9355
9356 static int
9357 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9358 {
9359         struct adapter *sc = arg1;
9360         int rc;
9361         struct sbuf *sb;
9362
9363         rc = sysctl_wire_old_buffer(req, 0);
9364         if (rc != 0)
9365                 return (rc);
9366         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9367         if (sb == NULL)
9368                 return (ENOMEM);
9369
9370         rc = sbuf_devlog(sc, sb, M_WAITOK);
9371         if (rc == 0)
9372                 rc = sbuf_finish(sb);
9373         sbuf_delete(sb);
9374         return (rc);
9375 }
9376
9377 void
9378 t4_os_dump_devlog(struct adapter *sc)
9379 {
9380         int rc;
9381         struct sbuf sb;
9382
9383         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
9384                 return;
9385         rc = sbuf_devlog(sc, &sb, M_NOWAIT);
9386         if (rc == 0) {
9387                 rc = sbuf_finish(&sb);
9388                 if (rc == 0) {
9389                         log(LOG_DEBUG, "%s: device log follows.\n%s",
9390                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
9391                 }
9392         }
9393         sbuf_delete(&sb);
9394 }
9395
9396 static int
9397 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9398 {
9399         struct adapter *sc = arg1;
9400         struct sbuf *sb;
9401         int rc;
9402         struct tp_fcoe_stats stats[MAX_NCHAN];
9403         int i, nchan = sc->chip_params->nchan;
9404
9405         rc = sysctl_wire_old_buffer(req, 0);
9406         if (rc != 0)
9407                 return (rc);
9408
9409         mtx_lock(&sc->reg_lock);
9410         if (hw_off_limits(sc))
9411                 rc = ENXIO;
9412         else {
9413                 for (i = 0; i < nchan; i++)
9414                         t4_get_fcoe_stats(sc, i, &stats[i], 1);
9415         }
9416         mtx_unlock(&sc->reg_lock);
9417         if (rc != 0)
9418                 return (rc);
9419
9420         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9421         if (sb == NULL)
9422                 return (ENOMEM);
9423
9424         if (nchan > 2) {
9425                 sbuf_printf(sb, "                   channel 0        channel 1"
9426                     "        channel 2        channel 3");
9427                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9428                     stats[0].octets_ddp, stats[1].octets_ddp,
9429                     stats[2].octets_ddp, stats[3].octets_ddp);
9430                 sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9431                     stats[0].frames_ddp, stats[1].frames_ddp,
9432                     stats[2].frames_ddp, stats[3].frames_ddp);
9433                 sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9434                     stats[0].frames_drop, stats[1].frames_drop,
9435                     stats[2].frames_drop, stats[3].frames_drop);
9436         } else {
9437                 sbuf_printf(sb, "                   channel 0        channel 1");
9438                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9439                     stats[0].octets_ddp, stats[1].octets_ddp);
9440                 sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9441                     stats[0].frames_ddp, stats[1].frames_ddp);
9442                 sbuf_printf(sb, "\nframesDrop: %16u %16u",
9443                     stats[0].frames_drop, stats[1].frames_drop);
9444         }
9445
9446         rc = sbuf_finish(sb);
9447         sbuf_delete(sb);
9448
9449         return (rc);
9450 }
9451
9452 static int
9453 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9454 {
9455         struct adapter *sc = arg1;
9456         struct sbuf *sb;
9457         int rc, i;
9458         unsigned int map, kbps, ipg, mode;
9459         unsigned int pace_tab[NTX_SCHED];
9460
9461         rc = sysctl_wire_old_buffer(req, 0);
9462         if (rc != 0)
9463                 return (rc);
9464
9465         sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9466         if (sb == NULL)
9467                 return (ENOMEM);
9468
9469         mtx_lock(&sc->reg_lock);
9470         if (hw_off_limits(sc)) {
9471                 rc = ENXIO;
9472                 goto done;
9473         }
9474
9475         map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9476         mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9477         t4_read_pace_tbl(sc, pace_tab);
9478
9479         sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9480             "Class IPG (0.1 ns)   Flow IPG (us)");
9481
9482         for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9483                 t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9484                 sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9485                     (mode & (1 << i)) ? "flow" : "class", map & 3);
9486                 if (kbps)
9487                         sbuf_printf(sb, "%9u     ", kbps);
9488                 else
9489                         sbuf_printf(sb, " disabled     ");
9490
9491                 if (ipg)
9492                         sbuf_printf(sb, "%13u        ", ipg);
9493                 else
9494                         sbuf_printf(sb, "     disabled        ");
9495
9496                 if (pace_tab[i])
9497                         sbuf_printf(sb, "%10u", pace_tab[i]);
9498                 else
9499                         sbuf_printf(sb, "  disabled");
9500         }
9501         rc = sbuf_finish(sb);
9502 done:
9503         mtx_unlock(&sc->reg_lock);
9504         sbuf_delete(sb);
9505         return (rc);
9506 }
9507
9508 static int
9509 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9510 {
9511         struct adapter *sc = arg1;
9512         struct sbuf *sb;
9513         int rc, i, j;
9514         uint64_t *p0, *p1;
9515         struct lb_port_stats s[2];
9516         static const char *stat_name[] = {
9517                 "OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9518                 "UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9519                 "Frames128To255:", "Frames256To511:", "Frames512To1023:",
9520                 "Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9521                 "BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9522                 "BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9523                 "BG2FramesTrunc:", "BG3FramesTrunc:"
9524         };
9525
9526         rc = sysctl_wire_old_buffer(req, 0);
9527         if (rc != 0)
9528                 return (rc);
9529
9530         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9531         if (sb == NULL)
9532                 return (ENOMEM);
9533
9534         memset(s, 0, sizeof(s));
9535
9536         for (i = 0; i < sc->chip_params->nchan; i += 2) {
9537                 mtx_lock(&sc->reg_lock);
9538                 if (hw_off_limits(sc))
9539                         rc = ENXIO;
9540                 else {
9541                         t4_get_lb_stats(sc, i, &s[0]);
9542                         t4_get_lb_stats(sc, i + 1, &s[1]);
9543                 }
9544                 mtx_unlock(&sc->reg_lock);
9545                 if (rc != 0)
9546                         break;
9547
9548                 p0 = &s[0].octets;
9549                 p1 = &s[1].octets;
9550                 sbuf_printf(sb, "%s                       Loopback %u"
9551                     "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9552
9553                 for (j = 0; j < nitems(stat_name); j++)
9554                         sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9555                                    *p0++, *p1++);
9556         }
9557
9558         rc = sbuf_finish(sb);
9559         sbuf_delete(sb);
9560
9561         return (rc);
9562 }
9563
9564 static int
9565 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9566 {
9567         int rc = 0;
9568         struct port_info *pi = arg1;
9569         struct link_config *lc = &pi->link_cfg;
9570         struct sbuf *sb;
9571
9572         rc = sysctl_wire_old_buffer(req, 0);
9573         if (rc != 0)
9574                 return(rc);
9575         sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9576         if (sb == NULL)
9577                 return (ENOMEM);
9578
9579         if (lc->link_ok || lc->link_down_rc == 255)
9580                 sbuf_printf(sb, "n/a");
9581         else
9582                 sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9583
9584         rc = sbuf_finish(sb);
9585         sbuf_delete(sb);
9586
9587         return (rc);
9588 }
9589
9590 struct mem_desc {
9591         unsigned int base;
9592         unsigned int limit;
9593         unsigned int idx;
9594 };
9595
9596 static int
9597 mem_desc_cmp(const void *a, const void *b)
9598 {
9599         return ((const struct mem_desc *)a)->base -
9600                ((const struct mem_desc *)b)->base;
9601 }
9602
9603 static void
9604 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9605     unsigned int to)
9606 {
9607         unsigned int size;
9608
9609         if (from == to)
9610                 return;
9611
9612         size = to - from + 1;
9613         if (size == 0)
9614                 return;
9615
9616         /* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9617         sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9618 }
9619
9620 static int
9621 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9622 {
9623         struct adapter *sc = arg1;
9624         struct sbuf *sb;
9625         int rc, i, n;
9626         uint32_t lo, hi, used, alloc;
9627         static const char *memory[] = {
9628                 "EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9629         };
9630         static const char *region[] = {
9631                 "DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9632                 "Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9633                 "Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9634                 "TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9635                 "RQUDP region:", "PBL region:", "TXPBL region:",
9636                 "DBVFIFO region:", "ULPRX state:", "ULPTX state:",
9637                 "On-chip queues:", "TLS keys:",
9638         };
9639         struct mem_desc avail[4];
9640         struct mem_desc mem[nitems(region) + 3];        /* up to 3 holes */
9641         struct mem_desc *md = mem;
9642
9643         rc = sysctl_wire_old_buffer(req, 0);
9644         if (rc != 0)
9645                 return (rc);
9646
9647         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9648         if (sb == NULL)
9649                 return (ENOMEM);
9650
9651         for (i = 0; i < nitems(mem); i++) {
9652                 mem[i].limit = 0;
9653                 mem[i].idx = i;
9654         }
9655
9656         mtx_lock(&sc->reg_lock);
9657         if (hw_off_limits(sc)) {
9658                 rc = ENXIO;
9659                 goto done;
9660         }
9661
9662         /* Find and sort the populated memory ranges */
9663         i = 0;
9664         lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9665         if (lo & F_EDRAM0_ENABLE) {
9666                 hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9667                 avail[i].base = G_EDRAM0_BASE(hi) << 20;
9668                 avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9669                 avail[i].idx = 0;
9670                 i++;
9671         }
9672         if (lo & F_EDRAM1_ENABLE) {
9673                 hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9674                 avail[i].base = G_EDRAM1_BASE(hi) << 20;
9675                 avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9676                 avail[i].idx = 1;
9677                 i++;
9678         }
9679         if (lo & F_EXT_MEM_ENABLE) {
9680                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9681                 avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9682                 avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9683                 avail[i].idx = is_t5(sc) ? 3 : 2;       /* Call it MC0 for T5 */
9684                 i++;
9685         }
9686         if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9687                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9688                 avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9689                 avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9690                 avail[i].idx = 4;
9691                 i++;
9692         }
9693         if (is_t6(sc) && lo & F_HMA_MUX) {
9694                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9695                 avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9696                 avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9697                 avail[i].idx = 5;
9698                 i++;
9699         }
9700         MPASS(i <= nitems(avail));
9701         if (!i)                                    /* no memory available */
9702                 goto done;
9703         qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9704
9705         (md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9706         (md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9707         (md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9708         (md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9709         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9710         (md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9711         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9712         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9713         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9714
9715         /* the next few have explicit upper bounds */
9716         md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9717         md->limit = md->base - 1 +
9718                     t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9719                     G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9720         md++;
9721
9722         md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9723         md->limit = md->base - 1 +
9724                     t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9725                     G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9726         md++;
9727
9728         if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9729                 if (chip_id(sc) <= CHELSIO_T5)
9730                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9731                 else
9732                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9733                 md->limit = 0;
9734         } else {
9735                 md->base = 0;
9736                 md->idx = nitems(region);  /* hide it */
9737         }
9738         md++;
9739
9740 #define ulp_region(reg) \
9741         md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9742         (md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9743
9744         ulp_region(RX_ISCSI);
9745         ulp_region(RX_TDDP);
9746         ulp_region(TX_TPT);
9747         ulp_region(RX_STAG);
9748         ulp_region(RX_RQ);
9749         ulp_region(RX_RQUDP);
9750         ulp_region(RX_PBL);
9751         ulp_region(TX_PBL);
9752 #undef ulp_region
9753
9754         md->base = 0;
9755         if (is_t4(sc))
9756                 md->idx = nitems(region);
9757         else {
9758                 uint32_t size = 0;
9759                 uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9760                 uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9761
9762                 if (is_t5(sc)) {
9763                         if (sge_ctrl & F_VFIFO_ENABLE)
9764                                 size = fifo_size << 2;
9765                 } else
9766                         size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9767
9768                 if (size) {
9769                         md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9770                         md->limit = md->base + size - 1;
9771                 } else
9772                         md->idx = nitems(region);
9773         }
9774         md++;
9775
9776         md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9777         md->limit = 0;
9778         md++;
9779         md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9780         md->limit = 0;
9781         md++;
9782
9783         md->base = sc->vres.ocq.start;
9784         if (sc->vres.ocq.size)
9785                 md->limit = md->base + sc->vres.ocq.size - 1;
9786         else
9787                 md->idx = nitems(region);  /* hide it */
9788         md++;
9789
9790         md->base = sc->vres.key.start;
9791         if (sc->vres.key.size)
9792                 md->limit = md->base + sc->vres.key.size - 1;
9793         else
9794                 md->idx = nitems(region);  /* hide it */
9795         md++;
9796
9797         /* add any address-space holes, there can be up to 3 */
9798         for (n = 0; n < i - 1; n++)
9799                 if (avail[n].limit < avail[n + 1].base)
9800                         (md++)->base = avail[n].limit;
9801         if (avail[n].limit)
9802                 (md++)->base = avail[n].limit;
9803
9804         n = md - mem;
9805         qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9806
9807         for (lo = 0; lo < i; lo++)
9808                 mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9809                                 avail[lo].limit - 1);
9810
9811         sbuf_printf(sb, "\n");
9812         for (i = 0; i < n; i++) {
9813                 if (mem[i].idx >= nitems(region))
9814                         continue;                        /* skip holes */
9815                 if (!mem[i].limit)
9816                         mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9817                 mem_region_show(sb, region[mem[i].idx], mem[i].base,
9818                                 mem[i].limit);
9819         }
9820
9821         sbuf_printf(sb, "\n");
9822         lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9823         hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9824         mem_region_show(sb, "uP RAM:", lo, hi);
9825
9826         lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9827         hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9828         mem_region_show(sb, "uP Extmem2:", lo, hi);
9829
9830         lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9831         sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
9832                    G_PMRXMAXPAGE(lo),
9833                    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9834                    (lo & F_PMRXNUMCHN) ? 2 : 1);
9835
9836         lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9837         hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9838         sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
9839                    G_PMTXMAXPAGE(lo),
9840                    hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9841                    hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9842         sbuf_printf(sb, "%u p-structs\n",
9843                    t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
9844
9845         for (i = 0; i < 4; i++) {
9846                 if (chip_id(sc) > CHELSIO_T5)
9847                         lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9848                 else
9849                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9850                 if (is_t5(sc)) {
9851                         used = G_T5_USED(lo);
9852                         alloc = G_T5_ALLOC(lo);
9853                 } else {
9854                         used = G_USED(lo);
9855                         alloc = G_ALLOC(lo);
9856                 }
9857                 /* For T6 these are MAC buffer groups */
9858                 sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9859                     i, used, alloc);
9860         }
9861         for (i = 0; i < sc->chip_params->nchan; i++) {
9862                 if (chip_id(sc) > CHELSIO_T5)
9863                         lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9864                 else
9865                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
9866                 if (is_t5(sc)) {
9867                         used = G_T5_USED(lo);
9868                         alloc = G_T5_ALLOC(lo);
9869                 } else {
9870                         used = G_USED(lo);
9871                         alloc = G_ALLOC(lo);
9872                 }
9873                 /* For T6 these are MAC buffer groups */
9874                 sbuf_printf(sb,
9875                     "\nLoopback %d using %u pages out of %u allocated",
9876                     i, used, alloc);
9877         }
9878 done:
9879         mtx_unlock(&sc->reg_lock);
9880         if (rc == 0)
9881                 rc = sbuf_finish(sb);
9882         sbuf_delete(sb);
9883         return (rc);
9884 }
9885
9886 static inline void
9887 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
9888 {
9889         *mask = x | y;
9890         y = htobe64(y);
9891         memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
9892 }
9893
9894 static int
9895 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
9896 {
9897         struct adapter *sc = arg1;
9898         struct sbuf *sb;
9899         int rc, i;
9900
9901         MPASS(chip_id(sc) <= CHELSIO_T5);
9902
9903         rc = sysctl_wire_old_buffer(req, 0);
9904         if (rc != 0)
9905                 return (rc);
9906
9907         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9908         if (sb == NULL)
9909                 return (ENOMEM);
9910
9911         sbuf_printf(sb,
9912             "Idx  Ethernet address     Mask     Vld Ports PF"
9913             "  VF              Replication             P0 P1 P2 P3  ML");
9914         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9915                 uint64_t tcamx, tcamy, mask;
9916                 uint32_t cls_lo, cls_hi;
9917                 uint8_t addr[ETHER_ADDR_LEN];
9918
9919                 mtx_lock(&sc->reg_lock);
9920                 if (hw_off_limits(sc))
9921                         rc = ENXIO;
9922                 else {
9923                         tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
9924                         tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
9925                 }
9926                 mtx_unlock(&sc->reg_lock);
9927                 if (rc != 0)
9928                         break;
9929                 if (tcamx & tcamy)
9930                         continue;
9931                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
9932                 mtx_lock(&sc->reg_lock);
9933                 if (hw_off_limits(sc))
9934                         rc = ENXIO;
9935                 else {
9936                         cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9937                         cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9938                 }
9939                 mtx_unlock(&sc->reg_lock);
9940                 if (rc != 0)
9941                         break;
9942                 sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
9943                            "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
9944                            addr[3], addr[4], addr[5], (uintmax_t)mask,
9945                            (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
9946                            G_PORTMAP(cls_hi), G_PF(cls_lo),
9947                            (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
9948
9949                 if (cls_lo & F_REPLICATE) {
9950                         struct fw_ldst_cmd ldst_cmd;
9951
9952                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9953                         ldst_cmd.op_to_addrspace =
9954                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9955                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
9956                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9957                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9958                         ldst_cmd.u.mps.rplc.fid_idx =
9959                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9960                                 V_FW_LDST_CMD_IDX(i));
9961
9962                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9963                             "t4mps");
9964                         if (rc)
9965                                 break;
9966                         if (hw_off_limits(sc))
9967                                 rc = ENXIO;
9968                         else
9969                                 rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9970                                     sizeof(ldst_cmd), &ldst_cmd);
9971                         end_synchronized_op(sc, 0);
9972                         if (rc != 0)
9973                                 break;
9974                         else {
9975                                 sbuf_printf(sb, " %08x %08x %08x %08x",
9976                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9977                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9978                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9979                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9980                         }
9981                 } else
9982                         sbuf_printf(sb, "%36s", "");
9983
9984                 sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9985                     G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9986                     G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9987         }
9988
9989         if (rc)
9990                 (void) sbuf_finish(sb);
9991         else
9992                 rc = sbuf_finish(sb);
9993         sbuf_delete(sb);
9994
9995         return (rc);
9996 }
9997
9998 static int
9999 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10000 {
10001         struct adapter *sc = arg1;
10002         struct sbuf *sb;
10003         int rc, i;
10004
10005         MPASS(chip_id(sc) > CHELSIO_T5);
10006
10007         rc = sysctl_wire_old_buffer(req, 0);
10008         if (rc != 0)
10009                 return (rc);
10010
10011         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10012         if (sb == NULL)
10013                 return (ENOMEM);
10014
10015         sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10016             "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10017             "                           Replication"
10018             "                                    P0 P1 P2 P3  ML\n");
10019
10020         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10021                 uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10022                 uint16_t ivlan;
10023                 uint64_t tcamx, tcamy, val, mask;
10024                 uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10025                 uint8_t addr[ETHER_ADDR_LEN];
10026
10027                 ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10028                 if (i < 256)
10029                         ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10030                 else
10031                         ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10032                 mtx_lock(&sc->reg_lock);
10033                 if (hw_off_limits(sc))
10034                         rc = ENXIO;
10035                 else {
10036                         t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10037                         val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10038                         tcamy = G_DMACH(val) << 32;
10039                         tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10040                         data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10041                 }
10042                 mtx_unlock(&sc->reg_lock);
10043                 if (rc != 0)
10044                         break;
10045
10046                 lookup_type = G_DATALKPTYPE(data2);
10047                 port_num = G_DATAPORTNUM(data2);
10048                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
10049                         /* Inner header VNI */
10050                         vniy = ((data2 & F_DATAVIDH2) << 23) |
10051                                        (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10052                         dip_hit = data2 & F_DATADIPHIT;
10053                         vlan_vld = 0;
10054                 } else {
10055                         vniy = 0;
10056                         dip_hit = 0;
10057                         vlan_vld = data2 & F_DATAVIDH2;
10058                         ivlan = G_VIDL(val);
10059                 }
10060
10061                 ctl |= V_CTLXYBITSEL(1);
10062                 mtx_lock(&sc->reg_lock);
10063                 if (hw_off_limits(sc))
10064                         rc = ENXIO;
10065                 else {
10066                         t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10067                         val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10068                         tcamx = G_DMACH(val) << 32;
10069                         tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10070                         data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10071                 }
10072                 mtx_unlock(&sc->reg_lock);
10073                 if (rc != 0)
10074                         break;
10075
10076                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
10077                         /* Inner header VNI mask */
10078                         vnix = ((data2 & F_DATAVIDH2) << 23) |
10079                                (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10080                 } else
10081                         vnix = 0;
10082
10083                 if (tcamx & tcamy)
10084                         continue;
10085                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
10086
10087                 mtx_lock(&sc->reg_lock);
10088                 if (hw_off_limits(sc))
10089                         rc = ENXIO;
10090                 else {
10091                         cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10092                         cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10093                 }
10094                 mtx_unlock(&sc->reg_lock);
10095                 if (rc != 0)
10096                         break;
10097
10098                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
10099                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10100                             "%012jx %06x %06x    -    -   %3c"
10101                             "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10102                             addr[1], addr[2], addr[3], addr[4], addr[5],
10103                             (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10104                             port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10105                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10106                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10107                 } else {
10108                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10109                             "%012jx    -       -   ", i, addr[0], addr[1],
10110                             addr[2], addr[3], addr[4], addr[5],
10111                             (uintmax_t)mask);
10112
10113                         if (vlan_vld)
10114                                 sbuf_printf(sb, "%4u   Y     ", ivlan);
10115                         else
10116                                 sbuf_printf(sb, "  -    N     ");
10117
10118                         sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10119                             lookup_type ? 'I' : 'O', port_num,
10120                             cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10121                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10122                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10123                 }
10124
10125
10126                 if (cls_lo & F_T6_REPLICATE) {
10127                         struct fw_ldst_cmd ldst_cmd;
10128
10129                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10130                         ldst_cmd.op_to_addrspace =
10131                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10132                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
10133                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10134                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10135                         ldst_cmd.u.mps.rplc.fid_idx =
10136                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10137                                 V_FW_LDST_CMD_IDX(i));
10138
10139                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10140                             "t6mps");
10141                         if (rc)
10142                                 break;
10143                         if (hw_off_limits(sc))
10144                                 rc = ENXIO;
10145                         else
10146                                 rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10147                                     sizeof(ldst_cmd), &ldst_cmd);
10148                         end_synchronized_op(sc, 0);
10149                         if (rc != 0)
10150                                 break;
10151                         else {
10152                                 sbuf_printf(sb, " %08x %08x %08x %08x"
10153                                     " %08x %08x %08x %08x",
10154                                     be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10155                                     be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10156                                     be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10157                                     be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10158                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10159                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10160                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10161                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10162                         }
10163                 } else
10164                         sbuf_printf(sb, "%72s", "");
10165
10166                 sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10167                     G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10168                     G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10169                     (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10170         }
10171
10172         if (rc)
10173                 (void) sbuf_finish(sb);
10174         else
10175                 rc = sbuf_finish(sb);
10176         sbuf_delete(sb);
10177
10178         return (rc);
10179 }
10180
10181 static int
10182 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10183 {
10184         struct adapter *sc = arg1;
10185         struct sbuf *sb;
10186         int rc;
10187         uint16_t mtus[NMTUS];
10188
10189         rc = sysctl_wire_old_buffer(req, 0);
10190         if (rc != 0)
10191                 return (rc);
10192
10193         mtx_lock(&sc->reg_lock);
10194         if (hw_off_limits(sc))
10195                 rc = ENXIO;
10196         else
10197                 t4_read_mtu_tbl(sc, mtus, NULL);
10198         mtx_unlock(&sc->reg_lock);
10199         if (rc != 0)
10200                 return (rc);
10201
10202         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10203         if (sb == NULL)
10204                 return (ENOMEM);
10205
10206         sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10207             mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10208             mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10209             mtus[14], mtus[15]);
10210
10211         rc = sbuf_finish(sb);
10212         sbuf_delete(sb);
10213
10214         return (rc);
10215 }
10216
10217 static int
10218 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10219 {
10220         struct adapter *sc = arg1;
10221         struct sbuf *sb;
10222         int rc, i;
10223         uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10224         uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10225         static const char *tx_stats[MAX_PM_NSTATS] = {
10226                 "Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10227                 "Tx FIFO wait", NULL, "Tx latency"
10228         };
10229         static const char *rx_stats[MAX_PM_NSTATS] = {
10230                 "Read:", "Write bypass:", "Write mem:", "Flush:",
10231                 "Rx FIFO wait", NULL, "Rx latency"
10232         };
10233
10234         rc = sysctl_wire_old_buffer(req, 0);
10235         if (rc != 0)
10236                 return (rc);
10237
10238         mtx_lock(&sc->reg_lock);
10239         if (hw_off_limits(sc))
10240                 rc = ENXIO;
10241         else {
10242                 t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10243                 t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10244         }
10245         mtx_unlock(&sc->reg_lock);
10246         if (rc != 0)
10247                 return (rc);
10248
10249         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10250         if (sb == NULL)
10251                 return (ENOMEM);
10252
10253         sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10254         for (i = 0; i < 4; i++) {
10255                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10256                     tx_cyc[i]);
10257         }
10258
10259         sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10260         for (i = 0; i < 4; i++) {
10261                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10262                     rx_cyc[i]);
10263         }
10264
10265         if (chip_id(sc) > CHELSIO_T5) {
10266                 sbuf_printf(sb,
10267                     "\n              Total wait      Total occupancy");
10268                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10269                     tx_cyc[i]);
10270                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10271                     rx_cyc[i]);
10272
10273                 i += 2;
10274                 MPASS(i < nitems(tx_stats));
10275
10276                 sbuf_printf(sb,
10277                     "\n                   Reads           Total wait");
10278                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10279                     tx_cyc[i]);
10280                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10281                     rx_cyc[i]);
10282         }
10283
10284         rc = sbuf_finish(sb);
10285         sbuf_delete(sb);
10286
10287         return (rc);
10288 }
10289
10290 static int
10291 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10292 {
10293         struct adapter *sc = arg1;
10294         struct sbuf *sb;
10295         int rc;
10296         struct tp_rdma_stats stats;
10297
10298         rc = sysctl_wire_old_buffer(req, 0);
10299         if (rc != 0)
10300                 return (rc);
10301
10302         mtx_lock(&sc->reg_lock);
10303         if (hw_off_limits(sc))
10304                 rc = ENXIO;
10305         else
10306                 t4_tp_get_rdma_stats(sc, &stats, 0);
10307         mtx_unlock(&sc->reg_lock);
10308         if (rc != 0)
10309                 return (rc);
10310
10311         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10312         if (sb == NULL)
10313                 return (ENOMEM);
10314
10315         sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10316         sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10317
10318         rc = sbuf_finish(sb);
10319         sbuf_delete(sb);
10320
10321         return (rc);
10322 }
10323
10324 static int
10325 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10326 {
10327         struct adapter *sc = arg1;
10328         struct sbuf *sb;
10329         int rc;
10330         struct tp_tcp_stats v4, v6;
10331
10332         rc = sysctl_wire_old_buffer(req, 0);
10333         if (rc != 0)
10334                 return (rc);
10335
10336         mtx_lock(&sc->reg_lock);
10337         if (hw_off_limits(sc))
10338                 rc = ENXIO;
10339         else
10340                 t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10341         mtx_unlock(&sc->reg_lock);
10342         if (rc != 0)
10343                 return (rc);
10344
10345         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10346         if (sb == NULL)
10347                 return (ENOMEM);
10348
10349         sbuf_printf(sb,
10350             "                                IP                 IPv6\n");
10351         sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10352             v4.tcp_out_rsts, v6.tcp_out_rsts);
10353         sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10354             v4.tcp_in_segs, v6.tcp_in_segs);
10355         sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10356             v4.tcp_out_segs, v6.tcp_out_segs);
10357         sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10358             v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10359
10360         rc = sbuf_finish(sb);
10361         sbuf_delete(sb);
10362
10363         return (rc);
10364 }
10365
10366 static int
10367 sysctl_tids(SYSCTL_HANDLER_ARGS)
10368 {
10369         struct adapter *sc = arg1;
10370         struct sbuf *sb;
10371         int rc;
10372         uint32_t x, y;
10373         struct tid_info *t = &sc->tids;
10374
10375         rc = sysctl_wire_old_buffer(req, 0);
10376         if (rc != 0)
10377                 return (rc);
10378
10379         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10380         if (sb == NULL)
10381                 return (ENOMEM);
10382
10383         if (t->natids) {
10384                 sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10385                     t->atids_in_use);
10386         }
10387
10388         if (t->nhpftids) {
10389                 sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10390                     t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10391         }
10392
10393         if (t->ntids) {
10394                 bool hashen = false;
10395
10396                 mtx_lock(&sc->reg_lock);
10397                 if (hw_off_limits(sc))
10398                         rc = ENXIO;
10399                 else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10400                         hashen = true;
10401                         if (chip_id(sc) <= CHELSIO_T5) {
10402                                 x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10403                                 y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10404                         } else {
10405                                 x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10406                                 y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10407                         }
10408                 }
10409                 mtx_unlock(&sc->reg_lock);
10410                 if (rc != 0)
10411                         goto done;
10412
10413                 sbuf_printf(sb, "TID range: ");
10414                 if (hashen) {
10415                         if (x)
10416                                 sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10417                         sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10418                 } else {
10419                         sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10420                             t->ntids - 1);
10421                 }
10422                 sbuf_printf(sb, ", in use: %u\n",
10423                     atomic_load_acq_int(&t->tids_in_use));
10424         }
10425
10426         if (t->nstids) {
10427                 sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10428                     t->stid_base + t->nstids - 1, t->stids_in_use);
10429         }
10430
10431         if (t->nftids) {
10432                 sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10433                     t->ftid_end, t->ftids_in_use);
10434         }
10435
10436         if (t->netids) {
10437                 sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10438                     t->etid_base + t->netids - 1, t->etids_in_use);
10439         }
10440
10441         mtx_lock(&sc->reg_lock);
10442         if (hw_off_limits(sc))
10443                 rc = ENXIO;
10444         else {
10445                 x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10446                 y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10447         }
10448         mtx_unlock(&sc->reg_lock);
10449         if (rc != 0)
10450                 goto done;
10451         sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10452 done:
10453         if (rc == 0)
10454                 rc = sbuf_finish(sb);
10455         else
10456                 (void)sbuf_finish(sb);
10457         sbuf_delete(sb);
10458
10459         return (rc);
10460 }
10461
10462 static int
10463 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10464 {
10465         struct adapter *sc = arg1;
10466         struct sbuf *sb;
10467         int rc;
10468         struct tp_err_stats stats;
10469
10470         rc = sysctl_wire_old_buffer(req, 0);
10471         if (rc != 0)
10472                 return (rc);
10473
10474         mtx_lock(&sc->reg_lock);
10475         if (hw_off_limits(sc))
10476                 rc = ENXIO;
10477         else
10478                 t4_tp_get_err_stats(sc, &stats, 0);
10479         mtx_unlock(&sc->reg_lock);
10480         if (rc != 0)
10481                 return (rc);
10482
10483         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10484         if (sb == NULL)
10485                 return (ENOMEM);
10486
10487         if (sc->chip_params->nchan > 2) {
10488                 sbuf_printf(sb, "                 channel 0  channel 1"
10489                     "  channel 2  channel 3\n");
10490                 sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10491                     stats.mac_in_errs[0], stats.mac_in_errs[1],
10492                     stats.mac_in_errs[2], stats.mac_in_errs[3]);
10493                 sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10494                     stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10495                     stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10496                 sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10497                     stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10498                     stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10499                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10500                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10501                     stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10502                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10503                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10504                     stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10505                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10506                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10507                     stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10508                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10509                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10510                     stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10511                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10512                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10513                     stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10514         } else {
10515                 sbuf_printf(sb, "                 channel 0  channel 1\n");
10516                 sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10517                     stats.mac_in_errs[0], stats.mac_in_errs[1]);
10518                 sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10519                     stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10520                 sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10521                     stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10522                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10523                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10524                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10525                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10526                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10527                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10528                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10529                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10530                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10531                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10532         }
10533
10534         sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10535             stats.ofld_no_neigh, stats.ofld_cong_defer);
10536
10537         rc = sbuf_finish(sb);
10538         sbuf_delete(sb);
10539
10540         return (rc);
10541 }
10542
10543 static int
10544 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10545 {
10546         struct adapter *sc = arg1;
10547         struct sbuf *sb;
10548         int rc;
10549         struct tp_tnl_stats stats;
10550
10551         rc = sysctl_wire_old_buffer(req, 0);
10552         if (rc != 0)
10553                 return(rc);
10554
10555         mtx_lock(&sc->reg_lock);
10556         if (hw_off_limits(sc))
10557                 rc = ENXIO;
10558         else
10559                 t4_tp_get_tnl_stats(sc, &stats, 1);
10560         mtx_unlock(&sc->reg_lock);
10561         if (rc != 0)
10562                 return (rc);
10563
10564         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10565         if (sb == NULL)
10566                 return (ENOMEM);
10567
10568         if (sc->chip_params->nchan > 2) {
10569                 sbuf_printf(sb, "           channel 0  channel 1"
10570                     "  channel 2  channel 3\n");
10571                 sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10572                     stats.out_pkt[0], stats.out_pkt[1],
10573                     stats.out_pkt[2], stats.out_pkt[3]);
10574                 sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10575                     stats.in_pkt[0], stats.in_pkt[1],
10576                     stats.in_pkt[2], stats.in_pkt[3]);
10577         } else {
10578                 sbuf_printf(sb, "           channel 0  channel 1\n");
10579                 sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10580                     stats.out_pkt[0], stats.out_pkt[1]);
10581                 sbuf_printf(sb, "InPkts:   %10u %10u",
10582                     stats.in_pkt[0], stats.in_pkt[1]);
10583         }
10584
10585         rc = sbuf_finish(sb);
10586         sbuf_delete(sb);
10587
10588         return (rc);
10589 }
10590
10591 static int
10592 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10593 {
10594         struct adapter *sc = arg1;
10595         struct tp_params *tpp = &sc->params.tp;
10596         u_int mask;
10597         int rc;
10598
10599         mask = tpp->la_mask >> 16;
10600         rc = sysctl_handle_int(oidp, &mask, 0, req);
10601         if (rc != 0 || req->newptr == NULL)
10602                 return (rc);
10603         if (mask > 0xffff)
10604                 return (EINVAL);
10605         mtx_lock(&sc->reg_lock);
10606         if (hw_off_limits(sc))
10607                 rc = ENXIO;
10608         else {
10609                 tpp->la_mask = mask << 16;
10610                 t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10611                     tpp->la_mask);
10612         }
10613         mtx_unlock(&sc->reg_lock);
10614
10615         return (rc);
10616 }
10617
10618 struct field_desc {
10619         const char *name;
10620         u_int start;
10621         u_int width;
10622 };
10623
10624 static void
10625 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10626 {
10627         char buf[32];
10628         int line_size = 0;
10629
10630         while (f->name) {
10631                 uint64_t mask = (1ULL << f->width) - 1;
10632                 int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10633                     ((uintmax_t)v >> f->start) & mask);
10634
10635                 if (line_size + len >= 79) {
10636                         line_size = 8;
10637                         sbuf_printf(sb, "\n        ");
10638                 }
10639                 sbuf_printf(sb, "%s ", buf);
10640                 line_size += len + 1;
10641                 f++;
10642         }
10643         sbuf_printf(sb, "\n");
10644 }
10645
10646 static const struct field_desc tp_la0[] = {
10647         { "RcfOpCodeOut", 60, 4 },
10648         { "State", 56, 4 },
10649         { "WcfState", 52, 4 },
10650         { "RcfOpcSrcOut", 50, 2 },
10651         { "CRxError", 49, 1 },
10652         { "ERxError", 48, 1 },
10653         { "SanityFailed", 47, 1 },
10654         { "SpuriousMsg", 46, 1 },
10655         { "FlushInputMsg", 45, 1 },
10656         { "FlushInputCpl", 44, 1 },
10657         { "RssUpBit", 43, 1 },
10658         { "RssFilterHit", 42, 1 },
10659         { "Tid", 32, 10 },
10660         { "InitTcb", 31, 1 },
10661         { "LineNumber", 24, 7 },
10662         { "Emsg", 23, 1 },
10663         { "EdataOut", 22, 1 },
10664         { "Cmsg", 21, 1 },
10665         { "CdataOut", 20, 1 },
10666         { "EreadPdu", 19, 1 },
10667         { "CreadPdu", 18, 1 },
10668         { "TunnelPkt", 17, 1 },
10669         { "RcfPeerFin", 16, 1 },
10670         { "RcfReasonOut", 12, 4 },
10671         { "TxCchannel", 10, 2 },
10672         { "RcfTxChannel", 8, 2 },
10673         { "RxEchannel", 6, 2 },
10674         { "RcfRxChannel", 5, 1 },
10675         { "RcfDataOutSrdy", 4, 1 },
10676         { "RxDvld", 3, 1 },
10677         { "RxOoDvld", 2, 1 },
10678         { "RxCongestion", 1, 1 },
10679         { "TxCongestion", 0, 1 },
10680         { NULL }
10681 };
10682
10683 static const struct field_desc tp_la1[] = {
10684         { "CplCmdIn", 56, 8 },
10685         { "CplCmdOut", 48, 8 },
10686         { "ESynOut", 47, 1 },
10687         { "EAckOut", 46, 1 },
10688         { "EFinOut", 45, 1 },
10689         { "ERstOut", 44, 1 },
10690         { "SynIn", 43, 1 },
10691         { "AckIn", 42, 1 },
10692         { "FinIn", 41, 1 },
10693         { "RstIn", 40, 1 },
10694         { "DataIn", 39, 1 },
10695         { "DataInVld", 38, 1 },
10696         { "PadIn", 37, 1 },
10697         { "RxBufEmpty", 36, 1 },
10698         { "RxDdp", 35, 1 },
10699         { "RxFbCongestion", 34, 1 },
10700         { "TxFbCongestion", 33, 1 },
10701         { "TxPktSumSrdy", 32, 1 },
10702         { "RcfUlpType", 28, 4 },
10703         { "Eread", 27, 1 },
10704         { "Ebypass", 26, 1 },
10705         { "Esave", 25, 1 },
10706         { "Static0", 24, 1 },
10707         { "Cread", 23, 1 },
10708         { "Cbypass", 22, 1 },
10709         { "Csave", 21, 1 },
10710         { "CPktOut", 20, 1 },
10711         { "RxPagePoolFull", 18, 2 },
10712         { "RxLpbkPkt", 17, 1 },
10713         { "TxLpbkPkt", 16, 1 },
10714         { "RxVfValid", 15, 1 },
10715         { "SynLearned", 14, 1 },
10716         { "SetDelEntry", 13, 1 },
10717         { "SetInvEntry", 12, 1 },
10718         { "CpcmdDvld", 11, 1 },
10719         { "CpcmdSave", 10, 1 },
10720         { "RxPstructsFull", 8, 2 },
10721         { "EpcmdDvld", 7, 1 },
10722         { "EpcmdFlush", 6, 1 },
10723         { "EpcmdTrimPrefix", 5, 1 },
10724         { "EpcmdTrimPostfix", 4, 1 },
10725         { "ERssIp4Pkt", 3, 1 },
10726         { "ERssIp6Pkt", 2, 1 },
10727         { "ERssTcpUdpPkt", 1, 1 },
10728         { "ERssFceFipPkt", 0, 1 },
10729         { NULL }
10730 };
10731
10732 static const struct field_desc tp_la2[] = {
10733         { "CplCmdIn", 56, 8 },
10734         { "MpsVfVld", 55, 1 },
10735         { "MpsPf", 52, 3 },
10736         { "MpsVf", 44, 8 },
10737         { "SynIn", 43, 1 },
10738         { "AckIn", 42, 1 },
10739         { "FinIn", 41, 1 },
10740         { "RstIn", 40, 1 },
10741         { "DataIn", 39, 1 },
10742         { "DataInVld", 38, 1 },
10743         { "PadIn", 37, 1 },
10744         { "RxBufEmpty", 36, 1 },
10745         { "RxDdp", 35, 1 },
10746         { "RxFbCongestion", 34, 1 },
10747         { "TxFbCongestion", 33, 1 },
10748         { "TxPktSumSrdy", 32, 1 },
10749         { "RcfUlpType", 28, 4 },
10750         { "Eread", 27, 1 },
10751         { "Ebypass", 26, 1 },
10752         { "Esave", 25, 1 },
10753         { "Static0", 24, 1 },
10754         { "Cread", 23, 1 },
10755         { "Cbypass", 22, 1 },
10756         { "Csave", 21, 1 },
10757         { "CPktOut", 20, 1 },
10758         { "RxPagePoolFull", 18, 2 },
10759         { "RxLpbkPkt", 17, 1 },
10760         { "TxLpbkPkt", 16, 1 },
10761         { "RxVfValid", 15, 1 },
10762         { "SynLearned", 14, 1 },
10763         { "SetDelEntry", 13, 1 },
10764         { "SetInvEntry", 12, 1 },
10765         { "CpcmdDvld", 11, 1 },
10766         { "CpcmdSave", 10, 1 },
10767         { "RxPstructsFull", 8, 2 },
10768         { "EpcmdDvld", 7, 1 },
10769         { "EpcmdFlush", 6, 1 },
10770         { "EpcmdTrimPrefix", 5, 1 },
10771         { "EpcmdTrimPostfix", 4, 1 },
10772         { "ERssIp4Pkt", 3, 1 },
10773         { "ERssIp6Pkt", 2, 1 },
10774         { "ERssTcpUdpPkt", 1, 1 },
10775         { "ERssFceFipPkt", 0, 1 },
10776         { NULL }
10777 };
10778
10779 static void
10780 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10781 {
10782
10783         field_desc_show(sb, *p, tp_la0);
10784 }
10785
10786 static void
10787 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10788 {
10789
10790         if (idx)
10791                 sbuf_printf(sb, "\n");
10792         field_desc_show(sb, p[0], tp_la0);
10793         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10794                 field_desc_show(sb, p[1], tp_la0);
10795 }
10796
10797 static void
10798 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10799 {
10800
10801         if (idx)
10802                 sbuf_printf(sb, "\n");
10803         field_desc_show(sb, p[0], tp_la0);
10804         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10805                 field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10806 }
10807
10808 static int
10809 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10810 {
10811         struct adapter *sc = arg1;
10812         struct sbuf *sb;
10813         uint64_t *buf, *p;
10814         int rc;
10815         u_int i, inc;
10816         void (*show_func)(struct sbuf *, uint64_t *, int);
10817
10818         rc = sysctl_wire_old_buffer(req, 0);
10819         if (rc != 0)
10820                 return (rc);
10821
10822         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10823         if (sb == NULL)
10824                 return (ENOMEM);
10825
10826         buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10827
10828         mtx_lock(&sc->reg_lock);
10829         if (hw_off_limits(sc))
10830                 rc = ENXIO;
10831         else {
10832                 t4_tp_read_la(sc, buf, NULL);
10833                 switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10834                 case 2:
10835                         inc = 2;
10836                         show_func = tp_la_show2;
10837                         break;
10838                 case 3:
10839                         inc = 2;
10840                         show_func = tp_la_show3;
10841                         break;
10842                 default:
10843                         inc = 1;
10844                         show_func = tp_la_show;
10845                 }
10846         }
10847         mtx_unlock(&sc->reg_lock);
10848         if (rc != 0)
10849                 goto done;
10850
10851         p = buf;
10852         for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10853                 (*show_func)(sb, p, i);
10854         rc = sbuf_finish(sb);
10855 done:
10856         sbuf_delete(sb);
10857         free(buf, M_CXGBE);
10858         return (rc);
10859 }
10860
10861 static int
10862 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10863 {
10864         struct adapter *sc = arg1;
10865         struct sbuf *sb;
10866         int rc;
10867         u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10868
10869         rc = sysctl_wire_old_buffer(req, 0);
10870         if (rc != 0)
10871                 return (rc);
10872
10873         mtx_lock(&sc->reg_lock);
10874         if (hw_off_limits(sc))
10875                 rc = ENXIO;
10876         else
10877                 t4_get_chan_txrate(sc, nrate, orate);
10878         mtx_unlock(&sc->reg_lock);
10879         if (rc != 0)
10880                 return (rc);
10881
10882         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10883         if (sb == NULL)
10884                 return (ENOMEM);
10885
10886         if (sc->chip_params->nchan > 2) {
10887                 sbuf_printf(sb, "              channel 0   channel 1"
10888                     "   channel 2   channel 3\n");
10889                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10890                     nrate[0], nrate[1], nrate[2], nrate[3]);
10891                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10892                     orate[0], orate[1], orate[2], orate[3]);
10893         } else {
10894                 sbuf_printf(sb, "              channel 0   channel 1\n");
10895                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10896                     nrate[0], nrate[1]);
10897                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10898                     orate[0], orate[1]);
10899         }
10900
10901         rc = sbuf_finish(sb);
10902         sbuf_delete(sb);
10903
10904         return (rc);
10905 }
10906
10907 static int
10908 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
10909 {
10910         struct adapter *sc = arg1;
10911         struct sbuf *sb;
10912         uint32_t *buf, *p;
10913         int rc, i;
10914
10915         rc = sysctl_wire_old_buffer(req, 0);
10916         if (rc != 0)
10917                 return (rc);
10918
10919         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10920         if (sb == NULL)
10921                 return (ENOMEM);
10922
10923         buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
10924             M_ZERO | M_WAITOK);
10925
10926         mtx_lock(&sc->reg_lock);
10927         if (hw_off_limits(sc))
10928                 rc = ENXIO;
10929         else
10930                 t4_ulprx_read_la(sc, buf);
10931         mtx_unlock(&sc->reg_lock);
10932         if (rc != 0)
10933                 goto done;
10934
10935         p = buf;
10936         sbuf_printf(sb, "      Pcmd        Type   Message"
10937             "                Data");
10938         for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
10939                 sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
10940                     p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
10941         }
10942         rc = sbuf_finish(sb);
10943 done:
10944         sbuf_delete(sb);
10945         free(buf, M_CXGBE);
10946         return (rc);
10947 }
10948
10949 static int
10950 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
10951 {
10952         struct adapter *sc = arg1;
10953         struct sbuf *sb;
10954         int rc;
10955         uint32_t cfg, s1, s2;
10956
10957         MPASS(chip_id(sc) >= CHELSIO_T5);
10958
10959         rc = sysctl_wire_old_buffer(req, 0);
10960         if (rc != 0)
10961                 return (rc);
10962
10963         mtx_lock(&sc->reg_lock);
10964         if (hw_off_limits(sc))
10965                 rc = ENXIO;
10966         else {
10967                 cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
10968                 s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
10969                 s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
10970         }
10971         mtx_unlock(&sc->reg_lock);
10972         if (rc != 0)
10973                 return (rc);
10974
10975         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10976         if (sb == NULL)
10977                 return (ENOMEM);
10978
10979         if (G_STATSOURCE_T5(cfg) == 7) {
10980                 int mode;
10981
10982                 mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
10983                 if (mode == 0)
10984                         sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
10985                 else if (mode == 1)
10986                         sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
10987                 else
10988                         sbuf_printf(sb, "unknown mode %d", mode);
10989         }
10990         rc = sbuf_finish(sb);
10991         sbuf_delete(sb);
10992
10993         return (rc);
10994 }
10995
10996 static int
10997 sysctl_cpus(SYSCTL_HANDLER_ARGS)
10998 {
10999         struct adapter *sc = arg1;
11000         enum cpu_sets op = arg2;
11001         cpuset_t cpuset;
11002         struct sbuf *sb;
11003         int i, rc;
11004
11005         MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11006
11007         CPU_ZERO(&cpuset);
11008         rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11009         if (rc != 0)
11010                 return (rc);
11011
11012         rc = sysctl_wire_old_buffer(req, 0);
11013         if (rc != 0)
11014                 return (rc);
11015
11016         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11017         if (sb == NULL)
11018                 return (ENOMEM);
11019
11020         CPU_FOREACH(i)
11021                 sbuf_printf(sb, "%d ", i);
11022         rc = sbuf_finish(sb);
11023         sbuf_delete(sb);
11024
11025         return (rc);
11026 }
11027
11028 static int
11029 sysctl_reset(SYSCTL_HANDLER_ARGS)
11030 {
11031         struct adapter *sc = arg1;
11032         u_int val;
11033         int rc;
11034
11035         val = sc->num_resets;
11036         rc = sysctl_handle_int(oidp, &val, 0, req);
11037         if (rc != 0 || req->newptr == NULL)
11038                 return (rc);
11039
11040         if (val == 0) {
11041                 /* Zero out the counter that tracks reset. */
11042                 sc->num_resets = 0;
11043                 return (0);
11044         }
11045
11046         if (val != 1)
11047                 return (EINVAL);        /* 0 or 1 are the only legal values */
11048
11049         if (hw_off_limits(sc))          /* harmless race */
11050                 return (EALREADY);
11051
11052         taskqueue_enqueue(reset_tq, &sc->reset_task);
11053         return (0);
11054 }
11055
11056 #ifdef TCP_OFFLOAD
11057 static int
11058 sysctl_tls(SYSCTL_HANDLER_ARGS)
11059 {
11060         struct adapter *sc = arg1;
11061         int i, j, v, rc;
11062         struct vi_info *vi;
11063
11064         v = sc->tt.tls;
11065         rc = sysctl_handle_int(oidp, &v, 0, req);
11066         if (rc != 0 || req->newptr == NULL)
11067                 return (rc);
11068
11069         if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11070                 return (ENOTSUP);
11071
11072         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11073         if (rc)
11074                 return (rc);
11075         if (hw_off_limits(sc))
11076                 rc = ENXIO;
11077         else {
11078                 sc->tt.tls = !!v;
11079                 for_each_port(sc, i) {
11080                         for_each_vi(sc->port[i], j, vi) {
11081                                 if (vi->flags & VI_INIT_DONE)
11082                                         t4_update_fl_bufsize(vi->ifp);
11083                         }
11084                 }
11085         }
11086         end_synchronized_op(sc, 0);
11087
11088         return (rc);
11089
11090 }
11091
11092 static int
11093 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
11094 {
11095         struct adapter *sc = arg1;
11096         int *old_ports, *new_ports;
11097         int i, new_count, rc;
11098
11099         if (req->newptr == NULL && req->oldptr == NULL)
11100                 return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
11101                     sizeof(sc->tt.tls_rx_ports[0])));
11102
11103         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
11104         if (rc)
11105                 return (rc);
11106
11107         if (hw_off_limits(sc)) {
11108                 rc = ENXIO;
11109                 goto done;
11110         }
11111
11112         if (sc->tt.num_tls_rx_ports == 0) {
11113                 i = -1;
11114                 rc = SYSCTL_OUT(req, &i, sizeof(i));
11115         } else
11116                 rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
11117                     sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
11118         if (rc == 0 && req->newptr != NULL) {
11119                 new_count = req->newlen / sizeof(new_ports[0]);
11120                 new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
11121                     M_WAITOK);
11122                 rc = SYSCTL_IN(req, new_ports, new_count *
11123                     sizeof(new_ports[0]));
11124                 if (rc)
11125                         goto err;
11126
11127                 /* Allow setting to a single '-1' to clear the list. */
11128                 if (new_count == 1 && new_ports[0] == -1) {
11129                         ADAPTER_LOCK(sc);
11130                         old_ports = sc->tt.tls_rx_ports;
11131                         sc->tt.tls_rx_ports = NULL;
11132                         sc->tt.num_tls_rx_ports = 0;
11133                         ADAPTER_UNLOCK(sc);
11134                         free(old_ports, M_CXGBE);
11135                 } else {
11136                         for (i = 0; i < new_count; i++) {
11137                                 if (new_ports[i] < 1 ||
11138                                     new_ports[i] > IPPORT_MAX) {
11139                                         rc = EINVAL;
11140                                         goto err;
11141                                 }
11142                         }
11143
11144                         ADAPTER_LOCK(sc);
11145                         old_ports = sc->tt.tls_rx_ports;
11146                         sc->tt.tls_rx_ports = new_ports;
11147                         sc->tt.num_tls_rx_ports = new_count;
11148                         ADAPTER_UNLOCK(sc);
11149                         free(old_ports, M_CXGBE);
11150                         new_ports = NULL;
11151                 }
11152         err:
11153                 free(new_ports, M_CXGBE);
11154         }
11155 done:
11156         end_synchronized_op(sc, 0);
11157         return (rc);
11158 }
11159
11160 static int
11161 sysctl_tls_rx_timeout(SYSCTL_HANDLER_ARGS)
11162 {
11163         struct adapter *sc = arg1;
11164         int v, rc;
11165
11166         v = sc->tt.tls_rx_timeout;
11167         rc = sysctl_handle_int(oidp, &v, 0, req);
11168         if (rc != 0 || req->newptr == NULL)
11169                 return (rc);
11170
11171         if (v < 0)
11172                 return (EINVAL);
11173
11174         if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11175                 return (ENOTSUP);
11176
11177         sc->tt.tls_rx_timeout = v;
11178
11179         return (0);
11180
11181 }
11182
11183 static void
11184 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11185 {
11186         u_int rem = val % factor;
11187
11188         if (rem == 0)
11189                 snprintf(buf, len, "%u", val / factor);
11190         else {
11191                 while (rem % 10 == 0)
11192                         rem /= 10;
11193                 snprintf(buf, len, "%u.%u", val / factor, rem);
11194         }
11195 }
11196
11197 static int
11198 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11199 {
11200         struct adapter *sc = arg1;
11201         char buf[16];
11202         u_int res, re;
11203         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11204
11205         mtx_lock(&sc->reg_lock);
11206         if (hw_off_limits(sc))
11207                 res = (u_int)-1;
11208         else
11209                 res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11210         mtx_unlock(&sc->reg_lock);
11211         if (res == (u_int)-1)
11212                 return (ENXIO);
11213
11214         switch (arg2) {
11215         case 0:
11216                 /* timer_tick */
11217                 re = G_TIMERRESOLUTION(res);
11218                 break;
11219         case 1:
11220                 /* TCP timestamp tick */
11221                 re = G_TIMESTAMPRESOLUTION(res);
11222                 break;
11223         case 2:
11224                 /* DACK tick */
11225                 re = G_DELAYEDACKRESOLUTION(res);
11226                 break;
11227         default:
11228                 return (EDOOFUS);
11229         }
11230
11231         unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11232
11233         return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11234 }
11235
11236 static int
11237 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11238 {
11239         struct adapter *sc = arg1;
11240         int rc;
11241         u_int dack_tmr, dack_re, v;
11242         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11243
11244         mtx_lock(&sc->reg_lock);
11245         if (hw_off_limits(sc))
11246                 rc = ENXIO;
11247         else {
11248                 rc = 0;
11249                 dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11250                     A_TP_TIMER_RESOLUTION));
11251                 dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11252         }
11253         mtx_unlock(&sc->reg_lock);
11254         if (rc != 0)
11255                 return (rc);
11256
11257         v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11258
11259         return (sysctl_handle_int(oidp, &v, 0, req));
11260 }
11261
11262 static int
11263 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11264 {
11265         struct adapter *sc = arg1;
11266         int rc, reg = arg2;
11267         u_int tre;
11268         u_long tp_tick_us, v;
11269         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11270
11271         MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11272             reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11273             reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11274             reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11275
11276         mtx_lock(&sc->reg_lock);
11277         if (hw_off_limits(sc))
11278                 rc = ENXIO;
11279         else {
11280                 rc = 0;
11281                 tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11282                 tp_tick_us = (cclk_ps << tre) / 1000000;
11283                 if (reg == A_TP_INIT_SRTT)
11284                         v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11285                 else
11286                         v = tp_tick_us * t4_read_reg(sc, reg);
11287         }
11288         mtx_unlock(&sc->reg_lock);
11289         if (rc != 0)
11290                 return (rc);
11291         else
11292                 return (sysctl_handle_long(oidp, &v, 0, req));
11293 }
11294
11295 /*
11296  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11297  * passed to this function.
11298  */
11299 static int
11300 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11301 {
11302         struct adapter *sc = arg1;
11303         int rc, idx = arg2;
11304         u_int v;
11305
11306         MPASS(idx >= 0 && idx <= 24);
11307
11308         mtx_lock(&sc->reg_lock);
11309         if (hw_off_limits(sc))
11310                 rc = ENXIO;
11311         else {
11312                 rc = 0;
11313                 v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11314         }
11315         mtx_unlock(&sc->reg_lock);
11316         if (rc != 0)
11317                 return (rc);
11318         else
11319                 return (sysctl_handle_int(oidp, &v, 0, req));
11320 }
11321
11322 static int
11323 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11324 {
11325         struct adapter *sc = arg1;
11326         int rc, idx = arg2;
11327         u_int shift, v, r;
11328
11329         MPASS(idx >= 0 && idx < 16);
11330
11331         r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11332         shift = (idx & 3) << 3;
11333         mtx_lock(&sc->reg_lock);
11334         if (hw_off_limits(sc))
11335                 rc = ENXIO;
11336         else {
11337                 rc = 0;
11338                 v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11339         }
11340         mtx_unlock(&sc->reg_lock);
11341         if (rc != 0)
11342                 return (rc);
11343         else
11344                 return (sysctl_handle_int(oidp, &v, 0, req));
11345 }
11346
11347 static int
11348 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11349 {
11350         struct vi_info *vi = arg1;
11351         struct adapter *sc = vi->adapter;
11352         int idx, rc, i;
11353         struct sge_ofld_rxq *ofld_rxq;
11354         uint8_t v;
11355
11356         idx = vi->ofld_tmr_idx;
11357
11358         rc = sysctl_handle_int(oidp, &idx, 0, req);
11359         if (rc != 0 || req->newptr == NULL)
11360                 return (rc);
11361
11362         if (idx < 0 || idx >= SGE_NTIMERS)
11363                 return (EINVAL);
11364
11365         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11366             "t4otmr");
11367         if (rc)
11368                 return (rc);
11369
11370         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11371         for_each_ofld_rxq(vi, i, ofld_rxq) {
11372 #ifdef atomic_store_rel_8
11373                 atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11374 #else
11375                 ofld_rxq->iq.intr_params = v;
11376 #endif
11377         }
11378         vi->ofld_tmr_idx = idx;
11379
11380         end_synchronized_op(sc, LOCK_HELD);
11381         return (0);
11382 }
11383
11384 static int
11385 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11386 {
11387         struct vi_info *vi = arg1;
11388         struct adapter *sc = vi->adapter;
11389         int idx, rc;
11390
11391         idx = vi->ofld_pktc_idx;
11392
11393         rc = sysctl_handle_int(oidp, &idx, 0, req);
11394         if (rc != 0 || req->newptr == NULL)
11395                 return (rc);
11396
11397         if (idx < -1 || idx >= SGE_NCOUNTERS)
11398                 return (EINVAL);
11399
11400         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11401             "t4opktc");
11402         if (rc)
11403                 return (rc);
11404
11405         if (vi->flags & VI_INIT_DONE)
11406                 rc = EBUSY; /* cannot be changed once the queues are created */
11407         else
11408                 vi->ofld_pktc_idx = idx;
11409
11410         end_synchronized_op(sc, LOCK_HELD);
11411         return (rc);
11412 }
11413 #endif
11414
11415 static int
11416 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11417 {
11418         int rc;
11419
11420         if (cntxt->cid > M_CTXTQID)
11421                 return (EINVAL);
11422
11423         if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11424             cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11425                 return (EINVAL);
11426
11427         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11428         if (rc)
11429                 return (rc);
11430
11431         if (hw_off_limits(sc)) {
11432                 rc = ENXIO;
11433                 goto done;
11434         }
11435
11436         if (sc->flags & FW_OK) {
11437                 rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11438                     &cntxt->data[0]);
11439                 if (rc == 0)
11440                         goto done;
11441         }
11442
11443         /*
11444          * Read via firmware failed or wasn't even attempted.  Read directly via
11445          * the backdoor.
11446          */
11447         rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11448 done:
11449         end_synchronized_op(sc, 0);
11450         return (rc);
11451 }
11452
11453 static int
11454 load_fw(struct adapter *sc, struct t4_data *fw)
11455 {
11456         int rc;
11457         uint8_t *fw_data;
11458
11459         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11460         if (rc)
11461                 return (rc);
11462
11463         if (hw_off_limits(sc)) {
11464                 rc = ENXIO;
11465                 goto done;
11466         }
11467
11468         /*
11469          * The firmware, with the sole exception of the memory parity error
11470          * handler, runs from memory and not flash.  It is almost always safe to
11471          * install a new firmware on a running system.  Just set bit 1 in
11472          * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11473          */
11474         if (sc->flags & FULL_INIT_DONE &&
11475             (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11476                 rc = EBUSY;
11477                 goto done;
11478         }
11479
11480         fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11481
11482         rc = copyin(fw->data, fw_data, fw->len);
11483         if (rc == 0)
11484                 rc = -t4_load_fw(sc, fw_data, fw->len);
11485
11486         free(fw_data, M_CXGBE);
11487 done:
11488         end_synchronized_op(sc, 0);
11489         return (rc);
11490 }
11491
11492 static int
11493 load_cfg(struct adapter *sc, struct t4_data *cfg)
11494 {
11495         int rc;
11496         uint8_t *cfg_data = NULL;
11497
11498         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11499         if (rc)
11500                 return (rc);
11501
11502         if (hw_off_limits(sc)) {
11503                 rc = ENXIO;
11504                 goto done;
11505         }
11506
11507         if (cfg->len == 0) {
11508                 /* clear */
11509                 rc = -t4_load_cfg(sc, NULL, 0);
11510                 goto done;
11511         }
11512
11513         cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11514
11515         rc = copyin(cfg->data, cfg_data, cfg->len);
11516         if (rc == 0)
11517                 rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11518
11519         free(cfg_data, M_CXGBE);
11520 done:
11521         end_synchronized_op(sc, 0);
11522         return (rc);
11523 }
11524
11525 static int
11526 load_boot(struct adapter *sc, struct t4_bootrom *br)
11527 {
11528         int rc;
11529         uint8_t *br_data = NULL;
11530         u_int offset;
11531
11532         if (br->len > 1024 * 1024)
11533                 return (EFBIG);
11534
11535         if (br->pf_offset == 0) {
11536                 /* pfidx */
11537                 if (br->pfidx_addr > 7)
11538                         return (EINVAL);
11539                 offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11540                     A_PCIE_PF_EXPROM_OFST)));
11541         } else if (br->pf_offset == 1) {
11542                 /* offset */
11543                 offset = G_OFFSET(br->pfidx_addr);
11544         } else {
11545                 return (EINVAL);
11546         }
11547
11548         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11549         if (rc)
11550                 return (rc);
11551
11552         if (hw_off_limits(sc)) {
11553                 rc = ENXIO;
11554                 goto done;
11555         }
11556
11557         if (br->len == 0) {
11558                 /* clear */
11559                 rc = -t4_load_boot(sc, NULL, offset, 0);
11560                 goto done;
11561         }
11562
11563         br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11564
11565         rc = copyin(br->data, br_data, br->len);
11566         if (rc == 0)
11567                 rc = -t4_load_boot(sc, br_data, offset, br->len);
11568
11569         free(br_data, M_CXGBE);
11570 done:
11571         end_synchronized_op(sc, 0);
11572         return (rc);
11573 }
11574
11575 static int
11576 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11577 {
11578         int rc;
11579         uint8_t *bc_data = NULL;
11580
11581         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11582         if (rc)
11583                 return (rc);
11584
11585         if (hw_off_limits(sc)) {
11586                 rc = ENXIO;
11587                 goto done;
11588         }
11589
11590         if (bc->len == 0) {
11591                 /* clear */
11592                 rc = -t4_load_bootcfg(sc, NULL, 0);
11593                 goto done;
11594         }
11595
11596         bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11597
11598         rc = copyin(bc->data, bc_data, bc->len);
11599         if (rc == 0)
11600                 rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11601
11602         free(bc_data, M_CXGBE);
11603 done:
11604         end_synchronized_op(sc, 0);
11605         return (rc);
11606 }
11607
11608 static int
11609 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11610 {
11611         int rc;
11612         struct cudbg_init *cudbg;
11613         void *handle, *buf;
11614
11615         /* buf is large, don't block if no memory is available */
11616         buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11617         if (buf == NULL)
11618                 return (ENOMEM);
11619
11620         handle = cudbg_alloc_handle();
11621         if (handle == NULL) {
11622                 rc = ENOMEM;
11623                 goto done;
11624         }
11625
11626         cudbg = cudbg_get_init(handle);
11627         cudbg->adap = sc;
11628         cudbg->print = (cudbg_print_cb)printf;
11629
11630 #ifndef notyet
11631         device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11632             __func__, dump->wr_flash, dump->len, dump->data);
11633 #endif
11634
11635         if (dump->wr_flash)
11636                 cudbg->use_flash = 1;
11637         MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11638         memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11639
11640         rc = cudbg_collect(handle, buf, &dump->len);
11641         if (rc != 0)
11642                 goto done;
11643
11644         rc = copyout(buf, dump->data, dump->len);
11645 done:
11646         cudbg_free_handle(handle);
11647         free(buf, M_CXGBE);
11648         return (rc);
11649 }
11650
11651 static void
11652 free_offload_policy(struct t4_offload_policy *op)
11653 {
11654         struct offload_rule *r;
11655         int i;
11656
11657         if (op == NULL)
11658                 return;
11659
11660         r = &op->rule[0];
11661         for (i = 0; i < op->nrules; i++, r++) {
11662                 free(r->bpf_prog.bf_insns, M_CXGBE);
11663         }
11664         free(op->rule, M_CXGBE);
11665         free(op, M_CXGBE);
11666 }
11667
11668 static int
11669 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11670 {
11671         int i, rc, len;
11672         struct t4_offload_policy *op, *old;
11673         struct bpf_program *bf;
11674         const struct offload_settings *s;
11675         struct offload_rule *r;
11676         void *u;
11677
11678         if (!is_offload(sc))
11679                 return (ENODEV);
11680
11681         if (uop->nrules == 0) {
11682                 /* Delete installed policies. */
11683                 op = NULL;
11684                 goto set_policy;
11685         } else if (uop->nrules > 256) { /* arbitrary */
11686                 return (E2BIG);
11687         }
11688
11689         /* Copy userspace offload policy to kernel */
11690         op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11691         op->nrules = uop->nrules;
11692         len = op->nrules * sizeof(struct offload_rule);
11693         op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11694         rc = copyin(uop->rule, op->rule, len);
11695         if (rc) {
11696                 free(op->rule, M_CXGBE);
11697                 free(op, M_CXGBE);
11698                 return (rc);
11699         }
11700
11701         r = &op->rule[0];
11702         for (i = 0; i < op->nrules; i++, r++) {
11703
11704                 /* Validate open_type */
11705                 if (r->open_type != OPEN_TYPE_LISTEN &&
11706                     r->open_type != OPEN_TYPE_ACTIVE &&
11707                     r->open_type != OPEN_TYPE_PASSIVE &&
11708                     r->open_type != OPEN_TYPE_DONTCARE) {
11709 error:
11710                         /*
11711                          * Rules 0 to i have malloc'd filters that need to be
11712                          * freed.  Rules i+1 to nrules have userspace pointers
11713                          * and should be left alone.
11714                          */
11715                         op->nrules = i;
11716                         free_offload_policy(op);
11717                         return (rc);
11718                 }
11719
11720                 /* Validate settings */
11721                 s = &r->settings;
11722                 if ((s->offload != 0 && s->offload != 1) ||
11723                     s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11724                     s->sched_class < -1 ||
11725                     s->sched_class >= sc->params.nsched_cls) {
11726                         rc = EINVAL;
11727                         goto error;
11728                 }
11729
11730                 bf = &r->bpf_prog;
11731                 u = bf->bf_insns;       /* userspace ptr */
11732                 bf->bf_insns = NULL;
11733                 if (bf->bf_len == 0) {
11734                         /* legal, matches everything */
11735                         continue;
11736                 }
11737                 len = bf->bf_len * sizeof(*bf->bf_insns);
11738                 bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11739                 rc = copyin(u, bf->bf_insns, len);
11740                 if (rc != 0)
11741                         goto error;
11742
11743                 if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11744                         rc = EINVAL;
11745                         goto error;
11746                 }
11747         }
11748 set_policy:
11749         rw_wlock(&sc->policy_lock);
11750         old = sc->policy;
11751         sc->policy = op;
11752         rw_wunlock(&sc->policy_lock);
11753         free_offload_policy(old);
11754
11755         return (0);
11756 }
11757
11758 #define MAX_READ_BUF_SIZE (128 * 1024)
11759 static int
11760 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11761 {
11762         uint32_t addr, remaining, n;
11763         uint32_t *buf;
11764         int rc;
11765         uint8_t *dst;
11766
11767         mtx_lock(&sc->reg_lock);
11768         if (hw_off_limits(sc))
11769                 rc = ENXIO;
11770         else
11771                 rc = validate_mem_range(sc, mr->addr, mr->len);
11772         mtx_unlock(&sc->reg_lock);
11773         if (rc != 0)
11774                 return (rc);
11775
11776         buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11777         addr = mr->addr;
11778         remaining = mr->len;
11779         dst = (void *)mr->data;
11780
11781         while (remaining) {
11782                 n = min(remaining, MAX_READ_BUF_SIZE);
11783                 mtx_lock(&sc->reg_lock);
11784                 if (hw_off_limits(sc))
11785                         rc = ENXIO;
11786                 else
11787                         read_via_memwin(sc, 2, addr, buf, n);
11788                 mtx_unlock(&sc->reg_lock);
11789                 if (rc != 0)
11790                         break;
11791
11792                 rc = copyout(buf, dst, n);
11793                 if (rc != 0)
11794                         break;
11795
11796                 dst += n;
11797                 remaining -= n;
11798                 addr += n;
11799         }
11800
11801         free(buf, M_CXGBE);
11802         return (rc);
11803 }
11804 #undef MAX_READ_BUF_SIZE
11805
11806 static int
11807 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11808 {
11809         int rc;
11810
11811         if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11812                 return (EINVAL);
11813
11814         if (i2cd->len > sizeof(i2cd->data))
11815                 return (EFBIG);
11816
11817         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11818         if (rc)
11819                 return (rc);
11820         if (hw_off_limits(sc))
11821                 rc = ENXIO;
11822         else
11823                 rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11824                     i2cd->offset, i2cd->len, &i2cd->data[0]);
11825         end_synchronized_op(sc, 0);
11826
11827         return (rc);
11828 }
11829
11830 static int
11831 clear_stats(struct adapter *sc, u_int port_id)
11832 {
11833         int i, v, chan_map;
11834         struct port_info *pi;
11835         struct vi_info *vi;
11836         struct sge_rxq *rxq;
11837         struct sge_txq *txq;
11838         struct sge_wrq *wrq;
11839 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11840         struct sge_ofld_txq *ofld_txq;
11841 #endif
11842 #ifdef TCP_OFFLOAD
11843         struct sge_ofld_rxq *ofld_rxq;
11844 #endif
11845
11846         if (port_id >= sc->params.nports)
11847                 return (EINVAL);
11848         pi = sc->port[port_id];
11849         if (pi == NULL)
11850                 return (EIO);
11851
11852         mtx_lock(&sc->reg_lock);
11853         if (!hw_off_limits(sc)) {
11854                 /* MAC stats */
11855                 t4_clr_port_stats(sc, pi->tx_chan);
11856                 if (is_t6(sc)) {
11857                         if (pi->fcs_reg != -1)
11858                                 pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11859                         else
11860                                 pi->stats.rx_fcs_err = 0;
11861                 }
11862                 for_each_vi(pi, v, vi) {
11863                         if (vi->flags & VI_INIT_DONE)
11864                                 t4_clr_vi_stats(sc, vi->vin);
11865                 }
11866                 chan_map = pi->rx_e_chan_map;
11867                 v = 0;  /* reuse */
11868                 while (chan_map) {
11869                         i = ffs(chan_map) - 1;
11870                         t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11871                             1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11872                         chan_map &= ~(1 << i);
11873                 }
11874         }
11875         mtx_unlock(&sc->reg_lock);
11876         pi->tx_parse_error = 0;
11877         pi->tnl_cong_drops = 0;
11878
11879         /*
11880          * Since this command accepts a port, clear stats for
11881          * all VIs on this port.
11882          */
11883         for_each_vi(pi, v, vi) {
11884                 if (vi->flags & VI_INIT_DONE) {
11885
11886                         for_each_rxq(vi, i, rxq) {
11887 #if defined(INET) || defined(INET6)
11888                                 rxq->lro.lro_queued = 0;
11889                                 rxq->lro.lro_flushed = 0;
11890 #endif
11891                                 rxq->rxcsum = 0;
11892                                 rxq->vlan_extraction = 0;
11893                                 rxq->vxlan_rxcsum = 0;
11894
11895                                 rxq->fl.cl_allocated = 0;
11896                                 rxq->fl.cl_recycled = 0;
11897                                 rxq->fl.cl_fast_recycled = 0;
11898                         }
11899
11900                         for_each_txq(vi, i, txq) {
11901                                 txq->txcsum = 0;
11902                                 txq->tso_wrs = 0;
11903                                 txq->vlan_insertion = 0;
11904                                 txq->imm_wrs = 0;
11905                                 txq->sgl_wrs = 0;
11906                                 txq->txpkt_wrs = 0;
11907                                 txq->txpkts0_wrs = 0;
11908                                 txq->txpkts1_wrs = 0;
11909                                 txq->txpkts0_pkts = 0;
11910                                 txq->txpkts1_pkts = 0;
11911                                 txq->txpkts_flush = 0;
11912                                 txq->raw_wrs = 0;
11913                                 txq->vxlan_tso_wrs = 0;
11914                                 txq->vxlan_txcsum = 0;
11915                                 txq->kern_tls_records = 0;
11916                                 txq->kern_tls_short = 0;
11917                                 txq->kern_tls_partial = 0;
11918                                 txq->kern_tls_full = 0;
11919                                 txq->kern_tls_octets = 0;
11920                                 txq->kern_tls_waste = 0;
11921                                 txq->kern_tls_options = 0;
11922                                 txq->kern_tls_header = 0;
11923                                 txq->kern_tls_fin = 0;
11924                                 txq->kern_tls_fin_short = 0;
11925                                 txq->kern_tls_cbc = 0;
11926                                 txq->kern_tls_gcm = 0;
11927                                 mp_ring_reset_stats(txq->r);
11928                         }
11929
11930 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11931                         for_each_ofld_txq(vi, i, ofld_txq) {
11932                                 ofld_txq->wrq.tx_wrs_direct = 0;
11933                                 ofld_txq->wrq.tx_wrs_copied = 0;
11934                                 counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11935                                 counter_u64_zero(ofld_txq->tx_iscsi_octets);
11936                                 counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11937                                 counter_u64_zero(ofld_txq->tx_toe_tls_records);
11938                                 counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11939                         }
11940 #endif
11941 #ifdef TCP_OFFLOAD
11942                         for_each_ofld_rxq(vi, i, ofld_rxq) {
11943                                 ofld_rxq->fl.cl_allocated = 0;
11944                                 ofld_rxq->fl.cl_recycled = 0;
11945                                 ofld_rxq->fl.cl_fast_recycled = 0;
11946                                 counter_u64_zero(
11947                                     ofld_rxq->rx_iscsi_ddp_setup_ok);
11948                                 counter_u64_zero(
11949                                     ofld_rxq->rx_iscsi_ddp_setup_error);
11950                                 ofld_rxq->rx_iscsi_ddp_pdus = 0;
11951                                 ofld_rxq->rx_iscsi_ddp_octets = 0;
11952                                 ofld_rxq->rx_iscsi_fl_pdus = 0;
11953                                 ofld_rxq->rx_iscsi_fl_octets = 0;
11954                                 ofld_rxq->rx_toe_tls_records = 0;
11955                                 ofld_rxq->rx_toe_tls_octets = 0;
11956                         }
11957 #endif
11958
11959                         if (IS_MAIN_VI(vi)) {
11960                                 wrq = &sc->sge.ctrlq[pi->port_id];
11961                                 wrq->tx_wrs_direct = 0;
11962                                 wrq->tx_wrs_copied = 0;
11963                         }
11964                 }
11965         }
11966
11967         return (0);
11968 }
11969
11970 static int
11971 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11972 {
11973 #ifdef INET6
11974         struct in6_addr in6;
11975
11976         bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11977         if (t4_get_clip_entry(sc, &in6, true) != NULL)
11978                 return (0);
11979         else
11980                 return (EIO);
11981 #else
11982         return (ENOTSUP);
11983 #endif
11984 }
11985
11986 static int
11987 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11988 {
11989 #ifdef INET6
11990         struct in6_addr in6;
11991
11992         bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11993         return (t4_release_clip_addr(sc, &in6));
11994 #else
11995         return (ENOTSUP);
11996 #endif
11997 }
11998
11999 int
12000 t4_os_find_pci_capability(struct adapter *sc, int cap)
12001 {
12002         int i;
12003
12004         return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12005 }
12006
12007 int
12008 t4_os_pci_save_state(struct adapter *sc)
12009 {
12010         device_t dev;
12011         struct pci_devinfo *dinfo;
12012
12013         dev = sc->dev;
12014         dinfo = device_get_ivars(dev);
12015
12016         pci_cfg_save(dev, dinfo, 0);
12017         return (0);
12018 }
12019
12020 int
12021 t4_os_pci_restore_state(struct adapter *sc)
12022 {
12023         device_t dev;
12024         struct pci_devinfo *dinfo;
12025
12026         dev = sc->dev;
12027         dinfo = device_get_ivars(dev);
12028
12029         pci_cfg_restore(dev, dinfo);
12030         return (0);
12031 }
12032
12033 void
12034 t4_os_portmod_changed(struct port_info *pi)
12035 {
12036         struct adapter *sc = pi->adapter;
12037         struct vi_info *vi;
12038         struct ifnet *ifp;
12039         static const char *mod_str[] = {
12040                 NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12041         };
12042
12043         KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12044             ("%s: port_type %u", __func__, pi->port_type));
12045
12046         vi = &pi->vi[0];
12047         if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12048                 PORT_LOCK(pi);
12049                 build_medialist(pi);
12050                 if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12051                         fixup_link_config(pi);
12052                         apply_link_config(pi);
12053                 }
12054                 PORT_UNLOCK(pi);
12055                 end_synchronized_op(sc, LOCK_HELD);
12056         }
12057
12058         ifp = vi->ifp;
12059         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12060                 if_printf(ifp, "transceiver unplugged.\n");
12061         else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12062                 if_printf(ifp, "unknown transceiver inserted.\n");
12063         else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12064                 if_printf(ifp, "unsupported transceiver inserted.\n");
12065         else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12066                 if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12067                     port_top_speed(pi), mod_str[pi->mod_type]);
12068         } else {
12069                 if_printf(ifp, "transceiver (type %d) inserted.\n",
12070                     pi->mod_type);
12071         }
12072 }
12073
12074 void
12075 t4_os_link_changed(struct port_info *pi)
12076 {
12077         struct vi_info *vi;
12078         struct ifnet *ifp;
12079         struct link_config *lc = &pi->link_cfg;
12080         struct adapter *sc = pi->adapter;
12081         int v;
12082
12083         PORT_LOCK_ASSERT_OWNED(pi);
12084
12085         if (is_t6(sc)) {
12086                 if (lc->link_ok) {
12087                         if (lc->speed > 25000 ||
12088                             (lc->speed == 25000 && lc->fec == FEC_RS)) {
12089                                 pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12090                                     A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12091                         } else {
12092                                 pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12093                                     A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12094                         }
12095                         pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12096                         pi->stats.rx_fcs_err = 0;
12097                 } else {
12098                         pi->fcs_reg = -1;
12099                 }
12100         } else {
12101                 MPASS(pi->fcs_reg != -1);
12102                 MPASS(pi->fcs_base == 0);
12103         }
12104
12105         for_each_vi(pi, v, vi) {
12106                 ifp = vi->ifp;
12107                 if (ifp == NULL)
12108                         continue;
12109
12110                 if (lc->link_ok) {
12111                         ifp->if_baudrate = IF_Mbps(lc->speed);
12112                         if_link_state_change(ifp, LINK_STATE_UP);
12113                 } else {
12114                         if_link_state_change(ifp, LINK_STATE_DOWN);
12115                 }
12116         }
12117 }
12118
12119 void
12120 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12121 {
12122         struct adapter *sc;
12123
12124         sx_slock(&t4_list_lock);
12125         SLIST_FOREACH(sc, &t4_list, link) {
12126                 /*
12127                  * func should not make any assumptions about what state sc is
12128                  * in - the only guarantee is that sc->sc_lock is a valid lock.
12129                  */
12130                 func(sc, arg);
12131         }
12132         sx_sunlock(&t4_list_lock);
12133 }
12134
12135 static int
12136 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12137     struct thread *td)
12138 {
12139         int rc;
12140         struct adapter *sc = dev->si_drv1;
12141
12142         rc = priv_check(td, PRIV_DRIVER);
12143         if (rc != 0)
12144                 return (rc);
12145
12146         switch (cmd) {
12147         case CHELSIO_T4_GETREG: {
12148                 struct t4_reg *edata = (struct t4_reg *)data;
12149
12150                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12151                         return (EFAULT);
12152
12153                 mtx_lock(&sc->reg_lock);
12154                 if (hw_off_limits(sc))
12155                         rc = ENXIO;
12156                 else if (edata->size == 4)
12157                         edata->val = t4_read_reg(sc, edata->addr);
12158                 else if (edata->size == 8)
12159                         edata->val = t4_read_reg64(sc, edata->addr);
12160                 else
12161                         rc = EINVAL;
12162                 mtx_unlock(&sc->reg_lock);
12163
12164                 break;
12165         }
12166         case CHELSIO_T4_SETREG: {
12167                 struct t4_reg *edata = (struct t4_reg *)data;
12168
12169                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12170                         return (EFAULT);
12171
12172                 mtx_lock(&sc->reg_lock);
12173                 if (hw_off_limits(sc))
12174                         rc = ENXIO;
12175                 else if (edata->size == 4) {
12176                         if (edata->val & 0xffffffff00000000)
12177                                 rc = EINVAL;
12178                         t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12179                 } else if (edata->size == 8)
12180                         t4_write_reg64(sc, edata->addr, edata->val);
12181                 else
12182                         rc = EINVAL;
12183                 mtx_unlock(&sc->reg_lock);
12184
12185                 break;
12186         }
12187         case CHELSIO_T4_REGDUMP: {
12188                 struct t4_regdump *regs = (struct t4_regdump *)data;
12189                 int reglen = t4_get_regs_len(sc);
12190                 uint8_t *buf;
12191
12192                 if (regs->len < reglen) {
12193                         regs->len = reglen; /* hint to the caller */
12194                         return (ENOBUFS);
12195                 }
12196
12197                 regs->len = reglen;
12198                 buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12199                 mtx_lock(&sc->reg_lock);
12200                 if (hw_off_limits(sc))
12201                         rc = ENXIO;
12202                 else
12203                         get_regs(sc, regs, buf);
12204                 mtx_unlock(&sc->reg_lock);
12205                 if (rc == 0)
12206                         rc = copyout(buf, regs->data, reglen);
12207                 free(buf, M_CXGBE);
12208                 break;
12209         }
12210         case CHELSIO_T4_GET_FILTER_MODE:
12211                 rc = get_filter_mode(sc, (uint32_t *)data);
12212                 break;
12213         case CHELSIO_T4_SET_FILTER_MODE:
12214                 rc = set_filter_mode(sc, *(uint32_t *)data);
12215                 break;
12216         case CHELSIO_T4_SET_FILTER_MASK:
12217                 rc = set_filter_mask(sc, *(uint32_t *)data);
12218                 break;
12219         case CHELSIO_T4_GET_FILTER:
12220                 rc = get_filter(sc, (struct t4_filter *)data);
12221                 break;
12222         case CHELSIO_T4_SET_FILTER:
12223                 rc = set_filter(sc, (struct t4_filter *)data);
12224                 break;
12225         case CHELSIO_T4_DEL_FILTER:
12226                 rc = del_filter(sc, (struct t4_filter *)data);
12227                 break;
12228         case CHELSIO_T4_GET_SGE_CONTEXT:
12229                 rc = get_sge_context(sc, (struct t4_sge_context *)data);
12230                 break;
12231         case CHELSIO_T4_LOAD_FW:
12232                 rc = load_fw(sc, (struct t4_data *)data);
12233                 break;
12234         case CHELSIO_T4_GET_MEM:
12235                 rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12236                 break;
12237         case CHELSIO_T4_GET_I2C:
12238                 rc = read_i2c(sc, (struct t4_i2c_data *)data);
12239                 break;
12240         case CHELSIO_T4_CLEAR_STATS:
12241                 rc = clear_stats(sc, *(uint32_t *)data);
12242                 break;
12243         case CHELSIO_T4_SCHED_CLASS:
12244                 rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12245                 break;
12246         case CHELSIO_T4_SCHED_QUEUE:
12247                 rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12248                 break;
12249         case CHELSIO_T4_GET_TRACER:
12250                 rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12251                 break;
12252         case CHELSIO_T4_SET_TRACER:
12253                 rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12254                 break;
12255         case CHELSIO_T4_LOAD_CFG:
12256                 rc = load_cfg(sc, (struct t4_data *)data);
12257                 break;
12258         case CHELSIO_T4_LOAD_BOOT:
12259                 rc = load_boot(sc, (struct t4_bootrom *)data);
12260                 break;
12261         case CHELSIO_T4_LOAD_BOOTCFG:
12262                 rc = load_bootcfg(sc, (struct t4_data *)data);
12263                 break;
12264         case CHELSIO_T4_CUDBG_DUMP:
12265                 rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12266                 break;
12267         case CHELSIO_T4_SET_OFLD_POLICY:
12268                 rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12269                 break;
12270         case CHELSIO_T4_HOLD_CLIP_ADDR:
12271                 rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12272                 break;
12273         case CHELSIO_T4_RELEASE_CLIP_ADDR:
12274                 rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12275                 break;
12276         default:
12277                 rc = ENOTTY;
12278         }
12279
12280         return (rc);
12281 }
12282
12283 #ifdef TCP_OFFLOAD
12284 static int
12285 toe_capability(struct vi_info *vi, bool enable)
12286 {
12287         int rc;
12288         struct port_info *pi = vi->pi;
12289         struct adapter *sc = pi->adapter;
12290
12291         ASSERT_SYNCHRONIZED_OP(sc);
12292
12293         if (!is_offload(sc))
12294                 return (ENODEV);
12295         if (hw_off_limits(sc))
12296                 return (ENXIO);
12297
12298         if (enable) {
12299 #ifdef KERN_TLS
12300                 if (sc->flags & KERN_TLS_ON) {
12301                         int i, j, n;
12302                         struct port_info *p;
12303                         struct vi_info *v;
12304
12305                         /*
12306                          * Reconfigure hardware for TOE if TXTLS is not enabled
12307                          * on any ifnet.
12308                          */
12309                         n = 0;
12310                         for_each_port(sc, i) {
12311                                 p = sc->port[i];
12312                                 for_each_vi(p, j, v) {
12313                                         if (v->ifp->if_capenable & IFCAP_TXTLS) {
12314                                                 CH_WARN(sc,
12315                                                     "%s has NIC TLS enabled.\n",
12316                                                     device_get_nameunit(v->dev));
12317                                                 n++;
12318                                         }
12319                                 }
12320                         }
12321                         if (n > 0) {
12322                                 CH_WARN(sc, "Disable NIC TLS on all interfaces "
12323                                     "associated with this adapter before "
12324                                     "trying to enable TOE.\n");
12325                                 return (EAGAIN);
12326                         }
12327                         rc = t4_config_kern_tls(sc, false);
12328                         if (rc)
12329                                 return (rc);
12330                 }
12331 #endif
12332                 if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
12333                         /* TOE is already enabled. */
12334                         return (0);
12335                 }
12336
12337                 /*
12338                  * We need the port's queues around so that we're able to send
12339                  * and receive CPLs to/from the TOE even if the ifnet for this
12340                  * port has never been UP'd administratively.
12341                  */
12342                 if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12343                         return (rc);
12344                 if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12345                     ((rc = vi_init(&pi->vi[0])) != 0))
12346                         return (rc);
12347
12348                 if (isset(&sc->offload_map, pi->port_id)) {
12349                         /* TOE is enabled on another VI of this port. */
12350                         pi->uld_vis++;
12351                         return (0);
12352                 }
12353
12354                 if (!uld_active(sc, ULD_TOM)) {
12355                         rc = t4_activate_uld(sc, ULD_TOM);
12356                         if (rc == EAGAIN) {
12357                                 log(LOG_WARNING,
12358                                     "You must kldload t4_tom.ko before trying "
12359                                     "to enable TOE on a cxgbe interface.\n");
12360                         }
12361                         if (rc != 0)
12362                                 return (rc);
12363                         KASSERT(sc->tom_softc != NULL,
12364                             ("%s: TOM activated but softc NULL", __func__));
12365                         KASSERT(uld_active(sc, ULD_TOM),
12366                             ("%s: TOM activated but flag not set", __func__));
12367                 }
12368
12369                 /* Activate iWARP and iSCSI too, if the modules are loaded. */
12370                 if (!uld_active(sc, ULD_IWARP))
12371                         (void) t4_activate_uld(sc, ULD_IWARP);
12372                 if (!uld_active(sc, ULD_ISCSI))
12373                         (void) t4_activate_uld(sc, ULD_ISCSI);
12374
12375                 pi->uld_vis++;
12376                 setbit(&sc->offload_map, pi->port_id);
12377         } else {
12378                 pi->uld_vis--;
12379
12380                 if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12381                         return (0);
12382
12383                 KASSERT(uld_active(sc, ULD_TOM),
12384                     ("%s: TOM never initialized?", __func__));
12385                 clrbit(&sc->offload_map, pi->port_id);
12386         }
12387
12388         return (0);
12389 }
12390
12391 /*
12392  * Add an upper layer driver to the global list.
12393  */
12394 int
12395 t4_register_uld(struct uld_info *ui)
12396 {
12397         int rc = 0;
12398         struct uld_info *u;
12399
12400         sx_xlock(&t4_uld_list_lock);
12401         SLIST_FOREACH(u, &t4_uld_list, link) {
12402             if (u->uld_id == ui->uld_id) {
12403                     rc = EEXIST;
12404                     goto done;
12405             }
12406         }
12407
12408         SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12409         ui->refcount = 0;
12410 done:
12411         sx_xunlock(&t4_uld_list_lock);
12412         return (rc);
12413 }
12414
12415 int
12416 t4_unregister_uld(struct uld_info *ui)
12417 {
12418         int rc = EINVAL;
12419         struct uld_info *u;
12420
12421         sx_xlock(&t4_uld_list_lock);
12422
12423         SLIST_FOREACH(u, &t4_uld_list, link) {
12424             if (u == ui) {
12425                     if (ui->refcount > 0) {
12426                             rc = EBUSY;
12427                             goto done;
12428                     }
12429
12430                     SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12431                     rc = 0;
12432                     goto done;
12433             }
12434         }
12435 done:
12436         sx_xunlock(&t4_uld_list_lock);
12437         return (rc);
12438 }
12439
12440 int
12441 t4_activate_uld(struct adapter *sc, int id)
12442 {
12443         int rc;
12444         struct uld_info *ui;
12445
12446         ASSERT_SYNCHRONIZED_OP(sc);
12447
12448         if (id < 0 || id > ULD_MAX)
12449                 return (EINVAL);
12450         rc = EAGAIN;    /* kldoad the module with this ULD and try again. */
12451
12452         sx_slock(&t4_uld_list_lock);
12453
12454         SLIST_FOREACH(ui, &t4_uld_list, link) {
12455                 if (ui->uld_id == id) {
12456                         if (!(sc->flags & FULL_INIT_DONE)) {
12457                                 rc = adapter_init(sc);
12458                                 if (rc != 0)
12459                                         break;
12460                         }
12461
12462                         rc = ui->activate(sc);
12463                         if (rc == 0) {
12464                                 setbit(&sc->active_ulds, id);
12465                                 ui->refcount++;
12466                         }
12467                         break;
12468                 }
12469         }
12470
12471         sx_sunlock(&t4_uld_list_lock);
12472
12473         return (rc);
12474 }
12475
12476 int
12477 t4_deactivate_uld(struct adapter *sc, int id)
12478 {
12479         int rc;
12480         struct uld_info *ui;
12481
12482         ASSERT_SYNCHRONIZED_OP(sc);
12483
12484         if (id < 0 || id > ULD_MAX)
12485                 return (EINVAL);
12486         rc = ENXIO;
12487
12488         sx_slock(&t4_uld_list_lock);
12489
12490         SLIST_FOREACH(ui, &t4_uld_list, link) {
12491                 if (ui->uld_id == id) {
12492                         rc = ui->deactivate(sc);
12493                         if (rc == 0) {
12494                                 clrbit(&sc->active_ulds, id);
12495                                 ui->refcount--;
12496                         }
12497                         break;
12498                 }
12499         }
12500
12501         sx_sunlock(&t4_uld_list_lock);
12502
12503         return (rc);
12504 }
12505
12506 static void
12507 t4_async_event(void *arg, int n)
12508 {
12509         struct uld_info *ui;
12510         struct adapter *sc = (struct adapter *)arg;
12511
12512         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12513                 return;
12514         sx_slock(&t4_uld_list_lock);
12515         SLIST_FOREACH(ui, &t4_uld_list, link) {
12516                 if (ui->uld_id == ULD_IWARP) {
12517                         ui->async_event(sc);
12518                         break;
12519                 }
12520         }
12521         sx_sunlock(&t4_uld_list_lock);
12522         end_synchronized_op(sc, 0);
12523 }
12524
12525 int
12526 uld_active(struct adapter *sc, int uld_id)
12527 {
12528
12529         MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12530
12531         return (isset(&sc->active_ulds, uld_id));
12532 }
12533 #endif
12534
12535 #ifdef KERN_TLS
12536 static int
12537 ktls_capability(struct adapter *sc, bool enable)
12538 {
12539         ASSERT_SYNCHRONIZED_OP(sc);
12540
12541         if (!is_ktls(sc))
12542                 return (ENODEV);
12543         if (hw_off_limits(sc))
12544                 return (ENXIO);
12545
12546         if (enable) {
12547                 if (sc->flags & KERN_TLS_ON)
12548                         return (0);     /* already on */
12549                 if (sc->offload_map != 0) {
12550                         CH_WARN(sc,
12551                             "Disable TOE on all interfaces associated with "
12552                             "this adapter before trying to enable NIC TLS.\n");
12553                         return (EAGAIN);
12554                 }
12555                 return (t4_config_kern_tls(sc, true));
12556         } else {
12557                 /*
12558                  * Nothing to do for disable.  If TOE is enabled sometime later
12559                  * then toe_capability will reconfigure the hardware.
12560                  */
12561                 return (0);
12562         }
12563 }
12564 #endif
12565
12566 /*
12567  * t  = ptr to tunable.
12568  * nc = number of CPUs.
12569  * c  = compiled in default for that tunable.
12570  */
12571 static void
12572 calculate_nqueues(int *t, int nc, const int c)
12573 {
12574         int nq;
12575
12576         if (*t > 0)
12577                 return;
12578         nq = *t < 0 ? -*t : c;
12579         *t = min(nc, nq);
12580 }
12581
12582 /*
12583  * Come up with reasonable defaults for some of the tunables, provided they're
12584  * not set by the user (in which case we'll use the values as is).
12585  */
12586 static void
12587 tweak_tunables(void)
12588 {
12589         int nc = mp_ncpus;      /* our snapshot of the number of CPUs */
12590
12591         if (t4_ntxq < 1) {
12592 #ifdef RSS
12593                 t4_ntxq = rss_getnumbuckets();
12594 #else
12595                 calculate_nqueues(&t4_ntxq, nc, NTXQ);
12596 #endif
12597         }
12598
12599         calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12600
12601         if (t4_nrxq < 1) {
12602 #ifdef RSS
12603                 t4_nrxq = rss_getnumbuckets();
12604 #else
12605                 calculate_nqueues(&t4_nrxq, nc, NRXQ);
12606 #endif
12607         }
12608
12609         calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12610
12611 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12612         calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12613         calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12614 #endif
12615 #ifdef TCP_OFFLOAD
12616         calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12617         calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12618 #endif
12619
12620 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12621         if (t4_toecaps_allowed == -1)
12622                 t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12623 #else
12624         if (t4_toecaps_allowed == -1)
12625                 t4_toecaps_allowed = 0;
12626 #endif
12627
12628 #ifdef TCP_OFFLOAD
12629         if (t4_rdmacaps_allowed == -1) {
12630                 t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12631                     FW_CAPS_CONFIG_RDMA_RDMAC;
12632         }
12633
12634         if (t4_iscsicaps_allowed == -1) {
12635                 t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12636                     FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12637                     FW_CAPS_CONFIG_ISCSI_T10DIF;
12638         }
12639
12640         if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12641                 t4_tmr_idx_ofld = TMR_IDX_OFLD;
12642
12643         if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12644                 t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12645
12646         if (t4_toe_tls_rx_timeout < 0)
12647                 t4_toe_tls_rx_timeout = 0;
12648 #else
12649         if (t4_rdmacaps_allowed == -1)
12650                 t4_rdmacaps_allowed = 0;
12651
12652         if (t4_iscsicaps_allowed == -1)
12653                 t4_iscsicaps_allowed = 0;
12654 #endif
12655
12656 #ifdef DEV_NETMAP
12657         calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12658         calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12659         calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12660         calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12661 #endif
12662
12663         if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12664                 t4_tmr_idx = TMR_IDX;
12665
12666         if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12667                 t4_pktc_idx = PKTC_IDX;
12668
12669         if (t4_qsize_txq < 128)
12670                 t4_qsize_txq = 128;
12671
12672         if (t4_qsize_rxq < 128)
12673                 t4_qsize_rxq = 128;
12674         while (t4_qsize_rxq & 7)
12675                 t4_qsize_rxq++;
12676
12677         t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12678
12679         /*
12680          * Number of VIs to create per-port.  The first VI is the "main" regular
12681          * VI for the port.  The rest are additional virtual interfaces on the
12682          * same physical port.  Note that the main VI does not have native
12683          * netmap support but the extra VIs do.
12684          *
12685          * Limit the number of VIs per port to the number of available
12686          * MAC addresses per port.
12687          */
12688         if (t4_num_vis < 1)
12689                 t4_num_vis = 1;
12690         if (t4_num_vis > nitems(vi_mac_funcs)) {
12691                 t4_num_vis = nitems(vi_mac_funcs);
12692                 printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12693         }
12694
12695         if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12696                 pcie_relaxed_ordering = 1;
12697 #if defined(__i386__) || defined(__amd64__)
12698                 if (cpu_vendor_id == CPU_VENDOR_INTEL)
12699                         pcie_relaxed_ordering = 0;
12700 #endif
12701         }
12702 }
12703
12704 #ifdef DDB
12705 static void
12706 t4_dump_tcb(struct adapter *sc, int tid)
12707 {
12708         uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12709
12710         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12711         save = t4_read_reg(sc, reg);
12712         base = sc->memwin[2].mw_base;
12713
12714         /* Dump TCB for the tid */
12715         tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12716         tcb_addr += tid * TCB_SIZE;
12717
12718         if (is_t4(sc)) {
12719                 pf = 0;
12720                 win_pos = tcb_addr & ~0xf;      /* start must be 16B aligned */
12721         } else {
12722                 pf = V_PFNUM(sc->pf);
12723                 win_pos = tcb_addr & ~0x7f;     /* start must be 128B aligned */
12724         }
12725         t4_write_reg(sc, reg, win_pos | pf);
12726         t4_read_reg(sc, reg);
12727
12728         off = tcb_addr - win_pos;
12729         for (i = 0; i < 4; i++) {
12730                 uint32_t buf[8];
12731                 for (j = 0; j < 8; j++, off += 4)
12732                         buf[j] = htonl(t4_read_reg(sc, base + off));
12733
12734                 db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12735                     buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12736                     buf[7]);
12737         }
12738
12739         t4_write_reg(sc, reg, save);
12740         t4_read_reg(sc, reg);
12741 }
12742
12743 static void
12744 t4_dump_devlog(struct adapter *sc)
12745 {
12746         struct devlog_params *dparams = &sc->params.devlog;
12747         struct fw_devlog_e e;
12748         int i, first, j, m, nentries, rc;
12749         uint64_t ftstamp = UINT64_MAX;
12750
12751         if (dparams->start == 0) {
12752                 db_printf("devlog params not valid\n");
12753                 return;
12754         }
12755
12756         nentries = dparams->size / sizeof(struct fw_devlog_e);
12757         m = fwmtype_to_hwmtype(dparams->memtype);
12758
12759         /* Find the first entry. */
12760         first = -1;
12761         for (i = 0; i < nentries && !db_pager_quit; i++) {
12762                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12763                     sizeof(e), (void *)&e);
12764                 if (rc != 0)
12765                         break;
12766
12767                 if (e.timestamp == 0)
12768                         break;
12769
12770                 e.timestamp = be64toh(e.timestamp);
12771                 if (e.timestamp < ftstamp) {
12772                         ftstamp = e.timestamp;
12773                         first = i;
12774                 }
12775         }
12776
12777         if (first == -1)
12778                 return;
12779
12780         i = first;
12781         do {
12782                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12783                     sizeof(e), (void *)&e);
12784                 if (rc != 0)
12785                         return;
12786
12787                 if (e.timestamp == 0)
12788                         return;
12789
12790                 e.timestamp = be64toh(e.timestamp);
12791                 e.seqno = be32toh(e.seqno);
12792                 for (j = 0; j < 8; j++)
12793                         e.params[j] = be32toh(e.params[j]);
12794
12795                 db_printf("%10d  %15ju  %8s  %8s  ",
12796                     e.seqno, e.timestamp,
12797                     (e.level < nitems(devlog_level_strings) ?
12798                         devlog_level_strings[e.level] : "UNKNOWN"),
12799                     (e.facility < nitems(devlog_facility_strings) ?
12800                         devlog_facility_strings[e.facility] : "UNKNOWN"));
12801                 db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12802                     e.params[3], e.params[4], e.params[5], e.params[6],
12803                     e.params[7]);
12804
12805                 if (++i == nentries)
12806                         i = 0;
12807         } while (i != first && !db_pager_quit);
12808 }
12809
12810 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
12811 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
12812
12813 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
12814 {
12815         device_t dev;
12816         int t;
12817         bool valid;
12818
12819         valid = false;
12820         t = db_read_token();
12821         if (t == tIDENT) {
12822                 dev = device_lookup_by_name(db_tok_string);
12823                 valid = true;
12824         }
12825         db_skip_to_eol();
12826         if (!valid) {
12827                 db_printf("usage: show t4 devlog <nexus>\n");
12828                 return;
12829         }
12830
12831         if (dev == NULL) {
12832                 db_printf("device not found\n");
12833                 return;
12834         }
12835
12836         t4_dump_devlog(device_get_softc(dev));
12837 }
12838
12839 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
12840 {
12841         device_t dev;
12842         int radix, tid, t;
12843         bool valid;
12844
12845         valid = false;
12846         radix = db_radix;
12847         db_radix = 10;
12848         t = db_read_token();
12849         if (t == tIDENT) {
12850                 dev = device_lookup_by_name(db_tok_string);
12851                 t = db_read_token();
12852                 if (t == tNUMBER) {
12853                         tid = db_tok_number;
12854                         valid = true;
12855                 }
12856         }       
12857         db_radix = radix;
12858         db_skip_to_eol();
12859         if (!valid) {
12860                 db_printf("usage: show t4 tcb <nexus> <tid>\n");
12861                 return;
12862         }
12863
12864         if (dev == NULL) {
12865                 db_printf("device not found\n");
12866                 return;
12867         }
12868         if (tid < 0) {
12869                 db_printf("invalid tid\n");
12870                 return;
12871         }
12872
12873         t4_dump_tcb(device_get_softc(dev), tid);
12874 }
12875 #endif
12876
12877 static eventhandler_tag vxlan_start_evtag;
12878 static eventhandler_tag vxlan_stop_evtag;
12879
12880 struct vxlan_evargs {
12881         struct ifnet *ifp;
12882         uint16_t port;
12883 };
12884
12885 static void
12886 enable_vxlan_rx(struct adapter *sc)
12887 {
12888         int i, rc;
12889         struct port_info *pi;
12890         uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12891
12892         ASSERT_SYNCHRONIZED_OP(sc);
12893
12894         t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12895             F_VXLAN_EN);
12896         for_each_port(sc, i) {
12897                 pi = sc->port[i];
12898                 if (pi->vxlan_tcam_entry == true)
12899                         continue;
12900                 rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12901                     match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12902                     true);
12903                 if (rc < 0) {
12904                         rc = -rc;
12905                         CH_ERR(&pi->vi[0],
12906                             "failed to add VXLAN TCAM entry: %d.\n", rc);
12907                 } else {
12908                         MPASS(rc == sc->rawf_base + pi->port_id);
12909                         pi->vxlan_tcam_entry = true;
12910                 }
12911         }
12912 }
12913
12914 static void
12915 t4_vxlan_start(struct adapter *sc, void *arg)
12916 {
12917         struct vxlan_evargs *v = arg;
12918
12919         if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12920                 return;
12921         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
12922                 return;
12923
12924         if (sc->vxlan_refcount == 0) {
12925                 sc->vxlan_port = v->port;
12926                 sc->vxlan_refcount = 1;
12927                 if (!hw_off_limits(sc))
12928                         enable_vxlan_rx(sc);
12929         } else if (sc->vxlan_port == v->port) {
12930                 sc->vxlan_refcount++;
12931         } else {
12932                 CH_ERR(sc, "VXLAN already configured on port  %d; "
12933                     "ignoring attempt to configure it on port %d\n",
12934                     sc->vxlan_port, v->port);
12935         }
12936         end_synchronized_op(sc, 0);
12937 }
12938
12939 static void
12940 t4_vxlan_stop(struct adapter *sc, void *arg)
12941 {
12942         struct vxlan_evargs *v = arg;
12943
12944         if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
12945                 return;
12946         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
12947                 return;
12948
12949         /*
12950          * VXLANs may have been configured before the driver was loaded so we
12951          * may see more stops than starts.  This is not handled cleanly but at
12952          * least we keep the refcount sane.
12953          */
12954         if (sc->vxlan_port != v->port)
12955                 goto done;
12956         if (sc->vxlan_refcount == 0) {
12957                 CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
12958                     "ignoring attempt to stop it again.\n", sc->vxlan_port);
12959         } else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
12960                 t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
12961 done:
12962         end_synchronized_op(sc, 0);
12963 }
12964
12965 static void
12966 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
12967     sa_family_t family, u_int port)
12968 {
12969         struct vxlan_evargs v;
12970
12971         MPASS(family == AF_INET || family == AF_INET6);
12972         v.ifp = ifp;
12973         v.port = port;
12974
12975         t4_iterate(t4_vxlan_start, &v);
12976 }
12977
12978 static void
12979 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
12980     u_int port)
12981 {
12982         struct vxlan_evargs v;
12983
12984         MPASS(family == AF_INET || family == AF_INET6);
12985         v.ifp = ifp;
12986         v.port = port;
12987
12988         t4_iterate(t4_vxlan_stop, &v);
12989 }
12990
12991
12992 static struct sx mlu;   /* mod load unload */
12993 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
12994
12995 static int
12996 mod_event(module_t mod, int cmd, void *arg)
12997 {
12998         int rc = 0;
12999         static int loaded = 0;
13000
13001         switch (cmd) {
13002         case MOD_LOAD:
13003                 sx_xlock(&mlu);
13004                 if (loaded++ == 0) {
13005                         t4_sge_modload();
13006                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13007                             t4_filter_rpl, CPL_COOKIE_FILTER);
13008                         t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13009                             do_l2t_write_rpl, CPL_COOKIE_FILTER);
13010                         t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13011                             t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13012                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13013                             t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13014                         t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13015                             t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13016                         t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13017                         t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13018                         t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13019                             do_smt_write_rpl);
13020                         sx_init(&t4_list_lock, "T4/T5 adapters");
13021                         SLIST_INIT(&t4_list);
13022                         callout_init(&fatal_callout, 1);
13023 #ifdef TCP_OFFLOAD
13024                         sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13025                         SLIST_INIT(&t4_uld_list);
13026 #endif
13027 #ifdef INET6
13028                         t4_clip_modload();
13029 #endif
13030 #ifdef KERN_TLS
13031                         t6_ktls_modload();
13032 #endif
13033                         t4_tracer_modload();
13034                         tweak_tunables();
13035                         vxlan_start_evtag =
13036                             EVENTHANDLER_REGISTER(vxlan_start,
13037                                 t4_vxlan_start_handler, NULL,
13038                                 EVENTHANDLER_PRI_ANY);
13039                         vxlan_stop_evtag =
13040                             EVENTHANDLER_REGISTER(vxlan_stop,
13041                                 t4_vxlan_stop_handler, NULL,
13042                                 EVENTHANDLER_PRI_ANY);
13043                         reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13044                             taskqueue_thread_enqueue, &reset_tq);
13045                         taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13046                             "t4_rst_thr");
13047                 }
13048                 sx_xunlock(&mlu);
13049                 break;
13050
13051         case MOD_UNLOAD:
13052                 sx_xlock(&mlu);
13053                 if (--loaded == 0) {
13054                         int tries;
13055
13056                         taskqueue_free(reset_tq);
13057                         sx_slock(&t4_list_lock);
13058                         if (!SLIST_EMPTY(&t4_list)) {
13059                                 rc = EBUSY;
13060                                 sx_sunlock(&t4_list_lock);
13061                                 goto done_unload;
13062                         }
13063 #ifdef TCP_OFFLOAD
13064                         sx_slock(&t4_uld_list_lock);
13065                         if (!SLIST_EMPTY(&t4_uld_list)) {
13066                                 rc = EBUSY;
13067                                 sx_sunlock(&t4_uld_list_lock);
13068                                 sx_sunlock(&t4_list_lock);
13069                                 goto done_unload;
13070                         }
13071 #endif
13072                         tries = 0;
13073                         while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13074                                 uprintf("%ju clusters with custom free routine "
13075                                     "still is use.\n", t4_sge_extfree_refs());
13076                                 pause("t4unload", 2 * hz);
13077                         }
13078 #ifdef TCP_OFFLOAD
13079                         sx_sunlock(&t4_uld_list_lock);
13080 #endif
13081                         sx_sunlock(&t4_list_lock);
13082
13083                         if (t4_sge_extfree_refs() == 0) {
13084                                 EVENTHANDLER_DEREGISTER(vxlan_start,
13085                                     vxlan_start_evtag);
13086                                 EVENTHANDLER_DEREGISTER(vxlan_stop,
13087                                     vxlan_stop_evtag);
13088                                 t4_tracer_modunload();
13089 #ifdef KERN_TLS
13090                                 t6_ktls_modunload();
13091 #endif
13092 #ifdef INET6
13093                                 t4_clip_modunload();
13094 #endif
13095 #ifdef TCP_OFFLOAD
13096                                 sx_destroy(&t4_uld_list_lock);
13097 #endif
13098                                 sx_destroy(&t4_list_lock);
13099                                 t4_sge_modunload();
13100                                 loaded = 0;
13101                         } else {
13102                                 rc = EBUSY;
13103                                 loaded++;       /* undo earlier decrement */
13104                         }
13105                 }
13106 done_unload:
13107                 sx_xunlock(&mlu);
13108                 break;
13109         }
13110
13111         return (rc);
13112 }
13113
13114 static devclass_t t4_devclass, t5_devclass, t6_devclass;
13115 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
13116 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
13117
13118 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
13119 MODULE_VERSION(t4nex, 1);
13120 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13121 #ifdef DEV_NETMAP
13122 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13123 #endif /* DEV_NETMAP */
13124
13125 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
13126 MODULE_VERSION(t5nex, 1);
13127 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13128 #ifdef DEV_NETMAP
13129 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13130 #endif /* DEV_NETMAP */
13131
13132 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
13133 MODULE_VERSION(t6nex, 1);
13134 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13135 #ifdef DEV_NETMAP
13136 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13137 #endif /* DEV_NETMAP */
13138
13139 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
13140 MODULE_VERSION(cxgbe, 1);
13141
13142 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
13143 MODULE_VERSION(cxl, 1);
13144
13145 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
13146 MODULE_VERSION(cc, 1);
13147
13148 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
13149 MODULE_VERSION(vcxgbe, 1);
13150
13151 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
13152 MODULE_VERSION(vcxl, 1);
13153
13154 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
13155 MODULE_VERSION(vcc, 1);