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