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