]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/t4_main.c
cxgbe(4): two new debug sysctls.
[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_str(device_t, device_t, char *, size_t);
101 static int t4_ready(device_t);
102 static int t4_read_port_device(device_t, int, device_t *);
103 static device_method_t t4_methods[] = {
104         DEVMETHOD(device_probe,         t4_probe),
105         DEVMETHOD(device_attach,        t4_attach),
106         DEVMETHOD(device_detach,        t4_detach),
107
108         DEVMETHOD(bus_child_location_str, t4_child_location_str),
109
110         DEVMETHOD(t4_is_main_ready,     t4_ready),
111         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
112
113         DEVMETHOD_END
114 };
115 static driver_t t4_driver = {
116         "t4nex",
117         t4_methods,
118         sizeof(struct adapter)
119 };
120
121
122 /* T4 port (cxgbe) interface */
123 static int cxgbe_probe(device_t);
124 static int cxgbe_attach(device_t);
125 static int cxgbe_detach(device_t);
126 device_method_t cxgbe_methods[] = {
127         DEVMETHOD(device_probe,         cxgbe_probe),
128         DEVMETHOD(device_attach,        cxgbe_attach),
129         DEVMETHOD(device_detach,        cxgbe_detach),
130         { 0, 0 }
131 };
132 static driver_t cxgbe_driver = {
133         "cxgbe",
134         cxgbe_methods,
135         sizeof(struct port_info)
136 };
137
138 /* T4 VI (vcxgbe) interface */
139 static int vcxgbe_probe(device_t);
140 static int vcxgbe_attach(device_t);
141 static int vcxgbe_detach(device_t);
142 static device_method_t vcxgbe_methods[] = {
143         DEVMETHOD(device_probe,         vcxgbe_probe),
144         DEVMETHOD(device_attach,        vcxgbe_attach),
145         DEVMETHOD(device_detach,        vcxgbe_detach),
146         { 0, 0 }
147 };
148 static driver_t vcxgbe_driver = {
149         "vcxgbe",
150         vcxgbe_methods,
151         sizeof(struct vi_info)
152 };
153
154 static d_ioctl_t t4_ioctl;
155
156 static struct cdevsw t4_cdevsw = {
157        .d_version = D_VERSION,
158        .d_ioctl = t4_ioctl,
159        .d_name = "t4nex",
160 };
161
162 /* T5 bus driver interface */
163 static int t5_probe(device_t);
164 static device_method_t t5_methods[] = {
165         DEVMETHOD(device_probe,         t5_probe),
166         DEVMETHOD(device_attach,        t4_attach),
167         DEVMETHOD(device_detach,        t4_detach),
168
169         DEVMETHOD(bus_child_location_str, t4_child_location_str),
170
171         DEVMETHOD(t4_is_main_ready,     t4_ready),
172         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
173
174         DEVMETHOD_END
175 };
176 static driver_t t5_driver = {
177         "t5nex",
178         t5_methods,
179         sizeof(struct adapter)
180 };
181
182
183 /* T5 port (cxl) interface */
184 static driver_t cxl_driver = {
185         "cxl",
186         cxgbe_methods,
187         sizeof(struct port_info)
188 };
189
190 /* T5 VI (vcxl) interface */
191 static driver_t vcxl_driver = {
192         "vcxl",
193         vcxgbe_methods,
194         sizeof(struct vi_info)
195 };
196
197 /* T6 bus driver interface */
198 static int t6_probe(device_t);
199 static device_method_t t6_methods[] = {
200         DEVMETHOD(device_probe,         t6_probe),
201         DEVMETHOD(device_attach,        t4_attach),
202         DEVMETHOD(device_detach,        t4_detach),
203
204         DEVMETHOD(bus_child_location_str, t4_child_location_str),
205
206         DEVMETHOD(t4_is_main_ready,     t4_ready),
207         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
208
209         DEVMETHOD_END
210 };
211 static driver_t t6_driver = {
212         "t6nex",
213         t6_methods,
214         sizeof(struct adapter)
215 };
216
217
218 /* T6 port (cc) interface */
219 static driver_t cc_driver = {
220         "cc",
221         cxgbe_methods,
222         sizeof(struct port_info)
223 };
224
225 /* T6 VI (vcc) interface */
226 static driver_t vcc_driver = {
227         "vcc",
228         vcxgbe_methods,
229         sizeof(struct vi_info)
230 };
231
232 /* ifnet interface */
233 static void cxgbe_init(void *);
234 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
235 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
236 static void cxgbe_qflush(struct ifnet *);
237 #if defined(KERN_TLS) || defined(RATELIMIT)
238 static int cxgbe_snd_tag_alloc(struct ifnet *, union if_snd_tag_alloc_params *,
239     struct m_snd_tag **);
240 static int cxgbe_snd_tag_modify(struct m_snd_tag *,
241     union if_snd_tag_modify_params *);
242 static int cxgbe_snd_tag_query(struct m_snd_tag *,
243     union if_snd_tag_query_params *);
244 static void cxgbe_snd_tag_free(struct m_snd_tag *);
245 #endif
246
247 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
248
249 /*
250  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
251  * then ADAPTER_LOCK, then t4_uld_list_lock.
252  */
253 static struct sx t4_list_lock;
254 SLIST_HEAD(, adapter) t4_list;
255 #ifdef TCP_OFFLOAD
256 static struct sx t4_uld_list_lock;
257 SLIST_HEAD(, uld_info) t4_uld_list;
258 #endif
259
260 /*
261  * Tunables.  See tweak_tunables() too.
262  *
263  * Each tunable is set to a default value here if it's known at compile-time.
264  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
265  * provide a reasonable default (upto n) when the driver is loaded.
266  *
267  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
268  * T5 are under hw.cxl.
269  */
270 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
271     "cxgbe(4) parameters");
272 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
273     "cxgbe(4) T5+ parameters");
274 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
275     "cxgbe(4) TOE parameters");
276
277 /*
278  * Number of queues for tx and rx, NIC and offload.
279  */
280 #define NTXQ 16
281 int t4_ntxq = -NTXQ;
282 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
283     "Number of TX queues per port");
284 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);      /* Old name, undocumented */
285
286 #define NRXQ 8
287 int t4_nrxq = -NRXQ;
288 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
289     "Number of RX queues per port");
290 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);      /* Old name, undocumented */
291
292 #define NTXQ_VI 1
293 static int t4_ntxq_vi = -NTXQ_VI;
294 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
295     "Number of TX queues per VI");
296
297 #define NRXQ_VI 1
298 static int t4_nrxq_vi = -NRXQ_VI;
299 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
300     "Number of RX queues per VI");
301
302 static int t4_rsrv_noflowq = 0;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
304     0, "Reserve TX queue 0 of each VI for non-flowid packets");
305
306 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
307 #define NOFLDTXQ 8
308 static int t4_nofldtxq = -NOFLDTXQ;
309 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
310     "Number of offload TX queues per port");
311
312 #define NOFLDRXQ 2
313 static int t4_nofldrxq = -NOFLDRXQ;
314 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
315     "Number of offload RX queues per port");
316
317 #define NOFLDTXQ_VI 1
318 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
319 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
320     "Number of offload TX queues per VI");
321
322 #define NOFLDRXQ_VI 1
323 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
324 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
325     "Number of offload RX queues per VI");
326
327 #define TMR_IDX_OFLD 1
328 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
329 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
330     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
331
332 #define PKTC_IDX_OFLD (-1)
333 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
334 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
335     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
336
337 /* 0 means chip/fw default, non-zero number is value in microseconds */
338 static u_long t4_toe_keepalive_idle = 0;
339 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
340     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
341
342 /* 0 means chip/fw default, non-zero number is value in microseconds */
343 static u_long t4_toe_keepalive_interval = 0;
344 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
345     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
346
347 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
348 static int t4_toe_keepalive_count = 0;
349 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
350     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
351
352 /* 0 means chip/fw default, non-zero number is value in microseconds */
353 static u_long t4_toe_rexmt_min = 0;
354 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
355     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
356
357 /* 0 means chip/fw default, non-zero number is value in microseconds */
358 static u_long t4_toe_rexmt_max = 0;
359 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
360     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
361
362 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
363 static int t4_toe_rexmt_count = 0;
364 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
365     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
366
367 /* -1 means chip/fw default, other values are raw backoff values to use */
368 static int t4_toe_rexmt_backoff[16] = {
369         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
370 };
371 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
372     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
373     "cxgbe(4) TOE retransmit backoff values");
374 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
375     &t4_toe_rexmt_backoff[0], 0, "");
376 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
377     &t4_toe_rexmt_backoff[1], 0, "");
378 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
379     &t4_toe_rexmt_backoff[2], 0, "");
380 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
381     &t4_toe_rexmt_backoff[3], 0, "");
382 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
383     &t4_toe_rexmt_backoff[4], 0, "");
384 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
385     &t4_toe_rexmt_backoff[5], 0, "");
386 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
387     &t4_toe_rexmt_backoff[6], 0, "");
388 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
389     &t4_toe_rexmt_backoff[7], 0, "");
390 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
391     &t4_toe_rexmt_backoff[8], 0, "");
392 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
393     &t4_toe_rexmt_backoff[9], 0, "");
394 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
395     &t4_toe_rexmt_backoff[10], 0, "");
396 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
397     &t4_toe_rexmt_backoff[11], 0, "");
398 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
399     &t4_toe_rexmt_backoff[12], 0, "");
400 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
401     &t4_toe_rexmt_backoff[13], 0, "");
402 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
403     &t4_toe_rexmt_backoff[14], 0, "");
404 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
405     &t4_toe_rexmt_backoff[15], 0, "");
406 #endif
407
408 #ifdef DEV_NETMAP
409 #define NN_MAIN_VI      (1 << 0)        /* Native netmap on the main VI */
410 #define NN_EXTRA_VI     (1 << 1)        /* Native netmap on the extra VI(s) */
411 static int t4_native_netmap = NN_EXTRA_VI;
412 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
413     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
414
415 #define NNMTXQ 8
416 static int t4_nnmtxq = -NNMTXQ;
417 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
418     "Number of netmap TX queues");
419
420 #define NNMRXQ 8
421 static int t4_nnmrxq = -NNMRXQ;
422 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
423     "Number of netmap RX queues");
424
425 #define NNMTXQ_VI 2
426 static int t4_nnmtxq_vi = -NNMTXQ_VI;
427 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
428     "Number of netmap TX queues per VI");
429
430 #define NNMRXQ_VI 2
431 static int t4_nnmrxq_vi = -NNMRXQ_VI;
432 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
433     "Number of netmap RX queues per VI");
434 #endif
435
436 /*
437  * Holdoff parameters for ports.
438  */
439 #define TMR_IDX 1
440 int t4_tmr_idx = TMR_IDX;
441 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
442     0, "Holdoff timer index");
443 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);     /* Old name */
444
445 #define PKTC_IDX (-1)
446 int t4_pktc_idx = PKTC_IDX;
447 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
448     0, "Holdoff packet counter index");
449 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);     /* Old name */
450
451 /*
452  * Size (# of entries) of each tx and rx queue.
453  */
454 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
455 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
456     "Number of descriptors in each TX queue");
457
458 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
459 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
460     "Number of descriptors in each RX queue");
461
462 /*
463  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
464  */
465 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
466 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
467     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
468
469 /*
470  * Configuration file.  All the _CF names here are special.
471  */
472 #define DEFAULT_CF      "default"
473 #define BUILTIN_CF      "built-in"
474 #define FLASH_CF        "flash"
475 #define UWIRE_CF        "uwire"
476 #define FPGA_CF         "fpga"
477 static char t4_cfg_file[32] = DEFAULT_CF;
478 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
479     sizeof(t4_cfg_file), "Firmware configuration file");
480
481 /*
482  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
483  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
484  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
485  *            mark or when signalled to do so, 0 to never emit PAUSE.
486  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
487  *                 negotiated settings will override rx_pause/tx_pause.
488  *                 Otherwise rx_pause/tx_pause are applied forcibly.
489  */
490 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
491 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
492     &t4_pause_settings, 0,
493     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
494
495 /*
496  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
497  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
498  *  0 to disable FEC.
499  */
500 static int t4_fec = -1;
501 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
502     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
503
504 /*
505  * Link autonegotiation.
506  * -1 to run with the firmware default.
507  *  0 to disable.
508  *  1 to enable.
509  */
510 static int t4_autoneg = -1;
511 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
512     "Link autonegotiation");
513
514 /*
515  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
516  * encouraged respectively).  '-n' is the same as 'n' except the firmware
517  * version used in the checks is read from the firmware bundled with the driver.
518  */
519 static int t4_fw_install = 1;
520 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
521     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
522
523 /*
524  * ASIC features that will be used.  Disable the ones you don't want so that the
525  * chip resources aren't wasted on features that will not be used.
526  */
527 static int t4_nbmcaps_allowed = 0;
528 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
529     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
530
531 static int t4_linkcaps_allowed = 0;     /* No DCBX, PPP, etc. by default */
532 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
533     &t4_linkcaps_allowed, 0, "Default link capabilities");
534
535 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
536     FW_CAPS_CONFIG_SWITCH_EGRESS;
537 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
538     &t4_switchcaps_allowed, 0, "Default switch capabilities");
539
540 #ifdef RATELIMIT
541 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
542         FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
543 #else
544 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
545         FW_CAPS_CONFIG_NIC_HASHFILTER;
546 #endif
547 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
548     &t4_niccaps_allowed, 0, "Default NIC capabilities");
549
550 static int t4_toecaps_allowed = -1;
551 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
552     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
553
554 static int t4_rdmacaps_allowed = -1;
555 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
556     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
557
558 static int t4_cryptocaps_allowed = -1;
559 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
560     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
561
562 static int t4_iscsicaps_allowed = -1;
563 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
564     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
565
566 static int t4_fcoecaps_allowed = 0;
567 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
568     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
569
570 static int t5_write_combine = 0;
571 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
572     0, "Use WC instead of UC for BAR2");
573
574 static int t4_num_vis = 1;
575 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
576     "Number of VIs per port");
577
578 /*
579  * PCIe Relaxed Ordering.
580  * -1: driver should figure out a good value.
581  * 0: disable RO.
582  * 1: enable RO.
583  * 2: leave RO alone.
584  */
585 static int pcie_relaxed_ordering = -1;
586 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
587     &pcie_relaxed_ordering, 0,
588     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
589
590 static int t4_panic_on_fatal_err = 0;
591 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RDTUN,
592     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
593
594 static int t4_tx_vm_wr = 0;
595 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
596     "Use VM work requests to transmit packets.");
597
598 /*
599  * Set to non-zero to enable the attack filter.  A packet that matches any of
600  * these conditions will get dropped on ingress:
601  * 1) IP && source address == destination address.
602  * 2) TCP/IP && source address is not a unicast address.
603  * 3) TCP/IP && destination address is not a unicast address.
604  * 4) IP && source address is loopback (127.x.y.z).
605  * 5) IP && destination address is loopback (127.x.y.z).
606  * 6) IPv6 && source address == destination address.
607  * 7) IPv6 && source address is not a unicast address.
608  * 8) IPv6 && source address is loopback (::1/128).
609  * 9) IPv6 && destination address is loopback (::1/128).
610  * 10) IPv6 && source address is unspecified (::/128).
611  * 11) IPv6 && destination address is unspecified (::/128).
612  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
613  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
614  */
615 static int t4_attack_filter = 0;
616 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
617     &t4_attack_filter, 0, "Drop suspicious traffic");
618
619 static int t4_drop_ip_fragments = 0;
620 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
621     &t4_drop_ip_fragments, 0, "Drop IP fragments");
622
623 static int t4_drop_pkts_with_l2_errors = 1;
624 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
625     &t4_drop_pkts_with_l2_errors, 0,
626     "Drop all frames with Layer 2 length or checksum errors");
627
628 static int t4_drop_pkts_with_l3_errors = 0;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
630     &t4_drop_pkts_with_l3_errors, 0,
631     "Drop all frames with IP version, length, or checksum errors");
632
633 static int t4_drop_pkts_with_l4_errors = 0;
634 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
635     &t4_drop_pkts_with_l4_errors, 0,
636     "Drop all frames with Layer 4 length, checksum, or other errors");
637
638 #ifdef TCP_OFFLOAD
639 /*
640  * TOE tunables.
641  */
642 static int t4_cop_managed_offloading = 0;
643 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
644     &t4_cop_managed_offloading, 0,
645     "COP (Connection Offload Policy) controls all TOE offload");
646 #endif
647
648 #ifdef KERN_TLS
649 /*
650  * This enables KERN_TLS for all adapters if set.
651  */
652 static int t4_kern_tls = 0;
653 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
654     "Enable KERN_TLS mode for all supported adapters");
655
656 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
657     "cxgbe(4) KERN_TLS parameters");
658
659 static int t4_tls_inline_keys = 0;
660 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
661     &t4_tls_inline_keys, 0,
662     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
663     "in card memory.");
664
665 static int t4_tls_combo_wrs = 0;
666 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
667     0, "Attempt to combine TCB field updates with TLS record work requests.");
668 #endif
669
670 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
671 static int vi_mac_funcs[] = {
672         FW_VI_FUNC_ETH,
673         FW_VI_FUNC_OFLD,
674         FW_VI_FUNC_IWARP,
675         FW_VI_FUNC_OPENISCSI,
676         FW_VI_FUNC_OPENFCOE,
677         FW_VI_FUNC_FOISCSI,
678         FW_VI_FUNC_FOFCOE,
679 };
680
681 struct intrs_and_queues {
682         uint16_t intr_type;     /* INTx, MSI, or MSI-X */
683         uint16_t num_vis;       /* number of VIs for each port */
684         uint16_t nirq;          /* Total # of vectors */
685         uint16_t ntxq;          /* # of NIC txq's for each port */
686         uint16_t nrxq;          /* # of NIC rxq's for each port */
687         uint16_t nofldtxq;      /* # of TOE/ETHOFLD txq's for each port */
688         uint16_t nofldrxq;      /* # of TOE rxq's for each port */
689         uint16_t nnmtxq;        /* # of netmap txq's */
690         uint16_t nnmrxq;        /* # of netmap rxq's */
691
692         /* The vcxgbe/vcxl interfaces use these and not the ones above. */
693         uint16_t ntxq_vi;       /* # of NIC txq's */
694         uint16_t nrxq_vi;       /* # of NIC rxq's */
695         uint16_t nofldtxq_vi;   /* # of TOE txq's */
696         uint16_t nofldrxq_vi;   /* # of TOE rxq's */
697         uint16_t nnmtxq_vi;     /* # of netmap txq's */
698         uint16_t nnmrxq_vi;     /* # of netmap rxq's */
699 };
700
701 static void setup_memwin(struct adapter *);
702 static void position_memwin(struct adapter *, int, uint32_t);
703 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
704 static int fwmtype_to_hwmtype(int);
705 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
706     uint32_t *);
707 static int fixup_devlog_params(struct adapter *);
708 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
709 static int contact_firmware(struct adapter *);
710 static int partition_resources(struct adapter *);
711 static int get_params__pre_init(struct adapter *);
712 static int set_params__pre_init(struct adapter *);
713 static int get_params__post_init(struct adapter *);
714 static int set_params__post_init(struct adapter *);
715 static void t4_set_desc(struct adapter *);
716 static bool fixed_ifmedia(struct port_info *);
717 static void build_medialist(struct port_info *);
718 static void init_link_config(struct port_info *);
719 static int fixup_link_config(struct port_info *);
720 static int apply_link_config(struct port_info *);
721 static int cxgbe_init_synchronized(struct vi_info *);
722 static int cxgbe_uninit_synchronized(struct vi_info *);
723 static void quiesce_txq(struct adapter *, struct sge_txq *);
724 static void quiesce_wrq(struct adapter *, struct sge_wrq *);
725 static void quiesce_iq(struct adapter *, struct sge_iq *);
726 static void quiesce_fl(struct adapter *, struct sge_fl *);
727 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
728     driver_intr_t *, void *, char *);
729 static int t4_free_irq(struct adapter *, struct irq *);
730 static void t4_init_atid_table(struct adapter *);
731 static void t4_free_atid_table(struct adapter *);
732 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
733 static void vi_refresh_stats(struct adapter *, struct vi_info *);
734 static void cxgbe_refresh_stats(struct adapter *, struct port_info *);
735 static void cxgbe_tick(void *);
736 static void cxgbe_sysctls(struct port_info *);
737 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
738 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
739 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
740 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
741 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
742 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
743 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
744 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
745 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
746 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
747 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
748 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
749 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
750 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
751 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
752 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
753 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
754 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
755 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
756 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
757 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
758 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
759 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
760 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
761 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
762 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
763 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
764 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
765 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
766 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
767 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
768 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
769 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
770 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
771 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
772 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
773 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
774 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
775 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
776 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
777 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
778 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
779 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
780 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
781 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
782 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
783 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
784 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
785 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
786 #ifdef TCP_OFFLOAD
787 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
788 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
789 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
790 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
791 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
792 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
793 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
794 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
795 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
796 #endif
797 static int get_sge_context(struct adapter *, struct t4_sge_context *);
798 static int load_fw(struct adapter *, struct t4_data *);
799 static int load_cfg(struct adapter *, struct t4_data *);
800 static int load_boot(struct adapter *, struct t4_bootrom *);
801 static int load_bootcfg(struct adapter *, struct t4_data *);
802 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
803 static void free_offload_policy(struct t4_offload_policy *);
804 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
805 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
806 static int read_i2c(struct adapter *, struct t4_i2c_data *);
807 static int clear_stats(struct adapter *, u_int);
808 #ifdef TCP_OFFLOAD
809 static int toe_capability(struct vi_info *, int);
810 static void t4_async_event(void *, int);
811 #endif
812 static int mod_event(module_t, int, void *);
813 static int notify_siblings(device_t, int);
814
815 struct {
816         uint16_t device;
817         char *desc;
818 } t4_pciids[] = {
819         {0xa000, "Chelsio Terminator 4 FPGA"},
820         {0x4400, "Chelsio T440-dbg"},
821         {0x4401, "Chelsio T420-CR"},
822         {0x4402, "Chelsio T422-CR"},
823         {0x4403, "Chelsio T440-CR"},
824         {0x4404, "Chelsio T420-BCH"},
825         {0x4405, "Chelsio T440-BCH"},
826         {0x4406, "Chelsio T440-CH"},
827         {0x4407, "Chelsio T420-SO"},
828         {0x4408, "Chelsio T420-CX"},
829         {0x4409, "Chelsio T420-BT"},
830         {0x440a, "Chelsio T404-BT"},
831         {0x440e, "Chelsio T440-LP-CR"},
832 }, t5_pciids[] = {
833         {0xb000, "Chelsio Terminator 5 FPGA"},
834         {0x5400, "Chelsio T580-dbg"},
835         {0x5401,  "Chelsio T520-CR"},           /* 2 x 10G */
836         {0x5402,  "Chelsio T522-CR"},           /* 2 x 10G, 2 X 1G */
837         {0x5403,  "Chelsio T540-CR"},           /* 4 x 10G */
838         {0x5407,  "Chelsio T520-SO"},           /* 2 x 10G, nomem */
839         {0x5409,  "Chelsio T520-BT"},           /* 2 x 10GBaseT */
840         {0x540a,  "Chelsio T504-BT"},           /* 4 x 1G */
841         {0x540d,  "Chelsio T580-CR"},           /* 2 x 40G */
842         {0x540e,  "Chelsio T540-LP-CR"},        /* 4 x 10G */
843         {0x5410,  "Chelsio T580-LP-CR"},        /* 2 x 40G */
844         {0x5411,  "Chelsio T520-LL-CR"},        /* 2 x 10G */
845         {0x5412,  "Chelsio T560-CR"},           /* 1 x 40G, 2 x 10G */
846         {0x5414,  "Chelsio T580-LP-SO-CR"},     /* 2 x 40G, nomem */
847         {0x5415,  "Chelsio T502-BT"},           /* 2 x 1G */
848         {0x5418,  "Chelsio T540-BT"},           /* 4 x 10GBaseT */
849         {0x5419,  "Chelsio T540-LP-BT"},        /* 4 x 10GBaseT */
850         {0x541a,  "Chelsio T540-SO-BT"},        /* 4 x 10GBaseT, nomem */
851         {0x541b,  "Chelsio T540-SO-CR"},        /* 4 x 10G, nomem */
852
853         /* Custom */
854         {0x5483, "Custom T540-CR"},
855         {0x5484, "Custom T540-BT"},
856 }, t6_pciids[] = {
857         {0xc006, "Chelsio Terminator 6 FPGA"},  /* T6 PE10K6 FPGA (PF0) */
858         {0x6400, "Chelsio T6-DBG-25"},          /* 2 x 10/25G, debug */
859         {0x6401, "Chelsio T6225-CR"},           /* 2 x 10/25G */
860         {0x6402, "Chelsio T6225-SO-CR"},        /* 2 x 10/25G, nomem */
861         {0x6403, "Chelsio T6425-CR"},           /* 4 x 10/25G */
862         {0x6404, "Chelsio T6425-SO-CR"},        /* 4 x 10/25G, nomem */
863         {0x6405, "Chelsio T6225-OCP-SO"},       /* 2 x 10/25G, nomem */
864         {0x6406, "Chelsio T62100-OCP-SO"},      /* 2 x 40/50/100G, nomem */
865         {0x6407, "Chelsio T62100-LP-CR"},       /* 2 x 40/50/100G */
866         {0x6408, "Chelsio T62100-SO-CR"},       /* 2 x 40/50/100G, nomem */
867         {0x6409, "Chelsio T6210-BT"},           /* 2 x 10GBASE-T */
868         {0x640d, "Chelsio T62100-CR"},          /* 2 x 40/50/100G */
869         {0x6410, "Chelsio T6-DBG-100"},         /* 2 x 40/50/100G, debug */
870         {0x6411, "Chelsio T6225-LL-CR"},        /* 2 x 10/25G */
871         {0x6414, "Chelsio T61100-OCP-SO"},      /* 1 x 40/50/100G, nomem */
872         {0x6415, "Chelsio T6201-BT"},           /* 2 x 1000BASE-T */
873
874         /* Custom */
875         {0x6480, "Custom T6225-CR"},
876         {0x6481, "Custom T62100-CR"},
877         {0x6482, "Custom T6225-CR"},
878         {0x6483, "Custom T62100-CR"},
879         {0x6484, "Custom T64100-CR"},
880         {0x6485, "Custom T6240-SO"},
881         {0x6486, "Custom T6225-SO-CR"},
882         {0x6487, "Custom T6225-CR"},
883 };
884
885 #ifdef TCP_OFFLOAD
886 /*
887  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
888  * be exactly the same for both rxq and ofld_rxq.
889  */
890 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
891 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
892 #endif
893 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
894
895 static int
896 t4_probe(device_t dev)
897 {
898         int i;
899         uint16_t v = pci_get_vendor(dev);
900         uint16_t d = pci_get_device(dev);
901         uint8_t f = pci_get_function(dev);
902
903         if (v != PCI_VENDOR_ID_CHELSIO)
904                 return (ENXIO);
905
906         /* Attach only to PF0 of the FPGA */
907         if (d == 0xa000 && f != 0)
908                 return (ENXIO);
909
910         for (i = 0; i < nitems(t4_pciids); i++) {
911                 if (d == t4_pciids[i].device) {
912                         device_set_desc(dev, t4_pciids[i].desc);
913                         return (BUS_PROBE_DEFAULT);
914                 }
915         }
916
917         return (ENXIO);
918 }
919
920 static int
921 t5_probe(device_t dev)
922 {
923         int i;
924         uint16_t v = pci_get_vendor(dev);
925         uint16_t d = pci_get_device(dev);
926         uint8_t f = pci_get_function(dev);
927
928         if (v != PCI_VENDOR_ID_CHELSIO)
929                 return (ENXIO);
930
931         /* Attach only to PF0 of the FPGA */
932         if (d == 0xb000 && f != 0)
933                 return (ENXIO);
934
935         for (i = 0; i < nitems(t5_pciids); i++) {
936                 if (d == t5_pciids[i].device) {
937                         device_set_desc(dev, t5_pciids[i].desc);
938                         return (BUS_PROBE_DEFAULT);
939                 }
940         }
941
942         return (ENXIO);
943 }
944
945 static int
946 t6_probe(device_t dev)
947 {
948         int i;
949         uint16_t v = pci_get_vendor(dev);
950         uint16_t d = pci_get_device(dev);
951
952         if (v != PCI_VENDOR_ID_CHELSIO)
953                 return (ENXIO);
954
955         for (i = 0; i < nitems(t6_pciids); i++) {
956                 if (d == t6_pciids[i].device) {
957                         device_set_desc(dev, t6_pciids[i].desc);
958                         return (BUS_PROBE_DEFAULT);
959                 }
960         }
961
962         return (ENXIO);
963 }
964
965 static void
966 t5_attribute_workaround(device_t dev)
967 {
968         device_t root_port;
969         uint32_t v;
970
971         /*
972          * The T5 chips do not properly echo the No Snoop and Relaxed
973          * Ordering attributes when replying to a TLP from a Root
974          * Port.  As a workaround, find the parent Root Port and
975          * disable No Snoop and Relaxed Ordering.  Note that this
976          * affects all devices under this root port.
977          */
978         root_port = pci_find_pcie_root_port(dev);
979         if (root_port == NULL) {
980                 device_printf(dev, "Unable to find parent root port\n");
981                 return;
982         }
983
984         v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
985             PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
986         if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
987             0)
988                 device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
989                     device_get_nameunit(root_port));
990 }
991
992 static const struct devnames devnames[] = {
993         {
994                 .nexus_name = "t4nex",
995                 .ifnet_name = "cxgbe",
996                 .vi_ifnet_name = "vcxgbe",
997                 .pf03_drv_name = "t4iov",
998                 .vf_nexus_name = "t4vf",
999                 .vf_ifnet_name = "cxgbev"
1000         }, {
1001                 .nexus_name = "t5nex",
1002                 .ifnet_name = "cxl",
1003                 .vi_ifnet_name = "vcxl",
1004                 .pf03_drv_name = "t5iov",
1005                 .vf_nexus_name = "t5vf",
1006                 .vf_ifnet_name = "cxlv"
1007         }, {
1008                 .nexus_name = "t6nex",
1009                 .ifnet_name = "cc",
1010                 .vi_ifnet_name = "vcc",
1011                 .pf03_drv_name = "t6iov",
1012                 .vf_nexus_name = "t6vf",
1013                 .vf_ifnet_name = "ccv"
1014         }
1015 };
1016
1017 void
1018 t4_init_devnames(struct adapter *sc)
1019 {
1020         int id;
1021
1022         id = chip_id(sc);
1023         if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1024                 sc->names = &devnames[id - CHELSIO_T4];
1025         else {
1026                 device_printf(sc->dev, "chip id %d is not supported.\n", id);
1027                 sc->names = NULL;
1028         }
1029 }
1030
1031 static int
1032 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1033 {
1034         const char *parent, *name;
1035         long value;
1036         int line, unit;
1037
1038         line = 0;
1039         parent = device_get_nameunit(sc->dev);
1040         name = sc->names->ifnet_name;
1041         while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1042                 if (resource_long_value(name, unit, "port", &value) == 0 &&
1043                     value == pi->port_id)
1044                         return (unit);
1045         }
1046         return (-1);
1047 }
1048
1049 static int
1050 t4_attach(device_t dev)
1051 {
1052         struct adapter *sc;
1053         int rc = 0, i, j, rqidx, tqidx, nports;
1054         struct make_dev_args mda;
1055         struct intrs_and_queues iaq;
1056         struct sge *s;
1057         uint32_t *buf;
1058 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1059         int ofld_tqidx;
1060 #endif
1061 #ifdef TCP_OFFLOAD
1062         int ofld_rqidx;
1063 #endif
1064 #ifdef DEV_NETMAP
1065         int nm_rqidx, nm_tqidx;
1066 #endif
1067         int num_vis;
1068
1069         sc = device_get_softc(dev);
1070         sc->dev = dev;
1071         TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1072
1073         if ((pci_get_device(dev) & 0xff00) == 0x5400)
1074                 t5_attribute_workaround(dev);
1075         pci_enable_busmaster(dev);
1076         if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1077                 uint32_t v;
1078
1079                 pci_set_max_read_req(dev, 4096);
1080                 v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1081                 sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1082                 if (pcie_relaxed_ordering == 0 &&
1083                     (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1084                         v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1085                         pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1086                 } else if (pcie_relaxed_ordering == 1 &&
1087                     (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1088                         v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1089                         pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1090                 }
1091         }
1092
1093         sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1094         sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1095         sc->traceq = -1;
1096         mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1097         snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1098             device_get_nameunit(dev));
1099
1100         snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1101             device_get_nameunit(dev));
1102         mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1103         t4_add_adapter(sc);
1104
1105         mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1106         TAILQ_INIT(&sc->sfl);
1107         callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1108
1109         mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1110
1111         sc->policy = NULL;
1112         rw_init(&sc->policy_lock, "connection offload policy");
1113
1114         callout_init(&sc->ktls_tick, 1);
1115
1116 #ifdef TCP_OFFLOAD
1117         TASK_INIT(&sc->async_event_task, 0, t4_async_event, sc);
1118 #endif
1119
1120         refcount_init(&sc->vxlan_refcount, 0);
1121
1122         rc = t4_map_bars_0_and_4(sc);
1123         if (rc != 0)
1124                 goto done; /* error message displayed already */
1125
1126         memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1127
1128         /* Prepare the adapter for operation. */
1129         buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1130         rc = -t4_prep_adapter(sc, buf);
1131         free(buf, M_CXGBE);
1132         if (rc != 0) {
1133                 device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1134                 goto done;
1135         }
1136
1137         /*
1138          * This is the real PF# to which we're attaching.  Works from within PCI
1139          * passthrough environments too, where pci_get_function() could return a
1140          * different PF# depending on the passthrough configuration.  We need to
1141          * use the real PF# in all our communication with the firmware.
1142          */
1143         j = t4_read_reg(sc, A_PL_WHOAMI);
1144         sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1145         sc->mbox = sc->pf;
1146
1147         t4_init_devnames(sc);
1148         if (sc->names == NULL) {
1149                 rc = ENOTSUP;
1150                 goto done; /* error message displayed already */
1151         }
1152
1153         /*
1154          * Do this really early, with the memory windows set up even before the
1155          * character device.  The userland tool's register i/o and mem read
1156          * will work even in "recovery mode".
1157          */
1158         setup_memwin(sc);
1159         if (t4_init_devlog_params(sc, 0) == 0)
1160                 fixup_devlog_params(sc);
1161         make_dev_args_init(&mda);
1162         mda.mda_devsw = &t4_cdevsw;
1163         mda.mda_uid = UID_ROOT;
1164         mda.mda_gid = GID_WHEEL;
1165         mda.mda_mode = 0600;
1166         mda.mda_si_drv1 = sc;
1167         rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1168         if (rc != 0)
1169                 device_printf(dev, "failed to create nexus char device: %d.\n",
1170                     rc);
1171
1172         /* Go no further if recovery mode has been requested. */
1173         if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1174                 device_printf(dev, "recovery mode.\n");
1175                 goto done;
1176         }
1177
1178 #if defined(__i386__)
1179         if ((cpu_feature & CPUID_CX8) == 0) {
1180                 device_printf(dev, "64 bit atomics not available.\n");
1181                 rc = ENOTSUP;
1182                 goto done;
1183         }
1184 #endif
1185
1186         /* Contact the firmware and try to become the master driver. */
1187         rc = contact_firmware(sc);
1188         if (rc != 0)
1189                 goto done; /* error message displayed already */
1190         MPASS(sc->flags & FW_OK);
1191
1192         rc = get_params__pre_init(sc);
1193         if (rc != 0)
1194                 goto done; /* error message displayed already */
1195
1196         if (sc->flags & MASTER_PF) {
1197                 rc = partition_resources(sc);
1198                 if (rc != 0)
1199                         goto done; /* error message displayed already */
1200                 t4_intr_clear(sc);
1201         }
1202
1203         rc = get_params__post_init(sc);
1204         if (rc != 0)
1205                 goto done; /* error message displayed already */
1206
1207         rc = set_params__post_init(sc);
1208         if (rc != 0)
1209                 goto done; /* error message displayed already */
1210
1211         rc = t4_map_bar_2(sc);
1212         if (rc != 0)
1213                 goto done; /* error message displayed already */
1214
1215         rc = t4_create_dma_tag(sc);
1216         if (rc != 0)
1217                 goto done; /* error message displayed already */
1218
1219         /*
1220          * First pass over all the ports - allocate VIs and initialize some
1221          * basic parameters like mac address, port type, etc.
1222          */
1223         for_each_port(sc, i) {
1224                 struct port_info *pi;
1225
1226                 pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1227                 sc->port[i] = pi;
1228
1229                 /* These must be set before t4_port_init */
1230                 pi->adapter = sc;
1231                 pi->port_id = i;
1232                 /*
1233                  * XXX: vi[0] is special so we can't delay this allocation until
1234                  * pi->nvi's final value is known.
1235                  */
1236                 pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1237                     M_ZERO | M_WAITOK);
1238
1239                 /*
1240                  * Allocate the "main" VI and initialize parameters
1241                  * like mac addr.
1242                  */
1243                 rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1244                 if (rc != 0) {
1245                         device_printf(dev, "unable to initialize port %d: %d\n",
1246                             i, rc);
1247                         free(pi->vi, M_CXGBE);
1248                         free(pi, M_CXGBE);
1249                         sc->port[i] = NULL;
1250                         goto done;
1251                 }
1252
1253                 snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1254                     device_get_nameunit(dev), i);
1255                 mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1256                 sc->chan_map[pi->tx_chan] = i;
1257
1258                 /*
1259                  * The MPS counter for FCS errors doesn't work correctly on the
1260                  * T6 so we use the MAC counter here.  Which MAC is in use
1261                  * depends on the link settings which will be known when the
1262                  * link comes up.
1263                  */
1264                 if (is_t6(sc)) {
1265                         pi->fcs_reg = -1;
1266                 } else if (is_t4(sc)) {
1267                         pi->fcs_reg = PORT_REG(pi->tx_chan,
1268                             A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1269                 } else {
1270                         pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1271                             A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1272                 }
1273                 pi->fcs_base = 0;
1274
1275                 /* All VIs on this port share this media. */
1276                 ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1277                     cxgbe_media_status);
1278
1279                 PORT_LOCK(pi);
1280                 init_link_config(pi);
1281                 fixup_link_config(pi);
1282                 build_medialist(pi);
1283                 if (fixed_ifmedia(pi))
1284                         pi->flags |= FIXED_IFMEDIA;
1285                 PORT_UNLOCK(pi);
1286
1287                 pi->dev = device_add_child(dev, sc->names->ifnet_name,
1288                     t4_ifnet_unit(sc, pi));
1289                 if (pi->dev == NULL) {
1290                         device_printf(dev,
1291                             "failed to add device for port %d.\n", i);
1292                         rc = ENXIO;
1293                         goto done;
1294                 }
1295                 pi->vi[0].dev = pi->dev;
1296                 device_set_softc(pi->dev, pi);
1297         }
1298
1299         /*
1300          * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1301          */
1302         nports = sc->params.nports;
1303         rc = cfg_itype_and_nqueues(sc, &iaq);
1304         if (rc != 0)
1305                 goto done; /* error message displayed already */
1306
1307         num_vis = iaq.num_vis;
1308         sc->intr_type = iaq.intr_type;
1309         sc->intr_count = iaq.nirq;
1310
1311         s = &sc->sge;
1312         s->nrxq = nports * iaq.nrxq;
1313         s->ntxq = nports * iaq.ntxq;
1314         if (num_vis > 1) {
1315                 s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1316                 s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1317         }
1318         s->neq = s->ntxq + s->nrxq;     /* the free list in an rxq is an eq */
1319         s->neq += nports;               /* ctrl queues: 1 per port */
1320         s->niq = s->nrxq + 1;           /* 1 extra for firmware event queue */
1321 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1322         if (is_offload(sc) || is_ethoffload(sc)) {
1323                 s->nofldtxq = nports * iaq.nofldtxq;
1324                 if (num_vis > 1)
1325                         s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1326                 s->neq += s->nofldtxq;
1327
1328                 s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_wrq),
1329                     M_CXGBE, M_ZERO | M_WAITOK);
1330         }
1331 #endif
1332 #ifdef TCP_OFFLOAD
1333         if (is_offload(sc)) {
1334                 s->nofldrxq = nports * iaq.nofldrxq;
1335                 if (num_vis > 1)
1336                         s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1337                 s->neq += s->nofldrxq;  /* free list */
1338                 s->niq += s->nofldrxq;
1339
1340                 s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1341                     M_CXGBE, M_ZERO | M_WAITOK);
1342         }
1343 #endif
1344 #ifdef DEV_NETMAP
1345         s->nnmrxq = 0;
1346         s->nnmtxq = 0;
1347         if (t4_native_netmap & NN_MAIN_VI) {
1348                 s->nnmrxq += nports * iaq.nnmrxq;
1349                 s->nnmtxq += nports * iaq.nnmtxq;
1350         }
1351         if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1352                 s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1353                 s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1354         }
1355         s->neq += s->nnmtxq + s->nnmrxq;
1356         s->niq += s->nnmrxq;
1357
1358         s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1359             M_CXGBE, M_ZERO | M_WAITOK);
1360         s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1361             M_CXGBE, M_ZERO | M_WAITOK);
1362 #endif
1363         MPASS(s->niq <= s->iqmap_sz);
1364         MPASS(s->neq <= s->eqmap_sz);
1365
1366         s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1367             M_ZERO | M_WAITOK);
1368         s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1369             M_ZERO | M_WAITOK);
1370         s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1371             M_ZERO | M_WAITOK);
1372         s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1373             M_ZERO | M_WAITOK);
1374         s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1375             M_ZERO | M_WAITOK);
1376
1377         sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1378             M_ZERO | M_WAITOK);
1379
1380         t4_init_l2t(sc, M_WAITOK);
1381         t4_init_smt(sc, M_WAITOK);
1382         t4_init_tx_sched(sc);
1383         t4_init_atid_table(sc);
1384 #ifdef RATELIMIT
1385         t4_init_etid_table(sc);
1386 #endif
1387 #ifdef INET6
1388         t4_init_clip_table(sc);
1389 #endif
1390         if (sc->vres.key.size != 0)
1391                 sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1392                     sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1393
1394         /*
1395          * Second pass over the ports.  This time we know the number of rx and
1396          * tx queues that each port should get.
1397          */
1398         rqidx = tqidx = 0;
1399 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1400         ofld_tqidx = 0;
1401 #endif
1402 #ifdef TCP_OFFLOAD
1403         ofld_rqidx = 0;
1404 #endif
1405 #ifdef DEV_NETMAP
1406         nm_rqidx = nm_tqidx = 0;
1407 #endif
1408         for_each_port(sc, i) {
1409                 struct port_info *pi = sc->port[i];
1410                 struct vi_info *vi;
1411
1412                 if (pi == NULL)
1413                         continue;
1414
1415                 pi->nvi = num_vis;
1416                 for_each_vi(pi, j, vi) {
1417                         vi->pi = pi;
1418                         vi->adapter = sc;
1419                         vi->qsize_rxq = t4_qsize_rxq;
1420                         vi->qsize_txq = t4_qsize_txq;
1421
1422                         vi->first_rxq = rqidx;
1423                         vi->first_txq = tqidx;
1424                         vi->tmr_idx = t4_tmr_idx;
1425                         vi->pktc_idx = t4_pktc_idx;
1426                         vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1427                         vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1428
1429                         rqidx += vi->nrxq;
1430                         tqidx += vi->ntxq;
1431
1432                         if (j == 0 && vi->ntxq > 1)
1433                                 vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1434                         else
1435                                 vi->rsrv_noflowq = 0;
1436
1437 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1438                         vi->first_ofld_txq = ofld_tqidx;
1439                         vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1440                         ofld_tqidx += vi->nofldtxq;
1441 #endif
1442 #ifdef TCP_OFFLOAD
1443                         vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1444                         vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1445                         vi->first_ofld_rxq = ofld_rqidx;
1446                         vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1447
1448                         ofld_rqidx += vi->nofldrxq;
1449 #endif
1450 #ifdef DEV_NETMAP
1451                         vi->first_nm_rxq = nm_rqidx;
1452                         vi->first_nm_txq = nm_tqidx;
1453                         if (j == 0) {
1454                                 vi->nnmrxq = iaq.nnmrxq;
1455                                 vi->nnmtxq = iaq.nnmtxq;
1456                         } else {
1457                                 vi->nnmrxq = iaq.nnmrxq_vi;
1458                                 vi->nnmtxq = iaq.nnmtxq_vi;
1459                         }
1460                         nm_rqidx += vi->nnmrxq;
1461                         nm_tqidx += vi->nnmtxq;
1462 #endif
1463                 }
1464         }
1465
1466         rc = t4_setup_intr_handlers(sc);
1467         if (rc != 0) {
1468                 device_printf(dev,
1469                     "failed to setup interrupt handlers: %d\n", rc);
1470                 goto done;
1471         }
1472
1473         rc = bus_generic_probe(dev);
1474         if (rc != 0) {
1475                 device_printf(dev, "failed to probe child drivers: %d\n", rc);
1476                 goto done;
1477         }
1478
1479         /*
1480          * Ensure thread-safe mailbox access (in debug builds).
1481          *
1482          * So far this was the only thread accessing the mailbox but various
1483          * ifnets and sysctls are about to be created and their handlers/ioctls
1484          * will access the mailbox from different threads.
1485          */
1486         sc->flags |= CHK_MBOX_ACCESS;
1487
1488         rc = bus_generic_attach(dev);
1489         if (rc != 0) {
1490                 device_printf(dev,
1491                     "failed to attach all child ports: %d\n", rc);
1492                 goto done;
1493         }
1494
1495         device_printf(dev,
1496             "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1497             sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1498             sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1499             (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1500             sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1501
1502         t4_set_desc(sc);
1503
1504         notify_siblings(dev, 0);
1505
1506 done:
1507         if (rc != 0 && sc->cdev) {
1508                 /* cdev was created and so cxgbetool works; recover that way. */
1509                 device_printf(dev,
1510                     "error during attach, adapter is now in recovery mode.\n");
1511                 rc = 0;
1512         }
1513
1514         if (rc != 0)
1515                 t4_detach_common(dev);
1516         else
1517                 t4_sysctls(sc);
1518
1519         return (rc);
1520 }
1521
1522 static int
1523 t4_child_location_str(device_t bus, device_t dev, char *buf, size_t buflen)
1524 {
1525         struct adapter *sc;
1526         struct port_info *pi;
1527         int i;
1528
1529         sc = device_get_softc(bus);
1530         buf[0] = '\0';
1531         for_each_port(sc, i) {
1532                 pi = sc->port[i];
1533                 if (pi != NULL && pi->dev == dev) {
1534                         snprintf(buf, buflen, "port=%d", pi->port_id);
1535                         break;
1536                 }
1537         }
1538         return (0);
1539 }
1540
1541 static int
1542 t4_ready(device_t dev)
1543 {
1544         struct adapter *sc;
1545
1546         sc = device_get_softc(dev);
1547         if (sc->flags & FW_OK)
1548                 return (0);
1549         return (ENXIO);
1550 }
1551
1552 static int
1553 t4_read_port_device(device_t dev, int port, device_t *child)
1554 {
1555         struct adapter *sc;
1556         struct port_info *pi;
1557
1558         sc = device_get_softc(dev);
1559         if (port < 0 || port >= MAX_NPORTS)
1560                 return (EINVAL);
1561         pi = sc->port[port];
1562         if (pi == NULL || pi->dev == NULL)
1563                 return (ENXIO);
1564         *child = pi->dev;
1565         return (0);
1566 }
1567
1568 static int
1569 notify_siblings(device_t dev, int detaching)
1570 {
1571         device_t sibling;
1572         int error, i;
1573
1574         error = 0;
1575         for (i = 0; i < PCI_FUNCMAX; i++) {
1576                 if (i == pci_get_function(dev))
1577                         continue;
1578                 sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1579                     pci_get_slot(dev), i);
1580                 if (sibling == NULL || !device_is_attached(sibling))
1581                         continue;
1582                 if (detaching)
1583                         error = T4_DETACH_CHILD(sibling);
1584                 else
1585                         (void)T4_ATTACH_CHILD(sibling);
1586                 if (error)
1587                         break;
1588         }
1589         return (error);
1590 }
1591
1592 /*
1593  * Idempotent
1594  */
1595 static int
1596 t4_detach(device_t dev)
1597 {
1598         struct adapter *sc;
1599         int rc;
1600
1601         sc = device_get_softc(dev);
1602
1603         rc = notify_siblings(dev, 1);
1604         if (rc) {
1605                 device_printf(dev,
1606                     "failed to detach sibling devices: %d\n", rc);
1607                 return (rc);
1608         }
1609
1610         return (t4_detach_common(dev));
1611 }
1612
1613 int
1614 t4_detach_common(device_t dev)
1615 {
1616         struct adapter *sc;
1617         struct port_info *pi;
1618         int i, rc;
1619
1620         sc = device_get_softc(dev);
1621
1622         if (sc->cdev) {
1623                 destroy_dev(sc->cdev);
1624                 sc->cdev = NULL;
1625         }
1626
1627         sx_xlock(&t4_list_lock);
1628         SLIST_REMOVE(&t4_list, sc, adapter, link);
1629         sx_xunlock(&t4_list_lock);
1630
1631         sc->flags &= ~CHK_MBOX_ACCESS;
1632         if (sc->flags & FULL_INIT_DONE) {
1633                 if (!(sc->flags & IS_VF))
1634                         t4_intr_disable(sc);
1635         }
1636
1637         if (device_is_attached(dev)) {
1638                 rc = bus_generic_detach(dev);
1639                 if (rc) {
1640                         device_printf(dev,
1641                             "failed to detach child devices: %d\n", rc);
1642                         return (rc);
1643                 }
1644         }
1645
1646 #ifdef TCP_OFFLOAD
1647         taskqueue_drain(taskqueue_thread, &sc->async_event_task);
1648 #endif
1649
1650         for (i = 0; i < sc->intr_count; i++)
1651                 t4_free_irq(sc, &sc->irq[i]);
1652
1653         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1654                 t4_free_tx_sched(sc);
1655
1656         for (i = 0; i < MAX_NPORTS; i++) {
1657                 pi = sc->port[i];
1658                 if (pi) {
1659                         t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1660                         if (pi->dev)
1661                                 device_delete_child(dev, pi->dev);
1662
1663                         mtx_destroy(&pi->pi_lock);
1664                         free(pi->vi, M_CXGBE);
1665                         free(pi, M_CXGBE);
1666                 }
1667         }
1668
1669         device_delete_children(dev);
1670
1671         if (sc->flags & FULL_INIT_DONE)
1672                 adapter_full_uninit(sc);
1673
1674         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1675                 t4_fw_bye(sc, sc->mbox);
1676
1677         if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1678                 pci_release_msi(dev);
1679
1680         if (sc->regs_res)
1681                 bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1682                     sc->regs_res);
1683
1684         if (sc->udbs_res)
1685                 bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1686                     sc->udbs_res);
1687
1688         if (sc->msix_res)
1689                 bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1690                     sc->msix_res);
1691
1692         if (sc->l2t)
1693                 t4_free_l2t(sc->l2t);
1694         if (sc->smt)
1695                 t4_free_smt(sc->smt);
1696         t4_free_atid_table(sc);
1697 #ifdef RATELIMIT
1698         t4_free_etid_table(sc);
1699 #endif
1700         if (sc->key_map)
1701                 vmem_destroy(sc->key_map);
1702 #ifdef INET6
1703         t4_destroy_clip_table(sc);
1704 #endif
1705
1706 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1707         free(sc->sge.ofld_txq, M_CXGBE);
1708 #endif
1709 #ifdef TCP_OFFLOAD
1710         free(sc->sge.ofld_rxq, M_CXGBE);
1711 #endif
1712 #ifdef DEV_NETMAP
1713         free(sc->sge.nm_rxq, M_CXGBE);
1714         free(sc->sge.nm_txq, M_CXGBE);
1715 #endif
1716         free(sc->irq, M_CXGBE);
1717         free(sc->sge.rxq, M_CXGBE);
1718         free(sc->sge.txq, M_CXGBE);
1719         free(sc->sge.ctrlq, M_CXGBE);
1720         free(sc->sge.iqmap, M_CXGBE);
1721         free(sc->sge.eqmap, M_CXGBE);
1722         free(sc->tids.ftid_tab, M_CXGBE);
1723         free(sc->tids.hpftid_tab, M_CXGBE);
1724         free_hftid_hash(&sc->tids);
1725         free(sc->tids.tid_tab, M_CXGBE);
1726         free(sc->tt.tls_rx_ports, M_CXGBE);
1727         t4_destroy_dma_tag(sc);
1728
1729         callout_drain(&sc->ktls_tick);
1730         callout_drain(&sc->sfl_callout);
1731         if (mtx_initialized(&sc->tids.ftid_lock)) {
1732                 mtx_destroy(&sc->tids.ftid_lock);
1733                 cv_destroy(&sc->tids.ftid_cv);
1734         }
1735         if (mtx_initialized(&sc->tids.atid_lock))
1736                 mtx_destroy(&sc->tids.atid_lock);
1737         if (mtx_initialized(&sc->ifp_lock))
1738                 mtx_destroy(&sc->ifp_lock);
1739
1740         if (rw_initialized(&sc->policy_lock)) {
1741                 rw_destroy(&sc->policy_lock);
1742 #ifdef TCP_OFFLOAD
1743                 if (sc->policy != NULL)
1744                         free_offload_policy(sc->policy);
1745 #endif
1746         }
1747
1748         for (i = 0; i < NUM_MEMWIN; i++) {
1749                 struct memwin *mw = &sc->memwin[i];
1750
1751                 if (rw_initialized(&mw->mw_lock))
1752                         rw_destroy(&mw->mw_lock);
1753         }
1754
1755         mtx_destroy(&sc->sfl_lock);
1756         mtx_destroy(&sc->reg_lock);
1757         mtx_destroy(&sc->sc_lock);
1758
1759         bzero(sc, sizeof(*sc));
1760
1761         return (0);
1762 }
1763
1764 static int
1765 cxgbe_probe(device_t dev)
1766 {
1767         char buf[128];
1768         struct port_info *pi = device_get_softc(dev);
1769
1770         snprintf(buf, sizeof(buf), "port %d", pi->port_id);
1771         device_set_desc_copy(dev, buf);
1772
1773         return (BUS_PROBE_DEFAULT);
1774 }
1775
1776 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
1777     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
1778     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
1779     IFCAP_HWRXTSTMP | IFCAP_NOMAP)
1780 #define T4_CAP_ENABLE (T4_CAP)
1781
1782 static int
1783 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
1784 {
1785         struct ifnet *ifp;
1786         struct sbuf *sb;
1787         struct pfil_head_args pa;
1788         struct adapter *sc = vi->adapter;
1789
1790         vi->xact_addr_filt = -1;
1791         callout_init(&vi->tick, 1);
1792         if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
1793                 vi->flags |= TX_USES_VM_WR;
1794
1795         /* Allocate an ifnet and set it up */
1796         ifp = if_alloc_dev(IFT_ETHER, dev);
1797         if (ifp == NULL) {
1798                 device_printf(dev, "Cannot allocate ifnet\n");
1799                 return (ENOMEM);
1800         }
1801         vi->ifp = ifp;
1802         ifp->if_softc = vi;
1803
1804         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1805         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1806
1807         ifp->if_init = cxgbe_init;
1808         ifp->if_ioctl = cxgbe_ioctl;
1809         ifp->if_transmit = cxgbe_transmit;
1810         ifp->if_qflush = cxgbe_qflush;
1811         ifp->if_get_counter = cxgbe_get_counter;
1812 #if defined(KERN_TLS) || defined(RATELIMIT)
1813         ifp->if_snd_tag_alloc = cxgbe_snd_tag_alloc;
1814         ifp->if_snd_tag_modify = cxgbe_snd_tag_modify;
1815         ifp->if_snd_tag_query = cxgbe_snd_tag_query;
1816         ifp->if_snd_tag_free = cxgbe_snd_tag_free;
1817 #endif
1818 #ifdef RATELIMIT
1819         ifp->if_ratelimit_query = cxgbe_ratelimit_query;
1820 #endif
1821
1822         ifp->if_capabilities = T4_CAP;
1823         ifp->if_capenable = T4_CAP_ENABLE;
1824         ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
1825             CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
1826         if (chip_id(sc) >= CHELSIO_T6) {
1827                 ifp->if_capabilities |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
1828                 ifp->if_capenable |= IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO;
1829                 ifp->if_hwassist |= CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
1830                     CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
1831                     CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN;
1832         }
1833
1834 #ifdef TCP_OFFLOAD
1835         if (vi->nofldrxq != 0 && (sc->flags & KERN_TLS_OK) == 0)
1836                 ifp->if_capabilities |= IFCAP_TOE;
1837 #endif
1838 #ifdef RATELIMIT
1839         if (is_ethoffload(sc) && vi->nofldtxq != 0) {
1840                 ifp->if_capabilities |= IFCAP_TXRTLMT;
1841                 ifp->if_capenable |= IFCAP_TXRTLMT;
1842         }
1843 #endif
1844
1845         ifp->if_hw_tsomax = IP_MAXPACKET;
1846         if (vi->flags & TX_USES_VM_WR)
1847                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
1848         else
1849                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
1850 #ifdef RATELIMIT
1851         if (is_ethoffload(sc) && vi->nofldtxq != 0)
1852                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
1853 #endif
1854         ifp->if_hw_tsomaxsegsize = 65536;
1855 #ifdef KERN_TLS
1856         if (sc->flags & KERN_TLS_OK) {
1857                 ifp->if_capabilities |= IFCAP_TXTLS;
1858                 ifp->if_capenable |= IFCAP_TXTLS;
1859         }
1860 #endif
1861
1862         ether_ifattach(ifp, vi->hw_addr);
1863 #ifdef DEV_NETMAP
1864         if (vi->nnmrxq != 0)
1865                 cxgbe_nm_attach(vi);
1866 #endif
1867         sb = sbuf_new_auto();
1868         sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
1869 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1870         switch (ifp->if_capabilities & (IFCAP_TOE | IFCAP_TXRTLMT)) {
1871         case IFCAP_TOE:
1872                 sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
1873                 break;
1874         case IFCAP_TOE | IFCAP_TXRTLMT:
1875                 sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
1876                 break;
1877         case IFCAP_TXRTLMT:
1878                 sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
1879                 break;
1880         }
1881 #endif
1882 #ifdef TCP_OFFLOAD
1883         if (ifp->if_capabilities & IFCAP_TOE)
1884                 sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
1885 #endif
1886 #ifdef DEV_NETMAP
1887         if (ifp->if_capabilities & IFCAP_NETMAP)
1888                 sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
1889                     vi->nnmtxq, vi->nnmrxq);
1890 #endif
1891         sbuf_finish(sb);
1892         device_printf(dev, "%s\n", sbuf_data(sb));
1893         sbuf_delete(sb);
1894
1895         vi_sysctls(vi);
1896
1897         pa.pa_version = PFIL_VERSION;
1898         pa.pa_flags = PFIL_IN;
1899         pa.pa_type = PFIL_TYPE_ETHERNET;
1900         pa.pa_headname = ifp->if_xname;
1901         vi->pfil = pfil_head_register(&pa);
1902
1903         return (0);
1904 }
1905
1906 static int
1907 cxgbe_attach(device_t dev)
1908 {
1909         struct port_info *pi = device_get_softc(dev);
1910         struct adapter *sc = pi->adapter;
1911         struct vi_info *vi;
1912         int i, rc;
1913
1914         callout_init_mtx(&pi->tick, &pi->pi_lock, 0);
1915
1916         rc = cxgbe_vi_attach(dev, &pi->vi[0]);
1917         if (rc)
1918                 return (rc);
1919
1920         for_each_vi(pi, i, vi) {
1921                 if (i == 0)
1922                         continue;
1923                 vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
1924                 if (vi->dev == NULL) {
1925                         device_printf(dev, "failed to add VI %d\n", i);
1926                         continue;
1927                 }
1928                 device_set_softc(vi->dev, vi);
1929         }
1930
1931         cxgbe_sysctls(pi);
1932
1933         bus_generic_attach(dev);
1934
1935         return (0);
1936 }
1937
1938 static void
1939 cxgbe_vi_detach(struct vi_info *vi)
1940 {
1941         struct ifnet *ifp = vi->ifp;
1942
1943         if (vi->pfil != NULL) {
1944                 pfil_head_unregister(vi->pfil);
1945                 vi->pfil = NULL;
1946         }
1947
1948         ether_ifdetach(ifp);
1949
1950         /* Let detach proceed even if these fail. */
1951 #ifdef DEV_NETMAP
1952         if (ifp->if_capabilities & IFCAP_NETMAP)
1953                 cxgbe_nm_detach(vi);
1954 #endif
1955         cxgbe_uninit_synchronized(vi);
1956         callout_drain(&vi->tick);
1957         vi_full_uninit(vi);
1958
1959         if_free(vi->ifp);
1960         vi->ifp = NULL;
1961 }
1962
1963 static int
1964 cxgbe_detach(device_t dev)
1965 {
1966         struct port_info *pi = device_get_softc(dev);
1967         struct adapter *sc = pi->adapter;
1968         int rc;
1969
1970         /* Detach the extra VIs first. */
1971         rc = bus_generic_detach(dev);
1972         if (rc)
1973                 return (rc);
1974         device_delete_children(dev);
1975
1976         doom_vi(sc, &pi->vi[0]);
1977
1978         if (pi->flags & HAS_TRACEQ) {
1979                 sc->traceq = -1;        /* cloner should not create ifnet */
1980                 t4_tracer_port_detach(sc);
1981         }
1982
1983         cxgbe_vi_detach(&pi->vi[0]);
1984         callout_drain(&pi->tick);
1985         ifmedia_removeall(&pi->media);
1986
1987         end_synchronized_op(sc, 0);
1988
1989         return (0);
1990 }
1991
1992 static void
1993 cxgbe_init(void *arg)
1994 {
1995         struct vi_info *vi = arg;
1996         struct adapter *sc = vi->adapter;
1997
1998         if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
1999                 return;
2000         cxgbe_init_synchronized(vi);
2001         end_synchronized_op(sc, 0);
2002 }
2003
2004 static int
2005 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
2006 {
2007         int rc = 0, mtu, flags;
2008         struct vi_info *vi = ifp->if_softc;
2009         struct port_info *pi = vi->pi;
2010         struct adapter *sc = pi->adapter;
2011         struct ifreq *ifr = (struct ifreq *)data;
2012         uint32_t mask;
2013
2014         switch (cmd) {
2015         case SIOCSIFMTU:
2016                 mtu = ifr->ifr_mtu;
2017                 if (mtu < ETHERMIN || mtu > MAX_MTU)
2018                         return (EINVAL);
2019
2020                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2021                 if (rc)
2022                         return (rc);
2023                 ifp->if_mtu = mtu;
2024                 if (vi->flags & VI_INIT_DONE) {
2025                         t4_update_fl_bufsize(ifp);
2026                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2027                                 rc = update_mac_settings(ifp, XGMAC_MTU);
2028                 }
2029                 end_synchronized_op(sc, 0);
2030                 break;
2031
2032         case SIOCSIFFLAGS:
2033                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2034                 if (rc)
2035                         return (rc);
2036
2037                 if (ifp->if_flags & IFF_UP) {
2038                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2039                                 flags = vi->if_flags;
2040                                 if ((ifp->if_flags ^ flags) &
2041                                     (IFF_PROMISC | IFF_ALLMULTI)) {
2042                                         rc = update_mac_settings(ifp,
2043                                             XGMAC_PROMISC | XGMAC_ALLMULTI);
2044                                 }
2045                         } else {
2046                                 rc = cxgbe_init_synchronized(vi);
2047                         }
2048                         vi->if_flags = ifp->if_flags;
2049                 } else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2050                         rc = cxgbe_uninit_synchronized(vi);
2051                 }
2052                 end_synchronized_op(sc, 0);
2053                 break;
2054
2055         case SIOCADDMULTI:
2056         case SIOCDELMULTI:
2057                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2058                 if (rc)
2059                         return (rc);
2060                 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2061                         rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2062                 end_synchronized_op(sc, 0);
2063                 break;
2064
2065         case SIOCSIFCAP:
2066                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2067                 if (rc)
2068                         return (rc);
2069
2070                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
2071                 if (mask & IFCAP_TXCSUM) {
2072                         ifp->if_capenable ^= IFCAP_TXCSUM;
2073                         ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
2074
2075                         if (IFCAP_TSO4 & ifp->if_capenable &&
2076                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
2077                                 mask &= ~IFCAP_TSO4;
2078                                 ifp->if_capenable &= ~IFCAP_TSO4;
2079                                 if_printf(ifp,
2080                                     "tso4 disabled due to -txcsum.\n");
2081                         }
2082                 }
2083                 if (mask & IFCAP_TXCSUM_IPV6) {
2084                         ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
2085                         ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2086
2087                         if (IFCAP_TSO6 & ifp->if_capenable &&
2088                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2089                                 mask &= ~IFCAP_TSO6;
2090                                 ifp->if_capenable &= ~IFCAP_TSO6;
2091                                 if_printf(ifp,
2092                                     "tso6 disabled due to -txcsum6.\n");
2093                         }
2094                 }
2095                 if (mask & IFCAP_RXCSUM)
2096                         ifp->if_capenable ^= IFCAP_RXCSUM;
2097                 if (mask & IFCAP_RXCSUM_IPV6)
2098                         ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
2099
2100                 /*
2101                  * Note that we leave CSUM_TSO alone (it is always set).  The
2102                  * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2103                  * sending a TSO request our way, so it's sufficient to toggle
2104                  * IFCAP_TSOx only.
2105                  */
2106                 if (mask & IFCAP_TSO4) {
2107                         if (!(IFCAP_TSO4 & ifp->if_capenable) &&
2108                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
2109                                 if_printf(ifp, "enable txcsum first.\n");
2110                                 rc = EAGAIN;
2111                                 goto fail;
2112                         }
2113                         ifp->if_capenable ^= IFCAP_TSO4;
2114                 }
2115                 if (mask & IFCAP_TSO6) {
2116                         if (!(IFCAP_TSO6 & ifp->if_capenable) &&
2117                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
2118                                 if_printf(ifp, "enable txcsum6 first.\n");
2119                                 rc = EAGAIN;
2120                                 goto fail;
2121                         }
2122                         ifp->if_capenable ^= IFCAP_TSO6;
2123                 }
2124                 if (mask & IFCAP_LRO) {
2125 #if defined(INET) || defined(INET6)
2126                         int i;
2127                         struct sge_rxq *rxq;
2128
2129                         ifp->if_capenable ^= IFCAP_LRO;
2130                         for_each_rxq(vi, i, rxq) {
2131                                 if (ifp->if_capenable & IFCAP_LRO)
2132                                         rxq->iq.flags |= IQ_LRO_ENABLED;
2133                                 else
2134                                         rxq->iq.flags &= ~IQ_LRO_ENABLED;
2135                         }
2136 #endif
2137                 }
2138 #ifdef TCP_OFFLOAD
2139                 if (mask & IFCAP_TOE) {
2140                         int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
2141
2142                         rc = toe_capability(vi, enable);
2143                         if (rc != 0)
2144                                 goto fail;
2145
2146                         ifp->if_capenable ^= mask;
2147                 }
2148 #endif
2149                 if (mask & IFCAP_VLAN_HWTAGGING) {
2150                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
2151                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2152                                 rc = update_mac_settings(ifp, XGMAC_VLANEX);
2153                 }
2154                 if (mask & IFCAP_VLAN_MTU) {
2155                         ifp->if_capenable ^= IFCAP_VLAN_MTU;
2156
2157                         /* Need to find out how to disable auto-mtu-inflation */
2158                 }
2159                 if (mask & IFCAP_VLAN_HWTSO)
2160                         ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
2161                 if (mask & IFCAP_VLAN_HWCSUM)
2162                         ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
2163 #ifdef RATELIMIT
2164                 if (mask & IFCAP_TXRTLMT)
2165                         ifp->if_capenable ^= IFCAP_TXRTLMT;
2166 #endif
2167                 if (mask & IFCAP_HWRXTSTMP) {
2168                         int i;
2169                         struct sge_rxq *rxq;
2170
2171                         ifp->if_capenable ^= IFCAP_HWRXTSTMP;
2172                         for_each_rxq(vi, i, rxq) {
2173                                 if (ifp->if_capenable & IFCAP_HWRXTSTMP)
2174                                         rxq->iq.flags |= IQ_RX_TIMESTAMP;
2175                                 else
2176                                         rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2177                         }
2178                 }
2179                 if (mask & IFCAP_NOMAP)
2180                         ifp->if_capenable ^= IFCAP_NOMAP;
2181
2182 #ifdef KERN_TLS
2183                 if (mask & IFCAP_TXTLS)
2184                         ifp->if_capenable ^= (mask & IFCAP_TXTLS);
2185 #endif
2186                 if (mask & IFCAP_VXLAN_HWCSUM) {
2187                         ifp->if_capenable ^= IFCAP_VXLAN_HWCSUM;
2188                         ifp->if_hwassist ^= CSUM_INNER_IP6_UDP |
2189                             CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2190                             CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP;
2191                 }
2192                 if (mask & IFCAP_VXLAN_HWTSO) {
2193                         ifp->if_capenable ^= IFCAP_VXLAN_HWTSO;
2194                         ifp->if_hwassist ^= CSUM_INNER_IP6_TSO |
2195                             CSUM_INNER_IP_TSO;
2196                 }
2197
2198 #ifdef VLAN_CAPABILITIES
2199                 VLAN_CAPABILITIES(ifp);
2200 #endif
2201 fail:
2202                 end_synchronized_op(sc, 0);
2203                 break;
2204
2205         case SIOCSIFMEDIA:
2206         case SIOCGIFMEDIA:
2207         case SIOCGIFXMEDIA:
2208                 ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
2209                 break;
2210
2211         case SIOCGI2C: {
2212                 struct ifi2creq i2c;
2213
2214                 rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
2215                 if (rc != 0)
2216                         break;
2217                 if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
2218                         rc = EPERM;
2219                         break;
2220                 }
2221                 if (i2c.len > sizeof(i2c.data)) {
2222                         rc = EINVAL;
2223                         break;
2224                 }
2225                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
2226                 if (rc)
2227                         return (rc);
2228                 rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
2229                     i2c.offset, i2c.len, &i2c.data[0]);
2230                 end_synchronized_op(sc, 0);
2231                 if (rc == 0)
2232                         rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
2233                 break;
2234         }
2235
2236         default:
2237                 rc = ether_ioctl(ifp, cmd, data);
2238         }
2239
2240         return (rc);
2241 }
2242
2243 static int
2244 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2245 {
2246         struct vi_info *vi = ifp->if_softc;
2247         struct port_info *pi = vi->pi;
2248         struct adapter *sc;
2249         struct sge_txq *txq;
2250         void *items[1];
2251         int rc;
2252
2253         M_ASSERTPKTHDR(m);
2254         MPASS(m->m_nextpkt == NULL);    /* not quite ready for this yet */
2255 #if defined(KERN_TLS) || defined(RATELIMIT)
2256         if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
2257                 MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
2258 #endif
2259
2260         if (__predict_false(pi->link_cfg.link_ok == false)) {
2261                 m_freem(m);
2262                 return (ENETDOWN);
2263         }
2264
2265         rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
2266         if (__predict_false(rc != 0)) {
2267                 MPASS(m == NULL);                       /* was freed already */
2268                 atomic_add_int(&pi->tx_parse_error, 1); /* rare, atomic is ok */
2269                 return (rc);
2270         }
2271 #ifdef RATELIMIT
2272         if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
2273                 if (m->m_pkthdr.snd_tag->type == IF_SND_TAG_TYPE_RATE_LIMIT)
2274                         return (ethofld_transmit(ifp, m));
2275         }
2276 #endif
2277
2278         /* Select a txq. */
2279         sc = vi->adapter;
2280         txq = &sc->sge.txq[vi->first_txq];
2281         if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2282                 txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2283                     vi->rsrv_noflowq);
2284
2285         items[0] = m;
2286         rc = mp_ring_enqueue(txq->r, items, 1, 256);
2287         if (__predict_false(rc != 0))
2288                 m_freem(m);
2289
2290         return (rc);
2291 }
2292
2293 static void
2294 cxgbe_qflush(struct ifnet *ifp)
2295 {
2296         struct vi_info *vi = ifp->if_softc;
2297         struct sge_txq *txq;
2298         int i;
2299
2300         /* queues do not exist if !VI_INIT_DONE. */
2301         if (vi->flags & VI_INIT_DONE) {
2302                 for_each_txq(vi, i, txq) {
2303                         TXQ_LOCK(txq);
2304                         txq->eq.flags |= EQ_QFLUSH;
2305                         TXQ_UNLOCK(txq);
2306                         while (!mp_ring_is_idle(txq->r)) {
2307                                 mp_ring_check_drainage(txq->r, 4096);
2308                                 pause("qflush", 1);
2309                         }
2310                         TXQ_LOCK(txq);
2311                         txq->eq.flags &= ~EQ_QFLUSH;
2312                         TXQ_UNLOCK(txq);
2313                 }
2314         }
2315         if_qflush(ifp);
2316 }
2317
2318 static uint64_t
2319 vi_get_counter(struct ifnet *ifp, ift_counter c)
2320 {
2321         struct vi_info *vi = ifp->if_softc;
2322         struct fw_vi_stats_vf *s = &vi->stats;
2323
2324         vi_refresh_stats(vi->adapter, vi);
2325
2326         switch (c) {
2327         case IFCOUNTER_IPACKETS:
2328                 return (s->rx_bcast_frames + s->rx_mcast_frames +
2329                     s->rx_ucast_frames);
2330         case IFCOUNTER_IERRORS:
2331                 return (s->rx_err_frames);
2332         case IFCOUNTER_OPACKETS:
2333                 return (s->tx_bcast_frames + s->tx_mcast_frames +
2334                     s->tx_ucast_frames + s->tx_offload_frames);
2335         case IFCOUNTER_OERRORS:
2336                 return (s->tx_drop_frames);
2337         case IFCOUNTER_IBYTES:
2338                 return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2339                     s->rx_ucast_bytes);
2340         case IFCOUNTER_OBYTES:
2341                 return (s->tx_bcast_bytes + s->tx_mcast_bytes +
2342                     s->tx_ucast_bytes + s->tx_offload_bytes);
2343         case IFCOUNTER_IMCASTS:
2344                 return (s->rx_mcast_frames);
2345         case IFCOUNTER_OMCASTS:
2346                 return (s->tx_mcast_frames);
2347         case IFCOUNTER_OQDROPS: {
2348                 uint64_t drops;
2349
2350                 drops = 0;
2351                 if (vi->flags & VI_INIT_DONE) {
2352                         int i;
2353                         struct sge_txq *txq;
2354
2355                         for_each_txq(vi, i, txq)
2356                                 drops += counter_u64_fetch(txq->r->dropped);
2357                 }
2358
2359                 return (drops);
2360
2361         }
2362
2363         default:
2364                 return (if_get_counter_default(ifp, c));
2365         }
2366 }
2367
2368 uint64_t
2369 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
2370 {
2371         struct vi_info *vi = ifp->if_softc;
2372         struct port_info *pi = vi->pi;
2373         struct adapter *sc = pi->adapter;
2374         struct port_stats *s = &pi->stats;
2375
2376         if (pi->nvi > 1 || sc->flags & IS_VF)
2377                 return (vi_get_counter(ifp, c));
2378
2379         cxgbe_refresh_stats(sc, pi);
2380
2381         switch (c) {
2382         case IFCOUNTER_IPACKETS:
2383                 return (s->rx_frames);
2384
2385         case IFCOUNTER_IERRORS:
2386                 return (s->rx_jabber + s->rx_runt + s->rx_too_long +
2387                     s->rx_fcs_err + s->rx_len_err);
2388
2389         case IFCOUNTER_OPACKETS:
2390                 return (s->tx_frames);
2391
2392         case IFCOUNTER_OERRORS:
2393                 return (s->tx_error_frames);
2394
2395         case IFCOUNTER_IBYTES:
2396                 return (s->rx_octets);
2397
2398         case IFCOUNTER_OBYTES:
2399                 return (s->tx_octets);
2400
2401         case IFCOUNTER_IMCASTS:
2402                 return (s->rx_mcast_frames);
2403
2404         case IFCOUNTER_OMCASTS:
2405                 return (s->tx_mcast_frames);
2406
2407         case IFCOUNTER_IQDROPS:
2408                 return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
2409                     s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
2410                     s->rx_trunc3 + pi->tnl_cong_drops);
2411
2412         case IFCOUNTER_OQDROPS: {
2413                 uint64_t drops;
2414
2415                 drops = s->tx_drop;
2416                 if (vi->flags & VI_INIT_DONE) {
2417                         int i;
2418                         struct sge_txq *txq;
2419
2420                         for_each_txq(vi, i, txq)
2421                                 drops += counter_u64_fetch(txq->r->dropped);
2422                 }
2423
2424                 return (drops);
2425
2426         }
2427
2428         default:
2429                 return (if_get_counter_default(ifp, c));
2430         }
2431 }
2432
2433 #if defined(KERN_TLS) || defined(RATELIMIT)
2434 static int
2435 cxgbe_snd_tag_alloc(struct ifnet *ifp, union if_snd_tag_alloc_params *params,
2436     struct m_snd_tag **pt)
2437 {
2438         int error;
2439
2440         switch (params->hdr.type) {
2441 #ifdef RATELIMIT
2442         case IF_SND_TAG_TYPE_RATE_LIMIT:
2443                 error = cxgbe_rate_tag_alloc(ifp, params, pt);
2444                 break;
2445 #endif
2446 #ifdef KERN_TLS
2447         case IF_SND_TAG_TYPE_TLS:
2448                 error = cxgbe_tls_tag_alloc(ifp, params, pt);
2449                 break;
2450 #endif
2451         default:
2452                 error = EOPNOTSUPP;
2453         }
2454         return (error);
2455 }
2456
2457 static int
2458 cxgbe_snd_tag_modify(struct m_snd_tag *mst,
2459     union if_snd_tag_modify_params *params)
2460 {
2461
2462         switch (mst->type) {
2463 #ifdef RATELIMIT
2464         case IF_SND_TAG_TYPE_RATE_LIMIT:
2465                 return (cxgbe_rate_tag_modify(mst, params));
2466 #endif
2467         default:
2468                 return (EOPNOTSUPP);
2469         }
2470 }
2471
2472 static int
2473 cxgbe_snd_tag_query(struct m_snd_tag *mst,
2474     union if_snd_tag_query_params *params)
2475 {
2476
2477         switch (mst->type) {
2478 #ifdef RATELIMIT
2479         case IF_SND_TAG_TYPE_RATE_LIMIT:
2480                 return (cxgbe_rate_tag_query(mst, params));
2481 #endif
2482         default:
2483                 return (EOPNOTSUPP);
2484         }
2485 }
2486
2487 static void
2488 cxgbe_snd_tag_free(struct m_snd_tag *mst)
2489 {
2490
2491         switch (mst->type) {
2492 #ifdef RATELIMIT
2493         case IF_SND_TAG_TYPE_RATE_LIMIT:
2494                 cxgbe_rate_tag_free(mst);
2495                 return;
2496 #endif
2497 #ifdef KERN_TLS
2498         case IF_SND_TAG_TYPE_TLS:
2499                 cxgbe_tls_tag_free(mst);
2500                 return;
2501 #endif
2502         default:
2503                 panic("shouldn't get here");
2504         }
2505 }
2506 #endif
2507
2508 /*
2509  * The kernel picks a media from the list we had provided but we still validate
2510  * the requeste.
2511  */
2512 int
2513 cxgbe_media_change(struct ifnet *ifp)
2514 {
2515         struct vi_info *vi = ifp->if_softc;
2516         struct port_info *pi = vi->pi;
2517         struct ifmedia *ifm = &pi->media;
2518         struct link_config *lc = &pi->link_cfg;
2519         struct adapter *sc = pi->adapter;
2520         int rc;
2521
2522         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
2523         if (rc != 0)
2524                 return (rc);
2525         PORT_LOCK(pi);
2526         if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
2527                 /* ifconfig .. media autoselect */
2528                 if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
2529                         rc = ENOTSUP; /* AN not supported by transceiver */
2530                         goto done;
2531                 }
2532                 lc->requested_aneg = AUTONEG_ENABLE;
2533                 lc->requested_speed = 0;
2534                 lc->requested_fc |= PAUSE_AUTONEG;
2535         } else {
2536                 lc->requested_aneg = AUTONEG_DISABLE;
2537                 lc->requested_speed =
2538                     ifmedia_baudrate(ifm->ifm_media) / 1000000;
2539                 lc->requested_fc = 0;
2540                 if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
2541                         lc->requested_fc |= PAUSE_RX;
2542                 if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
2543                         lc->requested_fc |= PAUSE_TX;
2544         }
2545         if (pi->up_vis > 0) {
2546                 fixup_link_config(pi);
2547                 rc = apply_link_config(pi);
2548         }
2549 done:
2550         PORT_UNLOCK(pi);
2551         end_synchronized_op(sc, 0);
2552         return (rc);
2553 }
2554
2555 /*
2556  * Base media word (without ETHER, pause, link active, etc.) for the port at the
2557  * given speed.
2558  */
2559 static int
2560 port_mword(struct port_info *pi, uint32_t speed)
2561 {
2562
2563         MPASS(speed & M_FW_PORT_CAP32_SPEED);
2564         MPASS(powerof2(speed));
2565
2566         switch(pi->port_type) {
2567         case FW_PORT_TYPE_BT_SGMII:
2568         case FW_PORT_TYPE_BT_XFI:
2569         case FW_PORT_TYPE_BT_XAUI:
2570                 /* BaseT */
2571                 switch (speed) {
2572                 case FW_PORT_CAP32_SPEED_100M:
2573                         return (IFM_100_T);
2574                 case FW_PORT_CAP32_SPEED_1G:
2575                         return (IFM_1000_T);
2576                 case FW_PORT_CAP32_SPEED_10G:
2577                         return (IFM_10G_T);
2578                 }
2579                 break;
2580         case FW_PORT_TYPE_KX4:
2581                 if (speed == FW_PORT_CAP32_SPEED_10G)
2582                         return (IFM_10G_KX4);
2583                 break;
2584         case FW_PORT_TYPE_CX4:
2585                 if (speed == FW_PORT_CAP32_SPEED_10G)
2586                         return (IFM_10G_CX4);
2587                 break;
2588         case FW_PORT_TYPE_KX:
2589                 if (speed == FW_PORT_CAP32_SPEED_1G)
2590                         return (IFM_1000_KX);
2591                 break;
2592         case FW_PORT_TYPE_KR:
2593         case FW_PORT_TYPE_BP_AP:
2594         case FW_PORT_TYPE_BP4_AP:
2595         case FW_PORT_TYPE_BP40_BA:
2596         case FW_PORT_TYPE_KR4_100G:
2597         case FW_PORT_TYPE_KR_SFP28:
2598         case FW_PORT_TYPE_KR_XLAUI:
2599                 switch (speed) {
2600                 case FW_PORT_CAP32_SPEED_1G:
2601                         return (IFM_1000_KX);
2602                 case FW_PORT_CAP32_SPEED_10G:
2603                         return (IFM_10G_KR);
2604                 case FW_PORT_CAP32_SPEED_25G:
2605                         return (IFM_25G_KR);
2606                 case FW_PORT_CAP32_SPEED_40G:
2607                         return (IFM_40G_KR4);
2608                 case FW_PORT_CAP32_SPEED_50G:
2609                         return (IFM_50G_KR2);
2610                 case FW_PORT_CAP32_SPEED_100G:
2611                         return (IFM_100G_KR4);
2612                 }
2613                 break;
2614         case FW_PORT_TYPE_FIBER_XFI:
2615         case FW_PORT_TYPE_FIBER_XAUI:
2616         case FW_PORT_TYPE_SFP:
2617         case FW_PORT_TYPE_QSFP_10G:
2618         case FW_PORT_TYPE_QSA:
2619         case FW_PORT_TYPE_QSFP:
2620         case FW_PORT_TYPE_CR4_QSFP:
2621         case FW_PORT_TYPE_CR_QSFP:
2622         case FW_PORT_TYPE_CR2_QSFP:
2623         case FW_PORT_TYPE_SFP28:
2624                 /* Pluggable transceiver */
2625                 switch (pi->mod_type) {
2626                 case FW_PORT_MOD_TYPE_LR:
2627                         switch (speed) {
2628                         case FW_PORT_CAP32_SPEED_1G:
2629                                 return (IFM_1000_LX);
2630                         case FW_PORT_CAP32_SPEED_10G:
2631                                 return (IFM_10G_LR);
2632                         case FW_PORT_CAP32_SPEED_25G:
2633                                 return (IFM_25G_LR);
2634                         case FW_PORT_CAP32_SPEED_40G:
2635                                 return (IFM_40G_LR4);
2636                         case FW_PORT_CAP32_SPEED_50G:
2637                                 return (IFM_50G_LR2);
2638                         case FW_PORT_CAP32_SPEED_100G:
2639                                 return (IFM_100G_LR4);
2640                         }
2641                         break;
2642                 case FW_PORT_MOD_TYPE_SR:
2643                         switch (speed) {
2644                         case FW_PORT_CAP32_SPEED_1G:
2645                                 return (IFM_1000_SX);
2646                         case FW_PORT_CAP32_SPEED_10G:
2647                                 return (IFM_10G_SR);
2648                         case FW_PORT_CAP32_SPEED_25G:
2649                                 return (IFM_25G_SR);
2650                         case FW_PORT_CAP32_SPEED_40G:
2651                                 return (IFM_40G_SR4);
2652                         case FW_PORT_CAP32_SPEED_50G:
2653                                 return (IFM_50G_SR2);
2654                         case FW_PORT_CAP32_SPEED_100G:
2655                                 return (IFM_100G_SR4);
2656                         }
2657                         break;
2658                 case FW_PORT_MOD_TYPE_ER:
2659                         if (speed == FW_PORT_CAP32_SPEED_10G)
2660                                 return (IFM_10G_ER);
2661                         break;
2662                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
2663                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
2664                         switch (speed) {
2665                         case FW_PORT_CAP32_SPEED_1G:
2666                                 return (IFM_1000_CX);
2667                         case FW_PORT_CAP32_SPEED_10G:
2668                                 return (IFM_10G_TWINAX);
2669                         case FW_PORT_CAP32_SPEED_25G:
2670                                 return (IFM_25G_CR);
2671                         case FW_PORT_CAP32_SPEED_40G:
2672                                 return (IFM_40G_CR4);
2673                         case FW_PORT_CAP32_SPEED_50G:
2674                                 return (IFM_50G_CR2);
2675                         case FW_PORT_CAP32_SPEED_100G:
2676                                 return (IFM_100G_CR4);
2677                         }
2678                         break;
2679                 case FW_PORT_MOD_TYPE_LRM:
2680                         if (speed == FW_PORT_CAP32_SPEED_10G)
2681                                 return (IFM_10G_LRM);
2682                         break;
2683                 case FW_PORT_MOD_TYPE_NA:
2684                         MPASS(0);       /* Not pluggable? */
2685                         /* fall throough */
2686                 case FW_PORT_MOD_TYPE_ERROR:
2687                 case FW_PORT_MOD_TYPE_UNKNOWN:
2688                 case FW_PORT_MOD_TYPE_NOTSUPPORTED:
2689                         break;
2690                 case FW_PORT_MOD_TYPE_NONE:
2691                         return (IFM_NONE);
2692                 }
2693                 break;
2694         case FW_PORT_TYPE_NONE:
2695                 return (IFM_NONE);
2696         }
2697
2698         return (IFM_UNKNOWN);
2699 }
2700
2701 void
2702 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
2703 {
2704         struct vi_info *vi = ifp->if_softc;
2705         struct port_info *pi = vi->pi;
2706         struct adapter *sc = pi->adapter;
2707         struct link_config *lc = &pi->link_cfg;
2708
2709         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
2710                 return;
2711         PORT_LOCK(pi);
2712
2713         if (pi->up_vis == 0) {
2714                 /*
2715                  * If all the interfaces are administratively down the firmware
2716                  * does not report transceiver changes.  Refresh port info here
2717                  * so that ifconfig displays accurate ifmedia at all times.
2718                  * This is the only reason we have a synchronized op in this
2719                  * function.  Just PORT_LOCK would have been enough otherwise.
2720                  */
2721                 t4_update_port_info(pi);
2722                 build_medialist(pi);
2723         }
2724
2725         /* ifm_status */
2726         ifmr->ifm_status = IFM_AVALID;
2727         if (lc->link_ok == false)
2728                 goto done;
2729         ifmr->ifm_status |= IFM_ACTIVE;
2730
2731         /* ifm_active */
2732         ifmr->ifm_active = IFM_ETHER | IFM_FDX;
2733         ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
2734         if (lc->fc & PAUSE_RX)
2735                 ifmr->ifm_active |= IFM_ETH_RXPAUSE;
2736         if (lc->fc & PAUSE_TX)
2737                 ifmr->ifm_active |= IFM_ETH_TXPAUSE;
2738         ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
2739 done:
2740         PORT_UNLOCK(pi);
2741         end_synchronized_op(sc, 0);
2742 }
2743
2744 static int
2745 vcxgbe_probe(device_t dev)
2746 {
2747         char buf[128];
2748         struct vi_info *vi = device_get_softc(dev);
2749
2750         snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
2751             vi - vi->pi->vi);
2752         device_set_desc_copy(dev, buf);
2753
2754         return (BUS_PROBE_DEFAULT);
2755 }
2756
2757 static int
2758 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
2759 {
2760         int func, index, rc;
2761         uint32_t param, val;
2762
2763         ASSERT_SYNCHRONIZED_OP(sc);
2764
2765         index = vi - pi->vi;
2766         MPASS(index > 0);       /* This function deals with _extra_ VIs only */
2767         KASSERT(index < nitems(vi_mac_funcs),
2768             ("%s: VI %s doesn't have a MAC func", __func__,
2769             device_get_nameunit(vi->dev)));
2770         func = vi_mac_funcs[index];
2771         rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
2772             vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
2773         if (rc < 0) {
2774                 device_printf(vi->dev, "failed to allocate virtual interface %d"
2775                     "for port %d: %d\n", index, pi->port_id, -rc);
2776                 return (-rc);
2777         }
2778         vi->viid = rc;
2779
2780         if (vi->rss_size == 1) {
2781                 /*
2782                  * This VI didn't get a slice of the RSS table.  Reduce the
2783                  * number of VIs being created (hw.cxgbe.num_vis) or modify the
2784                  * configuration file (nvi, rssnvi for this PF) if this is a
2785                  * problem.
2786                  */
2787                 device_printf(vi->dev, "RSS table not available.\n");
2788                 vi->rss_base = 0xffff;
2789
2790                 return (0);
2791         }
2792
2793         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
2794             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
2795             V_FW_PARAMS_PARAM_YZ(vi->viid);
2796         rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2797         if (rc)
2798                 vi->rss_base = 0xffff;
2799         else {
2800                 MPASS((val >> 16) == vi->rss_size);
2801                 vi->rss_base = val & 0xffff;
2802         }
2803
2804         return (0);
2805 }
2806
2807 static int
2808 vcxgbe_attach(device_t dev)
2809 {
2810         struct vi_info *vi;
2811         struct port_info *pi;
2812         struct adapter *sc;
2813         int rc;
2814
2815         vi = device_get_softc(dev);
2816         pi = vi->pi;
2817         sc = pi->adapter;
2818
2819         rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
2820         if (rc)
2821                 return (rc);
2822         rc = alloc_extra_vi(sc, pi, vi);
2823         end_synchronized_op(sc, 0);
2824         if (rc)
2825                 return (rc);
2826
2827         rc = cxgbe_vi_attach(dev, vi);
2828         if (rc) {
2829                 t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2830                 return (rc);
2831         }
2832         return (0);
2833 }
2834
2835 static int
2836 vcxgbe_detach(device_t dev)
2837 {
2838         struct vi_info *vi;
2839         struct adapter *sc;
2840
2841         vi = device_get_softc(dev);
2842         sc = vi->adapter;
2843
2844         doom_vi(sc, vi);
2845
2846         cxgbe_vi_detach(vi);
2847         t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2848
2849         end_synchronized_op(sc, 0);
2850
2851         return (0);
2852 }
2853
2854 static struct callout fatal_callout;
2855
2856 static void
2857 delayed_panic(void *arg)
2858 {
2859         struct adapter *sc = arg;
2860
2861         panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
2862 }
2863
2864 void
2865 t4_fatal_err(struct adapter *sc, bool fw_error)
2866 {
2867
2868         t4_shutdown_adapter(sc);
2869         log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
2870             device_get_nameunit(sc->dev));
2871         if (fw_error) {
2872                 ASSERT_SYNCHRONIZED_OP(sc);
2873                 sc->flags |= ADAP_ERR;
2874         } else {
2875                 ADAPTER_LOCK(sc);
2876                 sc->flags |= ADAP_ERR;
2877                 ADAPTER_UNLOCK(sc);
2878         }
2879 #ifdef TCP_OFFLOAD
2880         taskqueue_enqueue(taskqueue_thread, &sc->async_event_task);
2881 #endif
2882
2883         if (t4_panic_on_fatal_err) {
2884                 log(LOG_ALERT, "%s: panic on fatal error after 30s",
2885                     device_get_nameunit(sc->dev));
2886                 callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
2887         }
2888 }
2889
2890 void
2891 t4_add_adapter(struct adapter *sc)
2892 {
2893         sx_xlock(&t4_list_lock);
2894         SLIST_INSERT_HEAD(&t4_list, sc, link);
2895         sx_xunlock(&t4_list_lock);
2896 }
2897
2898 int
2899 t4_map_bars_0_and_4(struct adapter *sc)
2900 {
2901         sc->regs_rid = PCIR_BAR(0);
2902         sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2903             &sc->regs_rid, RF_ACTIVE);
2904         if (sc->regs_res == NULL) {
2905                 device_printf(sc->dev, "cannot map registers.\n");
2906                 return (ENXIO);
2907         }
2908         sc->bt = rman_get_bustag(sc->regs_res);
2909         sc->bh = rman_get_bushandle(sc->regs_res);
2910         sc->mmio_len = rman_get_size(sc->regs_res);
2911         setbit(&sc->doorbells, DOORBELL_KDB);
2912
2913         sc->msix_rid = PCIR_BAR(4);
2914         sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2915             &sc->msix_rid, RF_ACTIVE);
2916         if (sc->msix_res == NULL) {
2917                 device_printf(sc->dev, "cannot map MSI-X BAR.\n");
2918                 return (ENXIO);
2919         }
2920
2921         return (0);
2922 }
2923
2924 int
2925 t4_map_bar_2(struct adapter *sc)
2926 {
2927
2928         /*
2929          * T4: only iWARP driver uses the userspace doorbells.  There is no need
2930          * to map it if RDMA is disabled.
2931          */
2932         if (is_t4(sc) && sc->rdmacaps == 0)
2933                 return (0);
2934
2935         sc->udbs_rid = PCIR_BAR(2);
2936         sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2937             &sc->udbs_rid, RF_ACTIVE);
2938         if (sc->udbs_res == NULL) {
2939                 device_printf(sc->dev, "cannot map doorbell BAR.\n");
2940                 return (ENXIO);
2941         }
2942         sc->udbs_base = rman_get_virtual(sc->udbs_res);
2943
2944         if (chip_id(sc) >= CHELSIO_T5) {
2945                 setbit(&sc->doorbells, DOORBELL_UDB);
2946 #if defined(__i386__) || defined(__amd64__)
2947                 if (t5_write_combine) {
2948                         int rc, mode;
2949
2950                         /*
2951                          * Enable write combining on BAR2.  This is the
2952                          * userspace doorbell BAR and is split into 128B
2953                          * (UDBS_SEG_SIZE) doorbell regions, each associated
2954                          * with an egress queue.  The first 64B has the doorbell
2955                          * and the second 64B can be used to submit a tx work
2956                          * request with an implicit doorbell.
2957                          */
2958
2959                         rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
2960                             rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
2961                         if (rc == 0) {
2962                                 clrbit(&sc->doorbells, DOORBELL_UDB);
2963                                 setbit(&sc->doorbells, DOORBELL_WCWR);
2964                                 setbit(&sc->doorbells, DOORBELL_UDBWC);
2965                         } else {
2966                                 device_printf(sc->dev,
2967                                     "couldn't enable write combining: %d\n",
2968                                     rc);
2969                         }
2970
2971                         mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
2972                         t4_write_reg(sc, A_SGE_STAT_CFG,
2973                             V_STATSOURCE_T5(7) | mode);
2974                 }
2975 #endif
2976         }
2977         sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
2978
2979         return (0);
2980 }
2981
2982 struct memwin_init {
2983         uint32_t base;
2984         uint32_t aperture;
2985 };
2986
2987 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
2988         { MEMWIN0_BASE, MEMWIN0_APERTURE },
2989         { MEMWIN1_BASE, MEMWIN1_APERTURE },
2990         { MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
2991 };
2992
2993 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
2994         { MEMWIN0_BASE, MEMWIN0_APERTURE },
2995         { MEMWIN1_BASE, MEMWIN1_APERTURE },
2996         { MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
2997 };
2998
2999 static void
3000 setup_memwin(struct adapter *sc)
3001 {
3002         const struct memwin_init *mw_init;
3003         struct memwin *mw;
3004         int i;
3005         uint32_t bar0;
3006
3007         if (is_t4(sc)) {
3008                 /*
3009                  * Read low 32b of bar0 indirectly via the hardware backdoor
3010                  * mechanism.  Works from within PCI passthrough environments
3011                  * too, where rman_get_start() can return a different value.  We
3012                  * need to program the T4 memory window decoders with the actual
3013                  * addresses that will be coming across the PCIe link.
3014                  */
3015                 bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3016                 bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3017
3018                 mw_init = &t4_memwin[0];
3019         } else {
3020                 /* T5+ use the relative offset inside the PCIe BAR */
3021                 bar0 = 0;
3022
3023                 mw_init = &t5_memwin[0];
3024         }
3025
3026         for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3027                 rw_init(&mw->mw_lock, "memory window access");
3028                 mw->mw_base = mw_init->base;
3029                 mw->mw_aperture = mw_init->aperture;
3030                 mw->mw_curpos = 0;
3031                 t4_write_reg(sc,
3032                     PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3033                     (mw->mw_base + bar0) | V_BIR(0) |
3034                     V_WINDOW(ilog2(mw->mw_aperture) - 10));
3035                 rw_wlock(&mw->mw_lock);
3036                 position_memwin(sc, i, 0);
3037                 rw_wunlock(&mw->mw_lock);
3038         }
3039
3040         /* flush */
3041         t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3042 }
3043
3044 /*
3045  * Positions the memory window at the given address in the card's address space.
3046  * There are some alignment requirements and the actual position may be at an
3047  * address prior to the requested address.  mw->mw_curpos always has the actual
3048  * position of the window.
3049  */
3050 static void
3051 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3052 {
3053         struct memwin *mw;
3054         uint32_t pf;
3055         uint32_t reg;
3056
3057         MPASS(idx >= 0 && idx < NUM_MEMWIN);
3058         mw = &sc->memwin[idx];
3059         rw_assert(&mw->mw_lock, RA_WLOCKED);
3060
3061         if (is_t4(sc)) {
3062                 pf = 0;
3063                 mw->mw_curpos = addr & ~0xf;    /* start must be 16B aligned */
3064         } else {
3065                 pf = V_PFNUM(sc->pf);
3066                 mw->mw_curpos = addr & ~0x7f;   /* start must be 128B aligned */
3067         }
3068         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3069         t4_write_reg(sc, reg, mw->mw_curpos | pf);
3070         t4_read_reg(sc, reg);   /* flush */
3071 }
3072
3073 int
3074 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3075     int len, int rw)
3076 {
3077         struct memwin *mw;
3078         uint32_t mw_end, v;
3079
3080         MPASS(idx >= 0 && idx < NUM_MEMWIN);
3081
3082         /* Memory can only be accessed in naturally aligned 4 byte units */
3083         if (addr & 3 || len & 3 || len <= 0)
3084                 return (EINVAL);
3085
3086         mw = &sc->memwin[idx];
3087         while (len > 0) {
3088                 rw_rlock(&mw->mw_lock);
3089                 mw_end = mw->mw_curpos + mw->mw_aperture;
3090                 if (addr >= mw_end || addr < mw->mw_curpos) {
3091                         /* Will need to reposition the window */
3092                         if (!rw_try_upgrade(&mw->mw_lock)) {
3093                                 rw_runlock(&mw->mw_lock);
3094                                 rw_wlock(&mw->mw_lock);
3095                         }
3096                         rw_assert(&mw->mw_lock, RA_WLOCKED);
3097                         position_memwin(sc, idx, addr);
3098                         rw_downgrade(&mw->mw_lock);
3099                         mw_end = mw->mw_curpos + mw->mw_aperture;
3100                 }
3101                 rw_assert(&mw->mw_lock, RA_RLOCKED);
3102                 while (addr < mw_end && len > 0) {
3103                         if (rw == 0) {
3104                                 v = t4_read_reg(sc, mw->mw_base + addr -
3105                                     mw->mw_curpos);
3106                                 *val++ = le32toh(v);
3107                         } else {
3108                                 v = *val++;
3109                                 t4_write_reg(sc, mw->mw_base + addr -
3110                                     mw->mw_curpos, htole32(v));
3111                         }
3112                         addr += 4;
3113                         len -= 4;
3114                 }
3115                 rw_runlock(&mw->mw_lock);
3116         }
3117
3118         return (0);
3119 }
3120
3121 static void
3122 t4_init_atid_table(struct adapter *sc)
3123 {
3124         struct tid_info *t;
3125         int i;
3126
3127         t = &sc->tids;
3128         if (t->natids == 0)
3129                 return;
3130
3131         MPASS(t->atid_tab == NULL);
3132
3133         t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3134             M_ZERO | M_WAITOK);
3135         mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3136         t->afree = t->atid_tab;
3137         t->atids_in_use = 0;
3138         for (i = 1; i < t->natids; i++)
3139                 t->atid_tab[i - 1].next = &t->atid_tab[i];
3140         t->atid_tab[t->natids - 1].next = NULL;
3141 }
3142
3143 static void
3144 t4_free_atid_table(struct adapter *sc)
3145 {
3146         struct tid_info *t;
3147
3148         t = &sc->tids;
3149
3150         KASSERT(t->atids_in_use == 0,
3151             ("%s: %d atids still in use.", __func__, t->atids_in_use));
3152
3153         if (mtx_initialized(&t->atid_lock))
3154                 mtx_destroy(&t->atid_lock);
3155         free(t->atid_tab, M_CXGBE);
3156         t->atid_tab = NULL;
3157 }
3158
3159 int
3160 alloc_atid(struct adapter *sc, void *ctx)
3161 {
3162         struct tid_info *t = &sc->tids;
3163         int atid = -1;
3164
3165         mtx_lock(&t->atid_lock);
3166         if (t->afree) {
3167                 union aopen_entry *p = t->afree;
3168
3169                 atid = p - t->atid_tab;
3170                 MPASS(atid <= M_TID_TID);
3171                 t->afree = p->next;
3172                 p->data = ctx;
3173                 t->atids_in_use++;
3174         }
3175         mtx_unlock(&t->atid_lock);
3176         return (atid);
3177 }
3178
3179 void *
3180 lookup_atid(struct adapter *sc, int atid)
3181 {
3182         struct tid_info *t = &sc->tids;
3183
3184         return (t->atid_tab[atid].data);
3185 }
3186
3187 void
3188 free_atid(struct adapter *sc, int atid)
3189 {
3190         struct tid_info *t = &sc->tids;
3191         union aopen_entry *p = &t->atid_tab[atid];
3192
3193         mtx_lock(&t->atid_lock);
3194         p->next = t->afree;
3195         t->afree = p;
3196         t->atids_in_use--;
3197         mtx_unlock(&t->atid_lock);
3198 }
3199
3200 static void
3201 queue_tid_release(struct adapter *sc, int tid)
3202 {
3203
3204         CXGBE_UNIMPLEMENTED("deferred tid release");
3205 }
3206
3207 void
3208 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3209 {
3210         struct wrqe *wr;
3211         struct cpl_tid_release *req;
3212
3213         wr = alloc_wrqe(sizeof(*req), ctrlq);
3214         if (wr == NULL) {
3215                 queue_tid_release(sc, tid);     /* defer */
3216                 return;
3217         }
3218         req = wrtod(wr);
3219
3220         INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
3221
3222         t4_wrq_tx(sc, wr);
3223 }
3224
3225 static int
3226 t4_range_cmp(const void *a, const void *b)
3227 {
3228         return ((const struct t4_range *)a)->start -
3229                ((const struct t4_range *)b)->start;
3230 }
3231
3232 /*
3233  * Verify that the memory range specified by the addr/len pair is valid within
3234  * the card's address space.
3235  */
3236 static int
3237 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
3238 {
3239         struct t4_range mem_ranges[4], *r, *next;
3240         uint32_t em, addr_len;
3241         int i, n, remaining;
3242
3243         /* Memory can only be accessed in naturally aligned 4 byte units */
3244         if (addr & 3 || len & 3 || len == 0)
3245                 return (EINVAL);
3246
3247         /* Enabled memories */
3248         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3249
3250         r = &mem_ranges[0];
3251         n = 0;
3252         bzero(r, sizeof(mem_ranges));
3253         if (em & F_EDRAM0_ENABLE) {
3254                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3255                 r->size = G_EDRAM0_SIZE(addr_len) << 20;
3256                 if (r->size > 0) {
3257                         r->start = G_EDRAM0_BASE(addr_len) << 20;
3258                         if (addr >= r->start &&
3259                             addr + len <= r->start + r->size)
3260                                 return (0);
3261                         r++;
3262                         n++;
3263                 }
3264         }
3265         if (em & F_EDRAM1_ENABLE) {
3266                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3267                 r->size = G_EDRAM1_SIZE(addr_len) << 20;
3268                 if (r->size > 0) {
3269                         r->start = G_EDRAM1_BASE(addr_len) << 20;
3270                         if (addr >= r->start &&
3271                             addr + len <= r->start + r->size)
3272                                 return (0);
3273                         r++;
3274                         n++;
3275                 }
3276         }
3277         if (em & F_EXT_MEM_ENABLE) {
3278                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3279                 r->size = G_EXT_MEM_SIZE(addr_len) << 20;
3280                 if (r->size > 0) {
3281                         r->start = G_EXT_MEM_BASE(addr_len) << 20;
3282                         if (addr >= r->start &&
3283                             addr + len <= r->start + r->size)
3284                                 return (0);
3285                         r++;
3286                         n++;
3287                 }
3288         }
3289         if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
3290                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3291                 r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
3292                 if (r->size > 0) {
3293                         r->start = G_EXT_MEM1_BASE(addr_len) << 20;
3294                         if (addr >= r->start &&
3295                             addr + len <= r->start + r->size)
3296                                 return (0);
3297                         r++;
3298                         n++;
3299                 }
3300         }
3301         MPASS(n <= nitems(mem_ranges));
3302
3303         if (n > 1) {
3304                 /* Sort and merge the ranges. */
3305                 qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
3306
3307                 /* Start from index 0 and examine the next n - 1 entries. */
3308                 r = &mem_ranges[0];
3309                 for (remaining = n - 1; remaining > 0; remaining--, r++) {
3310
3311                         MPASS(r->size > 0);     /* r is a valid entry. */
3312                         next = r + 1;
3313                         MPASS(next->size > 0);  /* and so is the next one. */
3314
3315                         while (r->start + r->size >= next->start) {
3316                                 /* Merge the next one into the current entry. */
3317                                 r->size = max(r->start + r->size,
3318                                     next->start + next->size) - r->start;
3319                                 n--;    /* One fewer entry in total. */
3320                                 if (--remaining == 0)
3321                                         goto done;      /* short circuit */
3322                                 next++;
3323                         }
3324                         if (next != r + 1) {
3325                                 /*
3326                                  * Some entries were merged into r and next
3327                                  * points to the first valid entry that couldn't
3328                                  * be merged.
3329                                  */
3330                                 MPASS(next->size > 0);  /* must be valid */
3331                                 memcpy(r + 1, next, remaining * sizeof(*r));
3332 #ifdef INVARIANTS
3333                                 /*
3334                                  * This so that the foo->size assertion in the
3335                                  * next iteration of the loop do the right
3336                                  * thing for entries that were pulled up and are
3337                                  * no longer valid.
3338                                  */
3339                                 MPASS(n < nitems(mem_ranges));
3340                                 bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3341                                     sizeof(struct t4_range));
3342 #endif
3343                         }
3344                 }
3345 done:
3346                 /* Done merging the ranges. */
3347                 MPASS(n > 0);
3348                 r = &mem_ranges[0];
3349                 for (i = 0; i < n; i++, r++) {
3350                         if (addr >= r->start &&
3351                             addr + len <= r->start + r->size)
3352                                 return (0);
3353                 }
3354         }
3355
3356         return (EFAULT);
3357 }
3358
3359 static int
3360 fwmtype_to_hwmtype(int mtype)
3361 {
3362
3363         switch (mtype) {
3364         case FW_MEMTYPE_EDC0:
3365                 return (MEM_EDC0);
3366         case FW_MEMTYPE_EDC1:
3367                 return (MEM_EDC1);
3368         case FW_MEMTYPE_EXTMEM:
3369                 return (MEM_MC0);
3370         case FW_MEMTYPE_EXTMEM1:
3371                 return (MEM_MC1);
3372         default:
3373                 panic("%s: cannot translate fw mtype %d.", __func__, mtype);
3374         }
3375 }
3376
3377 /*
3378  * Verify that the memory range specified by the memtype/offset/len pair is
3379  * valid and lies entirely within the memtype specified.  The global address of
3380  * the start of the range is returned in addr.
3381  */
3382 static int
3383 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
3384     uint32_t *addr)
3385 {
3386         uint32_t em, addr_len, maddr;
3387
3388         /* Memory can only be accessed in naturally aligned 4 byte units */
3389         if (off & 3 || len & 3 || len == 0)
3390                 return (EINVAL);
3391
3392         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3393         switch (fwmtype_to_hwmtype(mtype)) {
3394         case MEM_EDC0:
3395                 if (!(em & F_EDRAM0_ENABLE))
3396                         return (EINVAL);
3397                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3398                 maddr = G_EDRAM0_BASE(addr_len) << 20;
3399                 break;
3400         case MEM_EDC1:
3401                 if (!(em & F_EDRAM1_ENABLE))
3402                         return (EINVAL);
3403                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3404                 maddr = G_EDRAM1_BASE(addr_len) << 20;
3405                 break;
3406         case MEM_MC:
3407                 if (!(em & F_EXT_MEM_ENABLE))
3408                         return (EINVAL);
3409                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3410                 maddr = G_EXT_MEM_BASE(addr_len) << 20;
3411                 break;
3412         case MEM_MC1:
3413                 if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
3414                         return (EINVAL);
3415                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3416                 maddr = G_EXT_MEM1_BASE(addr_len) << 20;
3417                 break;
3418         default:
3419                 return (EINVAL);
3420         }
3421
3422         *addr = maddr + off;    /* global address */
3423         return (validate_mem_range(sc, *addr, len));
3424 }
3425
3426 static int
3427 fixup_devlog_params(struct adapter *sc)
3428 {
3429         struct devlog_params *dparams = &sc->params.devlog;
3430         int rc;
3431
3432         rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
3433             dparams->size, &dparams->addr);
3434
3435         return (rc);
3436 }
3437
3438 static void
3439 update_nirq(struct intrs_and_queues *iaq, int nports)
3440 {
3441
3442         iaq->nirq = T4_EXTRA_INTR;
3443         iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
3444         iaq->nirq += nports * iaq->nofldrxq;
3445         iaq->nirq += nports * (iaq->num_vis - 1) *
3446             max(iaq->nrxq_vi, iaq->nnmrxq_vi);
3447         iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
3448 }
3449
3450 /*
3451  * Adjust requirements to fit the number of interrupts available.
3452  */
3453 static void
3454 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
3455     int navail)
3456 {
3457         int old_nirq;
3458         const int nports = sc->params.nports;
3459
3460         MPASS(nports > 0);
3461         MPASS(navail > 0);
3462
3463         bzero(iaq, sizeof(*iaq));
3464         iaq->intr_type = itype;
3465         iaq->num_vis = t4_num_vis;
3466         iaq->ntxq = t4_ntxq;
3467         iaq->ntxq_vi = t4_ntxq_vi;
3468         iaq->nrxq = t4_nrxq;
3469         iaq->nrxq_vi = t4_nrxq_vi;
3470 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
3471         if (is_offload(sc) || is_ethoffload(sc)) {
3472                 iaq->nofldtxq = t4_nofldtxq;
3473                 iaq->nofldtxq_vi = t4_nofldtxq_vi;
3474         }
3475 #endif
3476 #ifdef TCP_OFFLOAD
3477         if (is_offload(sc)) {
3478                 iaq->nofldrxq = t4_nofldrxq;
3479                 iaq->nofldrxq_vi = t4_nofldrxq_vi;
3480         }
3481 #endif
3482 #ifdef DEV_NETMAP
3483         if (t4_native_netmap & NN_MAIN_VI) {
3484                 iaq->nnmtxq = t4_nnmtxq;
3485                 iaq->nnmrxq = t4_nnmrxq;
3486         }
3487         if (t4_native_netmap & NN_EXTRA_VI) {
3488                 iaq->nnmtxq_vi = t4_nnmtxq_vi;
3489                 iaq->nnmrxq_vi = t4_nnmrxq_vi;
3490         }
3491 #endif
3492
3493         update_nirq(iaq, nports);
3494         if (iaq->nirq <= navail &&
3495             (itype != INTR_MSI || powerof2(iaq->nirq))) {
3496                 /*
3497                  * This is the normal case -- there are enough interrupts for
3498                  * everything.
3499                  */
3500                 goto done;
3501         }
3502
3503         /*
3504          * If extra VIs have been configured try reducing their count and see if
3505          * that works.
3506          */
3507         while (iaq->num_vis > 1) {
3508                 iaq->num_vis--;
3509                 update_nirq(iaq, nports);
3510                 if (iaq->nirq <= navail &&
3511                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
3512                         device_printf(sc->dev, "virtual interfaces per port "
3513                             "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
3514                             "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
3515                             "itype %d, navail %u, nirq %d.\n",
3516                             iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
3517                             iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
3518                             itype, navail, iaq->nirq);
3519                         goto done;
3520                 }
3521         }
3522
3523         /*
3524          * Extra VIs will not be created.  Log a message if they were requested.
3525          */
3526         MPASS(iaq->num_vis == 1);
3527         iaq->ntxq_vi = iaq->nrxq_vi = 0;
3528         iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
3529         iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
3530         if (iaq->num_vis != t4_num_vis) {
3531                 device_printf(sc->dev, "extra virtual interfaces disabled.  "
3532                     "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
3533                     "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
3534                     iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
3535                     iaq->nnmrxq_vi, itype, navail, iaq->nirq);
3536         }
3537
3538         /*
3539          * Keep reducing the number of NIC rx queues to the next lower power of
3540          * 2 (for even RSS distribution) and halving the TOE rx queues and see
3541          * if that works.
3542          */
3543         do {
3544                 if (iaq->nrxq > 1) {
3545                         do {
3546                                 iaq->nrxq--;
3547                         } while (!powerof2(iaq->nrxq));
3548                         if (iaq->nnmrxq > iaq->nrxq)
3549                                 iaq->nnmrxq = iaq->nrxq;
3550                 }
3551                 if (iaq->nofldrxq > 1)
3552                         iaq->nofldrxq >>= 1;
3553
3554                 old_nirq = iaq->nirq;
3555                 update_nirq(iaq, nports);
3556                 if (iaq->nirq <= navail &&
3557                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
3558                         device_printf(sc->dev, "running with reduced number of "
3559                             "rx queues because of shortage of interrupts.  "
3560                             "nrxq=%u, nofldrxq=%u.  "
3561                             "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
3562                             iaq->nofldrxq, itype, navail, iaq->nirq);
3563                         goto done;
3564                 }
3565         } while (old_nirq != iaq->nirq);
3566
3567         /* One interrupt for everything.  Ugh. */
3568         device_printf(sc->dev, "running with minimal number of queues.  "
3569             "itype %d, navail %u.\n", itype, navail);
3570         iaq->nirq = 1;
3571         iaq->nrxq = 1;
3572         iaq->ntxq = 1;
3573         if (iaq->nofldrxq > 0) {
3574                 iaq->nofldrxq = 1;
3575                 iaq->nofldtxq = 1;
3576         }
3577         iaq->nnmtxq = 0;
3578         iaq->nnmrxq = 0;
3579 done:
3580         MPASS(iaq->num_vis > 0);
3581         if (iaq->num_vis > 1) {
3582                 MPASS(iaq->nrxq_vi > 0);
3583                 MPASS(iaq->ntxq_vi > 0);
3584         }
3585         MPASS(iaq->nirq > 0);
3586         MPASS(iaq->nrxq > 0);
3587         MPASS(iaq->ntxq > 0);
3588         if (itype == INTR_MSI) {
3589                 MPASS(powerof2(iaq->nirq));
3590         }
3591 }
3592
3593 static int
3594 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
3595 {
3596         int rc, itype, navail, nalloc;
3597
3598         for (itype = INTR_MSIX; itype; itype >>= 1) {
3599
3600                 if ((itype & t4_intr_types) == 0)
3601                         continue;       /* not allowed */
3602
3603                 if (itype == INTR_MSIX)
3604                         navail = pci_msix_count(sc->dev);
3605                 else if (itype == INTR_MSI)
3606                         navail = pci_msi_count(sc->dev);
3607                 else
3608                         navail = 1;
3609 restart:
3610                 if (navail == 0)
3611                         continue;
3612
3613                 calculate_iaq(sc, iaq, itype, navail);
3614                 nalloc = iaq->nirq;
3615                 rc = 0;
3616                 if (itype == INTR_MSIX)
3617                         rc = pci_alloc_msix(sc->dev, &nalloc);
3618                 else if (itype == INTR_MSI)
3619                         rc = pci_alloc_msi(sc->dev, &nalloc);
3620
3621                 if (rc == 0 && nalloc > 0) {
3622                         if (nalloc == iaq->nirq)
3623                                 return (0);
3624
3625                         /*
3626                          * Didn't get the number requested.  Use whatever number
3627                          * the kernel is willing to allocate.
3628                          */
3629                         device_printf(sc->dev, "fewer vectors than requested, "
3630                             "type=%d, req=%d, rcvd=%d; will downshift req.\n",
3631                             itype, iaq->nirq, nalloc);
3632                         pci_release_msi(sc->dev);
3633                         navail = nalloc;
3634                         goto restart;
3635                 }
3636
3637                 device_printf(sc->dev,
3638                     "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
3639                     itype, rc, iaq->nirq, nalloc);
3640         }
3641
3642         device_printf(sc->dev,
3643             "failed to find a usable interrupt type.  "
3644             "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
3645             pci_msix_count(sc->dev), pci_msi_count(sc->dev));
3646
3647         return (ENXIO);
3648 }
3649
3650 #define FW_VERSION(chip) ( \
3651     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
3652     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
3653     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
3654     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
3655 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
3656
3657 /* Just enough of fw_hdr to cover all version info. */
3658 struct fw_h {
3659         __u8    ver;
3660         __u8    chip;
3661         __be16  len512;
3662         __be32  fw_ver;
3663         __be32  tp_microcode_ver;
3664         __u8    intfver_nic;
3665         __u8    intfver_vnic;
3666         __u8    intfver_ofld;
3667         __u8    intfver_ri;
3668         __u8    intfver_iscsipdu;
3669         __u8    intfver_iscsi;
3670         __u8    intfver_fcoepdu;
3671         __u8    intfver_fcoe;
3672 };
3673 /* Spot check a couple of fields. */
3674 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
3675 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
3676 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
3677
3678 struct fw_info {
3679         uint8_t chip;
3680         char *kld_name;
3681         char *fw_mod_name;
3682         struct fw_h fw_h;
3683 } fw_info[] = {
3684         {
3685                 .chip = CHELSIO_T4,
3686                 .kld_name = "t4fw_cfg",
3687                 .fw_mod_name = "t4fw",
3688                 .fw_h = {
3689                         .chip = FW_HDR_CHIP_T4,
3690                         .fw_ver = htobe32(FW_VERSION(T4)),
3691                         .intfver_nic = FW_INTFVER(T4, NIC),
3692                         .intfver_vnic = FW_INTFVER(T4, VNIC),
3693                         .intfver_ofld = FW_INTFVER(T4, OFLD),
3694                         .intfver_ri = FW_INTFVER(T4, RI),
3695                         .intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
3696                         .intfver_iscsi = FW_INTFVER(T4, ISCSI),
3697                         .intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
3698                         .intfver_fcoe = FW_INTFVER(T4, FCOE),
3699                 },
3700         }, {
3701                 .chip = CHELSIO_T5,
3702                 .kld_name = "t5fw_cfg",
3703                 .fw_mod_name = "t5fw",
3704                 .fw_h = {
3705                         .chip = FW_HDR_CHIP_T5,
3706                         .fw_ver = htobe32(FW_VERSION(T5)),
3707                         .intfver_nic = FW_INTFVER(T5, NIC),
3708                         .intfver_vnic = FW_INTFVER(T5, VNIC),
3709                         .intfver_ofld = FW_INTFVER(T5, OFLD),
3710                         .intfver_ri = FW_INTFVER(T5, RI),
3711                         .intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
3712                         .intfver_iscsi = FW_INTFVER(T5, ISCSI),
3713                         .intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
3714                         .intfver_fcoe = FW_INTFVER(T5, FCOE),
3715                 },
3716         }, {
3717                 .chip = CHELSIO_T6,
3718                 .kld_name = "t6fw_cfg",
3719                 .fw_mod_name = "t6fw",
3720                 .fw_h = {
3721                         .chip = FW_HDR_CHIP_T6,
3722                         .fw_ver = htobe32(FW_VERSION(T6)),
3723                         .intfver_nic = FW_INTFVER(T6, NIC),
3724                         .intfver_vnic = FW_INTFVER(T6, VNIC),
3725                         .intfver_ofld = FW_INTFVER(T6, OFLD),
3726                         .intfver_ri = FW_INTFVER(T6, RI),
3727                         .intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
3728                         .intfver_iscsi = FW_INTFVER(T6, ISCSI),
3729                         .intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
3730                         .intfver_fcoe = FW_INTFVER(T6, FCOE),
3731                 },
3732         }
3733 };
3734
3735 static struct fw_info *
3736 find_fw_info(int chip)
3737 {
3738         int i;
3739
3740         for (i = 0; i < nitems(fw_info); i++) {
3741                 if (fw_info[i].chip == chip)
3742                         return (&fw_info[i]);
3743         }
3744         return (NULL);
3745 }
3746
3747 /*
3748  * Is the given firmware API compatible with the one the driver was compiled
3749  * with?
3750  */
3751 static int
3752 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
3753 {
3754
3755         /* short circuit if it's the exact same firmware version */
3756         if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
3757                 return (1);
3758
3759         /*
3760          * XXX: Is this too conservative?  Perhaps I should limit this to the
3761          * features that are supported in the driver.
3762          */
3763 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
3764         if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
3765             SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
3766             SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
3767                 return (1);
3768 #undef SAME_INTF
3769
3770         return (0);
3771 }
3772
3773 static int
3774 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
3775     const struct firmware **fw)
3776 {
3777         struct fw_info *fw_info;
3778
3779         *dcfg = NULL;
3780         if (fw != NULL)
3781                 *fw = NULL;
3782
3783         fw_info = find_fw_info(chip_id(sc));
3784         if (fw_info == NULL) {
3785                 device_printf(sc->dev,
3786                     "unable to look up firmware information for chip %d.\n",
3787                     chip_id(sc));
3788                 return (EINVAL);
3789         }
3790
3791         *dcfg = firmware_get(fw_info->kld_name);
3792         if (*dcfg != NULL) {
3793                 if (fw != NULL)
3794                         *fw = firmware_get(fw_info->fw_mod_name);
3795                 return (0);
3796         }
3797
3798         return (ENOENT);
3799 }
3800
3801 static void
3802 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
3803     const struct firmware *fw)
3804 {
3805
3806         if (fw != NULL)
3807                 firmware_put(fw, FIRMWARE_UNLOAD);
3808         if (dcfg != NULL)
3809                 firmware_put(dcfg, FIRMWARE_UNLOAD);
3810 }
3811
3812 /*
3813  * Return values:
3814  * 0 means no firmware install attempted.
3815  * ERESTART means a firmware install was attempted and was successful.
3816  * +ve errno means a firmware install was attempted but failed.
3817  */
3818 static int
3819 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
3820     const struct fw_h *drv_fw, const char *reason, int *already)
3821 {
3822         const struct firmware *cfg, *fw;
3823         const uint32_t c = be32toh(card_fw->fw_ver);
3824         uint32_t d, k;
3825         int rc, fw_install;
3826         struct fw_h bundled_fw;
3827         bool load_attempted;
3828
3829         cfg = fw = NULL;
3830         load_attempted = false;
3831         fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
3832
3833         memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
3834         if (t4_fw_install < 0) {
3835                 rc = load_fw_module(sc, &cfg, &fw);
3836                 if (rc != 0 || fw == NULL) {
3837                         device_printf(sc->dev,
3838                             "failed to load firmware module: %d. cfg %p, fw %p;"
3839                             " will use compiled-in firmware version for"
3840                             "hw.cxgbe.fw_install checks.\n",
3841                             rc, cfg, fw);
3842                 } else {
3843                         memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
3844                 }
3845                 load_attempted = true;
3846         }
3847         d = be32toh(bundled_fw.fw_ver);
3848
3849         if (reason != NULL)
3850                 goto install;
3851
3852         if ((sc->flags & FW_OK) == 0) {
3853
3854                 if (c == 0xffffffff) {
3855                         reason = "missing";
3856                         goto install;
3857                 }
3858
3859                 rc = 0;
3860                 goto done;
3861         }
3862
3863         if (!fw_compatible(card_fw, &bundled_fw)) {
3864                 reason = "incompatible or unusable";
3865                 goto install;
3866         }
3867
3868         if (d > c) {
3869                 reason = "older than the version bundled with this driver";
3870                 goto install;
3871         }
3872
3873         if (fw_install == 2 && d != c) {
3874                 reason = "different than the version bundled with this driver";
3875                 goto install;
3876         }
3877
3878         /* No reason to do anything to the firmware already on the card. */
3879         rc = 0;
3880         goto done;
3881
3882 install:
3883         rc = 0;
3884         if ((*already)++)
3885                 goto done;
3886
3887         if (fw_install == 0) {
3888                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3889                     "but the driver is prohibited from installing a firmware "
3890                     "on the card.\n",
3891                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3892                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
3893
3894                 goto done;
3895         }
3896
3897         /*
3898          * We'll attempt to install a firmware.  Load the module first (if it
3899          * hasn't been loaded already).
3900          */
3901         if (!load_attempted) {
3902                 rc = load_fw_module(sc, &cfg, &fw);
3903                 if (rc != 0 || fw == NULL) {
3904                         device_printf(sc->dev,
3905                             "failed to load firmware module: %d. cfg %p, fw %p\n",
3906                             rc, cfg, fw);
3907                         /* carry on */
3908                 }
3909         }
3910         if (fw == NULL) {
3911                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3912                     "but the driver cannot take corrective action because it "
3913                     "is unable to load the firmware module.\n",
3914                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3915                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
3916                 rc = sc->flags & FW_OK ? 0 : ENOENT;
3917                 goto done;
3918         }
3919         k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
3920         if (k != d) {
3921                 MPASS(t4_fw_install > 0);
3922                 device_printf(sc->dev,
3923                     "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
3924                     "expecting (%u.%u.%u.%u) and will not be used.\n",
3925                     G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
3926                     G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
3927                     G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3928                     G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3929                 rc = sc->flags & FW_OK ? 0 : EINVAL;
3930                 goto done;
3931         }
3932
3933         device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3934             "installing firmware %u.%u.%u.%u on card.\n",
3935             G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3936             G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
3937             G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3938             G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3939
3940         rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
3941         if (rc != 0) {
3942                 device_printf(sc->dev, "failed to install firmware: %d\n", rc);
3943         } else {
3944                 /* Installed successfully, update the cached header too. */
3945                 rc = ERESTART;
3946                 memcpy(card_fw, fw->data, sizeof(*card_fw));
3947         }
3948 done:
3949         unload_fw_module(sc, cfg, fw);
3950
3951         return (rc);
3952 }
3953
3954 /*
3955  * Establish contact with the firmware and attempt to become the master driver.
3956  *
3957  * A firmware will be installed to the card if needed (if the driver is allowed
3958  * to do so).
3959  */
3960 static int
3961 contact_firmware(struct adapter *sc)
3962 {
3963         int rc, already = 0;
3964         enum dev_state state;
3965         struct fw_info *fw_info;
3966         struct fw_hdr *card_fw;         /* fw on the card */
3967         const struct fw_h *drv_fw;
3968
3969         fw_info = find_fw_info(chip_id(sc));
3970         if (fw_info == NULL) {
3971                 device_printf(sc->dev,
3972                     "unable to look up firmware information for chip %d.\n",
3973                     chip_id(sc));
3974                 return (EINVAL);
3975         }
3976         drv_fw = &fw_info->fw_h;
3977
3978         /* Read the header of the firmware on the card */
3979         card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
3980 restart:
3981         rc = -t4_get_fw_hdr(sc, card_fw);
3982         if (rc != 0) {
3983                 device_printf(sc->dev,
3984                     "unable to read firmware header from card's flash: %d\n",
3985                     rc);
3986                 goto done;
3987         }
3988
3989         rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
3990             &already);
3991         if (rc == ERESTART)
3992                 goto restart;
3993         if (rc != 0)
3994                 goto done;
3995
3996         rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
3997         if (rc < 0 || state == DEV_STATE_ERR) {
3998                 rc = -rc;
3999                 device_printf(sc->dev,
4000                     "failed to connect to the firmware: %d, %d.  "
4001                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4002 #if 0
4003                 if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4004                     "not responding properly to HELLO", &already) == ERESTART)
4005                         goto restart;
4006 #endif
4007                 goto done;
4008         }
4009         MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4010         sc->flags |= FW_OK;     /* The firmware responded to the FW_HELLO. */
4011
4012         if (rc == sc->pf) {
4013                 sc->flags |= MASTER_PF;
4014                 rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4015                     NULL, &already);
4016                 if (rc == ERESTART)
4017                         rc = 0;
4018                 else if (rc != 0)
4019                         goto done;
4020         } else if (state == DEV_STATE_UNINIT) {
4021                 /*
4022                  * We didn't get to be the master so we definitely won't be
4023                  * configuring the chip.  It's a bug if someone else hasn't
4024                  * configured it already.
4025                  */
4026                 device_printf(sc->dev, "couldn't be master(%d), "
4027                     "device not already initialized either(%d).  "
4028                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4029                 rc = EPROTO;
4030                 goto done;
4031         } else {
4032                 /*
4033                  * Some other PF is the master and has configured the chip.
4034                  * This is allowed but untested.
4035                  */
4036                 device_printf(sc->dev, "PF%d is master, device state %d.  "
4037                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4038                 snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4039                 sc->cfcsum = 0;
4040                 rc = 0;
4041         }
4042 done:
4043         if (rc != 0 && sc->flags & FW_OK) {
4044                 t4_fw_bye(sc, sc->mbox);
4045                 sc->flags &= ~FW_OK;
4046         }
4047         free(card_fw, M_CXGBE);
4048         return (rc);
4049 }
4050
4051 static int
4052 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4053     uint32_t mtype, uint32_t moff)
4054 {
4055         struct fw_info *fw_info;
4056         const struct firmware *dcfg, *rcfg = NULL;
4057         const uint32_t *cfdata;
4058         uint32_t cflen, addr;
4059         int rc;
4060
4061         load_fw_module(sc, &dcfg, NULL);
4062
4063         /* Card specific interpretation of "default". */
4064         if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4065                 if (pci_get_device(sc->dev) == 0x440a)
4066                         snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4067                 if (is_fpga(sc))
4068                         snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4069         }
4070
4071         if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4072                 if (dcfg == NULL) {
4073                         device_printf(sc->dev,
4074                             "KLD with default config is not available.\n");
4075                         rc = ENOENT;
4076                         goto done;
4077                 }
4078                 cfdata = dcfg->data;
4079                 cflen = dcfg->datasize & ~3;
4080         } else {
4081                 char s[32];
4082
4083                 fw_info = find_fw_info(chip_id(sc));
4084                 if (fw_info == NULL) {
4085                         device_printf(sc->dev,
4086                             "unable to look up firmware information for chip %d.\n",
4087                             chip_id(sc));
4088                         rc = EINVAL;
4089                         goto done;
4090                 }
4091                 snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4092
4093                 rcfg = firmware_get(s);
4094                 if (rcfg == NULL) {
4095                         device_printf(sc->dev,
4096                             "unable to load module \"%s\" for configuration "
4097                             "profile \"%s\".\n", s, cfg_file);
4098                         rc = ENOENT;
4099                         goto done;
4100                 }
4101                 cfdata = rcfg->data;
4102                 cflen = rcfg->datasize & ~3;
4103         }
4104
4105         if (cflen > FLASH_CFG_MAX_SIZE) {
4106                 device_printf(sc->dev,
4107                     "config file too long (%d, max allowed is %d).\n",
4108                     cflen, FLASH_CFG_MAX_SIZE);
4109                 rc = EINVAL;
4110                 goto done;
4111         }
4112
4113         rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4114         if (rc != 0) {
4115                 device_printf(sc->dev,
4116                     "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4117                     __func__, mtype, moff, cflen, rc);
4118                 rc = EINVAL;
4119                 goto done;
4120         }
4121         write_via_memwin(sc, 2, addr, cfdata, cflen);
4122 done:
4123         if (rcfg != NULL)
4124                 firmware_put(rcfg, FIRMWARE_UNLOAD);
4125         unload_fw_module(sc, dcfg, NULL);
4126         return (rc);
4127 }
4128
4129 struct caps_allowed {
4130         uint16_t nbmcaps;
4131         uint16_t linkcaps;
4132         uint16_t switchcaps;
4133         uint16_t niccaps;
4134         uint16_t toecaps;
4135         uint16_t rdmacaps;
4136         uint16_t cryptocaps;
4137         uint16_t iscsicaps;
4138         uint16_t fcoecaps;
4139 };
4140
4141 #define FW_PARAM_DEV(param) \
4142         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4143          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4144 #define FW_PARAM_PFVF(param) \
4145         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4146          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4147
4148 /*
4149  * Provide a configuration profile to the firmware and have it initialize the
4150  * chip accordingly.  This may involve uploading a configuration file to the
4151  * card.
4152  */
4153 static int
4154 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4155     const struct caps_allowed *caps_allowed)
4156 {
4157         int rc;
4158         struct fw_caps_config_cmd caps;
4159         uint32_t mtype, moff, finicsum, cfcsum, param, val;
4160
4161         rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4162         if (rc != 0) {
4163                 device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4164                 return (rc);
4165         }
4166
4167         bzero(&caps, sizeof(caps));
4168         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4169             F_FW_CMD_REQUEST | F_FW_CMD_READ);
4170         if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4171                 mtype = 0;
4172                 moff = 0;
4173                 caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4174         } else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4175                 mtype = FW_MEMTYPE_FLASH;
4176                 moff = t4_flash_cfg_addr(sc);
4177                 caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4178                     V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4179                     V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4180                     FW_LEN16(caps));
4181         } else {
4182                 /*
4183                  * Ask the firmware where it wants us to upload the config file.
4184                  */
4185                 param = FW_PARAM_DEV(CF);
4186                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4187                 if (rc != 0) {
4188                         /* No support for config file?  Shouldn't happen. */
4189                         device_printf(sc->dev,
4190                             "failed to query config file location: %d.\n", rc);
4191                         goto done;
4192                 }
4193                 mtype = G_FW_PARAMS_PARAM_Y(val);
4194                 moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4195                 caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4196                     V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4197                     V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4198                     FW_LEN16(caps));
4199
4200                 rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4201                 if (rc != 0) {
4202                         device_printf(sc->dev,
4203                             "failed to upload config file to card: %d.\n", rc);
4204                         goto done;
4205                 }
4206         }
4207         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4208         if (rc != 0) {
4209                 device_printf(sc->dev, "failed to pre-process config file: %d "
4210                     "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4211                 goto done;
4212         }
4213
4214         finicsum = be32toh(caps.finicsum);
4215         cfcsum = be32toh(caps.cfcsum);  /* actual */
4216         if (finicsum != cfcsum) {
4217                 device_printf(sc->dev,
4218                     "WARNING: config file checksum mismatch: %08x %08x\n",
4219                     finicsum, cfcsum);
4220         }
4221         sc->cfcsum = cfcsum;
4222         snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
4223
4224         /*
4225          * Let the firmware know what features will (not) be used so it can tune
4226          * things accordingly.
4227          */
4228 #define LIMIT_CAPS(x) do { \
4229         caps.x##caps &= htobe16(caps_allowed->x##caps); \
4230 } while (0)
4231         LIMIT_CAPS(nbm);
4232         LIMIT_CAPS(link);
4233         LIMIT_CAPS(switch);
4234         LIMIT_CAPS(nic);
4235         LIMIT_CAPS(toe);
4236         LIMIT_CAPS(rdma);
4237         LIMIT_CAPS(crypto);
4238         LIMIT_CAPS(iscsi);
4239         LIMIT_CAPS(fcoe);
4240 #undef LIMIT_CAPS
4241         if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
4242                 /*
4243                  * TOE and hashfilters are mutually exclusive.  It is a config
4244                  * file or firmware bug if both are reported as available.  Try
4245                  * to cope with the situation in non-debug builds by disabling
4246                  * TOE.
4247                  */
4248                 MPASS(caps.toecaps == 0);
4249
4250                 caps.toecaps = 0;
4251                 caps.rdmacaps = 0;
4252                 caps.iscsicaps = 0;
4253         }
4254
4255         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4256             F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
4257         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4258         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
4259         if (rc != 0) {
4260                 device_printf(sc->dev,
4261                     "failed to process config file: %d.\n", rc);
4262                 goto done;
4263         }
4264
4265         t4_tweak_chip_settings(sc);
4266         set_params__pre_init(sc);
4267
4268         /* get basic stuff going */
4269         rc = -t4_fw_initialize(sc, sc->mbox);
4270         if (rc != 0) {
4271                 device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
4272                 goto done;
4273         }
4274 done:
4275         return (rc);
4276 }
4277
4278 /*
4279  * Partition chip resources for use between various PFs, VFs, etc.
4280  */
4281 static int
4282 partition_resources(struct adapter *sc)
4283 {
4284         char cfg_file[sizeof(t4_cfg_file)];
4285         struct caps_allowed caps_allowed;
4286         int rc;
4287         bool fallback;
4288
4289         /* Only the master driver gets to configure the chip resources. */
4290         MPASS(sc->flags & MASTER_PF);
4291
4292 #define COPY_CAPS(x) do { \
4293         caps_allowed.x##caps = t4_##x##caps_allowed; \
4294 } while (0)
4295         bzero(&caps_allowed, sizeof(caps_allowed));
4296         COPY_CAPS(nbm);
4297         COPY_CAPS(link);
4298         COPY_CAPS(switch);
4299         COPY_CAPS(nic);
4300         COPY_CAPS(toe);
4301         COPY_CAPS(rdma);
4302         COPY_CAPS(crypto);
4303         COPY_CAPS(iscsi);
4304         COPY_CAPS(fcoe);
4305         fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
4306         snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
4307 retry:
4308         rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
4309         if (rc != 0 && fallback) {
4310                 device_printf(sc->dev,
4311                     "failed (%d) to configure card with \"%s\" profile, "
4312                     "will fall back to a basic configuration and retry.\n",
4313                     rc, cfg_file);
4314                 snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
4315                 bzero(&caps_allowed, sizeof(caps_allowed));
4316                 COPY_CAPS(switch);
4317                 caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
4318                 fallback = false;
4319                 goto retry;
4320         }
4321 #undef COPY_CAPS
4322         return (rc);
4323 }
4324
4325 /*
4326  * Retrieve parameters that are needed (or nice to have) very early.
4327  */
4328 static int
4329 get_params__pre_init(struct adapter *sc)
4330 {
4331         int rc;
4332         uint32_t param[2], val[2];
4333
4334         t4_get_version_info(sc);
4335
4336         snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
4337             G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
4338             G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
4339             G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
4340             G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
4341
4342         snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
4343             G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
4344             G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
4345             G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
4346             G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
4347
4348         snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
4349             G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4350             G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4351             G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4352             G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4353
4354         snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4355             G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4356             G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4357             G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4358             G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4359
4360         param[0] = FW_PARAM_DEV(PORTVEC);
4361         param[1] = FW_PARAM_DEV(CCLK);
4362         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4363         if (rc != 0) {
4364                 device_printf(sc->dev,
4365                     "failed to query parameters (pre_init): %d.\n", rc);
4366                 return (rc);
4367         }
4368
4369         sc->params.portvec = val[0];
4370         sc->params.nports = bitcount32(val[0]);
4371         sc->params.vpd.cclk = val[1];
4372
4373         /* Read device log parameters. */
4374         rc = -t4_init_devlog_params(sc, 1);
4375         if (rc == 0)
4376                 fixup_devlog_params(sc);
4377         else {
4378                 device_printf(sc->dev,
4379                     "failed to get devlog parameters: %d.\n", rc);
4380                 rc = 0; /* devlog isn't critical for device operation */
4381         }
4382
4383         return (rc);
4384 }
4385
4386 /*
4387  * Any params that need to be set before FW_INITIALIZE.
4388  */
4389 static int
4390 set_params__pre_init(struct adapter *sc)
4391 {
4392         int rc = 0;
4393         uint32_t param, val;
4394
4395         if (chip_id(sc) >= CHELSIO_T6) {
4396                 param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
4397                 val = 1;
4398                 rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4399                 /* firmwares < 1.20.1.0 do not have this param. */
4400                 if (rc == FW_EINVAL &&
4401                     sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
4402                         rc = 0;
4403                 }
4404                 if (rc != 0) {
4405                         device_printf(sc->dev,
4406                             "failed to enable high priority filters :%d.\n",
4407                             rc);
4408                 }
4409         }
4410
4411         /* Enable opaque VIIDs with firmwares that support it. */
4412         param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
4413         val = 1;
4414         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4415         if (rc == 0 && val == 1)
4416                 sc->params.viid_smt_extn_support = true;
4417         else
4418                 sc->params.viid_smt_extn_support = false;
4419
4420         return (rc);
4421 }
4422
4423 /*
4424  * Retrieve various parameters that are of interest to the driver.  The device
4425  * has been initialized by the firmware at this point.
4426  */
4427 static int
4428 get_params__post_init(struct adapter *sc)
4429 {
4430         int rc;
4431         uint32_t param[7], val[7];
4432         struct fw_caps_config_cmd caps;
4433
4434         param[0] = FW_PARAM_PFVF(IQFLINT_START);
4435         param[1] = FW_PARAM_PFVF(EQ_START);
4436         param[2] = FW_PARAM_PFVF(FILTER_START);
4437         param[3] = FW_PARAM_PFVF(FILTER_END);
4438         param[4] = FW_PARAM_PFVF(L2T_START);
4439         param[5] = FW_PARAM_PFVF(L2T_END);
4440         param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
4441             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
4442             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
4443         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
4444         if (rc != 0) {
4445                 device_printf(sc->dev,
4446                     "failed to query parameters (post_init): %d.\n", rc);
4447                 return (rc);
4448         }
4449
4450         sc->sge.iq_start = val[0];
4451         sc->sge.eq_start = val[1];
4452         if ((int)val[3] > (int)val[2]) {
4453                 sc->tids.ftid_base = val[2];
4454                 sc->tids.ftid_end = val[3];
4455                 sc->tids.nftids = val[3] - val[2] + 1;
4456         }
4457         sc->vres.l2t.start = val[4];
4458         sc->vres.l2t.size = val[5] - val[4] + 1;
4459         KASSERT(sc->vres.l2t.size <= L2T_SIZE,
4460             ("%s: L2 table size (%u) larger than expected (%u)",
4461             __func__, sc->vres.l2t.size, L2T_SIZE));
4462         sc->params.core_vdd = val[6];
4463
4464         param[0] = FW_PARAM_PFVF(IQFLINT_END);
4465         param[1] = FW_PARAM_PFVF(EQ_END);
4466         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4467         if (rc != 0) {
4468                 device_printf(sc->dev,
4469                     "failed to query parameters (post_init2): %d.\n", rc);
4470                 return (rc);
4471         }
4472         MPASS((int)val[0] >= sc->sge.iq_start);
4473         sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
4474         MPASS((int)val[1] >= sc->sge.eq_start);
4475         sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
4476
4477         if (chip_id(sc) >= CHELSIO_T6) {
4478
4479                 sc->tids.tid_base = t4_read_reg(sc,
4480                     A_LE_DB_ACTIVE_TABLE_START_INDEX);
4481
4482                 param[0] = FW_PARAM_PFVF(HPFILTER_START);
4483                 param[1] = FW_PARAM_PFVF(HPFILTER_END);
4484                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4485                 if (rc != 0) {
4486                         device_printf(sc->dev,
4487                            "failed to query hpfilter parameters: %d.\n", rc);
4488                         return (rc);
4489                 }
4490                 if ((int)val[1] > (int)val[0]) {
4491                         sc->tids.hpftid_base = val[0];
4492                         sc->tids.hpftid_end = val[1];
4493                         sc->tids.nhpftids = val[1] - val[0] + 1;
4494
4495                         /*
4496                          * These should go off if the layout changes and the
4497                          * driver needs to catch up.
4498                          */
4499                         MPASS(sc->tids.hpftid_base == 0);
4500                         MPASS(sc->tids.tid_base == sc->tids.nhpftids);
4501                 }
4502
4503                 param[0] = FW_PARAM_PFVF(RAWF_START);
4504                 param[1] = FW_PARAM_PFVF(RAWF_END);
4505                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4506                 if (rc != 0) {
4507                         device_printf(sc->dev,
4508                            "failed to query rawf parameters: %d.\n", rc);
4509                         return (rc);
4510                 }
4511                 if ((int)val[1] > (int)val[0]) {
4512                         sc->rawf_base = val[0];
4513                         sc->nrawf = val[1] - val[0] + 1;
4514                 }
4515         }
4516
4517         /*
4518          * MPSBGMAP is queried separately because only recent firmwares support
4519          * it as a parameter and we don't want the compound query above to fail
4520          * on older firmwares.
4521          */
4522         param[0] = FW_PARAM_DEV(MPSBGMAP);
4523         val[0] = 0;
4524         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4525         if (rc == 0)
4526                 sc->params.mps_bg_map = val[0];
4527         else
4528                 sc->params.mps_bg_map = 0;
4529
4530         /*
4531          * Determine whether the firmware supports the filter2 work request.
4532          * This is queried separately for the same reason as MPSBGMAP above.
4533          */
4534         param[0] = FW_PARAM_DEV(FILTER2_WR);
4535         val[0] = 0;
4536         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4537         if (rc == 0)
4538                 sc->params.filter2_wr_support = val[0] != 0;
4539         else
4540                 sc->params.filter2_wr_support = 0;
4541
4542         /*
4543          * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
4544          * This is queried separately for the same reason as other params above.
4545          */
4546         param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
4547         val[0] = 0;
4548         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4549         if (rc == 0)
4550                 sc->params.ulptx_memwrite_dsgl = val[0] != 0;
4551         else
4552                 sc->params.ulptx_memwrite_dsgl = false;
4553
4554         /* FW_RI_FR_NSMR_TPTE_WR support */
4555         param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
4556         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4557         if (rc == 0)
4558                 sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
4559         else
4560                 sc->params.fr_nsmr_tpte_wr_support = false;
4561
4562         param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
4563         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4564         if (rc == 0)
4565                 sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
4566         else
4567                 sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
4568
4569         /* get capabilites */
4570         bzero(&caps, sizeof(caps));
4571         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4572             F_FW_CMD_REQUEST | F_FW_CMD_READ);
4573         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4574         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4575         if (rc != 0) {
4576                 device_printf(sc->dev,
4577                     "failed to get card capabilities: %d.\n", rc);
4578                 return (rc);
4579         }
4580
4581 #define READ_CAPS(x) do { \
4582         sc->x = htobe16(caps.x); \
4583 } while (0)
4584         READ_CAPS(nbmcaps);
4585         READ_CAPS(linkcaps);
4586         READ_CAPS(switchcaps);
4587         READ_CAPS(niccaps);
4588         READ_CAPS(toecaps);
4589         READ_CAPS(rdmacaps);
4590         READ_CAPS(cryptocaps);
4591         READ_CAPS(iscsicaps);
4592         READ_CAPS(fcoecaps);
4593
4594         if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
4595                 MPASS(chip_id(sc) > CHELSIO_T4);
4596                 MPASS(sc->toecaps == 0);
4597                 sc->toecaps = 0;
4598
4599                 param[0] = FW_PARAM_DEV(NTID);
4600                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4601                 if (rc != 0) {
4602                         device_printf(sc->dev,
4603                             "failed to query HASHFILTER parameters: %d.\n", rc);
4604                         return (rc);
4605                 }
4606                 sc->tids.ntids = val[0];
4607                 if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
4608                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4609                         sc->tids.ntids -= sc->tids.nhpftids;
4610                 }
4611                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4612                 sc->params.hash_filter = 1;
4613         }
4614         if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
4615                 param[0] = FW_PARAM_PFVF(ETHOFLD_START);
4616                 param[1] = FW_PARAM_PFVF(ETHOFLD_END);
4617                 param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4618                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
4619                 if (rc != 0) {
4620                         device_printf(sc->dev,
4621                             "failed to query NIC parameters: %d.\n", rc);
4622                         return (rc);
4623                 }
4624                 if ((int)val[1] > (int)val[0]) {
4625                         sc->tids.etid_base = val[0];
4626                         sc->tids.etid_end = val[1];
4627                         sc->tids.netids = val[1] - val[0] + 1;
4628                         sc->params.eo_wr_cred = val[2];
4629                         sc->params.ethoffload = 1;
4630                 }
4631         }
4632         if (sc->toecaps) {
4633                 /* query offload-related parameters */
4634                 param[0] = FW_PARAM_DEV(NTID);
4635                 param[1] = FW_PARAM_PFVF(SERVER_START);
4636                 param[2] = FW_PARAM_PFVF(SERVER_END);
4637                 param[3] = FW_PARAM_PFVF(TDDP_START);
4638                 param[4] = FW_PARAM_PFVF(TDDP_END);
4639                 param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4640                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4641                 if (rc != 0) {
4642                         device_printf(sc->dev,
4643                             "failed to query TOE parameters: %d.\n", rc);
4644                         return (rc);
4645                 }
4646                 sc->tids.ntids = val[0];
4647                 if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
4648                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4649                         sc->tids.ntids -= sc->tids.nhpftids;
4650                 }
4651                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4652                 if ((int)val[2] > (int)val[1]) {
4653                         sc->tids.stid_base = val[1];
4654                         sc->tids.nstids = val[2] - val[1] + 1;
4655                 }
4656                 sc->vres.ddp.start = val[3];
4657                 sc->vres.ddp.size = val[4] - val[3] + 1;
4658                 sc->params.ofldq_wr_cred = val[5];
4659                 sc->params.offload = 1;
4660         } else {
4661                 /*
4662                  * The firmware attempts memfree TOE configuration for -SO cards
4663                  * and will report toecaps=0 if it runs out of resources (this
4664                  * depends on the config file).  It may not report 0 for other
4665                  * capabilities dependent on the TOE in this case.  Set them to
4666                  * 0 here so that the driver doesn't bother tracking resources
4667                  * that will never be used.
4668                  */
4669                 sc->iscsicaps = 0;
4670                 sc->rdmacaps = 0;
4671         }
4672         if (sc->rdmacaps) {
4673                 param[0] = FW_PARAM_PFVF(STAG_START);
4674                 param[1] = FW_PARAM_PFVF(STAG_END);
4675                 param[2] = FW_PARAM_PFVF(RQ_START);
4676                 param[3] = FW_PARAM_PFVF(RQ_END);
4677                 param[4] = FW_PARAM_PFVF(PBL_START);
4678                 param[5] = FW_PARAM_PFVF(PBL_END);
4679                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4680                 if (rc != 0) {
4681                         device_printf(sc->dev,
4682                             "failed to query RDMA parameters(1): %d.\n", rc);
4683                         return (rc);
4684                 }
4685                 sc->vres.stag.start = val[0];
4686                 sc->vres.stag.size = val[1] - val[0] + 1;
4687                 sc->vres.rq.start = val[2];
4688                 sc->vres.rq.size = val[3] - val[2] + 1;
4689                 sc->vres.pbl.start = val[4];
4690                 sc->vres.pbl.size = val[5] - val[4] + 1;
4691
4692                 param[0] = FW_PARAM_PFVF(SQRQ_START);
4693                 param[1] = FW_PARAM_PFVF(SQRQ_END);
4694                 param[2] = FW_PARAM_PFVF(CQ_START);
4695                 param[3] = FW_PARAM_PFVF(CQ_END);
4696                 param[4] = FW_PARAM_PFVF(OCQ_START);
4697                 param[5] = FW_PARAM_PFVF(OCQ_END);
4698                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4699                 if (rc != 0) {
4700                         device_printf(sc->dev,
4701                             "failed to query RDMA parameters(2): %d.\n", rc);
4702                         return (rc);
4703                 }
4704                 sc->vres.qp.start = val[0];
4705                 sc->vres.qp.size = val[1] - val[0] + 1;
4706                 sc->vres.cq.start = val[2];
4707                 sc->vres.cq.size = val[3] - val[2] + 1;
4708                 sc->vres.ocq.start = val[4];
4709                 sc->vres.ocq.size = val[5] - val[4] + 1;
4710
4711                 param[0] = FW_PARAM_PFVF(SRQ_START);
4712                 param[1] = FW_PARAM_PFVF(SRQ_END);
4713                 param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
4714                 param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
4715                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
4716                 if (rc != 0) {
4717                         device_printf(sc->dev,
4718                             "failed to query RDMA parameters(3): %d.\n", rc);
4719                         return (rc);
4720                 }
4721                 sc->vres.srq.start = val[0];
4722                 sc->vres.srq.size = val[1] - val[0] + 1;
4723                 sc->params.max_ordird_qp = val[2];
4724                 sc->params.max_ird_adapter = val[3];
4725         }
4726         if (sc->iscsicaps) {
4727                 param[0] = FW_PARAM_PFVF(ISCSI_START);
4728                 param[1] = FW_PARAM_PFVF(ISCSI_END);
4729                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4730                 if (rc != 0) {
4731                         device_printf(sc->dev,
4732                             "failed to query iSCSI parameters: %d.\n", rc);
4733                         return (rc);
4734                 }
4735                 sc->vres.iscsi.start = val[0];
4736                 sc->vres.iscsi.size = val[1] - val[0] + 1;
4737         }
4738         if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
4739                 param[0] = FW_PARAM_PFVF(TLS_START);
4740                 param[1] = FW_PARAM_PFVF(TLS_END);
4741                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4742                 if (rc != 0) {
4743                         device_printf(sc->dev,
4744                             "failed to query TLS parameters: %d.\n", rc);
4745                         return (rc);
4746                 }
4747                 sc->vres.key.start = val[0];
4748                 sc->vres.key.size = val[1] - val[0] + 1;
4749         }
4750
4751         t4_init_sge_params(sc);
4752
4753         /*
4754          * We've got the params we wanted to query via the firmware.  Now grab
4755          * some others directly from the chip.
4756          */
4757         rc = t4_read_chip_settings(sc);
4758
4759         return (rc);
4760 }
4761
4762 #ifdef KERN_TLS
4763 static void
4764 ktls_tick(void *arg)
4765 {
4766         struct adapter *sc;
4767         uint32_t tstamp;
4768
4769         sc = arg;
4770
4771         tstamp = tcp_ts_getticks();
4772         t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
4773         t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
4774
4775         callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
4776 }
4777
4778 static void
4779 t4_enable_kern_tls(struct adapter *sc)
4780 {
4781         uint32_t m, v;
4782
4783         m = F_ENABLECBYP;
4784         v = F_ENABLECBYP;
4785         t4_set_reg_field(sc, A_TP_PARA_REG6, m, v);
4786
4787         m = F_CPL_FLAGS_UPDATE_EN | F_SEQ_UPDATE_EN;
4788         v = F_CPL_FLAGS_UPDATE_EN | F_SEQ_UPDATE_EN;
4789         t4_set_reg_field(sc, A_ULP_TX_CONFIG, m, v);
4790
4791         m = F_NICMODE;
4792         v = F_NICMODE;
4793         t4_set_reg_field(sc, A_TP_IN_CONFIG, m, v);
4794
4795         m = F_LOOKUPEVERYPKT;
4796         v = 0;
4797         t4_set_reg_field(sc, A_TP_INGRESS_CONFIG, m, v);
4798
4799         m = F_TXDEFERENABLE | F_DISABLEWINDOWPSH | F_DISABLESEPPSHFLAG;
4800         v = F_DISABLEWINDOWPSH;
4801         t4_set_reg_field(sc, A_TP_PC_CONFIG, m, v);
4802
4803         m = V_TIMESTAMPRESOLUTION(M_TIMESTAMPRESOLUTION);
4804         v = V_TIMESTAMPRESOLUTION(0x1f);
4805         t4_set_reg_field(sc, A_TP_TIMER_RESOLUTION, m, v);
4806
4807         sc->flags |= KERN_TLS_OK;
4808
4809         sc->tlst.inline_keys = t4_tls_inline_keys;
4810         sc->tlst.combo_wrs = t4_tls_combo_wrs;
4811 }
4812 #endif
4813
4814 static int
4815 set_params__post_init(struct adapter *sc)
4816 {
4817         uint32_t mask, param, val;
4818 #ifdef TCP_OFFLOAD
4819         int i, v, shift;
4820 #endif
4821
4822         /* ask for encapsulated CPLs */
4823         param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
4824         val = 1;
4825         (void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4826
4827         /* Enable 32b port caps if the firmware supports it. */
4828         param = FW_PARAM_PFVF(PORT_CAPS32);
4829         val = 1;
4830         if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
4831                 sc->params.port_caps32 = 1;
4832
4833         /* Let filter + maskhash steer to a part of the VI's RSS region. */
4834         val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
4835         t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
4836             V_MASKFILTER(val - 1));
4837
4838         mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
4839             F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
4840             F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
4841             F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
4842         val = 0;
4843         if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
4844                 t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
4845                     F_ATTACKFILTERENABLE);
4846                 val |= F_DROPERRORATTACK;
4847         }
4848         if (t4_drop_ip_fragments != 0) {
4849                 t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
4850                     F_FRAGMENTDROP);
4851                 val |= F_DROPERRORFRAG;
4852         }
4853         if (t4_drop_pkts_with_l2_errors != 0)
4854                 val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
4855         if (t4_drop_pkts_with_l3_errors != 0) {
4856                 val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
4857                     F_DROPERRORCSUMIP;
4858         }
4859         if (t4_drop_pkts_with_l4_errors != 0) {
4860                 val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
4861                     F_DROPERRORTCPOPT | F_DROPERRORCSUM;
4862         }
4863         t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
4864
4865 #ifdef TCP_OFFLOAD
4866         /*
4867          * Override the TOE timers with user provided tunables.  This is not the
4868          * recommended way to change the timers (the firmware config file is) so
4869          * these tunables are not documented.
4870          *
4871          * All the timer tunables are in microseconds.
4872          */
4873         if (t4_toe_keepalive_idle != 0) {
4874                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
4875                 v &= M_KEEPALIVEIDLE;
4876                 t4_set_reg_field(sc, A_TP_KEEP_IDLE,
4877                     V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
4878         }
4879         if (t4_toe_keepalive_interval != 0) {
4880                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
4881                 v &= M_KEEPALIVEINTVL;
4882                 t4_set_reg_field(sc, A_TP_KEEP_INTVL,
4883                     V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
4884         }
4885         if (t4_toe_keepalive_count != 0) {
4886                 v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
4887                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4888                     V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
4889                     V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
4890                     V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
4891         }
4892         if (t4_toe_rexmt_min != 0) {
4893                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
4894                 v &= M_RXTMIN;
4895                 t4_set_reg_field(sc, A_TP_RXT_MIN,
4896                     V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
4897         }
4898         if (t4_toe_rexmt_max != 0) {
4899                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
4900                 v &= M_RXTMAX;
4901                 t4_set_reg_field(sc, A_TP_RXT_MAX,
4902                     V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
4903         }
4904         if (t4_toe_rexmt_count != 0) {
4905                 v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
4906                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4907                     V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
4908                     V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
4909                     V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
4910         }
4911         for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
4912                 if (t4_toe_rexmt_backoff[i] != -1) {
4913                         v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
4914                         shift = (i & 3) << 3;
4915                         t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
4916                             M_TIMERBACKOFFINDEX0 << shift, v << shift);
4917                 }
4918         }
4919 #endif
4920
4921 #ifdef KERN_TLS
4922         if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
4923             sc->toecaps & FW_CAPS_CONFIG_TOE) {
4924                 if (t4_kern_tls != 0)
4925                         t4_enable_kern_tls(sc);
4926                 else {
4927                         /*
4928                          * Limit TOE connections to 2 reassembly
4929                          * "islands".  This is required for TOE TLS
4930                          * connections to downgrade to plain TOE
4931                          * connections if an unsupported TLS version
4932                          * or ciphersuite is used.
4933                          */
4934                         t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
4935                             V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
4936                 }
4937         }
4938 #endif
4939         return (0);
4940 }
4941
4942 #undef FW_PARAM_PFVF
4943 #undef FW_PARAM_DEV
4944
4945 static void
4946 t4_set_desc(struct adapter *sc)
4947 {
4948         char buf[128];
4949         struct adapter_params *p = &sc->params;
4950
4951         snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
4952
4953         device_set_desc_copy(sc->dev, buf);
4954 }
4955
4956 static inline void
4957 ifmedia_add4(struct ifmedia *ifm, int m)
4958 {
4959
4960         ifmedia_add(ifm, m, 0, NULL);
4961         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
4962         ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
4963         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
4964 }
4965
4966 /*
4967  * This is the selected media, which is not quite the same as the active media.
4968  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
4969  * and active are not the same, and "media: Ethernet selected" otherwise.
4970  */
4971 static void
4972 set_current_media(struct port_info *pi)
4973 {
4974         struct link_config *lc;
4975         struct ifmedia *ifm;
4976         int mword;
4977         u_int speed;
4978
4979         PORT_LOCK_ASSERT_OWNED(pi);
4980
4981         /* Leave current media alone if it's already set to IFM_NONE. */
4982         ifm = &pi->media;
4983         if (ifm->ifm_cur != NULL &&
4984             IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
4985                 return;
4986
4987         lc = &pi->link_cfg;
4988         if (lc->requested_aneg != AUTONEG_DISABLE &&
4989             lc->pcaps & FW_PORT_CAP32_ANEG) {
4990                 ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
4991                 return;
4992         }
4993         mword = IFM_ETHER | IFM_FDX;
4994         if (lc->requested_fc & PAUSE_TX)
4995                 mword |= IFM_ETH_TXPAUSE;
4996         if (lc->requested_fc & PAUSE_RX)
4997                 mword |= IFM_ETH_RXPAUSE;
4998         if (lc->requested_speed == 0)
4999                 speed = port_top_speed(pi) * 1000;      /* Gbps -> Mbps */
5000         else
5001                 speed = lc->requested_speed;
5002         mword |= port_mword(pi, speed_to_fwcap(speed));
5003         ifmedia_set(ifm, mword);
5004 }
5005
5006 /*
5007  * Returns true if the ifmedia list for the port cannot change.
5008  */
5009 static bool
5010 fixed_ifmedia(struct port_info *pi)
5011 {
5012
5013         return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5014             pi->port_type == FW_PORT_TYPE_BT_XFI ||
5015             pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5016             pi->port_type == FW_PORT_TYPE_KX4 ||
5017             pi->port_type == FW_PORT_TYPE_KX ||
5018             pi->port_type == FW_PORT_TYPE_KR ||
5019             pi->port_type == FW_PORT_TYPE_BP_AP ||
5020             pi->port_type == FW_PORT_TYPE_BP4_AP ||
5021             pi->port_type == FW_PORT_TYPE_BP40_BA ||
5022             pi->port_type == FW_PORT_TYPE_KR4_100G ||
5023             pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5024             pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5025 }
5026
5027 static void
5028 build_medialist(struct port_info *pi)
5029 {
5030         uint32_t ss, speed;
5031         int unknown, mword, bit;
5032         struct link_config *lc;
5033         struct ifmedia *ifm;
5034
5035         PORT_LOCK_ASSERT_OWNED(pi);
5036
5037         if (pi->flags & FIXED_IFMEDIA)
5038                 return;
5039
5040         /*
5041          * Rebuild the ifmedia list.
5042          */
5043         ifm = &pi->media;
5044         ifmedia_removeall(ifm);
5045         lc = &pi->link_cfg;
5046         ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5047         if (__predict_false(ss == 0)) { /* not supposed to happen. */
5048                 MPASS(ss != 0);
5049 no_media:
5050                 MPASS(LIST_EMPTY(&ifm->ifm_list));
5051                 ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5052                 ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5053                 return;
5054         }
5055
5056         unknown = 0;
5057         for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5058                 speed = 1 << bit;
5059                 MPASS(speed & M_FW_PORT_CAP32_SPEED);
5060                 if (ss & speed) {
5061                         mword = port_mword(pi, speed);
5062                         if (mword == IFM_NONE) {
5063                                 goto no_media;
5064                         } else if (mword == IFM_UNKNOWN)
5065                                 unknown++;
5066                         else
5067                                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5068                 }
5069         }
5070         if (unknown > 0) /* Add one unknown for all unknown media types. */
5071                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5072         if (lc->pcaps & FW_PORT_CAP32_ANEG)
5073                 ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5074
5075         set_current_media(pi);
5076 }
5077
5078 /*
5079  * Initialize the requested fields in the link config based on driver tunables.
5080  */
5081 static void
5082 init_link_config(struct port_info *pi)
5083 {
5084         struct link_config *lc = &pi->link_cfg;
5085
5086         PORT_LOCK_ASSERT_OWNED(pi);
5087
5088         lc->requested_speed = 0;
5089
5090         if (t4_autoneg == 0)
5091                 lc->requested_aneg = AUTONEG_DISABLE;
5092         else if (t4_autoneg == 1)
5093                 lc->requested_aneg = AUTONEG_ENABLE;
5094         else
5095                 lc->requested_aneg = AUTONEG_AUTO;
5096
5097         lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5098             PAUSE_AUTONEG);
5099
5100         if (t4_fec & FEC_AUTO)
5101                 lc->requested_fec = FEC_AUTO;
5102         else if (t4_fec == 0)
5103                 lc->requested_fec = FEC_NONE;
5104         else {
5105                 /* -1 is handled by the FEC_AUTO block above and not here. */
5106                 lc->requested_fec = t4_fec &
5107                     (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5108                 if (lc->requested_fec == 0)
5109                         lc->requested_fec = FEC_AUTO;
5110         }
5111 }
5112
5113 /*
5114  * Makes sure that all requested settings comply with what's supported by the
5115  * port.  Returns the number of settings that were invalid and had to be fixed.
5116  */
5117 static int
5118 fixup_link_config(struct port_info *pi)
5119 {
5120         int n = 0;
5121         struct link_config *lc = &pi->link_cfg;
5122         uint32_t fwspeed;
5123
5124         PORT_LOCK_ASSERT_OWNED(pi);
5125
5126         /* Speed (when not autonegotiating) */
5127         if (lc->requested_speed != 0) {
5128                 fwspeed = speed_to_fwcap(lc->requested_speed);
5129                 if ((fwspeed & lc->pcaps) == 0) {
5130                         n++;
5131                         lc->requested_speed = 0;
5132                 }
5133         }
5134
5135         /* Link autonegotiation */
5136         MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5137             lc->requested_aneg == AUTONEG_DISABLE ||
5138             lc->requested_aneg == AUTONEG_AUTO);
5139         if (lc->requested_aneg == AUTONEG_ENABLE &&
5140             !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5141                 n++;
5142                 lc->requested_aneg = AUTONEG_AUTO;
5143         }
5144
5145         /* Flow control */
5146         MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5147         if (lc->requested_fc & PAUSE_TX &&
5148             !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5149                 n++;
5150                 lc->requested_fc &= ~PAUSE_TX;
5151         }
5152         if (lc->requested_fc & PAUSE_RX &&
5153             !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5154                 n++;
5155                 lc->requested_fc &= ~PAUSE_RX;
5156         }
5157         if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5158             !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5159                 n++;
5160                 lc->requested_fc |= PAUSE_AUTONEG;
5161         }
5162
5163         /* FEC */
5164         if ((lc->requested_fec & FEC_RS &&
5165             !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5166             (lc->requested_fec & FEC_BASER_RS &&
5167             !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5168                 n++;
5169                 lc->requested_fec = FEC_AUTO;
5170         }
5171
5172         return (n);
5173 }
5174
5175 /*
5176  * Apply the requested L1 settings, which are expected to be valid, to the
5177  * hardware.
5178  */
5179 static int
5180 apply_link_config(struct port_info *pi)
5181 {
5182         struct adapter *sc = pi->adapter;
5183         struct link_config *lc = &pi->link_cfg;
5184         int rc;
5185
5186 #ifdef INVARIANTS
5187         ASSERT_SYNCHRONIZED_OP(sc);
5188         PORT_LOCK_ASSERT_OWNED(pi);
5189
5190         if (lc->requested_aneg == AUTONEG_ENABLE)
5191                 MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
5192         if (!(lc->requested_fc & PAUSE_AUTONEG))
5193                 MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
5194         if (lc->requested_fc & PAUSE_TX)
5195                 MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
5196         if (lc->requested_fc & PAUSE_RX)
5197                 MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
5198         if (lc->requested_fec & FEC_RS)
5199                 MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
5200         if (lc->requested_fec & FEC_BASER_RS)
5201                 MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
5202 #endif
5203         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5204         if (rc != 0) {
5205                 /* Don't complain if the VF driver gets back an EPERM. */
5206                 if (!(sc->flags & IS_VF) || rc != FW_EPERM)
5207                         device_printf(pi->dev, "l1cfg failed: %d\n", rc);
5208         } else {
5209                 /*
5210                  * An L1_CFG will almost always result in a link-change event if
5211                  * the link is up, and the driver will refresh the actual
5212                  * fec/fc/etc. when the notification is processed.  If the link
5213                  * is down then the actual settings are meaningless.
5214                  *
5215                  * This takes care of the case where a change in the L1 settings
5216                  * may not result in a notification.
5217                  */
5218                 if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
5219                         lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
5220         }
5221         return (rc);
5222 }
5223
5224 #define FW_MAC_EXACT_CHUNK      7
5225 struct mcaddr_ctx {
5226         struct ifnet *ifp;
5227         const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5228         uint64_t hash;
5229         int i;
5230         int del;
5231         int rc;
5232 };
5233
5234 static u_int
5235 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5236 {
5237         struct mcaddr_ctx *ctx = arg;
5238         struct vi_info *vi = ctx->ifp->if_softc;
5239         struct port_info *pi = vi->pi;
5240         struct adapter *sc = pi->adapter;
5241
5242         if (ctx->rc < 0)
5243                 return (0);
5244
5245         ctx->mcaddr[ctx->i] = LLADDR(sdl);
5246         MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5247         ctx->i++;
5248
5249         if (ctx->i == FW_MAC_EXACT_CHUNK) {
5250                 ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5251                     ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5252                 if (ctx->rc < 0) {
5253                         int j;
5254
5255                         for (j = 0; j < ctx->i; j++) {
5256                                 if_printf(ctx->ifp,
5257                                     "failed to add mc address"
5258                                     " %02x:%02x:%02x:"
5259                                     "%02x:%02x:%02x rc=%d\n",
5260                                     ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5261                                     ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5262                                     ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5263                                     -ctx->rc);
5264                         }
5265                         return (0);
5266                 }
5267                 ctx->del = 0;
5268                 ctx->i = 0;
5269         }
5270
5271         return (1);
5272 }
5273
5274 /*
5275  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5276  * indicates which parameters should be programmed (the rest are left alone).
5277  */
5278 int
5279 update_mac_settings(struct ifnet *ifp, int flags)
5280 {
5281         int rc = 0;
5282         struct vi_info *vi = ifp->if_softc;
5283         struct port_info *pi = vi->pi;
5284         struct adapter *sc = pi->adapter;
5285         int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5286         uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
5287
5288         ASSERT_SYNCHRONIZED_OP(sc);
5289         KASSERT(flags, ("%s: not told what to update.", __func__));
5290
5291         if (flags & XGMAC_MTU)
5292                 mtu = ifp->if_mtu;
5293
5294         if (flags & XGMAC_PROMISC)
5295                 promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5296
5297         if (flags & XGMAC_ALLMULTI)
5298                 allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5299
5300         if (flags & XGMAC_VLANEX)
5301                 vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5302
5303         if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5304                 rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5305                     allmulti, 1, vlanex, false);
5306                 if (rc) {
5307                         if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5308                             rc);
5309                         return (rc);
5310                 }
5311         }
5312
5313         if (flags & XGMAC_UCADDR) {
5314                 uint8_t ucaddr[ETHER_ADDR_LEN];
5315
5316                 bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5317                 rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5318                     ucaddr, true, &vi->smt_idx);
5319                 if (rc < 0) {
5320                         rc = -rc;
5321                         if_printf(ifp, "change_mac failed: %d\n", rc);
5322                         return (rc);
5323                 } else {
5324                         vi->xact_addr_filt = rc;
5325                         rc = 0;
5326                 }
5327         }
5328
5329         if (flags & XGMAC_MCADDRS) {
5330                 struct epoch_tracker et;
5331                 struct mcaddr_ctx ctx;
5332                 int j;
5333
5334                 ctx.ifp = ifp;
5335                 ctx.hash = 0;
5336                 ctx.i = 0;
5337                 ctx.del = 1;
5338                 ctx.rc = 0;
5339                 /*
5340                  * Unlike other drivers, we accumulate list of pointers into
5341                  * interface address lists and we need to keep it safe even
5342                  * after if_foreach_llmaddr() returns, thus we must enter the
5343                  * network epoch.
5344                  */
5345                 NET_EPOCH_ENTER(et);
5346                 if_foreach_llmaddr(ifp, add_maddr, &ctx);
5347                 if (ctx.rc < 0) {
5348                         NET_EPOCH_EXIT(et);
5349                         rc = -ctx.rc;
5350                         return (rc);
5351                 }
5352                 if (ctx.i > 0) {
5353                         rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
5354                             ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
5355                         NET_EPOCH_EXIT(et);
5356                         if (rc < 0) {
5357                                 rc = -rc;
5358                                 for (j = 0; j < ctx.i; j++) {
5359                                         if_printf(ifp,
5360                                             "failed to add mcast address"
5361                                             " %02x:%02x:%02x:"
5362                                             "%02x:%02x:%02x rc=%d\n",
5363                                             ctx.mcaddr[j][0], ctx.mcaddr[j][1],
5364                                             ctx.mcaddr[j][2], ctx.mcaddr[j][3],
5365                                             ctx.mcaddr[j][4], ctx.mcaddr[j][5],
5366                                             rc);
5367                                 }
5368                                 return (rc);
5369                         }
5370                         ctx.del = 0;
5371                 } else
5372                         NET_EPOCH_EXIT(et);
5373
5374                 rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
5375                 if (rc != 0)
5376                         if_printf(ifp, "failed to set mcast address hash: %d\n",
5377                             rc);
5378                 if (ctx.del == 0) {
5379                         /* We clobbered the VXLAN entry if there was one. */
5380                         pi->vxlan_tcam_entry = false;
5381                 }
5382         }
5383
5384         if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
5385             pi->vxlan_tcam_entry == false) {
5386                 rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
5387                     match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
5388                     true);
5389                 if (rc < 0) {
5390                         rc = -rc;
5391                         if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
5392                             rc);
5393                 } else {
5394                         MPASS(rc == sc->rawf_base + pi->port_id);
5395                         rc = 0;
5396                         pi->vxlan_tcam_entry = true;
5397                 }
5398         }
5399
5400         return (rc);
5401 }
5402
5403 /*
5404  * {begin|end}_synchronized_op must be called from the same thread.
5405  */
5406 int
5407 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
5408     char *wmesg)
5409 {
5410         int rc, pri;
5411
5412 #ifdef WITNESS
5413         /* the caller thinks it's ok to sleep, but is it really? */
5414         if (flags & SLEEP_OK)
5415                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
5416                     "begin_synchronized_op");
5417 #endif
5418
5419         if (INTR_OK)
5420                 pri = PCATCH;
5421         else
5422                 pri = 0;
5423
5424         ADAPTER_LOCK(sc);
5425         for (;;) {
5426
5427                 if (vi && IS_DOOMED(vi)) {
5428                         rc = ENXIO;
5429                         goto done;
5430                 }
5431
5432                 if (!IS_BUSY(sc)) {
5433                         rc = 0;
5434                         break;
5435                 }
5436
5437                 if (!(flags & SLEEP_OK)) {
5438                         rc = EBUSY;
5439                         goto done;
5440                 }
5441
5442                 if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
5443                         rc = EINTR;
5444                         goto done;
5445                 }
5446         }
5447
5448         KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
5449         SET_BUSY(sc);
5450 #ifdef INVARIANTS
5451         sc->last_op = wmesg;
5452         sc->last_op_thr = curthread;
5453         sc->last_op_flags = flags;
5454 #endif
5455
5456 done:
5457         if (!(flags & HOLD_LOCK) || rc)
5458                 ADAPTER_UNLOCK(sc);
5459
5460         return (rc);
5461 }
5462
5463 /*
5464  * Tell if_ioctl and if_init that the VI is going away.  This is
5465  * special variant of begin_synchronized_op and must be paired with a
5466  * call to end_synchronized_op.
5467  */
5468 void
5469 doom_vi(struct adapter *sc, struct vi_info *vi)
5470 {
5471
5472         ADAPTER_LOCK(sc);
5473         SET_DOOMED(vi);
5474         wakeup(&sc->flags);
5475         while (IS_BUSY(sc))
5476                 mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
5477         SET_BUSY(sc);
5478 #ifdef INVARIANTS
5479         sc->last_op = "t4detach";
5480         sc->last_op_thr = curthread;
5481         sc->last_op_flags = 0;
5482 #endif
5483         ADAPTER_UNLOCK(sc);
5484 }
5485
5486 /*
5487  * {begin|end}_synchronized_op must be called from the same thread.
5488  */
5489 void
5490 end_synchronized_op(struct adapter *sc, int flags)
5491 {
5492
5493         if (flags & LOCK_HELD)
5494                 ADAPTER_LOCK_ASSERT_OWNED(sc);
5495         else
5496                 ADAPTER_LOCK(sc);
5497
5498         KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
5499         CLR_BUSY(sc);
5500         wakeup(&sc->flags);
5501         ADAPTER_UNLOCK(sc);
5502 }
5503
5504 static int
5505 cxgbe_init_synchronized(struct vi_info *vi)
5506 {
5507         struct port_info *pi = vi->pi;
5508         struct adapter *sc = pi->adapter;
5509         struct ifnet *ifp = vi->ifp;
5510         int rc = 0, i;
5511         struct sge_txq *txq;
5512
5513         ASSERT_SYNCHRONIZED_OP(sc);
5514
5515         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
5516                 return (0);     /* already running */
5517
5518         if (!(sc->flags & FULL_INIT_DONE) &&
5519             ((rc = adapter_full_init(sc)) != 0))
5520                 return (rc);    /* error message displayed already */
5521
5522         if (!(vi->flags & VI_INIT_DONE) &&
5523             ((rc = vi_full_init(vi)) != 0))
5524                 return (rc); /* error message displayed already */
5525
5526         rc = update_mac_settings(ifp, XGMAC_ALL);
5527         if (rc)
5528                 goto done;      /* error message displayed already */
5529
5530         PORT_LOCK(pi);
5531         if (pi->up_vis == 0) {
5532                 t4_update_port_info(pi);
5533                 fixup_link_config(pi);
5534                 build_medialist(pi);
5535                 apply_link_config(pi);
5536         }
5537
5538         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
5539         if (rc != 0) {
5540                 if_printf(ifp, "enable_vi failed: %d\n", rc);
5541                 PORT_UNLOCK(pi);
5542                 goto done;
5543         }
5544
5545         /*
5546          * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
5547          * if this changes.
5548          */
5549
5550         for_each_txq(vi, i, txq) {
5551                 TXQ_LOCK(txq);
5552                 txq->eq.flags |= EQ_ENABLED;
5553                 TXQ_UNLOCK(txq);
5554         }
5555
5556         /*
5557          * The first iq of the first port to come up is used for tracing.
5558          */
5559         if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
5560                 sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
5561                 t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
5562                     A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
5563                     V_QUEUENUMBER(sc->traceq));
5564                 pi->flags |= HAS_TRACEQ;
5565         }
5566
5567         /* all ok */
5568         pi->up_vis++;
5569         ifp->if_drv_flags |= IFF_DRV_RUNNING;
5570
5571         if (pi->nvi > 1 || sc->flags & IS_VF)
5572                 callout_reset(&vi->tick, hz, vi_tick, vi);
5573         else
5574                 callout_reset(&pi->tick, hz, cxgbe_tick, pi);
5575         if (pi->link_cfg.link_ok)
5576                 t4_os_link_changed(pi);
5577         PORT_UNLOCK(pi);
5578 done:
5579         if (rc != 0)
5580                 cxgbe_uninit_synchronized(vi);
5581
5582         return (rc);
5583 }
5584
5585 /*
5586  * Idempotent.
5587  */
5588 static int
5589 cxgbe_uninit_synchronized(struct vi_info *vi)
5590 {
5591         struct port_info *pi = vi->pi;
5592         struct adapter *sc = pi->adapter;
5593         struct ifnet *ifp = vi->ifp;
5594         int rc, i;
5595         struct sge_txq *txq;
5596
5597         ASSERT_SYNCHRONIZED_OP(sc);
5598
5599         if (!(vi->flags & VI_INIT_DONE)) {
5600                 if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5601                         KASSERT(0, ("uninited VI is running"));
5602                         if_printf(ifp, "uninited VI with running ifnet.  "
5603                             "vi->flags 0x%016lx, if_flags 0x%08x, "
5604                             "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
5605                             ifp->if_drv_flags);
5606                 }
5607                 return (0);
5608         }
5609
5610         /*
5611          * Disable the VI so that all its data in either direction is discarded
5612          * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
5613          * tick) intact as the TP can deliver negative advice or data that it's
5614          * holding in its RAM (for an offloaded connection) even after the VI is
5615          * disabled.
5616          */
5617         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
5618         if (rc) {
5619                 if_printf(ifp, "disable_vi failed: %d\n", rc);
5620                 return (rc);
5621         }
5622
5623         for_each_txq(vi, i, txq) {
5624                 TXQ_LOCK(txq);
5625                 txq->eq.flags &= ~EQ_ENABLED;
5626                 TXQ_UNLOCK(txq);
5627         }
5628
5629         PORT_LOCK(pi);
5630         if (pi->nvi > 1 || sc->flags & IS_VF)
5631                 callout_stop(&vi->tick);
5632         else
5633                 callout_stop(&pi->tick);
5634         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5635                 PORT_UNLOCK(pi);
5636                 return (0);
5637         }
5638         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
5639         pi->up_vis--;
5640         if (pi->up_vis > 0) {
5641                 PORT_UNLOCK(pi);
5642                 return (0);
5643         }
5644
5645         pi->link_cfg.link_ok = false;
5646         pi->link_cfg.speed = 0;
5647         pi->link_cfg.link_down_rc = 255;
5648         t4_os_link_changed(pi);
5649         PORT_UNLOCK(pi);
5650
5651         return (0);
5652 }
5653
5654 /*
5655  * It is ok for this function to fail midway and return right away.  t4_detach
5656  * will walk the entire sc->irq list and clean up whatever is valid.
5657  */
5658 int
5659 t4_setup_intr_handlers(struct adapter *sc)
5660 {
5661         int rc, rid, p, q, v;
5662         char s[8];
5663         struct irq *irq;
5664         struct port_info *pi;
5665         struct vi_info *vi;
5666         struct sge *sge = &sc->sge;
5667         struct sge_rxq *rxq;
5668 #ifdef TCP_OFFLOAD
5669         struct sge_ofld_rxq *ofld_rxq;
5670 #endif
5671 #ifdef DEV_NETMAP
5672         struct sge_nm_rxq *nm_rxq;
5673 #endif
5674 #ifdef RSS
5675         int nbuckets = rss_getnumbuckets();
5676 #endif
5677
5678         /*
5679          * Setup interrupts.
5680          */
5681         irq = &sc->irq[0];
5682         rid = sc->intr_type == INTR_INTX ? 0 : 1;
5683         if (forwarding_intr_to_fwq(sc))
5684                 return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
5685
5686         /* Multiple interrupts. */
5687         if (sc->flags & IS_VF)
5688                 KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
5689                     ("%s: too few intr.", __func__));
5690         else
5691                 KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
5692                     ("%s: too few intr.", __func__));
5693
5694         /* The first one is always error intr on PFs */
5695         if (!(sc->flags & IS_VF)) {
5696                 rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
5697                 if (rc != 0)
5698                         return (rc);
5699                 irq++;
5700                 rid++;
5701         }
5702
5703         /* The second one is always the firmware event queue (first on VFs) */
5704         rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
5705         if (rc != 0)
5706                 return (rc);
5707         irq++;
5708         rid++;
5709
5710         for_each_port(sc, p) {
5711                 pi = sc->port[p];
5712                 for_each_vi(pi, v, vi) {
5713                         vi->first_intr = rid - 1;
5714
5715                         if (vi->nnmrxq > 0) {
5716                                 int n = max(vi->nrxq, vi->nnmrxq);
5717
5718                                 rxq = &sge->rxq[vi->first_rxq];
5719 #ifdef DEV_NETMAP
5720                                 nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
5721 #endif
5722                                 for (q = 0; q < n; q++) {
5723                                         snprintf(s, sizeof(s), "%x%c%x", p,
5724                                             'a' + v, q);
5725                                         if (q < vi->nrxq)
5726                                                 irq->rxq = rxq++;
5727 #ifdef DEV_NETMAP
5728                                         if (q < vi->nnmrxq)
5729                                                 irq->nm_rxq = nm_rxq++;
5730
5731                                         if (irq->nm_rxq != NULL &&
5732                                             irq->rxq == NULL) {
5733                                                 /* Netmap rx only */
5734                                                 rc = t4_alloc_irq(sc, irq, rid,
5735                                                     t4_nm_intr, irq->nm_rxq, s);
5736                                         }
5737                                         if (irq->nm_rxq != NULL &&
5738                                             irq->rxq != NULL) {
5739                                                 /* NIC and Netmap rx */
5740                                                 rc = t4_alloc_irq(sc, irq, rid,
5741                                                     t4_vi_intr, irq, s);
5742                                         }
5743 #endif
5744                                         if (irq->rxq != NULL &&
5745                                             irq->nm_rxq == NULL) {
5746                                                 /* NIC rx only */
5747                                                 rc = t4_alloc_irq(sc, irq, rid,
5748                                                     t4_intr, irq->rxq, s);
5749                                         }
5750                                         if (rc != 0)
5751                                                 return (rc);
5752 #ifdef RSS
5753                                         if (q < vi->nrxq) {
5754                                                 bus_bind_intr(sc->dev, irq->res,
5755                                                     rss_getcpu(q % nbuckets));
5756                                         }
5757 #endif
5758                                         irq++;
5759                                         rid++;
5760                                         vi->nintr++;
5761                                 }
5762                         } else {
5763                                 for_each_rxq(vi, q, rxq) {
5764                                         snprintf(s, sizeof(s), "%x%c%x", p,
5765                                             'a' + v, q);
5766                                         rc = t4_alloc_irq(sc, irq, rid,
5767                                             t4_intr, rxq, s);
5768                                         if (rc != 0)
5769                                                 return (rc);
5770 #ifdef RSS
5771                                         bus_bind_intr(sc->dev, irq->res,
5772                                             rss_getcpu(q % nbuckets));
5773 #endif
5774                                         irq++;
5775                                         rid++;
5776                                         vi->nintr++;
5777                                 }
5778                         }
5779 #ifdef TCP_OFFLOAD
5780                         for_each_ofld_rxq(vi, q, ofld_rxq) {
5781                                 snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
5782                                 rc = t4_alloc_irq(sc, irq, rid, t4_intr,
5783                                     ofld_rxq, s);
5784                                 if (rc != 0)
5785                                         return (rc);
5786                                 irq++;
5787                                 rid++;
5788                                 vi->nintr++;
5789                         }
5790 #endif
5791                 }
5792         }
5793         MPASS(irq == &sc->irq[sc->intr_count]);
5794
5795         return (0);
5796 }
5797
5798 int
5799 adapter_full_init(struct adapter *sc)
5800 {
5801         int rc, i;
5802 #ifdef RSS
5803         uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5804         uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5805 #endif
5806
5807         ASSERT_SYNCHRONIZED_OP(sc);
5808         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5809         KASSERT((sc->flags & FULL_INIT_DONE) == 0,
5810             ("%s: FULL_INIT_DONE already", __func__));
5811
5812         /*
5813          * queues that belong to the adapter (not any particular port).
5814          */
5815         rc = t4_setup_adapter_queues(sc);
5816         if (rc != 0)
5817                 goto done;
5818
5819         for (i = 0; i < nitems(sc->tq); i++) {
5820                 sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
5821                     taskqueue_thread_enqueue, &sc->tq[i]);
5822                 if (sc->tq[i] == NULL) {
5823                         device_printf(sc->dev,
5824                             "failed to allocate task queue %d\n", i);
5825                         rc = ENOMEM;
5826                         goto done;
5827                 }
5828                 taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
5829                     device_get_nameunit(sc->dev), i);
5830         }
5831 #ifdef RSS
5832         MPASS(RSS_KEYSIZE == 40);
5833         rss_getkey((void *)&raw_rss_key[0]);
5834         for (i = 0; i < nitems(rss_key); i++) {
5835                 rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
5836         }
5837         t4_write_rss_key(sc, &rss_key[0], -1, 1);
5838 #endif
5839
5840         if (!(sc->flags & IS_VF))
5841                 t4_intr_enable(sc);
5842 #ifdef KERN_TLS
5843         if (sc->flags & KERN_TLS_OK)
5844                 callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5845                     C_HARDCLOCK);
5846 #endif
5847         sc->flags |= FULL_INIT_DONE;
5848 done:
5849         if (rc != 0)
5850                 adapter_full_uninit(sc);
5851
5852         return (rc);
5853 }
5854
5855 int
5856 adapter_full_uninit(struct adapter *sc)
5857 {
5858         int i;
5859
5860         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5861
5862         t4_teardown_adapter_queues(sc);
5863
5864         for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
5865                 taskqueue_free(sc->tq[i]);
5866                 sc->tq[i] = NULL;
5867         }
5868
5869         sc->flags &= ~FULL_INIT_DONE;
5870
5871         return (0);
5872 }
5873
5874 #ifdef RSS
5875 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
5876     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
5877     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
5878     RSS_HASHTYPE_RSS_UDP_IPV6)
5879
5880 /* Translates kernel hash types to hardware. */
5881 static int
5882 hashconfig_to_hashen(int hashconfig)
5883 {
5884         int hashen = 0;
5885
5886         if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
5887                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
5888         if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
5889                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
5890         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
5891                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5892                     F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5893         }
5894         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
5895                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5896                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5897         }
5898         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
5899                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5900         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
5901                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5902
5903         return (hashen);
5904 }
5905
5906 /* Translates hardware hash types to kernel. */
5907 static int
5908 hashen_to_hashconfig(int hashen)
5909 {
5910         int hashconfig = 0;
5911
5912         if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
5913                 /*
5914                  * If UDP hashing was enabled it must have been enabled for
5915                  * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
5916                  * enabling any 4-tuple hash is nonsense configuration.
5917                  */
5918                 MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5919                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
5920
5921                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5922                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
5923                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5924                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
5925         }
5926         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5927                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
5928         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5929                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
5930         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
5931                 hashconfig |= RSS_HASHTYPE_RSS_IPV4;
5932         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
5933                 hashconfig |= RSS_HASHTYPE_RSS_IPV6;
5934
5935         return (hashconfig);
5936 }
5937 #endif
5938
5939 int
5940 vi_full_init(struct vi_info *vi)
5941 {
5942         struct adapter *sc = vi->adapter;
5943         struct ifnet *ifp = vi->ifp;
5944         uint16_t *rss;
5945         struct sge_rxq *rxq;
5946         int rc, i, j;
5947 #ifdef RSS
5948         int nbuckets = rss_getnumbuckets();
5949         int hashconfig = rss_gethashconfig();
5950         int extra;
5951 #endif
5952
5953         ASSERT_SYNCHRONIZED_OP(sc);
5954         KASSERT((vi->flags & VI_INIT_DONE) == 0,
5955             ("%s: VI_INIT_DONE already", __func__));
5956
5957         sysctl_ctx_init(&vi->ctx);
5958         vi->flags |= VI_SYSCTL_CTX;
5959
5960         /*
5961          * Allocate tx/rx/fl queues for this VI.
5962          */
5963         rc = t4_setup_vi_queues(vi);
5964         if (rc != 0)
5965                 goto done;      /* error message displayed already */
5966
5967         /*
5968          * Setup RSS for this VI.  Save a copy of the RSS table for later use.
5969          */
5970         if (vi->nrxq > vi->rss_size) {
5971                 if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
5972                     "some queues will never receive traffic.\n", vi->nrxq,
5973                     vi->rss_size);
5974         } else if (vi->rss_size % vi->nrxq) {
5975                 if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
5976                     "expect uneven traffic distribution.\n", vi->nrxq,
5977                     vi->rss_size);
5978         }
5979 #ifdef RSS
5980         if (vi->nrxq != nbuckets) {
5981                 if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
5982                     "performance will be impacted.\n", vi->nrxq, nbuckets);
5983         }
5984 #endif
5985         rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
5986         for (i = 0; i < vi->rss_size;) {
5987 #ifdef RSS
5988                 j = rss_get_indirection_to_bucket(i);
5989                 j %= vi->nrxq;
5990                 rxq = &sc->sge.rxq[vi->first_rxq + j];
5991                 rss[i++] = rxq->iq.abs_id;
5992 #else
5993                 for_each_rxq(vi, j, rxq) {
5994                         rss[i++] = rxq->iq.abs_id;
5995                         if (i == vi->rss_size)
5996                                 break;
5997                 }
5998 #endif
5999         }
6000
6001         rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
6002             vi->rss_size);
6003         if (rc != 0) {
6004                 free(rss, M_CXGBE);
6005                 if_printf(ifp, "rss_config failed: %d\n", rc);
6006                 goto done;
6007         }
6008
6009 #ifdef RSS
6010         vi->hashen = hashconfig_to_hashen(hashconfig);
6011
6012         /*
6013          * We may have had to enable some hashes even though the global config
6014          * wants them disabled.  This is a potential problem that must be
6015          * reported to the user.
6016          */
6017         extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6018
6019         /*
6020          * If we consider only the supported hash types, then the enabled hashes
6021          * are a superset of the requested hashes.  In other words, there cannot
6022          * be any supported hash that was requested but not enabled, but there
6023          * can be hashes that were not requested but had to be enabled.
6024          */
6025         extra &= SUPPORTED_RSS_HASHTYPES;
6026         MPASS((extra & hashconfig) == 0);
6027
6028         if (extra) {
6029                 if_printf(ifp,
6030                     "global RSS config (0x%x) cannot be accommodated.\n",
6031                     hashconfig);
6032         }
6033         if (extra & RSS_HASHTYPE_RSS_IPV4)
6034                 if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
6035         if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6036                 if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
6037         if (extra & RSS_HASHTYPE_RSS_IPV6)
6038                 if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
6039         if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6040                 if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
6041         if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6042                 if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
6043         if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6044                 if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
6045 #else
6046         vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6047             F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6048             F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6049             F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6050 #endif
6051         rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, rss[0], 0, 0);
6052         if (rc != 0) {
6053                 free(rss, M_CXGBE);
6054                 if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
6055                 goto done;
6056         }
6057
6058         vi->rss = rss;
6059         vi->flags |= VI_INIT_DONE;
6060 done:
6061         if (rc != 0)
6062                 vi_full_uninit(vi);
6063
6064         return (rc);
6065 }
6066
6067 /*
6068  * Idempotent.
6069  */
6070 int
6071 vi_full_uninit(struct vi_info *vi)
6072 {
6073         struct port_info *pi = vi->pi;
6074         struct adapter *sc = pi->adapter;
6075         int i;
6076         struct sge_rxq *rxq;
6077         struct sge_txq *txq;
6078 #ifdef TCP_OFFLOAD
6079         struct sge_ofld_rxq *ofld_rxq;
6080 #endif
6081 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6082         struct sge_wrq *ofld_txq;
6083 #endif
6084
6085         if (vi->flags & VI_INIT_DONE) {
6086
6087                 /* Need to quiesce queues.  */
6088
6089                 /* XXX: Only for the first VI? */
6090                 if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
6091                         quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
6092
6093                 for_each_txq(vi, i, txq) {
6094                         quiesce_txq(sc, txq);
6095                 }
6096
6097 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6098                 for_each_ofld_txq(vi, i, ofld_txq) {
6099                         quiesce_wrq(sc, ofld_txq);
6100                 }
6101 #endif
6102
6103                 for_each_rxq(vi, i, rxq) {
6104                         quiesce_iq(sc, &rxq->iq);
6105                         quiesce_fl(sc, &rxq->fl);
6106                 }
6107
6108 #ifdef TCP_OFFLOAD
6109                 for_each_ofld_rxq(vi, i, ofld_rxq) {
6110                         quiesce_iq(sc, &ofld_rxq->iq);
6111                         quiesce_fl(sc, &ofld_rxq->fl);
6112                 }
6113 #endif
6114                 free(vi->rss, M_CXGBE);
6115                 free(vi->nm_rss, M_CXGBE);
6116         }
6117
6118         t4_teardown_vi_queues(vi);
6119         vi->flags &= ~VI_INIT_DONE;
6120
6121         return (0);
6122 }
6123
6124 static void
6125 quiesce_txq(struct adapter *sc, struct sge_txq *txq)
6126 {
6127         struct sge_eq *eq = &txq->eq;
6128         struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6129
6130         (void) sc;      /* unused */
6131
6132 #ifdef INVARIANTS
6133         TXQ_LOCK(txq);
6134         MPASS((eq->flags & EQ_ENABLED) == 0);
6135         TXQ_UNLOCK(txq);
6136 #endif
6137
6138         /* Wait for the mp_ring to empty. */
6139         while (!mp_ring_is_idle(txq->r)) {
6140                 mp_ring_check_drainage(txq->r, 4096);
6141                 pause("rquiesce", 1);
6142         }
6143
6144         /* Then wait for the hardware to finish. */
6145         while (spg->cidx != htobe16(eq->pidx))
6146                 pause("equiesce", 1);
6147
6148         /* Finally, wait for the driver to reclaim all descriptors. */
6149         while (eq->cidx != eq->pidx)
6150                 pause("dquiesce", 1);
6151 }
6152
6153 static void
6154 quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
6155 {
6156
6157         /* XXXTX */
6158 }
6159
6160 static void
6161 quiesce_iq(struct adapter *sc, struct sge_iq *iq)
6162 {
6163         (void) sc;      /* unused */
6164
6165         /* Synchronize with the interrupt handler */
6166         while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6167                 pause("iqfree", 1);
6168 }
6169
6170 static void
6171 quiesce_fl(struct adapter *sc, struct sge_fl *fl)
6172 {
6173         mtx_lock(&sc->sfl_lock);
6174         FL_LOCK(fl);
6175         fl->flags |= FL_DOOMED;
6176         FL_UNLOCK(fl);
6177         callout_stop(&sc->sfl_callout);
6178         mtx_unlock(&sc->sfl_lock);
6179
6180         KASSERT((fl->flags & FL_STARVING) == 0,
6181             ("%s: still starving", __func__));
6182 }
6183
6184 static int
6185 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
6186     driver_intr_t *handler, void *arg, char *name)
6187 {
6188         int rc;
6189
6190         irq->rid = rid;
6191         irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
6192             RF_SHAREABLE | RF_ACTIVE);
6193         if (irq->res == NULL) {
6194                 device_printf(sc->dev,
6195                     "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
6196                 return (ENOMEM);
6197         }
6198
6199         rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
6200             NULL, handler, arg, &irq->tag);
6201         if (rc != 0) {
6202                 device_printf(sc->dev,
6203                     "failed to setup interrupt for rid %d, name %s: %d\n",
6204                     rid, name, rc);
6205         } else if (name)
6206                 bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
6207
6208         return (rc);
6209 }
6210
6211 static int
6212 t4_free_irq(struct adapter *sc, struct irq *irq)
6213 {
6214         if (irq->tag)
6215                 bus_teardown_intr(sc->dev, irq->res, irq->tag);
6216         if (irq->res)
6217                 bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
6218
6219         bzero(irq, sizeof(*irq));
6220
6221         return (0);
6222 }
6223
6224 static void
6225 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
6226 {
6227
6228         regs->version = chip_id(sc) | chip_rev(sc) << 10;
6229         t4_get_regs(sc, buf, regs->len);
6230 }
6231
6232 #define A_PL_INDIR_CMD  0x1f8
6233
6234 #define S_PL_AUTOINC    31
6235 #define M_PL_AUTOINC    0x1U
6236 #define V_PL_AUTOINC(x) ((x) << S_PL_AUTOINC)
6237 #define G_PL_AUTOINC(x) (((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
6238
6239 #define S_PL_VFID       20
6240 #define M_PL_VFID       0xffU
6241 #define V_PL_VFID(x)    ((x) << S_PL_VFID)
6242 #define G_PL_VFID(x)    (((x) >> S_PL_VFID) & M_PL_VFID)
6243
6244 #define S_PL_ADDR       0
6245 #define M_PL_ADDR       0xfffffU
6246 #define V_PL_ADDR(x)    ((x) << S_PL_ADDR)
6247 #define G_PL_ADDR(x)    (((x) >> S_PL_ADDR) & M_PL_ADDR)
6248
6249 #define A_PL_INDIR_DATA 0x1fc
6250
6251 static uint64_t
6252 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6253 {
6254         u32 stats[2];
6255
6256         mtx_assert(&sc->reg_lock, MA_OWNED);
6257         if (sc->flags & IS_VF) {
6258                 stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6259                 stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6260         } else {
6261                 t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6262                     V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6263                 stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6264                 stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6265         }
6266         return (((uint64_t)stats[1]) << 32 | stats[0]);
6267 }
6268
6269 static void
6270 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6271 {
6272
6273 #define GET_STAT(name) \
6274         read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6275
6276         stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
6277         stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
6278         stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
6279         stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
6280         stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
6281         stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
6282         stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
6283         stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
6284         stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
6285         stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
6286         stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
6287         stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
6288         stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
6289         stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
6290         stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
6291         stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
6292
6293 #undef GET_STAT
6294 }
6295
6296 static void
6297 t4_clr_vi_stats(struct adapter *sc, u_int vin)
6298 {
6299         int reg;
6300
6301         t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
6302             V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
6303         for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
6304              reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
6305                 t4_write_reg(sc, A_PL_INDIR_DATA, 0);
6306 }
6307
6308 static void
6309 vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
6310 {
6311         struct timeval tv;
6312         const struct timeval interval = {0, 250000};    /* 250ms */
6313
6314         if (!(vi->flags & VI_INIT_DONE))
6315                 return;
6316
6317         getmicrotime(&tv);
6318         timevalsub(&tv, &interval);
6319         if (timevalcmp(&tv, &vi->last_refreshed, <))
6320                 return;
6321
6322         mtx_lock(&sc->reg_lock);
6323         t4_get_vi_stats(sc, vi->vin, &vi->stats);
6324         getmicrotime(&vi->last_refreshed);
6325         mtx_unlock(&sc->reg_lock);
6326 }
6327
6328 static void
6329 cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
6330 {
6331         u_int i, v, tnl_cong_drops, chan_map;
6332         struct timeval tv;
6333         const struct timeval interval = {0, 250000};    /* 250ms */
6334
6335         getmicrotime(&tv);
6336         timevalsub(&tv, &interval);
6337         if (timevalcmp(&tv, &pi->last_refreshed, <))
6338                 return;
6339
6340         tnl_cong_drops = 0;
6341         t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
6342         chan_map = pi->rx_e_chan_map;
6343         while (chan_map) {
6344                 i = ffs(chan_map) - 1;
6345                 mtx_lock(&sc->reg_lock);
6346                 t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
6347                     A_TP_MIB_TNL_CNG_DROP_0 + i);
6348                 mtx_unlock(&sc->reg_lock);
6349                 tnl_cong_drops += v;
6350                 chan_map &= ~(1 << i);
6351         }
6352         pi->tnl_cong_drops = tnl_cong_drops;
6353         getmicrotime(&pi->last_refreshed);
6354 }
6355
6356 static void
6357 cxgbe_tick(void *arg)
6358 {
6359         struct port_info *pi = arg;
6360         struct adapter *sc = pi->adapter;
6361
6362         PORT_LOCK_ASSERT_OWNED(pi);
6363         cxgbe_refresh_stats(sc, pi);
6364
6365         callout_schedule(&pi->tick, hz);
6366 }
6367
6368 void
6369 vi_tick(void *arg)
6370 {
6371         struct vi_info *vi = arg;
6372         struct adapter *sc = vi->adapter;
6373
6374         vi_refresh_stats(sc, vi);
6375
6376         callout_schedule(&vi->tick, hz);
6377 }
6378
6379 /*
6380  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
6381  */
6382 static char *caps_decoder[] = {
6383         "\20\001IPMI\002NCSI",                          /* 0: NBM */
6384         "\20\001PPP\002QFC\003DCBX",                    /* 1: link */
6385         "\20\001INGRESS\002EGRESS",                     /* 2: switch */
6386         "\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"      /* 3: NIC */
6387             "\006HASHFILTER\007ETHOFLD",
6388         "\20\001TOE",                                   /* 4: TOE */
6389         "\20\001RDDP\002RDMAC",                         /* 5: RDMA */
6390         "\20\001INITIATOR_PDU\002TARGET_PDU"            /* 6: iSCSI */
6391             "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
6392             "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
6393             "\007T10DIF"
6394             "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
6395         "\20\001LOOKASIDE\002TLSKEYS",                  /* 7: Crypto */
6396         "\20\001INITIATOR\002TARGET\003CTRL_OFLD"       /* 8: FCoE */
6397                     "\004PO_INITIATOR\005PO_TARGET",
6398 };
6399
6400 void
6401 t4_sysctls(struct adapter *sc)
6402 {
6403         struct sysctl_ctx_list *ctx;
6404         struct sysctl_oid *oid;
6405         struct sysctl_oid_list *children, *c0;
6406         static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
6407
6408         ctx = device_get_sysctl_ctx(sc->dev);
6409
6410         /*
6411          * dev.t4nex.X.
6412          */
6413         oid = device_get_sysctl_tree(sc->dev);
6414         c0 = children = SYSCTL_CHILDREN(oid);
6415
6416         sc->sc_do_rxcopy = 1;
6417         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
6418             &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
6419
6420         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
6421             sc->params.nports, "# of ports");
6422
6423         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
6424             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
6425             (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
6426             "available doorbells");
6427
6428         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
6429             sc->params.vpd.cclk, "core clock frequency (in KHz)");
6430
6431         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
6432             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
6433             sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
6434             sysctl_int_array, "A", "interrupt holdoff timer values (us)");
6435
6436         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
6437             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
6438             sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
6439             sysctl_int_array, "A", "interrupt holdoff packet counter values");
6440
6441         t4_sge_sysctls(sc, ctx, children);
6442
6443         sc->lro_timeout = 100;
6444         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
6445             &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
6446
6447         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
6448             &sc->debug_flags, 0, "flags to enable runtime debugging");
6449
6450         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
6451             CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
6452
6453         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
6454             CTLFLAG_RD, sc->fw_version, 0, "firmware version");
6455
6456         if (sc->flags & IS_VF)
6457                 return;
6458
6459         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
6460             NULL, chip_rev(sc), "chip hardware revision");
6461
6462         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
6463             CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
6464
6465         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
6466             CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
6467
6468         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
6469             CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
6470
6471         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
6472             CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
6473
6474         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
6475             CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
6476
6477         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
6478             sc->er_version, 0, "expansion ROM version");
6479
6480         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
6481             sc->bs_version, 0, "bootstrap firmware version");
6482
6483         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
6484             NULL, sc->params.scfg_vers, "serial config version");
6485
6486         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
6487             NULL, sc->params.vpd_vers, "VPD version");
6488
6489         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
6490             CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
6491
6492         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
6493             sc->cfcsum, "config file checksum");
6494
6495 #define SYSCTL_CAP(name, n, text) \
6496         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
6497             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
6498             (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
6499             "available " text " capabilities")
6500
6501         SYSCTL_CAP(nbmcaps, 0, "NBM");
6502         SYSCTL_CAP(linkcaps, 1, "link");
6503         SYSCTL_CAP(switchcaps, 2, "switch");
6504         SYSCTL_CAP(niccaps, 3, "NIC");
6505         SYSCTL_CAP(toecaps, 4, "TCP offload");
6506         SYSCTL_CAP(rdmacaps, 5, "RDMA");
6507         SYSCTL_CAP(iscsicaps, 6, "iSCSI");
6508         SYSCTL_CAP(cryptocaps, 7, "crypto");
6509         SYSCTL_CAP(fcoecaps, 8, "FCoE");
6510 #undef SYSCTL_CAP
6511
6512         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
6513             NULL, sc->tids.nftids, "number of filters");
6514
6515         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
6516             CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6517             sysctl_temperature, "I", "chip temperature (in Celsius)");
6518         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
6519             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
6520             sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
6521
6522         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
6523             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6524             sysctl_loadavg, "A",
6525             "microprocessor load averages (debug firmwares only)");
6526
6527         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
6528             CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
6529             "I", "core Vdd (in mV)");
6530
6531         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
6532             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
6533             sysctl_cpus, "A", "local CPUs");
6534
6535         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
6536             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
6537             sysctl_cpus, "A", "preferred CPUs for interrupts");
6538
6539         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
6540             &sc->swintr, 0, "software triggered interrupts");
6541
6542         /*
6543          * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
6544          */
6545         oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
6546             CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
6547             "logs and miscellaneous information");
6548         children = SYSCTL_CHILDREN(oid);
6549
6550         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
6551             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6552             sysctl_cctrl, "A", "congestion control");
6553
6554         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
6555             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6556             sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
6557
6558         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
6559             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
6560             sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
6561
6562         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
6563             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
6564             sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
6565
6566         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
6567             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
6568             sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
6569
6570         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
6571             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
6572             sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
6573
6574         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
6575             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
6576             sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
6577
6578         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
6579             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6580             sysctl_cim_la, "A", "CIM logic analyzer");
6581
6582         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
6583             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6584             sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
6585
6586         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
6587             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6588             0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
6589
6590         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
6591             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6592             1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
6593
6594         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
6595             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6596             2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
6597
6598         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
6599             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6600             3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
6601
6602         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
6603             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6604             4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
6605
6606         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
6607             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6608             5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
6609
6610         if (chip_id(sc) > CHELSIO_T4) {
6611                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
6612                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6613                     6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
6614                     "CIM OBQ 6 (SGE0-RX)");
6615
6616                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
6617                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6618                     7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
6619                     "CIM OBQ 7 (SGE1-RX)");
6620         }
6621
6622         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
6623             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6624             sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
6625
6626         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
6627             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6628             sysctl_cim_qcfg, "A", "CIM queue configuration");
6629
6630         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
6631             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6632             sysctl_cpl_stats, "A", "CPL statistics");
6633
6634         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
6635             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6636             sysctl_ddp_stats, "A", "non-TCP DDP statistics");
6637
6638         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
6639             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6640             sysctl_tid_stats, "A", "tid stats");
6641
6642         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
6643             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6644             sysctl_devlog, "A", "firmware's device log");
6645
6646         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
6647             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6648             sysctl_fcoe_stats, "A", "FCoE statistics");
6649
6650         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
6651             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6652             sysctl_hw_sched, "A", "hardware scheduler ");
6653
6654         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
6655             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6656             sysctl_l2t, "A", "hardware L2 table");
6657
6658         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
6659             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6660             sysctl_smt, "A", "hardware source MAC table");
6661
6662 #ifdef INET6
6663         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
6664             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6665             sysctl_clip, "A", "active CLIP table entries");
6666 #endif
6667
6668         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
6669             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6670             sysctl_lb_stats, "A", "loopback statistics");
6671
6672         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
6673             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6674             sysctl_meminfo, "A", "memory regions");
6675
6676         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
6677             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6678             chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
6679             "A", "MPS TCAM entries");
6680
6681         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
6682             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6683             sysctl_path_mtus, "A", "path MTUs");
6684
6685         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
6686             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6687             sysctl_pm_stats, "A", "PM statistics");
6688
6689         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
6690             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6691             sysctl_rdma_stats, "A", "RDMA statistics");
6692
6693         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
6694             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6695             sysctl_tcp_stats, "A", "TCP statistics");
6696
6697         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
6698             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6699             sysctl_tids, "A", "TID information");
6700
6701         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
6702             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6703             sysctl_tp_err_stats, "A", "TP error statistics");
6704
6705         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
6706             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6707             sysctl_tnl_stats, "A", "TP tunnel statistics");
6708
6709         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
6710             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
6711             sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
6712
6713         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
6714             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6715             sysctl_tp_la, "A", "TP logic analyzer");
6716
6717         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
6718             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6719             sysctl_tx_rate, "A", "Tx rate");
6720
6721         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
6722             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6723             sysctl_ulprx_la, "A", "ULPRX logic analyzer");
6724
6725         if (chip_id(sc) >= CHELSIO_T5) {
6726                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
6727                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6728                     sysctl_wcwr_stats, "A", "write combined work requests");
6729         }
6730
6731 #ifdef KERN_TLS
6732         if (sc->flags & KERN_TLS_OK) {
6733                 /*
6734                  * dev.t4nex.0.tls.
6735                  */
6736                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
6737                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
6738                 children = SYSCTL_CHILDREN(oid);
6739
6740                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
6741                     CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
6742                     "keys in work requests (1) or attempt to store TLS keys "
6743                     "in card memory.");
6744                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
6745                     CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
6746                     "TCB field updates with TLS record work requests.");
6747         }
6748 #endif
6749
6750 #ifdef TCP_OFFLOAD
6751         if (is_offload(sc)) {
6752                 int i;
6753                 char s[4];
6754
6755                 /*
6756                  * dev.t4nex.X.toe.
6757                  */
6758                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
6759                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
6760                 children = SYSCTL_CHILDREN(oid);
6761
6762                 sc->tt.cong_algorithm = -1;
6763                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
6764                     CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
6765                     "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
6766                     "3 = highspeed)");
6767
6768                 sc->tt.sndbuf = -1;
6769                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
6770                     &sc->tt.sndbuf, 0, "hardware send buffer");
6771
6772                 sc->tt.ddp = 0;
6773                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
6774                     CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
6775                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
6776                     &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
6777
6778                 sc->tt.rx_coalesce = -1;
6779                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
6780                     CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
6781
6782                 sc->tt.tls = 0;
6783                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
6784                     CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
6785                     "Inline TLS allowed");
6786
6787                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
6788                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
6789                     sysctl_tls_rx_ports, "I",
6790                     "TCP ports that use inline TLS+TOE RX");
6791
6792                 sc->tt.tx_align = -1;
6793                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
6794                     CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
6795
6796                 sc->tt.tx_zcopy = 0;
6797                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
6798                     CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
6799                     "Enable zero-copy aio_write(2)");
6800
6801                 sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
6802                 SYSCTL_ADD_INT(ctx, children, OID_AUTO,
6803                     "cop_managed_offloading", CTLFLAG_RW,
6804                     &sc->tt.cop_managed_offloading, 0,
6805                     "COP (Connection Offload Policy) controls all TOE offload");
6806
6807                 sc->tt.autorcvbuf_inc = 16 * 1024;
6808                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
6809                     CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
6810                     "autorcvbuf increment");
6811
6812                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
6813                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6814                     sysctl_tp_tick, "A", "TP timer tick (us)");
6815
6816                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
6817                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
6818                     sysctl_tp_tick, "A", "TCP timestamp tick (us)");
6819
6820                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
6821                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
6822                     sysctl_tp_tick, "A", "DACK tick (us)");
6823
6824                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
6825                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
6826                     sysctl_tp_dack_timer, "IU", "DACK timer (us)");
6827
6828                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
6829                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6830                     A_TP_RXT_MIN, sysctl_tp_timer, "LU",
6831                     "Minimum retransmit interval (us)");
6832
6833                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
6834                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6835                     A_TP_RXT_MAX, sysctl_tp_timer, "LU",
6836                     "Maximum retransmit interval (us)");
6837
6838                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
6839                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6840                     A_TP_PERS_MIN, sysctl_tp_timer, "LU",
6841                     "Persist timer min (us)");
6842
6843                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
6844                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6845                     A_TP_PERS_MAX, sysctl_tp_timer, "LU",
6846                     "Persist timer max (us)");
6847
6848                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
6849                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6850                     A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
6851                     "Keepalive idle timer (us)");
6852
6853                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
6854                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6855                     A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
6856                     "Keepalive interval timer (us)");
6857
6858                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
6859                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6860                     A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
6861
6862                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
6863                     CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6864                     A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
6865                     "FINWAIT2 timer (us)");
6866
6867                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
6868                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6869                     S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
6870                     "Number of SYN retransmissions before abort");
6871
6872                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
6873                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6874                     S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
6875                     "Number of retransmissions before abort");
6876
6877                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
6878                     CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6879                     S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
6880                     "Number of keepalive probes before abort");
6881
6882                 oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
6883                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
6884                     "TOE retransmit backoffs");
6885                 children = SYSCTL_CHILDREN(oid);
6886                 for (i = 0; i < 16; i++) {
6887                         snprintf(s, sizeof(s), "%u", i);
6888                         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
6889                             CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
6890                             i, sysctl_tp_backoff, "IU",
6891                             "TOE retransmit backoff");
6892                 }
6893         }
6894 #endif
6895 }
6896
6897 void
6898 vi_sysctls(struct vi_info *vi)
6899 {
6900         struct sysctl_ctx_list *ctx;
6901         struct sysctl_oid *oid;
6902         struct sysctl_oid_list *children;
6903
6904         ctx = device_get_sysctl_ctx(vi->dev);
6905
6906         /*
6907          * dev.v?(cxgbe|cxl).X.
6908          */
6909         oid = device_get_sysctl_tree(vi->dev);
6910         children = SYSCTL_CHILDREN(oid);
6911
6912         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
6913             vi->viid, "VI identifer");
6914         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
6915             &vi->nrxq, 0, "# of rx queues");
6916         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
6917             &vi->ntxq, 0, "# of tx queues");
6918         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
6919             &vi->first_rxq, 0, "index of first rx queue");
6920         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
6921             &vi->first_txq, 0, "index of first tx queue");
6922         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
6923             vi->rss_base, "start of RSS indirection table");
6924         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
6925             vi->rss_size, "size of RSS indirection table");
6926
6927         if (IS_MAIN_VI(vi)) {
6928                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
6929                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6930                     sysctl_noflowq, "IU",
6931                     "Reserve queue 0 for non-flowid packets");
6932         }
6933
6934         if (vi->adapter->flags & IS_VF) {
6935                 MPASS(vi->flags & TX_USES_VM_WR);
6936                 SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
6937                     NULL, 1, "use VM work requests for transmit");
6938         } else {
6939                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
6940                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6941                     sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
6942         }
6943
6944 #ifdef TCP_OFFLOAD
6945         if (vi->nofldrxq != 0) {
6946                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
6947                     &vi->nofldrxq, 0,
6948                     "# of rx queues for offloaded TCP connections");
6949                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
6950                     CTLFLAG_RD, &vi->first_ofld_rxq, 0,
6951                     "index of first TOE rx queue");
6952                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
6953                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6954                     sysctl_holdoff_tmr_idx_ofld, "I",
6955                     "holdoff timer index for TOE queues");
6956                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
6957                     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6958                     sysctl_holdoff_pktc_idx_ofld, "I",
6959                     "holdoff packet counter index for TOE queues");
6960         }
6961 #endif
6962 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6963         if (vi->nofldtxq != 0) {
6964                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
6965                     &vi->nofldtxq, 0,
6966                     "# of tx queues for TOE/ETHOFLD");
6967                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
6968                     CTLFLAG_RD, &vi->first_ofld_txq, 0,
6969                     "index of first TOE/ETHOFLD tx queue");
6970         }
6971 #endif
6972 #ifdef DEV_NETMAP
6973         if (vi->nnmrxq != 0) {
6974                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
6975                     &vi->nnmrxq, 0, "# of netmap rx queues");
6976                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
6977                     &vi->nnmtxq, 0, "# of netmap tx queues");
6978                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
6979                     CTLFLAG_RD, &vi->first_nm_rxq, 0,
6980                     "index of first netmap rx queue");
6981                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
6982                     CTLFLAG_RD, &vi->first_nm_txq, 0,
6983                     "index of first netmap tx queue");
6984         }
6985 #endif
6986
6987         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
6988             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6989             sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
6990         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
6991             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6992             sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
6993
6994         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
6995             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6996             sysctl_qsize_rxq, "I", "rx queue size");
6997         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
6998             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
6999             sysctl_qsize_txq, "I", "tx queue size");
7000 }
7001
7002 static void
7003 cxgbe_sysctls(struct port_info *pi)
7004 {
7005         struct sysctl_ctx_list *ctx;
7006         struct sysctl_oid *oid;
7007         struct sysctl_oid_list *children, *children2;
7008         struct adapter *sc = pi->adapter;
7009         int i;
7010         char name[16];
7011         static char *tc_flags = {"\20\1USER\2SYNC\3ASYNC\4ERR"};
7012
7013         ctx = device_get_sysctl_ctx(pi->dev);
7014
7015         /*
7016          * dev.cxgbe.X.
7017          */
7018         oid = device_get_sysctl_tree(pi->dev);
7019         children = SYSCTL_CHILDREN(oid);
7020
7021         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7022             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7023             sysctl_linkdnrc, "A", "reason why link is down");
7024         if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7025                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7026                     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7027                     sysctl_btphy, "I", "PHY temperature (in Celsius)");
7028                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7029                     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7030                     sysctl_btphy, "I", "PHY firmware version");
7031         }
7032
7033         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7034             CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7035             sysctl_pause_settings, "A",
7036             "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7037         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
7038             CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7039             sysctl_fec, "A",
7040             "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7041         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7042             CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7043             "FEC recommended by the cable/transceiver");
7044         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7045             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7046             sysctl_autoneg, "I",
7047             "autonegotiation (-1 = not supported)");
7048
7049         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7050             &pi->link_cfg.pcaps, 0, "port capabilities");
7051         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7052             &pi->link_cfg.acaps, 0, "advertised capabilities");
7053         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7054             &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7055
7056         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7057             port_top_speed(pi), "max speed (in Gbps)");
7058         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7059             pi->mps_bg_map, "MPS buffer group map");
7060         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7061             NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7062
7063         if (sc->flags & IS_VF)
7064                 return;
7065
7066         /*
7067          * dev.(cxgbe|cxl).X.tc.
7068          */
7069         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7070             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7071             "Tx scheduler traffic classes (cl_rl)");
7072         children2 = SYSCTL_CHILDREN(oid);
7073         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7074             CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7075             "pktsize for per-flow cl-rl (0 means up to the driver )");
7076         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7077             CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7078             "burstsize for per-flow cl-rl (0 means up to the driver)");
7079         for (i = 0; i < sc->chip_params->nsched_cls; i++) {
7080                 struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7081
7082                 snprintf(name, sizeof(name), "%d", i);
7083                 children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7084                     SYSCTL_CHILDREN(oid), OID_AUTO, name,
7085                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7086                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7087                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7088                     (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7089                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7090                     CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7091                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7092                     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7093                     (pi->port_id << 16) | i, sysctl_tc_params, "A",
7094                     "traffic class parameters");
7095         }
7096
7097         /*
7098          * dev.cxgbe.X.stats.
7099          */
7100         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
7101             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
7102         children = SYSCTL_CHILDREN(oid);
7103         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
7104             &pi->tx_parse_error, 0,
7105             "# of tx packets with invalid length or # of segments");
7106
7107 #define T4_REGSTAT(name, stat, desc) \
7108     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
7109         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
7110         (is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
7111         T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
7112         sysctl_handle_t4_reg64, "QU", desc)
7113
7114 /* We get these from port_stats and they may be stale by up to 1s */
7115 #define T4_PORTSTAT(name, desc) \
7116         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
7117             &pi->stats.name, desc)
7118
7119         T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
7120         T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
7121         T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
7122         T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
7123         T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
7124         T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
7125         T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
7126         T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
7127         T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
7128         T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
7129         T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
7130         T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
7131         T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
7132         T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
7133         T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
7134         T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
7135         T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
7136         T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
7137         T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
7138         T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
7139         T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
7140         T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
7141         T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
7142
7143         T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
7144         T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
7145         T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
7146         T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
7147         T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
7148         T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
7149         T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
7150         if (is_t6(sc)) {
7151                 T4_PORTSTAT(rx_fcs_err,
7152                     "# of frames received with bad FCS since last link up");
7153         } else {
7154                 T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
7155                     "# of frames received with bad FCS");
7156         }
7157         T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
7158         T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
7159         T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
7160         T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
7161         T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
7162         T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
7163         T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
7164         T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
7165         T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
7166         T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
7167         T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
7168         T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
7169         T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
7170         T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
7171         T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
7172         T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
7173         T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
7174         T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
7175         T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
7176
7177         T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
7178         T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
7179         T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
7180         T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
7181         T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
7182         T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
7183         T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
7184         T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
7185
7186 #undef T4_REGSTAT
7187 #undef T4_PORTSTAT
7188
7189         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_toe_tls_records",
7190             CTLFLAG_RD, &pi->tx_toe_tls_records,
7191             "# of TOE TLS records transmitted");
7192         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_toe_tls_octets",
7193             CTLFLAG_RD, &pi->tx_toe_tls_octets,
7194             "# of payload octets in transmitted TOE TLS records");
7195         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_toe_tls_records",
7196             CTLFLAG_RD, &pi->rx_toe_tls_records,
7197             "# of TOE TLS records received");
7198         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_toe_tls_octets",
7199             CTLFLAG_RD, &pi->rx_toe_tls_octets,
7200             "# of payload octets in received TOE TLS records");
7201 }
7202
7203 static int
7204 sysctl_int_array(SYSCTL_HANDLER_ARGS)
7205 {
7206         int rc, *i, space = 0;
7207         struct sbuf sb;
7208
7209         sbuf_new_for_sysctl(&sb, NULL, 64, req);
7210         for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
7211                 if (space)
7212                         sbuf_printf(&sb, " ");
7213                 sbuf_printf(&sb, "%d", *i);
7214                 space = 1;
7215         }
7216         rc = sbuf_finish(&sb);
7217         sbuf_delete(&sb);
7218         return (rc);
7219 }
7220
7221 static int
7222 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
7223 {
7224         int rc;
7225         struct sbuf *sb;
7226
7227         rc = sysctl_wire_old_buffer(req, 0);
7228         if (rc != 0)
7229                 return(rc);
7230
7231         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7232         if (sb == NULL)
7233                 return (ENOMEM);
7234
7235         sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7236         rc = sbuf_finish(sb);
7237         sbuf_delete(sb);
7238
7239         return (rc);
7240 }
7241
7242 static int
7243 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7244 {
7245         int rc;
7246         struct sbuf *sb;
7247
7248         rc = sysctl_wire_old_buffer(req, 0);
7249         if (rc != 0)
7250                 return(rc);
7251
7252         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7253         if (sb == NULL)
7254                 return (ENOMEM);
7255
7256         sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
7257         rc = sbuf_finish(sb);
7258         sbuf_delete(sb);
7259
7260         return (rc);
7261 }
7262
7263 static int
7264 sysctl_btphy(SYSCTL_HANDLER_ARGS)
7265 {
7266         struct port_info *pi = arg1;
7267         int op = arg2;
7268         struct adapter *sc = pi->adapter;
7269         u_int v;
7270         int rc;
7271
7272         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
7273         if (rc)
7274                 return (rc);
7275         /* XXX: magic numbers */
7276         rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
7277             &v);
7278         end_synchronized_op(sc, 0);
7279         if (rc)
7280                 return (rc);
7281         if (op == 0)
7282                 v /= 256;
7283
7284         rc = sysctl_handle_int(oidp, &v, 0, req);
7285         return (rc);
7286 }
7287
7288 static int
7289 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
7290 {
7291         struct vi_info *vi = arg1;
7292         int rc, val;
7293
7294         val = vi->rsrv_noflowq;
7295         rc = sysctl_handle_int(oidp, &val, 0, req);
7296         if (rc != 0 || req->newptr == NULL)
7297                 return (rc);
7298
7299         if ((val >= 1) && (vi->ntxq > 1))
7300                 vi->rsrv_noflowq = 1;
7301         else
7302                 vi->rsrv_noflowq = 0;
7303
7304         return (rc);
7305 }
7306
7307 static int
7308 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
7309 {
7310         struct vi_info *vi = arg1;
7311         struct adapter *sc = vi->adapter;
7312         int rc, val, i;
7313
7314         MPASS(!(sc->flags & IS_VF));
7315
7316         val = vi->flags & TX_USES_VM_WR ? 1 : 0;
7317         rc = sysctl_handle_int(oidp, &val, 0, req);
7318         if (rc != 0 || req->newptr == NULL)
7319                 return (rc);
7320
7321         if (val != 0 && val != 1)
7322                 return (EINVAL);
7323
7324         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7325             "t4txvm");
7326         if (rc)
7327                 return (rc);
7328         if (vi->ifp->if_drv_flags & IFF_DRV_RUNNING) {
7329                 /*
7330                  * We don't want parse_pkt to run with one setting (VF or PF)
7331                  * and then eth_tx to see a different setting but still use
7332                  * stale information calculated by parse_pkt.
7333                  */
7334                 rc = EBUSY;
7335         } else {
7336                 struct port_info *pi = vi->pi;
7337                 struct sge_txq *txq;
7338                 uint32_t ctrl0;
7339                 uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
7340
7341                 if (val) {
7342                         vi->flags |= TX_USES_VM_WR;
7343                         vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_VM_TSO;
7344                         ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
7345                             V_TXPKT_INTF(pi->tx_chan));
7346                         if (!(sc->flags & IS_VF))
7347                                 npkt--;
7348                 } else {
7349                         vi->flags &= ~TX_USES_VM_WR;
7350                         vi->ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
7351                         ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
7352                             V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
7353                             V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
7354                 }
7355                 for_each_txq(vi, i, txq) {
7356                         txq->cpl_ctrl0 = ctrl0;
7357                         txq->txp.max_npkt = npkt;
7358                 }
7359         }
7360         end_synchronized_op(sc, LOCK_HELD);
7361         return (rc);
7362 }
7363
7364 static int
7365 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
7366 {
7367         struct vi_info *vi = arg1;
7368         struct adapter *sc = vi->adapter;
7369         int idx, rc, i;
7370         struct sge_rxq *rxq;
7371         uint8_t v;
7372
7373         idx = vi->tmr_idx;
7374
7375         rc = sysctl_handle_int(oidp, &idx, 0, req);
7376         if (rc != 0 || req->newptr == NULL)
7377                 return (rc);
7378
7379         if (idx < 0 || idx >= SGE_NTIMERS)
7380                 return (EINVAL);
7381
7382         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7383             "t4tmr");
7384         if (rc)
7385                 return (rc);
7386
7387         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
7388         for_each_rxq(vi, i, rxq) {
7389 #ifdef atomic_store_rel_8
7390                 atomic_store_rel_8(&rxq->iq.intr_params, v);
7391 #else
7392                 rxq->iq.intr_params = v;
7393 #endif
7394         }
7395         vi->tmr_idx = idx;
7396
7397         end_synchronized_op(sc, LOCK_HELD);
7398         return (0);
7399 }
7400
7401 static int
7402 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
7403 {
7404         struct vi_info *vi = arg1;
7405         struct adapter *sc = vi->adapter;
7406         int idx, rc;
7407
7408         idx = vi->pktc_idx;
7409
7410         rc = sysctl_handle_int(oidp, &idx, 0, req);
7411         if (rc != 0 || req->newptr == NULL)
7412                 return (rc);
7413
7414         if (idx < -1 || idx >= SGE_NCOUNTERS)
7415                 return (EINVAL);
7416
7417         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7418             "t4pktc");
7419         if (rc)
7420                 return (rc);
7421
7422         if (vi->flags & VI_INIT_DONE)
7423                 rc = EBUSY; /* cannot be changed once the queues are created */
7424         else
7425                 vi->pktc_idx = idx;
7426
7427         end_synchronized_op(sc, LOCK_HELD);
7428         return (rc);
7429 }
7430
7431 static int
7432 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
7433 {
7434         struct vi_info *vi = arg1;
7435         struct adapter *sc = vi->adapter;
7436         int qsize, rc;
7437
7438         qsize = vi->qsize_rxq;
7439
7440         rc = sysctl_handle_int(oidp, &qsize, 0, req);
7441         if (rc != 0 || req->newptr == NULL)
7442                 return (rc);
7443
7444         if (qsize < 128 || (qsize & 7))
7445                 return (EINVAL);
7446
7447         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7448             "t4rxqs");
7449         if (rc)
7450                 return (rc);
7451
7452         if (vi->flags & VI_INIT_DONE)
7453                 rc = EBUSY; /* cannot be changed once the queues are created */
7454         else
7455                 vi->qsize_rxq = qsize;
7456
7457         end_synchronized_op(sc, LOCK_HELD);
7458         return (rc);
7459 }
7460
7461 static int
7462 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
7463 {
7464         struct vi_info *vi = arg1;
7465         struct adapter *sc = vi->adapter;
7466         int qsize, rc;
7467
7468         qsize = vi->qsize_txq;
7469
7470         rc = sysctl_handle_int(oidp, &qsize, 0, req);
7471         if (rc != 0 || req->newptr == NULL)
7472                 return (rc);
7473
7474         if (qsize < 128 || qsize > 65536)
7475                 return (EINVAL);
7476
7477         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7478             "t4txqs");
7479         if (rc)
7480                 return (rc);
7481
7482         if (vi->flags & VI_INIT_DONE)
7483                 rc = EBUSY; /* cannot be changed once the queues are created */
7484         else
7485                 vi->qsize_txq = qsize;
7486
7487         end_synchronized_op(sc, LOCK_HELD);
7488         return (rc);
7489 }
7490
7491 static int
7492 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
7493 {
7494         struct port_info *pi = arg1;
7495         struct adapter *sc = pi->adapter;
7496         struct link_config *lc = &pi->link_cfg;
7497         int rc;
7498
7499         if (req->newptr == NULL) {
7500                 struct sbuf *sb;
7501                 static char *bits = "\20\1RX\2TX\3AUTO";
7502
7503                 rc = sysctl_wire_old_buffer(req, 0);
7504                 if (rc != 0)
7505                         return(rc);
7506
7507                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7508                 if (sb == NULL)
7509                         return (ENOMEM);
7510
7511                 if (lc->link_ok) {
7512                         sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
7513                             (lc->requested_fc & PAUSE_AUTONEG), bits);
7514                 } else {
7515                         sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
7516                             PAUSE_RX | PAUSE_AUTONEG), bits);
7517                 }
7518                 rc = sbuf_finish(sb);
7519                 sbuf_delete(sb);
7520         } else {
7521                 char s[2];
7522                 int n;
7523
7524                 s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
7525                     PAUSE_AUTONEG));
7526                 s[1] = 0;
7527
7528                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
7529                 if (rc != 0)
7530                         return(rc);
7531
7532                 if (s[1] != 0)
7533                         return (EINVAL);
7534                 if (s[0] < '0' || s[0] > '9')
7535                         return (EINVAL);        /* not a number */
7536                 n = s[0] - '0';
7537                 if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
7538                         return (EINVAL);        /* some other bit is set too */
7539
7540                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7541                     "t4PAUSE");
7542                 if (rc)
7543                         return (rc);
7544                 PORT_LOCK(pi);
7545                 lc->requested_fc = n;
7546                 fixup_link_config(pi);
7547                 if (pi->up_vis > 0)
7548                         rc = apply_link_config(pi);
7549                 set_current_media(pi);
7550                 PORT_UNLOCK(pi);
7551                 end_synchronized_op(sc, 0);
7552         }
7553
7554         return (rc);
7555 }
7556
7557 static int
7558 sysctl_fec(SYSCTL_HANDLER_ARGS)
7559 {
7560         struct port_info *pi = arg1;
7561         struct adapter *sc = pi->adapter;
7562         struct link_config *lc = &pi->link_cfg;
7563         int rc;
7564         int8_t old;
7565
7566         if (req->newptr == NULL) {
7567                 struct sbuf *sb;
7568                 static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
7569                     "\5RSVD3\6auto\7module";
7570
7571                 rc = sysctl_wire_old_buffer(req, 0);
7572                 if (rc != 0)
7573                         return(rc);
7574
7575                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7576                 if (sb == NULL)
7577                         return (ENOMEM);
7578
7579                 /*
7580                  * Display the requested_fec when the link is down -- the actual
7581                  * FEC makes sense only when the link is up.
7582                  */
7583                 if (lc->link_ok) {
7584                         sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
7585                             (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
7586                             bits);
7587                 } else {
7588                         sbuf_printf(sb, "%b", lc->requested_fec, bits);
7589                 }
7590                 rc = sbuf_finish(sb);
7591                 sbuf_delete(sb);
7592         } else {
7593                 char s[8];
7594                 int n;
7595
7596                 snprintf(s, sizeof(s), "%d",
7597                     lc->requested_fec == FEC_AUTO ? -1 :
7598                     lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
7599
7600                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
7601                 if (rc != 0)
7602                         return(rc);
7603
7604                 n = strtol(&s[0], NULL, 0);
7605                 if (n < 0 || n & FEC_AUTO)
7606                         n = FEC_AUTO;
7607                 else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
7608                         return (EINVAL);/* some other bit is set too */
7609
7610                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7611                     "t4fec");
7612                 if (rc)
7613                         return (rc);
7614                 PORT_LOCK(pi);
7615                 old = lc->requested_fec;
7616                 if (n == FEC_AUTO)
7617                         lc->requested_fec = FEC_AUTO;
7618                 else if (n == 0 || n == FEC_NONE)
7619                         lc->requested_fec = FEC_NONE;
7620                 else {
7621                         if ((lc->pcaps |
7622                             V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
7623                             lc->pcaps) {
7624                                 rc = ENOTSUP;
7625                                 goto done;
7626                         }
7627                         lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
7628                             FEC_MODULE);
7629                 }
7630                 fixup_link_config(pi);
7631                 if (pi->up_vis > 0) {
7632                         rc = apply_link_config(pi);
7633                         if (rc != 0) {
7634                                 lc->requested_fec = old;
7635                                 if (rc == FW_EPROTO)
7636                                         rc = ENOTSUP;
7637                         }
7638                 }
7639 done:
7640                 PORT_UNLOCK(pi);
7641                 end_synchronized_op(sc, 0);
7642         }
7643
7644         return (rc);
7645 }
7646
7647 static int
7648 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
7649 {
7650         struct port_info *pi = arg1;
7651         struct adapter *sc = pi->adapter;
7652         struct link_config *lc = &pi->link_cfg;
7653         int rc;
7654         int8_t fec;
7655         struct sbuf *sb;
7656         static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
7657
7658         rc = sysctl_wire_old_buffer(req, 0);
7659         if (rc != 0)
7660                 return (rc);
7661
7662         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7663         if (sb == NULL)
7664                 return (ENOMEM);
7665
7666         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0)
7667                 return (EBUSY);
7668         PORT_LOCK(pi);
7669         if (pi->up_vis == 0) {
7670                 /*
7671                  * If all the interfaces are administratively down the firmware
7672                  * does not report transceiver changes.  Refresh port info here.
7673                  * This is the only reason we have a synchronized op in this
7674                  * function.  Just PORT_LOCK would have been enough otherwise.
7675                  */
7676                 t4_update_port_info(pi);
7677         }
7678
7679         fec = lc->fec_hint;
7680         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
7681             !fec_supported(lc->pcaps)) {
7682                 sbuf_printf(sb, "n/a");
7683         } else {
7684                 if (fec == 0)
7685                         fec = FEC_NONE;
7686                 sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
7687         }
7688         rc = sbuf_finish(sb);
7689         sbuf_delete(sb);
7690
7691         PORT_UNLOCK(pi);
7692         end_synchronized_op(sc, 0);
7693
7694         return (rc);
7695 }
7696
7697 static int
7698 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
7699 {
7700         struct port_info *pi = arg1;
7701         struct adapter *sc = pi->adapter;
7702         struct link_config *lc = &pi->link_cfg;
7703         int rc, val;
7704
7705         if (lc->pcaps & FW_PORT_CAP32_ANEG)
7706                 val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
7707         else
7708                 val = -1;
7709         rc = sysctl_handle_int(oidp, &val, 0, req);
7710         if (rc != 0 || req->newptr == NULL)
7711                 return (rc);
7712         if (val == 0)
7713                 val = AUTONEG_DISABLE;
7714         else if (val == 1)
7715                 val = AUTONEG_ENABLE;
7716         else
7717                 val = AUTONEG_AUTO;
7718
7719         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7720             "t4aneg");
7721         if (rc)
7722                 return (rc);
7723         PORT_LOCK(pi);
7724         if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
7725                 rc = ENOTSUP;
7726                 goto done;
7727         }
7728         lc->requested_aneg = val;
7729         fixup_link_config(pi);
7730         if (pi->up_vis > 0)
7731                 rc = apply_link_config(pi);
7732         set_current_media(pi);
7733 done:
7734         PORT_UNLOCK(pi);
7735         end_synchronized_op(sc, 0);
7736         return (rc);
7737 }
7738
7739 static int
7740 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
7741 {
7742         struct adapter *sc = arg1;
7743         int reg = arg2;
7744         uint64_t val;
7745
7746         val = t4_read_reg64(sc, reg);
7747
7748         return (sysctl_handle_64(oidp, &val, 0, req));
7749 }
7750
7751 static int
7752 sysctl_temperature(SYSCTL_HANDLER_ARGS)
7753 {
7754         struct adapter *sc = arg1;
7755         int rc, t;
7756         uint32_t param, val;
7757
7758         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
7759         if (rc)
7760                 return (rc);
7761         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7762             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7763             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
7764         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7765         end_synchronized_op(sc, 0);
7766         if (rc)
7767                 return (rc);
7768
7769         /* unknown is returned as 0 but we display -1 in that case */
7770         t = val == 0 ? -1 : val;
7771
7772         rc = sysctl_handle_int(oidp, &t, 0, req);
7773         return (rc);
7774 }
7775
7776 static int
7777 sysctl_vdd(SYSCTL_HANDLER_ARGS)
7778 {
7779         struct adapter *sc = arg1;
7780         int rc;
7781         uint32_t param, val;
7782
7783         if (sc->params.core_vdd == 0) {
7784                 rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
7785                     "t4vdd");
7786                 if (rc)
7787                         return (rc);
7788                 param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7789                     V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7790                     V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
7791                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7792                 end_synchronized_op(sc, 0);
7793                 if (rc)
7794                         return (rc);
7795                 sc->params.core_vdd = val;
7796         }
7797
7798         return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
7799 }
7800
7801 static int
7802 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
7803 {
7804         struct adapter *sc = arg1;
7805         int rc, v;
7806         uint32_t param, val;
7807
7808         v = sc->sensor_resets;
7809         rc = sysctl_handle_int(oidp, &v, 0, req);
7810         if (rc != 0 || req->newptr == NULL || v <= 0)
7811                 return (rc);
7812
7813         if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
7814             chip_id(sc) < CHELSIO_T5)
7815                 return (ENOTSUP);
7816
7817         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
7818         if (rc)
7819                 return (rc);
7820         param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7821             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7822             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
7823         val = 1;
7824         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7825         end_synchronized_op(sc, 0);
7826         if (rc == 0)
7827                 sc->sensor_resets++;
7828         return (rc);
7829 }
7830
7831 static int
7832 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
7833 {
7834         struct adapter *sc = arg1;
7835         struct sbuf *sb;
7836         int rc;
7837         uint32_t param, val;
7838
7839         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
7840         if (rc)
7841                 return (rc);
7842         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7843             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
7844         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7845         end_synchronized_op(sc, 0);
7846         if (rc)
7847                 return (rc);
7848
7849         rc = sysctl_wire_old_buffer(req, 0);
7850         if (rc != 0)
7851                 return (rc);
7852
7853         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7854         if (sb == NULL)
7855                 return (ENOMEM);
7856
7857         if (val == 0xffffffff) {
7858                 /* Only debug and custom firmwares report load averages. */
7859                 sbuf_printf(sb, "not available");
7860         } else {
7861                 sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
7862                     (val >> 16) & 0xff);
7863         }
7864         rc = sbuf_finish(sb);
7865         sbuf_delete(sb);
7866
7867         return (rc);
7868 }
7869
7870 static int
7871 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
7872 {
7873         struct adapter *sc = arg1;
7874         struct sbuf *sb;
7875         int rc, i;
7876         uint16_t incr[NMTUS][NCCTRL_WIN];
7877         static const char *dec_fac[] = {
7878                 "0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
7879                 "0.9375"
7880         };
7881
7882         rc = sysctl_wire_old_buffer(req, 0);
7883         if (rc != 0)
7884                 return (rc);
7885
7886         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7887         if (sb == NULL)
7888                 return (ENOMEM);
7889
7890         t4_read_cong_tbl(sc, incr);
7891
7892         for (i = 0; i < NCCTRL_WIN; ++i) {
7893                 sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
7894                     incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
7895                     incr[5][i], incr[6][i], incr[7][i]);
7896                 sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
7897                     incr[8][i], incr[9][i], incr[10][i], incr[11][i],
7898                     incr[12][i], incr[13][i], incr[14][i], incr[15][i],
7899                     sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
7900         }
7901
7902         rc = sbuf_finish(sb);
7903         sbuf_delete(sb);
7904
7905         return (rc);
7906 }
7907
7908 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
7909         "TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",   /* ibq's */
7910         "ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", /* obq's */
7911         "SGE0-RX", "SGE1-RX"    /* additional obq's (T5 onwards) */
7912 };
7913
7914 static int
7915 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
7916 {
7917         struct adapter *sc = arg1;
7918         struct sbuf *sb;
7919         int rc, i, n, qid = arg2;
7920         uint32_t *buf, *p;
7921         char *qtype;
7922         u_int cim_num_obq = sc->chip_params->cim_num_obq;
7923
7924         KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
7925             ("%s: bad qid %d\n", __func__, qid));
7926
7927         if (qid < CIM_NUM_IBQ) {
7928                 /* inbound queue */
7929                 qtype = "IBQ";
7930                 n = 4 * CIM_IBQ_SIZE;
7931                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7932                 rc = t4_read_cim_ibq(sc, qid, buf, n);
7933         } else {
7934                 /* outbound queue */
7935                 qtype = "OBQ";
7936                 qid -= CIM_NUM_IBQ;
7937                 n = 4 * cim_num_obq * CIM_OBQ_SIZE;
7938                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7939                 rc = t4_read_cim_obq(sc, qid, buf, n);
7940         }
7941
7942         if (rc < 0) {
7943                 rc = -rc;
7944                 goto done;
7945         }
7946         n = rc * sizeof(uint32_t);      /* rc has # of words actually read */
7947
7948         rc = sysctl_wire_old_buffer(req, 0);
7949         if (rc != 0)
7950                 goto done;
7951
7952         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7953         if (sb == NULL) {
7954                 rc = ENOMEM;
7955                 goto done;
7956         }
7957
7958         sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
7959         for (i = 0, p = buf; i < n; i += 16, p += 4)
7960                 sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
7961                     p[2], p[3]);
7962
7963         rc = sbuf_finish(sb);
7964         sbuf_delete(sb);
7965 done:
7966         free(buf, M_CXGBE);
7967         return (rc);
7968 }
7969
7970 static void
7971 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
7972 {
7973         uint32_t *p;
7974
7975         sbuf_printf(sb, "Status   Data      PC%s",
7976             cfg & F_UPDBGLACAPTPCONLY ? "" :
7977             "     LS0Stat  LS0Addr             LS0Data");
7978
7979         for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
7980                 if (cfg & F_UPDBGLACAPTPCONLY) {
7981                         sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
7982                             p[6], p[7]);
7983                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
7984                             (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
7985                             p[4] & 0xff, p[5] >> 8);
7986                         sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
7987                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7988                             p[1] & 0xf, p[2] >> 4);
7989                 } else {
7990                         sbuf_printf(sb,
7991                             "\n  %02x   %x%07x %x%07x %08x %08x "
7992                             "%08x%08x%08x%08x",
7993                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7994                             p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
7995                             p[6], p[7]);
7996                 }
7997         }
7998 }
7999
8000 static void
8001 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8002 {
8003         uint32_t *p;
8004
8005         sbuf_printf(sb, "Status   Inst    Data      PC%s",
8006             cfg & F_UPDBGLACAPTPCONLY ? "" :
8007             "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8008
8009         for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
8010                 if (cfg & F_UPDBGLACAPTPCONLY) {
8011                         sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
8012                             p[3] & 0xff, p[2], p[1], p[0]);
8013                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
8014                             (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
8015                             p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
8016                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
8017                             (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
8018                             p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
8019                             p[6] >> 16);
8020                 } else {
8021                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
8022                             "%08x %08x %08x %08x %08x %08x",
8023                             (p[9] >> 16) & 0xff,
8024                             p[9] & 0xffff, p[8] >> 16,
8025                             p[8] & 0xffff, p[7] >> 16,
8026                             p[7] & 0xffff, p[6] >> 16,
8027                             p[2], p[1], p[0], p[5], p[4], p[3]);
8028                 }
8029         }
8030 }
8031
8032 static int
8033 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
8034 {
8035         uint32_t cfg, *buf;
8036         int rc;
8037
8038         rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
8039         if (rc != 0)
8040                 return (rc);
8041
8042         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8043         buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
8044             M_ZERO | flags);
8045         if (buf == NULL)
8046                 return (ENOMEM);
8047
8048         rc = -t4_cim_read_la(sc, buf, NULL);
8049         if (rc != 0)
8050                 goto done;
8051         if (chip_id(sc) < CHELSIO_T6)
8052                 sbuf_cim_la4(sc, sb, buf, cfg);
8053         else
8054                 sbuf_cim_la6(sc, sb, buf, cfg);
8055
8056 done:
8057         free(buf, M_CXGBE);
8058         return (rc);
8059 }
8060
8061 static int
8062 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
8063 {
8064         struct adapter *sc = arg1;
8065         struct sbuf *sb;
8066         int rc;
8067
8068         rc = sysctl_wire_old_buffer(req, 0);
8069         if (rc != 0)
8070                 return (rc);
8071         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8072         if (sb == NULL)
8073                 return (ENOMEM);
8074
8075         rc = sbuf_cim_la(sc, sb, M_WAITOK);
8076         if (rc == 0)
8077                 rc = sbuf_finish(sb);
8078         sbuf_delete(sb);
8079         return (rc);
8080 }
8081
8082 bool
8083 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
8084 {
8085         struct sbuf sb;
8086         int rc;
8087
8088         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8089                 return (false);
8090         rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
8091         if (rc == 0) {
8092                 rc = sbuf_finish(&sb);
8093                 if (rc == 0) {
8094                         log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
8095                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
8096                 }
8097         }
8098         sbuf_delete(&sb);
8099         return (false);
8100 }
8101
8102 static int
8103 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
8104 {
8105         struct adapter *sc = arg1;
8106         u_int i;
8107         struct sbuf *sb;
8108         uint32_t *buf, *p;
8109         int rc;
8110
8111         rc = sysctl_wire_old_buffer(req, 0);
8112         if (rc != 0)
8113                 return (rc);
8114
8115         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8116         if (sb == NULL)
8117                 return (ENOMEM);
8118
8119         buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
8120             M_ZERO | M_WAITOK);
8121
8122         t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
8123         p = buf;
8124
8125         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8126                 sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
8127                     p[1], p[0]);
8128         }
8129
8130         sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
8131         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
8132                 sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
8133                     (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
8134                     (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
8135                     (p[1] >> 2) | ((p[2] & 3) << 30),
8136                     (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
8137                     p[0] & 1);
8138         }
8139
8140         rc = sbuf_finish(sb);
8141         sbuf_delete(sb);
8142         free(buf, M_CXGBE);
8143         return (rc);
8144 }
8145
8146 static int
8147 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
8148 {
8149         struct adapter *sc = arg1;
8150         u_int i;
8151         struct sbuf *sb;
8152         uint32_t *buf, *p;
8153         int rc;
8154
8155         rc = sysctl_wire_old_buffer(req, 0);
8156         if (rc != 0)
8157                 return (rc);
8158
8159         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8160         if (sb == NULL)
8161                 return (ENOMEM);
8162
8163         buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
8164             M_ZERO | M_WAITOK);
8165
8166         t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
8167         p = buf;
8168
8169         sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
8170         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
8171                 sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
8172                     (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
8173                     p[4], p[3], p[2], p[1], p[0]);
8174         }
8175
8176         sbuf_printf(sb, "\n\nCntl ID               Data");
8177         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
8178                 sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
8179                     (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
8180         }
8181
8182         rc = sbuf_finish(sb);
8183         sbuf_delete(sb);
8184         free(buf, M_CXGBE);
8185         return (rc);
8186 }
8187
8188 static int
8189 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
8190 {
8191         struct adapter *sc = arg1;
8192         struct sbuf *sb;
8193         int rc, i;
8194         uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
8195         uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
8196         uint16_t thres[CIM_NUM_IBQ];
8197         uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
8198         uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
8199         u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
8200
8201         cim_num_obq = sc->chip_params->cim_num_obq;
8202         if (is_t4(sc)) {
8203                 ibq_rdaddr = A_UP_IBQ_0_RDADDR;
8204                 obq_rdaddr = A_UP_OBQ_0_REALADDR;
8205         } else {
8206                 ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
8207                 obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
8208         }
8209         nq = CIM_NUM_IBQ + cim_num_obq;
8210
8211         rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
8212         if (rc == 0)
8213                 rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
8214         if (rc != 0)
8215                 return (rc);
8216
8217         t4_read_cimq_cfg(sc, base, size, thres);
8218
8219         rc = sysctl_wire_old_buffer(req, 0);
8220         if (rc != 0)
8221                 return (rc);
8222
8223         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8224         if (sb == NULL)
8225                 return (ENOMEM);
8226
8227         sbuf_printf(sb,
8228             "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
8229
8230         for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
8231                 sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
8232                     qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
8233                     G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
8234                     G_QUEREMFLITS(p[2]) * 16);
8235         for ( ; i < nq; i++, p += 4, wr += 2)
8236                 sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
8237                     base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
8238                     wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
8239                     G_QUEREMFLITS(p[2]) * 16);
8240
8241         rc = sbuf_finish(sb);
8242         sbuf_delete(sb);
8243
8244         return (rc);
8245 }
8246
8247 static int
8248 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
8249 {
8250         struct adapter *sc = arg1;
8251         struct sbuf *sb;
8252         int rc;
8253         struct tp_cpl_stats stats;
8254
8255         rc = sysctl_wire_old_buffer(req, 0);
8256         if (rc != 0)
8257                 return (rc);
8258
8259         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8260         if (sb == NULL)
8261                 return (ENOMEM);
8262
8263         mtx_lock(&sc->reg_lock);
8264         t4_tp_get_cpl_stats(sc, &stats, 0);
8265         mtx_unlock(&sc->reg_lock);
8266
8267         if (sc->chip_params->nchan > 2) {
8268                 sbuf_printf(sb, "                 channel 0  channel 1"
8269                     "  channel 2  channel 3");
8270                 sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
8271                     stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
8272                 sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
8273                     stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
8274         } else {
8275                 sbuf_printf(sb, "                 channel 0  channel 1");
8276                 sbuf_printf(sb, "\nCPL requests:   %10u %10u",
8277                     stats.req[0], stats.req[1]);
8278                 sbuf_printf(sb, "\nCPL responses:   %10u %10u",
8279                     stats.rsp[0], stats.rsp[1]);
8280         }
8281
8282         rc = sbuf_finish(sb);
8283         sbuf_delete(sb);
8284
8285         return (rc);
8286 }
8287
8288 static int
8289 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
8290 {
8291         struct adapter *sc = arg1;
8292         struct sbuf *sb;
8293         int rc;
8294         struct tp_usm_stats stats;
8295
8296         rc = sysctl_wire_old_buffer(req, 0);
8297         if (rc != 0)
8298                 return(rc);
8299
8300         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8301         if (sb == NULL)
8302                 return (ENOMEM);
8303
8304         mtx_lock(&sc->reg_lock);
8305         t4_get_usm_stats(sc, &stats, 1);
8306         mtx_unlock(&sc->reg_lock);
8307
8308         sbuf_printf(sb, "Frames: %u\n", stats.frames);
8309         sbuf_printf(sb, "Octets: %ju\n", stats.octets);
8310         sbuf_printf(sb, "Drops:  %u", stats.drops);
8311
8312         rc = sbuf_finish(sb);
8313         sbuf_delete(sb);
8314
8315         return (rc);
8316 }
8317
8318 static int
8319 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
8320 {
8321         struct adapter *sc = arg1;
8322         struct sbuf *sb;
8323         int rc;
8324         struct tp_tid_stats stats;
8325
8326         rc = sysctl_wire_old_buffer(req, 0);
8327         if (rc != 0)
8328                 return(rc);
8329
8330         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8331         if (sb == NULL)
8332                 return (ENOMEM);
8333
8334         mtx_lock(&sc->reg_lock);
8335         t4_tp_get_tid_stats(sc, &stats, 1);
8336         mtx_unlock(&sc->reg_lock);
8337
8338         sbuf_printf(sb, "Delete:     %u\n", stats.del);
8339         sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
8340         sbuf_printf(sb, "Active:     %u\n", stats.act);
8341         sbuf_printf(sb, "Passive:    %u", stats.pas);
8342
8343         rc = sbuf_finish(sb);
8344         sbuf_delete(sb);
8345
8346         return (rc);
8347 }
8348
8349 static const char * const devlog_level_strings[] = {
8350         [FW_DEVLOG_LEVEL_EMERG]         = "EMERG",
8351         [FW_DEVLOG_LEVEL_CRIT]          = "CRIT",
8352         [FW_DEVLOG_LEVEL_ERR]           = "ERR",
8353         [FW_DEVLOG_LEVEL_NOTICE]        = "NOTICE",
8354         [FW_DEVLOG_LEVEL_INFO]          = "INFO",
8355         [FW_DEVLOG_LEVEL_DEBUG]         = "DEBUG"
8356 };
8357
8358 static const char * const devlog_facility_strings[] = {
8359         [FW_DEVLOG_FACILITY_CORE]       = "CORE",
8360         [FW_DEVLOG_FACILITY_CF]         = "CF",
8361         [FW_DEVLOG_FACILITY_SCHED]      = "SCHED",
8362         [FW_DEVLOG_FACILITY_TIMER]      = "TIMER",
8363         [FW_DEVLOG_FACILITY_RES]        = "RES",
8364         [FW_DEVLOG_FACILITY_HW]         = "HW",
8365         [FW_DEVLOG_FACILITY_FLR]        = "FLR",
8366         [FW_DEVLOG_FACILITY_DMAQ]       = "DMAQ",
8367         [FW_DEVLOG_FACILITY_PHY]        = "PHY",
8368         [FW_DEVLOG_FACILITY_MAC]        = "MAC",
8369         [FW_DEVLOG_FACILITY_PORT]       = "PORT",
8370         [FW_DEVLOG_FACILITY_VI]         = "VI",
8371         [FW_DEVLOG_FACILITY_FILTER]     = "FILTER",
8372         [FW_DEVLOG_FACILITY_ACL]        = "ACL",
8373         [FW_DEVLOG_FACILITY_TM]         = "TM",
8374         [FW_DEVLOG_FACILITY_QFC]        = "QFC",
8375         [FW_DEVLOG_FACILITY_DCB]        = "DCB",
8376         [FW_DEVLOG_FACILITY_ETH]        = "ETH",
8377         [FW_DEVLOG_FACILITY_OFLD]       = "OFLD",
8378         [FW_DEVLOG_FACILITY_RI]         = "RI",
8379         [FW_DEVLOG_FACILITY_ISCSI]      = "ISCSI",
8380         [FW_DEVLOG_FACILITY_FCOE]       = "FCOE",
8381         [FW_DEVLOG_FACILITY_FOISCSI]    = "FOISCSI",
8382         [FW_DEVLOG_FACILITY_FOFCOE]     = "FOFCOE",
8383         [FW_DEVLOG_FACILITY_CHNET]      = "CHNET",
8384 };
8385
8386 static int
8387 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
8388 {
8389         int i, j, rc, nentries, first = 0;
8390         struct devlog_params *dparams = &sc->params.devlog;
8391         struct fw_devlog_e *buf, *e;
8392         uint64_t ftstamp = UINT64_MAX;
8393
8394         if (dparams->addr == 0)
8395                 return (ENXIO);
8396
8397         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8398         buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
8399         if (buf == NULL)
8400                 return (ENOMEM);
8401
8402         rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
8403         if (rc != 0)
8404                 goto done;
8405
8406         nentries = dparams->size / sizeof(struct fw_devlog_e);
8407         for (i = 0; i < nentries; i++) {
8408                 e = &buf[i];
8409
8410                 if (e->timestamp == 0)
8411                         break;  /* end */
8412
8413                 e->timestamp = be64toh(e->timestamp);
8414                 e->seqno = be32toh(e->seqno);
8415                 for (j = 0; j < 8; j++)
8416                         e->params[j] = be32toh(e->params[j]);
8417
8418                 if (e->timestamp < ftstamp) {
8419                         ftstamp = e->timestamp;
8420                         first = i;
8421                 }
8422         }
8423
8424         if (buf[first].timestamp == 0)
8425                 goto done;      /* nothing in the log */
8426
8427         sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
8428             "Seq#", "Tstamp", "Level", "Facility", "Message");
8429
8430         i = first;
8431         do {
8432                 e = &buf[i];
8433                 if (e->timestamp == 0)
8434                         break;  /* end */
8435
8436                 sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
8437                     e->seqno, e->timestamp,
8438                     (e->level < nitems(devlog_level_strings) ?
8439                         devlog_level_strings[e->level] : "UNKNOWN"),
8440                     (e->facility < nitems(devlog_facility_strings) ?
8441                         devlog_facility_strings[e->facility] : "UNKNOWN"));
8442                 sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
8443                     e->params[2], e->params[3], e->params[4],
8444                     e->params[5], e->params[6], e->params[7]);
8445
8446                 if (++i == nentries)
8447                         i = 0;
8448         } while (i != first);
8449 done:
8450         free(buf, M_CXGBE);
8451         return (rc);
8452 }
8453
8454 static int
8455 sysctl_devlog(SYSCTL_HANDLER_ARGS)
8456 {
8457         struct adapter *sc = arg1;
8458         int rc;
8459         struct sbuf *sb;
8460
8461         rc = sysctl_wire_old_buffer(req, 0);
8462         if (rc != 0)
8463                 return (rc);
8464         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8465         if (sb == NULL)
8466                 return (ENOMEM);
8467
8468         rc = sbuf_devlog(sc, sb, M_WAITOK);
8469         if (rc == 0)
8470                 rc = sbuf_finish(sb);
8471         sbuf_delete(sb);
8472         return (rc);
8473 }
8474
8475 void
8476 t4_os_dump_devlog(struct adapter *sc)
8477 {
8478         int rc;
8479         struct sbuf sb;
8480
8481         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8482                 return;
8483         rc = sbuf_devlog(sc, &sb, M_NOWAIT);
8484         if (rc == 0) {
8485                 rc = sbuf_finish(&sb);
8486                 if (rc == 0) {
8487                         log(LOG_DEBUG, "%s: device log follows.\n%s",
8488                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
8489                 }
8490         }
8491         sbuf_delete(&sb);
8492 }
8493
8494 static int
8495 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
8496 {
8497         struct adapter *sc = arg1;
8498         struct sbuf *sb;
8499         int rc;
8500         struct tp_fcoe_stats stats[MAX_NCHAN];
8501         int i, nchan = sc->chip_params->nchan;
8502
8503         rc = sysctl_wire_old_buffer(req, 0);
8504         if (rc != 0)
8505                 return (rc);
8506
8507         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8508         if (sb == NULL)
8509                 return (ENOMEM);
8510
8511         mtx_lock(&sc->reg_lock);
8512         for (i = 0; i < nchan; i++)
8513                 t4_get_fcoe_stats(sc, i, &stats[i], 1);
8514         mtx_unlock(&sc->reg_lock);
8515
8516         if (nchan > 2) {
8517                 sbuf_printf(sb, "                   channel 0        channel 1"
8518                     "        channel 2        channel 3");
8519                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
8520                     stats[0].octets_ddp, stats[1].octets_ddp,
8521                     stats[2].octets_ddp, stats[3].octets_ddp);
8522                 sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
8523                     stats[0].frames_ddp, stats[1].frames_ddp,
8524                     stats[2].frames_ddp, stats[3].frames_ddp);
8525                 sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
8526                     stats[0].frames_drop, stats[1].frames_drop,
8527                     stats[2].frames_drop, stats[3].frames_drop);
8528         } else {
8529                 sbuf_printf(sb, "                   channel 0        channel 1");
8530                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
8531                     stats[0].octets_ddp, stats[1].octets_ddp);
8532                 sbuf_printf(sb, "\nframesDDP:  %16u %16u",
8533                     stats[0].frames_ddp, stats[1].frames_ddp);
8534                 sbuf_printf(sb, "\nframesDrop: %16u %16u",
8535                     stats[0].frames_drop, stats[1].frames_drop);
8536         }
8537
8538         rc = sbuf_finish(sb);
8539         sbuf_delete(sb);
8540
8541         return (rc);
8542 }
8543
8544 static int
8545 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
8546 {
8547         struct adapter *sc = arg1;
8548         struct sbuf *sb;
8549         int rc, i;
8550         unsigned int map, kbps, ipg, mode;
8551         unsigned int pace_tab[NTX_SCHED];
8552
8553         rc = sysctl_wire_old_buffer(req, 0);
8554         if (rc != 0)
8555                 return (rc);
8556
8557         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8558         if (sb == NULL)
8559                 return (ENOMEM);
8560
8561         map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
8562         mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
8563         t4_read_pace_tbl(sc, pace_tab);
8564
8565         sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
8566             "Class IPG (0.1 ns)   Flow IPG (us)");
8567
8568         for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
8569                 t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
8570                 sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
8571                     (mode & (1 << i)) ? "flow" : "class", map & 3);
8572                 if (kbps)
8573                         sbuf_printf(sb, "%9u     ", kbps);
8574                 else
8575                         sbuf_printf(sb, " disabled     ");
8576
8577                 if (ipg)
8578                         sbuf_printf(sb, "%13u        ", ipg);
8579                 else
8580                         sbuf_printf(sb, "     disabled        ");
8581
8582                 if (pace_tab[i])
8583                         sbuf_printf(sb, "%10u", pace_tab[i]);
8584                 else
8585                         sbuf_printf(sb, "  disabled");
8586         }
8587
8588         rc = sbuf_finish(sb);
8589         sbuf_delete(sb);
8590
8591         return (rc);
8592 }
8593
8594 static int
8595 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
8596 {
8597         struct adapter *sc = arg1;
8598         struct sbuf *sb;
8599         int rc, i, j;
8600         uint64_t *p0, *p1;
8601         struct lb_port_stats s[2];
8602         static const char *stat_name[] = {
8603                 "OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
8604                 "UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
8605                 "Frames128To255:", "Frames256To511:", "Frames512To1023:",
8606                 "Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
8607                 "BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
8608                 "BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
8609                 "BG2FramesTrunc:", "BG3FramesTrunc:"
8610         };
8611
8612         rc = sysctl_wire_old_buffer(req, 0);
8613         if (rc != 0)
8614                 return (rc);
8615
8616         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8617         if (sb == NULL)
8618                 return (ENOMEM);
8619
8620         memset(s, 0, sizeof(s));
8621
8622         for (i = 0; i < sc->chip_params->nchan; i += 2) {
8623                 t4_get_lb_stats(sc, i, &s[0]);
8624                 t4_get_lb_stats(sc, i + 1, &s[1]);
8625
8626                 p0 = &s[0].octets;
8627                 p1 = &s[1].octets;
8628                 sbuf_printf(sb, "%s                       Loopback %u"
8629                     "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
8630
8631                 for (j = 0; j < nitems(stat_name); j++)
8632                         sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
8633                                    *p0++, *p1++);
8634         }
8635
8636         rc = sbuf_finish(sb);
8637         sbuf_delete(sb);
8638
8639         return (rc);
8640 }
8641
8642 static int
8643 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
8644 {
8645         int rc = 0;
8646         struct port_info *pi = arg1;
8647         struct link_config *lc = &pi->link_cfg;
8648         struct sbuf *sb;
8649
8650         rc = sysctl_wire_old_buffer(req, 0);
8651         if (rc != 0)
8652                 return(rc);
8653         sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
8654         if (sb == NULL)
8655                 return (ENOMEM);
8656
8657         if (lc->link_ok || lc->link_down_rc == 255)
8658                 sbuf_printf(sb, "n/a");
8659         else
8660                 sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
8661
8662         rc = sbuf_finish(sb);
8663         sbuf_delete(sb);
8664
8665         return (rc);
8666 }
8667
8668 struct mem_desc {
8669         unsigned int base;
8670         unsigned int limit;
8671         unsigned int idx;
8672 };
8673
8674 static int
8675 mem_desc_cmp(const void *a, const void *b)
8676 {
8677         return ((const struct mem_desc *)a)->base -
8678                ((const struct mem_desc *)b)->base;
8679 }
8680
8681 static void
8682 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
8683     unsigned int to)
8684 {
8685         unsigned int size;
8686
8687         if (from == to)
8688                 return;
8689
8690         size = to - from + 1;
8691         if (size == 0)
8692                 return;
8693
8694         /* XXX: need humanize_number(3) in libkern for a more readable 'size' */
8695         sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
8696 }
8697
8698 static int
8699 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
8700 {
8701         struct adapter *sc = arg1;
8702         struct sbuf *sb;
8703         int rc, i, n;
8704         uint32_t lo, hi, used, alloc;
8705         static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
8706         static const char *region[] = {
8707                 "DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
8708                 "Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
8709                 "Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
8710                 "TDDP region:", "TPT region:", "STAG region:", "RQ region:",
8711                 "RQUDP region:", "PBL region:", "TXPBL region:",
8712                 "DBVFIFO region:", "ULPRX state:", "ULPTX state:",
8713                 "On-chip queues:", "TLS keys:",
8714         };
8715         struct mem_desc avail[4];
8716         struct mem_desc mem[nitems(region) + 3];        /* up to 3 holes */
8717         struct mem_desc *md = mem;
8718
8719         rc = sysctl_wire_old_buffer(req, 0);
8720         if (rc != 0)
8721                 return (rc);
8722
8723         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8724         if (sb == NULL)
8725                 return (ENOMEM);
8726
8727         for (i = 0; i < nitems(mem); i++) {
8728                 mem[i].limit = 0;
8729                 mem[i].idx = i;
8730         }
8731
8732         /* Find and sort the populated memory ranges */
8733         i = 0;
8734         lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
8735         if (lo & F_EDRAM0_ENABLE) {
8736                 hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
8737                 avail[i].base = G_EDRAM0_BASE(hi) << 20;
8738                 avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
8739                 avail[i].idx = 0;
8740                 i++;
8741         }
8742         if (lo & F_EDRAM1_ENABLE) {
8743                 hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
8744                 avail[i].base = G_EDRAM1_BASE(hi) << 20;
8745                 avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
8746                 avail[i].idx = 1;
8747                 i++;
8748         }
8749         if (lo & F_EXT_MEM_ENABLE) {
8750                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
8751                 avail[i].base = G_EXT_MEM_BASE(hi) << 20;
8752                 avail[i].limit = avail[i].base +
8753                     (G_EXT_MEM_SIZE(hi) << 20);
8754                 avail[i].idx = is_t5(sc) ? 3 : 2;       /* Call it MC0 for T5 */
8755                 i++;
8756         }
8757         if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
8758                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
8759                 avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
8760                 avail[i].limit = avail[i].base +
8761                     (G_EXT_MEM1_SIZE(hi) << 20);
8762                 avail[i].idx = 4;
8763                 i++;
8764         }
8765         if (!i)                                    /* no memory available */
8766                 return 0;
8767         qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
8768
8769         (md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
8770         (md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
8771         (md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
8772         (md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
8773         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
8774         (md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
8775         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
8776         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
8777         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
8778
8779         /* the next few have explicit upper bounds */
8780         md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
8781         md->limit = md->base - 1 +
8782                     t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
8783                     G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
8784         md++;
8785
8786         md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
8787         md->limit = md->base - 1 +
8788                     t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
8789                     G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
8790         md++;
8791
8792         if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
8793                 if (chip_id(sc) <= CHELSIO_T5)
8794                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
8795                 else
8796                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
8797                 md->limit = 0;
8798         } else {
8799                 md->base = 0;
8800                 md->idx = nitems(region);  /* hide it */
8801         }
8802         md++;
8803
8804 #define ulp_region(reg) \
8805         md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
8806         (md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
8807
8808         ulp_region(RX_ISCSI);
8809         ulp_region(RX_TDDP);
8810         ulp_region(TX_TPT);
8811         ulp_region(RX_STAG);
8812         ulp_region(RX_RQ);
8813         ulp_region(RX_RQUDP);
8814         ulp_region(RX_PBL);
8815         ulp_region(TX_PBL);
8816 #undef ulp_region
8817
8818         md->base = 0;
8819         md->idx = nitems(region);
8820         if (!is_t4(sc)) {
8821                 uint32_t size = 0;
8822                 uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
8823                 uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
8824
8825                 if (is_t5(sc)) {
8826                         if (sge_ctrl & F_VFIFO_ENABLE)
8827                                 size = G_DBVFIFO_SIZE(fifo_size);
8828                 } else
8829                         size = G_T6_DBVFIFO_SIZE(fifo_size);
8830
8831                 if (size) {
8832                         md->base = G_BASEADDR(t4_read_reg(sc,
8833                             A_SGE_DBVFIFO_BADDR));
8834                         md->limit = md->base + (size << 2) - 1;
8835                 }
8836         }
8837         md++;
8838
8839         md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
8840         md->limit = 0;
8841         md++;
8842         md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
8843         md->limit = 0;
8844         md++;
8845
8846         md->base = sc->vres.ocq.start;
8847         if (sc->vres.ocq.size)
8848                 md->limit = md->base + sc->vres.ocq.size - 1;
8849         else
8850                 md->idx = nitems(region);  /* hide it */
8851         md++;
8852
8853         md->base = sc->vres.key.start;
8854         if (sc->vres.key.size)
8855                 md->limit = md->base + sc->vres.key.size - 1;
8856         else
8857                 md->idx = nitems(region);  /* hide it */
8858         md++;
8859
8860         /* add any address-space holes, there can be up to 3 */
8861         for (n = 0; n < i - 1; n++)
8862                 if (avail[n].limit < avail[n + 1].base)
8863                         (md++)->base = avail[n].limit;
8864         if (avail[n].limit)
8865                 (md++)->base = avail[n].limit;
8866
8867         n = md - mem;
8868         qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
8869
8870         for (lo = 0; lo < i; lo++)
8871                 mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
8872                                 avail[lo].limit - 1);
8873
8874         sbuf_printf(sb, "\n");
8875         for (i = 0; i < n; i++) {
8876                 if (mem[i].idx >= nitems(region))
8877                         continue;                        /* skip holes */
8878                 if (!mem[i].limit)
8879                         mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
8880                 mem_region_show(sb, region[mem[i].idx], mem[i].base,
8881                                 mem[i].limit);
8882         }
8883
8884         sbuf_printf(sb, "\n");
8885         lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
8886         hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
8887         mem_region_show(sb, "uP RAM:", lo, hi);
8888
8889         lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
8890         hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
8891         mem_region_show(sb, "uP Extmem2:", lo, hi);
8892
8893         lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
8894         sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
8895                    G_PMRXMAXPAGE(lo),
8896                    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
8897                    (lo & F_PMRXNUMCHN) ? 2 : 1);
8898
8899         lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
8900         hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
8901         sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
8902                    G_PMTXMAXPAGE(lo),
8903                    hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
8904                    hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
8905         sbuf_printf(sb, "%u p-structs\n",
8906                    t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
8907
8908         for (i = 0; i < 4; i++) {
8909                 if (chip_id(sc) > CHELSIO_T5)
8910                         lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
8911                 else
8912                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
8913                 if (is_t5(sc)) {
8914                         used = G_T5_USED(lo);
8915                         alloc = G_T5_ALLOC(lo);
8916                 } else {
8917                         used = G_USED(lo);
8918                         alloc = G_ALLOC(lo);
8919                 }
8920                 /* For T6 these are MAC buffer groups */
8921                 sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
8922                     i, used, alloc);
8923         }
8924         for (i = 0; i < sc->chip_params->nchan; i++) {
8925                 if (chip_id(sc) > CHELSIO_T5)
8926                         lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
8927                 else
8928                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
8929                 if (is_t5(sc)) {
8930                         used = G_T5_USED(lo);
8931                         alloc = G_T5_ALLOC(lo);
8932                 } else {
8933                         used = G_USED(lo);
8934                         alloc = G_ALLOC(lo);
8935                 }
8936                 /* For T6 these are MAC buffer groups */
8937                 sbuf_printf(sb,
8938                     "\nLoopback %d using %u pages out of %u allocated",
8939                     i, used, alloc);
8940         }
8941
8942         rc = sbuf_finish(sb);
8943         sbuf_delete(sb);
8944
8945         return (rc);
8946 }
8947
8948 static inline void
8949 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
8950 {
8951         *mask = x | y;
8952         y = htobe64(y);
8953         memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
8954 }
8955
8956 static int
8957 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
8958 {
8959         struct adapter *sc = arg1;
8960         struct sbuf *sb;
8961         int rc, i;
8962
8963         MPASS(chip_id(sc) <= CHELSIO_T5);
8964
8965         rc = sysctl_wire_old_buffer(req, 0);
8966         if (rc != 0)
8967                 return (rc);
8968
8969         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8970         if (sb == NULL)
8971                 return (ENOMEM);
8972
8973         sbuf_printf(sb,
8974             "Idx  Ethernet address     Mask     Vld Ports PF"
8975             "  VF              Replication             P0 P1 P2 P3  ML");
8976         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8977                 uint64_t tcamx, tcamy, mask;
8978                 uint32_t cls_lo, cls_hi;
8979                 uint8_t addr[ETHER_ADDR_LEN];
8980
8981                 tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
8982                 tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
8983                 if (tcamx & tcamy)
8984                         continue;
8985                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
8986                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8987                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8988                 sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
8989                            "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
8990                            addr[3], addr[4], addr[5], (uintmax_t)mask,
8991                            (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
8992                            G_PORTMAP(cls_hi), G_PF(cls_lo),
8993                            (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
8994
8995                 if (cls_lo & F_REPLICATE) {
8996                         struct fw_ldst_cmd ldst_cmd;
8997
8998                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8999                         ldst_cmd.op_to_addrspace =
9000                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9001                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
9002                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9003                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9004                         ldst_cmd.u.mps.rplc.fid_idx =
9005                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9006                                 V_FW_LDST_CMD_IDX(i));
9007
9008                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9009                             "t4mps");
9010                         if (rc)
9011                                 break;
9012                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9013                             sizeof(ldst_cmd), &ldst_cmd);
9014                         end_synchronized_op(sc, 0);
9015
9016                         if (rc != 0) {
9017                                 sbuf_printf(sb, "%36d", rc);
9018                                 rc = 0;
9019                         } else {
9020                                 sbuf_printf(sb, " %08x %08x %08x %08x",
9021                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9022                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9023                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9024                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9025                         }
9026                 } else
9027                         sbuf_printf(sb, "%36s", "");
9028
9029                 sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
9030                     G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
9031                     G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
9032         }
9033
9034         if (rc)
9035                 (void) sbuf_finish(sb);
9036         else
9037                 rc = sbuf_finish(sb);
9038         sbuf_delete(sb);
9039
9040         return (rc);
9041 }
9042
9043 static int
9044 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
9045 {
9046         struct adapter *sc = arg1;
9047         struct sbuf *sb;
9048         int rc, i;
9049
9050         MPASS(chip_id(sc) > CHELSIO_T5);
9051
9052         rc = sysctl_wire_old_buffer(req, 0);
9053         if (rc != 0)
9054                 return (rc);
9055
9056         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9057         if (sb == NULL)
9058                 return (ENOMEM);
9059
9060         sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
9061             "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
9062             "                           Replication"
9063             "                                    P0 P1 P2 P3  ML\n");
9064
9065         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
9066                 uint8_t dip_hit, vlan_vld, lookup_type, port_num;
9067                 uint16_t ivlan;
9068                 uint64_t tcamx, tcamy, val, mask;
9069                 uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
9070                 uint8_t addr[ETHER_ADDR_LEN];
9071
9072                 ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
9073                 if (i < 256)
9074                         ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
9075                 else
9076                         ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
9077                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9078                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9079                 tcamy = G_DMACH(val) << 32;
9080                 tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9081                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9082                 lookup_type = G_DATALKPTYPE(data2);
9083                 port_num = G_DATAPORTNUM(data2);
9084                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
9085                         /* Inner header VNI */
9086                         vniy = ((data2 & F_DATAVIDH2) << 23) |
9087                                        (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9088                         dip_hit = data2 & F_DATADIPHIT;
9089                         vlan_vld = 0;
9090                 } else {
9091                         vniy = 0;
9092                         dip_hit = 0;
9093                         vlan_vld = data2 & F_DATAVIDH2;
9094                         ivlan = G_VIDL(val);
9095                 }
9096
9097                 ctl |= V_CTLXYBITSEL(1);
9098                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
9099                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
9100                 tcamx = G_DMACH(val) << 32;
9101                 tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
9102                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
9103                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
9104                         /* Inner header VNI mask */
9105                         vnix = ((data2 & F_DATAVIDH2) << 23) |
9106                                (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
9107                 } else
9108                         vnix = 0;
9109
9110                 if (tcamx & tcamy)
9111                         continue;
9112                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
9113
9114                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
9115                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
9116
9117                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
9118                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
9119                             "%012jx %06x %06x    -    -   %3c"
9120                             "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
9121                             addr[1], addr[2], addr[3], addr[4], addr[5],
9122                             (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
9123                             port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
9124                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
9125                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
9126                 } else {
9127                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
9128                             "%012jx    -       -   ", i, addr[0], addr[1],
9129                             addr[2], addr[3], addr[4], addr[5],
9130                             (uintmax_t)mask);
9131
9132                         if (vlan_vld)
9133                                 sbuf_printf(sb, "%4u   Y     ", ivlan);
9134                         else
9135                                 sbuf_printf(sb, "  -    N     ");
9136
9137                         sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
9138                             lookup_type ? 'I' : 'O', port_num,
9139                             cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
9140                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
9141                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
9142                 }
9143
9144
9145                 if (cls_lo & F_T6_REPLICATE) {
9146                         struct fw_ldst_cmd ldst_cmd;
9147
9148                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
9149                         ldst_cmd.op_to_addrspace =
9150                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
9151                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
9152                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
9153                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
9154                         ldst_cmd.u.mps.rplc.fid_idx =
9155                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
9156                                 V_FW_LDST_CMD_IDX(i));
9157
9158                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9159                             "t6mps");
9160                         if (rc)
9161                                 break;
9162                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
9163                             sizeof(ldst_cmd), &ldst_cmd);
9164                         end_synchronized_op(sc, 0);
9165
9166                         if (rc != 0) {
9167                                 sbuf_printf(sb, "%72d", rc);
9168                                 rc = 0;
9169                         } else {
9170                                 sbuf_printf(sb, " %08x %08x %08x %08x"
9171                                     " %08x %08x %08x %08x",
9172                                     be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
9173                                     be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
9174                                     be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
9175                                     be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
9176                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
9177                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
9178                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
9179                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
9180                         }
9181                 } else
9182                         sbuf_printf(sb, "%72s", "");
9183
9184                 sbuf_printf(sb, "%4u%3u%3u%3u %#x",
9185                     G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
9186                     G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
9187                     (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
9188         }
9189
9190         if (rc)
9191                 (void) sbuf_finish(sb);
9192         else
9193                 rc = sbuf_finish(sb);
9194         sbuf_delete(sb);
9195
9196         return (rc);
9197 }
9198
9199 static int
9200 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
9201 {
9202         struct adapter *sc = arg1;
9203         struct sbuf *sb;
9204         int rc;
9205         uint16_t mtus[NMTUS];
9206
9207         rc = sysctl_wire_old_buffer(req, 0);
9208         if (rc != 0)
9209                 return (rc);
9210
9211         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9212         if (sb == NULL)
9213                 return (ENOMEM);
9214
9215         t4_read_mtu_tbl(sc, mtus, NULL);
9216
9217         sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
9218             mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
9219             mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
9220             mtus[14], mtus[15]);
9221
9222         rc = sbuf_finish(sb);
9223         sbuf_delete(sb);
9224
9225         return (rc);
9226 }
9227
9228 static int
9229 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
9230 {
9231         struct adapter *sc = arg1;
9232         struct sbuf *sb;
9233         int rc, i;
9234         uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
9235         uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
9236         static const char *tx_stats[MAX_PM_NSTATS] = {
9237                 "Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
9238                 "Tx FIFO wait", NULL, "Tx latency"
9239         };
9240         static const char *rx_stats[MAX_PM_NSTATS] = {
9241                 "Read:", "Write bypass:", "Write mem:", "Flush:",
9242                 "Rx FIFO wait", NULL, "Rx latency"
9243         };
9244
9245         rc = sysctl_wire_old_buffer(req, 0);
9246         if (rc != 0)
9247                 return (rc);
9248
9249         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9250         if (sb == NULL)
9251                 return (ENOMEM);
9252
9253         t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
9254         t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
9255
9256         sbuf_printf(sb, "                Tx pcmds             Tx bytes");
9257         for (i = 0; i < 4; i++) {
9258                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
9259                     tx_cyc[i]);
9260         }
9261
9262         sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
9263         for (i = 0; i < 4; i++) {
9264                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
9265                     rx_cyc[i]);
9266         }
9267
9268         if (chip_id(sc) > CHELSIO_T5) {
9269                 sbuf_printf(sb,
9270                     "\n              Total wait      Total occupancy");
9271                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
9272                     tx_cyc[i]);
9273                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
9274                     rx_cyc[i]);
9275
9276                 i += 2;
9277                 MPASS(i < nitems(tx_stats));
9278
9279                 sbuf_printf(sb,
9280                     "\n                   Reads           Total wait");
9281                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
9282                     tx_cyc[i]);
9283                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
9284                     rx_cyc[i]);
9285         }
9286
9287         rc = sbuf_finish(sb);
9288         sbuf_delete(sb);
9289
9290         return (rc);
9291 }
9292
9293 static int
9294 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
9295 {
9296         struct adapter *sc = arg1;
9297         struct sbuf *sb;
9298         int rc;
9299         struct tp_rdma_stats stats;
9300
9301         rc = sysctl_wire_old_buffer(req, 0);
9302         if (rc != 0)
9303                 return (rc);
9304
9305         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9306         if (sb == NULL)
9307                 return (ENOMEM);
9308
9309         mtx_lock(&sc->reg_lock);
9310         t4_tp_get_rdma_stats(sc, &stats, 0);
9311         mtx_unlock(&sc->reg_lock);
9312
9313         sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
9314         sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
9315
9316         rc = sbuf_finish(sb);
9317         sbuf_delete(sb);
9318
9319         return (rc);
9320 }
9321
9322 static int
9323 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
9324 {
9325         struct adapter *sc = arg1;
9326         struct sbuf *sb;
9327         int rc;
9328         struct tp_tcp_stats v4, v6;
9329
9330         rc = sysctl_wire_old_buffer(req, 0);
9331         if (rc != 0)
9332                 return (rc);
9333
9334         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9335         if (sb == NULL)
9336                 return (ENOMEM);
9337
9338         mtx_lock(&sc->reg_lock);
9339         t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
9340         mtx_unlock(&sc->reg_lock);
9341
9342         sbuf_printf(sb,
9343             "                                IP                 IPv6\n");
9344         sbuf_printf(sb, "OutRsts:      %20u %20u\n",
9345             v4.tcp_out_rsts, v6.tcp_out_rsts);
9346         sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
9347             v4.tcp_in_segs, v6.tcp_in_segs);
9348         sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
9349             v4.tcp_out_segs, v6.tcp_out_segs);
9350         sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
9351             v4.tcp_retrans_segs, v6.tcp_retrans_segs);
9352
9353         rc = sbuf_finish(sb);
9354         sbuf_delete(sb);
9355
9356         return (rc);
9357 }
9358
9359 static int
9360 sysctl_tids(SYSCTL_HANDLER_ARGS)
9361 {
9362         struct adapter *sc = arg1;
9363         struct sbuf *sb;
9364         int rc;
9365         struct tid_info *t = &sc->tids;
9366
9367         rc = sysctl_wire_old_buffer(req, 0);
9368         if (rc != 0)
9369                 return (rc);
9370
9371         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9372         if (sb == NULL)
9373                 return (ENOMEM);
9374
9375         if (t->natids) {
9376                 sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
9377                     t->atids_in_use);
9378         }
9379
9380         if (t->nhpftids) {
9381                 sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
9382                     t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
9383         }
9384
9385         if (t->ntids) {
9386                 sbuf_printf(sb, "TID range: ");
9387                 if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9388                         uint32_t b, hb;
9389
9390                         if (chip_id(sc) <= CHELSIO_T5) {
9391                                 b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
9392                                 hb = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
9393                         } else {
9394                                 b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
9395                                 hb = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
9396                         }
9397
9398                         if (b)
9399                                 sbuf_printf(sb, "%u-%u, ", t->tid_base, b - 1);
9400                         sbuf_printf(sb, "%u-%u", hb, t->ntids - 1);
9401                 } else {
9402                         sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
9403                             t->ntids - 1);
9404                 }
9405                 sbuf_printf(sb, ", in use: %u\n",
9406                     atomic_load_acq_int(&t->tids_in_use));
9407         }
9408
9409         if (t->nstids) {
9410                 sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
9411                     t->stid_base + t->nstids - 1, t->stids_in_use);
9412         }
9413
9414         if (t->nftids) {
9415                 sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
9416                     t->ftid_end, t->ftids_in_use);
9417         }
9418
9419         if (t->netids) {
9420                 sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
9421                     t->etid_base + t->netids - 1, t->etids_in_use);
9422         }
9423
9424         sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
9425             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
9426             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
9427
9428         rc = sbuf_finish(sb);
9429         sbuf_delete(sb);
9430
9431         return (rc);
9432 }
9433
9434 static int
9435 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
9436 {
9437         struct adapter *sc = arg1;
9438         struct sbuf *sb;
9439         int rc;
9440         struct tp_err_stats stats;
9441
9442         rc = sysctl_wire_old_buffer(req, 0);
9443         if (rc != 0)
9444                 return (rc);
9445
9446         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9447         if (sb == NULL)
9448                 return (ENOMEM);
9449
9450         mtx_lock(&sc->reg_lock);
9451         t4_tp_get_err_stats(sc, &stats, 0);
9452         mtx_unlock(&sc->reg_lock);
9453
9454         if (sc->chip_params->nchan > 2) {
9455                 sbuf_printf(sb, "                 channel 0  channel 1"
9456                     "  channel 2  channel 3\n");
9457                 sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
9458                     stats.mac_in_errs[0], stats.mac_in_errs[1],
9459                     stats.mac_in_errs[2], stats.mac_in_errs[3]);
9460                 sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
9461                     stats.hdr_in_errs[0], stats.hdr_in_errs[1],
9462                     stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
9463                 sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
9464                     stats.tcp_in_errs[0], stats.tcp_in_errs[1],
9465                     stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
9466                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
9467                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
9468                     stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
9469                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
9470                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
9471                     stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
9472                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
9473                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
9474                     stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
9475                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
9476                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
9477                     stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
9478                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
9479                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
9480                     stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
9481         } else {
9482                 sbuf_printf(sb, "                 channel 0  channel 1\n");
9483                 sbuf_printf(sb, "macInErrs:      %10u %10u\n",
9484                     stats.mac_in_errs[0], stats.mac_in_errs[1]);
9485                 sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
9486                     stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
9487                 sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
9488                     stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
9489                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
9490                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
9491                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
9492                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
9493                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
9494                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
9495                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
9496                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
9497                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
9498                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
9499         }
9500
9501         sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
9502             stats.ofld_no_neigh, stats.ofld_cong_defer);
9503
9504         rc = sbuf_finish(sb);
9505         sbuf_delete(sb);
9506
9507         return (rc);
9508 }
9509
9510 static int
9511 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
9512 {
9513         struct adapter *sc = arg1;
9514         struct sbuf *sb;
9515         int rc;
9516         struct tp_tnl_stats stats;
9517
9518         rc = sysctl_wire_old_buffer(req, 0);
9519         if (rc != 0)
9520                 return(rc);
9521
9522         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9523         if (sb == NULL)
9524                 return (ENOMEM);
9525
9526         mtx_lock(&sc->reg_lock);
9527         t4_tp_get_tnl_stats(sc, &stats, 1);
9528         mtx_unlock(&sc->reg_lock);
9529
9530         if (sc->chip_params->nchan > 2) {
9531                 sbuf_printf(sb, "           channel 0  channel 1"
9532                     "  channel 2  channel 3\n");
9533                 sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
9534                     stats.out_pkt[0], stats.out_pkt[1],
9535                     stats.out_pkt[2], stats.out_pkt[3]);
9536                 sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
9537                     stats.in_pkt[0], stats.in_pkt[1],
9538                     stats.in_pkt[2], stats.in_pkt[3]);
9539         } else {
9540                 sbuf_printf(sb, "           channel 0  channel 1\n");
9541                 sbuf_printf(sb, "OutPkts:  %10u %10u\n",
9542                     stats.out_pkt[0], stats.out_pkt[1]);
9543                 sbuf_printf(sb, "InPkts:   %10u %10u",
9544                     stats.in_pkt[0], stats.in_pkt[1]);
9545         }
9546
9547         rc = sbuf_finish(sb);
9548         sbuf_delete(sb);
9549
9550         return (rc);
9551 }
9552
9553 static int
9554 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
9555 {
9556         struct adapter *sc = arg1;
9557         struct tp_params *tpp = &sc->params.tp;
9558         u_int mask;
9559         int rc;
9560
9561         mask = tpp->la_mask >> 16;
9562         rc = sysctl_handle_int(oidp, &mask, 0, req);
9563         if (rc != 0 || req->newptr == NULL)
9564                 return (rc);
9565         if (mask > 0xffff)
9566                 return (EINVAL);
9567         tpp->la_mask = mask << 16;
9568         t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
9569
9570         return (0);
9571 }
9572
9573 struct field_desc {
9574         const char *name;
9575         u_int start;
9576         u_int width;
9577 };
9578
9579 static void
9580 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
9581 {
9582         char buf[32];
9583         int line_size = 0;
9584
9585         while (f->name) {
9586                 uint64_t mask = (1ULL << f->width) - 1;
9587                 int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
9588                     ((uintmax_t)v >> f->start) & mask);
9589
9590                 if (line_size + len >= 79) {
9591                         line_size = 8;
9592                         sbuf_printf(sb, "\n        ");
9593                 }
9594                 sbuf_printf(sb, "%s ", buf);
9595                 line_size += len + 1;
9596                 f++;
9597         }
9598         sbuf_printf(sb, "\n");
9599 }
9600
9601 static const struct field_desc tp_la0[] = {
9602         { "RcfOpCodeOut", 60, 4 },
9603         { "State", 56, 4 },
9604         { "WcfState", 52, 4 },
9605         { "RcfOpcSrcOut", 50, 2 },
9606         { "CRxError", 49, 1 },
9607         { "ERxError", 48, 1 },
9608         { "SanityFailed", 47, 1 },
9609         { "SpuriousMsg", 46, 1 },
9610         { "FlushInputMsg", 45, 1 },
9611         { "FlushInputCpl", 44, 1 },
9612         { "RssUpBit", 43, 1 },
9613         { "RssFilterHit", 42, 1 },
9614         { "Tid", 32, 10 },
9615         { "InitTcb", 31, 1 },
9616         { "LineNumber", 24, 7 },
9617         { "Emsg", 23, 1 },
9618         { "EdataOut", 22, 1 },
9619         { "Cmsg", 21, 1 },
9620         { "CdataOut", 20, 1 },
9621         { "EreadPdu", 19, 1 },
9622         { "CreadPdu", 18, 1 },
9623         { "TunnelPkt", 17, 1 },
9624         { "RcfPeerFin", 16, 1 },
9625         { "RcfReasonOut", 12, 4 },
9626         { "TxCchannel", 10, 2 },
9627         { "RcfTxChannel", 8, 2 },
9628         { "RxEchannel", 6, 2 },
9629         { "RcfRxChannel", 5, 1 },
9630         { "RcfDataOutSrdy", 4, 1 },
9631         { "RxDvld", 3, 1 },
9632         { "RxOoDvld", 2, 1 },
9633         { "RxCongestion", 1, 1 },
9634         { "TxCongestion", 0, 1 },
9635         { NULL }
9636 };
9637
9638 static const struct field_desc tp_la1[] = {
9639         { "CplCmdIn", 56, 8 },
9640         { "CplCmdOut", 48, 8 },
9641         { "ESynOut", 47, 1 },
9642         { "EAckOut", 46, 1 },
9643         { "EFinOut", 45, 1 },
9644         { "ERstOut", 44, 1 },
9645         { "SynIn", 43, 1 },
9646         { "AckIn", 42, 1 },
9647         { "FinIn", 41, 1 },
9648         { "RstIn", 40, 1 },
9649         { "DataIn", 39, 1 },
9650         { "DataInVld", 38, 1 },
9651         { "PadIn", 37, 1 },
9652         { "RxBufEmpty", 36, 1 },
9653         { "RxDdp", 35, 1 },
9654         { "RxFbCongestion", 34, 1 },
9655         { "TxFbCongestion", 33, 1 },
9656         { "TxPktSumSrdy", 32, 1 },
9657         { "RcfUlpType", 28, 4 },
9658         { "Eread", 27, 1 },
9659         { "Ebypass", 26, 1 },
9660         { "Esave", 25, 1 },
9661         { "Static0", 24, 1 },
9662         { "Cread", 23, 1 },
9663         { "Cbypass", 22, 1 },
9664         { "Csave", 21, 1 },
9665         { "CPktOut", 20, 1 },
9666         { "RxPagePoolFull", 18, 2 },
9667         { "RxLpbkPkt", 17, 1 },
9668         { "TxLpbkPkt", 16, 1 },
9669         { "RxVfValid", 15, 1 },
9670         { "SynLearned", 14, 1 },
9671         { "SetDelEntry", 13, 1 },
9672         { "SetInvEntry", 12, 1 },
9673         { "CpcmdDvld", 11, 1 },
9674         { "CpcmdSave", 10, 1 },
9675         { "RxPstructsFull", 8, 2 },
9676         { "EpcmdDvld", 7, 1 },
9677         { "EpcmdFlush", 6, 1 },
9678         { "EpcmdTrimPrefix", 5, 1 },
9679         { "EpcmdTrimPostfix", 4, 1 },
9680         { "ERssIp4Pkt", 3, 1 },
9681         { "ERssIp6Pkt", 2, 1 },
9682         { "ERssTcpUdpPkt", 1, 1 },
9683         { "ERssFceFipPkt", 0, 1 },
9684         { NULL }
9685 };
9686
9687 static const struct field_desc tp_la2[] = {
9688         { "CplCmdIn", 56, 8 },
9689         { "MpsVfVld", 55, 1 },
9690         { "MpsPf", 52, 3 },
9691         { "MpsVf", 44, 8 },
9692         { "SynIn", 43, 1 },
9693         { "AckIn", 42, 1 },
9694         { "FinIn", 41, 1 },
9695         { "RstIn", 40, 1 },
9696         { "DataIn", 39, 1 },
9697         { "DataInVld", 38, 1 },
9698         { "PadIn", 37, 1 },
9699         { "RxBufEmpty", 36, 1 },
9700         { "RxDdp", 35, 1 },
9701         { "RxFbCongestion", 34, 1 },
9702         { "TxFbCongestion", 33, 1 },
9703         { "TxPktSumSrdy", 32, 1 },
9704         { "RcfUlpType", 28, 4 },
9705         { "Eread", 27, 1 },
9706         { "Ebypass", 26, 1 },
9707         { "Esave", 25, 1 },
9708         { "Static0", 24, 1 },
9709         { "Cread", 23, 1 },
9710         { "Cbypass", 22, 1 },
9711         { "Csave", 21, 1 },
9712         { "CPktOut", 20, 1 },
9713         { "RxPagePoolFull", 18, 2 },
9714         { "RxLpbkPkt", 17, 1 },
9715         { "TxLpbkPkt", 16, 1 },
9716         { "RxVfValid", 15, 1 },
9717         { "SynLearned", 14, 1 },
9718         { "SetDelEntry", 13, 1 },
9719         { "SetInvEntry", 12, 1 },
9720         { "CpcmdDvld", 11, 1 },
9721         { "CpcmdSave", 10, 1 },
9722         { "RxPstructsFull", 8, 2 },
9723         { "EpcmdDvld", 7, 1 },
9724         { "EpcmdFlush", 6, 1 },
9725         { "EpcmdTrimPrefix", 5, 1 },
9726         { "EpcmdTrimPostfix", 4, 1 },
9727         { "ERssIp4Pkt", 3, 1 },
9728         { "ERssIp6Pkt", 2, 1 },
9729         { "ERssTcpUdpPkt", 1, 1 },
9730         { "ERssFceFipPkt", 0, 1 },
9731         { NULL }
9732 };
9733
9734 static void
9735 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
9736 {
9737
9738         field_desc_show(sb, *p, tp_la0);
9739 }
9740
9741 static void
9742 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
9743 {
9744
9745         if (idx)
9746                 sbuf_printf(sb, "\n");
9747         field_desc_show(sb, p[0], tp_la0);
9748         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
9749                 field_desc_show(sb, p[1], tp_la0);
9750 }
9751
9752 static void
9753 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
9754 {
9755
9756         if (idx)
9757                 sbuf_printf(sb, "\n");
9758         field_desc_show(sb, p[0], tp_la0);
9759         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
9760                 field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
9761 }
9762
9763 static int
9764 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
9765 {
9766         struct adapter *sc = arg1;
9767         struct sbuf *sb;
9768         uint64_t *buf, *p;
9769         int rc;
9770         u_int i, inc;
9771         void (*show_func)(struct sbuf *, uint64_t *, int);
9772
9773         rc = sysctl_wire_old_buffer(req, 0);
9774         if (rc != 0)
9775                 return (rc);
9776
9777         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9778         if (sb == NULL)
9779                 return (ENOMEM);
9780
9781         buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
9782
9783         t4_tp_read_la(sc, buf, NULL);
9784         p = buf;
9785
9786         switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
9787         case 2:
9788                 inc = 2;
9789                 show_func = tp_la_show2;
9790                 break;
9791         case 3:
9792                 inc = 2;
9793                 show_func = tp_la_show3;
9794                 break;
9795         default:
9796                 inc = 1;
9797                 show_func = tp_la_show;
9798         }
9799
9800         for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
9801                 (*show_func)(sb, p, i);
9802
9803         rc = sbuf_finish(sb);
9804         sbuf_delete(sb);
9805         free(buf, M_CXGBE);
9806         return (rc);
9807 }
9808
9809 static int
9810 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
9811 {
9812         struct adapter *sc = arg1;
9813         struct sbuf *sb;
9814         int rc;
9815         u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
9816
9817         rc = sysctl_wire_old_buffer(req, 0);
9818         if (rc != 0)
9819                 return (rc);
9820
9821         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9822         if (sb == NULL)
9823                 return (ENOMEM);
9824
9825         t4_get_chan_txrate(sc, nrate, orate);
9826
9827         if (sc->chip_params->nchan > 2) {
9828                 sbuf_printf(sb, "              channel 0   channel 1"
9829                     "   channel 2   channel 3\n");
9830                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
9831                     nrate[0], nrate[1], nrate[2], nrate[3]);
9832                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
9833                     orate[0], orate[1], orate[2], orate[3]);
9834         } else {
9835                 sbuf_printf(sb, "              channel 0   channel 1\n");
9836                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
9837                     nrate[0], nrate[1]);
9838                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
9839                     orate[0], orate[1]);
9840         }
9841
9842         rc = sbuf_finish(sb);
9843         sbuf_delete(sb);
9844
9845         return (rc);
9846 }
9847
9848 static int
9849 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
9850 {
9851         struct adapter *sc = arg1;
9852         struct sbuf *sb;
9853         uint32_t *buf, *p;
9854         int rc, i;
9855
9856         rc = sysctl_wire_old_buffer(req, 0);
9857         if (rc != 0)
9858                 return (rc);
9859
9860         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9861         if (sb == NULL)
9862                 return (ENOMEM);
9863
9864         buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
9865             M_ZERO | M_WAITOK);
9866
9867         t4_ulprx_read_la(sc, buf);
9868         p = buf;
9869
9870         sbuf_printf(sb, "      Pcmd        Type   Message"
9871             "                Data");
9872         for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
9873                 sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
9874                     p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
9875         }
9876
9877         rc = sbuf_finish(sb);
9878         sbuf_delete(sb);
9879         free(buf, M_CXGBE);
9880         return (rc);
9881 }
9882
9883 static int
9884 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
9885 {
9886         struct adapter *sc = arg1;
9887         struct sbuf *sb;
9888         int rc, v;
9889
9890         MPASS(chip_id(sc) >= CHELSIO_T5);
9891
9892         rc = sysctl_wire_old_buffer(req, 0);
9893         if (rc != 0)
9894                 return (rc);
9895
9896         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9897         if (sb == NULL)
9898                 return (ENOMEM);
9899
9900         v = t4_read_reg(sc, A_SGE_STAT_CFG);
9901         if (G_STATSOURCE_T5(v) == 7) {
9902                 int mode;
9903
9904                 mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
9905                 if (mode == 0) {
9906                         sbuf_printf(sb, "total %d, incomplete %d",
9907                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
9908                             t4_read_reg(sc, A_SGE_STAT_MATCH));
9909                 } else if (mode == 1) {
9910                         sbuf_printf(sb, "total %d, data overflow %d",
9911                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
9912                             t4_read_reg(sc, A_SGE_STAT_MATCH));
9913                 } else {
9914                         sbuf_printf(sb, "unknown mode %d", mode);
9915                 }
9916         }
9917         rc = sbuf_finish(sb);
9918         sbuf_delete(sb);
9919
9920         return (rc);
9921 }
9922
9923 static int
9924 sysctl_cpus(SYSCTL_HANDLER_ARGS)
9925 {
9926         struct adapter *sc = arg1;
9927         enum cpu_sets op = arg2;
9928         cpuset_t cpuset;
9929         struct sbuf *sb;
9930         int i, rc;
9931
9932         MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
9933
9934         CPU_ZERO(&cpuset);
9935         rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
9936         if (rc != 0)
9937                 return (rc);
9938
9939         rc = sysctl_wire_old_buffer(req, 0);
9940         if (rc != 0)
9941                 return (rc);
9942
9943         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9944         if (sb == NULL)
9945                 return (ENOMEM);
9946
9947         CPU_FOREACH(i)
9948                 sbuf_printf(sb, "%d ", i);
9949         rc = sbuf_finish(sb);
9950         sbuf_delete(sb);
9951
9952         return (rc);
9953 }
9954
9955 #ifdef TCP_OFFLOAD
9956 static int
9957 sysctl_tls(SYSCTL_HANDLER_ARGS)
9958 {
9959         struct adapter *sc = arg1;
9960         int i, j, v, rc;
9961         struct vi_info *vi;
9962
9963         v = sc->tt.tls;
9964         rc = sysctl_handle_int(oidp, &v, 0, req);
9965         if (rc != 0 || req->newptr == NULL)
9966                 return (rc);
9967
9968         if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
9969                 return (ENOTSUP);
9970
9971         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
9972         if (rc)
9973                 return (rc);
9974         sc->tt.tls = !!v;
9975         for_each_port(sc, i) {
9976                 for_each_vi(sc->port[i], j, vi) {
9977                         if (vi->flags & VI_INIT_DONE)
9978                                 t4_update_fl_bufsize(vi->ifp);
9979                 }
9980         }
9981         end_synchronized_op(sc, 0);
9982
9983         return (0);
9984
9985 }
9986
9987 static int
9988 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
9989 {
9990         struct adapter *sc = arg1;
9991         int *old_ports, *new_ports;
9992         int i, new_count, rc;
9993
9994         if (req->newptr == NULL && req->oldptr == NULL)
9995                 return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
9996                     sizeof(sc->tt.tls_rx_ports[0])));
9997
9998         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
9999         if (rc)
10000                 return (rc);
10001
10002         if (sc->tt.num_tls_rx_ports == 0) {
10003                 i = -1;
10004                 rc = SYSCTL_OUT(req, &i, sizeof(i));
10005         } else
10006                 rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
10007                     sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
10008         if (rc == 0 && req->newptr != NULL) {
10009                 new_count = req->newlen / sizeof(new_ports[0]);
10010                 new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
10011                     M_WAITOK);
10012                 rc = SYSCTL_IN(req, new_ports, new_count *
10013                     sizeof(new_ports[0]));
10014                 if (rc)
10015                         goto err;
10016
10017                 /* Allow setting to a single '-1' to clear the list. */
10018                 if (new_count == 1 && new_ports[0] == -1) {
10019                         ADAPTER_LOCK(sc);
10020                         old_ports = sc->tt.tls_rx_ports;
10021                         sc->tt.tls_rx_ports = NULL;
10022                         sc->tt.num_tls_rx_ports = 0;
10023                         ADAPTER_UNLOCK(sc);
10024                         free(old_ports, M_CXGBE);
10025                 } else {
10026                         for (i = 0; i < new_count; i++) {
10027                                 if (new_ports[i] < 1 ||
10028                                     new_ports[i] > IPPORT_MAX) {
10029                                         rc = EINVAL;
10030                                         goto err;
10031                                 }
10032                         }
10033
10034                         ADAPTER_LOCK(sc);
10035                         old_ports = sc->tt.tls_rx_ports;
10036                         sc->tt.tls_rx_ports = new_ports;
10037                         sc->tt.num_tls_rx_ports = new_count;
10038                         ADAPTER_UNLOCK(sc);
10039                         free(old_ports, M_CXGBE);
10040                         new_ports = NULL;
10041                 }
10042         err:
10043                 free(new_ports, M_CXGBE);
10044         }
10045         end_synchronized_op(sc, 0);
10046         return (rc);
10047 }
10048
10049 static void
10050 unit_conv(char *buf, size_t len, u_int val, u_int factor)
10051 {
10052         u_int rem = val % factor;
10053
10054         if (rem == 0)
10055                 snprintf(buf, len, "%u", val / factor);
10056         else {
10057                 while (rem % 10 == 0)
10058                         rem /= 10;
10059                 snprintf(buf, len, "%u.%u", val / factor, rem);
10060         }
10061 }
10062
10063 static int
10064 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
10065 {
10066         struct adapter *sc = arg1;
10067         char buf[16];
10068         u_int res, re;
10069         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
10070
10071         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
10072         switch (arg2) {
10073         case 0:
10074                 /* timer_tick */
10075                 re = G_TIMERRESOLUTION(res);
10076                 break;
10077         case 1:
10078                 /* TCP timestamp tick */
10079                 re = G_TIMESTAMPRESOLUTION(res);
10080                 break;
10081         case 2:
10082                 /* DACK tick */
10083                 re = G_DELAYEDACKRESOLUTION(res);
10084                 break;
10085         default:
10086                 return (EDOOFUS);
10087         }
10088
10089         unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
10090
10091         return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
10092 }
10093
10094 static int
10095 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
10096 {
10097         struct adapter *sc = arg1;
10098         u_int res, dack_re, v;
10099         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
10100
10101         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
10102         dack_re = G_DELAYEDACKRESOLUTION(res);
10103         v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
10104
10105         return (sysctl_handle_int(oidp, &v, 0, req));
10106 }
10107
10108 static int
10109 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
10110 {
10111         struct adapter *sc = arg1;
10112         int reg = arg2;
10113         u_int tre;
10114         u_long tp_tick_us, v;
10115         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
10116
10117         MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
10118             reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
10119             reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
10120             reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
10121
10122         tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
10123         tp_tick_us = (cclk_ps << tre) / 1000000;
10124
10125         if (reg == A_TP_INIT_SRTT)
10126                 v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
10127         else
10128                 v = tp_tick_us * t4_read_reg(sc, reg);
10129
10130         return (sysctl_handle_long(oidp, &v, 0, req));
10131 }
10132
10133 /*
10134  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
10135  * passed to this function.
10136  */
10137 static int
10138 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
10139 {
10140         struct adapter *sc = arg1;
10141         int idx = arg2;
10142         u_int v;
10143
10144         MPASS(idx >= 0 && idx <= 24);
10145
10146         v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
10147
10148         return (sysctl_handle_int(oidp, &v, 0, req));
10149 }
10150
10151 static int
10152 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
10153 {
10154         struct adapter *sc = arg1;
10155         int idx = arg2;
10156         u_int shift, v, r;
10157
10158         MPASS(idx >= 0 && idx < 16);
10159
10160         r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
10161         shift = (idx & 3) << 3;
10162         v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
10163
10164         return (sysctl_handle_int(oidp, &v, 0, req));
10165 }
10166
10167 static int
10168 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
10169 {
10170         struct vi_info *vi = arg1;
10171         struct adapter *sc = vi->adapter;
10172         int idx, rc, i;
10173         struct sge_ofld_rxq *ofld_rxq;
10174         uint8_t v;
10175
10176         idx = vi->ofld_tmr_idx;
10177
10178         rc = sysctl_handle_int(oidp, &idx, 0, req);
10179         if (rc != 0 || req->newptr == NULL)
10180                 return (rc);
10181
10182         if (idx < 0 || idx >= SGE_NTIMERS)
10183                 return (EINVAL);
10184
10185         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
10186             "t4otmr");
10187         if (rc)
10188                 return (rc);
10189
10190         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
10191         for_each_ofld_rxq(vi, i, ofld_rxq) {
10192 #ifdef atomic_store_rel_8
10193                 atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
10194 #else
10195                 ofld_rxq->iq.intr_params = v;
10196 #endif
10197         }
10198         vi->ofld_tmr_idx = idx;
10199
10200         end_synchronized_op(sc, LOCK_HELD);
10201         return (0);
10202 }
10203
10204 static int
10205 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
10206 {
10207         struct vi_info *vi = arg1;
10208         struct adapter *sc = vi->adapter;
10209         int idx, rc;
10210
10211         idx = vi->ofld_pktc_idx;
10212
10213         rc = sysctl_handle_int(oidp, &idx, 0, req);
10214         if (rc != 0 || req->newptr == NULL)
10215                 return (rc);
10216
10217         if (idx < -1 || idx >= SGE_NCOUNTERS)
10218                 return (EINVAL);
10219
10220         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
10221             "t4opktc");
10222         if (rc)
10223                 return (rc);
10224
10225         if (vi->flags & VI_INIT_DONE)
10226                 rc = EBUSY; /* cannot be changed once the queues are created */
10227         else
10228                 vi->ofld_pktc_idx = idx;
10229
10230         end_synchronized_op(sc, LOCK_HELD);
10231         return (rc);
10232 }
10233 #endif
10234
10235 static int
10236 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
10237 {
10238         int rc;
10239
10240         if (cntxt->cid > M_CTXTQID)
10241                 return (EINVAL);
10242
10243         if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
10244             cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
10245                 return (EINVAL);
10246
10247         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
10248         if (rc)
10249                 return (rc);
10250
10251         if (sc->flags & FW_OK) {
10252                 rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
10253                     &cntxt->data[0]);
10254                 if (rc == 0)
10255                         goto done;
10256         }
10257
10258         /*
10259          * Read via firmware failed or wasn't even attempted.  Read directly via
10260          * the backdoor.
10261          */
10262         rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
10263 done:
10264         end_synchronized_op(sc, 0);
10265         return (rc);
10266 }
10267
10268 static int
10269 load_fw(struct adapter *sc, struct t4_data *fw)
10270 {
10271         int rc;
10272         uint8_t *fw_data;
10273
10274         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
10275         if (rc)
10276                 return (rc);
10277
10278         /*
10279          * The firmware, with the sole exception of the memory parity error
10280          * handler, runs from memory and not flash.  It is almost always safe to
10281          * install a new firmware on a running system.  Just set bit 1 in
10282          * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
10283          */
10284         if (sc->flags & FULL_INIT_DONE &&
10285             (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
10286                 rc = EBUSY;
10287                 goto done;
10288         }
10289
10290         fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
10291
10292         rc = copyin(fw->data, fw_data, fw->len);
10293         if (rc == 0)
10294                 rc = -t4_load_fw(sc, fw_data, fw->len);
10295
10296         free(fw_data, M_CXGBE);
10297 done:
10298         end_synchronized_op(sc, 0);
10299         return (rc);
10300 }
10301
10302 static int
10303 load_cfg(struct adapter *sc, struct t4_data *cfg)
10304 {
10305         int rc;
10306         uint8_t *cfg_data = NULL;
10307
10308         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
10309         if (rc)
10310                 return (rc);
10311
10312         if (cfg->len == 0) {
10313                 /* clear */
10314                 rc = -t4_load_cfg(sc, NULL, 0);
10315                 goto done;
10316         }
10317
10318         cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
10319
10320         rc = copyin(cfg->data, cfg_data, cfg->len);
10321         if (rc == 0)
10322                 rc = -t4_load_cfg(sc, cfg_data, cfg->len);
10323
10324         free(cfg_data, M_CXGBE);
10325 done:
10326         end_synchronized_op(sc, 0);
10327         return (rc);
10328 }
10329
10330 static int
10331 load_boot(struct adapter *sc, struct t4_bootrom *br)
10332 {
10333         int rc;
10334         uint8_t *br_data = NULL;
10335         u_int offset;
10336
10337         if (br->len > 1024 * 1024)
10338                 return (EFBIG);
10339
10340         if (br->pf_offset == 0) {
10341                 /* pfidx */
10342                 if (br->pfidx_addr > 7)
10343                         return (EINVAL);
10344                 offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
10345                     A_PCIE_PF_EXPROM_OFST)));
10346         } else if (br->pf_offset == 1) {
10347                 /* offset */
10348                 offset = G_OFFSET(br->pfidx_addr);
10349         } else {
10350                 return (EINVAL);
10351         }
10352
10353         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
10354         if (rc)
10355                 return (rc);
10356
10357         if (br->len == 0) {
10358                 /* clear */
10359                 rc = -t4_load_boot(sc, NULL, offset, 0);
10360                 goto done;
10361         }
10362
10363         br_data = malloc(br->len, M_CXGBE, M_WAITOK);
10364
10365         rc = copyin(br->data, br_data, br->len);
10366         if (rc == 0)
10367                 rc = -t4_load_boot(sc, br_data, offset, br->len);
10368
10369         free(br_data, M_CXGBE);
10370 done:
10371         end_synchronized_op(sc, 0);
10372         return (rc);
10373 }
10374
10375 static int
10376 load_bootcfg(struct adapter *sc, struct t4_data *bc)
10377 {
10378         int rc;
10379         uint8_t *bc_data = NULL;
10380
10381         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
10382         if (rc)
10383                 return (rc);
10384
10385         if (bc->len == 0) {
10386                 /* clear */
10387                 rc = -t4_load_bootcfg(sc, NULL, 0);
10388                 goto done;
10389         }
10390
10391         bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
10392
10393         rc = copyin(bc->data, bc_data, bc->len);
10394         if (rc == 0)
10395                 rc = -t4_load_bootcfg(sc, bc_data, bc->len);
10396
10397         free(bc_data, M_CXGBE);
10398 done:
10399         end_synchronized_op(sc, 0);
10400         return (rc);
10401 }
10402
10403 static int
10404 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
10405 {
10406         int rc;
10407         struct cudbg_init *cudbg;
10408         void *handle, *buf;
10409
10410         /* buf is large, don't block if no memory is available */
10411         buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
10412         if (buf == NULL)
10413                 return (ENOMEM);
10414
10415         handle = cudbg_alloc_handle();
10416         if (handle == NULL) {
10417                 rc = ENOMEM;
10418                 goto done;
10419         }
10420
10421         cudbg = cudbg_get_init(handle);
10422         cudbg->adap = sc;
10423         cudbg->print = (cudbg_print_cb)printf;
10424
10425 #ifndef notyet
10426         device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
10427             __func__, dump->wr_flash, dump->len, dump->data);
10428 #endif
10429
10430         if (dump->wr_flash)
10431                 cudbg->use_flash = 1;
10432         MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
10433         memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
10434
10435         rc = cudbg_collect(handle, buf, &dump->len);
10436         if (rc != 0)
10437                 goto done;
10438
10439         rc = copyout(buf, dump->data, dump->len);
10440 done:
10441         cudbg_free_handle(handle);
10442         free(buf, M_CXGBE);
10443         return (rc);
10444 }
10445
10446 static void
10447 free_offload_policy(struct t4_offload_policy *op)
10448 {
10449         struct offload_rule *r;
10450         int i;
10451
10452         if (op == NULL)
10453                 return;
10454
10455         r = &op->rule[0];
10456         for (i = 0; i < op->nrules; i++, r++) {
10457                 free(r->bpf_prog.bf_insns, M_CXGBE);
10458         }
10459         free(op->rule, M_CXGBE);
10460         free(op, M_CXGBE);
10461 }
10462
10463 static int
10464 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
10465 {
10466         int i, rc, len;
10467         struct t4_offload_policy *op, *old;
10468         struct bpf_program *bf;
10469         const struct offload_settings *s;
10470         struct offload_rule *r;
10471         void *u;
10472
10473         if (!is_offload(sc))
10474                 return (ENODEV);
10475
10476         if (uop->nrules == 0) {
10477                 /* Delete installed policies. */
10478                 op = NULL;
10479                 goto set_policy;
10480         } else if (uop->nrules > 256) { /* arbitrary */
10481                 return (E2BIG);
10482         }
10483
10484         /* Copy userspace offload policy to kernel */
10485         op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
10486         op->nrules = uop->nrules;
10487         len = op->nrules * sizeof(struct offload_rule);
10488         op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
10489         rc = copyin(uop->rule, op->rule, len);
10490         if (rc) {
10491                 free(op->rule, M_CXGBE);
10492                 free(op, M_CXGBE);
10493                 return (rc);
10494         }
10495
10496         r = &op->rule[0];
10497         for (i = 0; i < op->nrules; i++, r++) {
10498
10499                 /* Validate open_type */
10500                 if (r->open_type != OPEN_TYPE_LISTEN &&
10501                     r->open_type != OPEN_TYPE_ACTIVE &&
10502                     r->open_type != OPEN_TYPE_PASSIVE &&
10503                     r->open_type != OPEN_TYPE_DONTCARE) {
10504 error:
10505                         /*
10506                          * Rules 0 to i have malloc'd filters that need to be
10507                          * freed.  Rules i+1 to nrules have userspace pointers
10508                          * and should be left alone.
10509                          */
10510                         op->nrules = i;
10511                         free_offload_policy(op);
10512                         return (rc);
10513                 }
10514
10515                 /* Validate settings */
10516                 s = &r->settings;
10517                 if ((s->offload != 0 && s->offload != 1) ||
10518                     s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
10519                     s->sched_class < -1 ||
10520                     s->sched_class >= sc->chip_params->nsched_cls) {
10521                         rc = EINVAL;
10522                         goto error;
10523                 }
10524
10525                 bf = &r->bpf_prog;
10526                 u = bf->bf_insns;       /* userspace ptr */
10527                 bf->bf_insns = NULL;
10528                 if (bf->bf_len == 0) {
10529                         /* legal, matches everything */
10530                         continue;
10531                 }
10532                 len = bf->bf_len * sizeof(*bf->bf_insns);
10533                 bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
10534                 rc = copyin(u, bf->bf_insns, len);
10535                 if (rc != 0)
10536                         goto error;
10537
10538                 if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
10539                         rc = EINVAL;
10540                         goto error;
10541                 }
10542         }
10543 set_policy:
10544         rw_wlock(&sc->policy_lock);
10545         old = sc->policy;
10546         sc->policy = op;
10547         rw_wunlock(&sc->policy_lock);
10548         free_offload_policy(old);
10549
10550         return (0);
10551 }
10552
10553 #define MAX_READ_BUF_SIZE (128 * 1024)
10554 static int
10555 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
10556 {
10557         uint32_t addr, remaining, n;
10558         uint32_t *buf;
10559         int rc;
10560         uint8_t *dst;
10561
10562         rc = validate_mem_range(sc, mr->addr, mr->len);
10563         if (rc != 0)
10564                 return (rc);
10565
10566         buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
10567         addr = mr->addr;
10568         remaining = mr->len;
10569         dst = (void *)mr->data;
10570
10571         while (remaining) {
10572                 n = min(remaining, MAX_READ_BUF_SIZE);
10573                 read_via_memwin(sc, 2, addr, buf, n);
10574
10575                 rc = copyout(buf, dst, n);
10576                 if (rc != 0)
10577                         break;
10578
10579                 dst += n;
10580                 remaining -= n;
10581                 addr += n;
10582         }
10583
10584         free(buf, M_CXGBE);
10585         return (rc);
10586 }
10587 #undef MAX_READ_BUF_SIZE
10588
10589 static int
10590 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
10591 {
10592         int rc;
10593
10594         if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
10595                 return (EINVAL);
10596
10597         if (i2cd->len > sizeof(i2cd->data))
10598                 return (EFBIG);
10599
10600         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
10601         if (rc)
10602                 return (rc);
10603         rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
10604             i2cd->offset, i2cd->len, &i2cd->data[0]);
10605         end_synchronized_op(sc, 0);
10606
10607         return (rc);
10608 }
10609
10610 static int
10611 clear_stats(struct adapter *sc, u_int port_id)
10612 {
10613         int i, v, chan_map;
10614         struct port_info *pi;
10615         struct vi_info *vi;
10616         struct sge_rxq *rxq;
10617         struct sge_txq *txq;
10618         struct sge_wrq *wrq;
10619 #ifdef TCP_OFFLOAD
10620         struct sge_ofld_rxq *ofld_rxq;
10621 #endif
10622
10623         if (port_id >= sc->params.nports)
10624                 return (EINVAL);
10625         pi = sc->port[port_id];
10626         if (pi == NULL)
10627                 return (EIO);
10628
10629         /* MAC stats */
10630         t4_clr_port_stats(sc, pi->tx_chan);
10631         if (is_t6(sc)) {
10632                 if (pi->fcs_reg != -1)
10633                         pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
10634                 else
10635                         pi->stats.rx_fcs_err = 0;
10636         }
10637         pi->tx_parse_error = 0;
10638         pi->tnl_cong_drops = 0;
10639         mtx_lock(&sc->reg_lock);
10640         for_each_vi(pi, v, vi) {
10641                 if (vi->flags & VI_INIT_DONE)
10642                         t4_clr_vi_stats(sc, vi->vin);
10643         }
10644         chan_map = pi->rx_e_chan_map;
10645         v = 0;  /* reuse */
10646         while (chan_map) {
10647                 i = ffs(chan_map) - 1;
10648                 t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
10649                     1, A_TP_MIB_TNL_CNG_DROP_0 + i);
10650                 chan_map &= ~(1 << i);
10651         }
10652         mtx_unlock(&sc->reg_lock);
10653
10654         /*
10655          * Since this command accepts a port, clear stats for
10656          * all VIs on this port.
10657          */
10658         for_each_vi(pi, v, vi) {
10659                 if (vi->flags & VI_INIT_DONE) {
10660
10661                         for_each_rxq(vi, i, rxq) {
10662 #if defined(INET) || defined(INET6)
10663                                 rxq->lro.lro_queued = 0;
10664                                 rxq->lro.lro_flushed = 0;
10665 #endif
10666                                 rxq->rxcsum = 0;
10667                                 rxq->vlan_extraction = 0;
10668                                 rxq->vxlan_rxcsum = 0;
10669
10670                                 rxq->fl.cl_allocated = 0;
10671                                 rxq->fl.cl_recycled = 0;
10672                                 rxq->fl.cl_fast_recycled = 0;
10673                         }
10674
10675                         for_each_txq(vi, i, txq) {
10676                                 txq->txcsum = 0;
10677                                 txq->tso_wrs = 0;
10678                                 txq->vlan_insertion = 0;
10679                                 txq->imm_wrs = 0;
10680                                 txq->sgl_wrs = 0;
10681                                 txq->txpkt_wrs = 0;
10682                                 txq->txpkts0_wrs = 0;
10683                                 txq->txpkts1_wrs = 0;
10684                                 txq->txpkts0_pkts = 0;
10685                                 txq->txpkts1_pkts = 0;
10686                                 txq->raw_wrs = 0;
10687                                 txq->vxlan_tso_wrs = 0;
10688                                 txq->vxlan_txcsum = 0;
10689                                 txq->kern_tls_records = 0;
10690                                 txq->kern_tls_short = 0;
10691                                 txq->kern_tls_partial = 0;
10692                                 txq->kern_tls_full = 0;
10693                                 txq->kern_tls_octets = 0;
10694                                 txq->kern_tls_waste = 0;
10695                                 txq->kern_tls_options = 0;
10696                                 txq->kern_tls_header = 0;
10697                                 txq->kern_tls_fin = 0;
10698                                 txq->kern_tls_fin_short = 0;
10699                                 txq->kern_tls_cbc = 0;
10700                                 txq->kern_tls_gcm = 0;
10701                                 mp_ring_reset_stats(txq->r);
10702                         }
10703
10704 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
10705                         for_each_ofld_txq(vi, i, wrq) {
10706                                 wrq->tx_wrs_direct = 0;
10707                                 wrq->tx_wrs_copied = 0;
10708                         }
10709 #endif
10710 #ifdef TCP_OFFLOAD
10711                         for_each_ofld_rxq(vi, i, ofld_rxq) {
10712                                 ofld_rxq->fl.cl_allocated = 0;
10713                                 ofld_rxq->fl.cl_recycled = 0;
10714                                 ofld_rxq->fl.cl_fast_recycled = 0;
10715                         }
10716 #endif
10717
10718                         if (IS_MAIN_VI(vi)) {
10719                                 wrq = &sc->sge.ctrlq[pi->port_id];
10720                                 wrq->tx_wrs_direct = 0;
10721                                 wrq->tx_wrs_copied = 0;
10722                         }
10723                 }
10724         }
10725
10726         return (0);
10727 }
10728
10729 int
10730 t4_os_find_pci_capability(struct adapter *sc, int cap)
10731 {
10732         int i;
10733
10734         return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
10735 }
10736
10737 int
10738 t4_os_pci_save_state(struct adapter *sc)
10739 {
10740         device_t dev;
10741         struct pci_devinfo *dinfo;
10742
10743         dev = sc->dev;
10744         dinfo = device_get_ivars(dev);
10745
10746         pci_cfg_save(dev, dinfo, 0);
10747         return (0);
10748 }
10749
10750 int
10751 t4_os_pci_restore_state(struct adapter *sc)
10752 {
10753         device_t dev;
10754         struct pci_devinfo *dinfo;
10755
10756         dev = sc->dev;
10757         dinfo = device_get_ivars(dev);
10758
10759         pci_cfg_restore(dev, dinfo);
10760         return (0);
10761 }
10762
10763 void
10764 t4_os_portmod_changed(struct port_info *pi)
10765 {
10766         struct adapter *sc = pi->adapter;
10767         struct vi_info *vi;
10768         struct ifnet *ifp;
10769         static const char *mod_str[] = {
10770                 NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
10771         };
10772
10773         KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
10774             ("%s: port_type %u", __func__, pi->port_type));
10775
10776         vi = &pi->vi[0];
10777         if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
10778                 PORT_LOCK(pi);
10779                 build_medialist(pi);
10780                 if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
10781                         fixup_link_config(pi);
10782                         apply_link_config(pi);
10783                 }
10784                 PORT_UNLOCK(pi);
10785                 end_synchronized_op(sc, LOCK_HELD);
10786         }
10787
10788         ifp = vi->ifp;
10789         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
10790                 if_printf(ifp, "transceiver unplugged.\n");
10791         else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
10792                 if_printf(ifp, "unknown transceiver inserted.\n");
10793         else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
10794                 if_printf(ifp, "unsupported transceiver inserted.\n");
10795         else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
10796                 if_printf(ifp, "%dGbps %s transceiver inserted.\n",
10797                     port_top_speed(pi), mod_str[pi->mod_type]);
10798         } else {
10799                 if_printf(ifp, "transceiver (type %d) inserted.\n",
10800                     pi->mod_type);
10801         }
10802 }
10803
10804 void
10805 t4_os_link_changed(struct port_info *pi)
10806 {
10807         struct vi_info *vi;
10808         struct ifnet *ifp;
10809         struct link_config *lc = &pi->link_cfg;
10810         struct adapter *sc = pi->adapter;
10811         int v;
10812
10813         PORT_LOCK_ASSERT_OWNED(pi);
10814
10815         if (is_t6(sc)) {
10816                 if (lc->link_ok) {
10817                         if (lc->speed > 25000 ||
10818                             (lc->speed == 25000 && lc->fec == FEC_RS)) {
10819                                 pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
10820                                     A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
10821                         } else {
10822                                 pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
10823                                     A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
10824                         }
10825                         pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
10826                         pi->stats.rx_fcs_err = 0;
10827                 } else {
10828                         pi->fcs_reg = -1;
10829                 }
10830         } else {
10831                 MPASS(pi->fcs_reg != -1);
10832                 MPASS(pi->fcs_base == 0);
10833         }
10834
10835         for_each_vi(pi, v, vi) {
10836                 ifp = vi->ifp;
10837                 if (ifp == NULL)
10838                         continue;
10839
10840                 if (lc->link_ok) {
10841                         ifp->if_baudrate = IF_Mbps(lc->speed);
10842                         if_link_state_change(ifp, LINK_STATE_UP);
10843                 } else {
10844                         if_link_state_change(ifp, LINK_STATE_DOWN);
10845                 }
10846         }
10847 }
10848
10849 void
10850 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
10851 {
10852         struct adapter *sc;
10853
10854         sx_slock(&t4_list_lock);
10855         SLIST_FOREACH(sc, &t4_list, link) {
10856                 /*
10857                  * func should not make any assumptions about what state sc is
10858                  * in - the only guarantee is that sc->sc_lock is a valid lock.
10859                  */
10860                 func(sc, arg);
10861         }
10862         sx_sunlock(&t4_list_lock);
10863 }
10864
10865 static int
10866 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
10867     struct thread *td)
10868 {
10869         int rc;
10870         struct adapter *sc = dev->si_drv1;
10871
10872         rc = priv_check(td, PRIV_DRIVER);
10873         if (rc != 0)
10874                 return (rc);
10875
10876         switch (cmd) {
10877         case CHELSIO_T4_GETREG: {
10878                 struct t4_reg *edata = (struct t4_reg *)data;
10879
10880                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
10881                         return (EFAULT);
10882
10883                 if (edata->size == 4)
10884                         edata->val = t4_read_reg(sc, edata->addr);
10885                 else if (edata->size == 8)
10886                         edata->val = t4_read_reg64(sc, edata->addr);
10887                 else
10888                         return (EINVAL);
10889
10890                 break;
10891         }
10892         case CHELSIO_T4_SETREG: {
10893                 struct t4_reg *edata = (struct t4_reg *)data;
10894
10895                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
10896                         return (EFAULT);
10897
10898                 if (edata->size == 4) {
10899                         if (edata->val & 0xffffffff00000000)
10900                                 return (EINVAL);
10901                         t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
10902                 } else if (edata->size == 8)
10903                         t4_write_reg64(sc, edata->addr, edata->val);
10904                 else
10905                         return (EINVAL);
10906                 break;
10907         }
10908         case CHELSIO_T4_REGDUMP: {
10909                 struct t4_regdump *regs = (struct t4_regdump *)data;
10910                 int reglen = t4_get_regs_len(sc);
10911                 uint8_t *buf;
10912
10913                 if (regs->len < reglen) {
10914                         regs->len = reglen; /* hint to the caller */
10915                         return (ENOBUFS);
10916                 }
10917
10918                 regs->len = reglen;
10919                 buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
10920                 get_regs(sc, regs, buf);
10921                 rc = copyout(buf, regs->data, reglen);
10922                 free(buf, M_CXGBE);
10923                 break;
10924         }
10925         case CHELSIO_T4_GET_FILTER_MODE:
10926                 rc = get_filter_mode(sc, (uint32_t *)data);
10927                 break;
10928         case CHELSIO_T4_SET_FILTER_MODE:
10929                 rc = set_filter_mode(sc, *(uint32_t *)data);
10930                 break;
10931         case CHELSIO_T4_GET_FILTER:
10932                 rc = get_filter(sc, (struct t4_filter *)data);
10933                 break;
10934         case CHELSIO_T4_SET_FILTER:
10935                 rc = set_filter(sc, (struct t4_filter *)data);
10936                 break;
10937         case CHELSIO_T4_DEL_FILTER:
10938                 rc = del_filter(sc, (struct t4_filter *)data);
10939                 break;
10940         case CHELSIO_T4_GET_SGE_CONTEXT:
10941                 rc = get_sge_context(sc, (struct t4_sge_context *)data);
10942                 break;
10943         case CHELSIO_T4_LOAD_FW:
10944                 rc = load_fw(sc, (struct t4_data *)data);
10945                 break;
10946         case CHELSIO_T4_GET_MEM:
10947                 rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
10948                 break;
10949         case CHELSIO_T4_GET_I2C:
10950                 rc = read_i2c(sc, (struct t4_i2c_data *)data);
10951                 break;
10952         case CHELSIO_T4_CLEAR_STATS:
10953                 rc = clear_stats(sc, *(uint32_t *)data);
10954                 break;
10955         case CHELSIO_T4_SCHED_CLASS:
10956                 rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
10957                 break;
10958         case CHELSIO_T4_SCHED_QUEUE:
10959                 rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
10960                 break;
10961         case CHELSIO_T4_GET_TRACER:
10962                 rc = t4_get_tracer(sc, (struct t4_tracer *)data);
10963                 break;
10964         case CHELSIO_T4_SET_TRACER:
10965                 rc = t4_set_tracer(sc, (struct t4_tracer *)data);
10966                 break;
10967         case CHELSIO_T4_LOAD_CFG:
10968                 rc = load_cfg(sc, (struct t4_data *)data);
10969                 break;
10970         case CHELSIO_T4_LOAD_BOOT:
10971                 rc = load_boot(sc, (struct t4_bootrom *)data);
10972                 break;
10973         case CHELSIO_T4_LOAD_BOOTCFG:
10974                 rc = load_bootcfg(sc, (struct t4_data *)data);
10975                 break;
10976         case CHELSIO_T4_CUDBG_DUMP:
10977                 rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
10978                 break;
10979         case CHELSIO_T4_SET_OFLD_POLICY:
10980                 rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
10981                 break;
10982         default:
10983                 rc = ENOTTY;
10984         }
10985
10986         return (rc);
10987 }
10988
10989 #ifdef TCP_OFFLOAD
10990 static int
10991 toe_capability(struct vi_info *vi, int enable)
10992 {
10993         int rc;
10994         struct port_info *pi = vi->pi;
10995         struct adapter *sc = pi->adapter;
10996
10997         ASSERT_SYNCHRONIZED_OP(sc);
10998
10999         if (!is_offload(sc))
11000                 return (ENODEV);
11001
11002         if (enable) {
11003                 if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
11004                         /* TOE is already enabled. */
11005                         return (0);
11006                 }
11007
11008                 /*
11009                  * We need the port's queues around so that we're able to send
11010                  * and receive CPLs to/from the TOE even if the ifnet for this
11011                  * port has never been UP'd administratively.
11012                  */
11013                 if (!(vi->flags & VI_INIT_DONE)) {
11014                         rc = vi_full_init(vi);
11015                         if (rc)
11016                                 return (rc);
11017                 }
11018                 if (!(pi->vi[0].flags & VI_INIT_DONE)) {
11019                         rc = vi_full_init(&pi->vi[0]);
11020                         if (rc)
11021                                 return (rc);
11022                 }
11023
11024                 if (isset(&sc->offload_map, pi->port_id)) {
11025                         /* TOE is enabled on another VI of this port. */
11026                         pi->uld_vis++;
11027                         return (0);
11028                 }
11029
11030                 if (!uld_active(sc, ULD_TOM)) {
11031                         rc = t4_activate_uld(sc, ULD_TOM);
11032                         if (rc == EAGAIN) {
11033                                 log(LOG_WARNING,
11034                                     "You must kldload t4_tom.ko before trying "
11035                                     "to enable TOE on a cxgbe interface.\n");
11036                         }
11037                         if (rc != 0)
11038                                 return (rc);
11039                         KASSERT(sc->tom_softc != NULL,
11040                             ("%s: TOM activated but softc NULL", __func__));
11041                         KASSERT(uld_active(sc, ULD_TOM),
11042                             ("%s: TOM activated but flag not set", __func__));
11043                 }
11044
11045                 /* Activate iWARP and iSCSI too, if the modules are loaded. */
11046                 if (!uld_active(sc, ULD_IWARP))
11047                         (void) t4_activate_uld(sc, ULD_IWARP);
11048                 if (!uld_active(sc, ULD_ISCSI))
11049                         (void) t4_activate_uld(sc, ULD_ISCSI);
11050
11051                 pi->uld_vis++;
11052                 setbit(&sc->offload_map, pi->port_id);
11053         } else {
11054                 pi->uld_vis--;
11055
11056                 if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
11057                         return (0);
11058
11059                 KASSERT(uld_active(sc, ULD_TOM),
11060                     ("%s: TOM never initialized?", __func__));
11061                 clrbit(&sc->offload_map, pi->port_id);
11062         }
11063
11064         return (0);
11065 }
11066
11067 /*
11068  * Add an upper layer driver to the global list.
11069  */
11070 int
11071 t4_register_uld(struct uld_info *ui)
11072 {
11073         int rc = 0;
11074         struct uld_info *u;
11075
11076         sx_xlock(&t4_uld_list_lock);
11077         SLIST_FOREACH(u, &t4_uld_list, link) {
11078             if (u->uld_id == ui->uld_id) {
11079                     rc = EEXIST;
11080                     goto done;
11081             }
11082         }
11083
11084         SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
11085         ui->refcount = 0;
11086 done:
11087         sx_xunlock(&t4_uld_list_lock);
11088         return (rc);
11089 }
11090
11091 int
11092 t4_unregister_uld(struct uld_info *ui)
11093 {
11094         int rc = EINVAL;
11095         struct uld_info *u;
11096
11097         sx_xlock(&t4_uld_list_lock);
11098
11099         SLIST_FOREACH(u, &t4_uld_list, link) {
11100             if (u == ui) {
11101                     if (ui->refcount > 0) {
11102                             rc = EBUSY;
11103                             goto done;
11104                     }
11105
11106                     SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
11107                     rc = 0;
11108                     goto done;
11109             }
11110         }
11111 done:
11112         sx_xunlock(&t4_uld_list_lock);
11113         return (rc);
11114 }
11115
11116 int
11117 t4_activate_uld(struct adapter *sc, int id)
11118 {
11119         int rc;
11120         struct uld_info *ui;
11121
11122         ASSERT_SYNCHRONIZED_OP(sc);
11123
11124         if (id < 0 || id > ULD_MAX)
11125                 return (EINVAL);
11126         rc = EAGAIN;    /* kldoad the module with this ULD and try again. */
11127
11128         sx_slock(&t4_uld_list_lock);
11129
11130         SLIST_FOREACH(ui, &t4_uld_list, link) {
11131                 if (ui->uld_id == id) {
11132                         if (!(sc->flags & FULL_INIT_DONE)) {
11133                                 rc = adapter_full_init(sc);
11134                                 if (rc != 0)
11135                                         break;
11136                         }
11137
11138                         rc = ui->activate(sc);
11139                         if (rc == 0) {
11140                                 setbit(&sc->active_ulds, id);
11141                                 ui->refcount++;
11142                         }
11143                         break;
11144                 }
11145         }
11146
11147         sx_sunlock(&t4_uld_list_lock);
11148
11149         return (rc);
11150 }
11151
11152 int
11153 t4_deactivate_uld(struct adapter *sc, int id)
11154 {
11155         int rc;
11156         struct uld_info *ui;
11157
11158         ASSERT_SYNCHRONIZED_OP(sc);
11159
11160         if (id < 0 || id > ULD_MAX)
11161                 return (EINVAL);
11162         rc = ENXIO;
11163
11164         sx_slock(&t4_uld_list_lock);
11165
11166         SLIST_FOREACH(ui, &t4_uld_list, link) {
11167                 if (ui->uld_id == id) {
11168                         rc = ui->deactivate(sc);
11169                         if (rc == 0) {
11170                                 clrbit(&sc->active_ulds, id);
11171                                 ui->refcount--;
11172                         }
11173                         break;
11174                 }
11175         }
11176
11177         sx_sunlock(&t4_uld_list_lock);
11178
11179         return (rc);
11180 }
11181
11182 static void
11183 t4_async_event(void *arg, int n)
11184 {
11185         struct uld_info *ui;
11186         struct adapter *sc = (struct adapter *)arg;
11187
11188         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
11189                 return;
11190         sx_slock(&t4_uld_list_lock);
11191         SLIST_FOREACH(ui, &t4_uld_list, link) {
11192                 if (ui->uld_id == ULD_IWARP) {
11193                         ui->async_event(sc);
11194                         break;
11195                 }
11196         }
11197         sx_sunlock(&t4_uld_list_lock);
11198         end_synchronized_op(sc, 0);
11199 }
11200
11201 int
11202 uld_active(struct adapter *sc, int uld_id)
11203 {
11204
11205         MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
11206
11207         return (isset(&sc->active_ulds, uld_id));
11208 }
11209 #endif
11210
11211 /*
11212  * t  = ptr to tunable.
11213  * nc = number of CPUs.
11214  * c  = compiled in default for that tunable.
11215  */
11216 static void
11217 calculate_nqueues(int *t, int nc, const int c)
11218 {
11219         int nq;
11220
11221         if (*t > 0)
11222                 return;
11223         nq = *t < 0 ? -*t : c;
11224         *t = min(nc, nq);
11225 }
11226
11227 /*
11228  * Come up with reasonable defaults for some of the tunables, provided they're
11229  * not set by the user (in which case we'll use the values as is).
11230  */
11231 static void
11232 tweak_tunables(void)
11233 {
11234         int nc = mp_ncpus;      /* our snapshot of the number of CPUs */
11235
11236         if (t4_ntxq < 1) {
11237 #ifdef RSS
11238                 t4_ntxq = rss_getnumbuckets();
11239 #else
11240                 calculate_nqueues(&t4_ntxq, nc, NTXQ);
11241 #endif
11242         }
11243
11244         calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
11245
11246         if (t4_nrxq < 1) {
11247 #ifdef RSS
11248                 t4_nrxq = rss_getnumbuckets();
11249 #else
11250                 calculate_nqueues(&t4_nrxq, nc, NRXQ);
11251 #endif
11252         }
11253
11254         calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
11255
11256 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11257         calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
11258         calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
11259 #endif
11260 #ifdef TCP_OFFLOAD
11261         calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
11262         calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
11263 #endif
11264
11265 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
11266         if (t4_toecaps_allowed == -1)
11267                 t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
11268 #else
11269         if (t4_toecaps_allowed == -1)
11270                 t4_toecaps_allowed = 0;
11271 #endif
11272
11273 #ifdef TCP_OFFLOAD
11274         if (t4_rdmacaps_allowed == -1) {
11275                 t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
11276                     FW_CAPS_CONFIG_RDMA_RDMAC;
11277         }
11278
11279         if (t4_iscsicaps_allowed == -1) {
11280                 t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
11281                     FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
11282                     FW_CAPS_CONFIG_ISCSI_T10DIF;
11283         }
11284
11285         if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
11286                 t4_tmr_idx_ofld = TMR_IDX_OFLD;
11287
11288         if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
11289                 t4_pktc_idx_ofld = PKTC_IDX_OFLD;
11290 #else
11291         if (t4_rdmacaps_allowed == -1)
11292                 t4_rdmacaps_allowed = 0;
11293
11294         if (t4_iscsicaps_allowed == -1)
11295                 t4_iscsicaps_allowed = 0;
11296 #endif
11297
11298 #ifdef DEV_NETMAP
11299         calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
11300         calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
11301         calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
11302         calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
11303 #endif
11304
11305         if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
11306                 t4_tmr_idx = TMR_IDX;
11307
11308         if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
11309                 t4_pktc_idx = PKTC_IDX;
11310
11311         if (t4_qsize_txq < 128)
11312                 t4_qsize_txq = 128;
11313
11314         if (t4_qsize_rxq < 128)
11315                 t4_qsize_rxq = 128;
11316         while (t4_qsize_rxq & 7)
11317                 t4_qsize_rxq++;
11318
11319         t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
11320
11321         /*
11322          * Number of VIs to create per-port.  The first VI is the "main" regular
11323          * VI for the port.  The rest are additional virtual interfaces on the
11324          * same physical port.  Note that the main VI does not have native
11325          * netmap support but the extra VIs do.
11326          *
11327          * Limit the number of VIs per port to the number of available
11328          * MAC addresses per port.
11329          */
11330         if (t4_num_vis < 1)
11331                 t4_num_vis = 1;
11332         if (t4_num_vis > nitems(vi_mac_funcs)) {
11333                 t4_num_vis = nitems(vi_mac_funcs);
11334                 printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
11335         }
11336
11337         if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
11338                 pcie_relaxed_ordering = 1;
11339 #if defined(__i386__) || defined(__amd64__)
11340                 if (cpu_vendor_id == CPU_VENDOR_INTEL)
11341                         pcie_relaxed_ordering = 0;
11342 #endif
11343         }
11344 }
11345
11346 #ifdef DDB
11347 static void
11348 t4_dump_tcb(struct adapter *sc, int tid)
11349 {
11350         uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
11351
11352         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
11353         save = t4_read_reg(sc, reg);
11354         base = sc->memwin[2].mw_base;
11355
11356         /* Dump TCB for the tid */
11357         tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
11358         tcb_addr += tid * TCB_SIZE;
11359
11360         if (is_t4(sc)) {
11361                 pf = 0;
11362                 win_pos = tcb_addr & ~0xf;      /* start must be 16B aligned */
11363         } else {
11364                 pf = V_PFNUM(sc->pf);
11365                 win_pos = tcb_addr & ~0x7f;     /* start must be 128B aligned */
11366         }
11367         t4_write_reg(sc, reg, win_pos | pf);
11368         t4_read_reg(sc, reg);
11369
11370         off = tcb_addr - win_pos;
11371         for (i = 0; i < 4; i++) {
11372                 uint32_t buf[8];
11373                 for (j = 0; j < 8; j++, off += 4)
11374                         buf[j] = htonl(t4_read_reg(sc, base + off));
11375
11376                 db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
11377                     buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
11378                     buf[7]);
11379         }
11380
11381         t4_write_reg(sc, reg, save);
11382         t4_read_reg(sc, reg);
11383 }
11384
11385 static void
11386 t4_dump_devlog(struct adapter *sc)
11387 {
11388         struct devlog_params *dparams = &sc->params.devlog;
11389         struct fw_devlog_e e;
11390         int i, first, j, m, nentries, rc;
11391         uint64_t ftstamp = UINT64_MAX;
11392
11393         if (dparams->start == 0) {
11394                 db_printf("devlog params not valid\n");
11395                 return;
11396         }
11397
11398         nentries = dparams->size / sizeof(struct fw_devlog_e);
11399         m = fwmtype_to_hwmtype(dparams->memtype);
11400
11401         /* Find the first entry. */
11402         first = -1;
11403         for (i = 0; i < nentries && !db_pager_quit; i++) {
11404                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
11405                     sizeof(e), (void *)&e);
11406                 if (rc != 0)
11407                         break;
11408
11409                 if (e.timestamp == 0)
11410                         break;
11411
11412                 e.timestamp = be64toh(e.timestamp);
11413                 if (e.timestamp < ftstamp) {
11414                         ftstamp = e.timestamp;
11415                         first = i;
11416                 }
11417         }
11418
11419         if (first == -1)
11420                 return;
11421
11422         i = first;
11423         do {
11424                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
11425                     sizeof(e), (void *)&e);
11426                 if (rc != 0)
11427                         return;
11428
11429                 if (e.timestamp == 0)
11430                         return;
11431
11432                 e.timestamp = be64toh(e.timestamp);
11433                 e.seqno = be32toh(e.seqno);
11434                 for (j = 0; j < 8; j++)
11435                         e.params[j] = be32toh(e.params[j]);
11436
11437                 db_printf("%10d  %15ju  %8s  %8s  ",
11438                     e.seqno, e.timestamp,
11439                     (e.level < nitems(devlog_level_strings) ?
11440                         devlog_level_strings[e.level] : "UNKNOWN"),
11441                     (e.facility < nitems(devlog_facility_strings) ?
11442                         devlog_facility_strings[e.facility] : "UNKNOWN"));
11443                 db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
11444                     e.params[3], e.params[4], e.params[5], e.params[6],
11445                     e.params[7]);
11446
11447                 if (++i == nentries)
11448                         i = 0;
11449         } while (i != first && !db_pager_quit);
11450 }
11451
11452 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
11453 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
11454
11455 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
11456 {
11457         device_t dev;
11458         int t;
11459         bool valid;
11460
11461         valid = false;
11462         t = db_read_token();
11463         if (t == tIDENT) {
11464                 dev = device_lookup_by_name(db_tok_string);
11465                 valid = true;
11466         }
11467         db_skip_to_eol();
11468         if (!valid) {
11469                 db_printf("usage: show t4 devlog <nexus>\n");
11470                 return;
11471         }
11472
11473         if (dev == NULL) {
11474                 db_printf("device not found\n");
11475                 return;
11476         }
11477
11478         t4_dump_devlog(device_get_softc(dev));
11479 }
11480
11481 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
11482 {
11483         device_t dev;
11484         int radix, tid, t;
11485         bool valid;
11486
11487         valid = false;
11488         radix = db_radix;
11489         db_radix = 10;
11490         t = db_read_token();
11491         if (t == tIDENT) {
11492                 dev = device_lookup_by_name(db_tok_string);
11493                 t = db_read_token();
11494                 if (t == tNUMBER) {
11495                         tid = db_tok_number;
11496                         valid = true;
11497                 }
11498         }       
11499         db_radix = radix;
11500         db_skip_to_eol();
11501         if (!valid) {
11502                 db_printf("usage: show t4 tcb <nexus> <tid>\n");
11503                 return;
11504         }
11505
11506         if (dev == NULL) {
11507                 db_printf("device not found\n");
11508                 return;
11509         }
11510         if (tid < 0) {
11511                 db_printf("invalid tid\n");
11512                 return;
11513         }
11514
11515         t4_dump_tcb(device_get_softc(dev), tid);
11516 }
11517 #endif
11518
11519 static eventhandler_tag vxlan_start_evtag;
11520 static eventhandler_tag vxlan_stop_evtag;
11521
11522 struct vxlan_evargs {
11523         struct ifnet *ifp;
11524         uint16_t port;
11525 };
11526
11527 static void
11528 t4_vxlan_start(struct adapter *sc, void *arg)
11529 {
11530         struct vxlan_evargs *v = arg;
11531         struct port_info *pi;
11532         uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
11533         int i, rc;
11534
11535         if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
11536                 return;
11537         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
11538                 return;
11539
11540         if (sc->vxlan_refcount == 0) {
11541                 sc->vxlan_port = v->port;
11542                 sc->vxlan_refcount = 1;
11543                 t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE,
11544                     V_VXLAN(v->port) | F_VXLAN_EN);
11545                 for_each_port(sc, i) {
11546                         pi = sc->port[i];
11547                         if (pi->vxlan_tcam_entry == true)
11548                                 continue;
11549                         rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid,
11550                             match_all_mac, match_all_mac,
11551                             sc->rawf_base + pi->port_id, 1, pi->port_id, true);
11552                         if (rc < 0) {
11553                                 rc = -rc;
11554                                 log(LOG_ERR,
11555                                     "%s: failed to add VXLAN TCAM entry: %d.\n",
11556                                     device_get_name(pi->vi[0].dev), rc);
11557                         } else {
11558                                 MPASS(rc == sc->rawf_base + pi->port_id);
11559                                 rc = 0;
11560                                 pi->vxlan_tcam_entry = true;
11561                         }
11562                 }
11563         } else if (sc->vxlan_port == v->port) {
11564                 sc->vxlan_refcount++;
11565         } else {
11566                 log(LOG_ERR, "%s: VXLAN already configured on port  %d; "
11567                     "ignoring attempt to configure it on port %d\n",
11568                     device_get_nameunit(sc->dev), sc->vxlan_port, v->port);
11569         }
11570         end_synchronized_op(sc, 0);
11571 }
11572
11573 static void
11574 t4_vxlan_stop(struct adapter *sc, void *arg)
11575 {
11576         struct vxlan_evargs *v = arg;
11577
11578         if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
11579                 return;
11580         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
11581                 return;
11582
11583         /*
11584          * VXLANs may have been configured before the driver was loaded so we
11585          * may see more stops than starts.  This is not handled cleanly but at
11586          * least we keep the refcount sane.
11587          */
11588         if (sc->vxlan_port != v->port)
11589                 goto done;
11590         if (sc->vxlan_refcount == 0) {
11591                 log(LOG_ERR,
11592                     "%s: VXLAN operation on port %d was stopped earlier; "
11593                     "ignoring attempt to stop it again.\n",
11594                     device_get_nameunit(sc->dev), sc->vxlan_port);
11595         } else if (--sc->vxlan_refcount == 0) {
11596                 t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
11597         }
11598 done:
11599         end_synchronized_op(sc, 0);
11600 }
11601
11602 static void
11603 t4_vxlan_start_handler(void *arg __unused, struct ifnet *ifp,
11604     sa_family_t family, u_int port)
11605 {
11606         struct vxlan_evargs v;
11607
11608         MPASS(family == AF_INET || family == AF_INET6);
11609         v.ifp = ifp;
11610         v.port = port;
11611
11612         t4_iterate(t4_vxlan_start, &v);
11613 }
11614
11615 static void
11616 t4_vxlan_stop_handler(void *arg __unused, struct ifnet *ifp, sa_family_t family,
11617     u_int port)
11618 {
11619         struct vxlan_evargs v;
11620
11621         MPASS(family == AF_INET || family == AF_INET6);
11622         v.ifp = ifp;
11623         v.port = port;
11624
11625         t4_iterate(t4_vxlan_stop, &v);
11626 }
11627
11628
11629 static struct sx mlu;   /* mod load unload */
11630 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
11631
11632 static int
11633 mod_event(module_t mod, int cmd, void *arg)
11634 {
11635         int rc = 0;
11636         static int loaded = 0;
11637
11638         switch (cmd) {
11639         case MOD_LOAD:
11640                 sx_xlock(&mlu);
11641                 if (loaded++ == 0) {
11642                         t4_sge_modload();
11643                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
11644                             t4_filter_rpl, CPL_COOKIE_FILTER);
11645                         t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
11646                             do_l2t_write_rpl, CPL_COOKIE_FILTER);
11647                         t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
11648                             t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
11649                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
11650                             t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
11651                         t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
11652                             t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
11653                         t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
11654                         t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
11655                         t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
11656                             do_smt_write_rpl);
11657                         sx_init(&t4_list_lock, "T4/T5 adapters");
11658                         SLIST_INIT(&t4_list);
11659                         callout_init(&fatal_callout, 1);
11660 #ifdef TCP_OFFLOAD
11661                         sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
11662                         SLIST_INIT(&t4_uld_list);
11663 #endif
11664 #ifdef INET6
11665                         t4_clip_modload();
11666 #endif
11667 #ifdef KERN_TLS
11668                         t6_ktls_modload();
11669 #endif
11670                         t4_tracer_modload();
11671                         tweak_tunables();
11672                         vxlan_start_evtag =
11673                             EVENTHANDLER_REGISTER(vxlan_start,
11674                                 t4_vxlan_start_handler, NULL,
11675                                 EVENTHANDLER_PRI_ANY);
11676                         vxlan_stop_evtag =
11677                             EVENTHANDLER_REGISTER(vxlan_stop,
11678                                 t4_vxlan_stop_handler, NULL,
11679                                 EVENTHANDLER_PRI_ANY);
11680                 }
11681                 sx_xunlock(&mlu);
11682                 break;
11683
11684         case MOD_UNLOAD:
11685                 sx_xlock(&mlu);
11686                 if (--loaded == 0) {
11687                         int tries;
11688
11689                         sx_slock(&t4_list_lock);
11690                         if (!SLIST_EMPTY(&t4_list)) {
11691                                 rc = EBUSY;
11692                                 sx_sunlock(&t4_list_lock);
11693                                 goto done_unload;
11694                         }
11695 #ifdef TCP_OFFLOAD
11696                         sx_slock(&t4_uld_list_lock);
11697                         if (!SLIST_EMPTY(&t4_uld_list)) {
11698                                 rc = EBUSY;
11699                                 sx_sunlock(&t4_uld_list_lock);
11700                                 sx_sunlock(&t4_list_lock);
11701                                 goto done_unload;
11702                         }
11703 #endif
11704                         tries = 0;
11705                         while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
11706                                 uprintf("%ju clusters with custom free routine "
11707                                     "still is use.\n", t4_sge_extfree_refs());
11708                                 pause("t4unload", 2 * hz);
11709                         }
11710 #ifdef TCP_OFFLOAD
11711                         sx_sunlock(&t4_uld_list_lock);
11712 #endif
11713                         sx_sunlock(&t4_list_lock);
11714
11715                         if (t4_sge_extfree_refs() == 0) {
11716                                 EVENTHANDLER_DEREGISTER(vxlan_start,
11717                                     vxlan_start_evtag);
11718                                 EVENTHANDLER_DEREGISTER(vxlan_stop,
11719                                     vxlan_stop_evtag);
11720                                 t4_tracer_modunload();
11721 #ifdef KERN_TLS
11722                                 t6_ktls_modunload();
11723 #endif
11724 #ifdef INET6
11725                                 t4_clip_modunload();
11726 #endif
11727 #ifdef TCP_OFFLOAD
11728                                 sx_destroy(&t4_uld_list_lock);
11729 #endif
11730                                 sx_destroy(&t4_list_lock);
11731                                 t4_sge_modunload();
11732                                 loaded = 0;
11733                         } else {
11734                                 rc = EBUSY;
11735                                 loaded++;       /* undo earlier decrement */
11736                         }
11737                 }
11738 done_unload:
11739                 sx_xunlock(&mlu);
11740                 break;
11741         }
11742
11743         return (rc);
11744 }
11745
11746 static devclass_t t4_devclass, t5_devclass, t6_devclass;
11747 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
11748 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
11749
11750 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
11751 MODULE_VERSION(t4nex, 1);
11752 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
11753 #ifdef DEV_NETMAP
11754 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
11755 #endif /* DEV_NETMAP */
11756
11757 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
11758 MODULE_VERSION(t5nex, 1);
11759 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
11760 #ifdef DEV_NETMAP
11761 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
11762 #endif /* DEV_NETMAP */
11763
11764 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
11765 MODULE_VERSION(t6nex, 1);
11766 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
11767 #ifdef DEV_NETMAP
11768 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
11769 #endif /* DEV_NETMAP */
11770
11771 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
11772 MODULE_VERSION(cxgbe, 1);
11773
11774 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
11775 MODULE_VERSION(cxl, 1);
11776
11777 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
11778 MODULE_VERSION(cc, 1);
11779
11780 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
11781 MODULE_VERSION(vcxgbe, 1);
11782
11783 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
11784 MODULE_VERSION(vcxl, 1);
11785
11786 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
11787 MODULE_VERSION(vcc, 1);