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