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