]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/t4_main.c
cxgbe(4): Simplify the firmware version checks a bit.
[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 &&
4255                     sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
4256                         rc = 0;
4257                 }
4258                 if (rc != 0) {
4259                         device_printf(sc->dev,
4260                             "failed to enable high priority filters :%d.\n",
4261                             rc);
4262                 }
4263         }
4264
4265         /* Enable opaque VIIDs with firmwares that support it. */
4266         param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
4267         val = 1;
4268         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4269         if (rc == 0 && val == 1)
4270                 sc->params.viid_smt_extn_support = true;
4271         else
4272                 sc->params.viid_smt_extn_support = false;
4273
4274         return (rc);
4275 }
4276
4277 /*
4278  * Retrieve various parameters that are of interest to the driver.  The device
4279  * has been initialized by the firmware at this point.
4280  */
4281 static int
4282 get_params__post_init(struct adapter *sc)
4283 {
4284         int rc;
4285         uint32_t param[7], val[7];
4286         struct fw_caps_config_cmd caps;
4287
4288         param[0] = FW_PARAM_PFVF(IQFLINT_START);
4289         param[1] = FW_PARAM_PFVF(EQ_START);
4290         param[2] = FW_PARAM_PFVF(FILTER_START);
4291         param[3] = FW_PARAM_PFVF(FILTER_END);
4292         param[4] = FW_PARAM_PFVF(L2T_START);
4293         param[5] = FW_PARAM_PFVF(L2T_END);
4294         param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
4295             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
4296             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
4297         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
4298         if (rc != 0) {
4299                 device_printf(sc->dev,
4300                     "failed to query parameters (post_init): %d.\n", rc);
4301                 return (rc);
4302         }
4303
4304         sc->sge.iq_start = val[0];
4305         sc->sge.eq_start = val[1];
4306         if ((int)val[3] > (int)val[2]) {
4307                 sc->tids.ftid_base = val[2];
4308                 sc->tids.ftid_end = val[3];
4309                 sc->tids.nftids = val[3] - val[2] + 1;
4310         }
4311         sc->vres.l2t.start = val[4];
4312         sc->vres.l2t.size = val[5] - val[4] + 1;
4313         KASSERT(sc->vres.l2t.size <= L2T_SIZE,
4314             ("%s: L2 table size (%u) larger than expected (%u)",
4315             __func__, sc->vres.l2t.size, L2T_SIZE));
4316         sc->params.core_vdd = val[6];
4317
4318         if (chip_id(sc) >= CHELSIO_T6) {
4319
4320                 sc->tids.tid_base = t4_read_reg(sc,
4321                     A_LE_DB_ACTIVE_TABLE_START_INDEX);
4322
4323                 param[0] = FW_PARAM_PFVF(HPFILTER_START);
4324                 param[1] = FW_PARAM_PFVF(HPFILTER_END);
4325                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4326                 if (rc != 0) {
4327                         device_printf(sc->dev,
4328                            "failed to query hpfilter parameters: %d.\n", rc);
4329                         return (rc);
4330                 }
4331                 if ((int)val[1] > (int)val[0]) {
4332                         sc->tids.hpftid_base = val[0];
4333                         sc->tids.hpftid_end = val[1];
4334                         sc->tids.nhpftids = val[1] - val[0] + 1;
4335
4336                         /*
4337                          * These should go off if the layout changes and the
4338                          * driver needs to catch up.
4339                          */
4340                         MPASS(sc->tids.hpftid_base == 0);
4341                         MPASS(sc->tids.tid_base == sc->tids.nhpftids);
4342                 }
4343         }
4344
4345         /*
4346          * MPSBGMAP is queried separately because only recent firmwares support
4347          * it as a parameter and we don't want the compound query above to fail
4348          * on older firmwares.
4349          */
4350         param[0] = FW_PARAM_DEV(MPSBGMAP);
4351         val[0] = 0;
4352         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4353         if (rc == 0)
4354                 sc->params.mps_bg_map = val[0];
4355         else
4356                 sc->params.mps_bg_map = 0;
4357
4358         /*
4359          * Determine whether the firmware supports the filter2 work request.
4360          * This is queried separately for the same reason as MPSBGMAP above.
4361          */
4362         param[0] = FW_PARAM_DEV(FILTER2_WR);
4363         val[0] = 0;
4364         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4365         if (rc == 0)
4366                 sc->params.filter2_wr_support = val[0] != 0;
4367         else
4368                 sc->params.filter2_wr_support = 0;
4369
4370         /*
4371          * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
4372          * This is queried separately for the same reason as other params above.
4373          */
4374         param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
4375         val[0] = 0;
4376         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4377         if (rc == 0)
4378                 sc->params.ulptx_memwrite_dsgl = val[0] != 0;
4379         else
4380                 sc->params.ulptx_memwrite_dsgl = false;
4381
4382         /* get capabilites */
4383         bzero(&caps, sizeof(caps));
4384         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4385             F_FW_CMD_REQUEST | F_FW_CMD_READ);
4386         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4387         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4388         if (rc != 0) {
4389                 device_printf(sc->dev,
4390                     "failed to get card capabilities: %d.\n", rc);
4391                 return (rc);
4392         }
4393
4394 #define READ_CAPS(x) do { \
4395         sc->x = htobe16(caps.x); \
4396 } while (0)
4397         READ_CAPS(nbmcaps);
4398         READ_CAPS(linkcaps);
4399         READ_CAPS(switchcaps);
4400         READ_CAPS(niccaps);
4401         READ_CAPS(toecaps);
4402         READ_CAPS(rdmacaps);
4403         READ_CAPS(cryptocaps);
4404         READ_CAPS(iscsicaps);
4405         READ_CAPS(fcoecaps);
4406
4407         if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
4408                 MPASS(chip_id(sc) > CHELSIO_T4);
4409                 MPASS(sc->toecaps == 0);
4410                 sc->toecaps = 0;
4411
4412                 param[0] = FW_PARAM_DEV(NTID);
4413                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4414                 if (rc != 0) {
4415                         device_printf(sc->dev,
4416                             "failed to query HASHFILTER parameters: %d.\n", rc);
4417                         return (rc);
4418                 }
4419                 sc->tids.ntids = val[0];
4420                 if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
4421                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4422                         sc->tids.ntids -= sc->tids.nhpftids;
4423                 }
4424                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4425                 sc->params.hash_filter = 1;
4426         }
4427         if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
4428                 param[0] = FW_PARAM_PFVF(ETHOFLD_START);
4429                 param[1] = FW_PARAM_PFVF(ETHOFLD_END);
4430                 param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4431                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
4432                 if (rc != 0) {
4433                         device_printf(sc->dev,
4434                             "failed to query NIC parameters: %d.\n", rc);
4435                         return (rc);
4436                 }
4437                 if ((int)val[1] > (int)val[0]) {
4438                         sc->tids.etid_base = val[0];
4439                         sc->tids.etid_end = val[1];
4440                         sc->tids.netids = val[1] - val[0] + 1;
4441                         sc->params.eo_wr_cred = val[2];
4442                         sc->params.ethoffload = 1;
4443                 }
4444         }
4445         if (sc->toecaps) {
4446                 /* query offload-related parameters */
4447                 param[0] = FW_PARAM_DEV(NTID);
4448                 param[1] = FW_PARAM_PFVF(SERVER_START);
4449                 param[2] = FW_PARAM_PFVF(SERVER_END);
4450                 param[3] = FW_PARAM_PFVF(TDDP_START);
4451                 param[4] = FW_PARAM_PFVF(TDDP_END);
4452                 param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4453                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4454                 if (rc != 0) {
4455                         device_printf(sc->dev,
4456                             "failed to query TOE parameters: %d.\n", rc);
4457                         return (rc);
4458                 }
4459                 sc->tids.ntids = val[0];
4460                 if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
4461                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4462                         sc->tids.ntids -= sc->tids.nhpftids;
4463                 }
4464                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4465                 if ((int)val[2] > (int)val[1]) {
4466                         sc->tids.stid_base = val[1];
4467                         sc->tids.nstids = val[2] - val[1] + 1;
4468                 }
4469                 sc->vres.ddp.start = val[3];
4470                 sc->vres.ddp.size = val[4] - val[3] + 1;
4471                 sc->params.ofldq_wr_cred = val[5];
4472                 sc->params.offload = 1;
4473         } else {
4474                 /*
4475                  * The firmware attempts memfree TOE configuration for -SO cards
4476                  * and will report toecaps=0 if it runs out of resources (this
4477                  * depends on the config file).  It may not report 0 for other
4478                  * capabilities dependent on the TOE in this case.  Set them to
4479                  * 0 here so that the driver doesn't bother tracking resources
4480                  * that will never be used.
4481                  */
4482                 sc->iscsicaps = 0;
4483                 sc->rdmacaps = 0;
4484         }
4485         if (sc->rdmacaps) {
4486                 param[0] = FW_PARAM_PFVF(STAG_START);
4487                 param[1] = FW_PARAM_PFVF(STAG_END);
4488                 param[2] = FW_PARAM_PFVF(RQ_START);
4489                 param[3] = FW_PARAM_PFVF(RQ_END);
4490                 param[4] = FW_PARAM_PFVF(PBL_START);
4491                 param[5] = FW_PARAM_PFVF(PBL_END);
4492                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4493                 if (rc != 0) {
4494                         device_printf(sc->dev,
4495                             "failed to query RDMA parameters(1): %d.\n", rc);
4496                         return (rc);
4497                 }
4498                 sc->vres.stag.start = val[0];
4499                 sc->vres.stag.size = val[1] - val[0] + 1;
4500                 sc->vres.rq.start = val[2];
4501                 sc->vres.rq.size = val[3] - val[2] + 1;
4502                 sc->vres.pbl.start = val[4];
4503                 sc->vres.pbl.size = val[5] - val[4] + 1;
4504
4505                 param[0] = FW_PARAM_PFVF(SQRQ_START);
4506                 param[1] = FW_PARAM_PFVF(SQRQ_END);
4507                 param[2] = FW_PARAM_PFVF(CQ_START);
4508                 param[3] = FW_PARAM_PFVF(CQ_END);
4509                 param[4] = FW_PARAM_PFVF(OCQ_START);
4510                 param[5] = FW_PARAM_PFVF(OCQ_END);
4511                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4512                 if (rc != 0) {
4513                         device_printf(sc->dev,
4514                             "failed to query RDMA parameters(2): %d.\n", rc);
4515                         return (rc);
4516                 }
4517                 sc->vres.qp.start = val[0];
4518                 sc->vres.qp.size = val[1] - val[0] + 1;
4519                 sc->vres.cq.start = val[2];
4520                 sc->vres.cq.size = val[3] - val[2] + 1;
4521                 sc->vres.ocq.start = val[4];
4522                 sc->vres.ocq.size = val[5] - val[4] + 1;
4523
4524                 param[0] = FW_PARAM_PFVF(SRQ_START);
4525                 param[1] = FW_PARAM_PFVF(SRQ_END);
4526                 param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
4527                 param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
4528                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
4529                 if (rc != 0) {
4530                         device_printf(sc->dev,
4531                             "failed to query RDMA parameters(3): %d.\n", rc);
4532                         return (rc);
4533                 }
4534                 sc->vres.srq.start = val[0];
4535                 sc->vres.srq.size = val[1] - val[0] + 1;
4536                 sc->params.max_ordird_qp = val[2];
4537                 sc->params.max_ird_adapter = val[3];
4538         }
4539         if (sc->iscsicaps) {
4540                 param[0] = FW_PARAM_PFVF(ISCSI_START);
4541                 param[1] = FW_PARAM_PFVF(ISCSI_END);
4542                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4543                 if (rc != 0) {
4544                         device_printf(sc->dev,
4545                             "failed to query iSCSI parameters: %d.\n", rc);
4546                         return (rc);
4547                 }
4548                 sc->vres.iscsi.start = val[0];
4549                 sc->vres.iscsi.size = val[1] - val[0] + 1;
4550         }
4551         if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
4552                 param[0] = FW_PARAM_PFVF(TLS_START);
4553                 param[1] = FW_PARAM_PFVF(TLS_END);
4554                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4555                 if (rc != 0) {
4556                         device_printf(sc->dev,
4557                             "failed to query TLS parameters: %d.\n", rc);
4558                         return (rc);
4559                 }
4560                 sc->vres.key.start = val[0];
4561                 sc->vres.key.size = val[1] - val[0] + 1;
4562         }
4563
4564         t4_init_sge_params(sc);
4565
4566         /*
4567          * We've got the params we wanted to query via the firmware.  Now grab
4568          * some others directly from the chip.
4569          */
4570         rc = t4_read_chip_settings(sc);
4571
4572         return (rc);
4573 }
4574
4575 #ifdef KERN_TLS
4576 static void
4577 ktls_tick(void *arg)
4578 {
4579         struct adapter *sc;
4580         uint32_t tstamp;
4581
4582         sc = arg;
4583
4584         tstamp = tcp_ts_getticks();
4585         t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
4586         t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
4587
4588         callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
4589 }
4590
4591 static void
4592 t4_enable_kern_tls(struct adapter *sc)
4593 {
4594         uint32_t m, v;
4595
4596         m = F_ENABLECBYP;
4597         v = F_ENABLECBYP;
4598         t4_set_reg_field(sc, A_TP_PARA_REG6, m, v);
4599
4600         m = F_CPL_FLAGS_UPDATE_EN | F_SEQ_UPDATE_EN;
4601         v = F_CPL_FLAGS_UPDATE_EN | F_SEQ_UPDATE_EN;
4602         t4_set_reg_field(sc, A_ULP_TX_CONFIG, m, v);
4603
4604         m = F_NICMODE;
4605         v = F_NICMODE;
4606         t4_set_reg_field(sc, A_TP_IN_CONFIG, m, v);
4607
4608         m = F_LOOKUPEVERYPKT;
4609         v = 0;
4610         t4_set_reg_field(sc, A_TP_INGRESS_CONFIG, m, v);
4611
4612         m = F_TXDEFERENABLE | F_DISABLEWINDOWPSH | F_DISABLESEPPSHFLAG;
4613         v = F_DISABLEWINDOWPSH;
4614         t4_set_reg_field(sc, A_TP_PC_CONFIG, m, v);
4615
4616         m = V_TIMESTAMPRESOLUTION(M_TIMESTAMPRESOLUTION);
4617         v = V_TIMESTAMPRESOLUTION(0x1f);
4618         t4_set_reg_field(sc, A_TP_TIMER_RESOLUTION, m, v);
4619
4620         sc->flags |= KERN_TLS_OK;
4621
4622         sc->tlst.inline_keys = t4_tls_inline_keys;
4623         sc->tlst.combo_wrs = t4_tls_combo_wrs;
4624 }
4625 #endif
4626
4627 static int
4628 set_params__post_init(struct adapter *sc)
4629 {
4630         uint32_t param, val;
4631 #ifdef TCP_OFFLOAD
4632         int i, v, shift;
4633 #endif
4634
4635         /* ask for encapsulated CPLs */
4636         param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
4637         val = 1;
4638         (void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4639
4640         /* Enable 32b port caps if the firmware supports it. */
4641         param = FW_PARAM_PFVF(PORT_CAPS32);
4642         val = 1;
4643         if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
4644                 sc->params.port_caps32 = 1;
4645
4646         /* Let filter + maskhash steer to a part of the VI's RSS region. */
4647         val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
4648         t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
4649             V_MASKFILTER(val - 1));
4650
4651 #ifdef TCP_OFFLOAD
4652         /*
4653          * Override the TOE timers with user provided tunables.  This is not the
4654          * recommended way to change the timers (the firmware config file is) so
4655          * these tunables are not documented.
4656          *
4657          * All the timer tunables are in microseconds.
4658          */
4659         if (t4_toe_keepalive_idle != 0) {
4660                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
4661                 v &= M_KEEPALIVEIDLE;
4662                 t4_set_reg_field(sc, A_TP_KEEP_IDLE,
4663                     V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
4664         }
4665         if (t4_toe_keepalive_interval != 0) {
4666                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
4667                 v &= M_KEEPALIVEINTVL;
4668                 t4_set_reg_field(sc, A_TP_KEEP_INTVL,
4669                     V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
4670         }
4671         if (t4_toe_keepalive_count != 0) {
4672                 v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
4673                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4674                     V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
4675                     V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
4676                     V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
4677         }
4678         if (t4_toe_rexmt_min != 0) {
4679                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
4680                 v &= M_RXTMIN;
4681                 t4_set_reg_field(sc, A_TP_RXT_MIN,
4682                     V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
4683         }
4684         if (t4_toe_rexmt_max != 0) {
4685                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
4686                 v &= M_RXTMAX;
4687                 t4_set_reg_field(sc, A_TP_RXT_MAX,
4688                     V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
4689         }
4690         if (t4_toe_rexmt_count != 0) {
4691                 v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
4692                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4693                     V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
4694                     V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
4695                     V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
4696         }
4697         for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
4698                 if (t4_toe_rexmt_backoff[i] != -1) {
4699                         v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
4700                         shift = (i & 3) << 3;
4701                         t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
4702                             M_TIMERBACKOFFINDEX0 << shift, v << shift);
4703                 }
4704         }
4705 #endif
4706
4707 #ifdef KERN_TLS
4708         if (t4_kern_tls != 0 && sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
4709             sc->toecaps & FW_CAPS_CONFIG_TOE)
4710                 t4_enable_kern_tls(sc);
4711 #endif
4712         return (0);
4713 }
4714
4715 #undef FW_PARAM_PFVF
4716 #undef FW_PARAM_DEV
4717
4718 static void
4719 t4_set_desc(struct adapter *sc)
4720 {
4721         char buf[128];
4722         struct adapter_params *p = &sc->params;
4723
4724         snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
4725
4726         device_set_desc_copy(sc->dev, buf);
4727 }
4728
4729 static inline void
4730 ifmedia_add4(struct ifmedia *ifm, int m)
4731 {
4732
4733         ifmedia_add(ifm, m, 0, NULL);
4734         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
4735         ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
4736         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
4737 }
4738
4739 /*
4740  * This is the selected media, which is not quite the same as the active media.
4741  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
4742  * and active are not the same, and "media: Ethernet selected" otherwise.
4743  */
4744 static void
4745 set_current_media(struct port_info *pi)
4746 {
4747         struct link_config *lc;
4748         struct ifmedia *ifm;
4749         int mword;
4750         u_int speed;
4751
4752         PORT_LOCK_ASSERT_OWNED(pi);
4753
4754         /* Leave current media alone if it's already set to IFM_NONE. */
4755         ifm = &pi->media;
4756         if (ifm->ifm_cur != NULL &&
4757             IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
4758                 return;
4759
4760         lc = &pi->link_cfg;
4761         if (lc->requested_aneg != AUTONEG_DISABLE &&
4762             lc->pcaps & FW_PORT_CAP32_ANEG) {
4763                 ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
4764                 return;
4765         }
4766         mword = IFM_ETHER | IFM_FDX;
4767         if (lc->requested_fc & PAUSE_TX)
4768                 mword |= IFM_ETH_TXPAUSE;
4769         if (lc->requested_fc & PAUSE_RX)
4770                 mword |= IFM_ETH_RXPAUSE;
4771         if (lc->requested_speed == 0)
4772                 speed = port_top_speed(pi) * 1000;      /* Gbps -> Mbps */
4773         else
4774                 speed = lc->requested_speed;
4775         mword |= port_mword(pi, speed_to_fwcap(speed));
4776         ifmedia_set(ifm, mword);
4777 }
4778
4779 /*
4780  * Returns true if the ifmedia list for the port cannot change.
4781  */
4782 static bool
4783 fixed_ifmedia(struct port_info *pi)
4784 {
4785
4786         return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
4787             pi->port_type == FW_PORT_TYPE_BT_XFI ||
4788             pi->port_type == FW_PORT_TYPE_BT_XAUI ||
4789             pi->port_type == FW_PORT_TYPE_KX4 ||
4790             pi->port_type == FW_PORT_TYPE_KX ||
4791             pi->port_type == FW_PORT_TYPE_KR ||
4792             pi->port_type == FW_PORT_TYPE_BP_AP ||
4793             pi->port_type == FW_PORT_TYPE_BP4_AP ||
4794             pi->port_type == FW_PORT_TYPE_BP40_BA ||
4795             pi->port_type == FW_PORT_TYPE_KR4_100G ||
4796             pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
4797             pi->port_type == FW_PORT_TYPE_KR_XLAUI);
4798 }
4799
4800 static void
4801 build_medialist(struct port_info *pi)
4802 {
4803         uint32_t ss, speed;
4804         int unknown, mword, bit;
4805         struct link_config *lc;
4806         struct ifmedia *ifm;
4807
4808         PORT_LOCK_ASSERT_OWNED(pi);
4809
4810         if (pi->flags & FIXED_IFMEDIA)
4811                 return;
4812
4813         /*
4814          * Rebuild the ifmedia list.
4815          */
4816         ifm = &pi->media;
4817         ifmedia_removeall(ifm);
4818         lc = &pi->link_cfg;
4819         ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
4820         if (__predict_false(ss == 0)) { /* not supposed to happen. */
4821                 MPASS(ss != 0);
4822 no_media:
4823                 MPASS(LIST_EMPTY(&ifm->ifm_list));
4824                 ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
4825                 ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
4826                 return;
4827         }
4828
4829         unknown = 0;
4830         for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
4831                 speed = 1 << bit;
4832                 MPASS(speed & M_FW_PORT_CAP32_SPEED);
4833                 if (ss & speed) {
4834                         mword = port_mword(pi, speed);
4835                         if (mword == IFM_NONE) {
4836                                 goto no_media;
4837                         } else if (mword == IFM_UNKNOWN)
4838                                 unknown++;
4839                         else
4840                                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
4841                 }
4842         }
4843         if (unknown > 0) /* Add one unknown for all unknown media types. */
4844                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
4845         if (lc->pcaps & FW_PORT_CAP32_ANEG)
4846                 ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
4847
4848         set_current_media(pi);
4849 }
4850
4851 /*
4852  * Initialize the requested fields in the link config based on driver tunables.
4853  */
4854 static void
4855 init_link_config(struct port_info *pi)
4856 {
4857         struct link_config *lc = &pi->link_cfg;
4858
4859         PORT_LOCK_ASSERT_OWNED(pi);
4860
4861         lc->requested_speed = 0;
4862
4863         if (t4_autoneg == 0)
4864                 lc->requested_aneg = AUTONEG_DISABLE;
4865         else if (t4_autoneg == 1)
4866                 lc->requested_aneg = AUTONEG_ENABLE;
4867         else
4868                 lc->requested_aneg = AUTONEG_AUTO;
4869
4870         lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
4871             PAUSE_AUTONEG);
4872
4873         if (t4_fec & FEC_AUTO)
4874                 lc->requested_fec = FEC_AUTO;
4875         else if (t4_fec == 0)
4876                 lc->requested_fec = FEC_NONE;
4877         else {
4878                 /* -1 is handled by the FEC_AUTO block above and not here. */
4879                 lc->requested_fec = t4_fec &
4880                     (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
4881                 if (lc->requested_fec == 0)
4882                         lc->requested_fec = FEC_AUTO;
4883         }
4884 }
4885
4886 /*
4887  * Makes sure that all requested settings comply with what's supported by the
4888  * port.  Returns the number of settings that were invalid and had to be fixed.
4889  */
4890 static int
4891 fixup_link_config(struct port_info *pi)
4892 {
4893         int n = 0;
4894         struct link_config *lc = &pi->link_cfg;
4895         uint32_t fwspeed;
4896
4897         PORT_LOCK_ASSERT_OWNED(pi);
4898
4899         /* Speed (when not autonegotiating) */
4900         if (lc->requested_speed != 0) {
4901                 fwspeed = speed_to_fwcap(lc->requested_speed);
4902                 if ((fwspeed & lc->pcaps) == 0) {
4903                         n++;
4904                         lc->requested_speed = 0;
4905                 }
4906         }
4907
4908         /* Link autonegotiation */
4909         MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
4910             lc->requested_aneg == AUTONEG_DISABLE ||
4911             lc->requested_aneg == AUTONEG_AUTO);
4912         if (lc->requested_aneg == AUTONEG_ENABLE &&
4913             !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
4914                 n++;
4915                 lc->requested_aneg = AUTONEG_AUTO;
4916         }
4917
4918         /* Flow control */
4919         MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
4920         if (lc->requested_fc & PAUSE_TX &&
4921             !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
4922                 n++;
4923                 lc->requested_fc &= ~PAUSE_TX;
4924         }
4925         if (lc->requested_fc & PAUSE_RX &&
4926             !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
4927                 n++;
4928                 lc->requested_fc &= ~PAUSE_RX;
4929         }
4930         if (!(lc->requested_fc & PAUSE_AUTONEG) &&
4931             !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
4932                 n++;
4933                 lc->requested_fc |= PAUSE_AUTONEG;
4934         }
4935
4936         /* FEC */
4937         if ((lc->requested_fec & FEC_RS &&
4938             !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
4939             (lc->requested_fec & FEC_BASER_RS &&
4940             !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
4941                 n++;
4942                 lc->requested_fec = FEC_AUTO;
4943         }
4944
4945         return (n);
4946 }
4947
4948 /*
4949  * Apply the requested L1 settings, which are expected to be valid, to the
4950  * hardware.
4951  */
4952 static int
4953 apply_link_config(struct port_info *pi)
4954 {
4955         struct adapter *sc = pi->adapter;
4956         struct link_config *lc = &pi->link_cfg;
4957         int rc;
4958
4959 #ifdef INVARIANTS
4960         ASSERT_SYNCHRONIZED_OP(sc);
4961         PORT_LOCK_ASSERT_OWNED(pi);
4962
4963         if (lc->requested_aneg == AUTONEG_ENABLE)
4964                 MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
4965         if (!(lc->requested_fc & PAUSE_AUTONEG))
4966                 MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
4967         if (lc->requested_fc & PAUSE_TX)
4968                 MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
4969         if (lc->requested_fc & PAUSE_RX)
4970                 MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
4971         if (lc->requested_fec & FEC_RS)
4972                 MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
4973         if (lc->requested_fec & FEC_BASER_RS)
4974                 MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
4975 #endif
4976         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
4977         if (rc != 0) {
4978                 /* Don't complain if the VF driver gets back an EPERM. */
4979                 if (!(sc->flags & IS_VF) || rc != FW_EPERM)
4980                         device_printf(pi->dev, "l1cfg failed: %d\n", rc);
4981         } else {
4982                 /*
4983                  * An L1_CFG will almost always result in a link-change event if
4984                  * the link is up, and the driver will refresh the actual
4985                  * fec/fc/etc. when the notification is processed.  If the link
4986                  * is down then the actual settings are meaningless.
4987                  *
4988                  * This takes care of the case where a change in the L1 settings
4989                  * may not result in a notification.
4990                  */
4991                 if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
4992                         lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
4993         }
4994         return (rc);
4995 }
4996
4997 #define FW_MAC_EXACT_CHUNK      7
4998 struct mcaddr_ctx {
4999         struct ifnet *ifp;
5000         const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
5001         uint64_t hash;
5002         int i;
5003         int del;
5004         int rc;
5005 };
5006
5007 static u_int
5008 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
5009 {
5010         struct mcaddr_ctx *ctx = arg;
5011         struct vi_info *vi = ctx->ifp->if_softc;
5012         struct port_info *pi = vi->pi;
5013         struct adapter *sc = pi->adapter;
5014
5015         if (ctx->rc < 0)
5016                 return (0);
5017
5018         ctx->mcaddr[ctx->i] = LLADDR(sdl);
5019         MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
5020         ctx->i++;
5021
5022         if (ctx->i == FW_MAC_EXACT_CHUNK) {
5023                 ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
5024                     ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
5025                 if (ctx->rc < 0) {
5026                         int j;
5027
5028                         for (j = 0; j < ctx->i; j++) {
5029                                 if_printf(ctx->ifp,
5030                                     "failed to add mc address"
5031                                     " %02x:%02x:%02x:"
5032                                     "%02x:%02x:%02x rc=%d\n",
5033                                     ctx->mcaddr[j][0], ctx->mcaddr[j][1],
5034                                     ctx->mcaddr[j][2], ctx->mcaddr[j][3],
5035                                     ctx->mcaddr[j][4], ctx->mcaddr[j][5],
5036                                     -ctx->rc);
5037                         }
5038                         return (0);
5039                 }
5040                 ctx->del = 0;
5041                 ctx->i = 0;
5042         }
5043
5044         return (1);
5045 }
5046
5047 /*
5048  * Program the port's XGMAC based on parameters in ifnet.  The caller also
5049  * indicates which parameters should be programmed (the rest are left alone).
5050  */
5051 int
5052 update_mac_settings(struct ifnet *ifp, int flags)
5053 {
5054         int rc = 0;
5055         struct vi_info *vi = ifp->if_softc;
5056         struct port_info *pi = vi->pi;
5057         struct adapter *sc = pi->adapter;
5058         int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
5059
5060         ASSERT_SYNCHRONIZED_OP(sc);
5061         KASSERT(flags, ("%s: not told what to update.", __func__));
5062
5063         if (flags & XGMAC_MTU)
5064                 mtu = ifp->if_mtu;
5065
5066         if (flags & XGMAC_PROMISC)
5067                 promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
5068
5069         if (flags & XGMAC_ALLMULTI)
5070                 allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
5071
5072         if (flags & XGMAC_VLANEX)
5073                 vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
5074
5075         if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
5076                 rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
5077                     allmulti, 1, vlanex, false);
5078                 if (rc) {
5079                         if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
5080                             rc);
5081                         return (rc);
5082                 }
5083         }
5084
5085         if (flags & XGMAC_UCADDR) {
5086                 uint8_t ucaddr[ETHER_ADDR_LEN];
5087
5088                 bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
5089                 rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
5090                     ucaddr, true, &vi->smt_idx);
5091                 if (rc < 0) {
5092                         rc = -rc;
5093                         if_printf(ifp, "change_mac failed: %d\n", rc);
5094                         return (rc);
5095                 } else {
5096                         vi->xact_addr_filt = rc;
5097                         rc = 0;
5098                 }
5099         }
5100
5101         if (flags & XGMAC_MCADDRS) {
5102                 struct epoch_tracker et;
5103                 struct mcaddr_ctx ctx;
5104                 int j;
5105
5106                 ctx.ifp = ifp;
5107                 ctx.hash = 0;
5108                 ctx.i = 0;
5109                 ctx.del = 1;
5110                 ctx.rc = 0;
5111                 /*
5112                  * Unlike other drivers, we accumulate list of pointers into
5113                  * interface address lists and we need to keep it safe even
5114                  * after if_foreach_llmaddr() returns, thus we must enter the
5115                  * network epoch.
5116                  */
5117                 NET_EPOCH_ENTER(et);
5118                 if_foreach_llmaddr(ifp, add_maddr, &ctx);
5119                 if (ctx.rc < 0) {
5120                         NET_EPOCH_EXIT(et);
5121                         rc = -ctx.rc;
5122                         return (rc);
5123                 }
5124                 if (ctx.i > 0) {
5125                         rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
5126                             ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
5127                         NET_EPOCH_EXIT(et);
5128                         if (rc < 0) {
5129                                 rc = -rc;
5130                                 for (j = 0; j < ctx.i; j++) {
5131                                         if_printf(ifp,
5132                                             "failed to add mc address"
5133                                             " %02x:%02x:%02x:"
5134                                             "%02x:%02x:%02x rc=%d\n",
5135                                             ctx.mcaddr[j][0], ctx.mcaddr[j][1],
5136                                             ctx.mcaddr[j][2], ctx.mcaddr[j][3],
5137                                             ctx.mcaddr[j][4], ctx.mcaddr[j][5],
5138                                             rc);
5139                                 }
5140                                 return (rc);
5141                         }
5142                 } else
5143                         NET_EPOCH_EXIT(et);
5144
5145                 rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
5146                 if (rc != 0)
5147                         if_printf(ifp, "failed to set mc address hash: %d", rc);
5148         }
5149
5150         return (rc);
5151 }
5152
5153 /*
5154  * {begin|end}_synchronized_op must be called from the same thread.
5155  */
5156 int
5157 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
5158     char *wmesg)
5159 {
5160         int rc, pri;
5161
5162 #ifdef WITNESS
5163         /* the caller thinks it's ok to sleep, but is it really? */
5164         if (flags & SLEEP_OK)
5165                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
5166                     "begin_synchronized_op");
5167 #endif
5168
5169         if (INTR_OK)
5170                 pri = PCATCH;
5171         else
5172                 pri = 0;
5173
5174         ADAPTER_LOCK(sc);
5175         for (;;) {
5176
5177                 if (vi && IS_DOOMED(vi)) {
5178                         rc = ENXIO;
5179                         goto done;
5180                 }
5181
5182                 if (!IS_BUSY(sc)) {
5183                         rc = 0;
5184                         break;
5185                 }
5186
5187                 if (!(flags & SLEEP_OK)) {
5188                         rc = EBUSY;
5189                         goto done;
5190                 }
5191
5192                 if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
5193                         rc = EINTR;
5194                         goto done;
5195                 }
5196         }
5197
5198         KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
5199         SET_BUSY(sc);
5200 #ifdef INVARIANTS
5201         sc->last_op = wmesg;
5202         sc->last_op_thr = curthread;
5203         sc->last_op_flags = flags;
5204 #endif
5205
5206 done:
5207         if (!(flags & HOLD_LOCK) || rc)
5208                 ADAPTER_UNLOCK(sc);
5209
5210         return (rc);
5211 }
5212
5213 /*
5214  * Tell if_ioctl and if_init that the VI is going away.  This is
5215  * special variant of begin_synchronized_op and must be paired with a
5216  * call to end_synchronized_op.
5217  */
5218 void
5219 doom_vi(struct adapter *sc, struct vi_info *vi)
5220 {
5221
5222         ADAPTER_LOCK(sc);
5223         SET_DOOMED(vi);
5224         wakeup(&sc->flags);
5225         while (IS_BUSY(sc))
5226                 mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
5227         SET_BUSY(sc);
5228 #ifdef INVARIANTS
5229         sc->last_op = "t4detach";
5230         sc->last_op_thr = curthread;
5231         sc->last_op_flags = 0;
5232 #endif
5233         ADAPTER_UNLOCK(sc);
5234 }
5235
5236 /*
5237  * {begin|end}_synchronized_op must be called from the same thread.
5238  */
5239 void
5240 end_synchronized_op(struct adapter *sc, int flags)
5241 {
5242
5243         if (flags & LOCK_HELD)
5244                 ADAPTER_LOCK_ASSERT_OWNED(sc);
5245         else
5246                 ADAPTER_LOCK(sc);
5247
5248         KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
5249         CLR_BUSY(sc);
5250         wakeup(&sc->flags);
5251         ADAPTER_UNLOCK(sc);
5252 }
5253
5254 static int
5255 cxgbe_init_synchronized(struct vi_info *vi)
5256 {
5257         struct port_info *pi = vi->pi;
5258         struct adapter *sc = pi->adapter;
5259         struct ifnet *ifp = vi->ifp;
5260         int rc = 0, i;
5261         struct sge_txq *txq;
5262
5263         ASSERT_SYNCHRONIZED_OP(sc);
5264
5265         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
5266                 return (0);     /* already running */
5267
5268         if (!(sc->flags & FULL_INIT_DONE) &&
5269             ((rc = adapter_full_init(sc)) != 0))
5270                 return (rc);    /* error message displayed already */
5271
5272         if (!(vi->flags & VI_INIT_DONE) &&
5273             ((rc = vi_full_init(vi)) != 0))
5274                 return (rc); /* error message displayed already */
5275
5276         rc = update_mac_settings(ifp, XGMAC_ALL);
5277         if (rc)
5278                 goto done;      /* error message displayed already */
5279
5280         PORT_LOCK(pi);
5281         if (pi->up_vis == 0) {
5282                 t4_update_port_info(pi);
5283                 fixup_link_config(pi);
5284                 build_medialist(pi);
5285                 apply_link_config(pi);
5286         }
5287
5288         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
5289         if (rc != 0) {
5290                 if_printf(ifp, "enable_vi failed: %d\n", rc);
5291                 PORT_UNLOCK(pi);
5292                 goto done;
5293         }
5294
5295         /*
5296          * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
5297          * if this changes.
5298          */
5299
5300         for_each_txq(vi, i, txq) {
5301                 TXQ_LOCK(txq);
5302                 txq->eq.flags |= EQ_ENABLED;
5303                 TXQ_UNLOCK(txq);
5304         }
5305
5306         /*
5307          * The first iq of the first port to come up is used for tracing.
5308          */
5309         if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
5310                 sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
5311                 t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
5312                     A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
5313                     V_QUEUENUMBER(sc->traceq));
5314                 pi->flags |= HAS_TRACEQ;
5315         }
5316
5317         /* all ok */
5318         pi->up_vis++;
5319         ifp->if_drv_flags |= IFF_DRV_RUNNING;
5320
5321         if (pi->nvi > 1 || sc->flags & IS_VF)
5322                 callout_reset(&vi->tick, hz, vi_tick, vi);
5323         else
5324                 callout_reset(&pi->tick, hz, cxgbe_tick, pi);
5325         if (pi->link_cfg.link_ok)
5326                 t4_os_link_changed(pi);
5327         PORT_UNLOCK(pi);
5328 done:
5329         if (rc != 0)
5330                 cxgbe_uninit_synchronized(vi);
5331
5332         return (rc);
5333 }
5334
5335 /*
5336  * Idempotent.
5337  */
5338 static int
5339 cxgbe_uninit_synchronized(struct vi_info *vi)
5340 {
5341         struct port_info *pi = vi->pi;
5342         struct adapter *sc = pi->adapter;
5343         struct ifnet *ifp = vi->ifp;
5344         int rc, i;
5345         struct sge_txq *txq;
5346
5347         ASSERT_SYNCHRONIZED_OP(sc);
5348
5349         if (!(vi->flags & VI_INIT_DONE)) {
5350                 if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5351                         KASSERT(0, ("uninited VI is running"));
5352                         if_printf(ifp, "uninited VI with running ifnet.  "
5353                             "vi->flags 0x%016lx, if_flags 0x%08x, "
5354                             "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
5355                             ifp->if_drv_flags);
5356                 }
5357                 return (0);
5358         }
5359
5360         /*
5361          * Disable the VI so that all its data in either direction is discarded
5362          * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
5363          * tick) intact as the TP can deliver negative advice or data that it's
5364          * holding in its RAM (for an offloaded connection) even after the VI is
5365          * disabled.
5366          */
5367         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
5368         if (rc) {
5369                 if_printf(ifp, "disable_vi failed: %d\n", rc);
5370                 return (rc);
5371         }
5372
5373         for_each_txq(vi, i, txq) {
5374                 TXQ_LOCK(txq);
5375                 txq->eq.flags &= ~EQ_ENABLED;
5376                 TXQ_UNLOCK(txq);
5377         }
5378
5379         PORT_LOCK(pi);
5380         if (pi->nvi > 1 || sc->flags & IS_VF)
5381                 callout_stop(&vi->tick);
5382         else
5383                 callout_stop(&pi->tick);
5384         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5385                 PORT_UNLOCK(pi);
5386                 return (0);
5387         }
5388         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
5389         pi->up_vis--;
5390         if (pi->up_vis > 0) {
5391                 PORT_UNLOCK(pi);
5392                 return (0);
5393         }
5394
5395         pi->link_cfg.link_ok = false;
5396         pi->link_cfg.speed = 0;
5397         pi->link_cfg.link_down_rc = 255;
5398         t4_os_link_changed(pi);
5399         PORT_UNLOCK(pi);
5400
5401         return (0);
5402 }
5403
5404 /*
5405  * It is ok for this function to fail midway and return right away.  t4_detach
5406  * will walk the entire sc->irq list and clean up whatever is valid.
5407  */
5408 int
5409 t4_setup_intr_handlers(struct adapter *sc)
5410 {
5411         int rc, rid, p, q, v;
5412         char s[8];
5413         struct irq *irq;
5414         struct port_info *pi;
5415         struct vi_info *vi;
5416         struct sge *sge = &sc->sge;
5417         struct sge_rxq *rxq;
5418 #ifdef TCP_OFFLOAD
5419         struct sge_ofld_rxq *ofld_rxq;
5420 #endif
5421 #ifdef DEV_NETMAP
5422         struct sge_nm_rxq *nm_rxq;
5423 #endif
5424 #ifdef RSS
5425         int nbuckets = rss_getnumbuckets();
5426 #endif
5427
5428         /*
5429          * Setup interrupts.
5430          */
5431         irq = &sc->irq[0];
5432         rid = sc->intr_type == INTR_INTX ? 0 : 1;
5433         if (forwarding_intr_to_fwq(sc))
5434                 return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
5435
5436         /* Multiple interrupts. */
5437         if (sc->flags & IS_VF)
5438                 KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
5439                     ("%s: too few intr.", __func__));
5440         else
5441                 KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
5442                     ("%s: too few intr.", __func__));
5443
5444         /* The first one is always error intr on PFs */
5445         if (!(sc->flags & IS_VF)) {
5446                 rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
5447                 if (rc != 0)
5448                         return (rc);
5449                 irq++;
5450                 rid++;
5451         }
5452
5453         /* The second one is always the firmware event queue (first on VFs) */
5454         rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
5455         if (rc != 0)
5456                 return (rc);
5457         irq++;
5458         rid++;
5459
5460         for_each_port(sc, p) {
5461                 pi = sc->port[p];
5462                 for_each_vi(pi, v, vi) {
5463                         vi->first_intr = rid - 1;
5464
5465                         if (vi->nnmrxq > 0) {
5466                                 int n = max(vi->nrxq, vi->nnmrxq);
5467
5468                                 rxq = &sge->rxq[vi->first_rxq];
5469 #ifdef DEV_NETMAP
5470                                 nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
5471 #endif
5472                                 for (q = 0; q < n; q++) {
5473                                         snprintf(s, sizeof(s), "%x%c%x", p,
5474                                             'a' + v, q);
5475                                         if (q < vi->nrxq)
5476                                                 irq->rxq = rxq++;
5477 #ifdef DEV_NETMAP
5478                                         if (q < vi->nnmrxq)
5479                                                 irq->nm_rxq = nm_rxq++;
5480
5481                                         if (irq->nm_rxq != NULL &&
5482                                             irq->rxq == NULL) {
5483                                                 /* Netmap rx only */
5484                                                 rc = t4_alloc_irq(sc, irq, rid,
5485                                                     t4_nm_intr, irq->nm_rxq, s);
5486                                         }
5487                                         if (irq->nm_rxq != NULL &&
5488                                             irq->rxq != NULL) {
5489                                                 /* NIC and Netmap rx */
5490                                                 rc = t4_alloc_irq(sc, irq, rid,
5491                                                     t4_vi_intr, irq, s);
5492                                         }
5493 #endif
5494                                         if (irq->rxq != NULL &&
5495                                             irq->nm_rxq == NULL) {
5496                                                 /* NIC rx only */
5497                                                 rc = t4_alloc_irq(sc, irq, rid,
5498                                                     t4_intr, irq->rxq, s);
5499                                         }
5500                                         if (rc != 0)
5501                                                 return (rc);
5502 #ifdef RSS
5503                                         if (q < vi->nrxq) {
5504                                                 bus_bind_intr(sc->dev, irq->res,
5505                                                     rss_getcpu(q % nbuckets));
5506                                         }
5507 #endif
5508                                         irq++;
5509                                         rid++;
5510                                         vi->nintr++;
5511                                 }
5512                         } else {
5513                                 for_each_rxq(vi, q, rxq) {
5514                                         snprintf(s, sizeof(s), "%x%c%x", p,
5515                                             'a' + v, q);
5516                                         rc = t4_alloc_irq(sc, irq, rid,
5517                                             t4_intr, rxq, s);
5518                                         if (rc != 0)
5519                                                 return (rc);
5520 #ifdef RSS
5521                                         bus_bind_intr(sc->dev, irq->res,
5522                                             rss_getcpu(q % nbuckets));
5523 #endif
5524                                         irq++;
5525                                         rid++;
5526                                         vi->nintr++;
5527                                 }
5528                         }
5529 #ifdef TCP_OFFLOAD
5530                         for_each_ofld_rxq(vi, q, ofld_rxq) {
5531                                 snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
5532                                 rc = t4_alloc_irq(sc, irq, rid, t4_intr,
5533                                     ofld_rxq, s);
5534                                 if (rc != 0)
5535                                         return (rc);
5536                                 irq++;
5537                                 rid++;
5538                                 vi->nintr++;
5539                         }
5540 #endif
5541                 }
5542         }
5543         MPASS(irq == &sc->irq[sc->intr_count]);
5544
5545         return (0);
5546 }
5547
5548 int
5549 adapter_full_init(struct adapter *sc)
5550 {
5551         int rc, i;
5552 #ifdef RSS
5553         uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5554         uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5555 #endif
5556
5557         ASSERT_SYNCHRONIZED_OP(sc);
5558         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5559         KASSERT((sc->flags & FULL_INIT_DONE) == 0,
5560             ("%s: FULL_INIT_DONE already", __func__));
5561
5562         /*
5563          * queues that belong to the adapter (not any particular port).
5564          */
5565         rc = t4_setup_adapter_queues(sc);
5566         if (rc != 0)
5567                 goto done;
5568
5569         for (i = 0; i < nitems(sc->tq); i++) {
5570                 sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
5571                     taskqueue_thread_enqueue, &sc->tq[i]);
5572                 if (sc->tq[i] == NULL) {
5573                         device_printf(sc->dev,
5574                             "failed to allocate task queue %d\n", i);
5575                         rc = ENOMEM;
5576                         goto done;
5577                 }
5578                 taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
5579                     device_get_nameunit(sc->dev), i);
5580         }
5581 #ifdef RSS
5582         MPASS(RSS_KEYSIZE == 40);
5583         rss_getkey((void *)&raw_rss_key[0]);
5584         for (i = 0; i < nitems(rss_key); i++) {
5585                 rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
5586         }
5587         t4_write_rss_key(sc, &rss_key[0], -1, 1);
5588 #endif
5589
5590         if (!(sc->flags & IS_VF))
5591                 t4_intr_enable(sc);
5592 #ifdef KERN_TLS
5593         if (sc->flags & KERN_TLS_OK)
5594                 callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5595                     C_HARDCLOCK);
5596 #endif
5597         sc->flags |= FULL_INIT_DONE;
5598 done:
5599         if (rc != 0)
5600                 adapter_full_uninit(sc);
5601
5602         return (rc);
5603 }
5604
5605 int
5606 adapter_full_uninit(struct adapter *sc)
5607 {
5608         int i;
5609
5610         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5611
5612         t4_teardown_adapter_queues(sc);
5613
5614         for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
5615                 taskqueue_free(sc->tq[i]);
5616                 sc->tq[i] = NULL;
5617         }
5618
5619         sc->flags &= ~FULL_INIT_DONE;
5620
5621         return (0);
5622 }
5623
5624 #ifdef RSS
5625 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
5626     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
5627     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
5628     RSS_HASHTYPE_RSS_UDP_IPV6)
5629
5630 /* Translates kernel hash types to hardware. */
5631 static int
5632 hashconfig_to_hashen(int hashconfig)
5633 {
5634         int hashen = 0;
5635
5636         if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
5637                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
5638         if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
5639                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
5640         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
5641                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5642                     F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5643         }
5644         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
5645                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5646                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5647         }
5648         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
5649                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5650         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
5651                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5652
5653         return (hashen);
5654 }
5655
5656 /* Translates hardware hash types to kernel. */
5657 static int
5658 hashen_to_hashconfig(int hashen)
5659 {
5660         int hashconfig = 0;
5661
5662         if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
5663                 /*
5664                  * If UDP hashing was enabled it must have been enabled for
5665                  * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
5666                  * enabling any 4-tuple hash is nonsense configuration.
5667                  */
5668                 MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5669                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
5670
5671                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5672                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
5673                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5674                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
5675         }
5676         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5677                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
5678         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5679                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
5680         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
5681                 hashconfig |= RSS_HASHTYPE_RSS_IPV4;
5682         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
5683                 hashconfig |= RSS_HASHTYPE_RSS_IPV6;
5684
5685         return (hashconfig);
5686 }
5687 #endif
5688
5689 int
5690 vi_full_init(struct vi_info *vi)
5691 {
5692         struct adapter *sc = vi->pi->adapter;
5693         struct ifnet *ifp = vi->ifp;
5694         uint16_t *rss;
5695         struct sge_rxq *rxq;
5696         int rc, i, j;
5697 #ifdef RSS
5698         int nbuckets = rss_getnumbuckets();
5699         int hashconfig = rss_gethashconfig();
5700         int extra;
5701 #endif
5702
5703         ASSERT_SYNCHRONIZED_OP(sc);
5704         KASSERT((vi->flags & VI_INIT_DONE) == 0,
5705             ("%s: VI_INIT_DONE already", __func__));
5706
5707         sysctl_ctx_init(&vi->ctx);
5708         vi->flags |= VI_SYSCTL_CTX;
5709
5710         /*
5711          * Allocate tx/rx/fl queues for this VI.
5712          */
5713         rc = t4_setup_vi_queues(vi);
5714         if (rc != 0)
5715                 goto done;      /* error message displayed already */
5716
5717         /*
5718          * Setup RSS for this VI.  Save a copy of the RSS table for later use.
5719          */
5720         if (vi->nrxq > vi->rss_size) {
5721                 if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
5722                     "some queues will never receive traffic.\n", vi->nrxq,
5723                     vi->rss_size);
5724         } else if (vi->rss_size % vi->nrxq) {
5725                 if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
5726                     "expect uneven traffic distribution.\n", vi->nrxq,
5727                     vi->rss_size);
5728         }
5729 #ifdef RSS
5730         if (vi->nrxq != nbuckets) {
5731                 if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
5732                     "performance will be impacted.\n", vi->nrxq, nbuckets);
5733         }
5734 #endif
5735         rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
5736         for (i = 0; i < vi->rss_size;) {
5737 #ifdef RSS
5738                 j = rss_get_indirection_to_bucket(i);
5739                 j %= vi->nrxq;
5740                 rxq = &sc->sge.rxq[vi->first_rxq + j];
5741                 rss[i++] = rxq->iq.abs_id;
5742 #else
5743                 for_each_rxq(vi, j, rxq) {
5744                         rss[i++] = rxq->iq.abs_id;
5745                         if (i == vi->rss_size)
5746                                 break;
5747                 }
5748 #endif
5749         }
5750
5751         rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
5752             vi->rss_size);
5753         if (rc != 0) {
5754                 free(rss, M_CXGBE);
5755                 if_printf(ifp, "rss_config failed: %d\n", rc);
5756                 goto done;
5757         }
5758
5759 #ifdef RSS
5760         vi->hashen = hashconfig_to_hashen(hashconfig);
5761
5762         /*
5763          * We may have had to enable some hashes even though the global config
5764          * wants them disabled.  This is a potential problem that must be
5765          * reported to the user.
5766          */
5767         extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
5768
5769         /*
5770          * If we consider only the supported hash types, then the enabled hashes
5771          * are a superset of the requested hashes.  In other words, there cannot
5772          * be any supported hash that was requested but not enabled, but there
5773          * can be hashes that were not requested but had to be enabled.
5774          */
5775         extra &= SUPPORTED_RSS_HASHTYPES;
5776         MPASS((extra & hashconfig) == 0);
5777
5778         if (extra) {
5779                 if_printf(ifp,
5780                     "global RSS config (0x%x) cannot be accommodated.\n",
5781                     hashconfig);
5782         }
5783         if (extra & RSS_HASHTYPE_RSS_IPV4)
5784                 if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
5785         if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
5786                 if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
5787         if (extra & RSS_HASHTYPE_RSS_IPV6)
5788                 if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
5789         if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
5790                 if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
5791         if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
5792                 if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
5793         if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
5794                 if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
5795 #else
5796         vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
5797             F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
5798             F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5799             F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
5800 #endif
5801         rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, rss[0], 0, 0);
5802         if (rc != 0) {
5803                 free(rss, M_CXGBE);
5804                 if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
5805                 goto done;
5806         }
5807
5808         vi->rss = rss;
5809         vi->flags |= VI_INIT_DONE;
5810 done:
5811         if (rc != 0)
5812                 vi_full_uninit(vi);
5813
5814         return (rc);
5815 }
5816
5817 /*
5818  * Idempotent.
5819  */
5820 int
5821 vi_full_uninit(struct vi_info *vi)
5822 {
5823         struct port_info *pi = vi->pi;
5824         struct adapter *sc = pi->adapter;
5825         int i;
5826         struct sge_rxq *rxq;
5827         struct sge_txq *txq;
5828 #ifdef TCP_OFFLOAD
5829         struct sge_ofld_rxq *ofld_rxq;
5830 #endif
5831 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
5832         struct sge_wrq *ofld_txq;
5833 #endif
5834
5835         if (vi->flags & VI_INIT_DONE) {
5836
5837                 /* Need to quiesce queues.  */
5838
5839                 /* XXX: Only for the first VI? */
5840                 if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
5841                         quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
5842
5843                 for_each_txq(vi, i, txq) {
5844                         quiesce_txq(sc, txq);
5845                 }
5846
5847 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
5848                 for_each_ofld_txq(vi, i, ofld_txq) {
5849                         quiesce_wrq(sc, ofld_txq);
5850                 }
5851 #endif
5852
5853                 for_each_rxq(vi, i, rxq) {
5854                         quiesce_iq(sc, &rxq->iq);
5855                         quiesce_fl(sc, &rxq->fl);
5856                 }
5857
5858 #ifdef TCP_OFFLOAD
5859                 for_each_ofld_rxq(vi, i, ofld_rxq) {
5860                         quiesce_iq(sc, &ofld_rxq->iq);
5861                         quiesce_fl(sc, &ofld_rxq->fl);
5862                 }
5863 #endif
5864                 free(vi->rss, M_CXGBE);
5865                 free(vi->nm_rss, M_CXGBE);
5866         }
5867
5868         t4_teardown_vi_queues(vi);
5869         vi->flags &= ~VI_INIT_DONE;
5870
5871         return (0);
5872 }
5873
5874 static void
5875 quiesce_txq(struct adapter *sc, struct sge_txq *txq)
5876 {
5877         struct sge_eq *eq = &txq->eq;
5878         struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
5879
5880         (void) sc;      /* unused */
5881
5882 #ifdef INVARIANTS
5883         TXQ_LOCK(txq);
5884         MPASS((eq->flags & EQ_ENABLED) == 0);
5885         TXQ_UNLOCK(txq);
5886 #endif
5887
5888         /* Wait for the mp_ring to empty. */
5889         while (!mp_ring_is_idle(txq->r)) {
5890                 mp_ring_check_drainage(txq->r, 0);
5891                 pause("rquiesce", 1);
5892         }
5893
5894         /* Then wait for the hardware to finish. */
5895         while (spg->cidx != htobe16(eq->pidx))
5896                 pause("equiesce", 1);
5897
5898         /* Finally, wait for the driver to reclaim all descriptors. */
5899         while (eq->cidx != eq->pidx)
5900                 pause("dquiesce", 1);
5901 }
5902
5903 static void
5904 quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
5905 {
5906
5907         /* XXXTX */
5908 }
5909
5910 static void
5911 quiesce_iq(struct adapter *sc, struct sge_iq *iq)
5912 {
5913         (void) sc;      /* unused */
5914
5915         /* Synchronize with the interrupt handler */
5916         while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
5917                 pause("iqfree", 1);
5918 }
5919
5920 static void
5921 quiesce_fl(struct adapter *sc, struct sge_fl *fl)
5922 {
5923         mtx_lock(&sc->sfl_lock);
5924         FL_LOCK(fl);
5925         fl->flags |= FL_DOOMED;
5926         FL_UNLOCK(fl);
5927         callout_stop(&sc->sfl_callout);
5928         mtx_unlock(&sc->sfl_lock);
5929
5930         KASSERT((fl->flags & FL_STARVING) == 0,
5931             ("%s: still starving", __func__));
5932 }
5933
5934 static int
5935 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
5936     driver_intr_t *handler, void *arg, char *name)
5937 {
5938         int rc;
5939
5940         irq->rid = rid;
5941         irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
5942             RF_SHAREABLE | RF_ACTIVE);
5943         if (irq->res == NULL) {
5944                 device_printf(sc->dev,
5945                     "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
5946                 return (ENOMEM);
5947         }
5948
5949         rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
5950             NULL, handler, arg, &irq->tag);
5951         if (rc != 0) {
5952                 device_printf(sc->dev,
5953                     "failed to setup interrupt for rid %d, name %s: %d\n",
5954                     rid, name, rc);
5955         } else if (name)
5956                 bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
5957
5958         return (rc);
5959 }
5960
5961 static int
5962 t4_free_irq(struct adapter *sc, struct irq *irq)
5963 {
5964         if (irq->tag)
5965                 bus_teardown_intr(sc->dev, irq->res, irq->tag);
5966         if (irq->res)
5967                 bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
5968
5969         bzero(irq, sizeof(*irq));
5970
5971         return (0);
5972 }
5973
5974 static void
5975 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
5976 {
5977
5978         regs->version = chip_id(sc) | chip_rev(sc) << 10;
5979         t4_get_regs(sc, buf, regs->len);
5980 }
5981
5982 #define A_PL_INDIR_CMD  0x1f8
5983
5984 #define S_PL_AUTOINC    31
5985 #define M_PL_AUTOINC    0x1U
5986 #define V_PL_AUTOINC(x) ((x) << S_PL_AUTOINC)
5987 #define G_PL_AUTOINC(x) (((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
5988
5989 #define S_PL_VFID       20
5990 #define M_PL_VFID       0xffU
5991 #define V_PL_VFID(x)    ((x) << S_PL_VFID)
5992 #define G_PL_VFID(x)    (((x) >> S_PL_VFID) & M_PL_VFID)
5993
5994 #define S_PL_ADDR       0
5995 #define M_PL_ADDR       0xfffffU
5996 #define V_PL_ADDR(x)    ((x) << S_PL_ADDR)
5997 #define G_PL_ADDR(x)    (((x) >> S_PL_ADDR) & M_PL_ADDR)
5998
5999 #define A_PL_INDIR_DATA 0x1fc
6000
6001 static uint64_t
6002 read_vf_stat(struct adapter *sc, u_int vin, int reg)
6003 {
6004         u32 stats[2];
6005
6006         mtx_assert(&sc->reg_lock, MA_OWNED);
6007         if (sc->flags & IS_VF) {
6008                 stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
6009                 stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
6010         } else {
6011                 t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
6012                     V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
6013                 stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
6014                 stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
6015         }
6016         return (((uint64_t)stats[1]) << 32 | stats[0]);
6017 }
6018
6019 static void
6020 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
6021 {
6022
6023 #define GET_STAT(name) \
6024         read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
6025
6026         stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
6027         stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
6028         stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
6029         stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
6030         stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
6031         stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
6032         stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
6033         stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
6034         stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
6035         stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
6036         stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
6037         stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
6038         stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
6039         stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
6040         stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
6041         stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
6042
6043 #undef GET_STAT
6044 }
6045
6046 static void
6047 t4_clr_vi_stats(struct adapter *sc, u_int vin)
6048 {
6049         int reg;
6050
6051         t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
6052             V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
6053         for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
6054              reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
6055                 t4_write_reg(sc, A_PL_INDIR_DATA, 0);
6056 }
6057
6058 static void
6059 vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
6060 {
6061         struct timeval tv;
6062         const struct timeval interval = {0, 250000};    /* 250ms */
6063
6064         if (!(vi->flags & VI_INIT_DONE))
6065                 return;
6066
6067         getmicrotime(&tv);
6068         timevalsub(&tv, &interval);
6069         if (timevalcmp(&tv, &vi->last_refreshed, <))
6070                 return;
6071
6072         mtx_lock(&sc->reg_lock);
6073         t4_get_vi_stats(sc, vi->vin, &vi->stats);
6074         getmicrotime(&vi->last_refreshed);
6075         mtx_unlock(&sc->reg_lock);
6076 }
6077
6078 static void
6079 cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
6080 {
6081         u_int i, v, tnl_cong_drops, bg_map;
6082         struct timeval tv;
6083         const struct timeval interval = {0, 250000};    /* 250ms */
6084
6085         getmicrotime(&tv);
6086         timevalsub(&tv, &interval);
6087         if (timevalcmp(&tv, &pi->last_refreshed, <))
6088                 return;
6089
6090         tnl_cong_drops = 0;
6091         t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
6092         bg_map = pi->mps_bg_map;
6093         while (bg_map) {
6094                 i = ffs(bg_map) - 1;
6095                 mtx_lock(&sc->reg_lock);
6096                 t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
6097                     A_TP_MIB_TNL_CNG_DROP_0 + i);
6098                 mtx_unlock(&sc->reg_lock);
6099                 tnl_cong_drops += v;
6100                 bg_map &= ~(1 << i);
6101         }
6102         pi->tnl_cong_drops = tnl_cong_drops;
6103         getmicrotime(&pi->last_refreshed);
6104 }
6105
6106 static void
6107 cxgbe_tick(void *arg)
6108 {
6109         struct port_info *pi = arg;
6110         struct adapter *sc = pi->adapter;
6111
6112         PORT_LOCK_ASSERT_OWNED(pi);
6113         cxgbe_refresh_stats(sc, pi);
6114
6115         callout_schedule(&pi->tick, hz);
6116 }
6117
6118 void
6119 vi_tick(void *arg)
6120 {
6121         struct vi_info *vi = arg;
6122         struct adapter *sc = vi->pi->adapter;
6123
6124         vi_refresh_stats(sc, vi);
6125
6126         callout_schedule(&vi->tick, hz);
6127 }
6128
6129 /*
6130  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
6131  */
6132 static char *caps_decoder[] = {
6133         "\20\001IPMI\002NCSI",                          /* 0: NBM */
6134         "\20\001PPP\002QFC\003DCBX",                    /* 1: link */
6135         "\20\001INGRESS\002EGRESS",                     /* 2: switch */
6136         "\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"      /* 3: NIC */
6137             "\006HASHFILTER\007ETHOFLD",
6138         "\20\001TOE",                                   /* 4: TOE */
6139         "\20\001RDDP\002RDMAC",                         /* 5: RDMA */
6140         "\20\001INITIATOR_PDU\002TARGET_PDU"            /* 6: iSCSI */
6141             "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
6142             "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
6143             "\007T10DIF"
6144             "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
6145         "\20\001LOOKASIDE\002TLSKEYS",                  /* 7: Crypto */
6146         "\20\001INITIATOR\002TARGET\003CTRL_OFLD"       /* 8: FCoE */
6147                     "\004PO_INITIATOR\005PO_TARGET",
6148 };
6149
6150 void
6151 t4_sysctls(struct adapter *sc)
6152 {
6153         struct sysctl_ctx_list *ctx;
6154         struct sysctl_oid *oid;
6155         struct sysctl_oid_list *children, *c0;
6156         static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
6157
6158         ctx = device_get_sysctl_ctx(sc->dev);
6159
6160         /*
6161          * dev.t4nex.X.
6162          */
6163         oid = device_get_sysctl_tree(sc->dev);
6164         c0 = children = SYSCTL_CHILDREN(oid);
6165
6166         sc->sc_do_rxcopy = 1;
6167         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
6168             &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
6169
6170         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
6171             sc->params.nports, "# of ports");
6172
6173         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
6174             CTLTYPE_STRING | CTLFLAG_RD, doorbells, (uintptr_t)&sc->doorbells,
6175             sysctl_bitfield_8b, "A", "available doorbells");
6176
6177         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
6178             sc->params.vpd.cclk, "core clock frequency (in KHz)");
6179
6180         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
6181             CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.timer_val,
6182             sizeof(sc->params.sge.timer_val), sysctl_int_array, "A",
6183             "interrupt holdoff timer values (us)");
6184
6185         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
6186             CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.counter_val,
6187             sizeof(sc->params.sge.counter_val), sysctl_int_array, "A",
6188             "interrupt holdoff packet counter values");
6189
6190         t4_sge_sysctls(sc, ctx, children);
6191
6192         sc->lro_timeout = 100;
6193         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
6194             &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
6195
6196         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
6197             &sc->debug_flags, 0, "flags to enable runtime debugging");
6198
6199         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
6200             CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
6201
6202         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
6203             CTLFLAG_RD, sc->fw_version, 0, "firmware version");
6204
6205         if (sc->flags & IS_VF)
6206                 return;
6207
6208         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
6209             NULL, chip_rev(sc), "chip hardware revision");
6210
6211         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
6212             CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
6213
6214         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
6215             CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
6216
6217         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
6218             CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
6219
6220         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
6221             CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
6222
6223         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
6224             CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
6225
6226         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
6227             sc->er_version, 0, "expansion ROM version");
6228
6229         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
6230             sc->bs_version, 0, "bootstrap firmware version");
6231
6232         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
6233             NULL, sc->params.scfg_vers, "serial config version");
6234
6235         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
6236             NULL, sc->params.vpd_vers, "VPD version");
6237
6238         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
6239             CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
6240
6241         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
6242             sc->cfcsum, "config file checksum");
6243
6244 #define SYSCTL_CAP(name, n, text) \
6245         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
6246             CTLTYPE_STRING | CTLFLAG_RD, caps_decoder[n], (uintptr_t)&sc->name, \
6247             sysctl_bitfield_16b, "A", "available " text " capabilities")
6248
6249         SYSCTL_CAP(nbmcaps, 0, "NBM");
6250         SYSCTL_CAP(linkcaps, 1, "link");
6251         SYSCTL_CAP(switchcaps, 2, "switch");
6252         SYSCTL_CAP(niccaps, 3, "NIC");
6253         SYSCTL_CAP(toecaps, 4, "TCP offload");
6254         SYSCTL_CAP(rdmacaps, 5, "RDMA");
6255         SYSCTL_CAP(iscsicaps, 6, "iSCSI");
6256         SYSCTL_CAP(cryptocaps, 7, "crypto");
6257         SYSCTL_CAP(fcoecaps, 8, "FCoE");
6258 #undef SYSCTL_CAP
6259
6260         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
6261             NULL, sc->tids.nftids, "number of filters");
6262
6263         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature", CTLTYPE_INT |
6264             CTLFLAG_RD, sc, 0, sysctl_temperature, "I",
6265             "chip temperature (in Celsius)");
6266         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor", CTLTYPE_INT |
6267             CTLFLAG_RW, sc, 0, sysctl_reset_sensor, "I",
6268             "reset the chip's temperature sensor.");
6269
6270         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg", CTLTYPE_STRING |
6271             CTLFLAG_RD, sc, 0, sysctl_loadavg, "A",
6272             "microprocessor load averages (debug firmwares only)");
6273
6274         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd", CTLTYPE_INT |
6275             CTLFLAG_RD, sc, 0, sysctl_vdd, "I", "core Vdd (in mV)");
6276
6277         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
6278             CTLTYPE_STRING | CTLFLAG_RD, sc, LOCAL_CPUS,
6279             sysctl_cpus, "A", "local CPUs");
6280
6281         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
6282             CTLTYPE_STRING | CTLFLAG_RD, sc, INTR_CPUS,
6283             sysctl_cpus, "A", "preferred CPUs for interrupts");
6284
6285         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
6286             &sc->swintr, 0, "software triggered interrupts");
6287
6288         /*
6289          * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
6290          */
6291         oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
6292             CTLFLAG_RD | CTLFLAG_SKIP, NULL,
6293             "logs and miscellaneous information");
6294         children = SYSCTL_CHILDREN(oid);
6295
6296         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
6297             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6298             sysctl_cctrl, "A", "congestion control");
6299
6300         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
6301             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6302             sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
6303
6304         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
6305             CTLTYPE_STRING | CTLFLAG_RD, sc, 1,
6306             sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
6307
6308         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
6309             CTLTYPE_STRING | CTLFLAG_RD, sc, 2,
6310             sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
6311
6312         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
6313             CTLTYPE_STRING | CTLFLAG_RD, sc, 3,
6314             sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
6315
6316         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
6317             CTLTYPE_STRING | CTLFLAG_RD, sc, 4,
6318             sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
6319
6320         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
6321             CTLTYPE_STRING | CTLFLAG_RD, sc, 5,
6322             sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
6323
6324         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
6325             CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_cim_la,
6326             "A", "CIM logic analyzer");
6327
6328         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
6329             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6330             sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
6331
6332         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
6333             CTLTYPE_STRING | CTLFLAG_RD, sc, 0 + CIM_NUM_IBQ,
6334             sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
6335
6336         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
6337             CTLTYPE_STRING | CTLFLAG_RD, sc, 1 + CIM_NUM_IBQ,
6338             sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
6339
6340         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
6341             CTLTYPE_STRING | CTLFLAG_RD, sc, 2 + CIM_NUM_IBQ,
6342             sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
6343
6344         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
6345             CTLTYPE_STRING | CTLFLAG_RD, sc, 3 + CIM_NUM_IBQ,
6346             sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
6347
6348         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
6349             CTLTYPE_STRING | CTLFLAG_RD, sc, 4 + CIM_NUM_IBQ,
6350             sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
6351
6352         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
6353             CTLTYPE_STRING | CTLFLAG_RD, sc, 5 + CIM_NUM_IBQ,
6354             sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
6355
6356         if (chip_id(sc) > CHELSIO_T4) {
6357                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
6358                     CTLTYPE_STRING | CTLFLAG_RD, sc, 6 + CIM_NUM_IBQ,
6359                     sysctl_cim_ibq_obq, "A", "CIM OBQ 6 (SGE0-RX)");
6360
6361                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
6362                     CTLTYPE_STRING | CTLFLAG_RD, sc, 7 + CIM_NUM_IBQ,
6363                     sysctl_cim_ibq_obq, "A", "CIM OBQ 7 (SGE1-RX)");
6364         }
6365
6366         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
6367             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6368             sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
6369
6370         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
6371             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6372             sysctl_cim_qcfg, "A", "CIM queue configuration");
6373
6374         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
6375             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6376             sysctl_cpl_stats, "A", "CPL statistics");
6377
6378         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
6379             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6380             sysctl_ddp_stats, "A", "non-TCP DDP statistics");
6381
6382         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
6383             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6384             sysctl_devlog, "A", "firmware's device log");
6385
6386         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
6387             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6388             sysctl_fcoe_stats, "A", "FCoE statistics");
6389
6390         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
6391             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6392             sysctl_hw_sched, "A", "hardware scheduler ");
6393
6394         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
6395             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6396             sysctl_l2t, "A", "hardware L2 table");
6397
6398         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
6399             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6400             sysctl_smt, "A", "hardware source MAC table");
6401
6402 #ifdef INET6
6403         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
6404             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6405             sysctl_clip, "A", "active CLIP table entries");
6406 #endif
6407
6408         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
6409             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6410             sysctl_lb_stats, "A", "loopback statistics");
6411
6412         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
6413             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6414             sysctl_meminfo, "A", "memory regions");
6415
6416         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
6417             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6418             chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
6419             "A", "MPS TCAM entries");
6420
6421         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
6422             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6423             sysctl_path_mtus, "A", "path MTUs");
6424
6425         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
6426             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6427             sysctl_pm_stats, "A", "PM statistics");
6428
6429         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
6430             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6431             sysctl_rdma_stats, "A", "RDMA statistics");
6432
6433         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
6434             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6435             sysctl_tcp_stats, "A", "TCP statistics");
6436
6437         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
6438             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6439             sysctl_tids, "A", "TID information");
6440
6441         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
6442             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6443             sysctl_tp_err_stats, "A", "TP error statistics");
6444
6445         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
6446             CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tp_la_mask, "I",
6447             "TP logic analyzer event capture mask");
6448
6449         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
6450             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6451             sysctl_tp_la, "A", "TP logic analyzer");
6452
6453         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
6454             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6455             sysctl_tx_rate, "A", "Tx rate");
6456
6457         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
6458             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6459             sysctl_ulprx_la, "A", "ULPRX logic analyzer");
6460
6461         if (chip_id(sc) >= CHELSIO_T5) {
6462                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
6463                     CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6464                     sysctl_wcwr_stats, "A", "write combined work requests");
6465         }
6466
6467 #ifdef KERN_TLS
6468         if (sc->flags & KERN_TLS_OK) {
6469                 /*
6470                  * dev.t4nex.0.tls.
6471                  */
6472                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls", CTLFLAG_RD,
6473                     NULL, "KERN_TLS parameters");
6474                 children = SYSCTL_CHILDREN(oid);
6475
6476                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
6477                     CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
6478                     "keys in work requests (1) or attempt to store TLS keys "
6479                     "in card memory.");
6480                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
6481                     CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to combine "
6482                     "TCB field updates with TLS record work requests.");
6483         }
6484 #endif
6485
6486 #ifdef TCP_OFFLOAD
6487         if (is_offload(sc)) {
6488                 int i;
6489                 char s[4];
6490
6491                 /*
6492                  * dev.t4nex.X.toe.
6493                  */
6494                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe", CTLFLAG_RD,
6495                     NULL, "TOE parameters");
6496                 children = SYSCTL_CHILDREN(oid);
6497
6498                 sc->tt.cong_algorithm = -1;
6499                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
6500                     CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
6501                     "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
6502                     "3 = highspeed)");
6503
6504                 sc->tt.sndbuf = -1;
6505                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
6506                     &sc->tt.sndbuf, 0, "hardware send buffer");
6507
6508                 sc->tt.ddp = 0;
6509                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
6510                     CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
6511                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
6512                     &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
6513
6514                 sc->tt.rx_coalesce = -1;
6515                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
6516                     CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
6517
6518                 sc->tt.tls = 0;
6519                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tls", CTLFLAG_RW,
6520                     &sc->tt.tls, 0, "Inline TLS allowed");
6521
6522                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
6523                     CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tls_rx_ports,
6524                     "I", "TCP ports that use inline TLS+TOE RX");
6525
6526                 sc->tt.tx_align = -1;
6527                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
6528                     CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
6529
6530                 sc->tt.tx_zcopy = 0;
6531                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
6532                     CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
6533                     "Enable zero-copy aio_write(2)");
6534
6535                 sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
6536                 SYSCTL_ADD_INT(ctx, children, OID_AUTO,
6537                     "cop_managed_offloading", CTLFLAG_RW,
6538                     &sc->tt.cop_managed_offloading, 0,
6539                     "COP (Connection Offload Policy) controls all TOE offload");
6540
6541                 sc->tt.autorcvbuf_inc = 16 * 1024;
6542                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
6543                     CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
6544                     "autorcvbuf increment");
6545
6546                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
6547                     CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_tp_tick, "A",
6548                     "TP timer tick (us)");
6549
6550                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
6551                     CTLTYPE_STRING | CTLFLAG_RD, sc, 1, sysctl_tp_tick, "A",
6552                     "TCP timestamp tick (us)");
6553
6554                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
6555                     CTLTYPE_STRING | CTLFLAG_RD, sc, 2, sysctl_tp_tick, "A",
6556                     "DACK tick (us)");
6557
6558                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
6559                     CTLTYPE_UINT | CTLFLAG_RD, sc, 0, sysctl_tp_dack_timer,
6560                     "IU", "DACK timer (us)");
6561
6562                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
6563                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MIN,
6564                     sysctl_tp_timer, "LU", "Minimum retransmit interval (us)");
6565
6566                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
6567                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MAX,
6568                     sysctl_tp_timer, "LU", "Maximum retransmit interval (us)");
6569
6570                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
6571                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MIN,
6572                     sysctl_tp_timer, "LU", "Persist timer min (us)");
6573
6574                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
6575                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MAX,
6576                     sysctl_tp_timer, "LU", "Persist timer max (us)");
6577
6578                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
6579                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_IDLE,
6580                     sysctl_tp_timer, "LU", "Keepalive idle timer (us)");
6581
6582                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
6583                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_INTVL,
6584                     sysctl_tp_timer, "LU", "Keepalive interval timer (us)");
6585
6586                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
6587                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_INIT_SRTT,
6588                     sysctl_tp_timer, "LU", "Initial SRTT (us)");
6589
6590                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
6591                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_FINWAIT2_TIMER,
6592                     sysctl_tp_timer, "LU", "FINWAIT2 timer (us)");
6593
6594                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
6595                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_SYNSHIFTMAX,
6596                     sysctl_tp_shift_cnt, "IU",
6597                     "Number of SYN retransmissions before abort");
6598
6599                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
6600                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_RXTSHIFTMAXR2,
6601                     sysctl_tp_shift_cnt, "IU",
6602                     "Number of retransmissions before abort");
6603
6604                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
6605                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_KEEPALIVEMAXR2,
6606                     sysctl_tp_shift_cnt, "IU",
6607                     "Number of keepalive probes before abort");
6608
6609                 oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
6610                     CTLFLAG_RD, NULL, "TOE retransmit backoffs");
6611                 children = SYSCTL_CHILDREN(oid);
6612                 for (i = 0; i < 16; i++) {
6613                         snprintf(s, sizeof(s), "%u", i);
6614                         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
6615                             CTLTYPE_UINT | CTLFLAG_RD, sc, i, sysctl_tp_backoff,
6616                             "IU", "TOE retransmit backoff");
6617                 }
6618         }
6619 #endif
6620 }
6621
6622 void
6623 vi_sysctls(struct vi_info *vi)
6624 {
6625         struct sysctl_ctx_list *ctx;
6626         struct sysctl_oid *oid;
6627         struct sysctl_oid_list *children;
6628
6629         ctx = device_get_sysctl_ctx(vi->dev);
6630
6631         /*
6632          * dev.v?(cxgbe|cxl).X.
6633          */
6634         oid = device_get_sysctl_tree(vi->dev);
6635         children = SYSCTL_CHILDREN(oid);
6636
6637         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
6638             vi->viid, "VI identifer");
6639         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
6640             &vi->nrxq, 0, "# of rx queues");
6641         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
6642             &vi->ntxq, 0, "# of tx queues");
6643         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
6644             &vi->first_rxq, 0, "index of first rx queue");
6645         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
6646             &vi->first_txq, 0, "index of first tx queue");
6647         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
6648             vi->rss_base, "start of RSS indirection table");
6649         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
6650             vi->rss_size, "size of RSS indirection table");
6651
6652         if (IS_MAIN_VI(vi)) {
6653                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
6654                     CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_noflowq, "IU",
6655                     "Reserve queue 0 for non-flowid packets");
6656         }
6657
6658 #ifdef TCP_OFFLOAD
6659         if (vi->nofldrxq != 0) {
6660                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
6661                     &vi->nofldrxq, 0,
6662                     "# of rx queues for offloaded TCP connections");
6663                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
6664                     CTLFLAG_RD, &vi->first_ofld_rxq, 0,
6665                     "index of first TOE rx queue");
6666                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
6667                     CTLTYPE_INT | CTLFLAG_RW, vi, 0,
6668                     sysctl_holdoff_tmr_idx_ofld, "I",
6669                     "holdoff timer index for TOE queues");
6670                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
6671                     CTLTYPE_INT | CTLFLAG_RW, vi, 0,
6672                     sysctl_holdoff_pktc_idx_ofld, "I",
6673                     "holdoff packet counter index for TOE queues");
6674         }
6675 #endif
6676 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
6677         if (vi->nofldtxq != 0) {
6678                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
6679                     &vi->nofldtxq, 0,
6680                     "# of tx queues for TOE/ETHOFLD");
6681                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
6682                     CTLFLAG_RD, &vi->first_ofld_txq, 0,
6683                     "index of first TOE/ETHOFLD tx queue");
6684         }
6685 #endif
6686 #ifdef DEV_NETMAP
6687         if (vi->nnmrxq != 0) {
6688                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
6689                     &vi->nnmrxq, 0, "# of netmap rx queues");
6690                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
6691                     &vi->nnmtxq, 0, "# of netmap tx queues");
6692                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
6693                     CTLFLAG_RD, &vi->first_nm_rxq, 0,
6694                     "index of first netmap rx queue");
6695                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
6696                     CTLFLAG_RD, &vi->first_nm_txq, 0,
6697                     "index of first netmap tx queue");
6698         }
6699 #endif
6700
6701         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
6702             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_tmr_idx, "I",
6703             "holdoff timer index");
6704         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
6705             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_pktc_idx, "I",
6706             "holdoff packet counter index");
6707
6708         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
6709             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_rxq, "I",
6710             "rx queue size");
6711         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
6712             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_txq, "I",
6713             "tx queue size");
6714 }
6715
6716 static void
6717 cxgbe_sysctls(struct port_info *pi)
6718 {
6719         struct sysctl_ctx_list *ctx;
6720         struct sysctl_oid *oid;
6721         struct sysctl_oid_list *children, *children2;
6722         struct adapter *sc = pi->adapter;
6723         int i;
6724         char name[16];
6725         static char *tc_flags = {"\20\1USER\2SYNC\3ASYNC\4ERR"};
6726
6727         ctx = device_get_sysctl_ctx(pi->dev);
6728
6729         /*
6730          * dev.cxgbe.X.
6731          */
6732         oid = device_get_sysctl_tree(pi->dev);
6733         children = SYSCTL_CHILDREN(oid);
6734
6735         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc", CTLTYPE_STRING |
6736            CTLFLAG_RD, pi, 0, sysctl_linkdnrc, "A", "reason why link is down");
6737         if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
6738                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
6739                     CTLTYPE_INT | CTLFLAG_RD, pi, 0, sysctl_btphy, "I",
6740                     "PHY temperature (in Celsius)");
6741                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
6742                     CTLTYPE_INT | CTLFLAG_RD, pi, 1, sysctl_btphy, "I",
6743                     "PHY firmware version");
6744         }
6745
6746         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
6747             CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_pause_settings, "A",
6748     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
6749         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
6750             CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_fec, "A",
6751             "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
6752         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
6753             CTLTYPE_STRING, pi, 0, sysctl_module_fec, "A",
6754             "FEC recommended by the cable/transceiver");
6755         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
6756             CTLTYPE_INT | CTLFLAG_RW, pi, 0, sysctl_autoneg, "I",
6757             "autonegotiation (-1 = not supported)");
6758
6759         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
6760             &pi->link_cfg.pcaps, 0, "port capabilities");
6761         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
6762             &pi->link_cfg.acaps, 0, "advertised capabilities");
6763         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
6764             &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
6765
6766         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
6767             port_top_speed(pi), "max speed (in Gbps)");
6768         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
6769             pi->mps_bg_map, "MPS buffer group map");
6770         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
6771             NULL, pi->rx_e_chan_map, "TP rx e-channel map");
6772
6773         if (sc->flags & IS_VF)
6774                 return;
6775
6776         /*
6777          * dev.(cxgbe|cxl).X.tc.
6778          */
6779         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc", CTLFLAG_RD, NULL,
6780             "Tx scheduler traffic classes (cl_rl)");
6781         children2 = SYSCTL_CHILDREN(oid);
6782         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
6783             CTLFLAG_RW, &pi->sched_params->pktsize, 0,
6784             "pktsize for per-flow cl-rl (0 means up to the driver )");
6785         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
6786             CTLFLAG_RW, &pi->sched_params->burstsize, 0,
6787             "burstsize for per-flow cl-rl (0 means up to the driver)");
6788         for (i = 0; i < sc->chip_params->nsched_cls; i++) {
6789                 struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
6790
6791                 snprintf(name, sizeof(name), "%d", i);
6792                 children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
6793                     SYSCTL_CHILDREN(oid), OID_AUTO, name, CTLFLAG_RD, NULL,
6794                     "traffic class"));
6795                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
6796                     CTLTYPE_STRING | CTLFLAG_RD, tc_flags, (uintptr_t)&tc->flags,
6797                     sysctl_bitfield_8b, "A", "flags");
6798                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
6799                     CTLFLAG_RD, &tc->refcount, 0, "references to this class");
6800                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
6801                     CTLTYPE_STRING | CTLFLAG_RD, sc, (pi->port_id << 16) | i,
6802                     sysctl_tc_params, "A", "traffic class parameters");
6803         }
6804
6805         /*
6806          * dev.cxgbe.X.stats.
6807          */
6808         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats", CTLFLAG_RD,
6809             NULL, "port statistics");
6810         children = SYSCTL_CHILDREN(oid);
6811         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
6812             &pi->tx_parse_error, 0,
6813             "# of tx packets with invalid length or # of segments");
6814
6815 #define SYSCTL_ADD_T4_REG64(pi, name, desc, reg) \
6816         SYSCTL_ADD_OID(ctx, children, OID_AUTO, name, \
6817             CTLTYPE_U64 | CTLFLAG_RD, sc, reg, \
6818             sysctl_handle_t4_reg64, "QU", desc)
6819
6820         SYSCTL_ADD_T4_REG64(pi, "tx_octets", "# of octets in good frames",
6821             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BYTES_L));
6822         SYSCTL_ADD_T4_REG64(pi, "tx_frames", "total # of good frames",
6823             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_FRAMES_L));
6824         SYSCTL_ADD_T4_REG64(pi, "tx_bcast_frames", "# of broadcast frames",
6825             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BCAST_L));
6826         SYSCTL_ADD_T4_REG64(pi, "tx_mcast_frames", "# of multicast frames",
6827             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_MCAST_L));
6828         SYSCTL_ADD_T4_REG64(pi, "tx_ucast_frames", "# of unicast frames",
6829             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_UCAST_L));
6830         SYSCTL_ADD_T4_REG64(pi, "tx_error_frames", "# of error frames",
6831             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_ERROR_L));
6832         SYSCTL_ADD_T4_REG64(pi, "tx_frames_64",
6833             "# of tx frames in this range",
6834             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_64B_L));
6835         SYSCTL_ADD_T4_REG64(pi, "tx_frames_65_127",
6836             "# of tx frames in this range",
6837             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_65B_127B_L));
6838         SYSCTL_ADD_T4_REG64(pi, "tx_frames_128_255",
6839             "# of tx frames in this range",
6840             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_128B_255B_L));
6841         SYSCTL_ADD_T4_REG64(pi, "tx_frames_256_511",
6842             "# of tx frames in this range",
6843             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_256B_511B_L));
6844         SYSCTL_ADD_T4_REG64(pi, "tx_frames_512_1023",
6845             "# of tx frames in this range",
6846             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_512B_1023B_L));
6847         SYSCTL_ADD_T4_REG64(pi, "tx_frames_1024_1518",
6848             "# of tx frames in this range",
6849             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1024B_1518B_L));
6850         SYSCTL_ADD_T4_REG64(pi, "tx_frames_1519_max",
6851             "# of tx frames in this range",
6852             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1519B_MAX_L));
6853         SYSCTL_ADD_T4_REG64(pi, "tx_drop", "# of dropped tx frames",
6854             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_DROP_L));
6855         SYSCTL_ADD_T4_REG64(pi, "tx_pause", "# of pause frames transmitted",
6856             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PAUSE_L));
6857         SYSCTL_ADD_T4_REG64(pi, "tx_ppp0", "# of PPP prio 0 frames transmitted",
6858             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP0_L));
6859         SYSCTL_ADD_T4_REG64(pi, "tx_ppp1", "# of PPP prio 1 frames transmitted",
6860             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP1_L));
6861         SYSCTL_ADD_T4_REG64(pi, "tx_ppp2", "# of PPP prio 2 frames transmitted",
6862             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP2_L));
6863         SYSCTL_ADD_T4_REG64(pi, "tx_ppp3", "# of PPP prio 3 frames transmitted",
6864             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP3_L));
6865         SYSCTL_ADD_T4_REG64(pi, "tx_ppp4", "# of PPP prio 4 frames transmitted",
6866             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP4_L));
6867         SYSCTL_ADD_T4_REG64(pi, "tx_ppp5", "# of PPP prio 5 frames transmitted",
6868             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP5_L));
6869         SYSCTL_ADD_T4_REG64(pi, "tx_ppp6", "# of PPP prio 6 frames transmitted",
6870             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP6_L));
6871         SYSCTL_ADD_T4_REG64(pi, "tx_ppp7", "# of PPP prio 7 frames transmitted",
6872             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP7_L));
6873
6874         SYSCTL_ADD_T4_REG64(pi, "rx_octets", "# of octets in good frames",
6875             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BYTES_L));
6876         SYSCTL_ADD_T4_REG64(pi, "rx_frames", "total # of good frames",
6877             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_FRAMES_L));
6878         SYSCTL_ADD_T4_REG64(pi, "rx_bcast_frames", "# of broadcast frames",
6879             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BCAST_L));
6880         SYSCTL_ADD_T4_REG64(pi, "rx_mcast_frames", "# of multicast frames",
6881             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MCAST_L));
6882         SYSCTL_ADD_T4_REG64(pi, "rx_ucast_frames", "# of unicast frames",
6883             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_UCAST_L));
6884         SYSCTL_ADD_T4_REG64(pi, "rx_too_long", "# of frames exceeding MTU",
6885             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_ERROR_L));
6886         SYSCTL_ADD_T4_REG64(pi, "rx_jabber", "# of jabber frames",
6887             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_CRC_ERROR_L));
6888         SYSCTL_ADD_T4_REG64(pi, "rx_fcs_err",
6889             "# of frames received with bad FCS",
6890             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L));
6891         SYSCTL_ADD_T4_REG64(pi, "rx_len_err",
6892             "# of frames received with length error",
6893             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LEN_ERROR_L));
6894         SYSCTL_ADD_T4_REG64(pi, "rx_symbol_err", "symbol errors",
6895             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_SYM_ERROR_L));
6896         SYSCTL_ADD_T4_REG64(pi, "rx_runt", "# of short frames received",
6897             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LESS_64B_L));
6898         SYSCTL_ADD_T4_REG64(pi, "rx_frames_64",
6899             "# of rx frames in this range",
6900             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_64B_L));
6901         SYSCTL_ADD_T4_REG64(pi, "rx_frames_65_127",
6902             "# of rx frames in this range",
6903             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_65B_127B_L));
6904         SYSCTL_ADD_T4_REG64(pi, "rx_frames_128_255",
6905             "# of rx frames in this range",
6906             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_128B_255B_L));
6907         SYSCTL_ADD_T4_REG64(pi, "rx_frames_256_511",
6908             "# of rx frames in this range",
6909             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_256B_511B_L));
6910         SYSCTL_ADD_T4_REG64(pi, "rx_frames_512_1023",
6911             "# of rx frames in this range",
6912             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_512B_1023B_L));
6913         SYSCTL_ADD_T4_REG64(pi, "rx_frames_1024_1518",
6914             "# of rx frames in this range",
6915             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1024B_1518B_L));
6916         SYSCTL_ADD_T4_REG64(pi, "rx_frames_1519_max",
6917             "# of rx frames in this range",
6918             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1519B_MAX_L));
6919         SYSCTL_ADD_T4_REG64(pi, "rx_pause", "# of pause frames received",
6920             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PAUSE_L));
6921         SYSCTL_ADD_T4_REG64(pi, "rx_ppp0", "# of PPP prio 0 frames received",
6922             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP0_L));
6923         SYSCTL_ADD_T4_REG64(pi, "rx_ppp1", "# of PPP prio 1 frames received",
6924             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP1_L));
6925         SYSCTL_ADD_T4_REG64(pi, "rx_ppp2", "# of PPP prio 2 frames received",
6926             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP2_L));
6927         SYSCTL_ADD_T4_REG64(pi, "rx_ppp3", "# of PPP prio 3 frames received",
6928             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP3_L));
6929         SYSCTL_ADD_T4_REG64(pi, "rx_ppp4", "# of PPP prio 4 frames received",
6930             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP4_L));
6931         SYSCTL_ADD_T4_REG64(pi, "rx_ppp5", "# of PPP prio 5 frames received",
6932             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP5_L));
6933         SYSCTL_ADD_T4_REG64(pi, "rx_ppp6", "# of PPP prio 6 frames received",
6934             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP6_L));
6935         SYSCTL_ADD_T4_REG64(pi, "rx_ppp7", "# of PPP prio 7 frames received",
6936             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP7_L));
6937
6938 #undef SYSCTL_ADD_T4_REG64
6939
6940 #define SYSCTL_ADD_T4_PORTSTAT(name, desc) \
6941         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
6942             &pi->stats.name, desc)
6943
6944         /* We get these from port_stats and they may be stale by up to 1s */
6945         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow0,
6946             "# drops due to buffer-group 0 overflows");
6947         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow1,
6948             "# drops due to buffer-group 1 overflows");
6949         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow2,
6950             "# drops due to buffer-group 2 overflows");
6951         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow3,
6952             "# drops due to buffer-group 3 overflows");
6953         SYSCTL_ADD_T4_PORTSTAT(rx_trunc0,
6954             "# of buffer-group 0 truncated packets");
6955         SYSCTL_ADD_T4_PORTSTAT(rx_trunc1,
6956             "# of buffer-group 1 truncated packets");
6957         SYSCTL_ADD_T4_PORTSTAT(rx_trunc2,
6958             "# of buffer-group 2 truncated packets");
6959         SYSCTL_ADD_T4_PORTSTAT(rx_trunc3,
6960             "# of buffer-group 3 truncated packets");
6961
6962 #undef SYSCTL_ADD_T4_PORTSTAT
6963
6964         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_tls_records",
6965             CTLFLAG_RD, &pi->tx_tls_records,
6966             "# of TOE TLS records transmitted");
6967         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_tls_octets",
6968             CTLFLAG_RD, &pi->tx_tls_octets,
6969             "# of payload octets in transmitted TOE TLS records");
6970         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_tls_records",
6971             CTLFLAG_RD, &pi->rx_tls_records,
6972             "# of TOE TLS records received");
6973         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_tls_octets",
6974             CTLFLAG_RD, &pi->rx_tls_octets,
6975             "# of payload octets in received TOE TLS records");
6976 }
6977
6978 static int
6979 sysctl_int_array(SYSCTL_HANDLER_ARGS)
6980 {
6981         int rc, *i, space = 0;
6982         struct sbuf sb;
6983
6984         sbuf_new_for_sysctl(&sb, NULL, 64, req);
6985         for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
6986                 if (space)
6987                         sbuf_printf(&sb, " ");
6988                 sbuf_printf(&sb, "%d", *i);
6989                 space = 1;
6990         }
6991         rc = sbuf_finish(&sb);
6992         sbuf_delete(&sb);
6993         return (rc);
6994 }
6995
6996 static int
6997 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
6998 {
6999         int rc;
7000         struct sbuf *sb;
7001
7002         rc = sysctl_wire_old_buffer(req, 0);
7003         if (rc != 0)
7004                 return(rc);
7005
7006         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7007         if (sb == NULL)
7008                 return (ENOMEM);
7009
7010         sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
7011         rc = sbuf_finish(sb);
7012         sbuf_delete(sb);
7013
7014         return (rc);
7015 }
7016
7017 static int
7018 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
7019 {
7020         int rc;
7021         struct sbuf *sb;
7022
7023         rc = sysctl_wire_old_buffer(req, 0);
7024         if (rc != 0)
7025                 return(rc);
7026
7027         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7028         if (sb == NULL)
7029                 return (ENOMEM);
7030
7031         sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
7032         rc = sbuf_finish(sb);
7033         sbuf_delete(sb);
7034
7035         return (rc);
7036 }
7037
7038 static int
7039 sysctl_btphy(SYSCTL_HANDLER_ARGS)
7040 {
7041         struct port_info *pi = arg1;
7042         int op = arg2;
7043         struct adapter *sc = pi->adapter;
7044         u_int v;
7045         int rc;
7046
7047         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
7048         if (rc)
7049                 return (rc);
7050         /* XXX: magic numbers */
7051         rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
7052             &v);
7053         end_synchronized_op(sc, 0);
7054         if (rc)
7055                 return (rc);
7056         if (op == 0)
7057                 v /= 256;
7058
7059         rc = sysctl_handle_int(oidp, &v, 0, req);
7060         return (rc);
7061 }
7062
7063 static int
7064 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
7065 {
7066         struct vi_info *vi = arg1;
7067         int rc, val;
7068
7069         val = vi->rsrv_noflowq;
7070         rc = sysctl_handle_int(oidp, &val, 0, req);
7071         if (rc != 0 || req->newptr == NULL)
7072                 return (rc);
7073
7074         if ((val >= 1) && (vi->ntxq > 1))
7075                 vi->rsrv_noflowq = 1;
7076         else
7077                 vi->rsrv_noflowq = 0;
7078
7079         return (rc);
7080 }
7081
7082 static int
7083 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
7084 {
7085         struct vi_info *vi = arg1;
7086         struct adapter *sc = vi->pi->adapter;
7087         int idx, rc, i;
7088         struct sge_rxq *rxq;
7089         uint8_t v;
7090
7091         idx = vi->tmr_idx;
7092
7093         rc = sysctl_handle_int(oidp, &idx, 0, req);
7094         if (rc != 0 || req->newptr == NULL)
7095                 return (rc);
7096
7097         if (idx < 0 || idx >= SGE_NTIMERS)
7098                 return (EINVAL);
7099
7100         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7101             "t4tmr");
7102         if (rc)
7103                 return (rc);
7104
7105         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
7106         for_each_rxq(vi, i, rxq) {
7107 #ifdef atomic_store_rel_8
7108                 atomic_store_rel_8(&rxq->iq.intr_params, v);
7109 #else
7110                 rxq->iq.intr_params = v;
7111 #endif
7112         }
7113         vi->tmr_idx = idx;
7114
7115         end_synchronized_op(sc, LOCK_HELD);
7116         return (0);
7117 }
7118
7119 static int
7120 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
7121 {
7122         struct vi_info *vi = arg1;
7123         struct adapter *sc = vi->pi->adapter;
7124         int idx, rc;
7125
7126         idx = vi->pktc_idx;
7127
7128         rc = sysctl_handle_int(oidp, &idx, 0, req);
7129         if (rc != 0 || req->newptr == NULL)
7130                 return (rc);
7131
7132         if (idx < -1 || idx >= SGE_NCOUNTERS)
7133                 return (EINVAL);
7134
7135         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7136             "t4pktc");
7137         if (rc)
7138                 return (rc);
7139
7140         if (vi->flags & VI_INIT_DONE)
7141                 rc = EBUSY; /* cannot be changed once the queues are created */
7142         else
7143                 vi->pktc_idx = idx;
7144
7145         end_synchronized_op(sc, LOCK_HELD);
7146         return (rc);
7147 }
7148
7149 static int
7150 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
7151 {
7152         struct vi_info *vi = arg1;
7153         struct adapter *sc = vi->pi->adapter;
7154         int qsize, rc;
7155
7156         qsize = vi->qsize_rxq;
7157
7158         rc = sysctl_handle_int(oidp, &qsize, 0, req);
7159         if (rc != 0 || req->newptr == NULL)
7160                 return (rc);
7161
7162         if (qsize < 128 || (qsize & 7))
7163                 return (EINVAL);
7164
7165         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7166             "t4rxqs");
7167         if (rc)
7168                 return (rc);
7169
7170         if (vi->flags & VI_INIT_DONE)
7171                 rc = EBUSY; /* cannot be changed once the queues are created */
7172         else
7173                 vi->qsize_rxq = qsize;
7174
7175         end_synchronized_op(sc, LOCK_HELD);
7176         return (rc);
7177 }
7178
7179 static int
7180 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
7181 {
7182         struct vi_info *vi = arg1;
7183         struct adapter *sc = vi->pi->adapter;
7184         int qsize, rc;
7185
7186         qsize = vi->qsize_txq;
7187
7188         rc = sysctl_handle_int(oidp, &qsize, 0, req);
7189         if (rc != 0 || req->newptr == NULL)
7190                 return (rc);
7191
7192         if (qsize < 128 || qsize > 65536)
7193                 return (EINVAL);
7194
7195         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
7196             "t4txqs");
7197         if (rc)
7198                 return (rc);
7199
7200         if (vi->flags & VI_INIT_DONE)
7201                 rc = EBUSY; /* cannot be changed once the queues are created */
7202         else
7203                 vi->qsize_txq = qsize;
7204
7205         end_synchronized_op(sc, LOCK_HELD);
7206         return (rc);
7207 }
7208
7209 static int
7210 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
7211 {
7212         struct port_info *pi = arg1;
7213         struct adapter *sc = pi->adapter;
7214         struct link_config *lc = &pi->link_cfg;
7215         int rc;
7216
7217         if (req->newptr == NULL) {
7218                 struct sbuf *sb;
7219                 static char *bits = "\20\1RX\2TX\3AUTO";
7220
7221                 rc = sysctl_wire_old_buffer(req, 0);
7222                 if (rc != 0)
7223                         return(rc);
7224
7225                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7226                 if (sb == NULL)
7227                         return (ENOMEM);
7228
7229                 if (lc->link_ok) {
7230                         sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
7231                             (lc->requested_fc & PAUSE_AUTONEG), bits);
7232                 } else {
7233                         sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
7234                             PAUSE_RX | PAUSE_AUTONEG), bits);
7235                 }
7236                 rc = sbuf_finish(sb);
7237                 sbuf_delete(sb);
7238         } else {
7239                 char s[2];
7240                 int n;
7241
7242                 s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
7243                     PAUSE_AUTONEG));
7244                 s[1] = 0;
7245
7246                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
7247                 if (rc != 0)
7248                         return(rc);
7249
7250                 if (s[1] != 0)
7251                         return (EINVAL);
7252                 if (s[0] < '0' || s[0] > '9')
7253                         return (EINVAL);        /* not a number */
7254                 n = s[0] - '0';
7255                 if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
7256                         return (EINVAL);        /* some other bit is set too */
7257
7258                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7259                     "t4PAUSE");
7260                 if (rc)
7261                         return (rc);
7262                 PORT_LOCK(pi);
7263                 lc->requested_fc = n;
7264                 fixup_link_config(pi);
7265                 if (pi->up_vis > 0)
7266                         rc = apply_link_config(pi);
7267                 set_current_media(pi);
7268                 PORT_UNLOCK(pi);
7269                 end_synchronized_op(sc, 0);
7270         }
7271
7272         return (rc);
7273 }
7274
7275 static int
7276 sysctl_fec(SYSCTL_HANDLER_ARGS)
7277 {
7278         struct port_info *pi = arg1;
7279         struct adapter *sc = pi->adapter;
7280         struct link_config *lc = &pi->link_cfg;
7281         int rc;
7282         int8_t old;
7283
7284         if (req->newptr == NULL) {
7285                 struct sbuf *sb;
7286                 static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
7287                     "\5RSVD3\6auto\7module";
7288
7289                 rc = sysctl_wire_old_buffer(req, 0);
7290                 if (rc != 0)
7291                         return(rc);
7292
7293                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7294                 if (sb == NULL)
7295                         return (ENOMEM);
7296
7297                 /*
7298                  * Display the requested_fec when the link is down -- the actual
7299                  * FEC makes sense only when the link is up.
7300                  */
7301                 if (lc->link_ok) {
7302                         sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
7303                             (lc->requested_fec & (FEC_AUTO | FEC_MODULE)),
7304                             bits);
7305                 } else {
7306                         sbuf_printf(sb, "%b", lc->requested_fec, bits);
7307                 }
7308                 rc = sbuf_finish(sb);
7309                 sbuf_delete(sb);
7310         } else {
7311                 char s[8];
7312                 int n;
7313
7314                 snprintf(s, sizeof(s), "%d",
7315                     lc->requested_fec == FEC_AUTO ? -1 :
7316                     lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
7317
7318                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
7319                 if (rc != 0)
7320                         return(rc);
7321
7322                 n = strtol(&s[0], NULL, 0);
7323                 if (n < 0 || n & FEC_AUTO)
7324                         n = FEC_AUTO;
7325                 else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
7326                         return (EINVAL);/* some other bit is set too */
7327
7328                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7329                     "t4fec");
7330                 if (rc)
7331                         return (rc);
7332                 PORT_LOCK(pi);
7333                 old = lc->requested_fec;
7334                 if (n == FEC_AUTO)
7335                         lc->requested_fec = FEC_AUTO;
7336                 else if (n == 0 || n == FEC_NONE)
7337                         lc->requested_fec = FEC_NONE;
7338                 else {
7339                         if ((lc->pcaps |
7340                             V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
7341                             lc->pcaps) {
7342                                 rc = ENOTSUP;
7343                                 goto done;
7344                         }
7345                         lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
7346                             FEC_MODULE);
7347                 }
7348                 fixup_link_config(pi);
7349                 if (pi->up_vis > 0) {
7350                         rc = apply_link_config(pi);
7351                         if (rc != 0) {
7352                                 lc->requested_fec = old;
7353                                 if (rc == FW_EPROTO)
7354                                         rc = ENOTSUP;
7355                         }
7356                 }
7357 done:
7358                 PORT_UNLOCK(pi);
7359                 end_synchronized_op(sc, 0);
7360         }
7361
7362         return (rc);
7363 }
7364
7365 static int
7366 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
7367 {
7368         struct port_info *pi = arg1;
7369         struct adapter *sc = pi->adapter;
7370         struct link_config *lc = &pi->link_cfg;
7371         int rc;
7372         int8_t fec;
7373         struct sbuf *sb;
7374         static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
7375
7376         rc = sysctl_wire_old_buffer(req, 0);
7377         if (rc != 0)
7378                 return (rc);
7379
7380         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
7381         if (sb == NULL)
7382                 return (ENOMEM);
7383
7384         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0)
7385                 return (EBUSY);
7386         PORT_LOCK(pi);
7387         if (pi->up_vis == 0) {
7388                 /*
7389                  * If all the interfaces are administratively down the firmware
7390                  * does not report transceiver changes.  Refresh port info here.
7391                  * This is the only reason we have a synchronized op in this
7392                  * function.  Just PORT_LOCK would have been enough otherwise.
7393                  */
7394                 t4_update_port_info(pi);
7395         }
7396
7397         fec = lc->fec_hint;
7398         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
7399             !fec_supported(lc->pcaps)) {
7400                 sbuf_printf(sb, "n/a");
7401         } else {
7402                 if (fec == 0)
7403                         fec = FEC_NONE;
7404                 sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
7405         }
7406         rc = sbuf_finish(sb);
7407         sbuf_delete(sb);
7408
7409         PORT_UNLOCK(pi);
7410         end_synchronized_op(sc, 0);
7411
7412         return (rc);
7413 }
7414
7415 static int
7416 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
7417 {
7418         struct port_info *pi = arg1;
7419         struct adapter *sc = pi->adapter;
7420         struct link_config *lc = &pi->link_cfg;
7421         int rc, val;
7422
7423         if (lc->pcaps & FW_PORT_CAP32_ANEG)
7424                 val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
7425         else
7426                 val = -1;
7427         rc = sysctl_handle_int(oidp, &val, 0, req);
7428         if (rc != 0 || req->newptr == NULL)
7429                 return (rc);
7430         if (val == 0)
7431                 val = AUTONEG_DISABLE;
7432         else if (val == 1)
7433                 val = AUTONEG_ENABLE;
7434         else
7435                 val = AUTONEG_AUTO;
7436
7437         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7438             "t4aneg");
7439         if (rc)
7440                 return (rc);
7441         PORT_LOCK(pi);
7442         if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
7443                 rc = ENOTSUP;
7444                 goto done;
7445         }
7446         lc->requested_aneg = val;
7447         fixup_link_config(pi);
7448         if (pi->up_vis > 0)
7449                 rc = apply_link_config(pi);
7450         set_current_media(pi);
7451 done:
7452         PORT_UNLOCK(pi);
7453         end_synchronized_op(sc, 0);
7454         return (rc);
7455 }
7456
7457 static int
7458 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
7459 {
7460         struct adapter *sc = arg1;
7461         int reg = arg2;
7462         uint64_t val;
7463
7464         val = t4_read_reg64(sc, reg);
7465
7466         return (sysctl_handle_64(oidp, &val, 0, req));
7467 }
7468
7469 static int
7470 sysctl_temperature(SYSCTL_HANDLER_ARGS)
7471 {
7472         struct adapter *sc = arg1;
7473         int rc, t;
7474         uint32_t param, val;
7475
7476         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
7477         if (rc)
7478                 return (rc);
7479         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7480             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7481             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
7482         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7483         end_synchronized_op(sc, 0);
7484         if (rc)
7485                 return (rc);
7486
7487         /* unknown is returned as 0 but we display -1 in that case */
7488         t = val == 0 ? -1 : val;
7489
7490         rc = sysctl_handle_int(oidp, &t, 0, req);
7491         return (rc);
7492 }
7493
7494 static int
7495 sysctl_vdd(SYSCTL_HANDLER_ARGS)
7496 {
7497         struct adapter *sc = arg1;
7498         int rc;
7499         uint32_t param, val;
7500
7501         if (sc->params.core_vdd == 0) {
7502                 rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
7503                     "t4vdd");
7504                 if (rc)
7505                         return (rc);
7506                 param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7507                     V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7508                     V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
7509                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7510                 end_synchronized_op(sc, 0);
7511                 if (rc)
7512                         return (rc);
7513                 sc->params.core_vdd = val;
7514         }
7515
7516         return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
7517 }
7518
7519 static int
7520 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
7521 {
7522         struct adapter *sc = arg1;
7523         int rc, v;
7524         uint32_t param, val;
7525
7526         v = sc->sensor_resets;
7527         rc = sysctl_handle_int(oidp, &v, 0, req);
7528         if (rc != 0 || req->newptr == NULL || v <= 0)
7529                 return (rc);
7530
7531         if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
7532             chip_id(sc) < CHELSIO_T5)
7533                 return (ENOTSUP);
7534
7535         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
7536         if (rc)
7537                 return (rc);
7538         param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7539             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7540             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
7541         val = 1;
7542         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7543         end_synchronized_op(sc, 0);
7544         if (rc == 0)
7545                 sc->sensor_resets++;
7546         return (rc);
7547 }
7548
7549 static int
7550 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
7551 {
7552         struct adapter *sc = arg1;
7553         struct sbuf *sb;
7554         int rc;
7555         uint32_t param, val;
7556
7557         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
7558         if (rc)
7559                 return (rc);
7560         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7561             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
7562         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7563         end_synchronized_op(sc, 0);
7564         if (rc)
7565                 return (rc);
7566
7567         rc = sysctl_wire_old_buffer(req, 0);
7568         if (rc != 0)
7569                 return (rc);
7570
7571         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7572         if (sb == NULL)
7573                 return (ENOMEM);
7574
7575         if (val == 0xffffffff) {
7576                 /* Only debug and custom firmwares report load averages. */
7577                 sbuf_printf(sb, "not available");
7578         } else {
7579                 sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
7580                     (val >> 16) & 0xff);
7581         }
7582         rc = sbuf_finish(sb);
7583         sbuf_delete(sb);
7584
7585         return (rc);
7586 }
7587
7588 static int
7589 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
7590 {
7591         struct adapter *sc = arg1;
7592         struct sbuf *sb;
7593         int rc, i;
7594         uint16_t incr[NMTUS][NCCTRL_WIN];
7595         static const char *dec_fac[] = {
7596                 "0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
7597                 "0.9375"
7598         };
7599
7600         rc = sysctl_wire_old_buffer(req, 0);
7601         if (rc != 0)
7602                 return (rc);
7603
7604         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7605         if (sb == NULL)
7606                 return (ENOMEM);
7607
7608         t4_read_cong_tbl(sc, incr);
7609
7610         for (i = 0; i < NCCTRL_WIN; ++i) {
7611                 sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
7612                     incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
7613                     incr[5][i], incr[6][i], incr[7][i]);
7614                 sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
7615                     incr[8][i], incr[9][i], incr[10][i], incr[11][i],
7616                     incr[12][i], incr[13][i], incr[14][i], incr[15][i],
7617                     sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
7618         }
7619
7620         rc = sbuf_finish(sb);
7621         sbuf_delete(sb);
7622
7623         return (rc);
7624 }
7625
7626 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
7627         "TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",   /* ibq's */
7628         "ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", /* obq's */
7629         "SGE0-RX", "SGE1-RX"    /* additional obq's (T5 onwards) */
7630 };
7631
7632 static int
7633 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
7634 {
7635         struct adapter *sc = arg1;
7636         struct sbuf *sb;
7637         int rc, i, n, qid = arg2;
7638         uint32_t *buf, *p;
7639         char *qtype;
7640         u_int cim_num_obq = sc->chip_params->cim_num_obq;
7641
7642         KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
7643             ("%s: bad qid %d\n", __func__, qid));
7644
7645         if (qid < CIM_NUM_IBQ) {
7646                 /* inbound queue */
7647                 qtype = "IBQ";
7648                 n = 4 * CIM_IBQ_SIZE;
7649                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7650                 rc = t4_read_cim_ibq(sc, qid, buf, n);
7651         } else {
7652                 /* outbound queue */
7653                 qtype = "OBQ";
7654                 qid -= CIM_NUM_IBQ;
7655                 n = 4 * cim_num_obq * CIM_OBQ_SIZE;
7656                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7657                 rc = t4_read_cim_obq(sc, qid, buf, n);
7658         }
7659
7660         if (rc < 0) {
7661                 rc = -rc;
7662                 goto done;
7663         }
7664         n = rc * sizeof(uint32_t);      /* rc has # of words actually read */
7665
7666         rc = sysctl_wire_old_buffer(req, 0);
7667         if (rc != 0)
7668                 goto done;
7669
7670         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7671         if (sb == NULL) {
7672                 rc = ENOMEM;
7673                 goto done;
7674         }
7675
7676         sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
7677         for (i = 0, p = buf; i < n; i += 16, p += 4)
7678                 sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
7679                     p[2], p[3]);
7680
7681         rc = sbuf_finish(sb);
7682         sbuf_delete(sb);
7683 done:
7684         free(buf, M_CXGBE);
7685         return (rc);
7686 }
7687
7688 static void
7689 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
7690 {
7691         uint32_t *p;
7692
7693         sbuf_printf(sb, "Status   Data      PC%s",
7694             cfg & F_UPDBGLACAPTPCONLY ? "" :
7695             "     LS0Stat  LS0Addr             LS0Data");
7696
7697         for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
7698                 if (cfg & F_UPDBGLACAPTPCONLY) {
7699                         sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
7700                             p[6], p[7]);
7701                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
7702                             (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
7703                             p[4] & 0xff, p[5] >> 8);
7704                         sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
7705                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7706                             p[1] & 0xf, p[2] >> 4);
7707                 } else {
7708                         sbuf_printf(sb,
7709                             "\n  %02x   %x%07x %x%07x %08x %08x "
7710                             "%08x%08x%08x%08x",
7711                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7712                             p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
7713                             p[6], p[7]);
7714                 }
7715         }
7716 }
7717
7718 static void
7719 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
7720 {
7721         uint32_t *p;
7722
7723         sbuf_printf(sb, "Status   Inst    Data      PC%s",
7724             cfg & F_UPDBGLACAPTPCONLY ? "" :
7725             "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
7726
7727         for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
7728                 if (cfg & F_UPDBGLACAPTPCONLY) {
7729                         sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
7730                             p[3] & 0xff, p[2], p[1], p[0]);
7731                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
7732                             (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
7733                             p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
7734                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
7735                             (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
7736                             p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
7737                             p[6] >> 16);
7738                 } else {
7739                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
7740                             "%08x %08x %08x %08x %08x %08x",
7741                             (p[9] >> 16) & 0xff,
7742                             p[9] & 0xffff, p[8] >> 16,
7743                             p[8] & 0xffff, p[7] >> 16,
7744                             p[7] & 0xffff, p[6] >> 16,
7745                             p[2], p[1], p[0], p[5], p[4], p[3]);
7746                 }
7747         }
7748 }
7749
7750 static int
7751 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
7752 {
7753         uint32_t cfg, *buf;
7754         int rc;
7755
7756         rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
7757         if (rc != 0)
7758                 return (rc);
7759
7760         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
7761         buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
7762             M_ZERO | flags);
7763         if (buf == NULL)
7764                 return (ENOMEM);
7765
7766         rc = -t4_cim_read_la(sc, buf, NULL);
7767         if (rc != 0)
7768                 goto done;
7769         if (chip_id(sc) < CHELSIO_T6)
7770                 sbuf_cim_la4(sc, sb, buf, cfg);
7771         else
7772                 sbuf_cim_la6(sc, sb, buf, cfg);
7773
7774 done:
7775         free(buf, M_CXGBE);
7776         return (rc);
7777 }
7778
7779 static int
7780 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
7781 {
7782         struct adapter *sc = arg1;
7783         struct sbuf *sb;
7784         int rc;
7785
7786         rc = sysctl_wire_old_buffer(req, 0);
7787         if (rc != 0)
7788                 return (rc);
7789         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7790         if (sb == NULL)
7791                 return (ENOMEM);
7792
7793         rc = sbuf_cim_la(sc, sb, M_WAITOK);
7794         if (rc == 0)
7795                 rc = sbuf_finish(sb);
7796         sbuf_delete(sb);
7797         return (rc);
7798 }
7799
7800 bool
7801 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
7802 {
7803         struct sbuf sb;
7804         int rc;
7805
7806         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
7807                 return (false);
7808         rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
7809         if (rc == 0) {
7810                 rc = sbuf_finish(&sb);
7811                 if (rc == 0) {
7812                         log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
7813                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
7814                 }
7815         }
7816         sbuf_delete(&sb);
7817         return (false);
7818 }
7819
7820 static int
7821 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
7822 {
7823         struct adapter *sc = arg1;
7824         u_int i;
7825         struct sbuf *sb;
7826         uint32_t *buf, *p;
7827         int rc;
7828
7829         rc = sysctl_wire_old_buffer(req, 0);
7830         if (rc != 0)
7831                 return (rc);
7832
7833         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7834         if (sb == NULL)
7835                 return (ENOMEM);
7836
7837         buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
7838             M_ZERO | M_WAITOK);
7839
7840         t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
7841         p = buf;
7842
7843         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
7844                 sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
7845                     p[1], p[0]);
7846         }
7847
7848         sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
7849         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
7850                 sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
7851                     (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
7852                     (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
7853                     (p[1] >> 2) | ((p[2] & 3) << 30),
7854                     (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
7855                     p[0] & 1);
7856         }
7857
7858         rc = sbuf_finish(sb);
7859         sbuf_delete(sb);
7860         free(buf, M_CXGBE);
7861         return (rc);
7862 }
7863
7864 static int
7865 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
7866 {
7867         struct adapter *sc = arg1;
7868         u_int i;
7869         struct sbuf *sb;
7870         uint32_t *buf, *p;
7871         int rc;
7872
7873         rc = sysctl_wire_old_buffer(req, 0);
7874         if (rc != 0)
7875                 return (rc);
7876
7877         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7878         if (sb == NULL)
7879                 return (ENOMEM);
7880
7881         buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
7882             M_ZERO | M_WAITOK);
7883
7884         t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
7885         p = buf;
7886
7887         sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
7888         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
7889                 sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
7890                     (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
7891                     p[4], p[3], p[2], p[1], p[0]);
7892         }
7893
7894         sbuf_printf(sb, "\n\nCntl ID               Data");
7895         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
7896                 sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
7897                     (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
7898         }
7899
7900         rc = sbuf_finish(sb);
7901         sbuf_delete(sb);
7902         free(buf, M_CXGBE);
7903         return (rc);
7904 }
7905
7906 static int
7907 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
7908 {
7909         struct adapter *sc = arg1;
7910         struct sbuf *sb;
7911         int rc, i;
7912         uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
7913         uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
7914         uint16_t thres[CIM_NUM_IBQ];
7915         uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
7916         uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
7917         u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
7918
7919         cim_num_obq = sc->chip_params->cim_num_obq;
7920         if (is_t4(sc)) {
7921                 ibq_rdaddr = A_UP_IBQ_0_RDADDR;
7922                 obq_rdaddr = A_UP_OBQ_0_REALADDR;
7923         } else {
7924                 ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
7925                 obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
7926         }
7927         nq = CIM_NUM_IBQ + cim_num_obq;
7928
7929         rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
7930         if (rc == 0)
7931                 rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
7932         if (rc != 0)
7933                 return (rc);
7934
7935         t4_read_cimq_cfg(sc, base, size, thres);
7936
7937         rc = sysctl_wire_old_buffer(req, 0);
7938         if (rc != 0)
7939                 return (rc);
7940
7941         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7942         if (sb == NULL)
7943                 return (ENOMEM);
7944
7945         sbuf_printf(sb,
7946             "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
7947
7948         for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
7949                 sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
7950                     qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
7951                     G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
7952                     G_QUEREMFLITS(p[2]) * 16);
7953         for ( ; i < nq; i++, p += 4, wr += 2)
7954                 sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
7955                     base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
7956                     wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
7957                     G_QUEREMFLITS(p[2]) * 16);
7958
7959         rc = sbuf_finish(sb);
7960         sbuf_delete(sb);
7961
7962         return (rc);
7963 }
7964
7965 static int
7966 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
7967 {
7968         struct adapter *sc = arg1;
7969         struct sbuf *sb;
7970         int rc;
7971         struct tp_cpl_stats stats;
7972
7973         rc = sysctl_wire_old_buffer(req, 0);
7974         if (rc != 0)
7975                 return (rc);
7976
7977         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7978         if (sb == NULL)
7979                 return (ENOMEM);
7980
7981         mtx_lock(&sc->reg_lock);
7982         t4_tp_get_cpl_stats(sc, &stats, 0);
7983         mtx_unlock(&sc->reg_lock);
7984
7985         if (sc->chip_params->nchan > 2) {
7986                 sbuf_printf(sb, "                 channel 0  channel 1"
7987                     "  channel 2  channel 3");
7988                 sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
7989                     stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
7990                 sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
7991                     stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
7992         } else {
7993                 sbuf_printf(sb, "                 channel 0  channel 1");
7994                 sbuf_printf(sb, "\nCPL requests:   %10u %10u",
7995                     stats.req[0], stats.req[1]);
7996                 sbuf_printf(sb, "\nCPL responses:   %10u %10u",
7997                     stats.rsp[0], stats.rsp[1]);
7998         }
7999
8000         rc = sbuf_finish(sb);
8001         sbuf_delete(sb);
8002
8003         return (rc);
8004 }
8005
8006 static int
8007 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
8008 {
8009         struct adapter *sc = arg1;
8010         struct sbuf *sb;
8011         int rc;
8012         struct tp_usm_stats stats;
8013
8014         rc = sysctl_wire_old_buffer(req, 0);
8015         if (rc != 0)
8016                 return(rc);
8017
8018         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8019         if (sb == NULL)
8020                 return (ENOMEM);
8021
8022         t4_get_usm_stats(sc, &stats, 1);
8023
8024         sbuf_printf(sb, "Frames: %u\n", stats.frames);
8025         sbuf_printf(sb, "Octets: %ju\n", stats.octets);
8026         sbuf_printf(sb, "Drops:  %u", stats.drops);
8027
8028         rc = sbuf_finish(sb);
8029         sbuf_delete(sb);
8030
8031         return (rc);
8032 }
8033
8034 static const char * const devlog_level_strings[] = {
8035         [FW_DEVLOG_LEVEL_EMERG]         = "EMERG",
8036         [FW_DEVLOG_LEVEL_CRIT]          = "CRIT",
8037         [FW_DEVLOG_LEVEL_ERR]           = "ERR",
8038         [FW_DEVLOG_LEVEL_NOTICE]        = "NOTICE",
8039         [FW_DEVLOG_LEVEL_INFO]          = "INFO",
8040         [FW_DEVLOG_LEVEL_DEBUG]         = "DEBUG"
8041 };
8042
8043 static const char * const devlog_facility_strings[] = {
8044         [FW_DEVLOG_FACILITY_CORE]       = "CORE",
8045         [FW_DEVLOG_FACILITY_CF]         = "CF",
8046         [FW_DEVLOG_FACILITY_SCHED]      = "SCHED",
8047         [FW_DEVLOG_FACILITY_TIMER]      = "TIMER",
8048         [FW_DEVLOG_FACILITY_RES]        = "RES",
8049         [FW_DEVLOG_FACILITY_HW]         = "HW",
8050         [FW_DEVLOG_FACILITY_FLR]        = "FLR",
8051         [FW_DEVLOG_FACILITY_DMAQ]       = "DMAQ",
8052         [FW_DEVLOG_FACILITY_PHY]        = "PHY",
8053         [FW_DEVLOG_FACILITY_MAC]        = "MAC",
8054         [FW_DEVLOG_FACILITY_PORT]       = "PORT",
8055         [FW_DEVLOG_FACILITY_VI]         = "VI",
8056         [FW_DEVLOG_FACILITY_FILTER]     = "FILTER",
8057         [FW_DEVLOG_FACILITY_ACL]        = "ACL",
8058         [FW_DEVLOG_FACILITY_TM]         = "TM",
8059         [FW_DEVLOG_FACILITY_QFC]        = "QFC",
8060         [FW_DEVLOG_FACILITY_DCB]        = "DCB",
8061         [FW_DEVLOG_FACILITY_ETH]        = "ETH",
8062         [FW_DEVLOG_FACILITY_OFLD]       = "OFLD",
8063         [FW_DEVLOG_FACILITY_RI]         = "RI",
8064         [FW_DEVLOG_FACILITY_ISCSI]      = "ISCSI",
8065         [FW_DEVLOG_FACILITY_FCOE]       = "FCOE",
8066         [FW_DEVLOG_FACILITY_FOISCSI]    = "FOISCSI",
8067         [FW_DEVLOG_FACILITY_FOFCOE]     = "FOFCOE",
8068         [FW_DEVLOG_FACILITY_CHNET]      = "CHNET",
8069 };
8070
8071 static int
8072 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
8073 {
8074         int i, j, rc, nentries, first = 0;
8075         struct devlog_params *dparams = &sc->params.devlog;
8076         struct fw_devlog_e *buf, *e;
8077         uint64_t ftstamp = UINT64_MAX;
8078
8079         if (dparams->addr == 0)
8080                 return (ENXIO);
8081
8082         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
8083         buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
8084         if (buf == NULL)
8085                 return (ENOMEM);
8086
8087         rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
8088         if (rc != 0)
8089                 goto done;
8090
8091         nentries = dparams->size / sizeof(struct fw_devlog_e);
8092         for (i = 0; i < nentries; i++) {
8093                 e = &buf[i];
8094
8095                 if (e->timestamp == 0)
8096                         break;  /* end */
8097
8098                 e->timestamp = be64toh(e->timestamp);
8099                 e->seqno = be32toh(e->seqno);
8100                 for (j = 0; j < 8; j++)
8101                         e->params[j] = be32toh(e->params[j]);
8102
8103                 if (e->timestamp < ftstamp) {
8104                         ftstamp = e->timestamp;
8105                         first = i;
8106                 }
8107         }
8108
8109         if (buf[first].timestamp == 0)
8110                 goto done;      /* nothing in the log */
8111
8112         sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
8113             "Seq#", "Tstamp", "Level", "Facility", "Message");
8114
8115         i = first;
8116         do {
8117                 e = &buf[i];
8118                 if (e->timestamp == 0)
8119                         break;  /* end */
8120
8121                 sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
8122                     e->seqno, e->timestamp,
8123                     (e->level < nitems(devlog_level_strings) ?
8124                         devlog_level_strings[e->level] : "UNKNOWN"),
8125                     (e->facility < nitems(devlog_facility_strings) ?
8126                         devlog_facility_strings[e->facility] : "UNKNOWN"));
8127                 sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
8128                     e->params[2], e->params[3], e->params[4],
8129                     e->params[5], e->params[6], e->params[7]);
8130
8131                 if (++i == nentries)
8132                         i = 0;
8133         } while (i != first);
8134 done:
8135         free(buf, M_CXGBE);
8136         return (rc);
8137 }
8138
8139 static int
8140 sysctl_devlog(SYSCTL_HANDLER_ARGS)
8141 {
8142         struct adapter *sc = arg1;
8143         int rc;
8144         struct sbuf *sb;
8145
8146         rc = sysctl_wire_old_buffer(req, 0);
8147         if (rc != 0)
8148                 return (rc);
8149         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8150         if (sb == NULL)
8151                 return (ENOMEM);
8152
8153         rc = sbuf_devlog(sc, sb, M_WAITOK);
8154         if (rc == 0)
8155                 rc = sbuf_finish(sb);
8156         sbuf_delete(sb);
8157         return (rc);
8158 }
8159
8160 void
8161 t4_os_dump_devlog(struct adapter *sc)
8162 {
8163         int rc;
8164         struct sbuf sb;
8165
8166         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
8167                 return;
8168         rc = sbuf_devlog(sc, &sb, M_NOWAIT);
8169         if (rc == 0) {
8170                 rc = sbuf_finish(&sb);
8171                 if (rc == 0) {
8172                         log(LOG_DEBUG, "%s: device log follows.\n%s",
8173                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
8174                 }
8175         }
8176         sbuf_delete(&sb);
8177 }
8178
8179 static int
8180 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
8181 {
8182         struct adapter *sc = arg1;
8183         struct sbuf *sb;
8184         int rc;
8185         struct tp_fcoe_stats stats[MAX_NCHAN];
8186         int i, nchan = sc->chip_params->nchan;
8187
8188         rc = sysctl_wire_old_buffer(req, 0);
8189         if (rc != 0)
8190                 return (rc);
8191
8192         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8193         if (sb == NULL)
8194                 return (ENOMEM);
8195
8196         for (i = 0; i < nchan; i++)
8197                 t4_get_fcoe_stats(sc, i, &stats[i], 1);
8198
8199         if (nchan > 2) {
8200                 sbuf_printf(sb, "                   channel 0        channel 1"
8201                     "        channel 2        channel 3");
8202                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
8203                     stats[0].octets_ddp, stats[1].octets_ddp,
8204                     stats[2].octets_ddp, stats[3].octets_ddp);
8205                 sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
8206                     stats[0].frames_ddp, stats[1].frames_ddp,
8207                     stats[2].frames_ddp, stats[3].frames_ddp);
8208                 sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
8209                     stats[0].frames_drop, stats[1].frames_drop,
8210                     stats[2].frames_drop, stats[3].frames_drop);
8211         } else {
8212                 sbuf_printf(sb, "                   channel 0        channel 1");
8213                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
8214                     stats[0].octets_ddp, stats[1].octets_ddp);
8215                 sbuf_printf(sb, "\nframesDDP:  %16u %16u",
8216                     stats[0].frames_ddp, stats[1].frames_ddp);
8217                 sbuf_printf(sb, "\nframesDrop: %16u %16u",
8218                     stats[0].frames_drop, stats[1].frames_drop);
8219         }
8220
8221         rc = sbuf_finish(sb);
8222         sbuf_delete(sb);
8223
8224         return (rc);
8225 }
8226
8227 static int
8228 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
8229 {
8230         struct adapter *sc = arg1;
8231         struct sbuf *sb;
8232         int rc, i;
8233         unsigned int map, kbps, ipg, mode;
8234         unsigned int pace_tab[NTX_SCHED];
8235
8236         rc = sysctl_wire_old_buffer(req, 0);
8237         if (rc != 0)
8238                 return (rc);
8239
8240         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8241         if (sb == NULL)
8242                 return (ENOMEM);
8243
8244         map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
8245         mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
8246         t4_read_pace_tbl(sc, pace_tab);
8247
8248         sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
8249             "Class IPG (0.1 ns)   Flow IPG (us)");
8250
8251         for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
8252                 t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
8253                 sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
8254                     (mode & (1 << i)) ? "flow" : "class", map & 3);
8255                 if (kbps)
8256                         sbuf_printf(sb, "%9u     ", kbps);
8257                 else
8258                         sbuf_printf(sb, " disabled     ");
8259
8260                 if (ipg)
8261                         sbuf_printf(sb, "%13u        ", ipg);
8262                 else
8263                         sbuf_printf(sb, "     disabled        ");
8264
8265                 if (pace_tab[i])
8266                         sbuf_printf(sb, "%10u", pace_tab[i]);
8267                 else
8268                         sbuf_printf(sb, "  disabled");
8269         }
8270
8271         rc = sbuf_finish(sb);
8272         sbuf_delete(sb);
8273
8274         return (rc);
8275 }
8276
8277 static int
8278 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
8279 {
8280         struct adapter *sc = arg1;
8281         struct sbuf *sb;
8282         int rc, i, j;
8283         uint64_t *p0, *p1;
8284         struct lb_port_stats s[2];
8285         static const char *stat_name[] = {
8286                 "OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
8287                 "UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
8288                 "Frames128To255:", "Frames256To511:", "Frames512To1023:",
8289                 "Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
8290                 "BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
8291                 "BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
8292                 "BG2FramesTrunc:", "BG3FramesTrunc:"
8293         };
8294
8295         rc = sysctl_wire_old_buffer(req, 0);
8296         if (rc != 0)
8297                 return (rc);
8298
8299         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8300         if (sb == NULL)
8301                 return (ENOMEM);
8302
8303         memset(s, 0, sizeof(s));
8304
8305         for (i = 0; i < sc->chip_params->nchan; i += 2) {
8306                 t4_get_lb_stats(sc, i, &s[0]);
8307                 t4_get_lb_stats(sc, i + 1, &s[1]);
8308
8309                 p0 = &s[0].octets;
8310                 p1 = &s[1].octets;
8311                 sbuf_printf(sb, "%s                       Loopback %u"
8312                     "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
8313
8314                 for (j = 0; j < nitems(stat_name); j++)
8315                         sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
8316                                    *p0++, *p1++);
8317         }
8318
8319         rc = sbuf_finish(sb);
8320         sbuf_delete(sb);
8321
8322         return (rc);
8323 }
8324
8325 static int
8326 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
8327 {
8328         int rc = 0;
8329         struct port_info *pi = arg1;
8330         struct link_config *lc = &pi->link_cfg;
8331         struct sbuf *sb;
8332
8333         rc = sysctl_wire_old_buffer(req, 0);
8334         if (rc != 0)
8335                 return(rc);
8336         sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
8337         if (sb == NULL)
8338                 return (ENOMEM);
8339
8340         if (lc->link_ok || lc->link_down_rc == 255)
8341                 sbuf_printf(sb, "n/a");
8342         else
8343                 sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
8344
8345         rc = sbuf_finish(sb);
8346         sbuf_delete(sb);
8347
8348         return (rc);
8349 }
8350
8351 struct mem_desc {
8352         unsigned int base;
8353         unsigned int limit;
8354         unsigned int idx;
8355 };
8356
8357 static int
8358 mem_desc_cmp(const void *a, const void *b)
8359 {
8360         return ((const struct mem_desc *)a)->base -
8361                ((const struct mem_desc *)b)->base;
8362 }
8363
8364 static void
8365 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
8366     unsigned int to)
8367 {
8368         unsigned int size;
8369
8370         if (from == to)
8371                 return;
8372
8373         size = to - from + 1;
8374         if (size == 0)
8375                 return;
8376
8377         /* XXX: need humanize_number(3) in libkern for a more readable 'size' */
8378         sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
8379 }
8380
8381 static int
8382 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
8383 {
8384         struct adapter *sc = arg1;
8385         struct sbuf *sb;
8386         int rc, i, n;
8387         uint32_t lo, hi, used, alloc;
8388         static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
8389         static const char *region[] = {
8390                 "DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
8391                 "Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
8392                 "Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
8393                 "TDDP region:", "TPT region:", "STAG region:", "RQ region:",
8394                 "RQUDP region:", "PBL region:", "TXPBL region:",
8395                 "DBVFIFO region:", "ULPRX state:", "ULPTX state:",
8396                 "On-chip queues:", "TLS keys:",
8397         };
8398         struct mem_desc avail[4];
8399         struct mem_desc mem[nitems(region) + 3];        /* up to 3 holes */
8400         struct mem_desc *md = mem;
8401
8402         rc = sysctl_wire_old_buffer(req, 0);
8403         if (rc != 0)
8404                 return (rc);
8405
8406         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8407         if (sb == NULL)
8408                 return (ENOMEM);
8409
8410         for (i = 0; i < nitems(mem); i++) {
8411                 mem[i].limit = 0;
8412                 mem[i].idx = i;
8413         }
8414
8415         /* Find and sort the populated memory ranges */
8416         i = 0;
8417         lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
8418         if (lo & F_EDRAM0_ENABLE) {
8419                 hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
8420                 avail[i].base = G_EDRAM0_BASE(hi) << 20;
8421                 avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
8422                 avail[i].idx = 0;
8423                 i++;
8424         }
8425         if (lo & F_EDRAM1_ENABLE) {
8426                 hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
8427                 avail[i].base = G_EDRAM1_BASE(hi) << 20;
8428                 avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
8429                 avail[i].idx = 1;
8430                 i++;
8431         }
8432         if (lo & F_EXT_MEM_ENABLE) {
8433                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
8434                 avail[i].base = G_EXT_MEM_BASE(hi) << 20;
8435                 avail[i].limit = avail[i].base +
8436                     (G_EXT_MEM_SIZE(hi) << 20);
8437                 avail[i].idx = is_t5(sc) ? 3 : 2;       /* Call it MC0 for T5 */
8438                 i++;
8439         }
8440         if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
8441                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
8442                 avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
8443                 avail[i].limit = avail[i].base +
8444                     (G_EXT_MEM1_SIZE(hi) << 20);
8445                 avail[i].idx = 4;
8446                 i++;
8447         }
8448         if (!i)                                    /* no memory available */
8449                 return 0;
8450         qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
8451
8452         (md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
8453         (md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
8454         (md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
8455         (md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
8456         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
8457         (md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
8458         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
8459         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
8460         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
8461
8462         /* the next few have explicit upper bounds */
8463         md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
8464         md->limit = md->base - 1 +
8465                     t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
8466                     G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
8467         md++;
8468
8469         md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
8470         md->limit = md->base - 1 +
8471                     t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
8472                     G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
8473         md++;
8474
8475         if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
8476                 if (chip_id(sc) <= CHELSIO_T5)
8477                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
8478                 else
8479                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
8480                 md->limit = 0;
8481         } else {
8482                 md->base = 0;
8483                 md->idx = nitems(region);  /* hide it */
8484         }
8485         md++;
8486
8487 #define ulp_region(reg) \
8488         md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
8489         (md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
8490
8491         ulp_region(RX_ISCSI);
8492         ulp_region(RX_TDDP);
8493         ulp_region(TX_TPT);
8494         ulp_region(RX_STAG);
8495         ulp_region(RX_RQ);
8496         ulp_region(RX_RQUDP);
8497         ulp_region(RX_PBL);
8498         ulp_region(TX_PBL);
8499 #undef ulp_region
8500
8501         md->base = 0;
8502         md->idx = nitems(region);
8503         if (!is_t4(sc)) {
8504                 uint32_t size = 0;
8505                 uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
8506                 uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
8507
8508                 if (is_t5(sc)) {
8509                         if (sge_ctrl & F_VFIFO_ENABLE)
8510                                 size = G_DBVFIFO_SIZE(fifo_size);
8511                 } else
8512                         size = G_T6_DBVFIFO_SIZE(fifo_size);
8513
8514                 if (size) {
8515                         md->base = G_BASEADDR(t4_read_reg(sc,
8516                             A_SGE_DBVFIFO_BADDR));
8517                         md->limit = md->base + (size << 2) - 1;
8518                 }
8519         }
8520         md++;
8521
8522         md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
8523         md->limit = 0;
8524         md++;
8525         md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
8526         md->limit = 0;
8527         md++;
8528
8529         md->base = sc->vres.ocq.start;
8530         if (sc->vres.ocq.size)
8531                 md->limit = md->base + sc->vres.ocq.size - 1;
8532         else
8533                 md->idx = nitems(region);  /* hide it */
8534         md++;
8535
8536         md->base = sc->vres.key.start;
8537         if (sc->vres.key.size)
8538                 md->limit = md->base + sc->vres.key.size - 1;
8539         else
8540                 md->idx = nitems(region);  /* hide it */
8541         md++;
8542
8543         /* add any address-space holes, there can be up to 3 */
8544         for (n = 0; n < i - 1; n++)
8545                 if (avail[n].limit < avail[n + 1].base)
8546                         (md++)->base = avail[n].limit;
8547         if (avail[n].limit)
8548                 (md++)->base = avail[n].limit;
8549
8550         n = md - mem;
8551         qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
8552
8553         for (lo = 0; lo < i; lo++)
8554                 mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
8555                                 avail[lo].limit - 1);
8556
8557         sbuf_printf(sb, "\n");
8558         for (i = 0; i < n; i++) {
8559                 if (mem[i].idx >= nitems(region))
8560                         continue;                        /* skip holes */
8561                 if (!mem[i].limit)
8562                         mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
8563                 mem_region_show(sb, region[mem[i].idx], mem[i].base,
8564                                 mem[i].limit);
8565         }
8566
8567         sbuf_printf(sb, "\n");
8568         lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
8569         hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
8570         mem_region_show(sb, "uP RAM:", lo, hi);
8571
8572         lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
8573         hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
8574         mem_region_show(sb, "uP Extmem2:", lo, hi);
8575
8576         lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
8577         sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
8578                    G_PMRXMAXPAGE(lo),
8579                    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
8580                    (lo & F_PMRXNUMCHN) ? 2 : 1);
8581
8582         lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
8583         hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
8584         sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
8585                    G_PMTXMAXPAGE(lo),
8586                    hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
8587                    hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
8588         sbuf_printf(sb, "%u p-structs\n",
8589                    t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
8590
8591         for (i = 0; i < 4; i++) {
8592                 if (chip_id(sc) > CHELSIO_T5)
8593                         lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
8594                 else
8595                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
8596                 if (is_t5(sc)) {
8597                         used = G_T5_USED(lo);
8598                         alloc = G_T5_ALLOC(lo);
8599                 } else {
8600                         used = G_USED(lo);
8601                         alloc = G_ALLOC(lo);
8602                 }
8603                 /* For T6 these are MAC buffer groups */
8604                 sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
8605                     i, used, alloc);
8606         }
8607         for (i = 0; i < sc->chip_params->nchan; i++) {
8608                 if (chip_id(sc) > CHELSIO_T5)
8609                         lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
8610                 else
8611                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
8612                 if (is_t5(sc)) {
8613                         used = G_T5_USED(lo);
8614                         alloc = G_T5_ALLOC(lo);
8615                 } else {
8616                         used = G_USED(lo);
8617                         alloc = G_ALLOC(lo);
8618                 }
8619                 /* For T6 these are MAC buffer groups */
8620                 sbuf_printf(sb,
8621                     "\nLoopback %d using %u pages out of %u allocated",
8622                     i, used, alloc);
8623         }
8624
8625         rc = sbuf_finish(sb);
8626         sbuf_delete(sb);
8627
8628         return (rc);
8629 }
8630
8631 static inline void
8632 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
8633 {
8634         *mask = x | y;
8635         y = htobe64(y);
8636         memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
8637 }
8638
8639 static int
8640 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
8641 {
8642         struct adapter *sc = arg1;
8643         struct sbuf *sb;
8644         int rc, i;
8645
8646         MPASS(chip_id(sc) <= CHELSIO_T5);
8647
8648         rc = sysctl_wire_old_buffer(req, 0);
8649         if (rc != 0)
8650                 return (rc);
8651
8652         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8653         if (sb == NULL)
8654                 return (ENOMEM);
8655
8656         sbuf_printf(sb,
8657             "Idx  Ethernet address     Mask     Vld Ports PF"
8658             "  VF              Replication             P0 P1 P2 P3  ML");
8659         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8660                 uint64_t tcamx, tcamy, mask;
8661                 uint32_t cls_lo, cls_hi;
8662                 uint8_t addr[ETHER_ADDR_LEN];
8663
8664                 tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
8665                 tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
8666                 if (tcamx & tcamy)
8667                         continue;
8668                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
8669                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8670                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8671                 sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
8672                            "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
8673                            addr[3], addr[4], addr[5], (uintmax_t)mask,
8674                            (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
8675                            G_PORTMAP(cls_hi), G_PF(cls_lo),
8676                            (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
8677
8678                 if (cls_lo & F_REPLICATE) {
8679                         struct fw_ldst_cmd ldst_cmd;
8680
8681                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8682                         ldst_cmd.op_to_addrspace =
8683                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
8684                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
8685                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
8686                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
8687                         ldst_cmd.u.mps.rplc.fid_idx =
8688                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
8689                                 V_FW_LDST_CMD_IDX(i));
8690
8691                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8692                             "t4mps");
8693                         if (rc)
8694                                 break;
8695                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
8696                             sizeof(ldst_cmd), &ldst_cmd);
8697                         end_synchronized_op(sc, 0);
8698
8699                         if (rc != 0) {
8700                                 sbuf_printf(sb, "%36d", rc);
8701                                 rc = 0;
8702                         } else {
8703                                 sbuf_printf(sb, " %08x %08x %08x %08x",
8704                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
8705                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
8706                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
8707                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
8708                         }
8709                 } else
8710                         sbuf_printf(sb, "%36s", "");
8711
8712                 sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
8713                     G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
8714                     G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
8715         }
8716
8717         if (rc)
8718                 (void) sbuf_finish(sb);
8719         else
8720                 rc = sbuf_finish(sb);
8721         sbuf_delete(sb);
8722
8723         return (rc);
8724 }
8725
8726 static int
8727 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
8728 {
8729         struct adapter *sc = arg1;
8730         struct sbuf *sb;
8731         int rc, i;
8732
8733         MPASS(chip_id(sc) > CHELSIO_T5);
8734
8735         rc = sysctl_wire_old_buffer(req, 0);
8736         if (rc != 0)
8737                 return (rc);
8738
8739         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8740         if (sb == NULL)
8741                 return (ENOMEM);
8742
8743         sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
8744             "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
8745             "                           Replication"
8746             "                                    P0 P1 P2 P3  ML\n");
8747
8748         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8749                 uint8_t dip_hit, vlan_vld, lookup_type, port_num;
8750                 uint16_t ivlan;
8751                 uint64_t tcamx, tcamy, val, mask;
8752                 uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
8753                 uint8_t addr[ETHER_ADDR_LEN];
8754
8755                 ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
8756                 if (i < 256)
8757                         ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
8758                 else
8759                         ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
8760                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
8761                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
8762                 tcamy = G_DMACH(val) << 32;
8763                 tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
8764                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
8765                 lookup_type = G_DATALKPTYPE(data2);
8766                 port_num = G_DATAPORTNUM(data2);
8767                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
8768                         /* Inner header VNI */
8769                         vniy = ((data2 & F_DATAVIDH2) << 23) |
8770                                        (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
8771                         dip_hit = data2 & F_DATADIPHIT;
8772                         vlan_vld = 0;
8773                 } else {
8774                         vniy = 0;
8775                         dip_hit = 0;
8776                         vlan_vld = data2 & F_DATAVIDH2;
8777                         ivlan = G_VIDL(val);
8778                 }
8779
8780                 ctl |= V_CTLXYBITSEL(1);
8781                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
8782                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
8783                 tcamx = G_DMACH(val) << 32;
8784                 tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
8785                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
8786                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
8787                         /* Inner header VNI mask */
8788                         vnix = ((data2 & F_DATAVIDH2) << 23) |
8789                                (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
8790                 } else
8791                         vnix = 0;
8792
8793                 if (tcamx & tcamy)
8794                         continue;
8795                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
8796
8797                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8798                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8799
8800                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
8801                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
8802                             "%012jx %06x %06x    -    -   %3c"
8803                             "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
8804                             addr[1], addr[2], addr[3], addr[4], addr[5],
8805                             (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
8806                             port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
8807                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
8808                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
8809                 } else {
8810                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
8811                             "%012jx    -       -   ", i, addr[0], addr[1],
8812                             addr[2], addr[3], addr[4], addr[5],
8813                             (uintmax_t)mask);
8814
8815                         if (vlan_vld)
8816                                 sbuf_printf(sb, "%4u   Y     ", ivlan);
8817                         else
8818                                 sbuf_printf(sb, "  -    N     ");
8819
8820                         sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
8821                             lookup_type ? 'I' : 'O', port_num,
8822                             cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
8823                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
8824                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
8825                 }
8826
8827
8828                 if (cls_lo & F_T6_REPLICATE) {
8829                         struct fw_ldst_cmd ldst_cmd;
8830
8831                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8832                         ldst_cmd.op_to_addrspace =
8833                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
8834                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
8835                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
8836                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
8837                         ldst_cmd.u.mps.rplc.fid_idx =
8838                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
8839                                 V_FW_LDST_CMD_IDX(i));
8840
8841                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8842                             "t6mps");
8843                         if (rc)
8844                                 break;
8845                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
8846                             sizeof(ldst_cmd), &ldst_cmd);
8847                         end_synchronized_op(sc, 0);
8848
8849                         if (rc != 0) {
8850                                 sbuf_printf(sb, "%72d", rc);
8851                                 rc = 0;
8852                         } else {
8853                                 sbuf_printf(sb, " %08x %08x %08x %08x"
8854                                     " %08x %08x %08x %08x",
8855                                     be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
8856                                     be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
8857                                     be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
8858                                     be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
8859                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
8860                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
8861                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
8862                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
8863                         }
8864                 } else
8865                         sbuf_printf(sb, "%72s", "");
8866
8867                 sbuf_printf(sb, "%4u%3u%3u%3u %#x",
8868                     G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
8869                     G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
8870                     (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
8871         }
8872
8873         if (rc)
8874                 (void) sbuf_finish(sb);
8875         else
8876                 rc = sbuf_finish(sb);
8877         sbuf_delete(sb);
8878
8879         return (rc);
8880 }
8881
8882 static int
8883 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
8884 {
8885         struct adapter *sc = arg1;
8886         struct sbuf *sb;
8887         int rc;
8888         uint16_t mtus[NMTUS];
8889
8890         rc = sysctl_wire_old_buffer(req, 0);
8891         if (rc != 0)
8892                 return (rc);
8893
8894         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8895         if (sb == NULL)
8896                 return (ENOMEM);
8897
8898         t4_read_mtu_tbl(sc, mtus, NULL);
8899
8900         sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
8901             mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
8902             mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
8903             mtus[14], mtus[15]);
8904
8905         rc = sbuf_finish(sb);
8906         sbuf_delete(sb);
8907
8908         return (rc);
8909 }
8910
8911 static int
8912 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
8913 {
8914         struct adapter *sc = arg1;
8915         struct sbuf *sb;
8916         int rc, i;
8917         uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
8918         uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
8919         static const char *tx_stats[MAX_PM_NSTATS] = {
8920                 "Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
8921                 "Tx FIFO wait", NULL, "Tx latency"
8922         };
8923         static const char *rx_stats[MAX_PM_NSTATS] = {
8924                 "Read:", "Write bypass:", "Write mem:", "Flush:",
8925                 "Rx FIFO wait", NULL, "Rx latency"
8926         };
8927
8928         rc = sysctl_wire_old_buffer(req, 0);
8929         if (rc != 0)
8930                 return (rc);
8931
8932         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8933         if (sb == NULL)
8934                 return (ENOMEM);
8935
8936         t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
8937         t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
8938
8939         sbuf_printf(sb, "                Tx pcmds             Tx bytes");
8940         for (i = 0; i < 4; i++) {
8941                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8942                     tx_cyc[i]);
8943         }
8944
8945         sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
8946         for (i = 0; i < 4; i++) {
8947                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8948                     rx_cyc[i]);
8949         }
8950
8951         if (chip_id(sc) > CHELSIO_T5) {
8952                 sbuf_printf(sb,
8953                     "\n              Total wait      Total occupancy");
8954                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8955                     tx_cyc[i]);
8956                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8957                     rx_cyc[i]);
8958
8959                 i += 2;
8960                 MPASS(i < nitems(tx_stats));
8961
8962                 sbuf_printf(sb,
8963                     "\n                   Reads           Total wait");
8964                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8965                     tx_cyc[i]);
8966                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8967                     rx_cyc[i]);
8968         }
8969
8970         rc = sbuf_finish(sb);
8971         sbuf_delete(sb);
8972
8973         return (rc);
8974 }
8975
8976 static int
8977 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
8978 {
8979         struct adapter *sc = arg1;
8980         struct sbuf *sb;
8981         int rc;
8982         struct tp_rdma_stats stats;
8983
8984         rc = sysctl_wire_old_buffer(req, 0);
8985         if (rc != 0)
8986                 return (rc);
8987
8988         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8989         if (sb == NULL)
8990                 return (ENOMEM);
8991
8992         mtx_lock(&sc->reg_lock);
8993         t4_tp_get_rdma_stats(sc, &stats, 0);
8994         mtx_unlock(&sc->reg_lock);
8995
8996         sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
8997         sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
8998
8999         rc = sbuf_finish(sb);
9000         sbuf_delete(sb);
9001
9002         return (rc);
9003 }
9004
9005 static int
9006 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
9007 {
9008         struct adapter *sc = arg1;
9009         struct sbuf *sb;
9010         int rc;
9011         struct tp_tcp_stats v4, v6;
9012
9013         rc = sysctl_wire_old_buffer(req, 0);
9014         if (rc != 0)
9015                 return (rc);
9016
9017         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9018         if (sb == NULL)
9019                 return (ENOMEM);
9020
9021         mtx_lock(&sc->reg_lock);
9022         t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
9023         mtx_unlock(&sc->reg_lock);
9024
9025         sbuf_printf(sb,
9026             "                                IP                 IPv6\n");
9027         sbuf_printf(sb, "OutRsts:      %20u %20u\n",
9028             v4.tcp_out_rsts, v6.tcp_out_rsts);
9029         sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
9030             v4.tcp_in_segs, v6.tcp_in_segs);
9031         sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
9032             v4.tcp_out_segs, v6.tcp_out_segs);
9033         sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
9034             v4.tcp_retrans_segs, v6.tcp_retrans_segs);
9035
9036         rc = sbuf_finish(sb);
9037         sbuf_delete(sb);
9038
9039         return (rc);
9040 }
9041
9042 static int
9043 sysctl_tids(SYSCTL_HANDLER_ARGS)
9044 {
9045         struct adapter *sc = arg1;
9046         struct sbuf *sb;
9047         int rc;
9048         struct tid_info *t = &sc->tids;
9049
9050         rc = sysctl_wire_old_buffer(req, 0);
9051         if (rc != 0)
9052                 return (rc);
9053
9054         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9055         if (sb == NULL)
9056                 return (ENOMEM);
9057
9058         if (t->natids) {
9059                 sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
9060                     t->atids_in_use);
9061         }
9062
9063         if (t->nhpftids) {
9064                 sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
9065                     t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
9066         }
9067
9068         if (t->ntids) {
9069                 sbuf_printf(sb, "TID range: ");
9070                 if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9071                         uint32_t b, hb;
9072
9073                         if (chip_id(sc) <= CHELSIO_T5) {
9074                                 b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
9075                                 hb = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
9076                         } else {
9077                                 b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
9078                                 hb = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
9079                         }
9080
9081                         if (b)
9082                                 sbuf_printf(sb, "%u-%u, ", t->tid_base, b - 1);
9083                         sbuf_printf(sb, "%u-%u", hb, t->ntids - 1);
9084                 } else
9085                         sbuf_printf(sb, "%u-%u", t->tid_base, t->ntids - 1);
9086                 sbuf_printf(sb, ", in use: %u\n",
9087                     atomic_load_acq_int(&t->tids_in_use));
9088         }
9089
9090         if (t->nstids) {
9091                 sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
9092                     t->stid_base + t->nstids - 1, t->stids_in_use);
9093         }
9094
9095         if (t->nftids) {
9096                 sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
9097                     t->ftid_end, t->ftids_in_use);
9098         }
9099
9100         if (t->netids) {
9101                 sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
9102                     t->etid_base + t->netids - 1, t->etids_in_use);
9103         }
9104
9105         sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
9106             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
9107             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
9108
9109         rc = sbuf_finish(sb);
9110         sbuf_delete(sb);
9111
9112         return (rc);
9113 }
9114
9115 static int
9116 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
9117 {
9118         struct adapter *sc = arg1;
9119         struct sbuf *sb;
9120         int rc;
9121         struct tp_err_stats stats;
9122
9123         rc = sysctl_wire_old_buffer(req, 0);
9124         if (rc != 0)
9125                 return (rc);
9126
9127         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9128         if (sb == NULL)
9129                 return (ENOMEM);
9130
9131         mtx_lock(&sc->reg_lock);
9132         t4_tp_get_err_stats(sc, &stats, 0);
9133         mtx_unlock(&sc->reg_lock);
9134
9135         if (sc->chip_params->nchan > 2) {
9136                 sbuf_printf(sb, "                 channel 0  channel 1"
9137                     "  channel 2  channel 3\n");
9138                 sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
9139                     stats.mac_in_errs[0], stats.mac_in_errs[1],
9140                     stats.mac_in_errs[2], stats.mac_in_errs[3]);
9141                 sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
9142                     stats.hdr_in_errs[0], stats.hdr_in_errs[1],
9143                     stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
9144                 sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
9145                     stats.tcp_in_errs[0], stats.tcp_in_errs[1],
9146                     stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
9147                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
9148                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
9149                     stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
9150                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
9151                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
9152                     stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
9153                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
9154                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
9155                     stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
9156                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
9157                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
9158                     stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
9159                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
9160                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
9161                     stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
9162         } else {
9163                 sbuf_printf(sb, "                 channel 0  channel 1\n");
9164                 sbuf_printf(sb, "macInErrs:      %10u %10u\n",
9165                     stats.mac_in_errs[0], stats.mac_in_errs[1]);
9166                 sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
9167                     stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
9168                 sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
9169                     stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
9170                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
9171                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
9172                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
9173                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
9174                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
9175                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
9176                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
9177                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
9178                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
9179                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
9180         }
9181
9182         sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
9183             stats.ofld_no_neigh, stats.ofld_cong_defer);
9184
9185         rc = sbuf_finish(sb);
9186         sbuf_delete(sb);
9187
9188         return (rc);
9189 }
9190
9191 static int
9192 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
9193 {
9194         struct adapter *sc = arg1;
9195         struct tp_params *tpp = &sc->params.tp;
9196         u_int mask;
9197         int rc;
9198
9199         mask = tpp->la_mask >> 16;
9200         rc = sysctl_handle_int(oidp, &mask, 0, req);
9201         if (rc != 0 || req->newptr == NULL)
9202                 return (rc);
9203         if (mask > 0xffff)
9204                 return (EINVAL);
9205         tpp->la_mask = mask << 16;
9206         t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
9207
9208         return (0);
9209 }
9210
9211 struct field_desc {
9212         const char *name;
9213         u_int start;
9214         u_int width;
9215 };
9216
9217 static void
9218 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
9219 {
9220         char buf[32];
9221         int line_size = 0;
9222
9223         while (f->name) {
9224                 uint64_t mask = (1ULL << f->width) - 1;
9225                 int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
9226                     ((uintmax_t)v >> f->start) & mask);
9227
9228                 if (line_size + len >= 79) {
9229                         line_size = 8;
9230                         sbuf_printf(sb, "\n        ");
9231                 }
9232                 sbuf_printf(sb, "%s ", buf);
9233                 line_size += len + 1;
9234                 f++;
9235         }
9236         sbuf_printf(sb, "\n");
9237 }
9238
9239 static const struct field_desc tp_la0[] = {
9240         { "RcfOpCodeOut", 60, 4 },
9241         { "State", 56, 4 },
9242         { "WcfState", 52, 4 },
9243         { "RcfOpcSrcOut", 50, 2 },
9244         { "CRxError", 49, 1 },
9245         { "ERxError", 48, 1 },
9246         { "SanityFailed", 47, 1 },
9247         { "SpuriousMsg", 46, 1 },
9248         { "FlushInputMsg", 45, 1 },
9249         { "FlushInputCpl", 44, 1 },
9250         { "RssUpBit", 43, 1 },
9251         { "RssFilterHit", 42, 1 },
9252         { "Tid", 32, 10 },
9253         { "InitTcb", 31, 1 },
9254         { "LineNumber", 24, 7 },
9255         { "Emsg", 23, 1 },
9256         { "EdataOut", 22, 1 },
9257         { "Cmsg", 21, 1 },
9258         { "CdataOut", 20, 1 },
9259         { "EreadPdu", 19, 1 },
9260         { "CreadPdu", 18, 1 },
9261         { "TunnelPkt", 17, 1 },
9262         { "RcfPeerFin", 16, 1 },
9263         { "RcfReasonOut", 12, 4 },
9264         { "TxCchannel", 10, 2 },
9265         { "RcfTxChannel", 8, 2 },
9266         { "RxEchannel", 6, 2 },
9267         { "RcfRxChannel", 5, 1 },
9268         { "RcfDataOutSrdy", 4, 1 },
9269         { "RxDvld", 3, 1 },
9270         { "RxOoDvld", 2, 1 },
9271         { "RxCongestion", 1, 1 },
9272         { "TxCongestion", 0, 1 },
9273         { NULL }
9274 };
9275
9276 static const struct field_desc tp_la1[] = {
9277         { "CplCmdIn", 56, 8 },
9278         { "CplCmdOut", 48, 8 },
9279         { "ESynOut", 47, 1 },
9280         { "EAckOut", 46, 1 },
9281         { "EFinOut", 45, 1 },
9282         { "ERstOut", 44, 1 },
9283         { "SynIn", 43, 1 },
9284         { "AckIn", 42, 1 },
9285         { "FinIn", 41, 1 },
9286         { "RstIn", 40, 1 },
9287         { "DataIn", 39, 1 },
9288         { "DataInVld", 38, 1 },
9289         { "PadIn", 37, 1 },
9290         { "RxBufEmpty", 36, 1 },
9291         { "RxDdp", 35, 1 },
9292         { "RxFbCongestion", 34, 1 },
9293         { "TxFbCongestion", 33, 1 },
9294         { "TxPktSumSrdy", 32, 1 },
9295         { "RcfUlpType", 28, 4 },
9296         { "Eread", 27, 1 },
9297         { "Ebypass", 26, 1 },
9298         { "Esave", 25, 1 },
9299         { "Static0", 24, 1 },
9300         { "Cread", 23, 1 },
9301         { "Cbypass", 22, 1 },
9302         { "Csave", 21, 1 },
9303         { "CPktOut", 20, 1 },
9304         { "RxPagePoolFull", 18, 2 },
9305         { "RxLpbkPkt", 17, 1 },
9306         { "TxLpbkPkt", 16, 1 },
9307         { "RxVfValid", 15, 1 },
9308         { "SynLearned", 14, 1 },
9309         { "SetDelEntry", 13, 1 },
9310         { "SetInvEntry", 12, 1 },
9311         { "CpcmdDvld", 11, 1 },
9312         { "CpcmdSave", 10, 1 },
9313         { "RxPstructsFull", 8, 2 },
9314         { "EpcmdDvld", 7, 1 },
9315         { "EpcmdFlush", 6, 1 },
9316         { "EpcmdTrimPrefix", 5, 1 },
9317         { "EpcmdTrimPostfix", 4, 1 },
9318         { "ERssIp4Pkt", 3, 1 },
9319         { "ERssIp6Pkt", 2, 1 },
9320         { "ERssTcpUdpPkt", 1, 1 },
9321         { "ERssFceFipPkt", 0, 1 },
9322         { NULL }
9323 };
9324
9325 static const struct field_desc tp_la2[] = {
9326         { "CplCmdIn", 56, 8 },
9327         { "MpsVfVld", 55, 1 },
9328         { "MpsPf", 52, 3 },
9329         { "MpsVf", 44, 8 },
9330         { "SynIn", 43, 1 },
9331         { "AckIn", 42, 1 },
9332         { "FinIn", 41, 1 },
9333         { "RstIn", 40, 1 },
9334         { "DataIn", 39, 1 },
9335         { "DataInVld", 38, 1 },
9336         { "PadIn", 37, 1 },
9337         { "RxBufEmpty", 36, 1 },
9338         { "RxDdp", 35, 1 },
9339         { "RxFbCongestion", 34, 1 },
9340         { "TxFbCongestion", 33, 1 },
9341         { "TxPktSumSrdy", 32, 1 },
9342         { "RcfUlpType", 28, 4 },
9343         { "Eread", 27, 1 },
9344         { "Ebypass", 26, 1 },
9345         { "Esave", 25, 1 },
9346         { "Static0", 24, 1 },
9347         { "Cread", 23, 1 },
9348         { "Cbypass", 22, 1 },
9349         { "Csave", 21, 1 },
9350         { "CPktOut", 20, 1 },
9351         { "RxPagePoolFull", 18, 2 },
9352         { "RxLpbkPkt", 17, 1 },
9353         { "TxLpbkPkt", 16, 1 },
9354         { "RxVfValid", 15, 1 },
9355         { "SynLearned", 14, 1 },
9356         { "SetDelEntry", 13, 1 },
9357         { "SetInvEntry", 12, 1 },
9358         { "CpcmdDvld", 11, 1 },
9359         { "CpcmdSave", 10, 1 },
9360         { "RxPstructsFull", 8, 2 },
9361         { "EpcmdDvld", 7, 1 },
9362         { "EpcmdFlush", 6, 1 },
9363         { "EpcmdTrimPrefix", 5, 1 },
9364         { "EpcmdTrimPostfix", 4, 1 },
9365         { "ERssIp4Pkt", 3, 1 },
9366         { "ERssIp6Pkt", 2, 1 },
9367         { "ERssTcpUdpPkt", 1, 1 },
9368         { "ERssFceFipPkt", 0, 1 },
9369         { NULL }
9370 };
9371
9372 static void
9373 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
9374 {
9375
9376         field_desc_show(sb, *p, tp_la0);
9377 }
9378
9379 static void
9380 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
9381 {
9382
9383         if (idx)
9384                 sbuf_printf(sb, "\n");
9385         field_desc_show(sb, p[0], tp_la0);
9386         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
9387                 field_desc_show(sb, p[1], tp_la0);
9388 }
9389
9390 static void
9391 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
9392 {
9393
9394         if (idx)
9395                 sbuf_printf(sb, "\n");
9396         field_desc_show(sb, p[0], tp_la0);
9397         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
9398                 field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
9399 }
9400
9401 static int
9402 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
9403 {
9404         struct adapter *sc = arg1;
9405         struct sbuf *sb;
9406         uint64_t *buf, *p;
9407         int rc;
9408         u_int i, inc;
9409         void (*show_func)(struct sbuf *, uint64_t *, int);
9410
9411         rc = sysctl_wire_old_buffer(req, 0);
9412         if (rc != 0)
9413                 return (rc);
9414
9415         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9416         if (sb == NULL)
9417                 return (ENOMEM);
9418
9419         buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
9420
9421         t4_tp_read_la(sc, buf, NULL);
9422         p = buf;
9423
9424         switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
9425         case 2:
9426                 inc = 2;
9427                 show_func = tp_la_show2;
9428                 break;
9429         case 3:
9430                 inc = 2;
9431                 show_func = tp_la_show3;
9432                 break;
9433         default:
9434                 inc = 1;
9435                 show_func = tp_la_show;
9436         }
9437
9438         for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
9439                 (*show_func)(sb, p, i);
9440
9441         rc = sbuf_finish(sb);
9442         sbuf_delete(sb);
9443         free(buf, M_CXGBE);
9444         return (rc);
9445 }
9446
9447 static int
9448 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
9449 {
9450         struct adapter *sc = arg1;
9451         struct sbuf *sb;
9452         int rc;
9453         u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
9454
9455         rc = sysctl_wire_old_buffer(req, 0);
9456         if (rc != 0)
9457                 return (rc);
9458
9459         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9460         if (sb == NULL)
9461                 return (ENOMEM);
9462
9463         t4_get_chan_txrate(sc, nrate, orate);
9464
9465         if (sc->chip_params->nchan > 2) {
9466                 sbuf_printf(sb, "              channel 0   channel 1"
9467                     "   channel 2   channel 3\n");
9468                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
9469                     nrate[0], nrate[1], nrate[2], nrate[3]);
9470                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
9471                     orate[0], orate[1], orate[2], orate[3]);
9472         } else {
9473                 sbuf_printf(sb, "              channel 0   channel 1\n");
9474                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
9475                     nrate[0], nrate[1]);
9476                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
9477                     orate[0], orate[1]);
9478         }
9479
9480         rc = sbuf_finish(sb);
9481         sbuf_delete(sb);
9482
9483         return (rc);
9484 }
9485
9486 static int
9487 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
9488 {
9489         struct adapter *sc = arg1;
9490         struct sbuf *sb;
9491         uint32_t *buf, *p;
9492         int rc, i;
9493
9494         rc = sysctl_wire_old_buffer(req, 0);
9495         if (rc != 0)
9496                 return (rc);
9497
9498         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9499         if (sb == NULL)
9500                 return (ENOMEM);
9501
9502         buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
9503             M_ZERO | M_WAITOK);
9504
9505         t4_ulprx_read_la(sc, buf);
9506         p = buf;
9507
9508         sbuf_printf(sb, "      Pcmd        Type   Message"
9509             "                Data");
9510         for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
9511                 sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
9512                     p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
9513         }
9514
9515         rc = sbuf_finish(sb);
9516         sbuf_delete(sb);
9517         free(buf, M_CXGBE);
9518         return (rc);
9519 }
9520
9521 static int
9522 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
9523 {
9524         struct adapter *sc = arg1;
9525         struct sbuf *sb;
9526         int rc, v;
9527
9528         MPASS(chip_id(sc) >= CHELSIO_T5);
9529
9530         rc = sysctl_wire_old_buffer(req, 0);
9531         if (rc != 0)
9532                 return (rc);
9533
9534         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9535         if (sb == NULL)
9536                 return (ENOMEM);
9537
9538         v = t4_read_reg(sc, A_SGE_STAT_CFG);
9539         if (G_STATSOURCE_T5(v) == 7) {
9540                 int mode;
9541
9542                 mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
9543                 if (mode == 0) {
9544                         sbuf_printf(sb, "total %d, incomplete %d",
9545                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
9546                             t4_read_reg(sc, A_SGE_STAT_MATCH));
9547                 } else if (mode == 1) {
9548                         sbuf_printf(sb, "total %d, data overflow %d",
9549                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
9550                             t4_read_reg(sc, A_SGE_STAT_MATCH));
9551                 } else {
9552                         sbuf_printf(sb, "unknown mode %d", mode);
9553                 }
9554         }
9555         rc = sbuf_finish(sb);
9556         sbuf_delete(sb);
9557
9558         return (rc);
9559 }
9560
9561 static int
9562 sysctl_cpus(SYSCTL_HANDLER_ARGS)
9563 {
9564         struct adapter *sc = arg1;
9565         enum cpu_sets op = arg2;
9566         cpuset_t cpuset;
9567         struct sbuf *sb;
9568         int i, rc;
9569
9570         MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
9571
9572         CPU_ZERO(&cpuset);
9573         rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
9574         if (rc != 0)
9575                 return (rc);
9576
9577         rc = sysctl_wire_old_buffer(req, 0);
9578         if (rc != 0)
9579                 return (rc);
9580
9581         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9582         if (sb == NULL)
9583                 return (ENOMEM);
9584
9585         CPU_FOREACH(i)
9586                 sbuf_printf(sb, "%d ", i);
9587         rc = sbuf_finish(sb);
9588         sbuf_delete(sb);
9589
9590         return (rc);
9591 }
9592
9593 #ifdef TCP_OFFLOAD
9594 static int
9595 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
9596 {
9597         struct adapter *sc = arg1;
9598         int *old_ports, *new_ports;
9599         int i, new_count, rc;
9600
9601         if (req->newptr == NULL && req->oldptr == NULL)
9602                 return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
9603                     sizeof(sc->tt.tls_rx_ports[0])));
9604
9605         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
9606         if (rc)
9607                 return (rc);
9608
9609         if (sc->tt.num_tls_rx_ports == 0) {
9610                 i = -1;
9611                 rc = SYSCTL_OUT(req, &i, sizeof(i));
9612         } else
9613                 rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
9614                     sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
9615         if (rc == 0 && req->newptr != NULL) {
9616                 new_count = req->newlen / sizeof(new_ports[0]);
9617                 new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
9618                     M_WAITOK);
9619                 rc = SYSCTL_IN(req, new_ports, new_count *
9620                     sizeof(new_ports[0]));
9621                 if (rc)
9622                         goto err;
9623
9624                 /* Allow setting to a single '-1' to clear the list. */
9625                 if (new_count == 1 && new_ports[0] == -1) {
9626                         ADAPTER_LOCK(sc);
9627                         old_ports = sc->tt.tls_rx_ports;
9628                         sc->tt.tls_rx_ports = NULL;
9629                         sc->tt.num_tls_rx_ports = 0;
9630                         ADAPTER_UNLOCK(sc);
9631                         free(old_ports, M_CXGBE);
9632                 } else {
9633                         for (i = 0; i < new_count; i++) {
9634                                 if (new_ports[i] < 1 ||
9635                                     new_ports[i] > IPPORT_MAX) {
9636                                         rc = EINVAL;
9637                                         goto err;
9638                                 }
9639                         }
9640
9641                         ADAPTER_LOCK(sc);
9642                         old_ports = sc->tt.tls_rx_ports;
9643                         sc->tt.tls_rx_ports = new_ports;
9644                         sc->tt.num_tls_rx_ports = new_count;
9645                         ADAPTER_UNLOCK(sc);
9646                         free(old_ports, M_CXGBE);
9647                         new_ports = NULL;
9648                 }
9649         err:
9650                 free(new_ports, M_CXGBE);
9651         }
9652         end_synchronized_op(sc, 0);
9653         return (rc);
9654 }
9655
9656 static void
9657 unit_conv(char *buf, size_t len, u_int val, u_int factor)
9658 {
9659         u_int rem = val % factor;
9660
9661         if (rem == 0)
9662                 snprintf(buf, len, "%u", val / factor);
9663         else {
9664                 while (rem % 10 == 0)
9665                         rem /= 10;
9666                 snprintf(buf, len, "%u.%u", val / factor, rem);
9667         }
9668 }
9669
9670 static int
9671 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
9672 {
9673         struct adapter *sc = arg1;
9674         char buf[16];
9675         u_int res, re;
9676         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9677
9678         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
9679         switch (arg2) {
9680         case 0:
9681                 /* timer_tick */
9682                 re = G_TIMERRESOLUTION(res);
9683                 break;
9684         case 1:
9685                 /* TCP timestamp tick */
9686                 re = G_TIMESTAMPRESOLUTION(res);
9687                 break;
9688         case 2:
9689                 /* DACK tick */
9690                 re = G_DELAYEDACKRESOLUTION(res);
9691                 break;
9692         default:
9693                 return (EDOOFUS);
9694         }
9695
9696         unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
9697
9698         return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
9699 }
9700
9701 static int
9702 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
9703 {
9704         struct adapter *sc = arg1;
9705         u_int res, dack_re, v;
9706         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9707
9708         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
9709         dack_re = G_DELAYEDACKRESOLUTION(res);
9710         v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
9711
9712         return (sysctl_handle_int(oidp, &v, 0, req));
9713 }
9714
9715 static int
9716 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
9717 {
9718         struct adapter *sc = arg1;
9719         int reg = arg2;
9720         u_int tre;
9721         u_long tp_tick_us, v;
9722         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9723
9724         MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
9725             reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
9726             reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
9727             reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
9728
9729         tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
9730         tp_tick_us = (cclk_ps << tre) / 1000000;
9731
9732         if (reg == A_TP_INIT_SRTT)
9733                 v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
9734         else
9735                 v = tp_tick_us * t4_read_reg(sc, reg);
9736
9737         return (sysctl_handle_long(oidp, &v, 0, req));
9738 }
9739
9740 /*
9741  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
9742  * passed to this function.
9743  */
9744 static int
9745 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
9746 {
9747         struct adapter *sc = arg1;
9748         int idx = arg2;
9749         u_int v;
9750
9751         MPASS(idx >= 0 && idx <= 24);
9752
9753         v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
9754
9755         return (sysctl_handle_int(oidp, &v, 0, req));
9756 }
9757
9758 static int
9759 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
9760 {
9761         struct adapter *sc = arg1;
9762         int idx = arg2;
9763         u_int shift, v, r;
9764
9765         MPASS(idx >= 0 && idx < 16);
9766
9767         r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
9768         shift = (idx & 3) << 3;
9769         v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
9770
9771         return (sysctl_handle_int(oidp, &v, 0, req));
9772 }
9773
9774 static int
9775 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
9776 {
9777         struct vi_info *vi = arg1;
9778         struct adapter *sc = vi->pi->adapter;
9779         int idx, rc, i;
9780         struct sge_ofld_rxq *ofld_rxq;
9781         uint8_t v;
9782
9783         idx = vi->ofld_tmr_idx;
9784
9785         rc = sysctl_handle_int(oidp, &idx, 0, req);
9786         if (rc != 0 || req->newptr == NULL)
9787                 return (rc);
9788
9789         if (idx < 0 || idx >= SGE_NTIMERS)
9790                 return (EINVAL);
9791
9792         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9793             "t4otmr");
9794         if (rc)
9795                 return (rc);
9796
9797         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
9798         for_each_ofld_rxq(vi, i, ofld_rxq) {
9799 #ifdef atomic_store_rel_8
9800                 atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
9801 #else
9802                 ofld_rxq->iq.intr_params = v;
9803 #endif
9804         }
9805         vi->ofld_tmr_idx = idx;
9806
9807         end_synchronized_op(sc, LOCK_HELD);
9808         return (0);
9809 }
9810
9811 static int
9812 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
9813 {
9814         struct vi_info *vi = arg1;
9815         struct adapter *sc = vi->pi->adapter;
9816         int idx, rc;
9817
9818         idx = vi->ofld_pktc_idx;
9819
9820         rc = sysctl_handle_int(oidp, &idx, 0, req);
9821         if (rc != 0 || req->newptr == NULL)
9822                 return (rc);
9823
9824         if (idx < -1 || idx >= SGE_NCOUNTERS)
9825                 return (EINVAL);
9826
9827         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9828             "t4opktc");
9829         if (rc)
9830                 return (rc);
9831
9832         if (vi->flags & VI_INIT_DONE)
9833                 rc = EBUSY; /* cannot be changed once the queues are created */
9834         else
9835                 vi->ofld_pktc_idx = idx;
9836
9837         end_synchronized_op(sc, LOCK_HELD);
9838         return (rc);
9839 }
9840 #endif
9841
9842 static int
9843 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
9844 {
9845         int rc;
9846
9847         if (cntxt->cid > M_CTXTQID)
9848                 return (EINVAL);
9849
9850         if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
9851             cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
9852                 return (EINVAL);
9853
9854         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
9855         if (rc)
9856                 return (rc);
9857
9858         if (sc->flags & FW_OK) {
9859                 rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
9860                     &cntxt->data[0]);
9861                 if (rc == 0)
9862                         goto done;
9863         }
9864
9865         /*
9866          * Read via firmware failed or wasn't even attempted.  Read directly via
9867          * the backdoor.
9868          */
9869         rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
9870 done:
9871         end_synchronized_op(sc, 0);
9872         return (rc);
9873 }
9874
9875 static int
9876 load_fw(struct adapter *sc, struct t4_data *fw)
9877 {
9878         int rc;
9879         uint8_t *fw_data;
9880
9881         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
9882         if (rc)
9883                 return (rc);
9884
9885         /*
9886          * The firmware, with the sole exception of the memory parity error
9887          * handler, runs from memory and not flash.  It is almost always safe to
9888          * install a new firmware on a running system.  Just set bit 1 in
9889          * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
9890          */
9891         if (sc->flags & FULL_INIT_DONE &&
9892             (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
9893                 rc = EBUSY;
9894                 goto done;
9895         }
9896
9897         fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
9898         if (fw_data == NULL) {
9899                 rc = ENOMEM;
9900                 goto done;
9901         }
9902
9903         rc = copyin(fw->data, fw_data, fw->len);
9904         if (rc == 0)
9905                 rc = -t4_load_fw(sc, fw_data, fw->len);
9906
9907         free(fw_data, M_CXGBE);
9908 done:
9909         end_synchronized_op(sc, 0);
9910         return (rc);
9911 }
9912
9913 static int
9914 load_cfg(struct adapter *sc, struct t4_data *cfg)
9915 {
9916         int rc;
9917         uint8_t *cfg_data = NULL;
9918
9919         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9920         if (rc)
9921                 return (rc);
9922
9923         if (cfg->len == 0) {
9924                 /* clear */
9925                 rc = -t4_load_cfg(sc, NULL, 0);
9926                 goto done;
9927         }
9928
9929         cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
9930         if (cfg_data == NULL) {
9931                 rc = ENOMEM;
9932                 goto done;
9933         }
9934
9935         rc = copyin(cfg->data, cfg_data, cfg->len);
9936         if (rc == 0)
9937                 rc = -t4_load_cfg(sc, cfg_data, cfg->len);
9938
9939         free(cfg_data, M_CXGBE);
9940 done:
9941         end_synchronized_op(sc, 0);
9942         return (rc);
9943 }
9944
9945 static int
9946 load_boot(struct adapter *sc, struct t4_bootrom *br)
9947 {
9948         int rc;
9949         uint8_t *br_data = NULL;
9950         u_int offset;
9951
9952         if (br->len > 1024 * 1024)
9953                 return (EFBIG);
9954
9955         if (br->pf_offset == 0) {
9956                 /* pfidx */
9957                 if (br->pfidx_addr > 7)
9958                         return (EINVAL);
9959                 offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
9960                     A_PCIE_PF_EXPROM_OFST)));
9961         } else if (br->pf_offset == 1) {
9962                 /* offset */
9963                 offset = G_OFFSET(br->pfidx_addr);
9964         } else {
9965                 return (EINVAL);
9966         }
9967
9968         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
9969         if (rc)
9970                 return (rc);
9971
9972         if (br->len == 0) {
9973                 /* clear */
9974                 rc = -t4_load_boot(sc, NULL, offset, 0);
9975                 goto done;
9976         }
9977
9978         br_data = malloc(br->len, M_CXGBE, M_WAITOK);
9979         if (br_data == NULL) {
9980                 rc = ENOMEM;
9981                 goto done;
9982         }
9983
9984         rc = copyin(br->data, br_data, br->len);
9985         if (rc == 0)
9986                 rc = -t4_load_boot(sc, br_data, offset, br->len);
9987
9988         free(br_data, M_CXGBE);
9989 done:
9990         end_synchronized_op(sc, 0);
9991         return (rc);
9992 }
9993
9994 static int
9995 load_bootcfg(struct adapter *sc, struct t4_data *bc)
9996 {
9997         int rc;
9998         uint8_t *bc_data = NULL;
9999
10000         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
10001         if (rc)
10002                 return (rc);
10003
10004         if (bc->len == 0) {
10005                 /* clear */
10006                 rc = -t4_load_bootcfg(sc, NULL, 0);
10007                 goto done;
10008         }
10009
10010         bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
10011         if (bc_data == NULL) {
10012                 rc = ENOMEM;
10013                 goto done;
10014         }
10015
10016         rc = copyin(bc->data, bc_data, bc->len);
10017         if (rc == 0)
10018                 rc = -t4_load_bootcfg(sc, bc_data, bc->len);
10019
10020         free(bc_data, M_CXGBE);
10021 done:
10022         end_synchronized_op(sc, 0);
10023         return (rc);
10024 }
10025
10026 static int
10027 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
10028 {
10029         int rc;
10030         struct cudbg_init *cudbg;
10031         void *handle, *buf;
10032
10033         /* buf is large, don't block if no memory is available */
10034         buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
10035         if (buf == NULL)
10036                 return (ENOMEM);
10037
10038         handle = cudbg_alloc_handle();
10039         if (handle == NULL) {
10040                 rc = ENOMEM;
10041                 goto done;
10042         }
10043
10044         cudbg = cudbg_get_init(handle);
10045         cudbg->adap = sc;
10046         cudbg->print = (cudbg_print_cb)printf;
10047
10048 #ifndef notyet
10049         device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
10050             __func__, dump->wr_flash, dump->len, dump->data);
10051 #endif
10052
10053         if (dump->wr_flash)
10054                 cudbg->use_flash = 1;
10055         MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
10056         memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
10057
10058         rc = cudbg_collect(handle, buf, &dump->len);
10059         if (rc != 0)
10060                 goto done;
10061
10062         rc = copyout(buf, dump->data, dump->len);
10063 done:
10064         cudbg_free_handle(handle);
10065         free(buf, M_CXGBE);
10066         return (rc);
10067 }
10068
10069 static void
10070 free_offload_policy(struct t4_offload_policy *op)
10071 {
10072         struct offload_rule *r;
10073         int i;
10074
10075         if (op == NULL)
10076                 return;
10077
10078         r = &op->rule[0];
10079         for (i = 0; i < op->nrules; i++, r++) {
10080                 free(r->bpf_prog.bf_insns, M_CXGBE);
10081         }
10082         free(op->rule, M_CXGBE);
10083         free(op, M_CXGBE);
10084 }
10085
10086 static int
10087 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
10088 {
10089         int i, rc, len;
10090         struct t4_offload_policy *op, *old;
10091         struct bpf_program *bf;
10092         const struct offload_settings *s;
10093         struct offload_rule *r;
10094         void *u;
10095
10096         if (!is_offload(sc))
10097                 return (ENODEV);
10098
10099         if (uop->nrules == 0) {
10100                 /* Delete installed policies. */
10101                 op = NULL;
10102                 goto set_policy;
10103         } else if (uop->nrules > 256) { /* arbitrary */
10104                 return (E2BIG);
10105         }
10106
10107         /* Copy userspace offload policy to kernel */
10108         op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
10109         op->nrules = uop->nrules;
10110         len = op->nrules * sizeof(struct offload_rule);
10111         op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
10112         rc = copyin(uop->rule, op->rule, len);
10113         if (rc) {
10114                 free(op->rule, M_CXGBE);
10115                 free(op, M_CXGBE);
10116                 return (rc);
10117         }
10118
10119         r = &op->rule[0];
10120         for (i = 0; i < op->nrules; i++, r++) {
10121
10122                 /* Validate open_type */
10123                 if (r->open_type != OPEN_TYPE_LISTEN &&
10124                     r->open_type != OPEN_TYPE_ACTIVE &&
10125                     r->open_type != OPEN_TYPE_PASSIVE &&
10126                     r->open_type != OPEN_TYPE_DONTCARE) {
10127 error:
10128                         /*
10129                          * Rules 0 to i have malloc'd filters that need to be
10130                          * freed.  Rules i+1 to nrules have userspace pointers
10131                          * and should be left alone.
10132                          */
10133                         op->nrules = i;
10134                         free_offload_policy(op);
10135                         return (rc);
10136                 }
10137
10138                 /* Validate settings */
10139                 s = &r->settings;
10140                 if ((s->offload != 0 && s->offload != 1) ||
10141                     s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
10142                     s->sched_class < -1 ||
10143                     s->sched_class >= sc->chip_params->nsched_cls) {
10144                         rc = EINVAL;
10145                         goto error;
10146                 }
10147
10148                 bf = &r->bpf_prog;
10149                 u = bf->bf_insns;       /* userspace ptr */
10150                 bf->bf_insns = NULL;
10151                 if (bf->bf_len == 0) {
10152                         /* legal, matches everything */
10153                         continue;
10154                 }
10155                 len = bf->bf_len * sizeof(*bf->bf_insns);
10156                 bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
10157                 rc = copyin(u, bf->bf_insns, len);
10158                 if (rc != 0)
10159                         goto error;
10160
10161                 if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
10162                         rc = EINVAL;
10163                         goto error;
10164                 }
10165         }
10166 set_policy:
10167         rw_wlock(&sc->policy_lock);
10168         old = sc->policy;
10169         sc->policy = op;
10170         rw_wunlock(&sc->policy_lock);
10171         free_offload_policy(old);
10172
10173         return (0);
10174 }
10175
10176 #define MAX_READ_BUF_SIZE (128 * 1024)
10177 static int
10178 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
10179 {
10180         uint32_t addr, remaining, n;
10181         uint32_t *buf;
10182         int rc;
10183         uint8_t *dst;
10184
10185         rc = validate_mem_range(sc, mr->addr, mr->len);
10186         if (rc != 0)
10187                 return (rc);
10188
10189         buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
10190         addr = mr->addr;
10191         remaining = mr->len;
10192         dst = (void *)mr->data;
10193
10194         while (remaining) {
10195                 n = min(remaining, MAX_READ_BUF_SIZE);
10196                 read_via_memwin(sc, 2, addr, buf, n);
10197
10198                 rc = copyout(buf, dst, n);
10199                 if (rc != 0)
10200                         break;
10201
10202                 dst += n;
10203                 remaining -= n;
10204                 addr += n;
10205         }
10206
10207         free(buf, M_CXGBE);
10208         return (rc);
10209 }
10210 #undef MAX_READ_BUF_SIZE
10211
10212 static int
10213 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
10214 {
10215         int rc;
10216
10217         if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
10218                 return (EINVAL);
10219
10220         if (i2cd->len > sizeof(i2cd->data))
10221                 return (EFBIG);
10222
10223         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
10224         if (rc)
10225                 return (rc);
10226         rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
10227             i2cd->offset, i2cd->len, &i2cd->data[0]);
10228         end_synchronized_op(sc, 0);
10229
10230         return (rc);
10231 }
10232
10233 static int
10234 clear_stats(struct adapter *sc, u_int port_id)
10235 {
10236         int i, v, bg_map;
10237         struct port_info *pi;
10238         struct vi_info *vi;
10239         struct sge_rxq *rxq;
10240         struct sge_txq *txq;
10241         struct sge_wrq *wrq;
10242 #ifdef TCP_OFFLOAD
10243         struct sge_ofld_rxq *ofld_rxq;
10244 #endif
10245
10246         if (port_id >= sc->params.nports)
10247                 return (EINVAL);
10248         pi = sc->port[port_id];
10249         if (pi == NULL)
10250                 return (EIO);
10251
10252         /* MAC stats */
10253         t4_clr_port_stats(sc, pi->tx_chan);
10254         pi->tx_parse_error = 0;
10255         pi->tnl_cong_drops = 0;
10256         mtx_lock(&sc->reg_lock);
10257         for_each_vi(pi, v, vi) {
10258                 if (vi->flags & VI_INIT_DONE)
10259                         t4_clr_vi_stats(sc, vi->vin);
10260         }
10261         bg_map = pi->mps_bg_map;
10262         v = 0;  /* reuse */
10263         while (bg_map) {
10264                 i = ffs(bg_map) - 1;
10265                 t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
10266                     1, A_TP_MIB_TNL_CNG_DROP_0 + i);
10267                 bg_map &= ~(1 << i);
10268         }
10269         mtx_unlock(&sc->reg_lock);
10270
10271         /*
10272          * Since this command accepts a port, clear stats for
10273          * all VIs on this port.
10274          */
10275         for_each_vi(pi, v, vi) {
10276                 if (vi->flags & VI_INIT_DONE) {
10277
10278                         for_each_rxq(vi, i, rxq) {
10279 #if defined(INET) || defined(INET6)
10280                                 rxq->lro.lro_queued = 0;
10281                                 rxq->lro.lro_flushed = 0;
10282 #endif
10283                                 rxq->rxcsum = 0;
10284                                 rxq->vlan_extraction = 0;
10285
10286                                 rxq->fl.mbuf_allocated = 0;
10287                                 rxq->fl.mbuf_inlined = 0;
10288                                 rxq->fl.cl_allocated = 0;
10289                                 rxq->fl.cl_recycled = 0;
10290                                 rxq->fl.cl_fast_recycled = 0;
10291                         }
10292
10293                         for_each_txq(vi, i, txq) {
10294                                 txq->txcsum = 0;
10295                                 txq->tso_wrs = 0;
10296                                 txq->vlan_insertion = 0;
10297                                 txq->imm_wrs = 0;
10298                                 txq->sgl_wrs = 0;
10299                                 txq->txpkt_wrs = 0;
10300                                 txq->txpkts0_wrs = 0;
10301                                 txq->txpkts1_wrs = 0;
10302                                 txq->txpkts0_pkts = 0;
10303                                 txq->txpkts1_pkts = 0;
10304                                 txq->raw_wrs = 0;
10305                                 txq->tls_wrs = 0;
10306                                 txq->kern_tls_records = 0;
10307                                 txq->kern_tls_short = 0;
10308                                 txq->kern_tls_partial = 0;
10309                                 txq->kern_tls_full = 0;
10310                                 txq->kern_tls_octets = 0;
10311                                 txq->kern_tls_waste = 0;
10312                                 txq->kern_tls_options = 0;
10313                                 txq->kern_tls_header = 0;
10314                                 txq->kern_tls_fin = 0;
10315                                 txq->kern_tls_fin_short = 0;
10316                                 txq->kern_tls_cbc = 0;
10317                                 txq->kern_tls_gcm = 0;
10318                                 mp_ring_reset_stats(txq->r);
10319                         }
10320
10321 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
10322                         for_each_ofld_txq(vi, i, wrq) {
10323                                 wrq->tx_wrs_direct = 0;
10324                                 wrq->tx_wrs_copied = 0;
10325                         }
10326 #endif
10327 #ifdef TCP_OFFLOAD
10328                         for_each_ofld_rxq(vi, i, ofld_rxq) {
10329                                 ofld_rxq->fl.mbuf_allocated = 0;
10330                                 ofld_rxq->fl.mbuf_inlined = 0;
10331                                 ofld_rxq->fl.cl_allocated = 0;
10332                                 ofld_rxq->fl.cl_recycled = 0;
10333                                 ofld_rxq->fl.cl_fast_recycled = 0;
10334                         }
10335 #endif
10336
10337                         if (IS_MAIN_VI(vi)) {
10338                                 wrq = &sc->sge.ctrlq[pi->port_id];
10339                                 wrq->tx_wrs_direct = 0;
10340                                 wrq->tx_wrs_copied = 0;
10341                         }
10342                 }
10343         }
10344
10345         return (0);
10346 }
10347
10348 int
10349 t4_os_find_pci_capability(struct adapter *sc, int cap)
10350 {
10351         int i;
10352
10353         return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
10354 }
10355
10356 int
10357 t4_os_pci_save_state(struct adapter *sc)
10358 {
10359         device_t dev;
10360         struct pci_devinfo *dinfo;
10361
10362         dev = sc->dev;
10363         dinfo = device_get_ivars(dev);
10364
10365         pci_cfg_save(dev, dinfo, 0);
10366         return (0);
10367 }
10368
10369 int
10370 t4_os_pci_restore_state(struct adapter *sc)
10371 {
10372         device_t dev;
10373         struct pci_devinfo *dinfo;
10374
10375         dev = sc->dev;
10376         dinfo = device_get_ivars(dev);
10377
10378         pci_cfg_restore(dev, dinfo);
10379         return (0);
10380 }
10381
10382 void
10383 t4_os_portmod_changed(struct port_info *pi)
10384 {
10385         struct adapter *sc = pi->adapter;
10386         struct vi_info *vi;
10387         struct ifnet *ifp;
10388         static const char *mod_str[] = {
10389                 NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
10390         };
10391
10392         KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
10393             ("%s: port_type %u", __func__, pi->port_type));
10394
10395         vi = &pi->vi[0];
10396         if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
10397                 PORT_LOCK(pi);
10398                 build_medialist(pi);
10399                 if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
10400                         fixup_link_config(pi);
10401                         apply_link_config(pi);
10402                 }
10403                 PORT_UNLOCK(pi);
10404                 end_synchronized_op(sc, LOCK_HELD);
10405         }
10406
10407         ifp = vi->ifp;
10408         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
10409                 if_printf(ifp, "transceiver unplugged.\n");
10410         else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
10411                 if_printf(ifp, "unknown transceiver inserted.\n");
10412         else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
10413                 if_printf(ifp, "unsupported transceiver inserted.\n");
10414         else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
10415                 if_printf(ifp, "%dGbps %s transceiver inserted.\n",
10416                     port_top_speed(pi), mod_str[pi->mod_type]);
10417         } else {
10418                 if_printf(ifp, "transceiver (type %d) inserted.\n",
10419                     pi->mod_type);
10420         }
10421 }
10422
10423 void
10424 t4_os_link_changed(struct port_info *pi)
10425 {
10426         struct vi_info *vi;
10427         struct ifnet *ifp;
10428         struct link_config *lc;
10429         int v;
10430
10431         PORT_LOCK_ASSERT_OWNED(pi);
10432
10433         for_each_vi(pi, v, vi) {
10434                 ifp = vi->ifp;
10435                 if (ifp == NULL)
10436                         continue;
10437
10438                 lc = &pi->link_cfg;
10439                 if (lc->link_ok) {
10440                         ifp->if_baudrate = IF_Mbps(lc->speed);
10441                         if_link_state_change(ifp, LINK_STATE_UP);
10442                 } else {
10443                         if_link_state_change(ifp, LINK_STATE_DOWN);
10444                 }
10445         }
10446 }
10447
10448 void
10449 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
10450 {
10451         struct adapter *sc;
10452
10453         sx_slock(&t4_list_lock);
10454         SLIST_FOREACH(sc, &t4_list, link) {
10455                 /*
10456                  * func should not make any assumptions about what state sc is
10457                  * in - the only guarantee is that sc->sc_lock is a valid lock.
10458                  */
10459                 func(sc, arg);
10460         }
10461         sx_sunlock(&t4_list_lock);
10462 }
10463
10464 static int
10465 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
10466     struct thread *td)
10467 {
10468         int rc;
10469         struct adapter *sc = dev->si_drv1;
10470
10471         rc = priv_check(td, PRIV_DRIVER);
10472         if (rc != 0)
10473                 return (rc);
10474
10475         switch (cmd) {
10476         case CHELSIO_T4_GETREG: {
10477                 struct t4_reg *edata = (struct t4_reg *)data;
10478
10479                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
10480                         return (EFAULT);
10481
10482                 if (edata->size == 4)
10483                         edata->val = t4_read_reg(sc, edata->addr);
10484                 else if (edata->size == 8)
10485                         edata->val = t4_read_reg64(sc, edata->addr);
10486                 else
10487                         return (EINVAL);
10488
10489                 break;
10490         }
10491         case CHELSIO_T4_SETREG: {
10492                 struct t4_reg *edata = (struct t4_reg *)data;
10493
10494                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
10495                         return (EFAULT);
10496
10497                 if (edata->size == 4) {
10498                         if (edata->val & 0xffffffff00000000)
10499                                 return (EINVAL);
10500                         t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
10501                 } else if (edata->size == 8)
10502                         t4_write_reg64(sc, edata->addr, edata->val);
10503                 else
10504                         return (EINVAL);
10505                 break;
10506         }
10507         case CHELSIO_T4_REGDUMP: {
10508                 struct t4_regdump *regs = (struct t4_regdump *)data;
10509                 int reglen = t4_get_regs_len(sc);
10510                 uint8_t *buf;
10511
10512                 if (regs->len < reglen) {
10513                         regs->len = reglen; /* hint to the caller */
10514                         return (ENOBUFS);
10515                 }
10516
10517                 regs->len = reglen;
10518                 buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
10519                 get_regs(sc, regs, buf);
10520                 rc = copyout(buf, regs->data, reglen);
10521                 free(buf, M_CXGBE);
10522                 break;
10523         }
10524         case CHELSIO_T4_GET_FILTER_MODE:
10525                 rc = get_filter_mode(sc, (uint32_t *)data);
10526                 break;
10527         case CHELSIO_T4_SET_FILTER_MODE:
10528                 rc = set_filter_mode(sc, *(uint32_t *)data);
10529                 break;
10530         case CHELSIO_T4_GET_FILTER:
10531                 rc = get_filter(sc, (struct t4_filter *)data);
10532                 break;
10533         case CHELSIO_T4_SET_FILTER:
10534                 rc = set_filter(sc, (struct t4_filter *)data);
10535                 break;
10536         case CHELSIO_T4_DEL_FILTER:
10537                 rc = del_filter(sc, (struct t4_filter *)data);
10538                 break;
10539         case CHELSIO_T4_GET_SGE_CONTEXT:
10540                 rc = get_sge_context(sc, (struct t4_sge_context *)data);
10541                 break;
10542         case CHELSIO_T4_LOAD_FW:
10543                 rc = load_fw(sc, (struct t4_data *)data);
10544                 break;
10545         case CHELSIO_T4_GET_MEM:
10546                 rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
10547                 break;
10548         case CHELSIO_T4_GET_I2C:
10549                 rc = read_i2c(sc, (struct t4_i2c_data *)data);
10550                 break;
10551         case CHELSIO_T4_CLEAR_STATS:
10552                 rc = clear_stats(sc, *(uint32_t *)data);
10553                 break;
10554         case CHELSIO_T4_SCHED_CLASS:
10555                 rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
10556                 break;
10557         case CHELSIO_T4_SCHED_QUEUE:
10558                 rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
10559                 break;
10560         case CHELSIO_T4_GET_TRACER:
10561                 rc = t4_get_tracer(sc, (struct t4_tracer *)data);
10562                 break;
10563         case CHELSIO_T4_SET_TRACER:
10564                 rc = t4_set_tracer(sc, (struct t4_tracer *)data);
10565                 break;
10566         case CHELSIO_T4_LOAD_CFG:
10567                 rc = load_cfg(sc, (struct t4_data *)data);
10568                 break;
10569         case CHELSIO_T4_LOAD_BOOT:
10570                 rc = load_boot(sc, (struct t4_bootrom *)data);
10571                 break;
10572         case CHELSIO_T4_LOAD_BOOTCFG:
10573                 rc = load_bootcfg(sc, (struct t4_data *)data);
10574                 break;
10575         case CHELSIO_T4_CUDBG_DUMP:
10576                 rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
10577                 break;
10578         case CHELSIO_T4_SET_OFLD_POLICY:
10579                 rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
10580                 break;
10581         default:
10582                 rc = ENOTTY;
10583         }
10584
10585         return (rc);
10586 }
10587
10588 #ifdef TCP_OFFLOAD
10589 static int
10590 toe_capability(struct vi_info *vi, int enable)
10591 {
10592         int rc;
10593         struct port_info *pi = vi->pi;
10594         struct adapter *sc = pi->adapter;
10595
10596         ASSERT_SYNCHRONIZED_OP(sc);
10597
10598         if (!is_offload(sc))
10599                 return (ENODEV);
10600
10601         if (enable) {
10602                 if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
10603                         /* TOE is already enabled. */
10604                         return (0);
10605                 }
10606
10607                 /*
10608                  * We need the port's queues around so that we're able to send
10609                  * and receive CPLs to/from the TOE even if the ifnet for this
10610                  * port has never been UP'd administratively.
10611                  */
10612                 if (!(vi->flags & VI_INIT_DONE)) {
10613                         rc = vi_full_init(vi);
10614                         if (rc)
10615                                 return (rc);
10616                 }
10617                 if (!(pi->vi[0].flags & VI_INIT_DONE)) {
10618                         rc = vi_full_init(&pi->vi[0]);
10619                         if (rc)
10620                                 return (rc);
10621                 }
10622
10623                 if (isset(&sc->offload_map, pi->port_id)) {
10624                         /* TOE is enabled on another VI of this port. */
10625                         pi->uld_vis++;
10626                         return (0);
10627                 }
10628
10629                 if (!uld_active(sc, ULD_TOM)) {
10630                         rc = t4_activate_uld(sc, ULD_TOM);
10631                         if (rc == EAGAIN) {
10632                                 log(LOG_WARNING,
10633                                     "You must kldload t4_tom.ko before trying "
10634                                     "to enable TOE on a cxgbe interface.\n");
10635                         }
10636                         if (rc != 0)
10637                                 return (rc);
10638                         KASSERT(sc->tom_softc != NULL,
10639                             ("%s: TOM activated but softc NULL", __func__));
10640                         KASSERT(uld_active(sc, ULD_TOM),
10641                             ("%s: TOM activated but flag not set", __func__));
10642                 }
10643
10644                 /* Activate iWARP and iSCSI too, if the modules are loaded. */
10645                 if (!uld_active(sc, ULD_IWARP))
10646                         (void) t4_activate_uld(sc, ULD_IWARP);
10647                 if (!uld_active(sc, ULD_ISCSI))
10648                         (void) t4_activate_uld(sc, ULD_ISCSI);
10649
10650                 pi->uld_vis++;
10651                 setbit(&sc->offload_map, pi->port_id);
10652         } else {
10653                 pi->uld_vis--;
10654
10655                 if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
10656                         return (0);
10657
10658                 KASSERT(uld_active(sc, ULD_TOM),
10659                     ("%s: TOM never initialized?", __func__));
10660                 clrbit(&sc->offload_map, pi->port_id);
10661         }
10662
10663         return (0);
10664 }
10665
10666 /*
10667  * Add an upper layer driver to the global list.
10668  */
10669 int
10670 t4_register_uld(struct uld_info *ui)
10671 {
10672         int rc = 0;
10673         struct uld_info *u;
10674
10675         sx_xlock(&t4_uld_list_lock);
10676         SLIST_FOREACH(u, &t4_uld_list, link) {
10677             if (u->uld_id == ui->uld_id) {
10678                     rc = EEXIST;
10679                     goto done;
10680             }
10681         }
10682
10683         SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
10684         ui->refcount = 0;
10685 done:
10686         sx_xunlock(&t4_uld_list_lock);
10687         return (rc);
10688 }
10689
10690 int
10691 t4_unregister_uld(struct uld_info *ui)
10692 {
10693         int rc = EINVAL;
10694         struct uld_info *u;
10695
10696         sx_xlock(&t4_uld_list_lock);
10697
10698         SLIST_FOREACH(u, &t4_uld_list, link) {
10699             if (u == ui) {
10700                     if (ui->refcount > 0) {
10701                             rc = EBUSY;
10702                             goto done;
10703                     }
10704
10705                     SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
10706                     rc = 0;
10707                     goto done;
10708             }
10709         }
10710 done:
10711         sx_xunlock(&t4_uld_list_lock);
10712         return (rc);
10713 }
10714
10715 int
10716 t4_activate_uld(struct adapter *sc, int id)
10717 {
10718         int rc;
10719         struct uld_info *ui;
10720
10721         ASSERT_SYNCHRONIZED_OP(sc);
10722
10723         if (id < 0 || id > ULD_MAX)
10724                 return (EINVAL);
10725         rc = EAGAIN;    /* kldoad the module with this ULD and try again. */
10726
10727         sx_slock(&t4_uld_list_lock);
10728
10729         SLIST_FOREACH(ui, &t4_uld_list, link) {
10730                 if (ui->uld_id == id) {
10731                         if (!(sc->flags & FULL_INIT_DONE)) {
10732                                 rc = adapter_full_init(sc);
10733                                 if (rc != 0)
10734                                         break;
10735                         }
10736
10737                         rc = ui->activate(sc);
10738                         if (rc == 0) {
10739                                 setbit(&sc->active_ulds, id);
10740                                 ui->refcount++;
10741                         }
10742                         break;
10743                 }
10744         }
10745
10746         sx_sunlock(&t4_uld_list_lock);
10747
10748         return (rc);
10749 }
10750
10751 int
10752 t4_deactivate_uld(struct adapter *sc, int id)
10753 {
10754         int rc;
10755         struct uld_info *ui;
10756
10757         ASSERT_SYNCHRONIZED_OP(sc);
10758
10759         if (id < 0 || id > ULD_MAX)
10760                 return (EINVAL);
10761         rc = ENXIO;
10762
10763         sx_slock(&t4_uld_list_lock);
10764
10765         SLIST_FOREACH(ui, &t4_uld_list, link) {
10766                 if (ui->uld_id == id) {
10767                         rc = ui->deactivate(sc);
10768                         if (rc == 0) {
10769                                 clrbit(&sc->active_ulds, id);
10770                                 ui->refcount--;
10771                         }
10772                         break;
10773                 }
10774         }
10775
10776         sx_sunlock(&t4_uld_list_lock);
10777
10778         return (rc);
10779 }
10780
10781 int
10782 uld_active(struct adapter *sc, int uld_id)
10783 {
10784
10785         MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
10786
10787         return (isset(&sc->active_ulds, uld_id));
10788 }
10789 #endif
10790
10791 /*
10792  * t  = ptr to tunable.
10793  * nc = number of CPUs.
10794  * c  = compiled in default for that tunable.
10795  */
10796 static void
10797 calculate_nqueues(int *t, int nc, const int c)
10798 {
10799         int nq;
10800
10801         if (*t > 0)
10802                 return;
10803         nq = *t < 0 ? -*t : c;
10804         *t = min(nc, nq);
10805 }
10806
10807 /*
10808  * Come up with reasonable defaults for some of the tunables, provided they're
10809  * not set by the user (in which case we'll use the values as is).
10810  */
10811 static void
10812 tweak_tunables(void)
10813 {
10814         int nc = mp_ncpus;      /* our snapshot of the number of CPUs */
10815
10816         if (t4_ntxq < 1) {
10817 #ifdef RSS
10818                 t4_ntxq = rss_getnumbuckets();
10819 #else
10820                 calculate_nqueues(&t4_ntxq, nc, NTXQ);
10821 #endif
10822         }
10823
10824         calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
10825
10826         if (t4_nrxq < 1) {
10827 #ifdef RSS
10828                 t4_nrxq = rss_getnumbuckets();
10829 #else
10830                 calculate_nqueues(&t4_nrxq, nc, NRXQ);
10831 #endif
10832         }
10833
10834         calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
10835
10836 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
10837         calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
10838         calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
10839 #endif
10840 #ifdef TCP_OFFLOAD
10841         calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
10842         calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
10843 #endif
10844
10845 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
10846         if (t4_toecaps_allowed == -1)
10847                 t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
10848 #else
10849         if (t4_toecaps_allowed == -1)
10850                 t4_toecaps_allowed = 0;
10851 #endif
10852
10853 #ifdef TCP_OFFLOAD
10854         if (t4_rdmacaps_allowed == -1) {
10855                 t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
10856                     FW_CAPS_CONFIG_RDMA_RDMAC;
10857         }
10858
10859         if (t4_iscsicaps_allowed == -1) {
10860                 t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
10861                     FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
10862                     FW_CAPS_CONFIG_ISCSI_T10DIF;
10863         }
10864
10865         if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
10866                 t4_tmr_idx_ofld = TMR_IDX_OFLD;
10867
10868         if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
10869                 t4_pktc_idx_ofld = PKTC_IDX_OFLD;
10870 #else
10871         if (t4_rdmacaps_allowed == -1)
10872                 t4_rdmacaps_allowed = 0;
10873
10874         if (t4_iscsicaps_allowed == -1)
10875                 t4_iscsicaps_allowed = 0;
10876 #endif
10877
10878 #ifdef DEV_NETMAP
10879         calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
10880         calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
10881 #endif
10882
10883         if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
10884                 t4_tmr_idx = TMR_IDX;
10885
10886         if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
10887                 t4_pktc_idx = PKTC_IDX;
10888
10889         if (t4_qsize_txq < 128)
10890                 t4_qsize_txq = 128;
10891
10892         if (t4_qsize_rxq < 128)
10893                 t4_qsize_rxq = 128;
10894         while (t4_qsize_rxq & 7)
10895                 t4_qsize_rxq++;
10896
10897         t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
10898
10899         /*
10900          * Number of VIs to create per-port.  The first VI is the "main" regular
10901          * VI for the port.  The rest are additional virtual interfaces on the
10902          * same physical port.  Note that the main VI does not have native
10903          * netmap support but the extra VIs do.
10904          *
10905          * Limit the number of VIs per port to the number of available
10906          * MAC addresses per port.
10907          */
10908         if (t4_num_vis < 1)
10909                 t4_num_vis = 1;
10910         if (t4_num_vis > nitems(vi_mac_funcs)) {
10911                 t4_num_vis = nitems(vi_mac_funcs);
10912                 printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
10913         }
10914
10915         if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
10916                 pcie_relaxed_ordering = 1;
10917 #if defined(__i386__) || defined(__amd64__)
10918                 if (cpu_vendor_id == CPU_VENDOR_INTEL)
10919                         pcie_relaxed_ordering = 0;
10920 #endif
10921         }
10922 }
10923
10924 #ifdef DDB
10925 static void
10926 t4_dump_tcb(struct adapter *sc, int tid)
10927 {
10928         uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
10929
10930         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
10931         save = t4_read_reg(sc, reg);
10932         base = sc->memwin[2].mw_base;
10933
10934         /* Dump TCB for the tid */
10935         tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10936         tcb_addr += tid * TCB_SIZE;
10937
10938         if (is_t4(sc)) {
10939                 pf = 0;
10940                 win_pos = tcb_addr & ~0xf;      /* start must be 16B aligned */
10941         } else {
10942                 pf = V_PFNUM(sc->pf);
10943                 win_pos = tcb_addr & ~0x7f;     /* start must be 128B aligned */
10944         }
10945         t4_write_reg(sc, reg, win_pos | pf);
10946         t4_read_reg(sc, reg);
10947
10948         off = tcb_addr - win_pos;
10949         for (i = 0; i < 4; i++) {
10950                 uint32_t buf[8];
10951                 for (j = 0; j < 8; j++, off += 4)
10952                         buf[j] = htonl(t4_read_reg(sc, base + off));
10953
10954                 db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
10955                     buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
10956                     buf[7]);
10957         }
10958
10959         t4_write_reg(sc, reg, save);
10960         t4_read_reg(sc, reg);
10961 }
10962
10963 static void
10964 t4_dump_devlog(struct adapter *sc)
10965 {
10966         struct devlog_params *dparams = &sc->params.devlog;
10967         struct fw_devlog_e e;
10968         int i, first, j, m, nentries, rc;
10969         uint64_t ftstamp = UINT64_MAX;
10970
10971         if (dparams->start == 0) {
10972                 db_printf("devlog params not valid\n");
10973                 return;
10974         }
10975
10976         nentries = dparams->size / sizeof(struct fw_devlog_e);
10977         m = fwmtype_to_hwmtype(dparams->memtype);
10978
10979         /* Find the first entry. */
10980         first = -1;
10981         for (i = 0; i < nentries && !db_pager_quit; i++) {
10982                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
10983                     sizeof(e), (void *)&e);
10984                 if (rc != 0)
10985                         break;
10986
10987                 if (e.timestamp == 0)
10988                         break;
10989
10990                 e.timestamp = be64toh(e.timestamp);
10991                 if (e.timestamp < ftstamp) {
10992                         ftstamp = e.timestamp;
10993                         first = i;
10994                 }
10995         }
10996
10997         if (first == -1)
10998                 return;
10999
11000         i = first;
11001         do {
11002                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
11003                     sizeof(e), (void *)&e);
11004                 if (rc != 0)
11005                         return;
11006
11007                 if (e.timestamp == 0)
11008                         return;
11009
11010                 e.timestamp = be64toh(e.timestamp);
11011                 e.seqno = be32toh(e.seqno);
11012                 for (j = 0; j < 8; j++)
11013                         e.params[j] = be32toh(e.params[j]);
11014
11015                 db_printf("%10d  %15ju  %8s  %8s  ",
11016                     e.seqno, e.timestamp,
11017                     (e.level < nitems(devlog_level_strings) ?
11018                         devlog_level_strings[e.level] : "UNKNOWN"),
11019                     (e.facility < nitems(devlog_facility_strings) ?
11020                         devlog_facility_strings[e.facility] : "UNKNOWN"));
11021                 db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
11022                     e.params[3], e.params[4], e.params[5], e.params[6],
11023                     e.params[7]);
11024
11025                 if (++i == nentries)
11026                         i = 0;
11027         } while (i != first && !db_pager_quit);
11028 }
11029
11030 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
11031 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
11032
11033 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
11034 {
11035         device_t dev;
11036         int t;
11037         bool valid;
11038
11039         valid = false;
11040         t = db_read_token();
11041         if (t == tIDENT) {
11042                 dev = device_lookup_by_name(db_tok_string);
11043                 valid = true;
11044         }
11045         db_skip_to_eol();
11046         if (!valid) {
11047                 db_printf("usage: show t4 devlog <nexus>\n");
11048                 return;
11049         }
11050
11051         if (dev == NULL) {
11052                 db_printf("device not found\n");
11053                 return;
11054         }
11055
11056         t4_dump_devlog(device_get_softc(dev));
11057 }
11058
11059 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
11060 {
11061         device_t dev;
11062         int radix, tid, t;
11063         bool valid;
11064
11065         valid = false;
11066         radix = db_radix;
11067         db_radix = 10;
11068         t = db_read_token();
11069         if (t == tIDENT) {
11070                 dev = device_lookup_by_name(db_tok_string);
11071                 t = db_read_token();
11072                 if (t == tNUMBER) {
11073                         tid = db_tok_number;
11074                         valid = true;
11075                 }
11076         }       
11077         db_radix = radix;
11078         db_skip_to_eol();
11079         if (!valid) {
11080                 db_printf("usage: show t4 tcb <nexus> <tid>\n");
11081                 return;
11082         }
11083
11084         if (dev == NULL) {
11085                 db_printf("device not found\n");
11086                 return;
11087         }
11088         if (tid < 0) {
11089                 db_printf("invalid tid\n");
11090                 return;
11091         }
11092
11093         t4_dump_tcb(device_get_softc(dev), tid);
11094 }
11095 #endif
11096
11097 static struct sx mlu;   /* mod load unload */
11098 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
11099
11100 static int
11101 mod_event(module_t mod, int cmd, void *arg)
11102 {
11103         int rc = 0;
11104         static int loaded = 0;
11105
11106         switch (cmd) {
11107         case MOD_LOAD:
11108                 sx_xlock(&mlu);
11109                 if (loaded++ == 0) {
11110                         t4_sge_modload();
11111                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
11112                             t4_filter_rpl, CPL_COOKIE_FILTER);
11113                         t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
11114                             do_l2t_write_rpl, CPL_COOKIE_FILTER);
11115                         t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
11116                             t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
11117                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
11118                             t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
11119                         t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
11120                             t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
11121                         t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
11122                         t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
11123                         t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
11124                             do_smt_write_rpl);
11125                         sx_init(&t4_list_lock, "T4/T5 adapters");
11126                         SLIST_INIT(&t4_list);
11127                         callout_init(&fatal_callout, 1);
11128 #ifdef TCP_OFFLOAD
11129                         sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
11130                         SLIST_INIT(&t4_uld_list);
11131 #endif
11132 #ifdef INET6
11133                         t4_clip_modload();
11134 #endif
11135 #ifdef KERN_TLS
11136                         t6_ktls_modload();
11137 #endif
11138                         t4_tracer_modload();
11139                         tweak_tunables();
11140                 }
11141                 sx_xunlock(&mlu);
11142                 break;
11143
11144         case MOD_UNLOAD:
11145                 sx_xlock(&mlu);
11146                 if (--loaded == 0) {
11147                         int tries;
11148
11149                         sx_slock(&t4_list_lock);
11150                         if (!SLIST_EMPTY(&t4_list)) {
11151                                 rc = EBUSY;
11152                                 sx_sunlock(&t4_list_lock);
11153                                 goto done_unload;
11154                         }
11155 #ifdef TCP_OFFLOAD
11156                         sx_slock(&t4_uld_list_lock);
11157                         if (!SLIST_EMPTY(&t4_uld_list)) {
11158                                 rc = EBUSY;
11159                                 sx_sunlock(&t4_uld_list_lock);
11160                                 sx_sunlock(&t4_list_lock);
11161                                 goto done_unload;
11162                         }
11163 #endif
11164                         tries = 0;
11165                         while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
11166                                 uprintf("%ju clusters with custom free routine "
11167                                     "still is use.\n", t4_sge_extfree_refs());
11168                                 pause("t4unload", 2 * hz);
11169                         }
11170 #ifdef TCP_OFFLOAD
11171                         sx_sunlock(&t4_uld_list_lock);
11172 #endif
11173                         sx_sunlock(&t4_list_lock);
11174
11175                         if (t4_sge_extfree_refs() == 0) {
11176                                 t4_tracer_modunload();
11177 #ifdef KERN_TLS
11178                                 t6_ktls_modunload();
11179 #endif
11180 #ifdef INET6
11181                                 t4_clip_modunload();
11182 #endif
11183 #ifdef TCP_OFFLOAD
11184                                 sx_destroy(&t4_uld_list_lock);
11185 #endif
11186                                 sx_destroy(&t4_list_lock);
11187                                 t4_sge_modunload();
11188                                 loaded = 0;
11189                         } else {
11190                                 rc = EBUSY;
11191                                 loaded++;       /* undo earlier decrement */
11192                         }
11193                 }
11194 done_unload:
11195                 sx_xunlock(&mlu);
11196                 break;
11197         }
11198
11199         return (rc);
11200 }
11201
11202 static devclass_t t4_devclass, t5_devclass, t6_devclass;
11203 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
11204 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
11205
11206 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
11207 MODULE_VERSION(t4nex, 1);
11208 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
11209 #ifdef DEV_NETMAP
11210 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
11211 #endif /* DEV_NETMAP */
11212
11213 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
11214 MODULE_VERSION(t5nex, 1);
11215 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
11216 #ifdef DEV_NETMAP
11217 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
11218 #endif /* DEV_NETMAP */
11219
11220 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
11221 MODULE_VERSION(t6nex, 1);
11222 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
11223 #ifdef DEV_NETMAP
11224 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
11225 #endif /* DEV_NETMAP */
11226
11227 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
11228 MODULE_VERSION(cxgbe, 1);
11229
11230 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
11231 MODULE_VERSION(cxl, 1);
11232
11233 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
11234 MODULE_VERSION(cc, 1);
11235
11236 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
11237 MODULE_VERSION(vcxgbe, 1);
11238
11239 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
11240 MODULE_VERSION(vcxl, 1);
11241
11242 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
11243 MODULE_VERSION(vcc, 1);