1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
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#include "opt_ddb.h"
32#include "opt_inet.h"
33#include "opt_inet6.h"
34#include "opt_kern_tls.h"
35#include "opt_ratelimit.h"
36#include "opt_rss.h"
37
38#include <sys/param.h>
39#include <sys/conf.h>
40#include <sys/priv.h>
41#include <sys/kernel.h>
42#include <sys/bus.h>
43#include <sys/eventhandler.h>
44#include <sys/module.h>
45#include <sys/malloc.h>
46#include <sys/queue.h>
47#include <sys/taskqueue.h>
48#include <sys/pciio.h>
49#include <dev/pci/pcireg.h>
50#include <dev/pci/pcivar.h>
51#include <dev/pci/pci_private.h>
52#include <sys/firmware.h>
53#include <sys/sbuf.h>
54#include <sys/smp.h>
55#include <sys/socket.h>
56#include <sys/sockio.h>
57#include <sys/sysctl.h>
58#include <net/ethernet.h>
59#include <net/if.h>
60#include <net/if_types.h>
61#include <net/if_dl.h>
62#include <net/if_vlan_var.h>
63#ifdef RSS
64#include <net/rss_config.h>
65#endif
66#include <netinet/in.h>
67#include <netinet/ip.h>
68#ifdef KERN_TLS
69#include <netinet/tcp_seq.h>
70#endif
71#if defined(__i386__) || defined(__amd64__)
72#include <machine/md_var.h>
73#include <machine/cputypes.h>
74#include <vm/vm.h>
75#include <vm/pmap.h>
76#endif
77#ifdef DDB
78#include <ddb/ddb.h>
79#include <ddb/db_lex.h>
80#endif
81
82#include "common/common.h"
83#include "common/t4_msg.h"
84#include "common/t4_regs.h"
85#include "common/t4_regs_values.h"
86#include "cudbg/cudbg.h"
87#include "t4_clip.h"
88#include "t4_ioctl.h"
89#include "t4_l2t.h"
90#include "t4_mp_ring.h"
91#include "t4_if.h"
92#include "t4_smt.h"
93
94/* T4 bus driver interface */
95static int t4_probe(device_t);
96static int t4_attach(device_t);
97static int t4_detach(device_t);
98static int t4_child_location(device_t, device_t, struct sbuf *);
99static int t4_ready(device_t);
100static int t4_read_port_device(device_t, int, device_t *);
101static int t4_suspend(device_t);
102static int t4_resume(device_t);
103static int t4_reset_prepare(device_t, device_t);
104static int t4_reset_post(device_t, device_t);
105static device_method_t t4_methods[] = {
106	DEVMETHOD(device_probe,		t4_probe),
107	DEVMETHOD(device_attach,	t4_attach),
108	DEVMETHOD(device_detach,	t4_detach),
109	DEVMETHOD(device_suspend,	t4_suspend),
110	DEVMETHOD(device_resume,	t4_resume),
111
112	DEVMETHOD(bus_child_location,	t4_child_location),
113	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
114	DEVMETHOD(bus_reset_post,	t4_reset_post),
115
116	DEVMETHOD(t4_is_main_ready,	t4_ready),
117	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
118
119	DEVMETHOD_END
120};
121static driver_t t4_driver = {
122	"t4nex",
123	t4_methods,
124	sizeof(struct adapter)
125};
126
127
128/* T4 port (cxgbe) interface */
129static int cxgbe_probe(device_t);
130static int cxgbe_attach(device_t);
131static int cxgbe_detach(device_t);
132device_method_t cxgbe_methods[] = {
133	DEVMETHOD(device_probe,		cxgbe_probe),
134	DEVMETHOD(device_attach,	cxgbe_attach),
135	DEVMETHOD(device_detach,	cxgbe_detach),
136	{ 0, 0 }
137};
138static driver_t cxgbe_driver = {
139	"cxgbe",
140	cxgbe_methods,
141	sizeof(struct port_info)
142};
143
144/* T4 VI (vcxgbe) interface */
145static int vcxgbe_probe(device_t);
146static int vcxgbe_attach(device_t);
147static int vcxgbe_detach(device_t);
148static device_method_t vcxgbe_methods[] = {
149	DEVMETHOD(device_probe,		vcxgbe_probe),
150	DEVMETHOD(device_attach,	vcxgbe_attach),
151	DEVMETHOD(device_detach,	vcxgbe_detach),
152	{ 0, 0 }
153};
154static driver_t vcxgbe_driver = {
155	"vcxgbe",
156	vcxgbe_methods,
157	sizeof(struct vi_info)
158};
159
160static d_ioctl_t t4_ioctl;
161
162static struct cdevsw t4_cdevsw = {
163       .d_version = D_VERSION,
164       .d_ioctl = t4_ioctl,
165       .d_name = "t4nex",
166};
167
168/* T5 bus driver interface */
169static int t5_probe(device_t);
170static device_method_t t5_methods[] = {
171	DEVMETHOD(device_probe,		t5_probe),
172	DEVMETHOD(device_attach,	t4_attach),
173	DEVMETHOD(device_detach,	t4_detach),
174	DEVMETHOD(device_suspend,	t4_suspend),
175	DEVMETHOD(device_resume,	t4_resume),
176
177	DEVMETHOD(bus_child_location,	t4_child_location),
178	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
179	DEVMETHOD(bus_reset_post,	t4_reset_post),
180
181	DEVMETHOD(t4_is_main_ready,	t4_ready),
182	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
183
184	DEVMETHOD_END
185};
186static driver_t t5_driver = {
187	"t5nex",
188	t5_methods,
189	sizeof(struct adapter)
190};
191
192
193/* T5 port (cxl) interface */
194static driver_t cxl_driver = {
195	"cxl",
196	cxgbe_methods,
197	sizeof(struct port_info)
198};
199
200/* T5 VI (vcxl) interface */
201static driver_t vcxl_driver = {
202	"vcxl",
203	vcxgbe_methods,
204	sizeof(struct vi_info)
205};
206
207/* T6 bus driver interface */
208static int t6_probe(device_t);
209static device_method_t t6_methods[] = {
210	DEVMETHOD(device_probe,		t6_probe),
211	DEVMETHOD(device_attach,	t4_attach),
212	DEVMETHOD(device_detach,	t4_detach),
213	DEVMETHOD(device_suspend,	t4_suspend),
214	DEVMETHOD(device_resume,	t4_resume),
215
216	DEVMETHOD(bus_child_location,	t4_child_location),
217	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
218	DEVMETHOD(bus_reset_post,	t4_reset_post),
219
220	DEVMETHOD(t4_is_main_ready,	t4_ready),
221	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
222
223	DEVMETHOD_END
224};
225static driver_t t6_driver = {
226	"t6nex",
227	t6_methods,
228	sizeof(struct adapter)
229};
230
231
232/* T6 port (cc) interface */
233static driver_t cc_driver = {
234	"cc",
235	cxgbe_methods,
236	sizeof(struct port_info)
237};
238
239/* T6 VI (vcc) interface */
240static driver_t vcc_driver = {
241	"vcc",
242	vcxgbe_methods,
243	sizeof(struct vi_info)
244};
245
246/* ifnet interface */
247static void cxgbe_init(void *);
248static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
249static int cxgbe_transmit(if_t, struct mbuf *);
250static void cxgbe_qflush(if_t);
251#if defined(KERN_TLS) || defined(RATELIMIT)
252static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
253    struct m_snd_tag **);
254#endif
255
256MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
257
258/*
259 * Correct lock order when you need to acquire multiple locks is t4_list_lock,
260 * then ADAPTER_LOCK, then t4_uld_list_lock.
261 */
262static struct sx t4_list_lock;
263SLIST_HEAD(, adapter) t4_list;
264#ifdef TCP_OFFLOAD
265static struct sx t4_uld_list_lock;
266SLIST_HEAD(, uld_info) t4_uld_list;
267#endif
268
269/*
270 * Tunables.  See tweak_tunables() too.
271 *
272 * Each tunable is set to a default value here if it's known at compile-time.
273 * Otherwise it is set to -n as an indication to tweak_tunables() that it should
274 * provide a reasonable default (upto n) when the driver is loaded.
275 *
276 * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
277 * T5 are under hw.cxl.
278 */
279SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
280    "cxgbe(4) parameters");
281SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282    "cxgbe(4) T5+ parameters");
283SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284    "cxgbe(4) TOE parameters");
285
286/*
287 * Number of queues for tx and rx, NIC and offload.
288 */
289#define NTXQ 16
290int t4_ntxq = -NTXQ;
291SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
292    "Number of TX queues per port");
293TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
294
295#define NRXQ 8
296int t4_nrxq = -NRXQ;
297SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
298    "Number of RX queues per port");
299TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
300
301#define NTXQ_VI 1
302static int t4_ntxq_vi = -NTXQ_VI;
303SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
304    "Number of TX queues per VI");
305
306#define NRXQ_VI 1
307static int t4_nrxq_vi = -NRXQ_VI;
308SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
309    "Number of RX queues per VI");
310
311static int t4_rsrv_noflowq = 0;
312SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
313    0, "Reserve TX queue 0 of each VI for non-flowid packets");
314
315#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
316#define NOFLDTXQ 8
317static int t4_nofldtxq = -NOFLDTXQ;
318SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
319    "Number of offload TX queues per port");
320
321#define NOFLDRXQ 2
322static int t4_nofldrxq = -NOFLDRXQ;
323SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
324    "Number of offload RX queues per port");
325
326#define NOFLDTXQ_VI 1
327static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
328SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
329    "Number of offload TX queues per VI");
330
331#define NOFLDRXQ_VI 1
332static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
333SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
334    "Number of offload RX queues per VI");
335
336#define TMR_IDX_OFLD 1
337int t4_tmr_idx_ofld = TMR_IDX_OFLD;
338SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
339    &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
340
341#define PKTC_IDX_OFLD (-1)
342int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
343SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
344    &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
345
346/* 0 means chip/fw default, non-zero number is value in microseconds */
347static u_long t4_toe_keepalive_idle = 0;
348SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
349    &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
350
351/* 0 means chip/fw default, non-zero number is value in microseconds */
352static u_long t4_toe_keepalive_interval = 0;
353SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
354    &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
355
356/* 0 means chip/fw default, non-zero number is # of keepalives before abort */
357static int t4_toe_keepalive_count = 0;
358SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
359    &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
360
361/* 0 means chip/fw default, non-zero number is value in microseconds */
362static u_long t4_toe_rexmt_min = 0;
363SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
364    &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
365
366/* 0 means chip/fw default, non-zero number is value in microseconds */
367static u_long t4_toe_rexmt_max = 0;
368SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
369    &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
370
371/* 0 means chip/fw default, non-zero number is # of rexmt before abort */
372static int t4_toe_rexmt_count = 0;
373SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
374    &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
375
376/* -1 means chip/fw default, other values are raw backoff values to use */
377static int t4_toe_rexmt_backoff[16] = {
378	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
379};
380SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
381    CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
382    "cxgbe(4) TOE retransmit backoff values");
383SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
384    &t4_toe_rexmt_backoff[0], 0, "");
385SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
386    &t4_toe_rexmt_backoff[1], 0, "");
387SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
388    &t4_toe_rexmt_backoff[2], 0, "");
389SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
390    &t4_toe_rexmt_backoff[3], 0, "");
391SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
392    &t4_toe_rexmt_backoff[4], 0, "");
393SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
394    &t4_toe_rexmt_backoff[5], 0, "");
395SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
396    &t4_toe_rexmt_backoff[6], 0, "");
397SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
398    &t4_toe_rexmt_backoff[7], 0, "");
399SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
400    &t4_toe_rexmt_backoff[8], 0, "");
401SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
402    &t4_toe_rexmt_backoff[9], 0, "");
403SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
404    &t4_toe_rexmt_backoff[10], 0, "");
405SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
406    &t4_toe_rexmt_backoff[11], 0, "");
407SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
408    &t4_toe_rexmt_backoff[12], 0, "");
409SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
410    &t4_toe_rexmt_backoff[13], 0, "");
411SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
412    &t4_toe_rexmt_backoff[14], 0, "");
413SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
414    &t4_toe_rexmt_backoff[15], 0, "");
415
416int t4_ddp_rcvbuf_len = 256 * 1024;
417SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
418    &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
419
420unsigned int t4_ddp_rcvbuf_cache = 4;
421SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
422    &t4_ddp_rcvbuf_cache, 0,
423    "maximum number of free DDP RX buffers to cache per connection");
424#endif
425
426#ifdef DEV_NETMAP
427#define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
428#define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
429static int t4_native_netmap = NN_EXTRA_VI;
430SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
431    0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
432
433#define NNMTXQ 8
434static int t4_nnmtxq = -NNMTXQ;
435SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
436    "Number of netmap TX queues");
437
438#define NNMRXQ 8
439static int t4_nnmrxq = -NNMRXQ;
440SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
441    "Number of netmap RX queues");
442
443#define NNMTXQ_VI 2
444static int t4_nnmtxq_vi = -NNMTXQ_VI;
445SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
446    "Number of netmap TX queues per VI");
447
448#define NNMRXQ_VI 2
449static int t4_nnmrxq_vi = -NNMRXQ_VI;
450SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
451    "Number of netmap RX queues per VI");
452#endif
453
454/*
455 * Holdoff parameters for ports.
456 */
457#define TMR_IDX 1
458int t4_tmr_idx = TMR_IDX;
459SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
460    0, "Holdoff timer index");
461TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
462
463#define PKTC_IDX (-1)
464int t4_pktc_idx = PKTC_IDX;
465SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
466    0, "Holdoff packet counter index");
467TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
468
469/*
470 * Size (# of entries) of each tx and rx queue.
471 */
472unsigned int t4_qsize_txq = TX_EQ_QSIZE;
473SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
474    "Number of descriptors in each TX queue");
475
476unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
477SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
478    "Number of descriptors in each RX queue");
479
480/*
481 * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
482 */
483int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
484SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
485    0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
486
487/*
488 * Configuration file.  All the _CF names here are special.
489 */
490#define DEFAULT_CF	"default"
491#define BUILTIN_CF	"built-in"
492#define FLASH_CF	"flash"
493#define UWIRE_CF	"uwire"
494#define FPGA_CF		"fpga"
495static char t4_cfg_file[32] = DEFAULT_CF;
496SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
497    sizeof(t4_cfg_file), "Firmware configuration file");
498
499/*
500 * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
501 * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
502 * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
503 *            mark or when signalled to do so, 0 to never emit PAUSE.
504 * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
505 *                 negotiated settings will override rx_pause/tx_pause.
506 *                 Otherwise rx_pause/tx_pause are applied forcibly.
507 */
508static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
509SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
510    &t4_pause_settings, 0,
511    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
512
513/*
514 * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
515 * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
516 *  0 to disable FEC.
517 */
518static int t4_fec = -1;
519SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
520    "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
521
522/*
523 * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
524 * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
525 * driver runs as if this is set to 0.
526 * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
527 *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
528 *    transceiver. Multiple FEC bits may not be okay but will be passed on to
529 *    the firmware anyway (may result in l1cfg errors with old firmwares).
530 *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
531 *    means set all FEC bits that are valid for the speed.
532 */
533static int t4_force_fec = -1;
534SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
535    "Controls the use of FORCE_FEC bit in L1 configuration.");
536
537/*
538 * Link autonegotiation.
539 * -1 to run with the firmware default.
540 *  0 to disable.
541 *  1 to enable.
542 */
543static int t4_autoneg = -1;
544SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
545    "Link autonegotiation");
546
547/*
548 * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
549 * encouraged respectively).  '-n' is the same as 'n' except the firmware
550 * version used in the checks is read from the firmware bundled with the driver.
551 */
552static int t4_fw_install = 1;
553SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
554    "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
555
556/*
557 * ASIC features that will be used.  Disable the ones you don't want so that the
558 * chip resources aren't wasted on features that will not be used.
559 */
560static int t4_nbmcaps_allowed = 0;
561SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
562    &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
563
564static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
565SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
566    &t4_linkcaps_allowed, 0, "Default link capabilities");
567
568static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
569    FW_CAPS_CONFIG_SWITCH_EGRESS;
570SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
571    &t4_switchcaps_allowed, 0, "Default switch capabilities");
572
573#ifdef RATELIMIT
574static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
575	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
576#else
577static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
578	FW_CAPS_CONFIG_NIC_HASHFILTER;
579#endif
580SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
581    &t4_niccaps_allowed, 0, "Default NIC capabilities");
582
583static int t4_toecaps_allowed = -1;
584SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
585    &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
586
587static int t4_rdmacaps_allowed = -1;
588SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
589    &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
590
591static int t4_cryptocaps_allowed = -1;
592SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
593    &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
594
595static int t4_iscsicaps_allowed = -1;
596SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
597    &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
598
599static int t4_fcoecaps_allowed = 0;
600SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
601    &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
602
603static int t5_write_combine = 0;
604SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
605    0, "Use WC instead of UC for BAR2");
606
607static int t4_num_vis = 1;
608SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
609    "Number of VIs per port");
610
611/*
612 * PCIe Relaxed Ordering.
613 * -1: driver should figure out a good value.
614 * 0: disable RO.
615 * 1: enable RO.
616 * 2: leave RO alone.
617 */
618static int pcie_relaxed_ordering = -1;
619SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
620    &pcie_relaxed_ordering, 0,
621    "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
622
623static int t4_panic_on_fatal_err = 0;
624SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
625    &t4_panic_on_fatal_err, 0, "panic on fatal errors");
626
627static int t4_reset_on_fatal_err = 0;
628SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
629    &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
630
631static int t4_clock_gate_on_suspend = 0;
632SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
633    &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
634
635static int t4_tx_vm_wr = 0;
636SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
637    "Use VM work requests to transmit packets.");
638
639/*
640 * Set to non-zero to enable the attack filter.  A packet that matches any of
641 * these conditions will get dropped on ingress:
642 * 1) IP && source address == destination address.
643 * 2) TCP/IP && source address is not a unicast address.
644 * 3) TCP/IP && destination address is not a unicast address.
645 * 4) IP && source address is loopback (127.x.y.z).
646 * 5) IP && destination address is loopback (127.x.y.z).
647 * 6) IPv6 && source address == destination address.
648 * 7) IPv6 && source address is not a unicast address.
649 * 8) IPv6 && source address is loopback (::1/128).
650 * 9) IPv6 && destination address is loopback (::1/128).
651 * 10) IPv6 && source address is unspecified (::/128).
652 * 11) IPv6 && destination address is unspecified (::/128).
653 * 12) TCP/IPv6 && source address is multicast (ff00::/8).
654 * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
655 */
656static int t4_attack_filter = 0;
657SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
658    &t4_attack_filter, 0, "Drop suspicious traffic");
659
660static int t4_drop_ip_fragments = 0;
661SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
662    &t4_drop_ip_fragments, 0, "Drop IP fragments");
663
664static int t4_drop_pkts_with_l2_errors = 1;
665SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
666    &t4_drop_pkts_with_l2_errors, 0,
667    "Drop all frames with Layer 2 length or checksum errors");
668
669static int t4_drop_pkts_with_l3_errors = 0;
670SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
671    &t4_drop_pkts_with_l3_errors, 0,
672    "Drop all frames with IP version, length, or checksum errors");
673
674static int t4_drop_pkts_with_l4_errors = 0;
675SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
676    &t4_drop_pkts_with_l4_errors, 0,
677    "Drop all frames with Layer 4 length, checksum, or other errors");
678
679#ifdef TCP_OFFLOAD
680/*
681 * TOE tunables.
682 */
683static int t4_cop_managed_offloading = 0;
684SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
685    &t4_cop_managed_offloading, 0,
686    "COP (Connection Offload Policy) controls all TOE offload");
687#endif
688
689#ifdef KERN_TLS
690/*
691 * This enables KERN_TLS for all adapters if set.
692 */
693static int t4_kern_tls = 0;
694SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
695    "Enable KERN_TLS mode for T6 adapters");
696
697SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
698    "cxgbe(4) KERN_TLS parameters");
699
700static int t4_tls_inline_keys = 0;
701SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
702    &t4_tls_inline_keys, 0,
703    "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
704    "in card memory.");
705
706static int t4_tls_combo_wrs = 0;
707SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
708    0, "Attempt to combine TCB field updates with TLS record work requests.");
709#endif
710
711/* Functions used by VIs to obtain unique MAC addresses for each VI. */
712static int vi_mac_funcs[] = {
713	FW_VI_FUNC_ETH,
714	FW_VI_FUNC_OFLD,
715	FW_VI_FUNC_IWARP,
716	FW_VI_FUNC_OPENISCSI,
717	FW_VI_FUNC_OPENFCOE,
718	FW_VI_FUNC_FOISCSI,
719	FW_VI_FUNC_FOFCOE,
720};
721
722struct intrs_and_queues {
723	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
724	uint16_t num_vis;	/* number of VIs for each port */
725	uint16_t nirq;		/* Total # of vectors */
726	uint16_t ntxq;		/* # of NIC txq's for each port */
727	uint16_t nrxq;		/* # of NIC rxq's for each port */
728	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
729	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
730	uint16_t nnmtxq;	/* # of netmap txq's */
731	uint16_t nnmrxq;	/* # of netmap rxq's */
732
733	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
734	uint16_t ntxq_vi;	/* # of NIC txq's */
735	uint16_t nrxq_vi;	/* # of NIC rxq's */
736	uint16_t nofldtxq_vi;	/* # of TOE txq's */
737	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
738	uint16_t nnmtxq_vi;	/* # of netmap txq's */
739	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
740};
741
742static void setup_memwin(struct adapter *);
743static void position_memwin(struct adapter *, int, uint32_t);
744static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
745static int fwmtype_to_hwmtype(int);
746static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
747    uint32_t *);
748static int fixup_devlog_params(struct adapter *);
749static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
750static int contact_firmware(struct adapter *);
751static int partition_resources(struct adapter *);
752static int get_params__pre_init(struct adapter *);
753static int set_params__pre_init(struct adapter *);
754static int get_params__post_init(struct adapter *);
755static int set_params__post_init(struct adapter *);
756static void t4_set_desc(struct adapter *);
757static bool fixed_ifmedia(struct port_info *);
758static void build_medialist(struct port_info *);
759static void init_link_config(struct port_info *);
760static int fixup_link_config(struct port_info *);
761static int apply_link_config(struct port_info *);
762static int cxgbe_init_synchronized(struct vi_info *);
763static int cxgbe_uninit_synchronized(struct vi_info *);
764static int adapter_full_init(struct adapter *);
765static void adapter_full_uninit(struct adapter *);
766static int vi_full_init(struct vi_info *);
767static void vi_full_uninit(struct vi_info *);
768static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
769static void quiesce_txq(struct sge_txq *);
770static void quiesce_wrq(struct sge_wrq *);
771static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
772static void quiesce_vi(struct vi_info *);
773static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
774    driver_intr_t *, void *, char *);
775static int t4_free_irq(struct adapter *, struct irq *);
776static void t4_init_atid_table(struct adapter *);
777static void t4_free_atid_table(struct adapter *);
778static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
779static void vi_refresh_stats(struct vi_info *);
780static void cxgbe_refresh_stats(struct vi_info *);
781static void cxgbe_tick(void *);
782static void vi_tick(void *);
783static void cxgbe_sysctls(struct port_info *);
784static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
785static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
786static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
787static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
788static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
789static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
790static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
791static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
792static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
793static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
794static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
795static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
796static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
797static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
798static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
799static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
800static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
801static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
802static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
803static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
804static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
805static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
806static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
807static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
808static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
809static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
810static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
811static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
812static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
813static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
814static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
815static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
816static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
817static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
818static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
819static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
820static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
821static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
822static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
823static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
824static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
825static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
826static int sysctl_tids(SYSCTL_HANDLER_ARGS);
827static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
828static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
829static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
830static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
831static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
832static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
833static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
834static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
835static int sysctl_reset(SYSCTL_HANDLER_ARGS);
836#ifdef TCP_OFFLOAD
837static int sysctl_tls(SYSCTL_HANDLER_ARGS);
838static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
839static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
840static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
841static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
842static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
843static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
844static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
845#endif
846static int get_sge_context(struct adapter *, struct t4_sge_context *);
847static int load_fw(struct adapter *, struct t4_data *);
848static int load_cfg(struct adapter *, struct t4_data *);
849static int load_boot(struct adapter *, struct t4_bootrom *);
850static int load_bootcfg(struct adapter *, struct t4_data *);
851static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
852static void free_offload_policy(struct t4_offload_policy *);
853static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
854static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
855static int read_i2c(struct adapter *, struct t4_i2c_data *);
856static int clear_stats(struct adapter *, u_int);
857static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
858static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
859#ifdef TCP_OFFLOAD
860static int toe_capability(struct vi_info *, bool);
861static int t4_deactivate_all_uld(struct adapter *);
862static void t4_async_event(struct adapter *);
863#endif
864#ifdef KERN_TLS
865static int ktls_capability(struct adapter *, bool);
866#endif
867static int mod_event(module_t, int, void *);
868static int notify_siblings(device_t, int);
869static uint64_t vi_get_counter(if_t, ift_counter);
870static uint64_t cxgbe_get_counter(if_t, ift_counter);
871static void enable_vxlan_rx(struct adapter *);
872static void reset_adapter_task(void *, int);
873static void fatal_error_task(void *, int);
874static void dump_devlog(struct adapter *);
875static void dump_cim_regs(struct adapter *);
876static void dump_cimla(struct adapter *);
877
878struct {
879	uint16_t device;
880	char *desc;
881} t4_pciids[] = {
882	{0xa000, "Chelsio Terminator 4 FPGA"},
883	{0x4400, "Chelsio T440-dbg"},
884	{0x4401, "Chelsio T420-CR"},
885	{0x4402, "Chelsio T422-CR"},
886	{0x4403, "Chelsio T440-CR"},
887	{0x4404, "Chelsio T420-BCH"},
888	{0x4405, "Chelsio T440-BCH"},
889	{0x4406, "Chelsio T440-CH"},
890	{0x4407, "Chelsio T420-SO"},
891	{0x4408, "Chelsio T420-CX"},
892	{0x4409, "Chelsio T420-BT"},
893	{0x440a, "Chelsio T404-BT"},
894	{0x440e, "Chelsio T440-LP-CR"},
895}, t5_pciids[] = {
896	{0xb000, "Chelsio Terminator 5 FPGA"},
897	{0x5400, "Chelsio T580-dbg"},
898	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
899	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
900	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
901	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
902	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
903	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
904	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
905	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
906	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
907	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
908	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
909	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
910	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
911	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
912	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
913	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
914	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
915
916	/* Custom */
917	{0x5483, "Custom T540-CR"},
918	{0x5484, "Custom T540-BT"},
919}, t6_pciids[] = {
920	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
921	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
922	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
923	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
924	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
925	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
926	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
927	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
928	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
929	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
930	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
931	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
932	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
933	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
934	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
935	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
936
937	/* Custom */
938	{0x6480, "Custom T6225-CR"},
939	{0x6481, "Custom T62100-CR"},
940	{0x6482, "Custom T6225-CR"},
941	{0x6483, "Custom T62100-CR"},
942	{0x6484, "Custom T64100-CR"},
943	{0x6485, "Custom T6240-SO"},
944	{0x6486, "Custom T6225-SO-CR"},
945	{0x6487, "Custom T6225-CR"},
946};
947
948#ifdef TCP_OFFLOAD
949/*
950 * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
951 * be exactly the same for both rxq and ofld_rxq.
952 */
953CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
954CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
955#endif
956CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
957
958static int
959t4_probe(device_t dev)
960{
961	int i;
962	uint16_t v = pci_get_vendor(dev);
963	uint16_t d = pci_get_device(dev);
964	uint8_t f = pci_get_function(dev);
965
966	if (v != PCI_VENDOR_ID_CHELSIO)
967		return (ENXIO);
968
969	/* Attach only to PF0 of the FPGA */
970	if (d == 0xa000 && f != 0)
971		return (ENXIO);
972
973	for (i = 0; i < nitems(t4_pciids); i++) {
974		if (d == t4_pciids[i].device) {
975			device_set_desc(dev, t4_pciids[i].desc);
976			return (BUS_PROBE_DEFAULT);
977		}
978	}
979
980	return (ENXIO);
981}
982
983static int
984t5_probe(device_t dev)
985{
986	int i;
987	uint16_t v = pci_get_vendor(dev);
988	uint16_t d = pci_get_device(dev);
989	uint8_t f = pci_get_function(dev);
990
991	if (v != PCI_VENDOR_ID_CHELSIO)
992		return (ENXIO);
993
994	/* Attach only to PF0 of the FPGA */
995	if (d == 0xb000 && f != 0)
996		return (ENXIO);
997
998	for (i = 0; i < nitems(t5_pciids); i++) {
999		if (d == t5_pciids[i].device) {
1000			device_set_desc(dev, t5_pciids[i].desc);
1001			return (BUS_PROBE_DEFAULT);
1002		}
1003	}
1004
1005	return (ENXIO);
1006}
1007
1008static int
1009t6_probe(device_t dev)
1010{
1011	int i;
1012	uint16_t v = pci_get_vendor(dev);
1013	uint16_t d = pci_get_device(dev);
1014
1015	if (v != PCI_VENDOR_ID_CHELSIO)
1016		return (ENXIO);
1017
1018	for (i = 0; i < nitems(t6_pciids); i++) {
1019		if (d == t6_pciids[i].device) {
1020			device_set_desc(dev, t6_pciids[i].desc);
1021			return (BUS_PROBE_DEFAULT);
1022		}
1023	}
1024
1025	return (ENXIO);
1026}
1027
1028static void
1029t5_attribute_workaround(device_t dev)
1030{
1031	device_t root_port;
1032	uint32_t v;
1033
1034	/*
1035	 * The T5 chips do not properly echo the No Snoop and Relaxed
1036	 * Ordering attributes when replying to a TLP from a Root
1037	 * Port.  As a workaround, find the parent Root Port and
1038	 * disable No Snoop and Relaxed Ordering.  Note that this
1039	 * affects all devices under this root port.
1040	 */
1041	root_port = pci_find_pcie_root_port(dev);
1042	if (root_port == NULL) {
1043		device_printf(dev, "Unable to find parent root port\n");
1044		return;
1045	}
1046
1047	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1048	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1049	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1050	    0)
1051		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1052		    device_get_nameunit(root_port));
1053}
1054
1055static const struct devnames devnames[] = {
1056	{
1057		.nexus_name = "t4nex",
1058		.ifnet_name = "cxgbe",
1059		.vi_ifnet_name = "vcxgbe",
1060		.pf03_drv_name = "t4iov",
1061		.vf_nexus_name = "t4vf",
1062		.vf_ifnet_name = "cxgbev"
1063	}, {
1064		.nexus_name = "t5nex",
1065		.ifnet_name = "cxl",
1066		.vi_ifnet_name = "vcxl",
1067		.pf03_drv_name = "t5iov",
1068		.vf_nexus_name = "t5vf",
1069		.vf_ifnet_name = "cxlv"
1070	}, {
1071		.nexus_name = "t6nex",
1072		.ifnet_name = "cc",
1073		.vi_ifnet_name = "vcc",
1074		.pf03_drv_name = "t6iov",
1075		.vf_nexus_name = "t6vf",
1076		.vf_ifnet_name = "ccv"
1077	}
1078};
1079
1080void
1081t4_init_devnames(struct adapter *sc)
1082{
1083	int id;
1084
1085	id = chip_id(sc);
1086	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1087		sc->names = &devnames[id - CHELSIO_T4];
1088	else {
1089		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1090		sc->names = NULL;
1091	}
1092}
1093
1094static int
1095t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1096{
1097	const char *parent, *name;
1098	long value;
1099	int line, unit;
1100
1101	line = 0;
1102	parent = device_get_nameunit(sc->dev);
1103	name = sc->names->ifnet_name;
1104	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1105		if (resource_long_value(name, unit, "port", &value) == 0 &&
1106		    value == pi->port_id)
1107			return (unit);
1108	}
1109	return (-1);
1110}
1111
1112static void
1113t4_calibration(void *arg)
1114{
1115	struct adapter *sc;
1116	struct clock_sync *cur, *nex;
1117	uint64_t hw;
1118	sbintime_t sbt;
1119	int next_up;
1120
1121	sc = (struct adapter *)arg;
1122
1123	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1124	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1125	sbt = sbinuptime();
1126
1127	cur = &sc->cal_info[sc->cal_current];
1128	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1129	nex = &sc->cal_info[next_up];
1130	if (__predict_false(sc->cal_count == 0)) {
1131		/* First time in, just get the values in */
1132		cur->hw_cur = hw;
1133		cur->sbt_cur = sbt;
1134		sc->cal_count++;
1135		goto done;
1136	}
1137
1138	if (cur->hw_cur == hw) {
1139		/* The clock is not advancing? */
1140		sc->cal_count = 0;
1141		atomic_store_rel_int(&cur->gen, 0);
1142		goto done;
1143	}
1144
1145	seqc_write_begin(&nex->gen);
1146	nex->hw_prev = cur->hw_cur;
1147	nex->sbt_prev = cur->sbt_cur;
1148	nex->hw_cur = hw;
1149	nex->sbt_cur = sbt;
1150	seqc_write_end(&nex->gen);
1151	sc->cal_current = next_up;
1152done:
1153	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1154	    sc, C_DIRECT_EXEC);
1155}
1156
1157static void
1158t4_calibration_start(struct adapter *sc)
1159{
1160	/*
1161	 * Here if we have not done a calibration
1162	 * then do so otherwise start the appropriate
1163	 * timer.
1164	 */
1165	int i;
1166
1167	for (i = 0; i < CNT_CAL_INFO; i++) {
1168		sc->cal_info[i].gen = 0;
1169	}
1170	sc->cal_current = 0;
1171	sc->cal_count = 0;
1172	sc->cal_gen = 0;
1173	t4_calibration(sc);
1174}
1175
1176static int
1177t4_attach(device_t dev)
1178{
1179	struct adapter *sc;
1180	int rc = 0, i, j, rqidx, tqidx, nports;
1181	struct make_dev_args mda;
1182	struct intrs_and_queues iaq;
1183	struct sge *s;
1184	uint32_t *buf;
1185#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1186	int ofld_tqidx;
1187#endif
1188#ifdef TCP_OFFLOAD
1189	int ofld_rqidx;
1190#endif
1191#ifdef DEV_NETMAP
1192	int nm_rqidx, nm_tqidx;
1193#endif
1194	int num_vis;
1195
1196	sc = device_get_softc(dev);
1197	sc->dev = dev;
1198	sysctl_ctx_init(&sc->ctx);
1199	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1200
1201	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1202		t5_attribute_workaround(dev);
1203	pci_enable_busmaster(dev);
1204	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1205		uint32_t v;
1206
1207		pci_set_max_read_req(dev, 4096);
1208		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1209		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1210		if (pcie_relaxed_ordering == 0 &&
1211		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1212			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1213			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1214		} else if (pcie_relaxed_ordering == 1 &&
1215		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1216			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1217			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1218		}
1219	}
1220
1221	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1222	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1223	sc->traceq = -1;
1224	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1225	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1226	    device_get_nameunit(dev));
1227
1228	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1229	    device_get_nameunit(dev));
1230	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1231	t4_add_adapter(sc);
1232
1233	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1234	TAILQ_INIT(&sc->sfl);
1235	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1236
1237	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1238
1239	sc->policy = NULL;
1240	rw_init(&sc->policy_lock, "connection offload policy");
1241
1242	callout_init(&sc->ktls_tick, 1);
1243
1244	callout_init(&sc->cal_callout, 1);
1245
1246	refcount_init(&sc->vxlan_refcount, 0);
1247
1248	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1249	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1250
1251	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1252	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1253	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1254	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1255	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1256	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1257
1258	rc = t4_map_bars_0_and_4(sc);
1259	if (rc != 0)
1260		goto done; /* error message displayed already */
1261
1262	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1263
1264	/* Prepare the adapter for operation. */
1265	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1266	rc = -t4_prep_adapter(sc, buf);
1267	free(buf, M_CXGBE);
1268	if (rc != 0) {
1269		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1270		goto done;
1271	}
1272
1273	/*
1274	 * This is the real PF# to which we're attaching.  Works from within PCI
1275	 * passthrough environments too, where pci_get_function() could return a
1276	 * different PF# depending on the passthrough configuration.  We need to
1277	 * use the real PF# in all our communication with the firmware.
1278	 */
1279	j = t4_read_reg(sc, A_PL_WHOAMI);
1280	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1281	sc->mbox = sc->pf;
1282
1283	t4_init_devnames(sc);
1284	if (sc->names == NULL) {
1285		rc = ENOTSUP;
1286		goto done; /* error message displayed already */
1287	}
1288
1289	/*
1290	 * Do this really early, with the memory windows set up even before the
1291	 * character device.  The userland tool's register i/o and mem read
1292	 * will work even in "recovery mode".
1293	 */
1294	setup_memwin(sc);
1295	if (t4_init_devlog_params(sc, 0) == 0)
1296		fixup_devlog_params(sc);
1297	make_dev_args_init(&mda);
1298	mda.mda_devsw = &t4_cdevsw;
1299	mda.mda_uid = UID_ROOT;
1300	mda.mda_gid = GID_WHEEL;
1301	mda.mda_mode = 0600;
1302	mda.mda_si_drv1 = sc;
1303	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1304	if (rc != 0)
1305		device_printf(dev, "failed to create nexus char device: %d.\n",
1306		    rc);
1307
1308	/* Go no further if recovery mode has been requested. */
1309	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1310		device_printf(dev, "recovery mode.\n");
1311		goto done;
1312	}
1313
1314#if defined(__i386__)
1315	if ((cpu_feature & CPUID_CX8) == 0) {
1316		device_printf(dev, "64 bit atomics not available.\n");
1317		rc = ENOTSUP;
1318		goto done;
1319	}
1320#endif
1321
1322	/* Contact the firmware and try to become the master driver. */
1323	rc = contact_firmware(sc);
1324	if (rc != 0)
1325		goto done; /* error message displayed already */
1326	MPASS(sc->flags & FW_OK);
1327
1328	rc = get_params__pre_init(sc);
1329	if (rc != 0)
1330		goto done; /* error message displayed already */
1331
1332	if (sc->flags & MASTER_PF) {
1333		rc = partition_resources(sc);
1334		if (rc != 0)
1335			goto done; /* error message displayed already */
1336	}
1337
1338	rc = get_params__post_init(sc);
1339	if (rc != 0)
1340		goto done; /* error message displayed already */
1341
1342	rc = set_params__post_init(sc);
1343	if (rc != 0)
1344		goto done; /* error message displayed already */
1345
1346	rc = t4_map_bar_2(sc);
1347	if (rc != 0)
1348		goto done; /* error message displayed already */
1349
1350	rc = t4_create_dma_tag(sc);
1351	if (rc != 0)
1352		goto done; /* error message displayed already */
1353
1354	/*
1355	 * First pass over all the ports - allocate VIs and initialize some
1356	 * basic parameters like mac address, port type, etc.
1357	 */
1358	for_each_port(sc, i) {
1359		struct port_info *pi;
1360
1361		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1362		sc->port[i] = pi;
1363
1364		/* These must be set before t4_port_init */
1365		pi->adapter = sc;
1366		pi->port_id = i;
1367		/*
1368		 * XXX: vi[0] is special so we can't delay this allocation until
1369		 * pi->nvi's final value is known.
1370		 */
1371		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1372		    M_ZERO | M_WAITOK);
1373
1374		/*
1375		 * Allocate the "main" VI and initialize parameters
1376		 * like mac addr.
1377		 */
1378		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1379		if (rc != 0) {
1380			device_printf(dev, "unable to initialize port %d: %d\n",
1381			    i, rc);
1382			free(pi->vi, M_CXGBE);
1383			free(pi, M_CXGBE);
1384			sc->port[i] = NULL;
1385			goto done;
1386		}
1387
1388		if (is_bt(pi->port_type))
1389			setbit(&sc->bt_map, pi->tx_chan);
1390		else
1391			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1392
1393		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1394		    device_get_nameunit(dev), i);
1395		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1396		sc->chan_map[pi->tx_chan] = i;
1397
1398		/*
1399		 * The MPS counter for FCS errors doesn't work correctly on the
1400		 * T6 so we use the MAC counter here.  Which MAC is in use
1401		 * depends on the link settings which will be known when the
1402		 * link comes up.
1403		 */
1404		if (is_t6(sc))
1405			pi->fcs_reg = -1;
1406		else {
1407			pi->fcs_reg = t4_port_reg(sc, pi->tx_chan,
1408			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1409		}
1410		pi->fcs_base = 0;
1411
1412		/* All VIs on this port share this media. */
1413		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1414		    cxgbe_media_status);
1415
1416		PORT_LOCK(pi);
1417		init_link_config(pi);
1418		fixup_link_config(pi);
1419		build_medialist(pi);
1420		if (fixed_ifmedia(pi))
1421			pi->flags |= FIXED_IFMEDIA;
1422		PORT_UNLOCK(pi);
1423
1424		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1425		    t4_ifnet_unit(sc, pi));
1426		if (pi->dev == NULL) {
1427			device_printf(dev,
1428			    "failed to add device for port %d.\n", i);
1429			rc = ENXIO;
1430			goto done;
1431		}
1432		pi->vi[0].dev = pi->dev;
1433		device_set_softc(pi->dev, pi);
1434	}
1435
1436	/*
1437	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1438	 */
1439	nports = sc->params.nports;
1440	rc = cfg_itype_and_nqueues(sc, &iaq);
1441	if (rc != 0)
1442		goto done; /* error message displayed already */
1443
1444	num_vis = iaq.num_vis;
1445	sc->intr_type = iaq.intr_type;
1446	sc->intr_count = iaq.nirq;
1447
1448	s = &sc->sge;
1449	s->nrxq = nports * iaq.nrxq;
1450	s->ntxq = nports * iaq.ntxq;
1451	if (num_vis > 1) {
1452		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1453		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1454	}
1455	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1456	s->neq += nports;		/* ctrl queues: 1 per port */
1457	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1458#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1459	if (is_offload(sc) || is_ethoffload(sc)) {
1460		s->nofldtxq = nports * iaq.nofldtxq;
1461		if (num_vis > 1)
1462			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1463		s->neq += s->nofldtxq;
1464
1465		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1466		    M_CXGBE, M_ZERO | M_WAITOK);
1467	}
1468#endif
1469#ifdef TCP_OFFLOAD
1470	if (is_offload(sc)) {
1471		s->nofldrxq = nports * iaq.nofldrxq;
1472		if (num_vis > 1)
1473			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1474		s->neq += s->nofldrxq;	/* free list */
1475		s->niq += s->nofldrxq;
1476
1477		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1478		    M_CXGBE, M_ZERO | M_WAITOK);
1479	}
1480#endif
1481#ifdef DEV_NETMAP
1482	s->nnmrxq = 0;
1483	s->nnmtxq = 0;
1484	if (t4_native_netmap & NN_MAIN_VI) {
1485		s->nnmrxq += nports * iaq.nnmrxq;
1486		s->nnmtxq += nports * iaq.nnmtxq;
1487	}
1488	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1489		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1490		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1491	}
1492	s->neq += s->nnmtxq + s->nnmrxq;
1493	s->niq += s->nnmrxq;
1494
1495	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1496	    M_CXGBE, M_ZERO | M_WAITOK);
1497	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1498	    M_CXGBE, M_ZERO | M_WAITOK);
1499#endif
1500	MPASS(s->niq <= s->iqmap_sz);
1501	MPASS(s->neq <= s->eqmap_sz);
1502
1503	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1504	    M_ZERO | M_WAITOK);
1505	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1506	    M_ZERO | M_WAITOK);
1507	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1508	    M_ZERO | M_WAITOK);
1509	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1510	    M_ZERO | M_WAITOK);
1511	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1512	    M_ZERO | M_WAITOK);
1513
1514	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1515	    M_ZERO | M_WAITOK);
1516
1517	t4_init_l2t(sc, M_WAITOK);
1518	t4_init_smt(sc, M_WAITOK);
1519	t4_init_tx_sched(sc);
1520	t4_init_atid_table(sc);
1521#ifdef RATELIMIT
1522	t4_init_etid_table(sc);
1523#endif
1524#ifdef INET6
1525	t4_init_clip_table(sc);
1526#endif
1527	if (sc->vres.key.size != 0)
1528		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1529		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1530
1531	/*
1532	 * Second pass over the ports.  This time we know the number of rx and
1533	 * tx queues that each port should get.
1534	 */
1535	rqidx = tqidx = 0;
1536#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1537	ofld_tqidx = 0;
1538#endif
1539#ifdef TCP_OFFLOAD
1540	ofld_rqidx = 0;
1541#endif
1542#ifdef DEV_NETMAP
1543	nm_rqidx = nm_tqidx = 0;
1544#endif
1545	for_each_port(sc, i) {
1546		struct port_info *pi = sc->port[i];
1547		struct vi_info *vi;
1548
1549		if (pi == NULL)
1550			continue;
1551
1552		pi->nvi = num_vis;
1553		for_each_vi(pi, j, vi) {
1554			vi->pi = pi;
1555			vi->adapter = sc;
1556			vi->first_intr = -1;
1557			vi->qsize_rxq = t4_qsize_rxq;
1558			vi->qsize_txq = t4_qsize_txq;
1559
1560			vi->first_rxq = rqidx;
1561			vi->first_txq = tqidx;
1562			vi->tmr_idx = t4_tmr_idx;
1563			vi->pktc_idx = t4_pktc_idx;
1564			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1565			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1566
1567			rqidx += vi->nrxq;
1568			tqidx += vi->ntxq;
1569
1570			if (j == 0 && vi->ntxq > 1)
1571				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1572			else
1573				vi->rsrv_noflowq = 0;
1574
1575#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1576			vi->first_ofld_txq = ofld_tqidx;
1577			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1578			ofld_tqidx += vi->nofldtxq;
1579#endif
1580#ifdef TCP_OFFLOAD
1581			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1582			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1583			vi->first_ofld_rxq = ofld_rqidx;
1584			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1585
1586			ofld_rqidx += vi->nofldrxq;
1587#endif
1588#ifdef DEV_NETMAP
1589			vi->first_nm_rxq = nm_rqidx;
1590			vi->first_nm_txq = nm_tqidx;
1591			if (j == 0) {
1592				vi->nnmrxq = iaq.nnmrxq;
1593				vi->nnmtxq = iaq.nnmtxq;
1594			} else {
1595				vi->nnmrxq = iaq.nnmrxq_vi;
1596				vi->nnmtxq = iaq.nnmtxq_vi;
1597			}
1598			nm_rqidx += vi->nnmrxq;
1599			nm_tqidx += vi->nnmtxq;
1600#endif
1601		}
1602	}
1603
1604	rc = t4_setup_intr_handlers(sc);
1605	if (rc != 0) {
1606		device_printf(dev,
1607		    "failed to setup interrupt handlers: %d\n", rc);
1608		goto done;
1609	}
1610
1611	rc = bus_generic_probe(dev);
1612	if (rc != 0) {
1613		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1614		goto done;
1615	}
1616
1617	/*
1618	 * Ensure thread-safe mailbox access (in debug builds).
1619	 *
1620	 * So far this was the only thread accessing the mailbox but various
1621	 * ifnets and sysctls are about to be created and their handlers/ioctls
1622	 * will access the mailbox from different threads.
1623	 */
1624	sc->flags |= CHK_MBOX_ACCESS;
1625
1626	rc = bus_generic_attach(dev);
1627	if (rc != 0) {
1628		device_printf(dev,
1629		    "failed to attach all child ports: %d\n", rc);
1630		goto done;
1631	}
1632	t4_calibration_start(sc);
1633
1634	device_printf(dev,
1635	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1636	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1637	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1638	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1639	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1640
1641	t4_set_desc(sc);
1642
1643	notify_siblings(dev, 0);
1644
1645done:
1646	if (rc != 0 && sc->cdev) {
1647		/* cdev was created and so cxgbetool works; recover that way. */
1648		device_printf(dev,
1649		    "error during attach, adapter is now in recovery mode.\n");
1650		rc = 0;
1651	}
1652
1653	if (rc != 0)
1654		t4_detach_common(dev);
1655	else
1656		t4_sysctls(sc);
1657
1658	return (rc);
1659}
1660
1661static int
1662t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1663{
1664	struct adapter *sc;
1665	struct port_info *pi;
1666	int i;
1667
1668	sc = device_get_softc(bus);
1669	for_each_port(sc, i) {
1670		pi = sc->port[i];
1671		if (pi != NULL && pi->dev == dev) {
1672			sbuf_printf(sb, "port=%d", pi->port_id);
1673			break;
1674		}
1675	}
1676	return (0);
1677}
1678
1679static int
1680t4_ready(device_t dev)
1681{
1682	struct adapter *sc;
1683
1684	sc = device_get_softc(dev);
1685	if (sc->flags & FW_OK)
1686		return (0);
1687	return (ENXIO);
1688}
1689
1690static int
1691t4_read_port_device(device_t dev, int port, device_t *child)
1692{
1693	struct adapter *sc;
1694	struct port_info *pi;
1695
1696	sc = device_get_softc(dev);
1697	if (port < 0 || port >= MAX_NPORTS)
1698		return (EINVAL);
1699	pi = sc->port[port];
1700	if (pi == NULL || pi->dev == NULL)
1701		return (ENXIO);
1702	*child = pi->dev;
1703	return (0);
1704}
1705
1706static int
1707notify_siblings(device_t dev, int detaching)
1708{
1709	device_t sibling;
1710	int error, i;
1711
1712	error = 0;
1713	for (i = 0; i < PCI_FUNCMAX; i++) {
1714		if (i == pci_get_function(dev))
1715			continue;
1716		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1717		    pci_get_slot(dev), i);
1718		if (sibling == NULL || !device_is_attached(sibling))
1719			continue;
1720		if (detaching)
1721			error = T4_DETACH_CHILD(sibling);
1722		else
1723			(void)T4_ATTACH_CHILD(sibling);
1724		if (error)
1725			break;
1726	}
1727	return (error);
1728}
1729
1730/*
1731 * Idempotent
1732 */
1733static int
1734t4_detach(device_t dev)
1735{
1736	int rc;
1737
1738	rc = notify_siblings(dev, 1);
1739	if (rc) {
1740		device_printf(dev,
1741		    "failed to detach sibling devices: %d\n", rc);
1742		return (rc);
1743	}
1744
1745	return (t4_detach_common(dev));
1746}
1747
1748int
1749t4_detach_common(device_t dev)
1750{
1751	struct adapter *sc;
1752	struct port_info *pi;
1753	int i, rc;
1754
1755	sc = device_get_softc(dev);
1756
1757#ifdef TCP_OFFLOAD
1758	rc = t4_deactivate_all_uld(sc);
1759	if (rc) {
1760		device_printf(dev,
1761		    "failed to detach upper layer drivers: %d\n", rc);
1762		return (rc);
1763	}
1764#endif
1765
1766	if (sc->cdev) {
1767		destroy_dev(sc->cdev);
1768		sc->cdev = NULL;
1769	}
1770
1771	sx_xlock(&t4_list_lock);
1772	SLIST_REMOVE(&t4_list, sc, adapter, link);
1773	sx_xunlock(&t4_list_lock);
1774
1775	sc->flags &= ~CHK_MBOX_ACCESS;
1776	if (sc->flags & FULL_INIT_DONE) {
1777		if (!(sc->flags & IS_VF))
1778			t4_intr_disable(sc);
1779	}
1780
1781	if (device_is_attached(dev)) {
1782		rc = bus_generic_detach(dev);
1783		if (rc) {
1784			device_printf(dev,
1785			    "failed to detach child devices: %d\n", rc);
1786			return (rc);
1787		}
1788	}
1789
1790	for (i = 0; i < sc->intr_count; i++)
1791		t4_free_irq(sc, &sc->irq[i]);
1792
1793	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1794		t4_free_tx_sched(sc);
1795
1796	for (i = 0; i < MAX_NPORTS; i++) {
1797		pi = sc->port[i];
1798		if (pi) {
1799			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1800			if (pi->dev)
1801				device_delete_child(dev, pi->dev);
1802
1803			mtx_destroy(&pi->pi_lock);
1804			free(pi->vi, M_CXGBE);
1805			free(pi, M_CXGBE);
1806		}
1807	}
1808	callout_stop(&sc->cal_callout);
1809	callout_drain(&sc->cal_callout);
1810	device_delete_children(dev);
1811	sysctl_ctx_free(&sc->ctx);
1812	adapter_full_uninit(sc);
1813
1814	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1815		t4_fw_bye(sc, sc->mbox);
1816
1817	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1818		pci_release_msi(dev);
1819
1820	if (sc->regs_res)
1821		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1822		    sc->regs_res);
1823
1824	if (sc->udbs_res)
1825		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1826		    sc->udbs_res);
1827
1828	if (sc->msix_res)
1829		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1830		    sc->msix_res);
1831
1832	if (sc->l2t)
1833		t4_free_l2t(sc->l2t);
1834	if (sc->smt)
1835		t4_free_smt(sc->smt);
1836	t4_free_atid_table(sc);
1837#ifdef RATELIMIT
1838	t4_free_etid_table(sc);
1839#endif
1840	if (sc->key_map)
1841		vmem_destroy(sc->key_map);
1842#ifdef INET6
1843	t4_destroy_clip_table(sc);
1844#endif
1845
1846#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1847	free(sc->sge.ofld_txq, M_CXGBE);
1848#endif
1849#ifdef TCP_OFFLOAD
1850	free(sc->sge.ofld_rxq, M_CXGBE);
1851#endif
1852#ifdef DEV_NETMAP
1853	free(sc->sge.nm_rxq, M_CXGBE);
1854	free(sc->sge.nm_txq, M_CXGBE);
1855#endif
1856	free(sc->irq, M_CXGBE);
1857	free(sc->sge.rxq, M_CXGBE);
1858	free(sc->sge.txq, M_CXGBE);
1859	free(sc->sge.ctrlq, M_CXGBE);
1860	free(sc->sge.iqmap, M_CXGBE);
1861	free(sc->sge.eqmap, M_CXGBE);
1862	free(sc->tids.ftid_tab, M_CXGBE);
1863	free(sc->tids.hpftid_tab, M_CXGBE);
1864	free_hftid_hash(&sc->tids);
1865	free(sc->tids.tid_tab, M_CXGBE);
1866	t4_destroy_dma_tag(sc);
1867
1868	callout_drain(&sc->ktls_tick);
1869	callout_drain(&sc->sfl_callout);
1870	if (mtx_initialized(&sc->tids.ftid_lock)) {
1871		mtx_destroy(&sc->tids.ftid_lock);
1872		cv_destroy(&sc->tids.ftid_cv);
1873	}
1874	if (mtx_initialized(&sc->tids.atid_lock))
1875		mtx_destroy(&sc->tids.atid_lock);
1876	if (mtx_initialized(&sc->ifp_lock))
1877		mtx_destroy(&sc->ifp_lock);
1878
1879	if (rw_initialized(&sc->policy_lock)) {
1880		rw_destroy(&sc->policy_lock);
1881#ifdef TCP_OFFLOAD
1882		if (sc->policy != NULL)
1883			free_offload_policy(sc->policy);
1884#endif
1885	}
1886
1887	for (i = 0; i < NUM_MEMWIN; i++) {
1888		struct memwin *mw = &sc->memwin[i];
1889
1890		if (rw_initialized(&mw->mw_lock))
1891			rw_destroy(&mw->mw_lock);
1892	}
1893
1894	mtx_destroy(&sc->sfl_lock);
1895	mtx_destroy(&sc->reg_lock);
1896	mtx_destroy(&sc->sc_lock);
1897
1898	bzero(sc, sizeof(*sc));
1899
1900	return (0);
1901}
1902
1903static inline bool
1904ok_to_reset(struct adapter *sc)
1905{
1906	struct tid_info *t = &sc->tids;
1907	struct port_info *pi;
1908	struct vi_info *vi;
1909	int i, j;
1910	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1911
1912	if (is_t6(sc))
1913		caps |= IFCAP_TXTLS;
1914
1915	ASSERT_SYNCHRONIZED_OP(sc);
1916	MPASS(!(sc->flags & IS_VF));
1917
1918	for_each_port(sc, i) {
1919		pi = sc->port[i];
1920		for_each_vi(pi, j, vi) {
1921			if (if_getcapenable(vi->ifp) & caps)
1922				return (false);
1923		}
1924	}
1925
1926	if (atomic_load_int(&t->tids_in_use) > 0)
1927		return (false);
1928	if (atomic_load_int(&t->stids_in_use) > 0)
1929		return (false);
1930	if (atomic_load_int(&t->atids_in_use) > 0)
1931		return (false);
1932	if (atomic_load_int(&t->ftids_in_use) > 0)
1933		return (false);
1934	if (atomic_load_int(&t->hpftids_in_use) > 0)
1935		return (false);
1936	if (atomic_load_int(&t->etids_in_use) > 0)
1937		return (false);
1938
1939	return (true);
1940}
1941
1942static inline int
1943stop_adapter(struct adapter *sc)
1944{
1945	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1946		return (1);		/* Already stopped. */
1947	return (t4_shutdown_adapter(sc));
1948}
1949
1950static int
1951t4_suspend(device_t dev)
1952{
1953	struct adapter *sc = device_get_softc(dev);
1954	struct port_info *pi;
1955	struct vi_info *vi;
1956	if_t ifp;
1957	struct sge_rxq *rxq;
1958	struct sge_txq *txq;
1959	struct sge_wrq *wrq;
1960#ifdef TCP_OFFLOAD
1961	struct sge_ofld_rxq *ofld_rxq;
1962#endif
1963#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1964	struct sge_ofld_txq *ofld_txq;
1965#endif
1966	int rc, i, j, k;
1967
1968	CH_ALERT(sc, "suspend requested\n");
1969
1970	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1971	if (rc != 0)
1972		return (ENXIO);
1973
1974	/* XXX: Can the kernel call suspend repeatedly without resume? */
1975	MPASS(!hw_off_limits(sc));
1976
1977	if (!ok_to_reset(sc)) {
1978		/* XXX: should list what resource is preventing suspend. */
1979		CH_ERR(sc, "not safe to suspend.\n");
1980		rc = EBUSY;
1981		goto done;
1982	}
1983
1984	/* No more DMA or interrupts. */
1985	stop_adapter(sc);
1986
1987	/* Quiesce all activity. */
1988	for_each_port(sc, i) {
1989		pi = sc->port[i];
1990		pi->vxlan_tcam_entry = false;
1991
1992		PORT_LOCK(pi);
1993		if (pi->up_vis > 0) {
1994			/*
1995			 * t4_shutdown_adapter has already shut down all the
1996			 * PHYs but it also disables interrupts and DMA so there
1997			 * won't be a link interrupt.  So we update the state
1998			 * manually and inform the kernel.
1999			 */
2000			pi->link_cfg.link_ok = false;
2001			t4_os_link_changed(pi);
2002		}
2003		PORT_UNLOCK(pi);
2004
2005		for_each_vi(pi, j, vi) {
2006			vi->xact_addr_filt = -1;
2007			mtx_lock(&vi->tick_mtx);
2008			vi->flags |= VI_SKIP_STATS;
2009			mtx_unlock(&vi->tick_mtx);
2010			if (!(vi->flags & VI_INIT_DONE))
2011				continue;
2012
2013			ifp = vi->ifp;
2014			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2015				mtx_lock(&vi->tick_mtx);
2016				callout_stop(&vi->tick);
2017				mtx_unlock(&vi->tick_mtx);
2018				callout_drain(&vi->tick);
2019			}
2020
2021			/*
2022			 * Note that the HW is not available.
2023			 */
2024			for_each_txq(vi, k, txq) {
2025				TXQ_LOCK(txq);
2026				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2027				TXQ_UNLOCK(txq);
2028			}
2029#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2030			for_each_ofld_txq(vi, k, ofld_txq) {
2031				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2032			}
2033#endif
2034			for_each_rxq(vi, k, rxq) {
2035				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2036			}
2037#if defined(TCP_OFFLOAD)
2038			for_each_ofld_rxq(vi, k, ofld_rxq) {
2039				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2040			}
2041#endif
2042
2043			quiesce_vi(vi);
2044		}
2045
2046		if (sc->flags & FULL_INIT_DONE) {
2047			/* Control queue */
2048			wrq = &sc->sge.ctrlq[i];
2049			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2050			quiesce_wrq(wrq);
2051		}
2052	}
2053	if (sc->flags & FULL_INIT_DONE) {
2054		/* Firmware event queue */
2055		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2056		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2057	}
2058
2059	/* Stop calibration */
2060	callout_stop(&sc->cal_callout);
2061	callout_drain(&sc->cal_callout);
2062
2063	/* Mark the adapter totally off limits. */
2064	mtx_lock(&sc->reg_lock);
2065	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2066	sc->flags &= ~(FW_OK | MASTER_PF);
2067	sc->reset_thread = NULL;
2068	mtx_unlock(&sc->reg_lock);
2069
2070	if (t4_clock_gate_on_suspend) {
2071		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2072		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2073		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2074	}
2075
2076	CH_ALERT(sc, "suspend completed.\n");
2077done:
2078	end_synchronized_op(sc, 0);
2079	return (rc);
2080}
2081
2082struct adapter_pre_reset_state {
2083	u_int flags;
2084	uint16_t nbmcaps;
2085	uint16_t linkcaps;
2086	uint16_t switchcaps;
2087	uint16_t niccaps;
2088	uint16_t toecaps;
2089	uint16_t rdmacaps;
2090	uint16_t cryptocaps;
2091	uint16_t iscsicaps;
2092	uint16_t fcoecaps;
2093
2094	u_int cfcsum;
2095	char cfg_file[32];
2096
2097	struct adapter_params params;
2098	struct t4_virt_res vres;
2099	struct tid_info tids;
2100	struct sge sge;
2101
2102	int rawf_base;
2103	int nrawf;
2104
2105};
2106
2107static void
2108save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2109{
2110
2111	ASSERT_SYNCHRONIZED_OP(sc);
2112
2113	o->flags = sc->flags;
2114
2115	o->nbmcaps =  sc->nbmcaps;
2116	o->linkcaps = sc->linkcaps;
2117	o->switchcaps = sc->switchcaps;
2118	o->niccaps = sc->niccaps;
2119	o->toecaps = sc->toecaps;
2120	o->rdmacaps = sc->rdmacaps;
2121	o->cryptocaps = sc->cryptocaps;
2122	o->iscsicaps = sc->iscsicaps;
2123	o->fcoecaps = sc->fcoecaps;
2124
2125	o->cfcsum = sc->cfcsum;
2126	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2127	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2128
2129	o->params = sc->params;
2130	o->vres = sc->vres;
2131	o->tids = sc->tids;
2132	o->sge = sc->sge;
2133
2134	o->rawf_base = sc->rawf_base;
2135	o->nrawf = sc->nrawf;
2136}
2137
2138static int
2139compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2140{
2141	int rc = 0;
2142
2143	ASSERT_SYNCHRONIZED_OP(sc);
2144
2145	/* Capabilities */
2146#define COMPARE_CAPS(c) do { \
2147	if (o->c##caps != sc->c##caps) { \
2148		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2149		    sc->c##caps); \
2150		rc = EINVAL; \
2151	} \
2152} while (0)
2153	COMPARE_CAPS(nbm);
2154	COMPARE_CAPS(link);
2155	COMPARE_CAPS(switch);
2156	COMPARE_CAPS(nic);
2157	COMPARE_CAPS(toe);
2158	COMPARE_CAPS(rdma);
2159	COMPARE_CAPS(crypto);
2160	COMPARE_CAPS(iscsi);
2161	COMPARE_CAPS(fcoe);
2162#undef COMPARE_CAPS
2163
2164	/* Firmware config file */
2165	if (o->cfcsum != sc->cfcsum) {
2166		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2167		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2168		rc = EINVAL;
2169	}
2170
2171#define COMPARE_PARAM(p, name) do { \
2172	if (o->p != sc->p) { \
2173		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2174		rc = EINVAL; \
2175	} \
2176} while (0)
2177	COMPARE_PARAM(sge.iq_start, iq_start);
2178	COMPARE_PARAM(sge.eq_start, eq_start);
2179	COMPARE_PARAM(tids.ftid_base, ftid_base);
2180	COMPARE_PARAM(tids.ftid_end, ftid_end);
2181	COMPARE_PARAM(tids.nftids, nftids);
2182	COMPARE_PARAM(vres.l2t.start, l2t_start);
2183	COMPARE_PARAM(vres.l2t.size, l2t_size);
2184	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2185	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2186	COMPARE_PARAM(tids.tid_base, tid_base);
2187	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2188	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2189	COMPARE_PARAM(tids.nhpftids, nhpftids);
2190	COMPARE_PARAM(rawf_base, rawf_base);
2191	COMPARE_PARAM(nrawf, nrawf);
2192	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2193	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2194	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2195	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2196	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2197	COMPARE_PARAM(tids.ntids, ntids);
2198	COMPARE_PARAM(tids.etid_base, etid_base);
2199	COMPARE_PARAM(tids.etid_end, etid_end);
2200	COMPARE_PARAM(tids.netids, netids);
2201	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2202	COMPARE_PARAM(params.ethoffload, ethoffload);
2203	COMPARE_PARAM(tids.natids, natids);
2204	COMPARE_PARAM(tids.stid_base, stid_base);
2205	COMPARE_PARAM(vres.ddp.start, ddp_start);
2206	COMPARE_PARAM(vres.ddp.size, ddp_size);
2207	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2208	COMPARE_PARAM(vres.stag.start, stag_start);
2209	COMPARE_PARAM(vres.stag.size, stag_size);
2210	COMPARE_PARAM(vres.rq.start, rq_start);
2211	COMPARE_PARAM(vres.rq.size, rq_size);
2212	COMPARE_PARAM(vres.pbl.start, pbl_start);
2213	COMPARE_PARAM(vres.pbl.size, pbl_size);
2214	COMPARE_PARAM(vres.qp.start, qp_start);
2215	COMPARE_PARAM(vres.qp.size, qp_size);
2216	COMPARE_PARAM(vres.cq.start, cq_start);
2217	COMPARE_PARAM(vres.cq.size, cq_size);
2218	COMPARE_PARAM(vres.ocq.start, ocq_start);
2219	COMPARE_PARAM(vres.ocq.size, ocq_size);
2220	COMPARE_PARAM(vres.srq.start, srq_start);
2221	COMPARE_PARAM(vres.srq.size, srq_size);
2222	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2223	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2224	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2225	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2226	COMPARE_PARAM(vres.key.start, key_start);
2227	COMPARE_PARAM(vres.key.size, key_size);
2228#undef COMPARE_PARAM
2229
2230	return (rc);
2231}
2232
2233static int
2234t4_resume(device_t dev)
2235{
2236	struct adapter *sc = device_get_softc(dev);
2237	struct adapter_pre_reset_state *old_state = NULL;
2238	struct port_info *pi;
2239	struct vi_info *vi;
2240	if_t ifp;
2241	struct sge_txq *txq;
2242	int rc, i, j, k;
2243
2244	CH_ALERT(sc, "resume requested.\n");
2245
2246	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2247	if (rc != 0)
2248		return (ENXIO);
2249	MPASS(hw_off_limits(sc));
2250	MPASS((sc->flags & FW_OK) == 0);
2251	MPASS((sc->flags & MASTER_PF) == 0);
2252	MPASS(sc->reset_thread == NULL);
2253	sc->reset_thread = curthread;
2254
2255	/* Register access is expected to work by the time we're here. */
2256	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2257		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2258		rc = ENXIO;
2259		goto done;
2260	}
2261
2262	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2263	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2264
2265	/* Restore memory window. */
2266	setup_memwin(sc);
2267
2268	/* Go no further if recovery mode has been requested. */
2269	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2270		CH_ALERT(sc, "recovery mode on resume.\n");
2271		rc = 0;
2272		mtx_lock(&sc->reg_lock);
2273		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2274		mtx_unlock(&sc->reg_lock);
2275		goto done;
2276	}
2277
2278	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2279	save_caps_and_params(sc, old_state);
2280
2281	/* Reestablish contact with firmware and become the primary PF. */
2282	rc = contact_firmware(sc);
2283	if (rc != 0)
2284		goto done; /* error message displayed already */
2285	MPASS(sc->flags & FW_OK);
2286
2287	if (sc->flags & MASTER_PF) {
2288		rc = partition_resources(sc);
2289		if (rc != 0)
2290			goto done; /* error message displayed already */
2291	}
2292
2293	rc = get_params__post_init(sc);
2294	if (rc != 0)
2295		goto done; /* error message displayed already */
2296
2297	rc = set_params__post_init(sc);
2298	if (rc != 0)
2299		goto done; /* error message displayed already */
2300
2301	rc = compare_caps_and_params(sc, old_state);
2302	if (rc != 0)
2303		goto done; /* error message displayed already */
2304
2305	for_each_port(sc, i) {
2306		pi = sc->port[i];
2307		MPASS(pi != NULL);
2308		MPASS(pi->vi != NULL);
2309		MPASS(pi->vi[0].dev == pi->dev);
2310
2311		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2312		if (rc != 0) {
2313			CH_ERR(sc,
2314			    "failed to re-initialize port %d: %d\n", i, rc);
2315			goto done;
2316		}
2317		MPASS(sc->chan_map[pi->tx_chan] == i);
2318
2319		PORT_LOCK(pi);
2320		fixup_link_config(pi);
2321		build_medialist(pi);
2322		PORT_UNLOCK(pi);
2323		for_each_vi(pi, j, vi) {
2324			if (IS_MAIN_VI(vi))
2325				continue;
2326			rc = alloc_extra_vi(sc, pi, vi);
2327			if (rc != 0) {
2328				CH_ERR(vi,
2329				    "failed to re-allocate extra VI: %d\n", rc);
2330				goto done;
2331			}
2332		}
2333	}
2334
2335	/*
2336	 * Interrupts and queues are about to be enabled and other threads will
2337	 * want to access the hardware too.  It is safe to do so.  Note that
2338	 * this thread is still in the middle of a synchronized_op.
2339	 */
2340	mtx_lock(&sc->reg_lock);
2341	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2342	mtx_unlock(&sc->reg_lock);
2343
2344	if (sc->flags & FULL_INIT_DONE) {
2345		rc = adapter_full_init(sc);
2346		if (rc != 0) {
2347			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2348			goto done;
2349		}
2350
2351		if (sc->vxlan_refcount > 0)
2352			enable_vxlan_rx(sc);
2353
2354		for_each_port(sc, i) {
2355			pi = sc->port[i];
2356			for_each_vi(pi, j, vi) {
2357				mtx_lock(&vi->tick_mtx);
2358				vi->flags &= ~VI_SKIP_STATS;
2359				mtx_unlock(&vi->tick_mtx);
2360				if (!(vi->flags & VI_INIT_DONE))
2361					continue;
2362				rc = vi_full_init(vi);
2363				if (rc != 0) {
2364					CH_ERR(vi, "failed to re-initialize "
2365					    "interface: %d\n", rc);
2366					goto done;
2367				}
2368
2369				ifp = vi->ifp;
2370				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2371					continue;
2372				/*
2373				 * Note that we do not setup multicast addresses
2374				 * in the first pass.  This ensures that the
2375				 * unicast DMACs for all VIs on all ports get an
2376				 * MPS TCAM entry.
2377				 */
2378				rc = update_mac_settings(ifp, XGMAC_ALL &
2379				    ~XGMAC_MCADDRS);
2380				if (rc != 0) {
2381					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2382					goto done;
2383				}
2384				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2385				    true);
2386				if (rc != 0) {
2387					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2388					goto done;
2389				}
2390				for_each_txq(vi, k, txq) {
2391					TXQ_LOCK(txq);
2392					txq->eq.flags |= EQ_ENABLED;
2393					TXQ_UNLOCK(txq);
2394				}
2395				mtx_lock(&vi->tick_mtx);
2396				callout_schedule(&vi->tick, hz);
2397				mtx_unlock(&vi->tick_mtx);
2398			}
2399			PORT_LOCK(pi);
2400			if (pi->up_vis > 0) {
2401				t4_update_port_info(pi);
2402				fixup_link_config(pi);
2403				build_medialist(pi);
2404				apply_link_config(pi);
2405				if (pi->link_cfg.link_ok)
2406					t4_os_link_changed(pi);
2407			}
2408			PORT_UNLOCK(pi);
2409		}
2410
2411		/* Now reprogram the L2 multicast addresses. */
2412		for_each_port(sc, i) {
2413			pi = sc->port[i];
2414			for_each_vi(pi, j, vi) {
2415				if (!(vi->flags & VI_INIT_DONE))
2416					continue;
2417				ifp = vi->ifp;
2418				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2419					continue;
2420				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2421				if (rc != 0) {
2422					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2423					rc = 0;	/* carry on */
2424				}
2425			}
2426		}
2427	}
2428
2429	/* Reset all calibration */
2430	t4_calibration_start(sc);
2431
2432done:
2433	if (rc == 0) {
2434		sc->incarnation++;
2435		CH_ALERT(sc, "resume completed.\n");
2436	}
2437	end_synchronized_op(sc, 0);
2438	free(old_state, M_CXGBE);
2439	return (rc);
2440}
2441
2442static int
2443t4_reset_prepare(device_t dev, device_t child)
2444{
2445	struct adapter *sc = device_get_softc(dev);
2446
2447	CH_ALERT(sc, "reset_prepare.\n");
2448	return (0);
2449}
2450
2451static int
2452t4_reset_post(device_t dev, device_t child)
2453{
2454	struct adapter *sc = device_get_softc(dev);
2455
2456	CH_ALERT(sc, "reset_post.\n");
2457	return (0);
2458}
2459
2460static int
2461reset_adapter(struct adapter *sc)
2462{
2463	int rc, oldinc, error_flags;
2464
2465	CH_ALERT(sc, "reset requested.\n");
2466
2467	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2468	if (rc != 0)
2469		return (EBUSY);
2470
2471	if (hw_off_limits(sc)) {
2472		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2473		rc = ENXIO;
2474		goto done;
2475	}
2476
2477	if (!ok_to_reset(sc)) {
2478		/* XXX: should list what resource is preventing reset. */
2479		CH_ERR(sc, "not safe to reset.\n");
2480		rc = EBUSY;
2481		goto done;
2482	}
2483
2484done:
2485	oldinc = sc->incarnation;
2486	end_synchronized_op(sc, 0);
2487	if (rc != 0)
2488		return (rc);	/* Error logged already. */
2489
2490	atomic_add_int(&sc->num_resets, 1);
2491	mtx_lock(&Giant);
2492	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2493	mtx_unlock(&Giant);
2494	if (rc != 0)
2495		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2496	else {
2497		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2498		if (rc != 0)
2499			return (EBUSY);
2500		error_flags = atomic_load_int(&sc->error_flags);
2501		if (sc->incarnation > oldinc && error_flags == 0) {
2502			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2503		} else {
2504			CH_ERR(sc, "adapter did not reset properly, flags "
2505			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2506			    error_flags);
2507			rc = ENXIO;
2508		}
2509		end_synchronized_op(sc, 0);
2510	}
2511
2512	return (rc);
2513}
2514
2515static void
2516reset_adapter_task(void *arg, int pending)
2517{
2518	/* XXX: t4_async_event here? */
2519	reset_adapter(arg);
2520}
2521
2522static int
2523cxgbe_probe(device_t dev)
2524{
2525	char buf[128];
2526	struct port_info *pi = device_get_softc(dev);
2527
2528	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2529	device_set_desc_copy(dev, buf);
2530
2531	return (BUS_PROBE_DEFAULT);
2532}
2533
2534#define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2535    IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2536    IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2537    IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2538#define T4_CAP_ENABLE (T4_CAP)
2539
2540static int
2541cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2542{
2543	if_t ifp;
2544	struct sbuf *sb;
2545	struct sysctl_ctx_list *ctx = &vi->ctx;
2546	struct sysctl_oid_list *children;
2547	struct pfil_head_args pa;
2548	struct adapter *sc = vi->adapter;
2549
2550	sysctl_ctx_init(ctx);
2551	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2552	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2553	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2554	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2555	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2556#ifdef DEV_NETMAP
2557	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2558	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2559	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2560	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2561#endif
2562#ifdef TCP_OFFLOAD
2563	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2564	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2565#endif
2566#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2567	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2568	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2569#endif
2570
2571	vi->xact_addr_filt = -1;
2572	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2573	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2574	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2575		vi->flags |= TX_USES_VM_WR;
2576
2577	/* Allocate an ifnet and set it up */
2578	ifp = if_alloc_dev(IFT_ETHER, dev);
2579	if (ifp == NULL) {
2580		device_printf(dev, "Cannot allocate ifnet\n");
2581		return (ENOMEM);
2582	}
2583	vi->ifp = ifp;
2584	if_setsoftc(ifp, vi);
2585
2586	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2587	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2588
2589	if_setinitfn(ifp, cxgbe_init);
2590	if_setioctlfn(ifp, cxgbe_ioctl);
2591	if_settransmitfn(ifp, cxgbe_transmit);
2592	if_setqflushfn(ifp, cxgbe_qflush);
2593	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2594		if_setgetcounterfn(ifp, vi_get_counter);
2595	else
2596		if_setgetcounterfn(ifp, cxgbe_get_counter);
2597#if defined(KERN_TLS) || defined(RATELIMIT)
2598	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2599#endif
2600#ifdef RATELIMIT
2601	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2602#endif
2603
2604	if_setcapabilities(ifp, T4_CAP);
2605	if_setcapenable(ifp, T4_CAP_ENABLE);
2606	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2607	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2608	if (chip_id(sc) >= CHELSIO_T6) {
2609		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2610		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2611		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2612		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2613		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2614	}
2615
2616#ifdef TCP_OFFLOAD
2617	if (vi->nofldrxq != 0)
2618		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2619#endif
2620#ifdef RATELIMIT
2621	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2622		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2623		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2624	}
2625#endif
2626
2627	if_sethwtsomax(ifp, IP_MAXPACKET);
2628	if (vi->flags & TX_USES_VM_WR)
2629		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2630	else
2631		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2632#ifdef RATELIMIT
2633	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2634		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2635#endif
2636	if_sethwtsomaxsegsize(ifp, 65536);
2637#ifdef KERN_TLS
2638	if (is_ktls(sc)) {
2639		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2640		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2641			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2642	}
2643#endif
2644
2645	ether_ifattach(ifp, vi->hw_addr);
2646#ifdef DEV_NETMAP
2647	if (vi->nnmrxq != 0)
2648		cxgbe_nm_attach(vi);
2649#endif
2650	sb = sbuf_new_auto();
2651	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2652#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2653	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2654	case IFCAP_TOE:
2655		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2656		break;
2657	case IFCAP_TOE | IFCAP_TXRTLMT:
2658		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2659		break;
2660	case IFCAP_TXRTLMT:
2661		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2662		break;
2663	}
2664#endif
2665#ifdef TCP_OFFLOAD
2666	if (if_getcapabilities(ifp) & IFCAP_TOE)
2667		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2668#endif
2669#ifdef DEV_NETMAP
2670	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2671		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2672		    vi->nnmtxq, vi->nnmrxq);
2673#endif
2674	sbuf_finish(sb);
2675	device_printf(dev, "%s\n", sbuf_data(sb));
2676	sbuf_delete(sb);
2677
2678	vi_sysctls(vi);
2679
2680	pa.pa_version = PFIL_VERSION;
2681	pa.pa_flags = PFIL_IN;
2682	pa.pa_type = PFIL_TYPE_ETHERNET;
2683	pa.pa_headname = if_name(ifp);
2684	vi->pfil = pfil_head_register(&pa);
2685
2686	return (0);
2687}
2688
2689static int
2690cxgbe_attach(device_t dev)
2691{
2692	struct port_info *pi = device_get_softc(dev);
2693	struct adapter *sc = pi->adapter;
2694	struct vi_info *vi;
2695	int i, rc;
2696
2697	sysctl_ctx_init(&pi->ctx);
2698
2699	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2700	if (rc)
2701		return (rc);
2702
2703	for_each_vi(pi, i, vi) {
2704		if (i == 0)
2705			continue;
2706		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2707		if (vi->dev == NULL) {
2708			device_printf(dev, "failed to add VI %d\n", i);
2709			continue;
2710		}
2711		device_set_softc(vi->dev, vi);
2712	}
2713
2714	cxgbe_sysctls(pi);
2715
2716	bus_generic_attach(dev);
2717
2718	return (0);
2719}
2720
2721static void
2722cxgbe_vi_detach(struct vi_info *vi)
2723{
2724	if_t ifp = vi->ifp;
2725
2726	if (vi->pfil != NULL) {
2727		pfil_head_unregister(vi->pfil);
2728		vi->pfil = NULL;
2729	}
2730
2731	ether_ifdetach(ifp);
2732
2733	/* Let detach proceed even if these fail. */
2734#ifdef DEV_NETMAP
2735	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2736		cxgbe_nm_detach(vi);
2737#endif
2738	cxgbe_uninit_synchronized(vi);
2739	callout_drain(&vi->tick);
2740	mtx_destroy(&vi->tick_mtx);
2741	sysctl_ctx_free(&vi->ctx);
2742	vi_full_uninit(vi);
2743
2744	if_free(vi->ifp);
2745	vi->ifp = NULL;
2746}
2747
2748static int
2749cxgbe_detach(device_t dev)
2750{
2751	struct port_info *pi = device_get_softc(dev);
2752	struct adapter *sc = pi->adapter;
2753	int rc;
2754
2755	/* Detach the extra VIs first. */
2756	rc = bus_generic_detach(dev);
2757	if (rc)
2758		return (rc);
2759	device_delete_children(dev);
2760
2761	sysctl_ctx_free(&pi->ctx);
2762	begin_vi_detach(sc, &pi->vi[0]);
2763	if (pi->flags & HAS_TRACEQ) {
2764		sc->traceq = -1;	/* cloner should not create ifnet */
2765		t4_tracer_port_detach(sc);
2766	}
2767	cxgbe_vi_detach(&pi->vi[0]);
2768	ifmedia_removeall(&pi->media);
2769	end_vi_detach(sc, &pi->vi[0]);
2770
2771	return (0);
2772}
2773
2774static void
2775cxgbe_init(void *arg)
2776{
2777	struct vi_info *vi = arg;
2778	struct adapter *sc = vi->adapter;
2779
2780	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2781		return;
2782	cxgbe_init_synchronized(vi);
2783	end_synchronized_op(sc, 0);
2784}
2785
2786static int
2787cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2788{
2789	int rc = 0, mtu, flags;
2790	struct vi_info *vi = if_getsoftc(ifp);
2791	struct port_info *pi = vi->pi;
2792	struct adapter *sc = pi->adapter;
2793	struct ifreq *ifr = (struct ifreq *)data;
2794	uint32_t mask;
2795
2796	switch (cmd) {
2797	case SIOCSIFMTU:
2798		mtu = ifr->ifr_mtu;
2799		if (mtu < ETHERMIN || mtu > MAX_MTU)
2800			return (EINVAL);
2801
2802		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2803		if (rc)
2804			return (rc);
2805		if_setmtu(ifp, mtu);
2806		if (vi->flags & VI_INIT_DONE) {
2807			t4_update_fl_bufsize(ifp);
2808			if (!hw_off_limits(sc) &&
2809			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2810				rc = update_mac_settings(ifp, XGMAC_MTU);
2811		}
2812		end_synchronized_op(sc, 0);
2813		break;
2814
2815	case SIOCSIFFLAGS:
2816		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2817		if (rc)
2818			return (rc);
2819
2820		if (hw_off_limits(sc)) {
2821			rc = ENXIO;
2822			goto fail;
2823		}
2824
2825		if (if_getflags(ifp) & IFF_UP) {
2826			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2827				flags = vi->if_flags;
2828				if ((if_getflags(ifp) ^ flags) &
2829				    (IFF_PROMISC | IFF_ALLMULTI)) {
2830					rc = update_mac_settings(ifp,
2831					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2832				}
2833			} else {
2834				rc = cxgbe_init_synchronized(vi);
2835			}
2836			vi->if_flags = if_getflags(ifp);
2837		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2838			rc = cxgbe_uninit_synchronized(vi);
2839		}
2840		end_synchronized_op(sc, 0);
2841		break;
2842
2843	case SIOCADDMULTI:
2844	case SIOCDELMULTI:
2845		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2846		if (rc)
2847			return (rc);
2848		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2849			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2850		end_synchronized_op(sc, 0);
2851		break;
2852
2853	case SIOCSIFCAP:
2854		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2855		if (rc)
2856			return (rc);
2857
2858		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2859		if (mask & IFCAP_TXCSUM) {
2860			if_togglecapenable(ifp, IFCAP_TXCSUM);
2861			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2862
2863			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2864			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2865				mask &= ~IFCAP_TSO4;
2866				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2867				if_printf(ifp,
2868				    "tso4 disabled due to -txcsum.\n");
2869			}
2870		}
2871		if (mask & IFCAP_TXCSUM_IPV6) {
2872			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2873			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2874
2875			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2876			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2877				mask &= ~IFCAP_TSO6;
2878				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2879				if_printf(ifp,
2880				    "tso6 disabled due to -txcsum6.\n");
2881			}
2882		}
2883		if (mask & IFCAP_RXCSUM)
2884			if_togglecapenable(ifp, IFCAP_RXCSUM);
2885		if (mask & IFCAP_RXCSUM_IPV6)
2886			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2887
2888		/*
2889		 * Note that we leave CSUM_TSO alone (it is always set).  The
2890		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2891		 * sending a TSO request our way, so it's sufficient to toggle
2892		 * IFCAP_TSOx only.
2893		 */
2894		if (mask & IFCAP_TSO4) {
2895			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2896			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2897				if_printf(ifp, "enable txcsum first.\n");
2898				rc = EAGAIN;
2899				goto fail;
2900			}
2901			if_togglecapenable(ifp, IFCAP_TSO4);
2902		}
2903		if (mask & IFCAP_TSO6) {
2904			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2905			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2906				if_printf(ifp, "enable txcsum6 first.\n");
2907				rc = EAGAIN;
2908				goto fail;
2909			}
2910			if_togglecapenable(ifp, IFCAP_TSO6);
2911		}
2912		if (mask & IFCAP_LRO) {
2913#if defined(INET) || defined(INET6)
2914			int i;
2915			struct sge_rxq *rxq;
2916
2917			if_togglecapenable(ifp, IFCAP_LRO);
2918			for_each_rxq(vi, i, rxq) {
2919				if (if_getcapenable(ifp) & IFCAP_LRO)
2920					rxq->iq.flags |= IQ_LRO_ENABLED;
2921				else
2922					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2923			}
2924#endif
2925		}
2926#ifdef TCP_OFFLOAD
2927		if (mask & IFCAP_TOE) {
2928			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2929
2930			rc = toe_capability(vi, enable);
2931			if (rc != 0)
2932				goto fail;
2933
2934			if_togglecapenable(ifp, mask);
2935		}
2936#endif
2937		if (mask & IFCAP_VLAN_HWTAGGING) {
2938			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2939			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2940				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2941		}
2942		if (mask & IFCAP_VLAN_MTU) {
2943			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2944
2945			/* Need to find out how to disable auto-mtu-inflation */
2946		}
2947		if (mask & IFCAP_VLAN_HWTSO)
2948			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2949		if (mask & IFCAP_VLAN_HWCSUM)
2950			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2951#ifdef RATELIMIT
2952		if (mask & IFCAP_TXRTLMT)
2953			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2954#endif
2955		if (mask & IFCAP_HWRXTSTMP) {
2956			int i;
2957			struct sge_rxq *rxq;
2958
2959			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2960			for_each_rxq(vi, i, rxq) {
2961				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2962					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2963				else
2964					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2965			}
2966		}
2967		if (mask & IFCAP_MEXTPG)
2968			if_togglecapenable(ifp, IFCAP_MEXTPG);
2969
2970#ifdef KERN_TLS
2971		if (mask & IFCAP_TXTLS) {
2972			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2973
2974			rc = ktls_capability(sc, enable);
2975			if (rc != 0)
2976				goto fail;
2977
2978			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
2979		}
2980#endif
2981		if (mask & IFCAP_VXLAN_HWCSUM) {
2982			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
2983			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
2984			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2985			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
2986		}
2987		if (mask & IFCAP_VXLAN_HWTSO) {
2988			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
2989			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
2990			    CSUM_INNER_IP_TSO);
2991		}
2992
2993#ifdef VLAN_CAPABILITIES
2994		VLAN_CAPABILITIES(ifp);
2995#endif
2996fail:
2997		end_synchronized_op(sc, 0);
2998		break;
2999
3000	case SIOCSIFMEDIA:
3001	case SIOCGIFMEDIA:
3002	case SIOCGIFXMEDIA:
3003		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3004		break;
3005
3006	case SIOCGI2C: {
3007		struct ifi2creq i2c;
3008
3009		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3010		if (rc != 0)
3011			break;
3012		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3013			rc = EPERM;
3014			break;
3015		}
3016		if (i2c.len > sizeof(i2c.data)) {
3017			rc = EINVAL;
3018			break;
3019		}
3020		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3021		if (rc)
3022			return (rc);
3023		if (hw_off_limits(sc))
3024			rc = ENXIO;
3025		else
3026			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3027			    i2c.offset, i2c.len, &i2c.data[0]);
3028		end_synchronized_op(sc, 0);
3029		if (rc == 0)
3030			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3031		break;
3032	}
3033
3034	default:
3035		rc = ether_ioctl(ifp, cmd, data);
3036	}
3037
3038	return (rc);
3039}
3040
3041static int
3042cxgbe_transmit(if_t ifp, struct mbuf *m)
3043{
3044	struct vi_info *vi = if_getsoftc(ifp);
3045	struct port_info *pi = vi->pi;
3046	struct adapter *sc;
3047	struct sge_txq *txq;
3048	void *items[1];
3049	int rc;
3050
3051	M_ASSERTPKTHDR(m);
3052	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3053#if defined(KERN_TLS) || defined(RATELIMIT)
3054	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3055		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3056#endif
3057
3058	if (__predict_false(pi->link_cfg.link_ok == false)) {
3059		m_freem(m);
3060		return (ENETDOWN);
3061	}
3062
3063	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3064	if (__predict_false(rc != 0)) {
3065		if (__predict_true(rc == EINPROGRESS)) {
3066			/* queued by parse_pkt */
3067			MPASS(m != NULL);
3068			return (0);
3069		}
3070
3071		MPASS(m == NULL);			/* was freed already */
3072		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3073		return (rc);
3074	}
3075
3076	/* Select a txq. */
3077	sc = vi->adapter;
3078	txq = &sc->sge.txq[vi->first_txq];
3079	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3080		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3081		    vi->rsrv_noflowq);
3082
3083	items[0] = m;
3084	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3085	if (__predict_false(rc != 0))
3086		m_freem(m);
3087
3088	return (rc);
3089}
3090
3091static void
3092cxgbe_qflush(if_t ifp)
3093{
3094	struct vi_info *vi = if_getsoftc(ifp);
3095	struct sge_txq *txq;
3096	int i;
3097
3098	/* queues do not exist if !VI_INIT_DONE. */
3099	if (vi->flags & VI_INIT_DONE) {
3100		for_each_txq(vi, i, txq) {
3101			TXQ_LOCK(txq);
3102			txq->eq.flags |= EQ_QFLUSH;
3103			TXQ_UNLOCK(txq);
3104			while (!mp_ring_is_idle(txq->r)) {
3105				mp_ring_check_drainage(txq->r, 4096);
3106				pause("qflush", 1);
3107			}
3108			TXQ_LOCK(txq);
3109			txq->eq.flags &= ~EQ_QFLUSH;
3110			TXQ_UNLOCK(txq);
3111		}
3112	}
3113	if_qflush(ifp);
3114}
3115
3116static uint64_t
3117vi_get_counter(if_t ifp, ift_counter c)
3118{
3119	struct vi_info *vi = if_getsoftc(ifp);
3120	struct fw_vi_stats_vf *s = &vi->stats;
3121
3122	mtx_lock(&vi->tick_mtx);
3123	vi_refresh_stats(vi);
3124	mtx_unlock(&vi->tick_mtx);
3125
3126	switch (c) {
3127	case IFCOUNTER_IPACKETS:
3128		return (s->rx_bcast_frames + s->rx_mcast_frames +
3129		    s->rx_ucast_frames);
3130	case IFCOUNTER_IERRORS:
3131		return (s->rx_err_frames);
3132	case IFCOUNTER_OPACKETS:
3133		return (s->tx_bcast_frames + s->tx_mcast_frames +
3134		    s->tx_ucast_frames + s->tx_offload_frames);
3135	case IFCOUNTER_OERRORS:
3136		return (s->tx_drop_frames);
3137	case IFCOUNTER_IBYTES:
3138		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3139		    s->rx_ucast_bytes);
3140	case IFCOUNTER_OBYTES:
3141		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3142		    s->tx_ucast_bytes + s->tx_offload_bytes);
3143	case IFCOUNTER_IMCASTS:
3144		return (s->rx_mcast_frames);
3145	case IFCOUNTER_OMCASTS:
3146		return (s->tx_mcast_frames);
3147	case IFCOUNTER_OQDROPS: {
3148		uint64_t drops;
3149
3150		drops = 0;
3151		if (vi->flags & VI_INIT_DONE) {
3152			int i;
3153			struct sge_txq *txq;
3154
3155			for_each_txq(vi, i, txq)
3156				drops += counter_u64_fetch(txq->r->dropped);
3157		}
3158
3159		return (drops);
3160
3161	}
3162
3163	default:
3164		return (if_get_counter_default(ifp, c));
3165	}
3166}
3167
3168static uint64_t
3169cxgbe_get_counter(if_t ifp, ift_counter c)
3170{
3171	struct vi_info *vi = if_getsoftc(ifp);
3172	struct port_info *pi = vi->pi;
3173	struct port_stats *s = &pi->stats;
3174
3175	mtx_lock(&vi->tick_mtx);
3176	cxgbe_refresh_stats(vi);
3177	mtx_unlock(&vi->tick_mtx);
3178
3179	switch (c) {
3180	case IFCOUNTER_IPACKETS:
3181		return (s->rx_frames);
3182
3183	case IFCOUNTER_IERRORS:
3184		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3185		    s->rx_fcs_err + s->rx_len_err);
3186
3187	case IFCOUNTER_OPACKETS:
3188		return (s->tx_frames);
3189
3190	case IFCOUNTER_OERRORS:
3191		return (s->tx_error_frames);
3192
3193	case IFCOUNTER_IBYTES:
3194		return (s->rx_octets);
3195
3196	case IFCOUNTER_OBYTES:
3197		return (s->tx_octets);
3198
3199	case IFCOUNTER_IMCASTS:
3200		return (s->rx_mcast_frames);
3201
3202	case IFCOUNTER_OMCASTS:
3203		return (s->tx_mcast_frames);
3204
3205	case IFCOUNTER_IQDROPS:
3206		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3207		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3208		    s->rx_trunc3 + pi->tnl_cong_drops);
3209
3210	case IFCOUNTER_OQDROPS: {
3211		uint64_t drops;
3212
3213		drops = s->tx_drop;
3214		if (vi->flags & VI_INIT_DONE) {
3215			int i;
3216			struct sge_txq *txq;
3217
3218			for_each_txq(vi, i, txq)
3219				drops += counter_u64_fetch(txq->r->dropped);
3220		}
3221
3222		return (drops);
3223
3224	}
3225
3226	default:
3227		return (if_get_counter_default(ifp, c));
3228	}
3229}
3230
3231#if defined(KERN_TLS) || defined(RATELIMIT)
3232static int
3233cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3234    struct m_snd_tag **pt)
3235{
3236	int error;
3237
3238	switch (params->hdr.type) {
3239#ifdef RATELIMIT
3240	case IF_SND_TAG_TYPE_RATE_LIMIT:
3241		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3242		break;
3243#endif
3244#ifdef KERN_TLS
3245	case IF_SND_TAG_TYPE_TLS:
3246	{
3247		struct vi_info *vi = if_getsoftc(ifp);
3248
3249		if (is_t6(vi->pi->adapter))
3250			error = t6_tls_tag_alloc(ifp, params, pt);
3251		else
3252			error = EOPNOTSUPP;
3253		break;
3254	}
3255#endif
3256	default:
3257		error = EOPNOTSUPP;
3258	}
3259	return (error);
3260}
3261#endif
3262
3263/*
3264 * The kernel picks a media from the list we had provided but we still validate
3265 * the requeste.
3266 */
3267int
3268cxgbe_media_change(if_t ifp)
3269{
3270	struct vi_info *vi = if_getsoftc(ifp);
3271	struct port_info *pi = vi->pi;
3272	struct ifmedia *ifm = &pi->media;
3273	struct link_config *lc = &pi->link_cfg;
3274	struct adapter *sc = pi->adapter;
3275	int rc;
3276
3277	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3278	if (rc != 0)
3279		return (rc);
3280	PORT_LOCK(pi);
3281	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3282		/* ifconfig .. media autoselect */
3283		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3284			rc = ENOTSUP; /* AN not supported by transceiver */
3285			goto done;
3286		}
3287		lc->requested_aneg = AUTONEG_ENABLE;
3288		lc->requested_speed = 0;
3289		lc->requested_fc |= PAUSE_AUTONEG;
3290	} else {
3291		lc->requested_aneg = AUTONEG_DISABLE;
3292		lc->requested_speed =
3293		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3294		lc->requested_fc = 0;
3295		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3296			lc->requested_fc |= PAUSE_RX;
3297		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3298			lc->requested_fc |= PAUSE_TX;
3299	}
3300	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3301		fixup_link_config(pi);
3302		rc = apply_link_config(pi);
3303	}
3304done:
3305	PORT_UNLOCK(pi);
3306	end_synchronized_op(sc, 0);
3307	return (rc);
3308}
3309
3310/*
3311 * Base media word (without ETHER, pause, link active, etc.) for the port at the
3312 * given speed.
3313 */
3314static int
3315port_mword(struct port_info *pi, uint32_t speed)
3316{
3317
3318	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3319	MPASS(powerof2(speed));
3320
3321	switch(pi->port_type) {
3322	case FW_PORT_TYPE_BT_SGMII:
3323	case FW_PORT_TYPE_BT_XFI:
3324	case FW_PORT_TYPE_BT_XAUI:
3325		/* BaseT */
3326		switch (speed) {
3327		case FW_PORT_CAP32_SPEED_100M:
3328			return (IFM_100_T);
3329		case FW_PORT_CAP32_SPEED_1G:
3330			return (IFM_1000_T);
3331		case FW_PORT_CAP32_SPEED_10G:
3332			return (IFM_10G_T);
3333		}
3334		break;
3335	case FW_PORT_TYPE_KX4:
3336		if (speed == FW_PORT_CAP32_SPEED_10G)
3337			return (IFM_10G_KX4);
3338		break;
3339	case FW_PORT_TYPE_CX4:
3340		if (speed == FW_PORT_CAP32_SPEED_10G)
3341			return (IFM_10G_CX4);
3342		break;
3343	case FW_PORT_TYPE_KX:
3344		if (speed == FW_PORT_CAP32_SPEED_1G)
3345			return (IFM_1000_KX);
3346		break;
3347	case FW_PORT_TYPE_KR:
3348	case FW_PORT_TYPE_BP_AP:
3349	case FW_PORT_TYPE_BP4_AP:
3350	case FW_PORT_TYPE_BP40_BA:
3351	case FW_PORT_TYPE_KR4_100G:
3352	case FW_PORT_TYPE_KR_SFP28:
3353	case FW_PORT_TYPE_KR_XLAUI:
3354		switch (speed) {
3355		case FW_PORT_CAP32_SPEED_1G:
3356			return (IFM_1000_KX);
3357		case FW_PORT_CAP32_SPEED_10G:
3358			return (IFM_10G_KR);
3359		case FW_PORT_CAP32_SPEED_25G:
3360			return (IFM_25G_KR);
3361		case FW_PORT_CAP32_SPEED_40G:
3362			return (IFM_40G_KR4);
3363		case FW_PORT_CAP32_SPEED_50G:
3364			return (IFM_50G_KR2);
3365		case FW_PORT_CAP32_SPEED_100G:
3366			return (IFM_100G_KR4);
3367		}
3368		break;
3369	case FW_PORT_TYPE_FIBER_XFI:
3370	case FW_PORT_TYPE_FIBER_XAUI:
3371	case FW_PORT_TYPE_SFP:
3372	case FW_PORT_TYPE_QSFP_10G:
3373	case FW_PORT_TYPE_QSA:
3374	case FW_PORT_TYPE_QSFP:
3375	case FW_PORT_TYPE_CR4_QSFP:
3376	case FW_PORT_TYPE_CR_QSFP:
3377	case FW_PORT_TYPE_CR2_QSFP:
3378	case FW_PORT_TYPE_SFP28:
3379		/* Pluggable transceiver */
3380		switch (pi->mod_type) {
3381		case FW_PORT_MOD_TYPE_LR:
3382			switch (speed) {
3383			case FW_PORT_CAP32_SPEED_1G:
3384				return (IFM_1000_LX);
3385			case FW_PORT_CAP32_SPEED_10G:
3386				return (IFM_10G_LR);
3387			case FW_PORT_CAP32_SPEED_25G:
3388				return (IFM_25G_LR);
3389			case FW_PORT_CAP32_SPEED_40G:
3390				return (IFM_40G_LR4);
3391			case FW_PORT_CAP32_SPEED_50G:
3392				return (IFM_50G_LR2);
3393			case FW_PORT_CAP32_SPEED_100G:
3394				return (IFM_100G_LR4);
3395			}
3396			break;
3397		case FW_PORT_MOD_TYPE_SR:
3398			switch (speed) {
3399			case FW_PORT_CAP32_SPEED_1G:
3400				return (IFM_1000_SX);
3401			case FW_PORT_CAP32_SPEED_10G:
3402				return (IFM_10G_SR);
3403			case FW_PORT_CAP32_SPEED_25G:
3404				return (IFM_25G_SR);
3405			case FW_PORT_CAP32_SPEED_40G:
3406				return (IFM_40G_SR4);
3407			case FW_PORT_CAP32_SPEED_50G:
3408				return (IFM_50G_SR2);
3409			case FW_PORT_CAP32_SPEED_100G:
3410				return (IFM_100G_SR4);
3411			}
3412			break;
3413		case FW_PORT_MOD_TYPE_ER:
3414			if (speed == FW_PORT_CAP32_SPEED_10G)
3415				return (IFM_10G_ER);
3416			break;
3417		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3418		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3419			switch (speed) {
3420			case FW_PORT_CAP32_SPEED_1G:
3421				return (IFM_1000_CX);
3422			case FW_PORT_CAP32_SPEED_10G:
3423				return (IFM_10G_TWINAX);
3424			case FW_PORT_CAP32_SPEED_25G:
3425				return (IFM_25G_CR);
3426			case FW_PORT_CAP32_SPEED_40G:
3427				return (IFM_40G_CR4);
3428			case FW_PORT_CAP32_SPEED_50G:
3429				return (IFM_50G_CR2);
3430			case FW_PORT_CAP32_SPEED_100G:
3431				return (IFM_100G_CR4);
3432			}
3433			break;
3434		case FW_PORT_MOD_TYPE_LRM:
3435			if (speed == FW_PORT_CAP32_SPEED_10G)
3436				return (IFM_10G_LRM);
3437			break;
3438		case FW_PORT_MOD_TYPE_NA:
3439			MPASS(0);	/* Not pluggable? */
3440			/* fall throough */
3441		case FW_PORT_MOD_TYPE_ERROR:
3442		case FW_PORT_MOD_TYPE_UNKNOWN:
3443		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3444			break;
3445		case FW_PORT_MOD_TYPE_NONE:
3446			return (IFM_NONE);
3447		}
3448		break;
3449	case FW_PORT_TYPE_NONE:
3450		return (IFM_NONE);
3451	}
3452
3453	return (IFM_UNKNOWN);
3454}
3455
3456void
3457cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3458{
3459	struct vi_info *vi = if_getsoftc(ifp);
3460	struct port_info *pi = vi->pi;
3461	struct adapter *sc = pi->adapter;
3462	struct link_config *lc = &pi->link_cfg;
3463
3464	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3465		return;
3466	PORT_LOCK(pi);
3467
3468	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3469		/*
3470		 * If all the interfaces are administratively down the firmware
3471		 * does not report transceiver changes.  Refresh port info here
3472		 * so that ifconfig displays accurate ifmedia at all times.
3473		 * This is the only reason we have a synchronized op in this
3474		 * function.  Just PORT_LOCK would have been enough otherwise.
3475		 */
3476		t4_update_port_info(pi);
3477		build_medialist(pi);
3478	}
3479
3480	/* ifm_status */
3481	ifmr->ifm_status = IFM_AVALID;
3482	if (lc->link_ok == false)
3483		goto done;
3484	ifmr->ifm_status |= IFM_ACTIVE;
3485
3486	/* ifm_active */
3487	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3488	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3489	if (lc->fc & PAUSE_RX)
3490		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3491	if (lc->fc & PAUSE_TX)
3492		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3493	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3494done:
3495	PORT_UNLOCK(pi);
3496	end_synchronized_op(sc, 0);
3497}
3498
3499static int
3500vcxgbe_probe(device_t dev)
3501{
3502	char buf[128];
3503	struct vi_info *vi = device_get_softc(dev);
3504
3505	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3506	    vi - vi->pi->vi);
3507	device_set_desc_copy(dev, buf);
3508
3509	return (BUS_PROBE_DEFAULT);
3510}
3511
3512static int
3513alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3514{
3515	int func, index, rc;
3516	uint32_t param, val;
3517
3518	ASSERT_SYNCHRONIZED_OP(sc);
3519
3520	index = vi - pi->vi;
3521	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3522	KASSERT(index < nitems(vi_mac_funcs),
3523	    ("%s: VI %s doesn't have a MAC func", __func__,
3524	    device_get_nameunit(vi->dev)));
3525	func = vi_mac_funcs[index];
3526	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3527	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3528	if (rc < 0) {
3529		CH_ERR(vi, "failed to allocate virtual interface %d"
3530		    "for port %d: %d\n", index, pi->port_id, -rc);
3531		return (-rc);
3532	}
3533	vi->viid = rc;
3534
3535	if (vi->rss_size == 1) {
3536		/*
3537		 * This VI didn't get a slice of the RSS table.  Reduce the
3538		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3539		 * configuration file (nvi, rssnvi for this PF) if this is a
3540		 * problem.
3541		 */
3542		device_printf(vi->dev, "RSS table not available.\n");
3543		vi->rss_base = 0xffff;
3544
3545		return (0);
3546	}
3547
3548	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3549	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3550	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3551	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3552	if (rc)
3553		vi->rss_base = 0xffff;
3554	else {
3555		MPASS((val >> 16) == vi->rss_size);
3556		vi->rss_base = val & 0xffff;
3557	}
3558
3559	return (0);
3560}
3561
3562static int
3563vcxgbe_attach(device_t dev)
3564{
3565	struct vi_info *vi;
3566	struct port_info *pi;
3567	struct adapter *sc;
3568	int rc;
3569
3570	vi = device_get_softc(dev);
3571	pi = vi->pi;
3572	sc = pi->adapter;
3573
3574	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3575	if (rc)
3576		return (rc);
3577	rc = alloc_extra_vi(sc, pi, vi);
3578	end_synchronized_op(sc, 0);
3579	if (rc)
3580		return (rc);
3581
3582	rc = cxgbe_vi_attach(dev, vi);
3583	if (rc) {
3584		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3585		return (rc);
3586	}
3587	return (0);
3588}
3589
3590static int
3591vcxgbe_detach(device_t dev)
3592{
3593	struct vi_info *vi;
3594	struct adapter *sc;
3595
3596	vi = device_get_softc(dev);
3597	sc = vi->adapter;
3598
3599	begin_vi_detach(sc, vi);
3600	cxgbe_vi_detach(vi);
3601	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3602	end_vi_detach(sc, vi);
3603
3604	return (0);
3605}
3606
3607static struct callout fatal_callout;
3608static struct taskqueue *reset_tq;
3609
3610static void
3611delayed_panic(void *arg)
3612{
3613	struct adapter *sc = arg;
3614
3615	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3616}
3617
3618static void
3619fatal_error_task(void *arg, int pending)
3620{
3621	struct adapter *sc = arg;
3622	int rc;
3623
3624#ifdef TCP_OFFLOAD
3625	t4_async_event(sc);
3626#endif
3627	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3628		dump_cim_regs(sc);
3629		dump_cimla(sc);
3630		dump_devlog(sc);
3631	}
3632
3633	if (t4_reset_on_fatal_err) {
3634		CH_ALERT(sc, "resetting on fatal error.\n");
3635		rc = reset_adapter(sc);
3636		if (rc == 0 && t4_panic_on_fatal_err) {
3637			CH_ALERT(sc, "reset was successful, "
3638			    "system will NOT panic.\n");
3639			return;
3640		}
3641	}
3642
3643	if (t4_panic_on_fatal_err) {
3644		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3645		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3646	}
3647}
3648
3649void
3650t4_fatal_err(struct adapter *sc, bool fw_error)
3651{
3652	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3653
3654	stop_adapter(sc);
3655	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3656		return;
3657	if (fw_error) {
3658		/*
3659		 * We are here because of a firmware error/timeout and not
3660		 * because of a hardware interrupt.  It is possible (although
3661		 * not very likely) that an error interrupt was also raised but
3662		 * this thread ran first and inhibited t4_intr_err.  We walk the
3663		 * main INT_CAUSE registers here to make sure we haven't missed
3664		 * anything interesting.
3665		 */
3666		t4_slow_intr_handler(sc, verbose);
3667		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3668	}
3669	t4_report_fw_error(sc);
3670	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3671	    device_get_nameunit(sc->dev), fw_error);
3672	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3673}
3674
3675void
3676t4_add_adapter(struct adapter *sc)
3677{
3678	sx_xlock(&t4_list_lock);
3679	SLIST_INSERT_HEAD(&t4_list, sc, link);
3680	sx_xunlock(&t4_list_lock);
3681}
3682
3683int
3684t4_map_bars_0_and_4(struct adapter *sc)
3685{
3686	sc->regs_rid = PCIR_BAR(0);
3687	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3688	    &sc->regs_rid, RF_ACTIVE);
3689	if (sc->regs_res == NULL) {
3690		device_printf(sc->dev, "cannot map registers.\n");
3691		return (ENXIO);
3692	}
3693	sc->bt = rman_get_bustag(sc->regs_res);
3694	sc->bh = rman_get_bushandle(sc->regs_res);
3695	sc->mmio_len = rman_get_size(sc->regs_res);
3696	setbit(&sc->doorbells, DOORBELL_KDB);
3697
3698	sc->msix_rid = PCIR_BAR(4);
3699	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3700	    &sc->msix_rid, RF_ACTIVE);
3701	if (sc->msix_res == NULL) {
3702		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3703		return (ENXIO);
3704	}
3705
3706	return (0);
3707}
3708
3709int
3710t4_map_bar_2(struct adapter *sc)
3711{
3712
3713	/*
3714	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3715	 * to map it if RDMA is disabled.
3716	 */
3717	if (is_t4(sc) && sc->rdmacaps == 0)
3718		return (0);
3719
3720	sc->udbs_rid = PCIR_BAR(2);
3721	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3722	    &sc->udbs_rid, RF_ACTIVE);
3723	if (sc->udbs_res == NULL) {
3724		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3725		return (ENXIO);
3726	}
3727	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3728
3729	if (chip_id(sc) >= CHELSIO_T5) {
3730		setbit(&sc->doorbells, DOORBELL_UDB);
3731#if defined(__i386__) || defined(__amd64__)
3732		if (t5_write_combine) {
3733			int rc, mode;
3734
3735			/*
3736			 * Enable write combining on BAR2.  This is the
3737			 * userspace doorbell BAR and is split into 128B
3738			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3739			 * with an egress queue.  The first 64B has the doorbell
3740			 * and the second 64B can be used to submit a tx work
3741			 * request with an implicit doorbell.
3742			 */
3743
3744			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3745			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3746			if (rc == 0) {
3747				clrbit(&sc->doorbells, DOORBELL_UDB);
3748				setbit(&sc->doorbells, DOORBELL_WCWR);
3749				setbit(&sc->doorbells, DOORBELL_UDBWC);
3750			} else {
3751				device_printf(sc->dev,
3752				    "couldn't enable write combining: %d\n",
3753				    rc);
3754			}
3755
3756			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3757			t4_write_reg(sc, A_SGE_STAT_CFG,
3758			    V_STATSOURCE_T5(7) | mode);
3759		}
3760#endif
3761	}
3762	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3763
3764	return (0);
3765}
3766
3767struct memwin_init {
3768	uint32_t base;
3769	uint32_t aperture;
3770};
3771
3772static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3773	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3774	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3775	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3776};
3777
3778static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3779	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3780	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3781	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3782};
3783
3784static void
3785setup_memwin(struct adapter *sc)
3786{
3787	const struct memwin_init *mw_init;
3788	struct memwin *mw;
3789	int i;
3790	uint32_t bar0;
3791
3792	if (is_t4(sc)) {
3793		/*
3794		 * Read low 32b of bar0 indirectly via the hardware backdoor
3795		 * mechanism.  Works from within PCI passthrough environments
3796		 * too, where rman_get_start() can return a different value.  We
3797		 * need to program the T4 memory window decoders with the actual
3798		 * addresses that will be coming across the PCIe link.
3799		 */
3800		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3801		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3802
3803		mw_init = &t4_memwin[0];
3804	} else {
3805		/* T5+ use the relative offset inside the PCIe BAR */
3806		bar0 = 0;
3807
3808		mw_init = &t5_memwin[0];
3809	}
3810
3811	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3812		if (!rw_initialized(&mw->mw_lock)) {
3813			rw_init(&mw->mw_lock, "memory window access");
3814			mw->mw_base = mw_init->base;
3815			mw->mw_aperture = mw_init->aperture;
3816			mw->mw_curpos = 0;
3817		}
3818		t4_write_reg(sc,
3819		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3820		    (mw->mw_base + bar0) | V_BIR(0) |
3821		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3822		rw_wlock(&mw->mw_lock);
3823		position_memwin(sc, i, mw->mw_curpos);
3824		rw_wunlock(&mw->mw_lock);
3825	}
3826
3827	/* flush */
3828	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3829}
3830
3831/*
3832 * Positions the memory window at the given address in the card's address space.
3833 * There are some alignment requirements and the actual position may be at an
3834 * address prior to the requested address.  mw->mw_curpos always has the actual
3835 * position of the window.
3836 */
3837static void
3838position_memwin(struct adapter *sc, int idx, uint32_t addr)
3839{
3840	struct memwin *mw;
3841	uint32_t pf;
3842	uint32_t reg;
3843
3844	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3845	mw = &sc->memwin[idx];
3846	rw_assert(&mw->mw_lock, RA_WLOCKED);
3847
3848	if (is_t4(sc)) {
3849		pf = 0;
3850		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3851	} else {
3852		pf = V_PFNUM(sc->pf);
3853		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3854	}
3855	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3856	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3857	t4_read_reg(sc, reg);	/* flush */
3858}
3859
3860int
3861rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3862    int len, int rw)
3863{
3864	struct memwin *mw;
3865	uint32_t mw_end, v;
3866
3867	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3868
3869	/* Memory can only be accessed in naturally aligned 4 byte units */
3870	if (addr & 3 || len & 3 || len <= 0)
3871		return (EINVAL);
3872
3873	mw = &sc->memwin[idx];
3874	while (len > 0) {
3875		rw_rlock(&mw->mw_lock);
3876		mw_end = mw->mw_curpos + mw->mw_aperture;
3877		if (addr >= mw_end || addr < mw->mw_curpos) {
3878			/* Will need to reposition the window */
3879			if (!rw_try_upgrade(&mw->mw_lock)) {
3880				rw_runlock(&mw->mw_lock);
3881				rw_wlock(&mw->mw_lock);
3882			}
3883			rw_assert(&mw->mw_lock, RA_WLOCKED);
3884			position_memwin(sc, idx, addr);
3885			rw_downgrade(&mw->mw_lock);
3886			mw_end = mw->mw_curpos + mw->mw_aperture;
3887		}
3888		rw_assert(&mw->mw_lock, RA_RLOCKED);
3889		while (addr < mw_end && len > 0) {
3890			if (rw == 0) {
3891				v = t4_read_reg(sc, mw->mw_base + addr -
3892				    mw->mw_curpos);
3893				*val++ = le32toh(v);
3894			} else {
3895				v = *val++;
3896				t4_write_reg(sc, mw->mw_base + addr -
3897				    mw->mw_curpos, htole32(v));
3898			}
3899			addr += 4;
3900			len -= 4;
3901		}
3902		rw_runlock(&mw->mw_lock);
3903	}
3904
3905	return (0);
3906}
3907
3908CTASSERT(M_TID_COOKIE == M_COOKIE);
3909CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3910
3911static void
3912t4_init_atid_table(struct adapter *sc)
3913{
3914	struct tid_info *t;
3915	int i;
3916
3917	t = &sc->tids;
3918	if (t->natids == 0)
3919		return;
3920
3921	MPASS(t->atid_tab == NULL);
3922
3923	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3924	    M_ZERO | M_WAITOK);
3925	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3926	t->afree = t->atid_tab;
3927	t->atids_in_use = 0;
3928	for (i = 1; i < t->natids; i++)
3929		t->atid_tab[i - 1].next = &t->atid_tab[i];
3930	t->atid_tab[t->natids - 1].next = NULL;
3931}
3932
3933static void
3934t4_free_atid_table(struct adapter *sc)
3935{
3936	struct tid_info *t;
3937
3938	t = &sc->tids;
3939
3940	KASSERT(t->atids_in_use == 0,
3941	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3942
3943	if (mtx_initialized(&t->atid_lock))
3944		mtx_destroy(&t->atid_lock);
3945	free(t->atid_tab, M_CXGBE);
3946	t->atid_tab = NULL;
3947}
3948
3949int
3950alloc_atid(struct adapter *sc, void *ctx)
3951{
3952	struct tid_info *t = &sc->tids;
3953	int atid = -1;
3954
3955	mtx_lock(&t->atid_lock);
3956	if (t->afree) {
3957		union aopen_entry *p = t->afree;
3958
3959		atid = p - t->atid_tab;
3960		MPASS(atid <= M_TID_TID);
3961		t->afree = p->next;
3962		p->data = ctx;
3963		t->atids_in_use++;
3964	}
3965	mtx_unlock(&t->atid_lock);
3966	return (atid);
3967}
3968
3969void *
3970lookup_atid(struct adapter *sc, int atid)
3971{
3972	struct tid_info *t = &sc->tids;
3973
3974	return (t->atid_tab[atid].data);
3975}
3976
3977void
3978free_atid(struct adapter *sc, int atid)
3979{
3980	struct tid_info *t = &sc->tids;
3981	union aopen_entry *p = &t->atid_tab[atid];
3982
3983	mtx_lock(&t->atid_lock);
3984	p->next = t->afree;
3985	t->afree = p;
3986	t->atids_in_use--;
3987	mtx_unlock(&t->atid_lock);
3988}
3989
3990static void
3991queue_tid_release(struct adapter *sc, int tid)
3992{
3993
3994	CXGBE_UNIMPLEMENTED("deferred tid release");
3995}
3996
3997void
3998release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3999{
4000	struct wrqe *wr;
4001	struct cpl_tid_release *req;
4002
4003	wr = alloc_wrqe(sizeof(*req), ctrlq);
4004	if (wr == NULL) {
4005		queue_tid_release(sc, tid);	/* defer */
4006		return;
4007	}
4008	req = wrtod(wr);
4009
4010	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4011
4012	t4_wrq_tx(sc, wr);
4013}
4014
4015static int
4016t4_range_cmp(const void *a, const void *b)
4017{
4018	return ((const struct t4_range *)a)->start -
4019	       ((const struct t4_range *)b)->start;
4020}
4021
4022/*
4023 * Verify that the memory range specified by the addr/len pair is valid within
4024 * the card's address space.
4025 */
4026static int
4027validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4028{
4029	struct t4_range mem_ranges[4], *r, *next;
4030	uint32_t em, addr_len;
4031	int i, n, remaining;
4032
4033	/* Memory can only be accessed in naturally aligned 4 byte units */
4034	if (addr & 3 || len & 3 || len == 0)
4035		return (EINVAL);
4036
4037	/* Enabled memories */
4038	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4039
4040	r = &mem_ranges[0];
4041	n = 0;
4042	bzero(r, sizeof(mem_ranges));
4043	if (em & F_EDRAM0_ENABLE) {
4044		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4045		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4046		if (r->size > 0) {
4047			r->start = G_EDRAM0_BASE(addr_len) << 20;
4048			if (addr >= r->start &&
4049			    addr + len <= r->start + r->size)
4050				return (0);
4051			r++;
4052			n++;
4053		}
4054	}
4055	if (em & F_EDRAM1_ENABLE) {
4056		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4057		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4058		if (r->size > 0) {
4059			r->start = G_EDRAM1_BASE(addr_len) << 20;
4060			if (addr >= r->start &&
4061			    addr + len <= r->start + r->size)
4062				return (0);
4063			r++;
4064			n++;
4065		}
4066	}
4067	if (em & F_EXT_MEM_ENABLE) {
4068		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4069		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4070		if (r->size > 0) {
4071			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4072			if (addr >= r->start &&
4073			    addr + len <= r->start + r->size)
4074				return (0);
4075			r++;
4076			n++;
4077		}
4078	}
4079	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4080		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4081		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4082		if (r->size > 0) {
4083			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4084			if (addr >= r->start &&
4085			    addr + len <= r->start + r->size)
4086				return (0);
4087			r++;
4088			n++;
4089		}
4090	}
4091	MPASS(n <= nitems(mem_ranges));
4092
4093	if (n > 1) {
4094		/* Sort and merge the ranges. */
4095		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4096
4097		/* Start from index 0 and examine the next n - 1 entries. */
4098		r = &mem_ranges[0];
4099		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4100
4101			MPASS(r->size > 0);	/* r is a valid entry. */
4102			next = r + 1;
4103			MPASS(next->size > 0);	/* and so is the next one. */
4104
4105			while (r->start + r->size >= next->start) {
4106				/* Merge the next one into the current entry. */
4107				r->size = max(r->start + r->size,
4108				    next->start + next->size) - r->start;
4109				n--;	/* One fewer entry in total. */
4110				if (--remaining == 0)
4111					goto done;	/* short circuit */
4112				next++;
4113			}
4114			if (next != r + 1) {
4115				/*
4116				 * Some entries were merged into r and next
4117				 * points to the first valid entry that couldn't
4118				 * be merged.
4119				 */
4120				MPASS(next->size > 0);	/* must be valid */
4121				memcpy(r + 1, next, remaining * sizeof(*r));
4122#ifdef INVARIANTS
4123				/*
4124				 * This so that the foo->size assertion in the
4125				 * next iteration of the loop do the right
4126				 * thing for entries that were pulled up and are
4127				 * no longer valid.
4128				 */
4129				MPASS(n < nitems(mem_ranges));
4130				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4131				    sizeof(struct t4_range));
4132#endif
4133			}
4134		}
4135done:
4136		/* Done merging the ranges. */
4137		MPASS(n > 0);
4138		r = &mem_ranges[0];
4139		for (i = 0; i < n; i++, r++) {
4140			if (addr >= r->start &&
4141			    addr + len <= r->start + r->size)
4142				return (0);
4143		}
4144	}
4145
4146	return (EFAULT);
4147}
4148
4149static int
4150fwmtype_to_hwmtype(int mtype)
4151{
4152
4153	switch (mtype) {
4154	case FW_MEMTYPE_EDC0:
4155		return (MEM_EDC0);
4156	case FW_MEMTYPE_EDC1:
4157		return (MEM_EDC1);
4158	case FW_MEMTYPE_EXTMEM:
4159		return (MEM_MC0);
4160	case FW_MEMTYPE_EXTMEM1:
4161		return (MEM_MC1);
4162	default:
4163		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4164	}
4165}
4166
4167/*
4168 * Verify that the memory range specified by the memtype/offset/len pair is
4169 * valid and lies entirely within the memtype specified.  The global address of
4170 * the start of the range is returned in addr.
4171 */
4172static int
4173validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4174    uint32_t *addr)
4175{
4176	uint32_t em, addr_len, maddr;
4177
4178	/* Memory can only be accessed in naturally aligned 4 byte units */
4179	if (off & 3 || len & 3 || len == 0)
4180		return (EINVAL);
4181
4182	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4183	switch (fwmtype_to_hwmtype(mtype)) {
4184	case MEM_EDC0:
4185		if (!(em & F_EDRAM0_ENABLE))
4186			return (EINVAL);
4187		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4188		maddr = G_EDRAM0_BASE(addr_len) << 20;
4189		break;
4190	case MEM_EDC1:
4191		if (!(em & F_EDRAM1_ENABLE))
4192			return (EINVAL);
4193		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4194		maddr = G_EDRAM1_BASE(addr_len) << 20;
4195		break;
4196	case MEM_MC:
4197		if (!(em & F_EXT_MEM_ENABLE))
4198			return (EINVAL);
4199		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4200		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4201		break;
4202	case MEM_MC1:
4203		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4204			return (EINVAL);
4205		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4206		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4207		break;
4208	default:
4209		return (EINVAL);
4210	}
4211
4212	*addr = maddr + off;	/* global address */
4213	return (validate_mem_range(sc, *addr, len));
4214}
4215
4216static int
4217fixup_devlog_params(struct adapter *sc)
4218{
4219	struct devlog_params *dparams = &sc->params.devlog;
4220	int rc;
4221
4222	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4223	    dparams->size, &dparams->addr);
4224
4225	return (rc);
4226}
4227
4228static void
4229update_nirq(struct intrs_and_queues *iaq, int nports)
4230{
4231
4232	iaq->nirq = T4_EXTRA_INTR;
4233	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4234	iaq->nirq += nports * iaq->nofldrxq;
4235	iaq->nirq += nports * (iaq->num_vis - 1) *
4236	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4237	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4238}
4239
4240/*
4241 * Adjust requirements to fit the number of interrupts available.
4242 */
4243static void
4244calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4245    int navail)
4246{
4247	int old_nirq;
4248	const int nports = sc->params.nports;
4249
4250	MPASS(nports > 0);
4251	MPASS(navail > 0);
4252
4253	bzero(iaq, sizeof(*iaq));
4254	iaq->intr_type = itype;
4255	iaq->num_vis = t4_num_vis;
4256	iaq->ntxq = t4_ntxq;
4257	iaq->ntxq_vi = t4_ntxq_vi;
4258	iaq->nrxq = t4_nrxq;
4259	iaq->nrxq_vi = t4_nrxq_vi;
4260#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4261	if (is_offload(sc) || is_ethoffload(sc)) {
4262		iaq->nofldtxq = t4_nofldtxq;
4263		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4264	}
4265#endif
4266#ifdef TCP_OFFLOAD
4267	if (is_offload(sc)) {
4268		iaq->nofldrxq = t4_nofldrxq;
4269		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4270	}
4271#endif
4272#ifdef DEV_NETMAP
4273	if (t4_native_netmap & NN_MAIN_VI) {
4274		iaq->nnmtxq = t4_nnmtxq;
4275		iaq->nnmrxq = t4_nnmrxq;
4276	}
4277	if (t4_native_netmap & NN_EXTRA_VI) {
4278		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4279		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4280	}
4281#endif
4282
4283	update_nirq(iaq, nports);
4284	if (iaq->nirq <= navail &&
4285	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4286		/*
4287		 * This is the normal case -- there are enough interrupts for
4288		 * everything.
4289		 */
4290		goto done;
4291	}
4292
4293	/*
4294	 * If extra VIs have been configured try reducing their count and see if
4295	 * that works.
4296	 */
4297	while (iaq->num_vis > 1) {
4298		iaq->num_vis--;
4299		update_nirq(iaq, nports);
4300		if (iaq->nirq <= navail &&
4301		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4302			device_printf(sc->dev, "virtual interfaces per port "
4303			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4304			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4305			    "itype %d, navail %u, nirq %d.\n",
4306			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4307			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4308			    itype, navail, iaq->nirq);
4309			goto done;
4310		}
4311	}
4312
4313	/*
4314	 * Extra VIs will not be created.  Log a message if they were requested.
4315	 */
4316	MPASS(iaq->num_vis == 1);
4317	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4318	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4319	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4320	if (iaq->num_vis != t4_num_vis) {
4321		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4322		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4323		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4324		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4325		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4326	}
4327
4328	/*
4329	 * Keep reducing the number of NIC rx queues to the next lower power of
4330	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4331	 * if that works.
4332	 */
4333	do {
4334		if (iaq->nrxq > 1) {
4335			do {
4336				iaq->nrxq--;
4337			} while (!powerof2(iaq->nrxq));
4338			if (iaq->nnmrxq > iaq->nrxq)
4339				iaq->nnmrxq = iaq->nrxq;
4340		}
4341		if (iaq->nofldrxq > 1)
4342			iaq->nofldrxq >>= 1;
4343
4344		old_nirq = iaq->nirq;
4345		update_nirq(iaq, nports);
4346		if (iaq->nirq <= navail &&
4347		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4348			device_printf(sc->dev, "running with reduced number of "
4349			    "rx queues because of shortage of interrupts.  "
4350			    "nrxq=%u, nofldrxq=%u.  "
4351			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4352			    iaq->nofldrxq, itype, navail, iaq->nirq);
4353			goto done;
4354		}
4355	} while (old_nirq != iaq->nirq);
4356
4357	/* One interrupt for everything.  Ugh. */
4358	device_printf(sc->dev, "running with minimal number of queues.  "
4359	    "itype %d, navail %u.\n", itype, navail);
4360	iaq->nirq = 1;
4361	iaq->nrxq = 1;
4362	iaq->ntxq = 1;
4363	if (iaq->nofldrxq > 0) {
4364		iaq->nofldrxq = 1;
4365		iaq->nofldtxq = 1;
4366	}
4367	iaq->nnmtxq = 0;
4368	iaq->nnmrxq = 0;
4369done:
4370	MPASS(iaq->num_vis > 0);
4371	if (iaq->num_vis > 1) {
4372		MPASS(iaq->nrxq_vi > 0);
4373		MPASS(iaq->ntxq_vi > 0);
4374	}
4375	MPASS(iaq->nirq > 0);
4376	MPASS(iaq->nrxq > 0);
4377	MPASS(iaq->ntxq > 0);
4378	if (itype == INTR_MSI) {
4379		MPASS(powerof2(iaq->nirq));
4380	}
4381}
4382
4383static int
4384cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4385{
4386	int rc, itype, navail, nalloc;
4387
4388	for (itype = INTR_MSIX; itype; itype >>= 1) {
4389
4390		if ((itype & t4_intr_types) == 0)
4391			continue;	/* not allowed */
4392
4393		if (itype == INTR_MSIX)
4394			navail = pci_msix_count(sc->dev);
4395		else if (itype == INTR_MSI)
4396			navail = pci_msi_count(sc->dev);
4397		else
4398			navail = 1;
4399restart:
4400		if (navail == 0)
4401			continue;
4402
4403		calculate_iaq(sc, iaq, itype, navail);
4404		nalloc = iaq->nirq;
4405		rc = 0;
4406		if (itype == INTR_MSIX)
4407			rc = pci_alloc_msix(sc->dev, &nalloc);
4408		else if (itype == INTR_MSI)
4409			rc = pci_alloc_msi(sc->dev, &nalloc);
4410
4411		if (rc == 0 && nalloc > 0) {
4412			if (nalloc == iaq->nirq)
4413				return (0);
4414
4415			/*
4416			 * Didn't get the number requested.  Use whatever number
4417			 * the kernel is willing to allocate.
4418			 */
4419			device_printf(sc->dev, "fewer vectors than requested, "
4420			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4421			    itype, iaq->nirq, nalloc);
4422			pci_release_msi(sc->dev);
4423			navail = nalloc;
4424			goto restart;
4425		}
4426
4427		device_printf(sc->dev,
4428		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4429		    itype, rc, iaq->nirq, nalloc);
4430	}
4431
4432	device_printf(sc->dev,
4433	    "failed to find a usable interrupt type.  "
4434	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4435	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4436
4437	return (ENXIO);
4438}
4439
4440#define FW_VERSION(chip) ( \
4441    V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4442    V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4443    V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4444    V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4445#define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4446
4447/* Just enough of fw_hdr to cover all version info. */
4448struct fw_h {
4449	__u8	ver;
4450	__u8	chip;
4451	__be16	len512;
4452	__be32	fw_ver;
4453	__be32	tp_microcode_ver;
4454	__u8	intfver_nic;
4455	__u8	intfver_vnic;
4456	__u8	intfver_ofld;
4457	__u8	intfver_ri;
4458	__u8	intfver_iscsipdu;
4459	__u8	intfver_iscsi;
4460	__u8	intfver_fcoepdu;
4461	__u8	intfver_fcoe;
4462};
4463/* Spot check a couple of fields. */
4464CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4465CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4466CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4467
4468struct fw_info {
4469	uint8_t chip;
4470	char *kld_name;
4471	char *fw_mod_name;
4472	struct fw_h fw_h;
4473} fw_info[] = {
4474	{
4475		.chip = CHELSIO_T4,
4476		.kld_name = "t4fw_cfg",
4477		.fw_mod_name = "t4fw",
4478		.fw_h = {
4479			.chip = FW_HDR_CHIP_T4,
4480			.fw_ver = htobe32(FW_VERSION(T4)),
4481			.intfver_nic = FW_INTFVER(T4, NIC),
4482			.intfver_vnic = FW_INTFVER(T4, VNIC),
4483			.intfver_ofld = FW_INTFVER(T4, OFLD),
4484			.intfver_ri = FW_INTFVER(T4, RI),
4485			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4486			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4487			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4488			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4489		},
4490	}, {
4491		.chip = CHELSIO_T5,
4492		.kld_name = "t5fw_cfg",
4493		.fw_mod_name = "t5fw",
4494		.fw_h = {
4495			.chip = FW_HDR_CHIP_T5,
4496			.fw_ver = htobe32(FW_VERSION(T5)),
4497			.intfver_nic = FW_INTFVER(T5, NIC),
4498			.intfver_vnic = FW_INTFVER(T5, VNIC),
4499			.intfver_ofld = FW_INTFVER(T5, OFLD),
4500			.intfver_ri = FW_INTFVER(T5, RI),
4501			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4502			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4503			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4504			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4505		},
4506	}, {
4507		.chip = CHELSIO_T6,
4508		.kld_name = "t6fw_cfg",
4509		.fw_mod_name = "t6fw",
4510		.fw_h = {
4511			.chip = FW_HDR_CHIP_T6,
4512			.fw_ver = htobe32(FW_VERSION(T6)),
4513			.intfver_nic = FW_INTFVER(T6, NIC),
4514			.intfver_vnic = FW_INTFVER(T6, VNIC),
4515			.intfver_ofld = FW_INTFVER(T6, OFLD),
4516			.intfver_ri = FW_INTFVER(T6, RI),
4517			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4518			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4519			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4520			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4521		},
4522	}
4523};
4524
4525static struct fw_info *
4526find_fw_info(int chip)
4527{
4528	int i;
4529
4530	for (i = 0; i < nitems(fw_info); i++) {
4531		if (fw_info[i].chip == chip)
4532			return (&fw_info[i]);
4533	}
4534	return (NULL);
4535}
4536
4537/*
4538 * Is the given firmware API compatible with the one the driver was compiled
4539 * with?
4540 */
4541static int
4542fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4543{
4544
4545	/* short circuit if it's the exact same firmware version */
4546	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4547		return (1);
4548
4549	/*
4550	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4551	 * features that are supported in the driver.
4552	 */
4553#define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4554	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4555	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4556	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4557		return (1);
4558#undef SAME_INTF
4559
4560	return (0);
4561}
4562
4563static int
4564load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4565    const struct firmware **fw)
4566{
4567	struct fw_info *fw_info;
4568
4569	*dcfg = NULL;
4570	if (fw != NULL)
4571		*fw = NULL;
4572
4573	fw_info = find_fw_info(chip_id(sc));
4574	if (fw_info == NULL) {
4575		device_printf(sc->dev,
4576		    "unable to look up firmware information for chip %d.\n",
4577		    chip_id(sc));
4578		return (EINVAL);
4579	}
4580
4581	*dcfg = firmware_get(fw_info->kld_name);
4582	if (*dcfg != NULL) {
4583		if (fw != NULL)
4584			*fw = firmware_get(fw_info->fw_mod_name);
4585		return (0);
4586	}
4587
4588	return (ENOENT);
4589}
4590
4591static void
4592unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4593    const struct firmware *fw)
4594{
4595
4596	if (fw != NULL)
4597		firmware_put(fw, FIRMWARE_UNLOAD);
4598	if (dcfg != NULL)
4599		firmware_put(dcfg, FIRMWARE_UNLOAD);
4600}
4601
4602/*
4603 * Return values:
4604 * 0 means no firmware install attempted.
4605 * ERESTART means a firmware install was attempted and was successful.
4606 * +ve errno means a firmware install was attempted but failed.
4607 */
4608static int
4609install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4610    const struct fw_h *drv_fw, const char *reason, int *already)
4611{
4612	const struct firmware *cfg, *fw;
4613	const uint32_t c = be32toh(card_fw->fw_ver);
4614	uint32_t d, k;
4615	int rc, fw_install;
4616	struct fw_h bundled_fw;
4617	bool load_attempted;
4618
4619	cfg = fw = NULL;
4620	load_attempted = false;
4621	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4622
4623	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4624	if (t4_fw_install < 0) {
4625		rc = load_fw_module(sc, &cfg, &fw);
4626		if (rc != 0 || fw == NULL) {
4627			device_printf(sc->dev,
4628			    "failed to load firmware module: %d. cfg %p, fw %p;"
4629			    " will use compiled-in firmware version for"
4630			    "hw.cxgbe.fw_install checks.\n",
4631			    rc, cfg, fw);
4632		} else {
4633			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4634		}
4635		load_attempted = true;
4636	}
4637	d = be32toh(bundled_fw.fw_ver);
4638
4639	if (reason != NULL)
4640		goto install;
4641
4642	if ((sc->flags & FW_OK) == 0) {
4643
4644		if (c == 0xffffffff) {
4645			reason = "missing";
4646			goto install;
4647		}
4648
4649		rc = 0;
4650		goto done;
4651	}
4652
4653	if (!fw_compatible(card_fw, &bundled_fw)) {
4654		reason = "incompatible or unusable";
4655		goto install;
4656	}
4657
4658	if (d > c) {
4659		reason = "older than the version bundled with this driver";
4660		goto install;
4661	}
4662
4663	if (fw_install == 2 && d != c) {
4664		reason = "different than the version bundled with this driver";
4665		goto install;
4666	}
4667
4668	/* No reason to do anything to the firmware already on the card. */
4669	rc = 0;
4670	goto done;
4671
4672install:
4673	rc = 0;
4674	if ((*already)++)
4675		goto done;
4676
4677	if (fw_install == 0) {
4678		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4679		    "but the driver is prohibited from installing a firmware "
4680		    "on the card.\n",
4681		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4682		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4683
4684		goto done;
4685	}
4686
4687	/*
4688	 * We'll attempt to install a firmware.  Load the module first (if it
4689	 * hasn't been loaded already).
4690	 */
4691	if (!load_attempted) {
4692		rc = load_fw_module(sc, &cfg, &fw);
4693		if (rc != 0 || fw == NULL) {
4694			device_printf(sc->dev,
4695			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4696			    rc, cfg, fw);
4697			/* carry on */
4698		}
4699	}
4700	if (fw == NULL) {
4701		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4702		    "but the driver cannot take corrective action because it "
4703		    "is unable to load the firmware module.\n",
4704		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4705		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4706		rc = sc->flags & FW_OK ? 0 : ENOENT;
4707		goto done;
4708	}
4709	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4710	if (k != d) {
4711		MPASS(t4_fw_install > 0);
4712		device_printf(sc->dev,
4713		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4714		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4715		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4716		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4717		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4718		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4719		rc = sc->flags & FW_OK ? 0 : EINVAL;
4720		goto done;
4721	}
4722
4723	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4724	    "installing firmware %u.%u.%u.%u on card.\n",
4725	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4726	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4727	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4728	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4729
4730	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4731	if (rc != 0) {
4732		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4733	} else {
4734		/* Installed successfully, update the cached header too. */
4735		rc = ERESTART;
4736		memcpy(card_fw, fw->data, sizeof(*card_fw));
4737	}
4738done:
4739	unload_fw_module(sc, cfg, fw);
4740
4741	return (rc);
4742}
4743
4744/*
4745 * Establish contact with the firmware and attempt to become the master driver.
4746 *
4747 * A firmware will be installed to the card if needed (if the driver is allowed
4748 * to do so).
4749 */
4750static int
4751contact_firmware(struct adapter *sc)
4752{
4753	int rc, already = 0;
4754	enum dev_state state;
4755	struct fw_info *fw_info;
4756	struct fw_hdr *card_fw;		/* fw on the card */
4757	const struct fw_h *drv_fw;
4758
4759	fw_info = find_fw_info(chip_id(sc));
4760	if (fw_info == NULL) {
4761		device_printf(sc->dev,
4762		    "unable to look up firmware information for chip %d.\n",
4763		    chip_id(sc));
4764		return (EINVAL);
4765	}
4766	drv_fw = &fw_info->fw_h;
4767
4768	/* Read the header of the firmware on the card */
4769	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4770restart:
4771	rc = -t4_get_fw_hdr(sc, card_fw);
4772	if (rc != 0) {
4773		device_printf(sc->dev,
4774		    "unable to read firmware header from card's flash: %d\n",
4775		    rc);
4776		goto done;
4777	}
4778
4779	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4780	    &already);
4781	if (rc == ERESTART)
4782		goto restart;
4783	if (rc != 0)
4784		goto done;
4785
4786	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4787	if (rc < 0 || state == DEV_STATE_ERR) {
4788		rc = -rc;
4789		device_printf(sc->dev,
4790		    "failed to connect to the firmware: %d, %d.  "
4791		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4792#if 0
4793		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4794		    "not responding properly to HELLO", &already) == ERESTART)
4795			goto restart;
4796#endif
4797		goto done;
4798	}
4799	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4800	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4801
4802	if (rc == sc->pf) {
4803		sc->flags |= MASTER_PF;
4804		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4805		    NULL, &already);
4806		if (rc == ERESTART)
4807			rc = 0;
4808		else if (rc != 0)
4809			goto done;
4810	} else if (state == DEV_STATE_UNINIT) {
4811		/*
4812		 * We didn't get to be the master so we definitely won't be
4813		 * configuring the chip.  It's a bug if someone else hasn't
4814		 * configured it already.
4815		 */
4816		device_printf(sc->dev, "couldn't be master(%d), "
4817		    "device not already initialized either(%d).  "
4818		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4819		rc = EPROTO;
4820		goto done;
4821	} else {
4822		/*
4823		 * Some other PF is the master and has configured the chip.
4824		 * This is allowed but untested.
4825		 */
4826		device_printf(sc->dev, "PF%d is master, device state %d.  "
4827		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4828		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4829		sc->cfcsum = 0;
4830		rc = 0;
4831	}
4832done:
4833	if (rc != 0 && sc->flags & FW_OK) {
4834		t4_fw_bye(sc, sc->mbox);
4835		sc->flags &= ~FW_OK;
4836	}
4837	free(card_fw, M_CXGBE);
4838	return (rc);
4839}
4840
4841static int
4842copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4843    uint32_t mtype, uint32_t moff)
4844{
4845	struct fw_info *fw_info;
4846	const struct firmware *dcfg, *rcfg = NULL;
4847	const uint32_t *cfdata;
4848	uint32_t cflen, addr;
4849	int rc;
4850
4851	load_fw_module(sc, &dcfg, NULL);
4852
4853	/* Card specific interpretation of "default". */
4854	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4855		if (pci_get_device(sc->dev) == 0x440a)
4856			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4857		if (is_fpga(sc))
4858			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4859	}
4860
4861	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4862		if (dcfg == NULL) {
4863			device_printf(sc->dev,
4864			    "KLD with default config is not available.\n");
4865			rc = ENOENT;
4866			goto done;
4867		}
4868		cfdata = dcfg->data;
4869		cflen = dcfg->datasize & ~3;
4870	} else {
4871		char s[32];
4872
4873		fw_info = find_fw_info(chip_id(sc));
4874		if (fw_info == NULL) {
4875			device_printf(sc->dev,
4876			    "unable to look up firmware information for chip %d.\n",
4877			    chip_id(sc));
4878			rc = EINVAL;
4879			goto done;
4880		}
4881		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4882
4883		rcfg = firmware_get(s);
4884		if (rcfg == NULL) {
4885			device_printf(sc->dev,
4886			    "unable to load module \"%s\" for configuration "
4887			    "profile \"%s\".\n", s, cfg_file);
4888			rc = ENOENT;
4889			goto done;
4890		}
4891		cfdata = rcfg->data;
4892		cflen = rcfg->datasize & ~3;
4893	}
4894
4895	if (cflen > FLASH_CFG_MAX_SIZE) {
4896		device_printf(sc->dev,
4897		    "config file too long (%d, max allowed is %d).\n",
4898		    cflen, FLASH_CFG_MAX_SIZE);
4899		rc = EINVAL;
4900		goto done;
4901	}
4902
4903	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4904	if (rc != 0) {
4905		device_printf(sc->dev,
4906		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4907		    __func__, mtype, moff, cflen, rc);
4908		rc = EINVAL;
4909		goto done;
4910	}
4911	write_via_memwin(sc, 2, addr, cfdata, cflen);
4912done:
4913	if (rcfg != NULL)
4914		firmware_put(rcfg, FIRMWARE_UNLOAD);
4915	unload_fw_module(sc, dcfg, NULL);
4916	return (rc);
4917}
4918
4919struct caps_allowed {
4920	uint16_t nbmcaps;
4921	uint16_t linkcaps;
4922	uint16_t switchcaps;
4923	uint16_t niccaps;
4924	uint16_t toecaps;
4925	uint16_t rdmacaps;
4926	uint16_t cryptocaps;
4927	uint16_t iscsicaps;
4928	uint16_t fcoecaps;
4929};
4930
4931#define FW_PARAM_DEV(param) \
4932	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4933	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4934#define FW_PARAM_PFVF(param) \
4935	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4936	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4937
4938/*
4939 * Provide a configuration profile to the firmware and have it initialize the
4940 * chip accordingly.  This may involve uploading a configuration file to the
4941 * card.
4942 */
4943static int
4944apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4945    const struct caps_allowed *caps_allowed)
4946{
4947	int rc;
4948	struct fw_caps_config_cmd caps;
4949	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4950
4951	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4952	if (rc != 0) {
4953		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4954		return (rc);
4955	}
4956
4957	bzero(&caps, sizeof(caps));
4958	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4959	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4960	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4961		mtype = 0;
4962		moff = 0;
4963		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4964	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4965		mtype = FW_MEMTYPE_FLASH;
4966		moff = t4_flash_cfg_addr(sc);
4967		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4968		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4969		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4970		    FW_LEN16(caps));
4971	} else {
4972		/*
4973		 * Ask the firmware where it wants us to upload the config file.
4974		 */
4975		param = FW_PARAM_DEV(CF);
4976		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4977		if (rc != 0) {
4978			/* No support for config file?  Shouldn't happen. */
4979			device_printf(sc->dev,
4980			    "failed to query config file location: %d.\n", rc);
4981			goto done;
4982		}
4983		mtype = G_FW_PARAMS_PARAM_Y(val);
4984		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4985		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4986		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4987		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4988		    FW_LEN16(caps));
4989
4990		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4991		if (rc != 0) {
4992			device_printf(sc->dev,
4993			    "failed to upload config file to card: %d.\n", rc);
4994			goto done;
4995		}
4996	}
4997	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4998	if (rc != 0) {
4999		device_printf(sc->dev, "failed to pre-process config file: %d "
5000		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5001		goto done;
5002	}
5003
5004	finicsum = be32toh(caps.finicsum);
5005	cfcsum = be32toh(caps.cfcsum);	/* actual */
5006	if (finicsum != cfcsum) {
5007		device_printf(sc->dev,
5008		    "WARNING: config file checksum mismatch: %08x %08x\n",
5009		    finicsum, cfcsum);
5010	}
5011	sc->cfcsum = cfcsum;
5012	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5013
5014	/*
5015	 * Let the firmware know what features will (not) be used so it can tune
5016	 * things accordingly.
5017	 */
5018#define LIMIT_CAPS(x) do { \
5019	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5020} while (0)
5021	LIMIT_CAPS(nbm);
5022	LIMIT_CAPS(link);
5023	LIMIT_CAPS(switch);
5024	LIMIT_CAPS(nic);
5025	LIMIT_CAPS(toe);
5026	LIMIT_CAPS(rdma);
5027	LIMIT_CAPS(crypto);
5028	LIMIT_CAPS(iscsi);
5029	LIMIT_CAPS(fcoe);
5030#undef LIMIT_CAPS
5031	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5032		/*
5033		 * TOE and hashfilters are mutually exclusive.  It is a config
5034		 * file or firmware bug if both are reported as available.  Try
5035		 * to cope with the situation in non-debug builds by disabling
5036		 * TOE.
5037		 */
5038		MPASS(caps.toecaps == 0);
5039
5040		caps.toecaps = 0;
5041		caps.rdmacaps = 0;
5042		caps.iscsicaps = 0;
5043	}
5044
5045	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5046	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5047	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5048	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5049	if (rc != 0) {
5050		device_printf(sc->dev,
5051		    "failed to process config file: %d.\n", rc);
5052		goto done;
5053	}
5054
5055	t4_tweak_chip_settings(sc);
5056	set_params__pre_init(sc);
5057
5058	/* get basic stuff going */
5059	rc = -t4_fw_initialize(sc, sc->mbox);
5060	if (rc != 0) {
5061		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5062		goto done;
5063	}
5064done:
5065	return (rc);
5066}
5067
5068/*
5069 * Partition chip resources for use between various PFs, VFs, etc.
5070 */
5071static int
5072partition_resources(struct adapter *sc)
5073{
5074	char cfg_file[sizeof(t4_cfg_file)];
5075	struct caps_allowed caps_allowed;
5076	int rc;
5077	bool fallback;
5078
5079	/* Only the master driver gets to configure the chip resources. */
5080	MPASS(sc->flags & MASTER_PF);
5081
5082#define COPY_CAPS(x) do { \
5083	caps_allowed.x##caps = t4_##x##caps_allowed; \
5084} while (0)
5085	bzero(&caps_allowed, sizeof(caps_allowed));
5086	COPY_CAPS(nbm);
5087	COPY_CAPS(link);
5088	COPY_CAPS(switch);
5089	COPY_CAPS(nic);
5090	COPY_CAPS(toe);
5091	COPY_CAPS(rdma);
5092	COPY_CAPS(crypto);
5093	COPY_CAPS(iscsi);
5094	COPY_CAPS(fcoe);
5095	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5096	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5097retry:
5098	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5099	if (rc != 0 && fallback) {
5100		dump_devlog(sc);
5101		device_printf(sc->dev,
5102		    "failed (%d) to configure card with \"%s\" profile, "
5103		    "will fall back to a basic configuration and retry.\n",
5104		    rc, cfg_file);
5105		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5106		bzero(&caps_allowed, sizeof(caps_allowed));
5107		COPY_CAPS(switch);
5108		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5109		fallback = false;
5110		goto retry;
5111	}
5112#undef COPY_CAPS
5113	return (rc);
5114}
5115
5116/*
5117 * Retrieve parameters that are needed (or nice to have) very early.
5118 */
5119static int
5120get_params__pre_init(struct adapter *sc)
5121{
5122	int rc;
5123	uint32_t param[2], val[2];
5124
5125	t4_get_version_info(sc);
5126
5127	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5128	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5129	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5130	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5131	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5132
5133	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5134	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5135	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5136	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5137	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5138
5139	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5140	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5141	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5142	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5143	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5144
5145	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5146	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5147	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5148	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5149	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5150
5151	param[0] = FW_PARAM_DEV(PORTVEC);
5152	param[1] = FW_PARAM_DEV(CCLK);
5153	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5154	if (rc != 0) {
5155		device_printf(sc->dev,
5156		    "failed to query parameters (pre_init): %d.\n", rc);
5157		return (rc);
5158	}
5159
5160	sc->params.portvec = val[0];
5161	sc->params.nports = bitcount32(val[0]);
5162	sc->params.vpd.cclk = val[1];
5163
5164	/* Read device log parameters. */
5165	rc = -t4_init_devlog_params(sc, 1);
5166	if (rc == 0)
5167		fixup_devlog_params(sc);
5168	else {
5169		device_printf(sc->dev,
5170		    "failed to get devlog parameters: %d.\n", rc);
5171		rc = 0;	/* devlog isn't critical for device operation */
5172	}
5173
5174	return (rc);
5175}
5176
5177/*
5178 * Any params that need to be set before FW_INITIALIZE.
5179 */
5180static int
5181set_params__pre_init(struct adapter *sc)
5182{
5183	int rc = 0;
5184	uint32_t param, val;
5185
5186	if (chip_id(sc) >= CHELSIO_T6) {
5187		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5188		val = 1;
5189		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5190		/* firmwares < 1.20.1.0 do not have this param. */
5191		if (rc == FW_EINVAL &&
5192		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5193			rc = 0;
5194		}
5195		if (rc != 0) {
5196			device_printf(sc->dev,
5197			    "failed to enable high priority filters :%d.\n",
5198			    rc);
5199		}
5200
5201		param = FW_PARAM_DEV(PPOD_EDRAM);
5202		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5203		if (rc == 0 && val == 1) {
5204			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5205			    &val);
5206			if (rc != 0) {
5207				device_printf(sc->dev,
5208				    "failed to set PPOD_EDRAM: %d.\n", rc);
5209			}
5210		}
5211	}
5212
5213	/* Enable opaque VIIDs with firmwares that support it. */
5214	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5215	val = 1;
5216	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5217	if (rc == 0 && val == 1)
5218		sc->params.viid_smt_extn_support = true;
5219	else
5220		sc->params.viid_smt_extn_support = false;
5221
5222	return (rc);
5223}
5224
5225/*
5226 * Retrieve various parameters that are of interest to the driver.  The device
5227 * has been initialized by the firmware at this point.
5228 */
5229static int
5230get_params__post_init(struct adapter *sc)
5231{
5232	int rc;
5233	uint32_t param[7], val[7];
5234	struct fw_caps_config_cmd caps;
5235
5236	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5237	param[1] = FW_PARAM_PFVF(EQ_START);
5238	param[2] = FW_PARAM_PFVF(FILTER_START);
5239	param[3] = FW_PARAM_PFVF(FILTER_END);
5240	param[4] = FW_PARAM_PFVF(L2T_START);
5241	param[5] = FW_PARAM_PFVF(L2T_END);
5242	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5243	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5244	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5245	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5246	if (rc != 0) {
5247		device_printf(sc->dev,
5248		    "failed to query parameters (post_init): %d.\n", rc);
5249		return (rc);
5250	}
5251
5252	sc->sge.iq_start = val[0];
5253	sc->sge.eq_start = val[1];
5254	if ((int)val[3] > (int)val[2]) {
5255		sc->tids.ftid_base = val[2];
5256		sc->tids.ftid_end = val[3];
5257		sc->tids.nftids = val[3] - val[2] + 1;
5258	}
5259	sc->vres.l2t.start = val[4];
5260	sc->vres.l2t.size = val[5] - val[4] + 1;
5261	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5262	    ("%s: L2 table size (%u) larger than expected (%u)",
5263	    __func__, sc->vres.l2t.size, L2T_SIZE));
5264	sc->params.core_vdd = val[6];
5265
5266	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5267	param[1] = FW_PARAM_PFVF(EQ_END);
5268	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5269	if (rc != 0) {
5270		device_printf(sc->dev,
5271		    "failed to query parameters (post_init2): %d.\n", rc);
5272		return (rc);
5273	}
5274	MPASS((int)val[0] >= sc->sge.iq_start);
5275	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5276	MPASS((int)val[1] >= sc->sge.eq_start);
5277	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5278
5279	if (chip_id(sc) >= CHELSIO_T6) {
5280
5281		sc->tids.tid_base = t4_read_reg(sc,
5282		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5283
5284		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5285		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5286		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5287		if (rc != 0) {
5288			device_printf(sc->dev,
5289			   "failed to query hpfilter parameters: %d.\n", rc);
5290			return (rc);
5291		}
5292		if ((int)val[1] > (int)val[0]) {
5293			sc->tids.hpftid_base = val[0];
5294			sc->tids.hpftid_end = val[1];
5295			sc->tids.nhpftids = val[1] - val[0] + 1;
5296
5297			/*
5298			 * These should go off if the layout changes and the
5299			 * driver needs to catch up.
5300			 */
5301			MPASS(sc->tids.hpftid_base == 0);
5302			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5303		}
5304
5305		param[0] = FW_PARAM_PFVF(RAWF_START);
5306		param[1] = FW_PARAM_PFVF(RAWF_END);
5307		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5308		if (rc != 0) {
5309			device_printf(sc->dev,
5310			   "failed to query rawf parameters: %d.\n", rc);
5311			return (rc);
5312		}
5313		if ((int)val[1] > (int)val[0]) {
5314			sc->rawf_base = val[0];
5315			sc->nrawf = val[1] - val[0] + 1;
5316		}
5317	}
5318
5319	/*
5320	 * The parameters that follow may not be available on all firmwares.  We
5321	 * query them individually rather than in a compound query because old
5322	 * firmwares fail the entire query if an unknown parameter is queried.
5323	 */
5324
5325	/*
5326	 * MPS buffer group configuration.
5327	 */
5328	param[0] = FW_PARAM_DEV(MPSBGMAP);
5329	val[0] = 0;
5330	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5331	if (rc == 0)
5332		sc->params.mps_bg_map = val[0];
5333	else
5334		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5335
5336	param[0] = FW_PARAM_DEV(TPCHMAP);
5337	val[0] = 0;
5338	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5339	if (rc == 0)
5340		sc->params.tp_ch_map = val[0];
5341	else
5342		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5343
5344	/*
5345	 * Determine whether the firmware supports the filter2 work request.
5346	 */
5347	param[0] = FW_PARAM_DEV(FILTER2_WR);
5348	val[0] = 0;
5349	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5350	if (rc == 0)
5351		sc->params.filter2_wr_support = val[0] != 0;
5352	else
5353		sc->params.filter2_wr_support = 0;
5354
5355	/*
5356	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5357	 */
5358	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5359	val[0] = 0;
5360	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5361	if (rc == 0)
5362		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5363	else
5364		sc->params.ulptx_memwrite_dsgl = false;
5365
5366	/* FW_RI_FR_NSMR_TPTE_WR support */
5367	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5368	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5369	if (rc == 0)
5370		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5371	else
5372		sc->params.fr_nsmr_tpte_wr_support = false;
5373
5374	/* Support for 512 SGL entries per FR MR. */
5375	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5376	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5377	if (rc == 0)
5378		sc->params.dev_512sgl_mr = val[0] != 0;
5379	else
5380		sc->params.dev_512sgl_mr = false;
5381
5382	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5383	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5384	if (rc == 0)
5385		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5386	else
5387		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5388
5389	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5390	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5391	if (rc == 0) {
5392		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5393		sc->params.nsched_cls = val[0];
5394	} else
5395		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5396
5397	/* get capabilites */
5398	bzero(&caps, sizeof(caps));
5399	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5400	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5401	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5402	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5403	if (rc != 0) {
5404		device_printf(sc->dev,
5405		    "failed to get card capabilities: %d.\n", rc);
5406		return (rc);
5407	}
5408
5409#define READ_CAPS(x) do { \
5410	sc->x = htobe16(caps.x); \
5411} while (0)
5412	READ_CAPS(nbmcaps);
5413	READ_CAPS(linkcaps);
5414	READ_CAPS(switchcaps);
5415	READ_CAPS(niccaps);
5416	READ_CAPS(toecaps);
5417	READ_CAPS(rdmacaps);
5418	READ_CAPS(cryptocaps);
5419	READ_CAPS(iscsicaps);
5420	READ_CAPS(fcoecaps);
5421
5422	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5423		MPASS(chip_id(sc) > CHELSIO_T4);
5424		MPASS(sc->toecaps == 0);
5425		sc->toecaps = 0;
5426
5427		param[0] = FW_PARAM_DEV(NTID);
5428		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5429		if (rc != 0) {
5430			device_printf(sc->dev,
5431			    "failed to query HASHFILTER parameters: %d.\n", rc);
5432			return (rc);
5433		}
5434		sc->tids.ntids = val[0];
5435		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5436			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5437			sc->tids.ntids -= sc->tids.nhpftids;
5438		}
5439		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5440		sc->params.hash_filter = 1;
5441	}
5442	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5443		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5444		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5445		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5446		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5447		if (rc != 0) {
5448			device_printf(sc->dev,
5449			    "failed to query NIC parameters: %d.\n", rc);
5450			return (rc);
5451		}
5452		if ((int)val[1] > (int)val[0]) {
5453			sc->tids.etid_base = val[0];
5454			sc->tids.etid_end = val[1];
5455			sc->tids.netids = val[1] - val[0] + 1;
5456			sc->params.eo_wr_cred = val[2];
5457			sc->params.ethoffload = 1;
5458		}
5459	}
5460	if (sc->toecaps) {
5461		/* query offload-related parameters */
5462		param[0] = FW_PARAM_DEV(NTID);
5463		param[1] = FW_PARAM_PFVF(SERVER_START);
5464		param[2] = FW_PARAM_PFVF(SERVER_END);
5465		param[3] = FW_PARAM_PFVF(TDDP_START);
5466		param[4] = FW_PARAM_PFVF(TDDP_END);
5467		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5468		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5469		if (rc != 0) {
5470			device_printf(sc->dev,
5471			    "failed to query TOE parameters: %d.\n", rc);
5472			return (rc);
5473		}
5474		sc->tids.ntids = val[0];
5475		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5476			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5477			sc->tids.ntids -= sc->tids.nhpftids;
5478		}
5479		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5480		if ((int)val[2] > (int)val[1]) {
5481			sc->tids.stid_base = val[1];
5482			sc->tids.nstids = val[2] - val[1] + 1;
5483		}
5484		sc->vres.ddp.start = val[3];
5485		sc->vres.ddp.size = val[4] - val[3] + 1;
5486		sc->params.ofldq_wr_cred = val[5];
5487		sc->params.offload = 1;
5488	} else {
5489		/*
5490		 * The firmware attempts memfree TOE configuration for -SO cards
5491		 * and will report toecaps=0 if it runs out of resources (this
5492		 * depends on the config file).  It may not report 0 for other
5493		 * capabilities dependent on the TOE in this case.  Set them to
5494		 * 0 here so that the driver doesn't bother tracking resources
5495		 * that will never be used.
5496		 */
5497		sc->iscsicaps = 0;
5498		sc->rdmacaps = 0;
5499	}
5500	if (sc->rdmacaps) {
5501		param[0] = FW_PARAM_PFVF(STAG_START);
5502		param[1] = FW_PARAM_PFVF(STAG_END);
5503		param[2] = FW_PARAM_PFVF(RQ_START);
5504		param[3] = FW_PARAM_PFVF(RQ_END);
5505		param[4] = FW_PARAM_PFVF(PBL_START);
5506		param[5] = FW_PARAM_PFVF(PBL_END);
5507		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5508		if (rc != 0) {
5509			device_printf(sc->dev,
5510			    "failed to query RDMA parameters(1): %d.\n", rc);
5511			return (rc);
5512		}
5513		sc->vres.stag.start = val[0];
5514		sc->vres.stag.size = val[1] - val[0] + 1;
5515		sc->vres.rq.start = val[2];
5516		sc->vres.rq.size = val[3] - val[2] + 1;
5517		sc->vres.pbl.start = val[4];
5518		sc->vres.pbl.size = val[5] - val[4] + 1;
5519
5520		param[0] = FW_PARAM_PFVF(SQRQ_START);
5521		param[1] = FW_PARAM_PFVF(SQRQ_END);
5522		param[2] = FW_PARAM_PFVF(CQ_START);
5523		param[3] = FW_PARAM_PFVF(CQ_END);
5524		param[4] = FW_PARAM_PFVF(OCQ_START);
5525		param[5] = FW_PARAM_PFVF(OCQ_END);
5526		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5527		if (rc != 0) {
5528			device_printf(sc->dev,
5529			    "failed to query RDMA parameters(2): %d.\n", rc);
5530			return (rc);
5531		}
5532		sc->vres.qp.start = val[0];
5533		sc->vres.qp.size = val[1] - val[0] + 1;
5534		sc->vres.cq.start = val[2];
5535		sc->vres.cq.size = val[3] - val[2] + 1;
5536		sc->vres.ocq.start = val[4];
5537		sc->vres.ocq.size = val[5] - val[4] + 1;
5538
5539		param[0] = FW_PARAM_PFVF(SRQ_START);
5540		param[1] = FW_PARAM_PFVF(SRQ_END);
5541		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5542		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5543		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5544		if (rc != 0) {
5545			device_printf(sc->dev,
5546			    "failed to query RDMA parameters(3): %d.\n", rc);
5547			return (rc);
5548		}
5549		sc->vres.srq.start = val[0];
5550		sc->vres.srq.size = val[1] - val[0] + 1;
5551		sc->params.max_ordird_qp = val[2];
5552		sc->params.max_ird_adapter = val[3];
5553	}
5554	if (sc->iscsicaps) {
5555		param[0] = FW_PARAM_PFVF(ISCSI_START);
5556		param[1] = FW_PARAM_PFVF(ISCSI_END);
5557		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5558		if (rc != 0) {
5559			device_printf(sc->dev,
5560			    "failed to query iSCSI parameters: %d.\n", rc);
5561			return (rc);
5562		}
5563		sc->vres.iscsi.start = val[0];
5564		sc->vres.iscsi.size = val[1] - val[0] + 1;
5565	}
5566	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5567		param[0] = FW_PARAM_PFVF(TLS_START);
5568		param[1] = FW_PARAM_PFVF(TLS_END);
5569		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5570		if (rc != 0) {
5571			device_printf(sc->dev,
5572			    "failed to query TLS parameters: %d.\n", rc);
5573			return (rc);
5574		}
5575		sc->vres.key.start = val[0];
5576		sc->vres.key.size = val[1] - val[0] + 1;
5577	}
5578
5579	/*
5580	 * We've got the params we wanted to query directly from the firmware.
5581	 * Grab some others via other means.
5582	 */
5583	t4_init_sge_params(sc);
5584	t4_init_tp_params(sc);
5585	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5586	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5587
5588	rc = t4_verify_chip_settings(sc);
5589	if (rc != 0)
5590		return (rc);
5591	t4_init_rx_buf_info(sc);
5592
5593	return (rc);
5594}
5595
5596#ifdef KERN_TLS
5597static void
5598ktls_tick(void *arg)
5599{
5600	struct adapter *sc;
5601	uint32_t tstamp;
5602
5603	sc = arg;
5604	tstamp = tcp_ts_getticks();
5605	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5606	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5607	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5608}
5609
5610static int
5611t6_config_kern_tls(struct adapter *sc, bool enable)
5612{
5613	int rc;
5614	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5615	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5616	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5617	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5618
5619	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5620	if (rc != 0) {
5621		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5622		    enable ?  "enable" : "disable", rc);
5623		return (rc);
5624	}
5625
5626	if (enable) {
5627		sc->flags |= KERN_TLS_ON;
5628		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5629		    C_HARDCLOCK);
5630	} else {
5631		sc->flags &= ~KERN_TLS_ON;
5632		callout_stop(&sc->ktls_tick);
5633	}
5634
5635	return (rc);
5636}
5637#endif
5638
5639static int
5640set_params__post_init(struct adapter *sc)
5641{
5642	uint32_t mask, param, val;
5643#ifdef TCP_OFFLOAD
5644	int i, v, shift;
5645#endif
5646
5647	/* ask for encapsulated CPLs */
5648	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5649	val = 1;
5650	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5651
5652	/* Enable 32b port caps if the firmware supports it. */
5653	param = FW_PARAM_PFVF(PORT_CAPS32);
5654	val = 1;
5655	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5656		sc->params.port_caps32 = 1;
5657
5658	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5659	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5660	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5661	    V_MASKFILTER(val - 1));
5662
5663	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5664	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5665	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5666	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5667	val = 0;
5668	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5669		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5670		    F_ATTACKFILTERENABLE);
5671		val |= F_DROPERRORATTACK;
5672	}
5673	if (t4_drop_ip_fragments != 0) {
5674		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5675		    F_FRAGMENTDROP);
5676		val |= F_DROPERRORFRAG;
5677	}
5678	if (t4_drop_pkts_with_l2_errors != 0)
5679		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5680	if (t4_drop_pkts_with_l3_errors != 0) {
5681		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5682		    F_DROPERRORCSUMIP;
5683	}
5684	if (t4_drop_pkts_with_l4_errors != 0) {
5685		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5686		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5687	}
5688	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5689
5690#ifdef TCP_OFFLOAD
5691	/*
5692	 * Override the TOE timers with user provided tunables.  This is not the
5693	 * recommended way to change the timers (the firmware config file is) so
5694	 * these tunables are not documented.
5695	 *
5696	 * All the timer tunables are in microseconds.
5697	 */
5698	if (t4_toe_keepalive_idle != 0) {
5699		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5700		v &= M_KEEPALIVEIDLE;
5701		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5702		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5703	}
5704	if (t4_toe_keepalive_interval != 0) {
5705		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5706		v &= M_KEEPALIVEINTVL;
5707		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5708		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5709	}
5710	if (t4_toe_keepalive_count != 0) {
5711		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5712		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5713		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5714		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5715		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5716	}
5717	if (t4_toe_rexmt_min != 0) {
5718		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5719		v &= M_RXTMIN;
5720		t4_set_reg_field(sc, A_TP_RXT_MIN,
5721		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5722	}
5723	if (t4_toe_rexmt_max != 0) {
5724		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5725		v &= M_RXTMAX;
5726		t4_set_reg_field(sc, A_TP_RXT_MAX,
5727		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5728	}
5729	if (t4_toe_rexmt_count != 0) {
5730		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5731		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5732		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5733		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5734		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5735	}
5736	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5737		if (t4_toe_rexmt_backoff[i] != -1) {
5738			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5739			shift = (i & 3) << 3;
5740			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5741			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5742		}
5743	}
5744#endif
5745
5746	/*
5747	 * Limit TOE connections to 2 reassembly "islands".  This is
5748	 * required to permit migrating TOE connections to either
5749	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5750	 */
5751	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5752	    V_PASSMODE(2));
5753
5754#ifdef KERN_TLS
5755	if (is_ktls(sc)) {
5756		sc->tlst.inline_keys = t4_tls_inline_keys;
5757		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5758		if (t4_kern_tls != 0 && is_t6(sc))
5759			t6_config_kern_tls(sc, true);
5760	}
5761#endif
5762	return (0);
5763}
5764
5765#undef FW_PARAM_PFVF
5766#undef FW_PARAM_DEV
5767
5768static void
5769t4_set_desc(struct adapter *sc)
5770{
5771	char buf[128];
5772	struct adapter_params *p = &sc->params;
5773
5774	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5775
5776	device_set_desc_copy(sc->dev, buf);
5777}
5778
5779static inline void
5780ifmedia_add4(struct ifmedia *ifm, int m)
5781{
5782
5783	ifmedia_add(ifm, m, 0, NULL);
5784	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5785	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5786	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5787}
5788
5789/*
5790 * This is the selected media, which is not quite the same as the active media.
5791 * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5792 * and active are not the same, and "media: Ethernet selected" otherwise.
5793 */
5794static void
5795set_current_media(struct port_info *pi)
5796{
5797	struct link_config *lc;
5798	struct ifmedia *ifm;
5799	int mword;
5800	u_int speed;
5801
5802	PORT_LOCK_ASSERT_OWNED(pi);
5803
5804	/* Leave current media alone if it's already set to IFM_NONE. */
5805	ifm = &pi->media;
5806	if (ifm->ifm_cur != NULL &&
5807	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5808		return;
5809
5810	lc = &pi->link_cfg;
5811	if (lc->requested_aneg != AUTONEG_DISABLE &&
5812	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5813		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5814		return;
5815	}
5816	mword = IFM_ETHER | IFM_FDX;
5817	if (lc->requested_fc & PAUSE_TX)
5818		mword |= IFM_ETH_TXPAUSE;
5819	if (lc->requested_fc & PAUSE_RX)
5820		mword |= IFM_ETH_RXPAUSE;
5821	if (lc->requested_speed == 0)
5822		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5823	else
5824		speed = lc->requested_speed;
5825	mword |= port_mword(pi, speed_to_fwcap(speed));
5826	ifmedia_set(ifm, mword);
5827}
5828
5829/*
5830 * Returns true if the ifmedia list for the port cannot change.
5831 */
5832static bool
5833fixed_ifmedia(struct port_info *pi)
5834{
5835
5836	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5837	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5838	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5839	    pi->port_type == FW_PORT_TYPE_KX4 ||
5840	    pi->port_type == FW_PORT_TYPE_KX ||
5841	    pi->port_type == FW_PORT_TYPE_KR ||
5842	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5843	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5844	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5845	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5846	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5847	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5848}
5849
5850static void
5851build_medialist(struct port_info *pi)
5852{
5853	uint32_t ss, speed;
5854	int unknown, mword, bit;
5855	struct link_config *lc;
5856	struct ifmedia *ifm;
5857
5858	PORT_LOCK_ASSERT_OWNED(pi);
5859
5860	if (pi->flags & FIXED_IFMEDIA)
5861		return;
5862
5863	/*
5864	 * Rebuild the ifmedia list.
5865	 */
5866	ifm = &pi->media;
5867	ifmedia_removeall(ifm);
5868	lc = &pi->link_cfg;
5869	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5870	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5871		MPASS(ss != 0);
5872no_media:
5873		MPASS(LIST_EMPTY(&ifm->ifm_list));
5874		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5875		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5876		return;
5877	}
5878
5879	unknown = 0;
5880	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5881		speed = 1 << bit;
5882		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5883		if (ss & speed) {
5884			mword = port_mword(pi, speed);
5885			if (mword == IFM_NONE) {
5886				goto no_media;
5887			} else if (mword == IFM_UNKNOWN)
5888				unknown++;
5889			else
5890				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5891		}
5892	}
5893	if (unknown > 0) /* Add one unknown for all unknown media types. */
5894		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5895	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5896		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5897
5898	set_current_media(pi);
5899}
5900
5901/*
5902 * Initialize the requested fields in the link config based on driver tunables.
5903 */
5904static void
5905init_link_config(struct port_info *pi)
5906{
5907	struct link_config *lc = &pi->link_cfg;
5908
5909	PORT_LOCK_ASSERT_OWNED(pi);
5910
5911	lc->requested_caps = 0;
5912	lc->requested_speed = 0;
5913
5914	if (t4_autoneg == 0)
5915		lc->requested_aneg = AUTONEG_DISABLE;
5916	else if (t4_autoneg == 1)
5917		lc->requested_aneg = AUTONEG_ENABLE;
5918	else
5919		lc->requested_aneg = AUTONEG_AUTO;
5920
5921	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5922	    PAUSE_AUTONEG);
5923
5924	if (t4_fec & FEC_AUTO)
5925		lc->requested_fec = FEC_AUTO;
5926	else if (t4_fec == 0)
5927		lc->requested_fec = FEC_NONE;
5928	else {
5929		/* -1 is handled by the FEC_AUTO block above and not here. */
5930		lc->requested_fec = t4_fec &
5931		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5932		if (lc->requested_fec == 0)
5933			lc->requested_fec = FEC_AUTO;
5934	}
5935	if (t4_force_fec < 0)
5936		lc->force_fec = -1;
5937	else if (t4_force_fec > 0)
5938		lc->force_fec = 1;
5939	else
5940		lc->force_fec = 0;
5941}
5942
5943/*
5944 * Makes sure that all requested settings comply with what's supported by the
5945 * port.  Returns the number of settings that were invalid and had to be fixed.
5946 */
5947static int
5948fixup_link_config(struct port_info *pi)
5949{
5950	int n = 0;
5951	struct link_config *lc = &pi->link_cfg;
5952	uint32_t fwspeed;
5953
5954	PORT_LOCK_ASSERT_OWNED(pi);
5955
5956	/* Speed (when not autonegotiating) */
5957	if (lc->requested_speed != 0) {
5958		fwspeed = speed_to_fwcap(lc->requested_speed);
5959		if ((fwspeed & lc->pcaps) == 0) {
5960			n++;
5961			lc->requested_speed = 0;
5962		}
5963	}
5964
5965	/* Link autonegotiation */
5966	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5967	    lc->requested_aneg == AUTONEG_DISABLE ||
5968	    lc->requested_aneg == AUTONEG_AUTO);
5969	if (lc->requested_aneg == AUTONEG_ENABLE &&
5970	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5971		n++;
5972		lc->requested_aneg = AUTONEG_AUTO;
5973	}
5974
5975	/* Flow control */
5976	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5977	if (lc->requested_fc & PAUSE_TX &&
5978	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5979		n++;
5980		lc->requested_fc &= ~PAUSE_TX;
5981	}
5982	if (lc->requested_fc & PAUSE_RX &&
5983	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5984		n++;
5985		lc->requested_fc &= ~PAUSE_RX;
5986	}
5987	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5988	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5989		n++;
5990		lc->requested_fc |= PAUSE_AUTONEG;
5991	}
5992
5993	/* FEC */
5994	if ((lc->requested_fec & FEC_RS &&
5995	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5996	    (lc->requested_fec & FEC_BASER_RS &&
5997	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5998		n++;
5999		lc->requested_fec = FEC_AUTO;
6000	}
6001
6002	return (n);
6003}
6004
6005/*
6006 * Apply the requested L1 settings, which are expected to be valid, to the
6007 * hardware.
6008 */
6009static int
6010apply_link_config(struct port_info *pi)
6011{
6012	struct adapter *sc = pi->adapter;
6013	struct link_config *lc = &pi->link_cfg;
6014	int rc;
6015
6016#ifdef INVARIANTS
6017	ASSERT_SYNCHRONIZED_OP(sc);
6018	PORT_LOCK_ASSERT_OWNED(pi);
6019
6020	if (lc->requested_aneg == AUTONEG_ENABLE)
6021		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6022	if (!(lc->requested_fc & PAUSE_AUTONEG))
6023		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6024	if (lc->requested_fc & PAUSE_TX)
6025		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6026	if (lc->requested_fc & PAUSE_RX)
6027		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6028	if (lc->requested_fec & FEC_RS)
6029		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6030	if (lc->requested_fec & FEC_BASER_RS)
6031		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6032#endif
6033	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6034	if (rc != 0) {
6035		/* Don't complain if the VF driver gets back an EPERM. */
6036		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
6037			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6038	} else {
6039		/*
6040		 * An L1_CFG will almost always result in a link-change event if
6041		 * the link is up, and the driver will refresh the actual
6042		 * fec/fc/etc. when the notification is processed.  If the link
6043		 * is down then the actual settings are meaningless.
6044		 *
6045		 * This takes care of the case where a change in the L1 settings
6046		 * may not result in a notification.
6047		 */
6048		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6049			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6050	}
6051	return (rc);
6052}
6053
6054#define FW_MAC_EXACT_CHUNK	7
6055struct mcaddr_ctx {
6056	if_t ifp;
6057	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6058	uint64_t hash;
6059	int i;
6060	int del;
6061	int rc;
6062};
6063
6064static u_int
6065add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6066{
6067	struct mcaddr_ctx *ctx = arg;
6068	struct vi_info *vi = if_getsoftc(ctx->ifp);
6069	struct port_info *pi = vi->pi;
6070	struct adapter *sc = pi->adapter;
6071
6072	if (ctx->rc < 0)
6073		return (0);
6074
6075	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6076	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6077	ctx->i++;
6078
6079	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6080		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6081		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6082		if (ctx->rc < 0) {
6083			int j;
6084
6085			for (j = 0; j < ctx->i; j++) {
6086				if_printf(ctx->ifp,
6087				    "failed to add mc address"
6088				    " %02x:%02x:%02x:"
6089				    "%02x:%02x:%02x rc=%d\n",
6090				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6091				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6092				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6093				    -ctx->rc);
6094			}
6095			return (0);
6096		}
6097		ctx->del = 0;
6098		ctx->i = 0;
6099	}
6100
6101	return (1);
6102}
6103
6104/*
6105 * Program the port's XGMAC based on parameters in ifnet.  The caller also
6106 * indicates which parameters should be programmed (the rest are left alone).
6107 */
6108int
6109update_mac_settings(if_t ifp, int flags)
6110{
6111	int rc = 0;
6112	struct vi_info *vi = if_getsoftc(ifp);
6113	struct port_info *pi = vi->pi;
6114	struct adapter *sc = pi->adapter;
6115	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6116	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6117
6118	ASSERT_SYNCHRONIZED_OP(sc);
6119	KASSERT(flags, ("%s: not told what to update.", __func__));
6120
6121	if (flags & XGMAC_MTU)
6122		mtu = if_getmtu(ifp);
6123
6124	if (flags & XGMAC_PROMISC)
6125		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6126
6127	if (flags & XGMAC_ALLMULTI)
6128		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6129
6130	if (flags & XGMAC_VLANEX)
6131		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6132
6133	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6134		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6135		    allmulti, 1, vlanex, false);
6136		if (rc) {
6137			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6138			    rc);
6139			return (rc);
6140		}
6141	}
6142
6143	if (flags & XGMAC_UCADDR) {
6144		uint8_t ucaddr[ETHER_ADDR_LEN];
6145
6146		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6147		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6148		    ucaddr, true, &vi->smt_idx);
6149		if (rc < 0) {
6150			rc = -rc;
6151			if_printf(ifp, "change_mac failed: %d\n", rc);
6152			return (rc);
6153		} else {
6154			vi->xact_addr_filt = rc;
6155			rc = 0;
6156		}
6157	}
6158
6159	if (flags & XGMAC_MCADDRS) {
6160		struct epoch_tracker et;
6161		struct mcaddr_ctx ctx;
6162		int j;
6163
6164		ctx.ifp = ifp;
6165		ctx.hash = 0;
6166		ctx.i = 0;
6167		ctx.del = 1;
6168		ctx.rc = 0;
6169		/*
6170		 * Unlike other drivers, we accumulate list of pointers into
6171		 * interface address lists and we need to keep it safe even
6172		 * after if_foreach_llmaddr() returns, thus we must enter the
6173		 * network epoch.
6174		 */
6175		NET_EPOCH_ENTER(et);
6176		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6177		if (ctx.rc < 0) {
6178			NET_EPOCH_EXIT(et);
6179			rc = -ctx.rc;
6180			return (rc);
6181		}
6182		if (ctx.i > 0) {
6183			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6184			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6185			NET_EPOCH_EXIT(et);
6186			if (rc < 0) {
6187				rc = -rc;
6188				for (j = 0; j < ctx.i; j++) {
6189					if_printf(ifp,
6190					    "failed to add mcast address"
6191					    " %02x:%02x:%02x:"
6192					    "%02x:%02x:%02x rc=%d\n",
6193					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6194					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6195					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6196					    rc);
6197				}
6198				return (rc);
6199			}
6200			ctx.del = 0;
6201		} else
6202			NET_EPOCH_EXIT(et);
6203
6204		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6205		if (rc != 0)
6206			if_printf(ifp, "failed to set mcast address hash: %d\n",
6207			    rc);
6208		if (ctx.del == 0) {
6209			/* We clobbered the VXLAN entry if there was one. */
6210			pi->vxlan_tcam_entry = false;
6211		}
6212	}
6213
6214	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6215	    pi->vxlan_tcam_entry == false) {
6216		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6217		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6218		    true);
6219		if (rc < 0) {
6220			rc = -rc;
6221			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6222			    rc);
6223		} else {
6224			MPASS(rc == sc->rawf_base + pi->port_id);
6225			rc = 0;
6226			pi->vxlan_tcam_entry = true;
6227		}
6228	}
6229
6230	return (rc);
6231}
6232
6233/*
6234 * {begin|end}_synchronized_op must be called from the same thread.
6235 */
6236int
6237begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6238    char *wmesg)
6239{
6240	int rc, pri;
6241
6242#ifdef WITNESS
6243	/* the caller thinks it's ok to sleep, but is it really? */
6244	if (flags & SLEEP_OK)
6245		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6246		    "begin_synchronized_op");
6247#endif
6248
6249	if (INTR_OK)
6250		pri = PCATCH;
6251	else
6252		pri = 0;
6253
6254	ADAPTER_LOCK(sc);
6255	for (;;) {
6256
6257		if (vi && IS_DETACHING(vi)) {
6258			rc = ENXIO;
6259			goto done;
6260		}
6261
6262		if (!IS_BUSY(sc)) {
6263			rc = 0;
6264			break;
6265		}
6266
6267		if (!(flags & SLEEP_OK)) {
6268			rc = EBUSY;
6269			goto done;
6270		}
6271
6272		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6273			rc = EINTR;
6274			goto done;
6275		}
6276	}
6277
6278	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6279	SET_BUSY(sc);
6280#ifdef INVARIANTS
6281	sc->last_op = wmesg;
6282	sc->last_op_thr = curthread;
6283	sc->last_op_flags = flags;
6284#endif
6285
6286done:
6287	if (!(flags & HOLD_LOCK) || rc)
6288		ADAPTER_UNLOCK(sc);
6289
6290	return (rc);
6291}
6292
6293/*
6294 * Tell if_ioctl and if_init that the VI is going away.  This is
6295 * special variant of begin_synchronized_op and must be paired with a
6296 * call to end_vi_detach.
6297 */
6298void
6299begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6300{
6301	ADAPTER_LOCK(sc);
6302	SET_DETACHING(vi);
6303	wakeup(&sc->flags);
6304	while (IS_BUSY(sc))
6305		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6306	SET_BUSY(sc);
6307#ifdef INVARIANTS
6308	sc->last_op = "t4detach";
6309	sc->last_op_thr = curthread;
6310	sc->last_op_flags = 0;
6311#endif
6312	ADAPTER_UNLOCK(sc);
6313}
6314
6315void
6316end_vi_detach(struct adapter *sc, struct vi_info *vi)
6317{
6318	ADAPTER_LOCK(sc);
6319	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6320	CLR_BUSY(sc);
6321	CLR_DETACHING(vi);
6322	wakeup(&sc->flags);
6323	ADAPTER_UNLOCK(sc);
6324}
6325
6326/*
6327 * {begin|end}_synchronized_op must be called from the same thread.
6328 */
6329void
6330end_synchronized_op(struct adapter *sc, int flags)
6331{
6332
6333	if (flags & LOCK_HELD)
6334		ADAPTER_LOCK_ASSERT_OWNED(sc);
6335	else
6336		ADAPTER_LOCK(sc);
6337
6338	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6339	CLR_BUSY(sc);
6340	wakeup(&sc->flags);
6341	ADAPTER_UNLOCK(sc);
6342}
6343
6344static int
6345cxgbe_init_synchronized(struct vi_info *vi)
6346{
6347	struct port_info *pi = vi->pi;
6348	struct adapter *sc = pi->adapter;
6349	if_t ifp = vi->ifp;
6350	int rc = 0, i;
6351	struct sge_txq *txq;
6352
6353	ASSERT_SYNCHRONIZED_OP(sc);
6354
6355	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6356		return (0);	/* already running */
6357
6358	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6359		return (rc);	/* error message displayed already */
6360
6361	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6362		return (rc); /* error message displayed already */
6363
6364	rc = update_mac_settings(ifp, XGMAC_ALL);
6365	if (rc)
6366		goto done;	/* error message displayed already */
6367
6368	PORT_LOCK(pi);
6369	if (pi->up_vis == 0) {
6370		t4_update_port_info(pi);
6371		fixup_link_config(pi);
6372		build_medialist(pi);
6373		apply_link_config(pi);
6374	}
6375
6376	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6377	if (rc != 0) {
6378		if_printf(ifp, "enable_vi failed: %d\n", rc);
6379		PORT_UNLOCK(pi);
6380		goto done;
6381	}
6382
6383	/*
6384	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6385	 * if this changes.
6386	 */
6387
6388	for_each_txq(vi, i, txq) {
6389		TXQ_LOCK(txq);
6390		txq->eq.flags |= EQ_ENABLED;
6391		TXQ_UNLOCK(txq);
6392	}
6393
6394	/*
6395	 * The first iq of the first port to come up is used for tracing.
6396	 */
6397	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6398		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6399		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6400		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6401		    V_QUEUENUMBER(sc->traceq));
6402		pi->flags |= HAS_TRACEQ;
6403	}
6404
6405	/* all ok */
6406	pi->up_vis++;
6407	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6408	if (pi->link_cfg.link_ok)
6409		t4_os_link_changed(pi);
6410	PORT_UNLOCK(pi);
6411
6412	mtx_lock(&vi->tick_mtx);
6413	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6414		callout_reset(&vi->tick, hz, vi_tick, vi);
6415	else
6416		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6417	mtx_unlock(&vi->tick_mtx);
6418done:
6419	if (rc != 0)
6420		cxgbe_uninit_synchronized(vi);
6421
6422	return (rc);
6423}
6424
6425/*
6426 * Idempotent.
6427 */
6428static int
6429cxgbe_uninit_synchronized(struct vi_info *vi)
6430{
6431	struct port_info *pi = vi->pi;
6432	struct adapter *sc = pi->adapter;
6433	if_t ifp = vi->ifp;
6434	int rc, i;
6435	struct sge_txq *txq;
6436
6437	ASSERT_SYNCHRONIZED_OP(sc);
6438
6439	if (!(vi->flags & VI_INIT_DONE)) {
6440		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6441			KASSERT(0, ("uninited VI is running"));
6442			if_printf(ifp, "uninited VI with running ifnet.  "
6443			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6444			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6445			    if_getdrvflags(ifp));
6446		}
6447		return (0);
6448	}
6449
6450	/*
6451	 * Disable the VI so that all its data in either direction is discarded
6452	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6453	 * tick) intact as the TP can deliver negative advice or data that it's
6454	 * holding in its RAM (for an offloaded connection) even after the VI is
6455	 * disabled.
6456	 */
6457	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6458	if (rc) {
6459		if_printf(ifp, "disable_vi failed: %d\n", rc);
6460		return (rc);
6461	}
6462
6463	for_each_txq(vi, i, txq) {
6464		TXQ_LOCK(txq);
6465		txq->eq.flags &= ~EQ_ENABLED;
6466		TXQ_UNLOCK(txq);
6467	}
6468
6469	mtx_lock(&vi->tick_mtx);
6470	callout_stop(&vi->tick);
6471	mtx_unlock(&vi->tick_mtx);
6472
6473	PORT_LOCK(pi);
6474	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6475		PORT_UNLOCK(pi);
6476		return (0);
6477	}
6478	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6479	pi->up_vis--;
6480	if (pi->up_vis > 0) {
6481		PORT_UNLOCK(pi);
6482		return (0);
6483	}
6484
6485	pi->link_cfg.link_ok = false;
6486	pi->link_cfg.speed = 0;
6487	pi->link_cfg.link_down_rc = 255;
6488	t4_os_link_changed(pi);
6489	PORT_UNLOCK(pi);
6490
6491	return (0);
6492}
6493
6494/*
6495 * It is ok for this function to fail midway and return right away.  t4_detach
6496 * will walk the entire sc->irq list and clean up whatever is valid.
6497 */
6498int
6499t4_setup_intr_handlers(struct adapter *sc)
6500{
6501	int rc, rid, p, q, v;
6502	char s[8];
6503	struct irq *irq;
6504	struct port_info *pi;
6505	struct vi_info *vi;
6506	struct sge *sge = &sc->sge;
6507	struct sge_rxq *rxq;
6508#ifdef TCP_OFFLOAD
6509	struct sge_ofld_rxq *ofld_rxq;
6510#endif
6511#ifdef DEV_NETMAP
6512	struct sge_nm_rxq *nm_rxq;
6513#endif
6514#ifdef RSS
6515	int nbuckets = rss_getnumbuckets();
6516#endif
6517
6518	/*
6519	 * Setup interrupts.
6520	 */
6521	irq = &sc->irq[0];
6522	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6523	if (forwarding_intr_to_fwq(sc))
6524		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6525
6526	/* Multiple interrupts. */
6527	if (sc->flags & IS_VF)
6528		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6529		    ("%s: too few intr.", __func__));
6530	else
6531		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6532		    ("%s: too few intr.", __func__));
6533
6534	/* The first one is always error intr on PFs */
6535	if (!(sc->flags & IS_VF)) {
6536		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6537		if (rc != 0)
6538			return (rc);
6539		irq++;
6540		rid++;
6541	}
6542
6543	/* The second one is always the firmware event queue (first on VFs) */
6544	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6545	if (rc != 0)
6546		return (rc);
6547	irq++;
6548	rid++;
6549
6550	for_each_port(sc, p) {
6551		pi = sc->port[p];
6552		for_each_vi(pi, v, vi) {
6553			vi->first_intr = rid - 1;
6554
6555			if (vi->nnmrxq > 0) {
6556				int n = max(vi->nrxq, vi->nnmrxq);
6557
6558				rxq = &sge->rxq[vi->first_rxq];
6559#ifdef DEV_NETMAP
6560				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6561#endif
6562				for (q = 0; q < n; q++) {
6563					snprintf(s, sizeof(s), "%x%c%x", p,
6564					    'a' + v, q);
6565					if (q < vi->nrxq)
6566						irq->rxq = rxq++;
6567#ifdef DEV_NETMAP
6568					if (q < vi->nnmrxq)
6569						irq->nm_rxq = nm_rxq++;
6570
6571					if (irq->nm_rxq != NULL &&
6572					    irq->rxq == NULL) {
6573						/* Netmap rx only */
6574						rc = t4_alloc_irq(sc, irq, rid,
6575						    t4_nm_intr, irq->nm_rxq, s);
6576					}
6577					if (irq->nm_rxq != NULL &&
6578					    irq->rxq != NULL) {
6579						/* NIC and Netmap rx */
6580						rc = t4_alloc_irq(sc, irq, rid,
6581						    t4_vi_intr, irq, s);
6582					}
6583#endif
6584					if (irq->rxq != NULL &&
6585					    irq->nm_rxq == NULL) {
6586						/* NIC rx only */
6587						rc = t4_alloc_irq(sc, irq, rid,
6588						    t4_intr, irq->rxq, s);
6589					}
6590					if (rc != 0)
6591						return (rc);
6592#ifdef RSS
6593					if (q < vi->nrxq) {
6594						bus_bind_intr(sc->dev, irq->res,
6595						    rss_getcpu(q % nbuckets));
6596					}
6597#endif
6598					irq++;
6599					rid++;
6600					vi->nintr++;
6601				}
6602			} else {
6603				for_each_rxq(vi, q, rxq) {
6604					snprintf(s, sizeof(s), "%x%c%x", p,
6605					    'a' + v, q);
6606					rc = t4_alloc_irq(sc, irq, rid,
6607					    t4_intr, rxq, s);
6608					if (rc != 0)
6609						return (rc);
6610#ifdef RSS
6611					bus_bind_intr(sc->dev, irq->res,
6612					    rss_getcpu(q % nbuckets));
6613#endif
6614					irq++;
6615					rid++;
6616					vi->nintr++;
6617				}
6618			}
6619#ifdef TCP_OFFLOAD
6620			for_each_ofld_rxq(vi, q, ofld_rxq) {
6621				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6622				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6623				    ofld_rxq, s);
6624				if (rc != 0)
6625					return (rc);
6626				irq++;
6627				rid++;
6628				vi->nintr++;
6629			}
6630#endif
6631		}
6632	}
6633	MPASS(irq == &sc->irq[sc->intr_count]);
6634
6635	return (0);
6636}
6637
6638static void
6639write_global_rss_key(struct adapter *sc)
6640{
6641#ifdef RSS
6642	int i;
6643	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6644	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6645
6646	CTASSERT(RSS_KEYSIZE == 40);
6647
6648	rss_getkey((void *)&raw_rss_key[0]);
6649	for (i = 0; i < nitems(rss_key); i++) {
6650		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6651	}
6652	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6653#endif
6654}
6655
6656/*
6657 * Idempotent.
6658 */
6659static int
6660adapter_full_init(struct adapter *sc)
6661{
6662	int rc, i;
6663
6664	ASSERT_SYNCHRONIZED_OP(sc);
6665
6666	/*
6667	 * queues that belong to the adapter (not any particular port).
6668	 */
6669	rc = t4_setup_adapter_queues(sc);
6670	if (rc != 0)
6671		return (rc);
6672
6673	MPASS(sc->params.nports <= nitems(sc->tq));
6674	for (i = 0; i < sc->params.nports; i++) {
6675		if (sc->tq[i] != NULL)
6676			continue;
6677		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6678		    taskqueue_thread_enqueue, &sc->tq[i]);
6679		if (sc->tq[i] == NULL) {
6680			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6681			return (ENOMEM);
6682		}
6683		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6684		    device_get_nameunit(sc->dev), i);
6685	}
6686
6687	if (!(sc->flags & IS_VF)) {
6688		write_global_rss_key(sc);
6689		t4_intr_enable(sc);
6690	}
6691	return (0);
6692}
6693
6694int
6695adapter_init(struct adapter *sc)
6696{
6697	int rc;
6698
6699	ASSERT_SYNCHRONIZED_OP(sc);
6700	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6701	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6702	    ("%s: FULL_INIT_DONE already", __func__));
6703
6704	rc = adapter_full_init(sc);
6705	if (rc != 0)
6706		adapter_full_uninit(sc);
6707	else
6708		sc->flags |= FULL_INIT_DONE;
6709
6710	return (rc);
6711}
6712
6713/*
6714 * Idempotent.
6715 */
6716static void
6717adapter_full_uninit(struct adapter *sc)
6718{
6719	int i;
6720
6721	t4_teardown_adapter_queues(sc);
6722
6723	for (i = 0; i < nitems(sc->tq); i++) {
6724		if (sc->tq[i] == NULL)
6725			continue;
6726		taskqueue_free(sc->tq[i]);
6727		sc->tq[i] = NULL;
6728	}
6729
6730	sc->flags &= ~FULL_INIT_DONE;
6731}
6732
6733#ifdef RSS
6734#define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6735    RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6736    RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6737    RSS_HASHTYPE_RSS_UDP_IPV6)
6738
6739/* Translates kernel hash types to hardware. */
6740static int
6741hashconfig_to_hashen(int hashconfig)
6742{
6743	int hashen = 0;
6744
6745	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6746		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6747	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6748		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6749	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6750		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6751		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6752	}
6753	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6754		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6755		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6756	}
6757	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6758		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6759	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6760		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6761
6762	return (hashen);
6763}
6764
6765/* Translates hardware hash types to kernel. */
6766static int
6767hashen_to_hashconfig(int hashen)
6768{
6769	int hashconfig = 0;
6770
6771	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6772		/*
6773		 * If UDP hashing was enabled it must have been enabled for
6774		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6775		 * enabling any 4-tuple hash is nonsense configuration.
6776		 */
6777		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6778		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6779
6780		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6781			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6782		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6783			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6784	}
6785	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6786		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6787	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6788		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6789	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6790		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6791	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6792		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6793
6794	return (hashconfig);
6795}
6796#endif
6797
6798/*
6799 * Idempotent.
6800 */
6801static int
6802vi_full_init(struct vi_info *vi)
6803{
6804	struct adapter *sc = vi->adapter;
6805	struct sge_rxq *rxq;
6806	int rc, i, j;
6807#ifdef RSS
6808	int nbuckets = rss_getnumbuckets();
6809	int hashconfig = rss_gethashconfig();
6810	int extra;
6811#endif
6812
6813	ASSERT_SYNCHRONIZED_OP(sc);
6814
6815	/*
6816	 * Allocate tx/rx/fl queues for this VI.
6817	 */
6818	rc = t4_setup_vi_queues(vi);
6819	if (rc != 0)
6820		return (rc);
6821
6822	/*
6823	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6824	 */
6825	if (vi->nrxq > vi->rss_size) {
6826		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6827		    "some queues will never receive traffic.\n", vi->nrxq,
6828		    vi->rss_size);
6829	} else if (vi->rss_size % vi->nrxq) {
6830		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6831		    "expect uneven traffic distribution.\n", vi->nrxq,
6832		    vi->rss_size);
6833	}
6834#ifdef RSS
6835	if (vi->nrxq != nbuckets) {
6836		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6837		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6838	}
6839#endif
6840	if (vi->rss == NULL)
6841		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6842		    M_ZERO | M_WAITOK);
6843	for (i = 0; i < vi->rss_size;) {
6844#ifdef RSS
6845		j = rss_get_indirection_to_bucket(i);
6846		j %= vi->nrxq;
6847		rxq = &sc->sge.rxq[vi->first_rxq + j];
6848		vi->rss[i++] = rxq->iq.abs_id;
6849#else
6850		for_each_rxq(vi, j, rxq) {
6851			vi->rss[i++] = rxq->iq.abs_id;
6852			if (i == vi->rss_size)
6853				break;
6854		}
6855#endif
6856	}
6857
6858	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6859	    vi->rss, vi->rss_size);
6860	if (rc != 0) {
6861		CH_ERR(vi, "rss_config failed: %d\n", rc);
6862		return (rc);
6863	}
6864
6865#ifdef RSS
6866	vi->hashen = hashconfig_to_hashen(hashconfig);
6867
6868	/*
6869	 * We may have had to enable some hashes even though the global config
6870	 * wants them disabled.  This is a potential problem that must be
6871	 * reported to the user.
6872	 */
6873	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6874
6875	/*
6876	 * If we consider only the supported hash types, then the enabled hashes
6877	 * are a superset of the requested hashes.  In other words, there cannot
6878	 * be any supported hash that was requested but not enabled, but there
6879	 * can be hashes that were not requested but had to be enabled.
6880	 */
6881	extra &= SUPPORTED_RSS_HASHTYPES;
6882	MPASS((extra & hashconfig) == 0);
6883
6884	if (extra) {
6885		CH_ALERT(vi,
6886		    "global RSS config (0x%x) cannot be accommodated.\n",
6887		    hashconfig);
6888	}
6889	if (extra & RSS_HASHTYPE_RSS_IPV4)
6890		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6891	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6892		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6893	if (extra & RSS_HASHTYPE_RSS_IPV6)
6894		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6895	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6896		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6897	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6898		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6899	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6900		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6901#else
6902	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6903	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6904	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6905	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6906#endif
6907	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6908	    0, 0);
6909	if (rc != 0) {
6910		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6911		return (rc);
6912	}
6913
6914	return (0);
6915}
6916
6917int
6918vi_init(struct vi_info *vi)
6919{
6920	int rc;
6921
6922	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6923	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6924	    ("%s: VI_INIT_DONE already", __func__));
6925
6926	rc = vi_full_init(vi);
6927	if (rc != 0)
6928		vi_full_uninit(vi);
6929	else
6930		vi->flags |= VI_INIT_DONE;
6931
6932	return (rc);
6933}
6934
6935/*
6936 * Idempotent.
6937 */
6938static void
6939vi_full_uninit(struct vi_info *vi)
6940{
6941
6942	if (vi->flags & VI_INIT_DONE) {
6943		quiesce_vi(vi);
6944		free(vi->rss, M_CXGBE);
6945		free(vi->nm_rss, M_CXGBE);
6946	}
6947
6948	t4_teardown_vi_queues(vi);
6949	vi->flags &= ~VI_INIT_DONE;
6950}
6951
6952static void
6953quiesce_txq(struct sge_txq *txq)
6954{
6955	struct sge_eq *eq = &txq->eq;
6956	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6957
6958	MPASS(eq->flags & EQ_SW_ALLOCATED);
6959	MPASS(!(eq->flags & EQ_ENABLED));
6960
6961	/* Wait for the mp_ring to empty. */
6962	while (!mp_ring_is_idle(txq->r)) {
6963		mp_ring_check_drainage(txq->r, 4096);
6964		pause("rquiesce", 1);
6965	}
6966	MPASS(txq->txp.npkt == 0);
6967
6968	if (eq->flags & EQ_HW_ALLOCATED) {
6969		/*
6970		 * Hardware is alive and working normally.  Wait for it to
6971		 * finish and then wait for the driver to catch up and reclaim
6972		 * all descriptors.
6973		 */
6974		while (spg->cidx != htobe16(eq->pidx))
6975			pause("equiesce", 1);
6976		while (eq->cidx != eq->pidx)
6977			pause("dquiesce", 1);
6978	} else {
6979		/*
6980		 * Hardware is unavailable.  Discard all pending tx and reclaim
6981		 * descriptors directly.
6982		 */
6983		TXQ_LOCK(txq);
6984		while (eq->cidx != eq->pidx) {
6985			struct mbuf *m, *nextpkt;
6986			struct tx_sdesc *txsd;
6987
6988			txsd = &txq->sdesc[eq->cidx];
6989			for (m = txsd->m; m != NULL; m = nextpkt) {
6990				nextpkt = m->m_nextpkt;
6991				m->m_nextpkt = NULL;
6992				m_freem(m);
6993			}
6994			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6995		}
6996		spg->pidx = spg->cidx = htobe16(eq->cidx);
6997		TXQ_UNLOCK(txq);
6998	}
6999}
7000
7001static void
7002quiesce_wrq(struct sge_wrq *wrq)
7003{
7004
7005	/* XXXTX */
7006}
7007
7008static void
7009quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7010{
7011	/* Synchronize with the interrupt handler */
7012	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7013		pause("iqfree", 1);
7014
7015	if (fl != NULL) {
7016		MPASS(iq->flags & IQ_HAS_FL);
7017
7018		mtx_lock(&sc->sfl_lock);
7019		FL_LOCK(fl);
7020		fl->flags |= FL_DOOMED;
7021		FL_UNLOCK(fl);
7022		callout_stop(&sc->sfl_callout);
7023		mtx_unlock(&sc->sfl_lock);
7024
7025		KASSERT((fl->flags & FL_STARVING) == 0,
7026		    ("%s: still starving", __func__));
7027
7028		/* Release all buffers if hardware is no longer available. */
7029		if (!(iq->flags & IQ_HW_ALLOCATED))
7030			free_fl_buffers(sc, fl);
7031	}
7032}
7033
7034/*
7035 * Wait for all activity on all the queues of the VI to complete.  It is assumed
7036 * that no new work is being enqueued by the hardware or the driver.  That part
7037 * should be arranged before calling this function.
7038 */
7039static void
7040quiesce_vi(struct vi_info *vi)
7041{
7042	int i;
7043	struct adapter *sc = vi->adapter;
7044	struct sge_rxq *rxq;
7045	struct sge_txq *txq;
7046#ifdef TCP_OFFLOAD
7047	struct sge_ofld_rxq *ofld_rxq;
7048#endif
7049#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7050	struct sge_ofld_txq *ofld_txq;
7051#endif
7052
7053	if (!(vi->flags & VI_INIT_DONE))
7054		return;
7055
7056	for_each_txq(vi, i, txq) {
7057		quiesce_txq(txq);
7058	}
7059
7060#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7061	for_each_ofld_txq(vi, i, ofld_txq) {
7062		quiesce_wrq(&ofld_txq->wrq);
7063	}
7064#endif
7065
7066	for_each_rxq(vi, i, rxq) {
7067		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7068	}
7069
7070#ifdef TCP_OFFLOAD
7071	for_each_ofld_rxq(vi, i, ofld_rxq) {
7072		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7073	}
7074#endif
7075}
7076
7077static int
7078t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7079    driver_intr_t *handler, void *arg, char *name)
7080{
7081	int rc;
7082
7083	irq->rid = rid;
7084	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7085	    RF_SHAREABLE | RF_ACTIVE);
7086	if (irq->res == NULL) {
7087		device_printf(sc->dev,
7088		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7089		return (ENOMEM);
7090	}
7091
7092	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7093	    NULL, handler, arg, &irq->tag);
7094	if (rc != 0) {
7095		device_printf(sc->dev,
7096		    "failed to setup interrupt for rid %d, name %s: %d\n",
7097		    rid, name, rc);
7098	} else if (name)
7099		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7100
7101	return (rc);
7102}
7103
7104static int
7105t4_free_irq(struct adapter *sc, struct irq *irq)
7106{
7107	if (irq->tag)
7108		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7109	if (irq->res)
7110		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7111
7112	bzero(irq, sizeof(*irq));
7113
7114	return (0);
7115}
7116
7117static void
7118get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7119{
7120
7121	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7122	t4_get_regs(sc, buf, regs->len);
7123}
7124
7125#define	A_PL_INDIR_CMD	0x1f8
7126
7127#define	S_PL_AUTOINC	31
7128#define	M_PL_AUTOINC	0x1U
7129#define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7130#define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7131
7132#define	S_PL_VFID	20
7133#define	M_PL_VFID	0xffU
7134#define	V_PL_VFID(x)	((x) << S_PL_VFID)
7135#define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7136
7137#define	S_PL_ADDR	0
7138#define	M_PL_ADDR	0xfffffU
7139#define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7140#define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7141
7142#define	A_PL_INDIR_DATA	0x1fc
7143
7144static uint64_t
7145read_vf_stat(struct adapter *sc, u_int vin, int reg)
7146{
7147	u32 stats[2];
7148
7149	if (sc->flags & IS_VF) {
7150		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7151		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7152	} else {
7153		mtx_assert(&sc->reg_lock, MA_OWNED);
7154		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7155		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7156		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7157		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7158	}
7159	return (((uint64_t)stats[1]) << 32 | stats[0]);
7160}
7161
7162static void
7163t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7164{
7165
7166#define GET_STAT(name) \
7167	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7168
7169	if (!(sc->flags & IS_VF))
7170		mtx_lock(&sc->reg_lock);
7171	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7172	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7173	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7174	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7175	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7176	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7177	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7178	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7179	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7180	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7181	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7182	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7183	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7184	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7185	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7186	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7187	if (!(sc->flags & IS_VF))
7188		mtx_unlock(&sc->reg_lock);
7189
7190#undef GET_STAT
7191}
7192
7193static void
7194t4_clr_vi_stats(struct adapter *sc, u_int vin)
7195{
7196	int reg;
7197
7198	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7199	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7200	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7201	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7202		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7203}
7204
7205static void
7206vi_refresh_stats(struct vi_info *vi)
7207{
7208	struct timeval tv;
7209	const struct timeval interval = {0, 250000};	/* 250ms */
7210
7211	mtx_assert(&vi->tick_mtx, MA_OWNED);
7212
7213	if (vi->flags & VI_SKIP_STATS)
7214		return;
7215
7216	getmicrotime(&tv);
7217	timevalsub(&tv, &interval);
7218	if (timevalcmp(&tv, &vi->last_refreshed, <))
7219		return;
7220
7221	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7222	getmicrotime(&vi->last_refreshed);
7223}
7224
7225static void
7226cxgbe_refresh_stats(struct vi_info *vi)
7227{
7228	u_int i, v, tnl_cong_drops, chan_map;
7229	struct timeval tv;
7230	const struct timeval interval = {0, 250000};	/* 250ms */
7231	struct port_info *pi;
7232	struct adapter *sc;
7233
7234	mtx_assert(&vi->tick_mtx, MA_OWNED);
7235
7236	if (vi->flags & VI_SKIP_STATS)
7237		return;
7238
7239	getmicrotime(&tv);
7240	timevalsub(&tv, &interval);
7241	if (timevalcmp(&tv, &vi->last_refreshed, <))
7242		return;
7243
7244	pi = vi->pi;
7245	sc = vi->adapter;
7246	tnl_cong_drops = 0;
7247	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7248	chan_map = pi->rx_e_chan_map;
7249	while (chan_map) {
7250		i = ffs(chan_map) - 1;
7251		mtx_lock(&sc->reg_lock);
7252		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7253		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7254		mtx_unlock(&sc->reg_lock);
7255		tnl_cong_drops += v;
7256		chan_map &= ~(1 << i);
7257	}
7258	pi->tnl_cong_drops = tnl_cong_drops;
7259	getmicrotime(&vi->last_refreshed);
7260}
7261
7262static void
7263cxgbe_tick(void *arg)
7264{
7265	struct vi_info *vi = arg;
7266
7267	MPASS(IS_MAIN_VI(vi));
7268	mtx_assert(&vi->tick_mtx, MA_OWNED);
7269
7270	cxgbe_refresh_stats(vi);
7271	callout_schedule(&vi->tick, hz);
7272}
7273
7274static void
7275vi_tick(void *arg)
7276{
7277	struct vi_info *vi = arg;
7278
7279	mtx_assert(&vi->tick_mtx, MA_OWNED);
7280
7281	vi_refresh_stats(vi);
7282	callout_schedule(&vi->tick, hz);
7283}
7284
7285/*
7286 * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7287 */
7288static char *caps_decoder[] = {
7289	"\20\001IPMI\002NCSI",				/* 0: NBM */
7290	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7291	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7292	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7293	    "\006HASHFILTER\007ETHOFLD",
7294	"\20\001TOE",					/* 4: TOE */
7295	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7296	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7297	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7298	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7299	    "\007T10DIF"
7300	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7301	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7302	    "\004TLS_HW",
7303	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7304		    "\004PO_INITIATOR\005PO_TARGET",
7305};
7306
7307void
7308t4_sysctls(struct adapter *sc)
7309{
7310	struct sysctl_ctx_list *ctx = &sc->ctx;
7311	struct sysctl_oid *oid;
7312	struct sysctl_oid_list *children, *c0;
7313	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7314
7315	/*
7316	 * dev.t4nex.X.
7317	 */
7318	oid = device_get_sysctl_tree(sc->dev);
7319	c0 = children = SYSCTL_CHILDREN(oid);
7320
7321	sc->sc_do_rxcopy = 1;
7322	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7323	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7324
7325	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7326	    sc->params.nports, "# of ports");
7327
7328	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7329	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7330	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7331	    "available doorbells");
7332
7333	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7334	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7335
7336	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7337	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7338	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7339	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7340
7341	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7342	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7343	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7344	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7345
7346	t4_sge_sysctls(sc, ctx, children);
7347
7348	sc->lro_timeout = 100;
7349	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7350	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7351
7352	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7353	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7354
7355	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7356	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7357
7358	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7359	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7360
7361	if (sc->flags & IS_VF)
7362		return;
7363
7364	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7365	    NULL, chip_rev(sc), "chip hardware revision");
7366
7367	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7368	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7369
7370	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7371	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7372
7373	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7374	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7375
7376	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7377	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7378
7379	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7380	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7381
7382	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7383	    sc->er_version, 0, "expansion ROM version");
7384
7385	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7386	    sc->bs_version, 0, "bootstrap firmware version");
7387
7388	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7389	    NULL, sc->params.scfg_vers, "serial config version");
7390
7391	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7392	    NULL, sc->params.vpd_vers, "VPD version");
7393
7394	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7395	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7396
7397	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7398	    sc->cfcsum, "config file checksum");
7399
7400#define SYSCTL_CAP(name, n, text) \
7401	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7402	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7403	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7404	    "available " text " capabilities")
7405
7406	SYSCTL_CAP(nbmcaps, 0, "NBM");
7407	SYSCTL_CAP(linkcaps, 1, "link");
7408	SYSCTL_CAP(switchcaps, 2, "switch");
7409	SYSCTL_CAP(niccaps, 3, "NIC");
7410	SYSCTL_CAP(toecaps, 4, "TCP offload");
7411	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7412	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7413	SYSCTL_CAP(cryptocaps, 7, "crypto");
7414	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7415#undef SYSCTL_CAP
7416
7417	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7418	    NULL, sc->tids.nftids, "number of filters");
7419
7420	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7421	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7422	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7423	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7424	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7425	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7426
7427	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7428	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7429	    sysctl_loadavg, "A",
7430	    "microprocessor load averages (debug firmwares only)");
7431
7432	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7433	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7434	    "I", "core Vdd (in mV)");
7435
7436	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7437	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7438	    sysctl_cpus, "A", "local CPUs");
7439
7440	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7441	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7442	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7443
7444	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7445	    &sc->swintr, 0, "software triggered interrupts");
7446
7447	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7448	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7449	    "1 = reset adapter, 0 = zero reset counter");
7450
7451	/*
7452	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7453	 */
7454	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7455	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7456	    "logs and miscellaneous information");
7457	children = SYSCTL_CHILDREN(oid);
7458
7459	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7460	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7461	    sysctl_cctrl, "A", "congestion control");
7462
7463	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7464	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7465	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7466
7467	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7468	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7469	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7470
7471	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7472	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7473	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7474
7475	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7476	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7477	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7478
7479	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7480	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7481	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7482
7483	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7484	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7485	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7486
7487	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7488	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7489	    sysctl_cim_la, "A", "CIM logic analyzer");
7490
7491	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7492	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7493	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7494
7495	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7496	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7497	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7498
7499	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7500	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7501	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7502
7503	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7504	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7505	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7506
7507	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7508	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7509	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7510
7511	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7512	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7513	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7514
7515	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7516	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7517	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7518
7519	if (chip_id(sc) > CHELSIO_T4) {
7520		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7521		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7522		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7523		    "CIM OBQ 6 (SGE0-RX)");
7524
7525		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7526		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7527		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7528		    "CIM OBQ 7 (SGE1-RX)");
7529	}
7530
7531	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7532	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7533	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7534
7535	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7536	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7537	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7538
7539	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7540	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7541	    sysctl_cpl_stats, "A", "CPL statistics");
7542
7543	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7544	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7545	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7546
7547	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7548	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7549	    sysctl_tid_stats, "A", "tid stats");
7550
7551	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7552	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7553	    sysctl_devlog, "A", "firmware's device log");
7554
7555	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7556	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7557	    sysctl_fcoe_stats, "A", "FCoE statistics");
7558
7559	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7560	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7561	    sysctl_hw_sched, "A", "hardware scheduler ");
7562
7563	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7564	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7565	    sysctl_l2t, "A", "hardware L2 table");
7566
7567	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7568	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7569	    sysctl_smt, "A", "hardware source MAC table");
7570
7571#ifdef INET6
7572	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7573	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7574	    sysctl_clip, "A", "active CLIP table entries");
7575#endif
7576
7577	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7578	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7579	    sysctl_lb_stats, "A", "loopback statistics");
7580
7581	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7582	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7583	    sysctl_meminfo, "A", "memory regions");
7584
7585	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7586	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7587	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7588	    "A", "MPS TCAM entries");
7589
7590	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7591	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7592	    sysctl_path_mtus, "A", "path MTUs");
7593
7594	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7595	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7596	    sysctl_pm_stats, "A", "PM statistics");
7597
7598	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7599	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7600	    sysctl_rdma_stats, "A", "RDMA statistics");
7601
7602	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7603	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7604	    sysctl_tcp_stats, "A", "TCP statistics");
7605
7606	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7607	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7608	    sysctl_tids, "A", "TID information");
7609
7610	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7611	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7612	    sysctl_tp_err_stats, "A", "TP error statistics");
7613
7614	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7615	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7616	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7617
7618	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7619	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7620	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7621
7622	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7623	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7624	    sysctl_tp_la, "A", "TP logic analyzer");
7625
7626	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7627	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7628	    sysctl_tx_rate, "A", "Tx rate");
7629
7630	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7631	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7632	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7633
7634	if (chip_id(sc) >= CHELSIO_T5) {
7635		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7636		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7637		    sysctl_wcwr_stats, "A", "write combined work requests");
7638	}
7639
7640#ifdef KERN_TLS
7641	if (is_ktls(sc)) {
7642		/*
7643		 * dev.t4nex.0.tls.
7644		 */
7645		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7646		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7647		children = SYSCTL_CHILDREN(oid);
7648
7649		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7650		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7651		    "keys in work requests (1) or attempt to store TLS keys "
7652		    "in card memory.");
7653
7654		if (is_t6(sc))
7655			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7656			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7657			    "combine TCB field updates with TLS record work "
7658			    "requests.");
7659	}
7660#endif
7661
7662#ifdef TCP_OFFLOAD
7663	if (is_offload(sc)) {
7664		int i;
7665		char s[4];
7666
7667		/*
7668		 * dev.t4nex.X.toe.
7669		 */
7670		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7671		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7672		children = SYSCTL_CHILDREN(oid);
7673
7674		sc->tt.cong_algorithm = -1;
7675		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7676		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7677		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7678		    "3 = highspeed)");
7679
7680		sc->tt.sndbuf = -1;
7681		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7682		    &sc->tt.sndbuf, 0, "hardware send buffer");
7683
7684		sc->tt.ddp = 0;
7685		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7686		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7687		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7688		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7689
7690		sc->tt.rx_coalesce = -1;
7691		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7692		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7693
7694		sc->tt.tls = 0;
7695		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7696		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7697		    "Inline TLS allowed");
7698
7699		sc->tt.tx_align = -1;
7700		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7701		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7702
7703		sc->tt.tx_zcopy = 0;
7704		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7705		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7706		    "Enable zero-copy aio_write(2)");
7707
7708		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7709		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7710		    "cop_managed_offloading", CTLFLAG_RW,
7711		    &sc->tt.cop_managed_offloading, 0,
7712		    "COP (Connection Offload Policy) controls all TOE offload");
7713
7714		sc->tt.autorcvbuf_inc = 16 * 1024;
7715		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7716		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7717		    "autorcvbuf increment");
7718
7719		sc->tt.update_hc_on_pmtu_change = 1;
7720		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7721		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7722		    &sc->tt.update_hc_on_pmtu_change, 0,
7723		    "Update hostcache entry if the PMTU changes");
7724
7725		sc->tt.iso = 1;
7726		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7727		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7728
7729		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7730		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7731		    sysctl_tp_tick, "A", "TP timer tick (us)");
7732
7733		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7734		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7735		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7736
7737		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7738		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7739		    sysctl_tp_tick, "A", "DACK tick (us)");
7740
7741		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7742		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7743		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7744
7745		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7746		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7747		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7748		    "Minimum retransmit interval (us)");
7749
7750		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7751		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7752		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7753		    "Maximum retransmit interval (us)");
7754
7755		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7756		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7757		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7758		    "Persist timer min (us)");
7759
7760		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7761		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7762		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7763		    "Persist timer max (us)");
7764
7765		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7766		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7767		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7768		    "Keepalive idle timer (us)");
7769
7770		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7771		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7772		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7773		    "Keepalive interval timer (us)");
7774
7775		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7776		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7777		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7778
7779		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7780		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7781		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7782		    "FINWAIT2 timer (us)");
7783
7784		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7785		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7786		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7787		    "Number of SYN retransmissions before abort");
7788
7789		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7790		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7791		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7792		    "Number of retransmissions before abort");
7793
7794		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7795		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7796		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7797		    "Number of keepalive probes before abort");
7798
7799		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7800		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7801		    "TOE retransmit backoffs");
7802		children = SYSCTL_CHILDREN(oid);
7803		for (i = 0; i < 16; i++) {
7804			snprintf(s, sizeof(s), "%u", i);
7805			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7806			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7807			    i, sysctl_tp_backoff, "IU",
7808			    "TOE retransmit backoff");
7809		}
7810	}
7811#endif
7812}
7813
7814void
7815vi_sysctls(struct vi_info *vi)
7816{
7817	struct sysctl_ctx_list *ctx = &vi->ctx;
7818	struct sysctl_oid *oid;
7819	struct sysctl_oid_list *children;
7820
7821	/*
7822	 * dev.v?(cxgbe|cxl).X.
7823	 */
7824	oid = device_get_sysctl_tree(vi->dev);
7825	children = SYSCTL_CHILDREN(oid);
7826
7827	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7828	    vi->viid, "VI identifer");
7829	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7830	    &vi->nrxq, 0, "# of rx queues");
7831	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7832	    &vi->ntxq, 0, "# of tx queues");
7833	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7834	    &vi->first_rxq, 0, "index of first rx queue");
7835	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7836	    &vi->first_txq, 0, "index of first tx queue");
7837	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7838	    vi->rss_base, "start of RSS indirection table");
7839	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7840	    vi->rss_size, "size of RSS indirection table");
7841
7842	if (IS_MAIN_VI(vi)) {
7843		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7844		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7845		    sysctl_noflowq, "IU",
7846		    "Reserve queue 0 for non-flowid packets");
7847	}
7848
7849	if (vi->adapter->flags & IS_VF) {
7850		MPASS(vi->flags & TX_USES_VM_WR);
7851		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7852		    NULL, 1, "use VM work requests for transmit");
7853	} else {
7854		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7855		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7856		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7857	}
7858
7859#ifdef TCP_OFFLOAD
7860	if (vi->nofldrxq != 0) {
7861		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7862		    &vi->nofldrxq, 0,
7863		    "# of rx queues for offloaded TCP connections");
7864		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7865		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7866		    "index of first TOE rx queue");
7867		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7868		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7869		    sysctl_holdoff_tmr_idx_ofld, "I",
7870		    "holdoff timer index for TOE queues");
7871		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7872		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7873		    sysctl_holdoff_pktc_idx_ofld, "I",
7874		    "holdoff packet counter index for TOE queues");
7875	}
7876#endif
7877#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7878	if (vi->nofldtxq != 0) {
7879		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7880		    &vi->nofldtxq, 0,
7881		    "# of tx queues for TOE/ETHOFLD");
7882		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7883		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7884		    "index of first TOE/ETHOFLD tx queue");
7885	}
7886#endif
7887#ifdef DEV_NETMAP
7888	if (vi->nnmrxq != 0) {
7889		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7890		    &vi->nnmrxq, 0, "# of netmap rx queues");
7891		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7892		    &vi->nnmtxq, 0, "# of netmap tx queues");
7893		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7894		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7895		    "index of first netmap rx queue");
7896		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7897		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7898		    "index of first netmap tx queue");
7899	}
7900#endif
7901
7902	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7903	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7904	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7905	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7906	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7907	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7908
7909	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7910	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7911	    sysctl_qsize_rxq, "I", "rx queue size");
7912	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7913	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7914	    sysctl_qsize_txq, "I", "tx queue size");
7915}
7916
7917static void
7918cxgbe_sysctls(struct port_info *pi)
7919{
7920	struct sysctl_ctx_list *ctx = &pi->ctx;
7921	struct sysctl_oid *oid;
7922	struct sysctl_oid_list *children, *children2;
7923	struct adapter *sc = pi->adapter;
7924	int i;
7925	char name[16];
7926	static char *tc_flags = {"\20\1USER"};
7927
7928	/*
7929	 * dev.cxgbe.X.
7930	 */
7931	oid = device_get_sysctl_tree(pi->dev);
7932	children = SYSCTL_CHILDREN(oid);
7933
7934	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7935	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7936	    sysctl_linkdnrc, "A", "reason why link is down");
7937	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7938		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7939		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7940		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7941		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7942		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7943		    sysctl_btphy, "I", "PHY firmware version");
7944	}
7945
7946	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7947	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7948	    sysctl_pause_settings, "A",
7949	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7950	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7951	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7952	    "FEC in use on the link");
7953	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7954	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7955	    sysctl_requested_fec, "A",
7956	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7957	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7958	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7959	    "FEC recommended by the cable/transceiver");
7960	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7961	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7962	    sysctl_autoneg, "I",
7963	    "autonegotiation (-1 = not supported)");
7964	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7965	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7966	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7967
7968	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7969	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7970	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7971	    &pi->link_cfg.pcaps, 0, "port capabilities");
7972	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7973	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7974	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7975	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7976
7977	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7978	    port_top_speed(pi), "max speed (in Gbps)");
7979	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7980	    pi->mps_bg_map, "MPS buffer group map");
7981	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7982	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7983	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
7984	    pi->tx_chan, "TP tx c-channel");
7985	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
7986	    pi->rx_chan, "TP rx c-channel");
7987
7988	if (sc->flags & IS_VF)
7989		return;
7990
7991	/*
7992	 * dev.(cxgbe|cxl).X.tc.
7993	 */
7994	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7995	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7996	    "Tx scheduler traffic classes (cl_rl)");
7997	children2 = SYSCTL_CHILDREN(oid);
7998	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7999	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8000	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8001	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8002	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8003	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8004	for (i = 0; i < sc->params.nsched_cls; i++) {
8005		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8006
8007		snprintf(name, sizeof(name), "%d", i);
8008		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8009		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8010		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8011		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8012		    CTLFLAG_RD, &tc->state, 0, "current state");
8013		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8014		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8015		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8016		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8017		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8018		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8019		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8020		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8021		    "traffic class parameters");
8022	}
8023
8024	/*
8025	 * dev.cxgbe.X.stats.
8026	 */
8027	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8028	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8029	children = SYSCTL_CHILDREN(oid);
8030	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8031	    &pi->tx_parse_error, 0,
8032	    "# of tx packets with invalid length or # of segments");
8033
8034#define T4_REGSTAT(name, stat, desc) \
8035    SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8036	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8037	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8038        sysctl_handle_t4_reg64, "QU", desc)
8039
8040/* We get these from port_stats and they may be stale by up to 1s */
8041#define T4_PORTSTAT(name, desc) \
8042	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8043	    &pi->stats.name, desc)
8044
8045	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8046	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8047	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8048	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8049	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8050	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8051	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8052	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8053	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8054	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8055	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8056	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8057	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8058	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8059	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8060	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8061	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8062	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8063	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8064	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8065	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8066	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8067	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8068
8069	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8070	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8071	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8072	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8073	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8074	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8075	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8076	if (is_t6(sc)) {
8077		T4_PORTSTAT(rx_fcs_err,
8078		    "# of frames received with bad FCS since last link up");
8079	} else {
8080		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8081		    "# of frames received with bad FCS");
8082	}
8083	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8084	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8085	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8086	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8087	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8088	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8089	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8090	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8091	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8092	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8093	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8094	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8095	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8096	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8097	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8098	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8099	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8100	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8101	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8102
8103	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8104	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8105	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8106	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8107	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8108	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8109	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8110	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8111
8112#undef T4_REGSTAT
8113#undef T4_PORTSTAT
8114}
8115
8116static int
8117sysctl_int_array(SYSCTL_HANDLER_ARGS)
8118{
8119	int rc, *i, space = 0;
8120	struct sbuf sb;
8121
8122	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8123	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8124		if (space)
8125			sbuf_printf(&sb, " ");
8126		sbuf_printf(&sb, "%d", *i);
8127		space = 1;
8128	}
8129	rc = sbuf_finish(&sb);
8130	sbuf_delete(&sb);
8131	return (rc);
8132}
8133
8134static int
8135sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8136{
8137	int rc;
8138	struct sbuf *sb;
8139
8140	rc = sysctl_wire_old_buffer(req, 0);
8141	if (rc != 0)
8142		return(rc);
8143
8144	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8145	if (sb == NULL)
8146		return (ENOMEM);
8147
8148	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8149	rc = sbuf_finish(sb);
8150	sbuf_delete(sb);
8151
8152	return (rc);
8153}
8154
8155static int
8156sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8157{
8158	int rc;
8159	struct sbuf *sb;
8160
8161	rc = sysctl_wire_old_buffer(req, 0);
8162	if (rc != 0)
8163		return(rc);
8164
8165	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8166	if (sb == NULL)
8167		return (ENOMEM);
8168
8169	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8170	rc = sbuf_finish(sb);
8171	sbuf_delete(sb);
8172
8173	return (rc);
8174}
8175
8176static int
8177sysctl_btphy(SYSCTL_HANDLER_ARGS)
8178{
8179	struct port_info *pi = arg1;
8180	int op = arg2;
8181	struct adapter *sc = pi->adapter;
8182	u_int v;
8183	int rc;
8184
8185	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8186	if (rc)
8187		return (rc);
8188	if (hw_off_limits(sc))
8189		rc = ENXIO;
8190	else {
8191		/* XXX: magic numbers */
8192		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8193		    op ? 0x20 : 0xc820, &v);
8194	}
8195	end_synchronized_op(sc, 0);
8196	if (rc)
8197		return (rc);
8198	if (op == 0)
8199		v /= 256;
8200
8201	rc = sysctl_handle_int(oidp, &v, 0, req);
8202	return (rc);
8203}
8204
8205static int
8206sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8207{
8208	struct vi_info *vi = arg1;
8209	int rc, val;
8210
8211	val = vi->rsrv_noflowq;
8212	rc = sysctl_handle_int(oidp, &val, 0, req);
8213	if (rc != 0 || req->newptr == NULL)
8214		return (rc);
8215
8216	if ((val >= 1) && (vi->ntxq > 1))
8217		vi->rsrv_noflowq = 1;
8218	else
8219		vi->rsrv_noflowq = 0;
8220
8221	return (rc);
8222}
8223
8224static int
8225sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8226{
8227	struct vi_info *vi = arg1;
8228	struct adapter *sc = vi->adapter;
8229	int rc, val, i;
8230
8231	MPASS(!(sc->flags & IS_VF));
8232
8233	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8234	rc = sysctl_handle_int(oidp, &val, 0, req);
8235	if (rc != 0 || req->newptr == NULL)
8236		return (rc);
8237
8238	if (val != 0 && val != 1)
8239		return (EINVAL);
8240
8241	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8242	    "t4txvm");
8243	if (rc)
8244		return (rc);
8245	if (hw_off_limits(sc))
8246		rc = ENXIO;
8247	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8248		/*
8249		 * We don't want parse_pkt to run with one setting (VF or PF)
8250		 * and then eth_tx to see a different setting but still use
8251		 * stale information calculated by parse_pkt.
8252		 */
8253		rc = EBUSY;
8254	} else {
8255		struct port_info *pi = vi->pi;
8256		struct sge_txq *txq;
8257		uint32_t ctrl0;
8258		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8259
8260		if (val) {
8261			vi->flags |= TX_USES_VM_WR;
8262			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8263			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8264			    V_TXPKT_INTF(pi->tx_chan));
8265			if (!(sc->flags & IS_VF))
8266				npkt--;
8267		} else {
8268			vi->flags &= ~TX_USES_VM_WR;
8269			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8270			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8271			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8272			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8273		}
8274		for_each_txq(vi, i, txq) {
8275			txq->cpl_ctrl0 = ctrl0;
8276			txq->txp.max_npkt = npkt;
8277		}
8278	}
8279	end_synchronized_op(sc, LOCK_HELD);
8280	return (rc);
8281}
8282
8283static int
8284sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8285{
8286	struct vi_info *vi = arg1;
8287	struct adapter *sc = vi->adapter;
8288	int idx, rc, i;
8289	struct sge_rxq *rxq;
8290	uint8_t v;
8291
8292	idx = vi->tmr_idx;
8293
8294	rc = sysctl_handle_int(oidp, &idx, 0, req);
8295	if (rc != 0 || req->newptr == NULL)
8296		return (rc);
8297
8298	if (idx < 0 || idx >= SGE_NTIMERS)
8299		return (EINVAL);
8300
8301	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8302	    "t4tmr");
8303	if (rc)
8304		return (rc);
8305
8306	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8307	for_each_rxq(vi, i, rxq) {
8308#ifdef atomic_store_rel_8
8309		atomic_store_rel_8(&rxq->iq.intr_params, v);
8310#else
8311		rxq->iq.intr_params = v;
8312#endif
8313	}
8314	vi->tmr_idx = idx;
8315
8316	end_synchronized_op(sc, LOCK_HELD);
8317	return (0);
8318}
8319
8320static int
8321sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8322{
8323	struct vi_info *vi = arg1;
8324	struct adapter *sc = vi->adapter;
8325	int idx, rc;
8326
8327	idx = vi->pktc_idx;
8328
8329	rc = sysctl_handle_int(oidp, &idx, 0, req);
8330	if (rc != 0 || req->newptr == NULL)
8331		return (rc);
8332
8333	if (idx < -1 || idx >= SGE_NCOUNTERS)
8334		return (EINVAL);
8335
8336	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8337	    "t4pktc");
8338	if (rc)
8339		return (rc);
8340
8341	if (vi->flags & VI_INIT_DONE)
8342		rc = EBUSY; /* cannot be changed once the queues are created */
8343	else
8344		vi->pktc_idx = idx;
8345
8346	end_synchronized_op(sc, LOCK_HELD);
8347	return (rc);
8348}
8349
8350static int
8351sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8352{
8353	struct vi_info *vi = arg1;
8354	struct adapter *sc = vi->adapter;
8355	int qsize, rc;
8356
8357	qsize = vi->qsize_rxq;
8358
8359	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8360	if (rc != 0 || req->newptr == NULL)
8361		return (rc);
8362
8363	if (qsize < 128 || (qsize & 7))
8364		return (EINVAL);
8365
8366	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8367	    "t4rxqs");
8368	if (rc)
8369		return (rc);
8370
8371	if (vi->flags & VI_INIT_DONE)
8372		rc = EBUSY; /* cannot be changed once the queues are created */
8373	else
8374		vi->qsize_rxq = qsize;
8375
8376	end_synchronized_op(sc, LOCK_HELD);
8377	return (rc);
8378}
8379
8380static int
8381sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8382{
8383	struct vi_info *vi = arg1;
8384	struct adapter *sc = vi->adapter;
8385	int qsize, rc;
8386
8387	qsize = vi->qsize_txq;
8388
8389	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8390	if (rc != 0 || req->newptr == NULL)
8391		return (rc);
8392
8393	if (qsize < 128 || qsize > 65536)
8394		return (EINVAL);
8395
8396	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8397	    "t4txqs");
8398	if (rc)
8399		return (rc);
8400
8401	if (vi->flags & VI_INIT_DONE)
8402		rc = EBUSY; /* cannot be changed once the queues are created */
8403	else
8404		vi->qsize_txq = qsize;
8405
8406	end_synchronized_op(sc, LOCK_HELD);
8407	return (rc);
8408}
8409
8410static int
8411sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8412{
8413	struct port_info *pi = arg1;
8414	struct adapter *sc = pi->adapter;
8415	struct link_config *lc = &pi->link_cfg;
8416	int rc;
8417
8418	if (req->newptr == NULL) {
8419		struct sbuf *sb;
8420		static char *bits = "\20\1RX\2TX\3AUTO";
8421
8422		rc = sysctl_wire_old_buffer(req, 0);
8423		if (rc != 0)
8424			return(rc);
8425
8426		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8427		if (sb == NULL)
8428			return (ENOMEM);
8429
8430		if (lc->link_ok) {
8431			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8432			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8433		} else {
8434			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8435			    PAUSE_RX | PAUSE_AUTONEG), bits);
8436		}
8437		rc = sbuf_finish(sb);
8438		sbuf_delete(sb);
8439	} else {
8440		char s[2];
8441		int n;
8442
8443		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8444		    PAUSE_AUTONEG));
8445		s[1] = 0;
8446
8447		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8448		if (rc != 0)
8449			return(rc);
8450
8451		if (s[1] != 0)
8452			return (EINVAL);
8453		if (s[0] < '0' || s[0] > '9')
8454			return (EINVAL);	/* not a number */
8455		n = s[0] - '0';
8456		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8457			return (EINVAL);	/* some other bit is set too */
8458
8459		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8460		    "t4PAUSE");
8461		if (rc)
8462			return (rc);
8463		if (!hw_off_limits(sc)) {
8464			PORT_LOCK(pi);
8465			lc->requested_fc = n;
8466			fixup_link_config(pi);
8467			if (pi->up_vis > 0)
8468				rc = apply_link_config(pi);
8469			set_current_media(pi);
8470			PORT_UNLOCK(pi);
8471		}
8472		end_synchronized_op(sc, 0);
8473	}
8474
8475	return (rc);
8476}
8477
8478static int
8479sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8480{
8481	struct port_info *pi = arg1;
8482	struct link_config *lc = &pi->link_cfg;
8483	int rc;
8484	struct sbuf *sb;
8485	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8486
8487	rc = sysctl_wire_old_buffer(req, 0);
8488	if (rc != 0)
8489		return(rc);
8490
8491	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8492	if (sb == NULL)
8493		return (ENOMEM);
8494	if (lc->link_ok)
8495		sbuf_printf(sb, "%b", lc->fec, bits);
8496	else
8497		sbuf_printf(sb, "no link");
8498	rc = sbuf_finish(sb);
8499	sbuf_delete(sb);
8500
8501	return (rc);
8502}
8503
8504static int
8505sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8506{
8507	struct port_info *pi = arg1;
8508	struct adapter *sc = pi->adapter;
8509	struct link_config *lc = &pi->link_cfg;
8510	int rc;
8511	int8_t old;
8512
8513	if (req->newptr == NULL) {
8514		struct sbuf *sb;
8515		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8516		    "\5RSVD3\6auto\7module";
8517
8518		rc = sysctl_wire_old_buffer(req, 0);
8519		if (rc != 0)
8520			return(rc);
8521
8522		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8523		if (sb == NULL)
8524			return (ENOMEM);
8525
8526		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8527		rc = sbuf_finish(sb);
8528		sbuf_delete(sb);
8529	} else {
8530		char s[8];
8531		int n;
8532
8533		snprintf(s, sizeof(s), "%d",
8534		    lc->requested_fec == FEC_AUTO ? -1 :
8535		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8536
8537		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8538		if (rc != 0)
8539			return(rc);
8540
8541		n = strtol(&s[0], NULL, 0);
8542		if (n < 0 || n & FEC_AUTO)
8543			n = FEC_AUTO;
8544		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8545			return (EINVAL);/* some other bit is set too */
8546
8547		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8548		    "t4reqf");
8549		if (rc)
8550			return (rc);
8551		PORT_LOCK(pi);
8552		old = lc->requested_fec;
8553		if (n == FEC_AUTO)
8554			lc->requested_fec = FEC_AUTO;
8555		else if (n == 0 || n == FEC_NONE)
8556			lc->requested_fec = FEC_NONE;
8557		else {
8558			if ((lc->pcaps |
8559			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8560			    lc->pcaps) {
8561				rc = ENOTSUP;
8562				goto done;
8563			}
8564			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8565			    FEC_MODULE);
8566		}
8567		if (!hw_off_limits(sc)) {
8568			fixup_link_config(pi);
8569			if (pi->up_vis > 0) {
8570				rc = apply_link_config(pi);
8571				if (rc != 0) {
8572					lc->requested_fec = old;
8573					if (rc == FW_EPROTO)
8574						rc = ENOTSUP;
8575				}
8576			}
8577		}
8578done:
8579		PORT_UNLOCK(pi);
8580		end_synchronized_op(sc, 0);
8581	}
8582
8583	return (rc);
8584}
8585
8586static int
8587sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8588{
8589	struct port_info *pi = arg1;
8590	struct adapter *sc = pi->adapter;
8591	struct link_config *lc = &pi->link_cfg;
8592	int rc;
8593	int8_t fec;
8594	struct sbuf *sb;
8595	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8596
8597	rc = sysctl_wire_old_buffer(req, 0);
8598	if (rc != 0)
8599		return (rc);
8600
8601	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8602	if (sb == NULL)
8603		return (ENOMEM);
8604
8605	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8606		rc = EBUSY;
8607		goto done;
8608	}
8609	if (hw_off_limits(sc)) {
8610		rc = ENXIO;
8611		goto done;
8612	}
8613	PORT_LOCK(pi);
8614	if (pi->up_vis == 0) {
8615		/*
8616		 * If all the interfaces are administratively down the firmware
8617		 * does not report transceiver changes.  Refresh port info here.
8618		 * This is the only reason we have a synchronized op in this
8619		 * function.  Just PORT_LOCK would have been enough otherwise.
8620		 */
8621		t4_update_port_info(pi);
8622	}
8623
8624	fec = lc->fec_hint;
8625	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8626	    !fec_supported(lc->pcaps)) {
8627		sbuf_printf(sb, "n/a");
8628	} else {
8629		if (fec == 0)
8630			fec = FEC_NONE;
8631		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8632	}
8633	rc = sbuf_finish(sb);
8634	PORT_UNLOCK(pi);
8635done:
8636	sbuf_delete(sb);
8637	end_synchronized_op(sc, 0);
8638
8639	return (rc);
8640}
8641
8642static int
8643sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8644{
8645	struct port_info *pi = arg1;
8646	struct adapter *sc = pi->adapter;
8647	struct link_config *lc = &pi->link_cfg;
8648	int rc, val;
8649
8650	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8651		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8652	else
8653		val = -1;
8654	rc = sysctl_handle_int(oidp, &val, 0, req);
8655	if (rc != 0 || req->newptr == NULL)
8656		return (rc);
8657	if (val == 0)
8658		val = AUTONEG_DISABLE;
8659	else if (val == 1)
8660		val = AUTONEG_ENABLE;
8661	else
8662		val = AUTONEG_AUTO;
8663
8664	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8665	    "t4aneg");
8666	if (rc)
8667		return (rc);
8668	PORT_LOCK(pi);
8669	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8670		rc = ENOTSUP;
8671		goto done;
8672	}
8673	lc->requested_aneg = val;
8674	if (!hw_off_limits(sc)) {
8675		fixup_link_config(pi);
8676		if (pi->up_vis > 0)
8677			rc = apply_link_config(pi);
8678		set_current_media(pi);
8679	}
8680done:
8681	PORT_UNLOCK(pi);
8682	end_synchronized_op(sc, 0);
8683	return (rc);
8684}
8685
8686static int
8687sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8688{
8689	struct port_info *pi = arg1;
8690	struct adapter *sc = pi->adapter;
8691	struct link_config *lc = &pi->link_cfg;
8692	int rc, val;
8693
8694	val = lc->force_fec;
8695	MPASS(val >= -1 && val <= 1);
8696	rc = sysctl_handle_int(oidp, &val, 0, req);
8697	if (rc != 0 || req->newptr == NULL)
8698		return (rc);
8699	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8700		return (ENOTSUP);
8701	if (val < -1 || val > 1)
8702		return (EINVAL);
8703
8704	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8705	if (rc)
8706		return (rc);
8707	PORT_LOCK(pi);
8708	lc->force_fec = val;
8709	if (!hw_off_limits(sc)) {
8710		fixup_link_config(pi);
8711		if (pi->up_vis > 0)
8712			rc = apply_link_config(pi);
8713	}
8714	PORT_UNLOCK(pi);
8715	end_synchronized_op(sc, 0);
8716	return (rc);
8717}
8718
8719static int
8720sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8721{
8722	struct adapter *sc = arg1;
8723	int rc, reg = arg2;
8724	uint64_t val;
8725
8726	mtx_lock(&sc->reg_lock);
8727	if (hw_off_limits(sc))
8728		rc = ENXIO;
8729	else {
8730		rc = 0;
8731		val = t4_read_reg64(sc, reg);
8732	}
8733	mtx_unlock(&sc->reg_lock);
8734	if (rc == 0)
8735		rc = sysctl_handle_64(oidp, &val, 0, req);
8736	return (rc);
8737}
8738
8739static int
8740sysctl_temperature(SYSCTL_HANDLER_ARGS)
8741{
8742	struct adapter *sc = arg1;
8743	int rc, t;
8744	uint32_t param, val;
8745
8746	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8747	if (rc)
8748		return (rc);
8749	if (hw_off_limits(sc))
8750		rc = ENXIO;
8751	else {
8752		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8753		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8754		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8755		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8756	}
8757	end_synchronized_op(sc, 0);
8758	if (rc)
8759		return (rc);
8760
8761	/* unknown is returned as 0 but we display -1 in that case */
8762	t = val == 0 ? -1 : val;
8763
8764	rc = sysctl_handle_int(oidp, &t, 0, req);
8765	return (rc);
8766}
8767
8768static int
8769sysctl_vdd(SYSCTL_HANDLER_ARGS)
8770{
8771	struct adapter *sc = arg1;
8772	int rc;
8773	uint32_t param, val;
8774
8775	if (sc->params.core_vdd == 0) {
8776		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8777		    "t4vdd");
8778		if (rc)
8779			return (rc);
8780		if (hw_off_limits(sc))
8781			rc = ENXIO;
8782		else {
8783			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8784			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8785			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8786			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8787			    &param, &val);
8788		}
8789		end_synchronized_op(sc, 0);
8790		if (rc)
8791			return (rc);
8792		sc->params.core_vdd = val;
8793	}
8794
8795	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8796}
8797
8798static int
8799sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8800{
8801	struct adapter *sc = arg1;
8802	int rc, v;
8803	uint32_t param, val;
8804
8805	v = sc->sensor_resets;
8806	rc = sysctl_handle_int(oidp, &v, 0, req);
8807	if (rc != 0 || req->newptr == NULL || v <= 0)
8808		return (rc);
8809
8810	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8811	    chip_id(sc) < CHELSIO_T5)
8812		return (ENOTSUP);
8813
8814	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8815	if (rc)
8816		return (rc);
8817	if (hw_off_limits(sc))
8818		rc = ENXIO;
8819	else {
8820		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8821		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8822		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8823		val = 1;
8824		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8825	}
8826	end_synchronized_op(sc, 0);
8827	if (rc == 0)
8828		sc->sensor_resets++;
8829	return (rc);
8830}
8831
8832static int
8833sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8834{
8835	struct adapter *sc = arg1;
8836	struct sbuf *sb;
8837	int rc;
8838	uint32_t param, val;
8839
8840	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8841	if (rc)
8842		return (rc);
8843	if (hw_off_limits(sc))
8844		rc = ENXIO;
8845	else {
8846		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8847		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8848		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8849	}
8850	end_synchronized_op(sc, 0);
8851	if (rc)
8852		return (rc);
8853
8854	rc = sysctl_wire_old_buffer(req, 0);
8855	if (rc != 0)
8856		return (rc);
8857
8858	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8859	if (sb == NULL)
8860		return (ENOMEM);
8861
8862	if (val == 0xffffffff) {
8863		/* Only debug and custom firmwares report load averages. */
8864		sbuf_printf(sb, "not available");
8865	} else {
8866		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8867		    (val >> 16) & 0xff);
8868	}
8869	rc = sbuf_finish(sb);
8870	sbuf_delete(sb);
8871
8872	return (rc);
8873}
8874
8875static int
8876sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8877{
8878	struct adapter *sc = arg1;
8879	struct sbuf *sb;
8880	int rc, i;
8881	uint16_t incr[NMTUS][NCCTRL_WIN];
8882	static const char *dec_fac[] = {
8883		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8884		"0.9375"
8885	};
8886
8887	rc = sysctl_wire_old_buffer(req, 0);
8888	if (rc != 0)
8889		return (rc);
8890
8891	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8892	if (sb == NULL)
8893		return (ENOMEM);
8894
8895	mtx_lock(&sc->reg_lock);
8896	if (hw_off_limits(sc))
8897		rc = ENXIO;
8898	else
8899		t4_read_cong_tbl(sc, incr);
8900	mtx_unlock(&sc->reg_lock);
8901	if (rc)
8902		goto done;
8903
8904	for (i = 0; i < NCCTRL_WIN; ++i) {
8905		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8906		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8907		    incr[5][i], incr[6][i], incr[7][i]);
8908		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8909		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8910		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8911		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8912	}
8913
8914	rc = sbuf_finish(sb);
8915done:
8916	sbuf_delete(sb);
8917	return (rc);
8918}
8919
8920static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8921	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8922	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8923	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8924};
8925
8926static int
8927sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8928{
8929	struct adapter *sc = arg1;
8930	struct sbuf *sb;
8931	int rc, i, n, qid = arg2;
8932	uint32_t *buf, *p;
8933	char *qtype;
8934	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8935
8936	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8937	    ("%s: bad qid %d\n", __func__, qid));
8938
8939	if (qid < CIM_NUM_IBQ) {
8940		/* inbound queue */
8941		qtype = "IBQ";
8942		n = 4 * CIM_IBQ_SIZE;
8943		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8944		mtx_lock(&sc->reg_lock);
8945		if (hw_off_limits(sc))
8946			rc = -ENXIO;
8947		else
8948			rc = t4_read_cim_ibq(sc, qid, buf, n);
8949		mtx_unlock(&sc->reg_lock);
8950	} else {
8951		/* outbound queue */
8952		qtype = "OBQ";
8953		qid -= CIM_NUM_IBQ;
8954		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8955		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8956		mtx_lock(&sc->reg_lock);
8957		if (hw_off_limits(sc))
8958			rc = -ENXIO;
8959		else
8960			rc = t4_read_cim_obq(sc, qid, buf, n);
8961		mtx_unlock(&sc->reg_lock);
8962	}
8963
8964	if (rc < 0) {
8965		rc = -rc;
8966		goto done;
8967	}
8968	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8969
8970	rc = sysctl_wire_old_buffer(req, 0);
8971	if (rc != 0)
8972		goto done;
8973
8974	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8975	if (sb == NULL) {
8976		rc = ENOMEM;
8977		goto done;
8978	}
8979
8980	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8981	for (i = 0, p = buf; i < n; i += 16, p += 4)
8982		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8983		    p[2], p[3]);
8984
8985	rc = sbuf_finish(sb);
8986	sbuf_delete(sb);
8987done:
8988	free(buf, M_CXGBE);
8989	return (rc);
8990}
8991
8992static void
8993sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8994{
8995	uint32_t *p;
8996
8997	sbuf_printf(sb, "Status   Data      PC%s",
8998	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8999	    "     LS0Stat  LS0Addr             LS0Data");
9000
9001	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9002		if (cfg & F_UPDBGLACAPTPCONLY) {
9003			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9004			    p[6], p[7]);
9005			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9006			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9007			    p[4] & 0xff, p[5] >> 8);
9008			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9009			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9010			    p[1] & 0xf, p[2] >> 4);
9011		} else {
9012			sbuf_printf(sb,
9013			    "\n  %02x   %x%07x %x%07x %08x %08x "
9014			    "%08x%08x%08x%08x",
9015			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9016			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9017			    p[6], p[7]);
9018		}
9019	}
9020}
9021
9022static void
9023sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9024{
9025	uint32_t *p;
9026
9027	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9028	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9029	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9030
9031	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9032		if (cfg & F_UPDBGLACAPTPCONLY) {
9033			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9034			    p[3] & 0xff, p[2], p[1], p[0]);
9035			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9036			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9037			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9038			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9039			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9040			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9041			    p[6] >> 16);
9042		} else {
9043			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9044			    "%08x %08x %08x %08x %08x %08x",
9045			    (p[9] >> 16) & 0xff,
9046			    p[9] & 0xffff, p[8] >> 16,
9047			    p[8] & 0xffff, p[7] >> 16,
9048			    p[7] & 0xffff, p[6] >> 16,
9049			    p[2], p[1], p[0], p[5], p[4], p[3]);
9050		}
9051	}
9052}
9053
9054static int
9055sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9056{
9057	uint32_t cfg, *buf;
9058	int rc;
9059
9060	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9061	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9062	    M_ZERO | flags);
9063	if (buf == NULL)
9064		return (ENOMEM);
9065
9066	mtx_lock(&sc->reg_lock);
9067	if (hw_off_limits(sc))
9068		rc = ENXIO;
9069	else {
9070		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9071		if (rc == 0)
9072			rc = -t4_cim_read_la(sc, buf, NULL);
9073	}
9074	mtx_unlock(&sc->reg_lock);
9075	if (rc == 0) {
9076		if (chip_id(sc) < CHELSIO_T6)
9077			sbuf_cim_la4(sc, sb, buf, cfg);
9078		else
9079			sbuf_cim_la6(sc, sb, buf, cfg);
9080	}
9081	free(buf, M_CXGBE);
9082	return (rc);
9083}
9084
9085static int
9086sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9087{
9088	struct adapter *sc = arg1;
9089	struct sbuf *sb;
9090	int rc;
9091
9092	rc = sysctl_wire_old_buffer(req, 0);
9093	if (rc != 0)
9094		return (rc);
9095	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9096	if (sb == NULL)
9097		return (ENOMEM);
9098
9099	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9100	if (rc == 0)
9101		rc = sbuf_finish(sb);
9102	sbuf_delete(sb);
9103	return (rc);
9104}
9105
9106static void
9107dump_cim_regs(struct adapter *sc)
9108{
9109	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9110	    device_get_nameunit(sc->dev),
9111	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9112	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9113	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9114	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9115	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9116	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9117	    device_get_nameunit(sc->dev),
9118	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9119	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9120	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9121	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9122	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9123}
9124
9125static void
9126dump_cimla(struct adapter *sc)
9127{
9128	struct sbuf sb;
9129	int rc;
9130
9131	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9132		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9133		    device_get_nameunit(sc->dev));
9134		return;
9135	}
9136	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9137	if (rc == 0) {
9138		rc = sbuf_finish(&sb);
9139		if (rc == 0) {
9140			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9141			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9142		}
9143	}
9144	sbuf_delete(&sb);
9145}
9146
9147void
9148t4_os_cim_err(struct adapter *sc)
9149{
9150	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9151}
9152
9153static int
9154sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9155{
9156	struct adapter *sc = arg1;
9157	u_int i;
9158	struct sbuf *sb;
9159	uint32_t *buf, *p;
9160	int rc;
9161
9162	rc = sysctl_wire_old_buffer(req, 0);
9163	if (rc != 0)
9164		return (rc);
9165
9166	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9167	if (sb == NULL)
9168		return (ENOMEM);
9169
9170	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9171	    M_ZERO | M_WAITOK);
9172
9173	mtx_lock(&sc->reg_lock);
9174	if (hw_off_limits(sc))
9175		rc = ENXIO;
9176	else
9177		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9178	mtx_unlock(&sc->reg_lock);
9179	if (rc)
9180		goto done;
9181
9182	p = buf;
9183	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9184		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9185		    p[1], p[0]);
9186	}
9187
9188	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9189	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9190		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9191		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9192		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9193		    (p[1] >> 2) | ((p[2] & 3) << 30),
9194		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9195		    p[0] & 1);
9196	}
9197	rc = sbuf_finish(sb);
9198done:
9199	sbuf_delete(sb);
9200	free(buf, M_CXGBE);
9201	return (rc);
9202}
9203
9204static int
9205sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9206{
9207	struct adapter *sc = arg1;
9208	u_int i;
9209	struct sbuf *sb;
9210	uint32_t *buf, *p;
9211	int rc;
9212
9213	rc = sysctl_wire_old_buffer(req, 0);
9214	if (rc != 0)
9215		return (rc);
9216
9217	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9218	if (sb == NULL)
9219		return (ENOMEM);
9220
9221	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9222	    M_ZERO | M_WAITOK);
9223
9224	mtx_lock(&sc->reg_lock);
9225	if (hw_off_limits(sc))
9226		rc = ENXIO;
9227	else
9228		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9229	mtx_unlock(&sc->reg_lock);
9230	if (rc)
9231		goto done;
9232
9233	p = buf;
9234	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9235	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9236		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9237		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9238		    p[4], p[3], p[2], p[1], p[0]);
9239	}
9240
9241	sbuf_printf(sb, "\n\nCntl ID               Data");
9242	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9243		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9244		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9245	}
9246
9247	rc = sbuf_finish(sb);
9248done:
9249	sbuf_delete(sb);
9250	free(buf, M_CXGBE);
9251	return (rc);
9252}
9253
9254static int
9255sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9256{
9257	struct adapter *sc = arg1;
9258	struct sbuf *sb;
9259	int rc, i;
9260	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9261	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9262	uint16_t thres[CIM_NUM_IBQ];
9263	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9264	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9265	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9266
9267	cim_num_obq = sc->chip_params->cim_num_obq;
9268	if (is_t4(sc)) {
9269		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9270		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9271	} else {
9272		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9273		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9274	}
9275	nq = CIM_NUM_IBQ + cim_num_obq;
9276
9277	mtx_lock(&sc->reg_lock);
9278	if (hw_off_limits(sc))
9279		rc = ENXIO;
9280	else {
9281		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9282		if (rc == 0) {
9283			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9284			    obq_wr);
9285			if (rc == 0)
9286				t4_read_cimq_cfg(sc, base, size, thres);
9287		}
9288	}
9289	mtx_unlock(&sc->reg_lock);
9290	if (rc)
9291		return (rc);
9292
9293	rc = sysctl_wire_old_buffer(req, 0);
9294	if (rc != 0)
9295		return (rc);
9296
9297	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9298	if (sb == NULL)
9299		return (ENOMEM);
9300
9301	sbuf_printf(sb,
9302	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9303
9304	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9305		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9306		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9307		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9308		    G_QUEREMFLITS(p[2]) * 16);
9309	for ( ; i < nq; i++, p += 4, wr += 2)
9310		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9311		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9312		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9313		    G_QUEREMFLITS(p[2]) * 16);
9314
9315	rc = sbuf_finish(sb);
9316	sbuf_delete(sb);
9317
9318	return (rc);
9319}
9320
9321static int
9322sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9323{
9324	struct adapter *sc = arg1;
9325	struct sbuf *sb;
9326	int rc;
9327	struct tp_cpl_stats stats;
9328
9329	rc = sysctl_wire_old_buffer(req, 0);
9330	if (rc != 0)
9331		return (rc);
9332
9333	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9334	if (sb == NULL)
9335		return (ENOMEM);
9336
9337	mtx_lock(&sc->reg_lock);
9338	if (hw_off_limits(sc))
9339		rc = ENXIO;
9340	else
9341		t4_tp_get_cpl_stats(sc, &stats, 0);
9342	mtx_unlock(&sc->reg_lock);
9343	if (rc)
9344		goto done;
9345
9346	if (sc->chip_params->nchan > 2) {
9347		sbuf_printf(sb, "                 channel 0  channel 1"
9348		    "  channel 2  channel 3");
9349		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9350		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9351		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9352		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9353	} else {
9354		sbuf_printf(sb, "                 channel 0  channel 1");
9355		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9356		    stats.req[0], stats.req[1]);
9357		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9358		    stats.rsp[0], stats.rsp[1]);
9359	}
9360
9361	rc = sbuf_finish(sb);
9362done:
9363	sbuf_delete(sb);
9364	return (rc);
9365}
9366
9367static int
9368sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9369{
9370	struct adapter *sc = arg1;
9371	struct sbuf *sb;
9372	int rc;
9373	struct tp_usm_stats stats;
9374
9375	rc = sysctl_wire_old_buffer(req, 0);
9376	if (rc != 0)
9377		return(rc);
9378
9379	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9380	if (sb == NULL)
9381		return (ENOMEM);
9382
9383	mtx_lock(&sc->reg_lock);
9384	if (hw_off_limits(sc))
9385		rc = ENXIO;
9386	else
9387		t4_get_usm_stats(sc, &stats, 1);
9388	mtx_unlock(&sc->reg_lock);
9389	if (rc == 0) {
9390		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9391		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9392		sbuf_printf(sb, "Drops:  %u", stats.drops);
9393		rc = sbuf_finish(sb);
9394	}
9395	sbuf_delete(sb);
9396
9397	return (rc);
9398}
9399
9400static int
9401sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9402{
9403	struct adapter *sc = arg1;
9404	struct sbuf *sb;
9405	int rc;
9406	struct tp_tid_stats stats;
9407
9408	rc = sysctl_wire_old_buffer(req, 0);
9409	if (rc != 0)
9410		return(rc);
9411
9412	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9413	if (sb == NULL)
9414		return (ENOMEM);
9415
9416	mtx_lock(&sc->reg_lock);
9417	if (hw_off_limits(sc))
9418		rc = ENXIO;
9419	else
9420		t4_tp_get_tid_stats(sc, &stats, 1);
9421	mtx_unlock(&sc->reg_lock);
9422	if (rc == 0) {
9423		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9424		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9425		sbuf_printf(sb, "Active:     %u\n", stats.act);
9426		sbuf_printf(sb, "Passive:    %u", stats.pas);
9427		rc = sbuf_finish(sb);
9428	}
9429	sbuf_delete(sb);
9430
9431	return (rc);
9432}
9433
9434static const char * const devlog_level_strings[] = {
9435	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9436	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9437	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9438	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9439	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9440	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9441};
9442
9443static const char * const devlog_facility_strings[] = {
9444	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9445	[FW_DEVLOG_FACILITY_CF]		= "CF",
9446	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9447	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9448	[FW_DEVLOG_FACILITY_RES]	= "RES",
9449	[FW_DEVLOG_FACILITY_HW]		= "HW",
9450	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9451	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9452	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9453	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9454	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9455	[FW_DEVLOG_FACILITY_VI]		= "VI",
9456	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9457	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9458	[FW_DEVLOG_FACILITY_TM]		= "TM",
9459	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9460	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9461	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9462	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9463	[FW_DEVLOG_FACILITY_RI]		= "RI",
9464	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9465	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9466	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9467	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9468	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9469};
9470
9471static int
9472sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9473{
9474	int i, j, rc, nentries, first = 0;
9475	struct devlog_params *dparams = &sc->params.devlog;
9476	struct fw_devlog_e *buf, *e;
9477	uint64_t ftstamp = UINT64_MAX;
9478
9479	if (dparams->addr == 0)
9480		return (ENXIO);
9481
9482	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9483	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9484	if (buf == NULL)
9485		return (ENOMEM);
9486
9487	mtx_lock(&sc->reg_lock);
9488	if (hw_off_limits(sc))
9489		rc = ENXIO;
9490	else
9491		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9492		    dparams->size);
9493	mtx_unlock(&sc->reg_lock);
9494	if (rc != 0)
9495		goto done;
9496
9497	nentries = dparams->size / sizeof(struct fw_devlog_e);
9498	for (i = 0; i < nentries; i++) {
9499		e = &buf[i];
9500
9501		if (e->timestamp == 0)
9502			break;	/* end */
9503
9504		e->timestamp = be64toh(e->timestamp);
9505		e->seqno = be32toh(e->seqno);
9506		for (j = 0; j < 8; j++)
9507			e->params[j] = be32toh(e->params[j]);
9508
9509		if (e->timestamp < ftstamp) {
9510			ftstamp = e->timestamp;
9511			first = i;
9512		}
9513	}
9514
9515	if (buf[first].timestamp == 0)
9516		goto done;	/* nothing in the log */
9517
9518	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9519	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9520
9521	i = first;
9522	do {
9523		e = &buf[i];
9524		if (e->timestamp == 0)
9525			break;	/* end */
9526
9527		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9528		    e->seqno, e->timestamp,
9529		    (e->level < nitems(devlog_level_strings) ?
9530			devlog_level_strings[e->level] : "UNKNOWN"),
9531		    (e->facility < nitems(devlog_facility_strings) ?
9532			devlog_facility_strings[e->facility] : "UNKNOWN"));
9533		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9534		    e->params[2], e->params[3], e->params[4],
9535		    e->params[5], e->params[6], e->params[7]);
9536
9537		if (++i == nentries)
9538			i = 0;
9539	} while (i != first);
9540done:
9541	free(buf, M_CXGBE);
9542	return (rc);
9543}
9544
9545static int
9546sysctl_devlog(SYSCTL_HANDLER_ARGS)
9547{
9548	struct adapter *sc = arg1;
9549	int rc;
9550	struct sbuf *sb;
9551
9552	rc = sysctl_wire_old_buffer(req, 0);
9553	if (rc != 0)
9554		return (rc);
9555	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9556	if (sb == NULL)
9557		return (ENOMEM);
9558
9559	rc = sbuf_devlog(sc, sb, M_WAITOK);
9560	if (rc == 0)
9561		rc = sbuf_finish(sb);
9562	sbuf_delete(sb);
9563	return (rc);
9564}
9565
9566static void
9567dump_devlog(struct adapter *sc)
9568{
9569	int rc;
9570	struct sbuf sb;
9571
9572	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9573		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9574		    device_get_nameunit(sc->dev));
9575		return;
9576	}
9577	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9578	if (rc == 0) {
9579		rc = sbuf_finish(&sb);
9580		if (rc == 0) {
9581			log(LOG_DEBUG, "%s: device log follows.\n%s",
9582			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9583		}
9584	}
9585	sbuf_delete(&sb);
9586}
9587
9588static int
9589sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9590{
9591	struct adapter *sc = arg1;
9592	struct sbuf *sb;
9593	int rc;
9594	struct tp_fcoe_stats stats[MAX_NCHAN];
9595	int i, nchan = sc->chip_params->nchan;
9596
9597	rc = sysctl_wire_old_buffer(req, 0);
9598	if (rc != 0)
9599		return (rc);
9600
9601	mtx_lock(&sc->reg_lock);
9602	if (hw_off_limits(sc))
9603		rc = ENXIO;
9604	else {
9605		for (i = 0; i < nchan; i++)
9606			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9607	}
9608	mtx_unlock(&sc->reg_lock);
9609	if (rc != 0)
9610		return (rc);
9611
9612	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9613	if (sb == NULL)
9614		return (ENOMEM);
9615
9616	if (nchan > 2) {
9617		sbuf_printf(sb, "                   channel 0        channel 1"
9618		    "        channel 2        channel 3");
9619		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9620		    stats[0].octets_ddp, stats[1].octets_ddp,
9621		    stats[2].octets_ddp, stats[3].octets_ddp);
9622		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9623		    stats[0].frames_ddp, stats[1].frames_ddp,
9624		    stats[2].frames_ddp, stats[3].frames_ddp);
9625		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9626		    stats[0].frames_drop, stats[1].frames_drop,
9627		    stats[2].frames_drop, stats[3].frames_drop);
9628	} else {
9629		sbuf_printf(sb, "                   channel 0        channel 1");
9630		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9631		    stats[0].octets_ddp, stats[1].octets_ddp);
9632		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9633		    stats[0].frames_ddp, stats[1].frames_ddp);
9634		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9635		    stats[0].frames_drop, stats[1].frames_drop);
9636	}
9637
9638	rc = sbuf_finish(sb);
9639	sbuf_delete(sb);
9640
9641	return (rc);
9642}
9643
9644static int
9645sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9646{
9647	struct adapter *sc = arg1;
9648	struct sbuf *sb;
9649	int rc, i;
9650	unsigned int map, kbps, ipg, mode;
9651	unsigned int pace_tab[NTX_SCHED];
9652
9653	rc = sysctl_wire_old_buffer(req, 0);
9654	if (rc != 0)
9655		return (rc);
9656
9657	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9658	if (sb == NULL)
9659		return (ENOMEM);
9660
9661	mtx_lock(&sc->reg_lock);
9662	if (hw_off_limits(sc)) {
9663		rc = ENXIO;
9664		goto done;
9665	}
9666
9667	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9668	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9669	t4_read_pace_tbl(sc, pace_tab);
9670
9671	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9672	    "Class IPG (0.1 ns)   Flow IPG (us)");
9673
9674	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9675		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9676		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9677		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9678		if (kbps)
9679			sbuf_printf(sb, "%9u     ", kbps);
9680		else
9681			sbuf_printf(sb, " disabled     ");
9682
9683		if (ipg)
9684			sbuf_printf(sb, "%13u        ", ipg);
9685		else
9686			sbuf_printf(sb, "     disabled        ");
9687
9688		if (pace_tab[i])
9689			sbuf_printf(sb, "%10u", pace_tab[i]);
9690		else
9691			sbuf_printf(sb, "  disabled");
9692	}
9693	rc = sbuf_finish(sb);
9694done:
9695	mtx_unlock(&sc->reg_lock);
9696	sbuf_delete(sb);
9697	return (rc);
9698}
9699
9700static int
9701sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9702{
9703	struct adapter *sc = arg1;
9704	struct sbuf *sb;
9705	int rc, i, j;
9706	uint64_t *p0, *p1;
9707	struct lb_port_stats s[2];
9708	static const char *stat_name[] = {
9709		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9710		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9711		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9712		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9713		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9714		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9715		"BG2FramesTrunc:", "BG3FramesTrunc:"
9716	};
9717
9718	rc = sysctl_wire_old_buffer(req, 0);
9719	if (rc != 0)
9720		return (rc);
9721
9722	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9723	if (sb == NULL)
9724		return (ENOMEM);
9725
9726	memset(s, 0, sizeof(s));
9727
9728	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9729		mtx_lock(&sc->reg_lock);
9730		if (hw_off_limits(sc))
9731			rc = ENXIO;
9732		else {
9733			t4_get_lb_stats(sc, i, &s[0]);
9734			t4_get_lb_stats(sc, i + 1, &s[1]);
9735		}
9736		mtx_unlock(&sc->reg_lock);
9737		if (rc != 0)
9738			break;
9739
9740		p0 = &s[0].octets;
9741		p1 = &s[1].octets;
9742		sbuf_printf(sb, "%s                       Loopback %u"
9743		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9744
9745		for (j = 0; j < nitems(stat_name); j++)
9746			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9747				   *p0++, *p1++);
9748	}
9749
9750	rc = sbuf_finish(sb);
9751	sbuf_delete(sb);
9752
9753	return (rc);
9754}
9755
9756static int
9757sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9758{
9759	int rc = 0;
9760	struct port_info *pi = arg1;
9761	struct link_config *lc = &pi->link_cfg;
9762	struct sbuf *sb;
9763
9764	rc = sysctl_wire_old_buffer(req, 0);
9765	if (rc != 0)
9766		return(rc);
9767	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9768	if (sb == NULL)
9769		return (ENOMEM);
9770
9771	if (lc->link_ok || lc->link_down_rc == 255)
9772		sbuf_printf(sb, "n/a");
9773	else
9774		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9775
9776	rc = sbuf_finish(sb);
9777	sbuf_delete(sb);
9778
9779	return (rc);
9780}
9781
9782struct mem_desc {
9783	u_int base;
9784	u_int limit;
9785	u_int idx;
9786};
9787
9788static int
9789mem_desc_cmp(const void *a, const void *b)
9790{
9791	const u_int v1 = ((const struct mem_desc *)a)->base;
9792	const u_int v2 = ((const struct mem_desc *)b)->base;
9793
9794	if (v1 < v2)
9795		return (-1);
9796	else if (v1 > v2)
9797		return (1);
9798
9799	return (0);
9800}
9801
9802static void
9803mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9804    unsigned int to)
9805{
9806	unsigned int size;
9807
9808	if (from == to)
9809		return;
9810
9811	size = to - from + 1;
9812	if (size == 0)
9813		return;
9814
9815	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9816	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9817}
9818
9819static int
9820sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9821{
9822	struct adapter *sc = arg1;
9823	struct sbuf *sb;
9824	int rc, i, n;
9825	uint32_t lo, hi, used, free, alloc;
9826	static const char *memory[] = {
9827		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9828	};
9829	static const char *region[] = {
9830		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9831		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9832		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9833		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9834		"RQUDP region:", "PBL region:", "TXPBL region:",
9835		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9836		"ULPTX state:", "On-chip queues:",
9837	};
9838	struct mem_desc avail[4];
9839	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9840	struct mem_desc *md = mem;
9841
9842	rc = sysctl_wire_old_buffer(req, 0);
9843	if (rc != 0)
9844		return (rc);
9845
9846	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9847	if (sb == NULL)
9848		return (ENOMEM);
9849
9850	for (i = 0; i < nitems(mem); i++) {
9851		mem[i].limit = 0;
9852		mem[i].idx = i;
9853	}
9854
9855	mtx_lock(&sc->reg_lock);
9856	if (hw_off_limits(sc)) {
9857		rc = ENXIO;
9858		goto done;
9859	}
9860
9861	/* Find and sort the populated memory ranges */
9862	i = 0;
9863	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9864	if (lo & F_EDRAM0_ENABLE) {
9865		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9866		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9867		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9868		avail[i].idx = 0;
9869		i++;
9870	}
9871	if (lo & F_EDRAM1_ENABLE) {
9872		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9873		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9874		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9875		avail[i].idx = 1;
9876		i++;
9877	}
9878	if (lo & F_EXT_MEM_ENABLE) {
9879		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9880		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9881		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9882		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9883		i++;
9884	}
9885	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9886		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9887		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9888		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9889		avail[i].idx = 4;
9890		i++;
9891	}
9892	if (is_t6(sc) && lo & F_HMA_MUX) {
9893		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9894		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9895		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9896		avail[i].idx = 5;
9897		i++;
9898	}
9899	MPASS(i <= nitems(avail));
9900	if (!i)                                    /* no memory available */
9901		goto done;
9902	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9903
9904	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9905	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9906	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9907	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9908	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9909	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9910	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9911	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9912	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9913
9914	/* the next few have explicit upper bounds */
9915	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9916	md->limit = md->base - 1 +
9917		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9918		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9919	md++;
9920
9921	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9922	md->limit = md->base - 1 +
9923		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9924		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9925	md++;
9926
9927	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9928		if (chip_id(sc) <= CHELSIO_T5)
9929			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9930		else
9931			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9932		md->limit = 0;
9933	} else {
9934		md->base = 0;
9935		md->idx = nitems(region);  /* hide it */
9936	}
9937	md++;
9938
9939#define ulp_region(reg) \
9940	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9941	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9942
9943	ulp_region(RX_ISCSI);
9944	ulp_region(RX_TDDP);
9945	ulp_region(TX_TPT);
9946	ulp_region(RX_STAG);
9947	ulp_region(RX_RQ);
9948	ulp_region(RX_RQUDP);
9949	ulp_region(RX_PBL);
9950	ulp_region(TX_PBL);
9951	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9952		ulp_region(RX_TLS_KEY);
9953	}
9954#undef ulp_region
9955
9956	md->base = 0;
9957	if (is_t4(sc))
9958		md->idx = nitems(region);
9959	else {
9960		uint32_t size = 0;
9961		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9962		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9963
9964		if (is_t5(sc)) {
9965			if (sge_ctrl & F_VFIFO_ENABLE)
9966				size = fifo_size << 2;
9967		} else
9968			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9969
9970		if (size) {
9971			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9972			md->limit = md->base + size - 1;
9973		} else
9974			md->idx = nitems(region);
9975	}
9976	md++;
9977
9978	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9979	md->limit = 0;
9980	md++;
9981	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9982	md->limit = 0;
9983	md++;
9984
9985	md->base = sc->vres.ocq.start;
9986	if (sc->vres.ocq.size)
9987		md->limit = md->base + sc->vres.ocq.size - 1;
9988	else
9989		md->idx = nitems(region);  /* hide it */
9990	md++;
9991
9992	/* add any address-space holes, there can be up to 3 */
9993	for (n = 0; n < i - 1; n++)
9994		if (avail[n].limit < avail[n + 1].base)
9995			(md++)->base = avail[n].limit;
9996	if (avail[n].limit)
9997		(md++)->base = avail[n].limit;
9998
9999	n = md - mem;
10000	MPASS(n <= nitems(mem));
10001	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10002
10003	for (lo = 0; lo < i; lo++)
10004		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10005				avail[lo].limit - 1);
10006
10007	sbuf_printf(sb, "\n");
10008	for (i = 0; i < n; i++) {
10009		if (mem[i].idx >= nitems(region))
10010			continue;                        /* skip holes */
10011		if (!mem[i].limit)
10012			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10013		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10014				mem[i].limit);
10015	}
10016
10017	sbuf_printf(sb, "\n");
10018	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10019	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10020	mem_region_show(sb, "uP RAM:", lo, hi);
10021
10022	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10023	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10024	mem_region_show(sb, "uP Extmem2:", lo, hi);
10025
10026	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10027	for (i = 0, free = 0; i < 2; i++)
10028		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10029	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10030		   G_PMRXMAXPAGE(lo), free,
10031		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10032		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10033
10034	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10035	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10036	for (i = 0, free = 0; i < 4; i++)
10037		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10038	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10039		   G_PMTXMAXPAGE(lo), free,
10040		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10041		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10042	sbuf_printf(sb, "%u p-structs (%u free)\n",
10043		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10044		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10045
10046	for (i = 0; i < 4; i++) {
10047		if (chip_id(sc) > CHELSIO_T5)
10048			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10049		else
10050			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10051		if (is_t5(sc)) {
10052			used = G_T5_USED(lo);
10053			alloc = G_T5_ALLOC(lo);
10054		} else {
10055			used = G_USED(lo);
10056			alloc = G_ALLOC(lo);
10057		}
10058		/* For T6 these are MAC buffer groups */
10059		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10060		    i, used, alloc);
10061	}
10062	for (i = 0; i < sc->chip_params->nchan; i++) {
10063		if (chip_id(sc) > CHELSIO_T5)
10064			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10065		else
10066			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10067		if (is_t5(sc)) {
10068			used = G_T5_USED(lo);
10069			alloc = G_T5_ALLOC(lo);
10070		} else {
10071			used = G_USED(lo);
10072			alloc = G_ALLOC(lo);
10073		}
10074		/* For T6 these are MAC buffer groups */
10075		sbuf_printf(sb,
10076		    "\nLoopback %d using %u pages out of %u allocated",
10077		    i, used, alloc);
10078	}
10079done:
10080	mtx_unlock(&sc->reg_lock);
10081	if (rc == 0)
10082		rc = sbuf_finish(sb);
10083	sbuf_delete(sb);
10084	return (rc);
10085}
10086
10087static inline void
10088tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10089{
10090	*mask = x | y;
10091	y = htobe64(y);
10092	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10093}
10094
10095static int
10096sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10097{
10098	struct adapter *sc = arg1;
10099	struct sbuf *sb;
10100	int rc, i;
10101
10102	MPASS(chip_id(sc) <= CHELSIO_T5);
10103
10104	rc = sysctl_wire_old_buffer(req, 0);
10105	if (rc != 0)
10106		return (rc);
10107
10108	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10109	if (sb == NULL)
10110		return (ENOMEM);
10111
10112	sbuf_printf(sb,
10113	    "Idx  Ethernet address     Mask     Vld Ports PF"
10114	    "  VF              Replication             P0 P1 P2 P3  ML");
10115	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10116		uint64_t tcamx, tcamy, mask;
10117		uint32_t cls_lo, cls_hi;
10118		uint8_t addr[ETHER_ADDR_LEN];
10119
10120		mtx_lock(&sc->reg_lock);
10121		if (hw_off_limits(sc))
10122			rc = ENXIO;
10123		else {
10124			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10125			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10126		}
10127		mtx_unlock(&sc->reg_lock);
10128		if (rc != 0)
10129			break;
10130		if (tcamx & tcamy)
10131			continue;
10132		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10133		mtx_lock(&sc->reg_lock);
10134		if (hw_off_limits(sc))
10135			rc = ENXIO;
10136		else {
10137			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10138			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10139		}
10140		mtx_unlock(&sc->reg_lock);
10141		if (rc != 0)
10142			break;
10143		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10144			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10145			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10146			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10147			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10148			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10149
10150		if (cls_lo & F_REPLICATE) {
10151			struct fw_ldst_cmd ldst_cmd;
10152
10153			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10154			ldst_cmd.op_to_addrspace =
10155			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10156				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10157				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10158			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10159			ldst_cmd.u.mps.rplc.fid_idx =
10160			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10161				V_FW_LDST_CMD_IDX(i));
10162
10163			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10164			    "t4mps");
10165			if (rc)
10166				break;
10167			if (hw_off_limits(sc))
10168				rc = ENXIO;
10169			else
10170				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10171				    sizeof(ldst_cmd), &ldst_cmd);
10172			end_synchronized_op(sc, 0);
10173			if (rc != 0)
10174				break;
10175			else {
10176				sbuf_printf(sb, " %08x %08x %08x %08x",
10177				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10178				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10179				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10180				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10181			}
10182		} else
10183			sbuf_printf(sb, "%36s", "");
10184
10185		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10186		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10187		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10188	}
10189
10190	if (rc)
10191		(void) sbuf_finish(sb);
10192	else
10193		rc = sbuf_finish(sb);
10194	sbuf_delete(sb);
10195
10196	return (rc);
10197}
10198
10199static int
10200sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10201{
10202	struct adapter *sc = arg1;
10203	struct sbuf *sb;
10204	int rc, i;
10205
10206	MPASS(chip_id(sc) > CHELSIO_T5);
10207
10208	rc = sysctl_wire_old_buffer(req, 0);
10209	if (rc != 0)
10210		return (rc);
10211
10212	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10213	if (sb == NULL)
10214		return (ENOMEM);
10215
10216	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10217	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10218	    "                           Replication"
10219	    "                                    P0 P1 P2 P3  ML\n");
10220
10221	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10222		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10223		uint16_t ivlan;
10224		uint64_t tcamx, tcamy, val, mask;
10225		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10226		uint8_t addr[ETHER_ADDR_LEN];
10227
10228		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10229		if (i < 256)
10230			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10231		else
10232			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10233		mtx_lock(&sc->reg_lock);
10234		if (hw_off_limits(sc))
10235			rc = ENXIO;
10236		else {
10237			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10238			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10239			tcamy = G_DMACH(val) << 32;
10240			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10241			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10242		}
10243		mtx_unlock(&sc->reg_lock);
10244		if (rc != 0)
10245			break;
10246
10247		lookup_type = G_DATALKPTYPE(data2);
10248		port_num = G_DATAPORTNUM(data2);
10249		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10250			/* Inner header VNI */
10251			vniy = ((data2 & F_DATAVIDH2) << 23) |
10252				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10253			dip_hit = data2 & F_DATADIPHIT;
10254			vlan_vld = 0;
10255		} else {
10256			vniy = 0;
10257			dip_hit = 0;
10258			vlan_vld = data2 & F_DATAVIDH2;
10259			ivlan = G_VIDL(val);
10260		}
10261
10262		ctl |= V_CTLXYBITSEL(1);
10263		mtx_lock(&sc->reg_lock);
10264		if (hw_off_limits(sc))
10265			rc = ENXIO;
10266		else {
10267			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10268			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10269			tcamx = G_DMACH(val) << 32;
10270			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10271			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10272		}
10273		mtx_unlock(&sc->reg_lock);
10274		if (rc != 0)
10275			break;
10276
10277		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10278			/* Inner header VNI mask */
10279			vnix = ((data2 & F_DATAVIDH2) << 23) |
10280			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10281		} else
10282			vnix = 0;
10283
10284		if (tcamx & tcamy)
10285			continue;
10286		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10287
10288		mtx_lock(&sc->reg_lock);
10289		if (hw_off_limits(sc))
10290			rc = ENXIO;
10291		else {
10292			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10293			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10294		}
10295		mtx_unlock(&sc->reg_lock);
10296		if (rc != 0)
10297			break;
10298
10299		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10300			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10301			    "%012jx %06x %06x    -    -   %3c"
10302			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10303			    addr[1], addr[2], addr[3], addr[4], addr[5],
10304			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10305			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10306			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10307			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10308		} else {
10309			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10310			    "%012jx    -       -   ", i, addr[0], addr[1],
10311			    addr[2], addr[3], addr[4], addr[5],
10312			    (uintmax_t)mask);
10313
10314			if (vlan_vld)
10315				sbuf_printf(sb, "%4u   Y     ", ivlan);
10316			else
10317				sbuf_printf(sb, "  -    N     ");
10318
10319			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10320			    lookup_type ? 'I' : 'O', port_num,
10321			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10322			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10323			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10324		}
10325
10326
10327		if (cls_lo & F_T6_REPLICATE) {
10328			struct fw_ldst_cmd ldst_cmd;
10329
10330			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10331			ldst_cmd.op_to_addrspace =
10332			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10333				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10334				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10335			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10336			ldst_cmd.u.mps.rplc.fid_idx =
10337			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10338				V_FW_LDST_CMD_IDX(i));
10339
10340			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10341			    "t6mps");
10342			if (rc)
10343				break;
10344			if (hw_off_limits(sc))
10345				rc = ENXIO;
10346			else
10347				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10348				    sizeof(ldst_cmd), &ldst_cmd);
10349			end_synchronized_op(sc, 0);
10350			if (rc != 0)
10351				break;
10352			else {
10353				sbuf_printf(sb, " %08x %08x %08x %08x"
10354				    " %08x %08x %08x %08x",
10355				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10356				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10357				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10358				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10359				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10360				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10361				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10362				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10363			}
10364		} else
10365			sbuf_printf(sb, "%72s", "");
10366
10367		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10368		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10369		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10370		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10371	}
10372
10373	if (rc)
10374		(void) sbuf_finish(sb);
10375	else
10376		rc = sbuf_finish(sb);
10377	sbuf_delete(sb);
10378
10379	return (rc);
10380}
10381
10382static int
10383sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10384{
10385	struct adapter *sc = arg1;
10386	struct sbuf *sb;
10387	int rc;
10388	uint16_t mtus[NMTUS];
10389
10390	rc = sysctl_wire_old_buffer(req, 0);
10391	if (rc != 0)
10392		return (rc);
10393
10394	mtx_lock(&sc->reg_lock);
10395	if (hw_off_limits(sc))
10396		rc = ENXIO;
10397	else
10398		t4_read_mtu_tbl(sc, mtus, NULL);
10399	mtx_unlock(&sc->reg_lock);
10400	if (rc != 0)
10401		return (rc);
10402
10403	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10404	if (sb == NULL)
10405		return (ENOMEM);
10406
10407	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10408	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10409	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10410	    mtus[14], mtus[15]);
10411
10412	rc = sbuf_finish(sb);
10413	sbuf_delete(sb);
10414
10415	return (rc);
10416}
10417
10418static int
10419sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10420{
10421	struct adapter *sc = arg1;
10422	struct sbuf *sb;
10423	int rc, i;
10424	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10425	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10426	static const char *tx_stats[MAX_PM_NSTATS] = {
10427		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10428		"Tx FIFO wait", NULL, "Tx latency"
10429	};
10430	static const char *rx_stats[MAX_PM_NSTATS] = {
10431		"Read:", "Write bypass:", "Write mem:", "Flush:",
10432		"Rx FIFO wait", NULL, "Rx latency"
10433	};
10434
10435	rc = sysctl_wire_old_buffer(req, 0);
10436	if (rc != 0)
10437		return (rc);
10438
10439	mtx_lock(&sc->reg_lock);
10440	if (hw_off_limits(sc))
10441		rc = ENXIO;
10442	else {
10443		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10444		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10445	}
10446	mtx_unlock(&sc->reg_lock);
10447	if (rc != 0)
10448		return (rc);
10449
10450	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10451	if (sb == NULL)
10452		return (ENOMEM);
10453
10454	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10455	for (i = 0; i < 4; i++) {
10456		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10457		    tx_cyc[i]);
10458	}
10459
10460	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10461	for (i = 0; i < 4; i++) {
10462		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10463		    rx_cyc[i]);
10464	}
10465
10466	if (chip_id(sc) > CHELSIO_T5) {
10467		sbuf_printf(sb,
10468		    "\n              Total wait      Total occupancy");
10469		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10470		    tx_cyc[i]);
10471		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10472		    rx_cyc[i]);
10473
10474		i += 2;
10475		MPASS(i < nitems(tx_stats));
10476
10477		sbuf_printf(sb,
10478		    "\n                   Reads           Total wait");
10479		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10480		    tx_cyc[i]);
10481		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10482		    rx_cyc[i]);
10483	}
10484
10485	rc = sbuf_finish(sb);
10486	sbuf_delete(sb);
10487
10488	return (rc);
10489}
10490
10491static int
10492sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10493{
10494	struct adapter *sc = arg1;
10495	struct sbuf *sb;
10496	int rc;
10497	struct tp_rdma_stats stats;
10498
10499	rc = sysctl_wire_old_buffer(req, 0);
10500	if (rc != 0)
10501		return (rc);
10502
10503	mtx_lock(&sc->reg_lock);
10504	if (hw_off_limits(sc))
10505		rc = ENXIO;
10506	else
10507		t4_tp_get_rdma_stats(sc, &stats, 0);
10508	mtx_unlock(&sc->reg_lock);
10509	if (rc != 0)
10510		return (rc);
10511
10512	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10513	if (sb == NULL)
10514		return (ENOMEM);
10515
10516	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10517	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10518
10519	rc = sbuf_finish(sb);
10520	sbuf_delete(sb);
10521
10522	return (rc);
10523}
10524
10525static int
10526sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10527{
10528	struct adapter *sc = arg1;
10529	struct sbuf *sb;
10530	int rc;
10531	struct tp_tcp_stats v4, v6;
10532
10533	rc = sysctl_wire_old_buffer(req, 0);
10534	if (rc != 0)
10535		return (rc);
10536
10537	mtx_lock(&sc->reg_lock);
10538	if (hw_off_limits(sc))
10539		rc = ENXIO;
10540	else
10541		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10542	mtx_unlock(&sc->reg_lock);
10543	if (rc != 0)
10544		return (rc);
10545
10546	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10547	if (sb == NULL)
10548		return (ENOMEM);
10549
10550	sbuf_printf(sb,
10551	    "                                IP                 IPv6\n");
10552	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10553	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10554	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10555	    v4.tcp_in_segs, v6.tcp_in_segs);
10556	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10557	    v4.tcp_out_segs, v6.tcp_out_segs);
10558	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10559	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10560
10561	rc = sbuf_finish(sb);
10562	sbuf_delete(sb);
10563
10564	return (rc);
10565}
10566
10567static int
10568sysctl_tids(SYSCTL_HANDLER_ARGS)
10569{
10570	struct adapter *sc = arg1;
10571	struct sbuf *sb;
10572	int rc;
10573	uint32_t x, y;
10574	struct tid_info *t = &sc->tids;
10575
10576	rc = sysctl_wire_old_buffer(req, 0);
10577	if (rc != 0)
10578		return (rc);
10579
10580	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10581	if (sb == NULL)
10582		return (ENOMEM);
10583
10584	if (t->natids) {
10585		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10586		    t->atids_in_use);
10587	}
10588
10589	if (t->nhpftids) {
10590		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10591		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10592	}
10593
10594	if (t->ntids) {
10595		bool hashen = false;
10596
10597		mtx_lock(&sc->reg_lock);
10598		if (hw_off_limits(sc))
10599			rc = ENXIO;
10600		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10601			hashen = true;
10602			if (chip_id(sc) <= CHELSIO_T5) {
10603				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10604				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10605			} else {
10606				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10607				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10608			}
10609		}
10610		mtx_unlock(&sc->reg_lock);
10611		if (rc != 0)
10612			goto done;
10613
10614		sbuf_printf(sb, "TID range: ");
10615		if (hashen) {
10616			if (x)
10617				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10618			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10619		} else {
10620			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10621			    t->ntids - 1);
10622		}
10623		sbuf_printf(sb, ", in use: %u\n",
10624		    atomic_load_acq_int(&t->tids_in_use));
10625	}
10626
10627	if (t->nstids) {
10628		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10629		    t->stid_base + t->nstids - 1, t->stids_in_use);
10630	}
10631
10632	if (t->nftids) {
10633		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10634		    t->ftid_end, t->ftids_in_use);
10635	}
10636
10637	if (t->netids) {
10638		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10639		    t->etid_base + t->netids - 1, t->etids_in_use);
10640	}
10641
10642	mtx_lock(&sc->reg_lock);
10643	if (hw_off_limits(sc))
10644		rc = ENXIO;
10645	else {
10646		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10647		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10648	}
10649	mtx_unlock(&sc->reg_lock);
10650	if (rc != 0)
10651		goto done;
10652	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10653done:
10654	if (rc == 0)
10655		rc = sbuf_finish(sb);
10656	else
10657		(void)sbuf_finish(sb);
10658	sbuf_delete(sb);
10659
10660	return (rc);
10661}
10662
10663static int
10664sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10665{
10666	struct adapter *sc = arg1;
10667	struct sbuf *sb;
10668	int rc;
10669	struct tp_err_stats stats;
10670
10671	rc = sysctl_wire_old_buffer(req, 0);
10672	if (rc != 0)
10673		return (rc);
10674
10675	mtx_lock(&sc->reg_lock);
10676	if (hw_off_limits(sc))
10677		rc = ENXIO;
10678	else
10679		t4_tp_get_err_stats(sc, &stats, 0);
10680	mtx_unlock(&sc->reg_lock);
10681	if (rc != 0)
10682		return (rc);
10683
10684	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10685	if (sb == NULL)
10686		return (ENOMEM);
10687
10688	if (sc->chip_params->nchan > 2) {
10689		sbuf_printf(sb, "                 channel 0  channel 1"
10690		    "  channel 2  channel 3\n");
10691		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10692		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10693		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10694		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10695		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10696		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10697		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10698		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10699		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10700		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10701		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10702		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10703		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10704		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10705		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10706		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10707		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10708		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10709		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10710		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10711		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10712		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10713		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10714		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10715	} else {
10716		sbuf_printf(sb, "                 channel 0  channel 1\n");
10717		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10718		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10719		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10720		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10721		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10722		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10723		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10724		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10725		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10726		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10727		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10728		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10729		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10730		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10731		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10732		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10733	}
10734
10735	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10736	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10737
10738	rc = sbuf_finish(sb);
10739	sbuf_delete(sb);
10740
10741	return (rc);
10742}
10743
10744static int
10745sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10746{
10747	struct adapter *sc = arg1;
10748	struct sbuf *sb;
10749	int rc;
10750	struct tp_tnl_stats stats;
10751
10752	rc = sysctl_wire_old_buffer(req, 0);
10753	if (rc != 0)
10754		return(rc);
10755
10756	mtx_lock(&sc->reg_lock);
10757	if (hw_off_limits(sc))
10758		rc = ENXIO;
10759	else
10760		t4_tp_get_tnl_stats(sc, &stats, 1);
10761	mtx_unlock(&sc->reg_lock);
10762	if (rc != 0)
10763		return (rc);
10764
10765	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10766	if (sb == NULL)
10767		return (ENOMEM);
10768
10769	if (sc->chip_params->nchan > 2) {
10770		sbuf_printf(sb, "           channel 0  channel 1"
10771		    "  channel 2  channel 3\n");
10772		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10773		    stats.out_pkt[0], stats.out_pkt[1],
10774		    stats.out_pkt[2], stats.out_pkt[3]);
10775		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10776		    stats.in_pkt[0], stats.in_pkt[1],
10777		    stats.in_pkt[2], stats.in_pkt[3]);
10778	} else {
10779		sbuf_printf(sb, "           channel 0  channel 1\n");
10780		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10781		    stats.out_pkt[0], stats.out_pkt[1]);
10782		sbuf_printf(sb, "InPkts:   %10u %10u",
10783		    stats.in_pkt[0], stats.in_pkt[1]);
10784	}
10785
10786	rc = sbuf_finish(sb);
10787	sbuf_delete(sb);
10788
10789	return (rc);
10790}
10791
10792static int
10793sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10794{
10795	struct adapter *sc = arg1;
10796	struct tp_params *tpp = &sc->params.tp;
10797	u_int mask;
10798	int rc;
10799
10800	mask = tpp->la_mask >> 16;
10801	rc = sysctl_handle_int(oidp, &mask, 0, req);
10802	if (rc != 0 || req->newptr == NULL)
10803		return (rc);
10804	if (mask > 0xffff)
10805		return (EINVAL);
10806	mtx_lock(&sc->reg_lock);
10807	if (hw_off_limits(sc))
10808		rc = ENXIO;
10809	else {
10810		tpp->la_mask = mask << 16;
10811		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10812		    tpp->la_mask);
10813	}
10814	mtx_unlock(&sc->reg_lock);
10815
10816	return (rc);
10817}
10818
10819struct field_desc {
10820	const char *name;
10821	u_int start;
10822	u_int width;
10823};
10824
10825static void
10826field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10827{
10828	char buf[32];
10829	int line_size = 0;
10830
10831	while (f->name) {
10832		uint64_t mask = (1ULL << f->width) - 1;
10833		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10834		    ((uintmax_t)v >> f->start) & mask);
10835
10836		if (line_size + len >= 79) {
10837			line_size = 8;
10838			sbuf_printf(sb, "\n        ");
10839		}
10840		sbuf_printf(sb, "%s ", buf);
10841		line_size += len + 1;
10842		f++;
10843	}
10844	sbuf_printf(sb, "\n");
10845}
10846
10847static const struct field_desc tp_la0[] = {
10848	{ "RcfOpCodeOut", 60, 4 },
10849	{ "State", 56, 4 },
10850	{ "WcfState", 52, 4 },
10851	{ "RcfOpcSrcOut", 50, 2 },
10852	{ "CRxError", 49, 1 },
10853	{ "ERxError", 48, 1 },
10854	{ "SanityFailed", 47, 1 },
10855	{ "SpuriousMsg", 46, 1 },
10856	{ "FlushInputMsg", 45, 1 },
10857	{ "FlushInputCpl", 44, 1 },
10858	{ "RssUpBit", 43, 1 },
10859	{ "RssFilterHit", 42, 1 },
10860	{ "Tid", 32, 10 },
10861	{ "InitTcb", 31, 1 },
10862	{ "LineNumber", 24, 7 },
10863	{ "Emsg", 23, 1 },
10864	{ "EdataOut", 22, 1 },
10865	{ "Cmsg", 21, 1 },
10866	{ "CdataOut", 20, 1 },
10867	{ "EreadPdu", 19, 1 },
10868	{ "CreadPdu", 18, 1 },
10869	{ "TunnelPkt", 17, 1 },
10870	{ "RcfPeerFin", 16, 1 },
10871	{ "RcfReasonOut", 12, 4 },
10872	{ "TxCchannel", 10, 2 },
10873	{ "RcfTxChannel", 8, 2 },
10874	{ "RxEchannel", 6, 2 },
10875	{ "RcfRxChannel", 5, 1 },
10876	{ "RcfDataOutSrdy", 4, 1 },
10877	{ "RxDvld", 3, 1 },
10878	{ "RxOoDvld", 2, 1 },
10879	{ "RxCongestion", 1, 1 },
10880	{ "TxCongestion", 0, 1 },
10881	{ NULL }
10882};
10883
10884static const struct field_desc tp_la1[] = {
10885	{ "CplCmdIn", 56, 8 },
10886	{ "CplCmdOut", 48, 8 },
10887	{ "ESynOut", 47, 1 },
10888	{ "EAckOut", 46, 1 },
10889	{ "EFinOut", 45, 1 },
10890	{ "ERstOut", 44, 1 },
10891	{ "SynIn", 43, 1 },
10892	{ "AckIn", 42, 1 },
10893	{ "FinIn", 41, 1 },
10894	{ "RstIn", 40, 1 },
10895	{ "DataIn", 39, 1 },
10896	{ "DataInVld", 38, 1 },
10897	{ "PadIn", 37, 1 },
10898	{ "RxBufEmpty", 36, 1 },
10899	{ "RxDdp", 35, 1 },
10900	{ "RxFbCongestion", 34, 1 },
10901	{ "TxFbCongestion", 33, 1 },
10902	{ "TxPktSumSrdy", 32, 1 },
10903	{ "RcfUlpType", 28, 4 },
10904	{ "Eread", 27, 1 },
10905	{ "Ebypass", 26, 1 },
10906	{ "Esave", 25, 1 },
10907	{ "Static0", 24, 1 },
10908	{ "Cread", 23, 1 },
10909	{ "Cbypass", 22, 1 },
10910	{ "Csave", 21, 1 },
10911	{ "CPktOut", 20, 1 },
10912	{ "RxPagePoolFull", 18, 2 },
10913	{ "RxLpbkPkt", 17, 1 },
10914	{ "TxLpbkPkt", 16, 1 },
10915	{ "RxVfValid", 15, 1 },
10916	{ "SynLearned", 14, 1 },
10917	{ "SetDelEntry", 13, 1 },
10918	{ "SetInvEntry", 12, 1 },
10919	{ "CpcmdDvld", 11, 1 },
10920	{ "CpcmdSave", 10, 1 },
10921	{ "RxPstructsFull", 8, 2 },
10922	{ "EpcmdDvld", 7, 1 },
10923	{ "EpcmdFlush", 6, 1 },
10924	{ "EpcmdTrimPrefix", 5, 1 },
10925	{ "EpcmdTrimPostfix", 4, 1 },
10926	{ "ERssIp4Pkt", 3, 1 },
10927	{ "ERssIp6Pkt", 2, 1 },
10928	{ "ERssTcpUdpPkt", 1, 1 },
10929	{ "ERssFceFipPkt", 0, 1 },
10930	{ NULL }
10931};
10932
10933static const struct field_desc tp_la2[] = {
10934	{ "CplCmdIn", 56, 8 },
10935	{ "MpsVfVld", 55, 1 },
10936	{ "MpsPf", 52, 3 },
10937	{ "MpsVf", 44, 8 },
10938	{ "SynIn", 43, 1 },
10939	{ "AckIn", 42, 1 },
10940	{ "FinIn", 41, 1 },
10941	{ "RstIn", 40, 1 },
10942	{ "DataIn", 39, 1 },
10943	{ "DataInVld", 38, 1 },
10944	{ "PadIn", 37, 1 },
10945	{ "RxBufEmpty", 36, 1 },
10946	{ "RxDdp", 35, 1 },
10947	{ "RxFbCongestion", 34, 1 },
10948	{ "TxFbCongestion", 33, 1 },
10949	{ "TxPktSumSrdy", 32, 1 },
10950	{ "RcfUlpType", 28, 4 },
10951	{ "Eread", 27, 1 },
10952	{ "Ebypass", 26, 1 },
10953	{ "Esave", 25, 1 },
10954	{ "Static0", 24, 1 },
10955	{ "Cread", 23, 1 },
10956	{ "Cbypass", 22, 1 },
10957	{ "Csave", 21, 1 },
10958	{ "CPktOut", 20, 1 },
10959	{ "RxPagePoolFull", 18, 2 },
10960	{ "RxLpbkPkt", 17, 1 },
10961	{ "TxLpbkPkt", 16, 1 },
10962	{ "RxVfValid", 15, 1 },
10963	{ "SynLearned", 14, 1 },
10964	{ "SetDelEntry", 13, 1 },
10965	{ "SetInvEntry", 12, 1 },
10966	{ "CpcmdDvld", 11, 1 },
10967	{ "CpcmdSave", 10, 1 },
10968	{ "RxPstructsFull", 8, 2 },
10969	{ "EpcmdDvld", 7, 1 },
10970	{ "EpcmdFlush", 6, 1 },
10971	{ "EpcmdTrimPrefix", 5, 1 },
10972	{ "EpcmdTrimPostfix", 4, 1 },
10973	{ "ERssIp4Pkt", 3, 1 },
10974	{ "ERssIp6Pkt", 2, 1 },
10975	{ "ERssTcpUdpPkt", 1, 1 },
10976	{ "ERssFceFipPkt", 0, 1 },
10977	{ NULL }
10978};
10979
10980static void
10981tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10982{
10983
10984	field_desc_show(sb, *p, tp_la0);
10985}
10986
10987static void
10988tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10989{
10990
10991	if (idx)
10992		sbuf_printf(sb, "\n");
10993	field_desc_show(sb, p[0], tp_la0);
10994	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10995		field_desc_show(sb, p[1], tp_la0);
10996}
10997
10998static void
10999tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
11000{
11001
11002	if (idx)
11003		sbuf_printf(sb, "\n");
11004	field_desc_show(sb, p[0], tp_la0);
11005	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11006		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
11007}
11008
11009static int
11010sysctl_tp_la(SYSCTL_HANDLER_ARGS)
11011{
11012	struct adapter *sc = arg1;
11013	struct sbuf *sb;
11014	uint64_t *buf, *p;
11015	int rc;
11016	u_int i, inc;
11017	void (*show_func)(struct sbuf *, uint64_t *, int);
11018
11019	rc = sysctl_wire_old_buffer(req, 0);
11020	if (rc != 0)
11021		return (rc);
11022
11023	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11024	if (sb == NULL)
11025		return (ENOMEM);
11026
11027	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11028
11029	mtx_lock(&sc->reg_lock);
11030	if (hw_off_limits(sc))
11031		rc = ENXIO;
11032	else {
11033		t4_tp_read_la(sc, buf, NULL);
11034		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11035		case 2:
11036			inc = 2;
11037			show_func = tp_la_show2;
11038			break;
11039		case 3:
11040			inc = 2;
11041			show_func = tp_la_show3;
11042			break;
11043		default:
11044			inc = 1;
11045			show_func = tp_la_show;
11046		}
11047	}
11048	mtx_unlock(&sc->reg_lock);
11049	if (rc != 0)
11050		goto done;
11051
11052	p = buf;
11053	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11054		(*show_func)(sb, p, i);
11055	rc = sbuf_finish(sb);
11056done:
11057	sbuf_delete(sb);
11058	free(buf, M_CXGBE);
11059	return (rc);
11060}
11061
11062static int
11063sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11064{
11065	struct adapter *sc = arg1;
11066	struct sbuf *sb;
11067	int rc;
11068	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11069
11070	rc = sysctl_wire_old_buffer(req, 0);
11071	if (rc != 0)
11072		return (rc);
11073
11074	mtx_lock(&sc->reg_lock);
11075	if (hw_off_limits(sc))
11076		rc = ENXIO;
11077	else
11078		t4_get_chan_txrate(sc, nrate, orate);
11079	mtx_unlock(&sc->reg_lock);
11080	if (rc != 0)
11081		return (rc);
11082
11083	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11084	if (sb == NULL)
11085		return (ENOMEM);
11086
11087	if (sc->chip_params->nchan > 2) {
11088		sbuf_printf(sb, "              channel 0   channel 1"
11089		    "   channel 2   channel 3\n");
11090		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11091		    nrate[0], nrate[1], nrate[2], nrate[3]);
11092		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11093		    orate[0], orate[1], orate[2], orate[3]);
11094	} else {
11095		sbuf_printf(sb, "              channel 0   channel 1\n");
11096		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11097		    nrate[0], nrate[1]);
11098		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11099		    orate[0], orate[1]);
11100	}
11101
11102	rc = sbuf_finish(sb);
11103	sbuf_delete(sb);
11104
11105	return (rc);
11106}
11107
11108static int
11109sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11110{
11111	struct adapter *sc = arg1;
11112	struct sbuf *sb;
11113	uint32_t *buf, *p;
11114	int rc, i;
11115
11116	rc = sysctl_wire_old_buffer(req, 0);
11117	if (rc != 0)
11118		return (rc);
11119
11120	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11121	if (sb == NULL)
11122		return (ENOMEM);
11123
11124	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11125	    M_ZERO | M_WAITOK);
11126
11127	mtx_lock(&sc->reg_lock);
11128	if (hw_off_limits(sc))
11129		rc = ENXIO;
11130	else
11131		t4_ulprx_read_la(sc, buf);
11132	mtx_unlock(&sc->reg_lock);
11133	if (rc != 0)
11134		goto done;
11135
11136	p = buf;
11137	sbuf_printf(sb, "      Pcmd        Type   Message"
11138	    "                Data");
11139	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11140		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11141		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11142	}
11143	rc = sbuf_finish(sb);
11144done:
11145	sbuf_delete(sb);
11146	free(buf, M_CXGBE);
11147	return (rc);
11148}
11149
11150static int
11151sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11152{
11153	struct adapter *sc = arg1;
11154	struct sbuf *sb;
11155	int rc;
11156	uint32_t cfg, s1, s2;
11157
11158	MPASS(chip_id(sc) >= CHELSIO_T5);
11159
11160	rc = sysctl_wire_old_buffer(req, 0);
11161	if (rc != 0)
11162		return (rc);
11163
11164	mtx_lock(&sc->reg_lock);
11165	if (hw_off_limits(sc))
11166		rc = ENXIO;
11167	else {
11168		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11169		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11170		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11171	}
11172	mtx_unlock(&sc->reg_lock);
11173	if (rc != 0)
11174		return (rc);
11175
11176	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11177	if (sb == NULL)
11178		return (ENOMEM);
11179
11180	if (G_STATSOURCE_T5(cfg) == 7) {
11181		int mode;
11182
11183		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11184		if (mode == 0)
11185			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11186		else if (mode == 1)
11187			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11188		else
11189			sbuf_printf(sb, "unknown mode %d", mode);
11190	}
11191	rc = sbuf_finish(sb);
11192	sbuf_delete(sb);
11193
11194	return (rc);
11195}
11196
11197static int
11198sysctl_cpus(SYSCTL_HANDLER_ARGS)
11199{
11200	struct adapter *sc = arg1;
11201	enum cpu_sets op = arg2;
11202	cpuset_t cpuset;
11203	struct sbuf *sb;
11204	int i, rc;
11205
11206	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11207
11208	CPU_ZERO(&cpuset);
11209	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11210	if (rc != 0)
11211		return (rc);
11212
11213	rc = sysctl_wire_old_buffer(req, 0);
11214	if (rc != 0)
11215		return (rc);
11216
11217	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11218	if (sb == NULL)
11219		return (ENOMEM);
11220
11221	CPU_FOREACH(i)
11222		sbuf_printf(sb, "%d ", i);
11223	rc = sbuf_finish(sb);
11224	sbuf_delete(sb);
11225
11226	return (rc);
11227}
11228
11229static int
11230sysctl_reset(SYSCTL_HANDLER_ARGS)
11231{
11232	struct adapter *sc = arg1;
11233	u_int val;
11234	int rc;
11235
11236	val = atomic_load_int(&sc->num_resets);
11237	rc = sysctl_handle_int(oidp, &val, 0, req);
11238	if (rc != 0 || req->newptr == NULL)
11239		return (rc);
11240
11241	if (val == 0) {
11242		/* Zero out the counter that tracks reset. */
11243		atomic_store_int(&sc->num_resets, 0);
11244		return (0);
11245	}
11246
11247	if (val != 1)
11248		return (EINVAL);	/* 0 or 1 are the only legal values */
11249
11250	if (hw_off_limits(sc))		/* harmless race */
11251		return (EALREADY);
11252
11253	taskqueue_enqueue(reset_tq, &sc->reset_task);
11254	return (0);
11255}
11256
11257#ifdef TCP_OFFLOAD
11258static int
11259sysctl_tls(SYSCTL_HANDLER_ARGS)
11260{
11261	struct adapter *sc = arg1;
11262	int i, j, v, rc;
11263	struct vi_info *vi;
11264
11265	v = sc->tt.tls;
11266	rc = sysctl_handle_int(oidp, &v, 0, req);
11267	if (rc != 0 || req->newptr == NULL)
11268		return (rc);
11269
11270	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11271		return (ENOTSUP);
11272
11273	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11274	if (rc)
11275		return (rc);
11276	if (hw_off_limits(sc))
11277		rc = ENXIO;
11278	else {
11279		sc->tt.tls = !!v;
11280		for_each_port(sc, i) {
11281			for_each_vi(sc->port[i], j, vi) {
11282				if (vi->flags & VI_INIT_DONE)
11283					t4_update_fl_bufsize(vi->ifp);
11284			}
11285		}
11286	}
11287	end_synchronized_op(sc, 0);
11288
11289	return (rc);
11290
11291}
11292
11293static void
11294unit_conv(char *buf, size_t len, u_int val, u_int factor)
11295{
11296	u_int rem = val % factor;
11297
11298	if (rem == 0)
11299		snprintf(buf, len, "%u", val / factor);
11300	else {
11301		while (rem % 10 == 0)
11302			rem /= 10;
11303		snprintf(buf, len, "%u.%u", val / factor, rem);
11304	}
11305}
11306
11307static int
11308sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11309{
11310	struct adapter *sc = arg1;
11311	char buf[16];
11312	u_int res, re;
11313	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11314
11315	mtx_lock(&sc->reg_lock);
11316	if (hw_off_limits(sc))
11317		res = (u_int)-1;
11318	else
11319		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11320	mtx_unlock(&sc->reg_lock);
11321	if (res == (u_int)-1)
11322		return (ENXIO);
11323
11324	switch (arg2) {
11325	case 0:
11326		/* timer_tick */
11327		re = G_TIMERRESOLUTION(res);
11328		break;
11329	case 1:
11330		/* TCP timestamp tick */
11331		re = G_TIMESTAMPRESOLUTION(res);
11332		break;
11333	case 2:
11334		/* DACK tick */
11335		re = G_DELAYEDACKRESOLUTION(res);
11336		break;
11337	default:
11338		return (EDOOFUS);
11339	}
11340
11341	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11342
11343	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11344}
11345
11346static int
11347sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11348{
11349	struct adapter *sc = arg1;
11350	int rc;
11351	u_int dack_tmr, dack_re, v;
11352	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11353
11354	mtx_lock(&sc->reg_lock);
11355	if (hw_off_limits(sc))
11356		rc = ENXIO;
11357	else {
11358		rc = 0;
11359		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11360		    A_TP_TIMER_RESOLUTION));
11361		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11362	}
11363	mtx_unlock(&sc->reg_lock);
11364	if (rc != 0)
11365		return (rc);
11366
11367	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11368
11369	return (sysctl_handle_int(oidp, &v, 0, req));
11370}
11371
11372static int
11373sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11374{
11375	struct adapter *sc = arg1;
11376	int rc, reg = arg2;
11377	u_int tre;
11378	u_long tp_tick_us, v;
11379	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11380
11381	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11382	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11383	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11384	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11385
11386	mtx_lock(&sc->reg_lock);
11387	if (hw_off_limits(sc))
11388		rc = ENXIO;
11389	else {
11390		rc = 0;
11391		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11392		tp_tick_us = (cclk_ps << tre) / 1000000;
11393		if (reg == A_TP_INIT_SRTT)
11394			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11395		else
11396			v = tp_tick_us * t4_read_reg(sc, reg);
11397	}
11398	mtx_unlock(&sc->reg_lock);
11399	if (rc != 0)
11400		return (rc);
11401	else
11402		return (sysctl_handle_long(oidp, &v, 0, req));
11403}
11404
11405/*
11406 * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11407 * passed to this function.
11408 */
11409static int
11410sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11411{
11412	struct adapter *sc = arg1;
11413	int rc, idx = arg2;
11414	u_int v;
11415
11416	MPASS(idx >= 0 && idx <= 24);
11417
11418	mtx_lock(&sc->reg_lock);
11419	if (hw_off_limits(sc))
11420		rc = ENXIO;
11421	else {
11422		rc = 0;
11423		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11424	}
11425	mtx_unlock(&sc->reg_lock);
11426	if (rc != 0)
11427		return (rc);
11428	else
11429		return (sysctl_handle_int(oidp, &v, 0, req));
11430}
11431
11432static int
11433sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11434{
11435	struct adapter *sc = arg1;
11436	int rc, idx = arg2;
11437	u_int shift, v, r;
11438
11439	MPASS(idx >= 0 && idx < 16);
11440
11441	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11442	shift = (idx & 3) << 3;
11443	mtx_lock(&sc->reg_lock);
11444	if (hw_off_limits(sc))
11445		rc = ENXIO;
11446	else {
11447		rc = 0;
11448		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11449	}
11450	mtx_unlock(&sc->reg_lock);
11451	if (rc != 0)
11452		return (rc);
11453	else
11454		return (sysctl_handle_int(oidp, &v, 0, req));
11455}
11456
11457static int
11458sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11459{
11460	struct vi_info *vi = arg1;
11461	struct adapter *sc = vi->adapter;
11462	int idx, rc, i;
11463	struct sge_ofld_rxq *ofld_rxq;
11464	uint8_t v;
11465
11466	idx = vi->ofld_tmr_idx;
11467
11468	rc = sysctl_handle_int(oidp, &idx, 0, req);
11469	if (rc != 0 || req->newptr == NULL)
11470		return (rc);
11471
11472	if (idx < 0 || idx >= SGE_NTIMERS)
11473		return (EINVAL);
11474
11475	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11476	    "t4otmr");
11477	if (rc)
11478		return (rc);
11479
11480	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11481	for_each_ofld_rxq(vi, i, ofld_rxq) {
11482#ifdef atomic_store_rel_8
11483		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11484#else
11485		ofld_rxq->iq.intr_params = v;
11486#endif
11487	}
11488	vi->ofld_tmr_idx = idx;
11489
11490	end_synchronized_op(sc, LOCK_HELD);
11491	return (0);
11492}
11493
11494static int
11495sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11496{
11497	struct vi_info *vi = arg1;
11498	struct adapter *sc = vi->adapter;
11499	int idx, rc;
11500
11501	idx = vi->ofld_pktc_idx;
11502
11503	rc = sysctl_handle_int(oidp, &idx, 0, req);
11504	if (rc != 0 || req->newptr == NULL)
11505		return (rc);
11506
11507	if (idx < -1 || idx >= SGE_NCOUNTERS)
11508		return (EINVAL);
11509
11510	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11511	    "t4opktc");
11512	if (rc)
11513		return (rc);
11514
11515	if (vi->flags & VI_INIT_DONE)
11516		rc = EBUSY; /* cannot be changed once the queues are created */
11517	else
11518		vi->ofld_pktc_idx = idx;
11519
11520	end_synchronized_op(sc, LOCK_HELD);
11521	return (rc);
11522}
11523#endif
11524
11525static int
11526get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11527{
11528	int rc;
11529
11530	if (cntxt->cid > M_CTXTQID)
11531		return (EINVAL);
11532
11533	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11534	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11535		return (EINVAL);
11536
11537	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11538	if (rc)
11539		return (rc);
11540
11541	if (hw_off_limits(sc)) {
11542		rc = ENXIO;
11543		goto done;
11544	}
11545
11546	if (sc->flags & FW_OK) {
11547		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11548		    &cntxt->data[0]);
11549		if (rc == 0)
11550			goto done;
11551	}
11552
11553	/*
11554	 * Read via firmware failed or wasn't even attempted.  Read directly via
11555	 * the backdoor.
11556	 */
11557	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11558done:
11559	end_synchronized_op(sc, 0);
11560	return (rc);
11561}
11562
11563static int
11564load_fw(struct adapter *sc, struct t4_data *fw)
11565{
11566	int rc;
11567	uint8_t *fw_data;
11568
11569	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11570	if (rc)
11571		return (rc);
11572
11573	if (hw_off_limits(sc)) {
11574		rc = ENXIO;
11575		goto done;
11576	}
11577
11578	/*
11579	 * The firmware, with the sole exception of the memory parity error
11580	 * handler, runs from memory and not flash.  It is almost always safe to
11581	 * install a new firmware on a running system.  Just set bit 1 in
11582	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11583	 */
11584	if (sc->flags & FULL_INIT_DONE &&
11585	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11586		rc = EBUSY;
11587		goto done;
11588	}
11589
11590	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11591
11592	rc = copyin(fw->data, fw_data, fw->len);
11593	if (rc == 0)
11594		rc = -t4_load_fw(sc, fw_data, fw->len);
11595
11596	free(fw_data, M_CXGBE);
11597done:
11598	end_synchronized_op(sc, 0);
11599	return (rc);
11600}
11601
11602static int
11603load_cfg(struct adapter *sc, struct t4_data *cfg)
11604{
11605	int rc;
11606	uint8_t *cfg_data = NULL;
11607
11608	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11609	if (rc)
11610		return (rc);
11611
11612	if (hw_off_limits(sc)) {
11613		rc = ENXIO;
11614		goto done;
11615	}
11616
11617	if (cfg->len == 0) {
11618		/* clear */
11619		rc = -t4_load_cfg(sc, NULL, 0);
11620		goto done;
11621	}
11622
11623	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11624
11625	rc = copyin(cfg->data, cfg_data, cfg->len);
11626	if (rc == 0)
11627		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11628
11629	free(cfg_data, M_CXGBE);
11630done:
11631	end_synchronized_op(sc, 0);
11632	return (rc);
11633}
11634
11635static int
11636load_boot(struct adapter *sc, struct t4_bootrom *br)
11637{
11638	int rc;
11639	uint8_t *br_data = NULL;
11640	u_int offset;
11641
11642	if (br->len > 1024 * 1024)
11643		return (EFBIG);
11644
11645	if (br->pf_offset == 0) {
11646		/* pfidx */
11647		if (br->pfidx_addr > 7)
11648			return (EINVAL);
11649		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11650		    A_PCIE_PF_EXPROM_OFST)));
11651	} else if (br->pf_offset == 1) {
11652		/* offset */
11653		offset = G_OFFSET(br->pfidx_addr);
11654	} else {
11655		return (EINVAL);
11656	}
11657
11658	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11659	if (rc)
11660		return (rc);
11661
11662	if (hw_off_limits(sc)) {
11663		rc = ENXIO;
11664		goto done;
11665	}
11666
11667	if (br->len == 0) {
11668		/* clear */
11669		rc = -t4_load_boot(sc, NULL, offset, 0);
11670		goto done;
11671	}
11672
11673	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11674
11675	rc = copyin(br->data, br_data, br->len);
11676	if (rc == 0)
11677		rc = -t4_load_boot(sc, br_data, offset, br->len);
11678
11679	free(br_data, M_CXGBE);
11680done:
11681	end_synchronized_op(sc, 0);
11682	return (rc);
11683}
11684
11685static int
11686load_bootcfg(struct adapter *sc, struct t4_data *bc)
11687{
11688	int rc;
11689	uint8_t *bc_data = NULL;
11690
11691	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11692	if (rc)
11693		return (rc);
11694
11695	if (hw_off_limits(sc)) {
11696		rc = ENXIO;
11697		goto done;
11698	}
11699
11700	if (bc->len == 0) {
11701		/* clear */
11702		rc = -t4_load_bootcfg(sc, NULL, 0);
11703		goto done;
11704	}
11705
11706	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11707
11708	rc = copyin(bc->data, bc_data, bc->len);
11709	if (rc == 0)
11710		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11711
11712	free(bc_data, M_CXGBE);
11713done:
11714	end_synchronized_op(sc, 0);
11715	return (rc);
11716}
11717
11718static int
11719cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11720{
11721	int rc;
11722	struct cudbg_init *cudbg;
11723	void *handle, *buf;
11724
11725	/* buf is large, don't block if no memory is available */
11726	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11727	if (buf == NULL)
11728		return (ENOMEM);
11729
11730	handle = cudbg_alloc_handle();
11731	if (handle == NULL) {
11732		rc = ENOMEM;
11733		goto done;
11734	}
11735
11736	cudbg = cudbg_get_init(handle);
11737	cudbg->adap = sc;
11738	cudbg->print = (cudbg_print_cb)printf;
11739
11740#ifndef notyet
11741	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11742	    __func__, dump->wr_flash, dump->len, dump->data);
11743#endif
11744
11745	if (dump->wr_flash)
11746		cudbg->use_flash = 1;
11747	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11748	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11749
11750	rc = cudbg_collect(handle, buf, &dump->len);
11751	if (rc != 0)
11752		goto done;
11753
11754	rc = copyout(buf, dump->data, dump->len);
11755done:
11756	cudbg_free_handle(handle);
11757	free(buf, M_CXGBE);
11758	return (rc);
11759}
11760
11761static void
11762free_offload_policy(struct t4_offload_policy *op)
11763{
11764	struct offload_rule *r;
11765	int i;
11766
11767	if (op == NULL)
11768		return;
11769
11770	r = &op->rule[0];
11771	for (i = 0; i < op->nrules; i++, r++) {
11772		free(r->bpf_prog.bf_insns, M_CXGBE);
11773	}
11774	free(op->rule, M_CXGBE);
11775	free(op, M_CXGBE);
11776}
11777
11778static int
11779set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11780{
11781	int i, rc, len;
11782	struct t4_offload_policy *op, *old;
11783	struct bpf_program *bf;
11784	const struct offload_settings *s;
11785	struct offload_rule *r;
11786	void *u;
11787
11788	if (!is_offload(sc))
11789		return (ENODEV);
11790
11791	if (uop->nrules == 0) {
11792		/* Delete installed policies. */
11793		op = NULL;
11794		goto set_policy;
11795	} else if (uop->nrules > 256) { /* arbitrary */
11796		return (E2BIG);
11797	}
11798
11799	/* Copy userspace offload policy to kernel */
11800	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11801	op->nrules = uop->nrules;
11802	len = op->nrules * sizeof(struct offload_rule);
11803	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11804	rc = copyin(uop->rule, op->rule, len);
11805	if (rc) {
11806		free(op->rule, M_CXGBE);
11807		free(op, M_CXGBE);
11808		return (rc);
11809	}
11810
11811	r = &op->rule[0];
11812	for (i = 0; i < op->nrules; i++, r++) {
11813
11814		/* Validate open_type */
11815		if (r->open_type != OPEN_TYPE_LISTEN &&
11816		    r->open_type != OPEN_TYPE_ACTIVE &&
11817		    r->open_type != OPEN_TYPE_PASSIVE &&
11818		    r->open_type != OPEN_TYPE_DONTCARE) {
11819error:
11820			/*
11821			 * Rules 0 to i have malloc'd filters that need to be
11822			 * freed.  Rules i+1 to nrules have userspace pointers
11823			 * and should be left alone.
11824			 */
11825			op->nrules = i;
11826			free_offload_policy(op);
11827			return (rc);
11828		}
11829
11830		/* Validate settings */
11831		s = &r->settings;
11832		if ((s->offload != 0 && s->offload != 1) ||
11833		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11834		    s->sched_class < -1 ||
11835		    s->sched_class >= sc->params.nsched_cls) {
11836			rc = EINVAL;
11837			goto error;
11838		}
11839
11840		bf = &r->bpf_prog;
11841		u = bf->bf_insns;	/* userspace ptr */
11842		bf->bf_insns = NULL;
11843		if (bf->bf_len == 0) {
11844			/* legal, matches everything */
11845			continue;
11846		}
11847		len = bf->bf_len * sizeof(*bf->bf_insns);
11848		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11849		rc = copyin(u, bf->bf_insns, len);
11850		if (rc != 0)
11851			goto error;
11852
11853		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11854			rc = EINVAL;
11855			goto error;
11856		}
11857	}
11858set_policy:
11859	rw_wlock(&sc->policy_lock);
11860	old = sc->policy;
11861	sc->policy = op;
11862	rw_wunlock(&sc->policy_lock);
11863	free_offload_policy(old);
11864
11865	return (0);
11866}
11867
11868#define MAX_READ_BUF_SIZE (128 * 1024)
11869static int
11870read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11871{
11872	uint32_t addr, remaining, n;
11873	uint32_t *buf;
11874	int rc;
11875	uint8_t *dst;
11876
11877	mtx_lock(&sc->reg_lock);
11878	if (hw_off_limits(sc))
11879		rc = ENXIO;
11880	else
11881		rc = validate_mem_range(sc, mr->addr, mr->len);
11882	mtx_unlock(&sc->reg_lock);
11883	if (rc != 0)
11884		return (rc);
11885
11886	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11887	addr = mr->addr;
11888	remaining = mr->len;
11889	dst = (void *)mr->data;
11890
11891	while (remaining) {
11892		n = min(remaining, MAX_READ_BUF_SIZE);
11893		mtx_lock(&sc->reg_lock);
11894		if (hw_off_limits(sc))
11895			rc = ENXIO;
11896		else
11897			read_via_memwin(sc, 2, addr, buf, n);
11898		mtx_unlock(&sc->reg_lock);
11899		if (rc != 0)
11900			break;
11901
11902		rc = copyout(buf, dst, n);
11903		if (rc != 0)
11904			break;
11905
11906		dst += n;
11907		remaining -= n;
11908		addr += n;
11909	}
11910
11911	free(buf, M_CXGBE);
11912	return (rc);
11913}
11914#undef MAX_READ_BUF_SIZE
11915
11916static int
11917read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11918{
11919	int rc;
11920
11921	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11922		return (EINVAL);
11923
11924	if (i2cd->len > sizeof(i2cd->data))
11925		return (EFBIG);
11926
11927	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11928	if (rc)
11929		return (rc);
11930	if (hw_off_limits(sc))
11931		rc = ENXIO;
11932	else
11933		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11934		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11935	end_synchronized_op(sc, 0);
11936
11937	return (rc);
11938}
11939
11940static int
11941clear_stats(struct adapter *sc, u_int port_id)
11942{
11943	int i, v, chan_map;
11944	struct port_info *pi;
11945	struct vi_info *vi;
11946	struct sge_rxq *rxq;
11947	struct sge_txq *txq;
11948	struct sge_wrq *wrq;
11949#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11950	struct sge_ofld_txq *ofld_txq;
11951#endif
11952#ifdef TCP_OFFLOAD
11953	struct sge_ofld_rxq *ofld_rxq;
11954#endif
11955
11956	if (port_id >= sc->params.nports)
11957		return (EINVAL);
11958	pi = sc->port[port_id];
11959	if (pi == NULL)
11960		return (EIO);
11961
11962	mtx_lock(&sc->reg_lock);
11963	if (!hw_off_limits(sc)) {
11964		/* MAC stats */
11965		t4_clr_port_stats(sc, pi->tx_chan);
11966		if (is_t6(sc)) {
11967			if (pi->fcs_reg != -1)
11968				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11969			else
11970				pi->stats.rx_fcs_err = 0;
11971		}
11972		for_each_vi(pi, v, vi) {
11973			if (vi->flags & VI_INIT_DONE)
11974				t4_clr_vi_stats(sc, vi->vin);
11975		}
11976		chan_map = pi->rx_e_chan_map;
11977		v = 0;	/* reuse */
11978		while (chan_map) {
11979			i = ffs(chan_map) - 1;
11980			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11981			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11982			chan_map &= ~(1 << i);
11983		}
11984	}
11985	mtx_unlock(&sc->reg_lock);
11986	pi->tx_parse_error = 0;
11987	pi->tnl_cong_drops = 0;
11988
11989	/*
11990	 * Since this command accepts a port, clear stats for
11991	 * all VIs on this port.
11992	 */
11993	for_each_vi(pi, v, vi) {
11994		if (vi->flags & VI_INIT_DONE) {
11995
11996			for_each_rxq(vi, i, rxq) {
11997#if defined(INET) || defined(INET6)
11998				rxq->lro.lro_queued = 0;
11999				rxq->lro.lro_flushed = 0;
12000#endif
12001				rxq->rxcsum = 0;
12002				rxq->vlan_extraction = 0;
12003				rxq->vxlan_rxcsum = 0;
12004
12005				rxq->fl.cl_allocated = 0;
12006				rxq->fl.cl_recycled = 0;
12007				rxq->fl.cl_fast_recycled = 0;
12008			}
12009
12010			for_each_txq(vi, i, txq) {
12011				txq->txcsum = 0;
12012				txq->tso_wrs = 0;
12013				txq->vlan_insertion = 0;
12014				txq->imm_wrs = 0;
12015				txq->sgl_wrs = 0;
12016				txq->txpkt_wrs = 0;
12017				txq->txpkts0_wrs = 0;
12018				txq->txpkts1_wrs = 0;
12019				txq->txpkts0_pkts = 0;
12020				txq->txpkts1_pkts = 0;
12021				txq->txpkts_flush = 0;
12022				txq->raw_wrs = 0;
12023				txq->vxlan_tso_wrs = 0;
12024				txq->vxlan_txcsum = 0;
12025				txq->kern_tls_records = 0;
12026				txq->kern_tls_short = 0;
12027				txq->kern_tls_partial = 0;
12028				txq->kern_tls_full = 0;
12029				txq->kern_tls_octets = 0;
12030				txq->kern_tls_waste = 0;
12031				txq->kern_tls_options = 0;
12032				txq->kern_tls_header = 0;
12033				txq->kern_tls_fin = 0;
12034				txq->kern_tls_fin_short = 0;
12035				txq->kern_tls_cbc = 0;
12036				txq->kern_tls_gcm = 0;
12037				mp_ring_reset_stats(txq->r);
12038			}
12039
12040#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12041			for_each_ofld_txq(vi, i, ofld_txq) {
12042				ofld_txq->wrq.tx_wrs_direct = 0;
12043				ofld_txq->wrq.tx_wrs_copied = 0;
12044				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12045				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12046				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12047				counter_u64_zero(ofld_txq->tx_aio_jobs);
12048				counter_u64_zero(ofld_txq->tx_aio_octets);
12049				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12050				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12051			}
12052#endif
12053#ifdef TCP_OFFLOAD
12054			for_each_ofld_rxq(vi, i, ofld_rxq) {
12055				ofld_rxq->fl.cl_allocated = 0;
12056				ofld_rxq->fl.cl_recycled = 0;
12057				ofld_rxq->fl.cl_fast_recycled = 0;
12058				counter_u64_zero(
12059				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12060				counter_u64_zero(
12061				    ofld_rxq->rx_iscsi_ddp_setup_error);
12062				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12063				ofld_rxq->rx_iscsi_ddp_octets = 0;
12064				ofld_rxq->rx_iscsi_fl_pdus = 0;
12065				ofld_rxq->rx_iscsi_fl_octets = 0;
12066				ofld_rxq->rx_aio_ddp_jobs = 0;
12067				ofld_rxq->rx_aio_ddp_octets = 0;
12068				ofld_rxq->rx_toe_tls_records = 0;
12069				ofld_rxq->rx_toe_tls_octets = 0;
12070				ofld_rxq->rx_toe_ddp_octets = 0;
12071				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12072				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12073				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12074			}
12075#endif
12076
12077			if (IS_MAIN_VI(vi)) {
12078				wrq = &sc->sge.ctrlq[pi->port_id];
12079				wrq->tx_wrs_direct = 0;
12080				wrq->tx_wrs_copied = 0;
12081			}
12082		}
12083	}
12084
12085	return (0);
12086}
12087
12088static int
12089hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12090{
12091#ifdef INET6
12092	struct in6_addr in6;
12093
12094	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12095	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12096		return (0);
12097	else
12098		return (EIO);
12099#else
12100	return (ENOTSUP);
12101#endif
12102}
12103
12104static int
12105release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12106{
12107#ifdef INET6
12108	struct in6_addr in6;
12109
12110	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12111	return (t4_release_clip_addr(sc, &in6));
12112#else
12113	return (ENOTSUP);
12114#endif
12115}
12116
12117int
12118t4_os_find_pci_capability(struct adapter *sc, int cap)
12119{
12120	int i;
12121
12122	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12123}
12124
12125int
12126t4_os_pci_save_state(struct adapter *sc)
12127{
12128	device_t dev;
12129	struct pci_devinfo *dinfo;
12130
12131	dev = sc->dev;
12132	dinfo = device_get_ivars(dev);
12133
12134	pci_cfg_save(dev, dinfo, 0);
12135	return (0);
12136}
12137
12138int
12139t4_os_pci_restore_state(struct adapter *sc)
12140{
12141	device_t dev;
12142	struct pci_devinfo *dinfo;
12143
12144	dev = sc->dev;
12145	dinfo = device_get_ivars(dev);
12146
12147	pci_cfg_restore(dev, dinfo);
12148	return (0);
12149}
12150
12151void
12152t4_os_portmod_changed(struct port_info *pi)
12153{
12154	struct adapter *sc = pi->adapter;
12155	struct vi_info *vi;
12156	if_t ifp;
12157	static const char *mod_str[] = {
12158		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12159	};
12160
12161	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12162	    ("%s: port_type %u", __func__, pi->port_type));
12163
12164	vi = &pi->vi[0];
12165	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12166		PORT_LOCK(pi);
12167		build_medialist(pi);
12168		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12169			fixup_link_config(pi);
12170			apply_link_config(pi);
12171		}
12172		PORT_UNLOCK(pi);
12173		end_synchronized_op(sc, LOCK_HELD);
12174	}
12175
12176	ifp = vi->ifp;
12177	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12178		if_printf(ifp, "transceiver unplugged.\n");
12179	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12180		if_printf(ifp, "unknown transceiver inserted.\n");
12181	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12182		if_printf(ifp, "unsupported transceiver inserted.\n");
12183	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12184		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12185		    port_top_speed(pi), mod_str[pi->mod_type]);
12186	} else {
12187		if_printf(ifp, "transceiver (type %d) inserted.\n",
12188		    pi->mod_type);
12189	}
12190}
12191
12192void
12193t4_os_link_changed(struct port_info *pi)
12194{
12195	struct vi_info *vi;
12196	if_t ifp;
12197	struct link_config *lc = &pi->link_cfg;
12198	struct adapter *sc = pi->adapter;
12199	int v;
12200
12201	PORT_LOCK_ASSERT_OWNED(pi);
12202
12203	if (is_t6(sc)) {
12204		if (lc->link_ok) {
12205			if (lc->speed > 25000 ||
12206			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12207				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12208				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12209			} else {
12210				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12211				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12212			}
12213			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12214			pi->stats.rx_fcs_err = 0;
12215		} else {
12216			pi->fcs_reg = -1;
12217		}
12218	} else {
12219		MPASS(pi->fcs_reg != -1);
12220		MPASS(pi->fcs_base == 0);
12221	}
12222
12223	for_each_vi(pi, v, vi) {
12224		ifp = vi->ifp;
12225		if (ifp == NULL)
12226			continue;
12227
12228		if (lc->link_ok) {
12229			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12230			if_link_state_change(ifp, LINK_STATE_UP);
12231		} else {
12232			if_link_state_change(ifp, LINK_STATE_DOWN);
12233		}
12234	}
12235}
12236
12237void
12238t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12239{
12240	struct adapter *sc;
12241
12242	sx_slock(&t4_list_lock);
12243	SLIST_FOREACH(sc, &t4_list, link) {
12244		/*
12245		 * func should not make any assumptions about what state sc is
12246		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12247		 */
12248		func(sc, arg);
12249	}
12250	sx_sunlock(&t4_list_lock);
12251}
12252
12253static int
12254t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12255    struct thread *td)
12256{
12257	int rc;
12258	struct adapter *sc = dev->si_drv1;
12259
12260	rc = priv_check(td, PRIV_DRIVER);
12261	if (rc != 0)
12262		return (rc);
12263
12264	switch (cmd) {
12265	case CHELSIO_T4_GETREG: {
12266		struct t4_reg *edata = (struct t4_reg *)data;
12267
12268		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12269			return (EFAULT);
12270
12271		mtx_lock(&sc->reg_lock);
12272		if (hw_off_limits(sc))
12273			rc = ENXIO;
12274		else if (edata->size == 4)
12275			edata->val = t4_read_reg(sc, edata->addr);
12276		else if (edata->size == 8)
12277			edata->val = t4_read_reg64(sc, edata->addr);
12278		else
12279			rc = EINVAL;
12280		mtx_unlock(&sc->reg_lock);
12281
12282		break;
12283	}
12284	case CHELSIO_T4_SETREG: {
12285		struct t4_reg *edata = (struct t4_reg *)data;
12286
12287		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12288			return (EFAULT);
12289
12290		mtx_lock(&sc->reg_lock);
12291		if (hw_off_limits(sc))
12292			rc = ENXIO;
12293		else if (edata->size == 4) {
12294			if (edata->val & 0xffffffff00000000)
12295				rc = EINVAL;
12296			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12297		} else if (edata->size == 8)
12298			t4_write_reg64(sc, edata->addr, edata->val);
12299		else
12300			rc = EINVAL;
12301		mtx_unlock(&sc->reg_lock);
12302
12303		break;
12304	}
12305	case CHELSIO_T4_REGDUMP: {
12306		struct t4_regdump *regs = (struct t4_regdump *)data;
12307		int reglen = t4_get_regs_len(sc);
12308		uint8_t *buf;
12309
12310		if (regs->len < reglen) {
12311			regs->len = reglen; /* hint to the caller */
12312			return (ENOBUFS);
12313		}
12314
12315		regs->len = reglen;
12316		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12317		mtx_lock(&sc->reg_lock);
12318		if (hw_off_limits(sc))
12319			rc = ENXIO;
12320		else
12321			get_regs(sc, regs, buf);
12322		mtx_unlock(&sc->reg_lock);
12323		if (rc == 0)
12324			rc = copyout(buf, regs->data, reglen);
12325		free(buf, M_CXGBE);
12326		break;
12327	}
12328	case CHELSIO_T4_GET_FILTER_MODE:
12329		rc = get_filter_mode(sc, (uint32_t *)data);
12330		break;
12331	case CHELSIO_T4_SET_FILTER_MODE:
12332		rc = set_filter_mode(sc, *(uint32_t *)data);
12333		break;
12334	case CHELSIO_T4_SET_FILTER_MASK:
12335		rc = set_filter_mask(sc, *(uint32_t *)data);
12336		break;
12337	case CHELSIO_T4_GET_FILTER:
12338		rc = get_filter(sc, (struct t4_filter *)data);
12339		break;
12340	case CHELSIO_T4_SET_FILTER:
12341		rc = set_filter(sc, (struct t4_filter *)data);
12342		break;
12343	case CHELSIO_T4_DEL_FILTER:
12344		rc = del_filter(sc, (struct t4_filter *)data);
12345		break;
12346	case CHELSIO_T4_GET_SGE_CONTEXT:
12347		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12348		break;
12349	case CHELSIO_T4_LOAD_FW:
12350		rc = load_fw(sc, (struct t4_data *)data);
12351		break;
12352	case CHELSIO_T4_GET_MEM:
12353		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12354		break;
12355	case CHELSIO_T4_GET_I2C:
12356		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12357		break;
12358	case CHELSIO_T4_CLEAR_STATS:
12359		rc = clear_stats(sc, *(uint32_t *)data);
12360		break;
12361	case CHELSIO_T4_SCHED_CLASS:
12362		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12363		break;
12364	case CHELSIO_T4_SCHED_QUEUE:
12365		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12366		break;
12367	case CHELSIO_T4_GET_TRACER:
12368		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12369		break;
12370	case CHELSIO_T4_SET_TRACER:
12371		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12372		break;
12373	case CHELSIO_T4_LOAD_CFG:
12374		rc = load_cfg(sc, (struct t4_data *)data);
12375		break;
12376	case CHELSIO_T4_LOAD_BOOT:
12377		rc = load_boot(sc, (struct t4_bootrom *)data);
12378		break;
12379	case CHELSIO_T4_LOAD_BOOTCFG:
12380		rc = load_bootcfg(sc, (struct t4_data *)data);
12381		break;
12382	case CHELSIO_T4_CUDBG_DUMP:
12383		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12384		break;
12385	case CHELSIO_T4_SET_OFLD_POLICY:
12386		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12387		break;
12388	case CHELSIO_T4_HOLD_CLIP_ADDR:
12389		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12390		break;
12391	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12392		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12393		break;
12394	default:
12395		rc = ENOTTY;
12396	}
12397
12398	return (rc);
12399}
12400
12401#ifdef TCP_OFFLOAD
12402static int
12403toe_capability(struct vi_info *vi, bool enable)
12404{
12405	int rc;
12406	struct port_info *pi = vi->pi;
12407	struct adapter *sc = pi->adapter;
12408
12409	ASSERT_SYNCHRONIZED_OP(sc);
12410
12411	if (!is_offload(sc))
12412		return (ENODEV);
12413	if (hw_off_limits(sc))
12414		return (ENXIO);
12415
12416	if (enable) {
12417#ifdef KERN_TLS
12418		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12419			int i, j, n;
12420			struct port_info *p;
12421			struct vi_info *v;
12422
12423			/*
12424			 * Reconfigure hardware for TOE if TXTLS is not enabled
12425			 * on any ifnet.
12426			 */
12427			n = 0;
12428			for_each_port(sc, i) {
12429				p = sc->port[i];
12430				for_each_vi(p, j, v) {
12431					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12432						CH_WARN(sc,
12433						    "%s has NIC TLS enabled.\n",
12434						    device_get_nameunit(v->dev));
12435						n++;
12436					}
12437				}
12438			}
12439			if (n > 0) {
12440				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12441				    "associated with this adapter before "
12442				    "trying to enable TOE.\n");
12443				return (EAGAIN);
12444			}
12445			rc = t6_config_kern_tls(sc, false);
12446			if (rc)
12447				return (rc);
12448		}
12449#endif
12450		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12451			/* TOE is already enabled. */
12452			return (0);
12453		}
12454
12455		/*
12456		 * We need the port's queues around so that we're able to send
12457		 * and receive CPLs to/from the TOE even if the ifnet for this
12458		 * port has never been UP'd administratively.
12459		 */
12460		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12461			return (rc);
12462		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12463		    ((rc = vi_init(&pi->vi[0])) != 0))
12464			return (rc);
12465
12466		if (isset(&sc->offload_map, pi->port_id)) {
12467			/* TOE is enabled on another VI of this port. */
12468			pi->uld_vis++;
12469			return (0);
12470		}
12471
12472		if (!uld_active(sc, ULD_TOM)) {
12473			rc = t4_activate_uld(sc, ULD_TOM);
12474			if (rc == EAGAIN) {
12475				log(LOG_WARNING,
12476				    "You must kldload t4_tom.ko before trying "
12477				    "to enable TOE on a cxgbe interface.\n");
12478			}
12479			if (rc != 0)
12480				return (rc);
12481			KASSERT(sc->tom_softc != NULL,
12482			    ("%s: TOM activated but softc NULL", __func__));
12483			KASSERT(uld_active(sc, ULD_TOM),
12484			    ("%s: TOM activated but flag not set", __func__));
12485		}
12486
12487		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12488		if (!uld_active(sc, ULD_IWARP))
12489			(void) t4_activate_uld(sc, ULD_IWARP);
12490		if (!uld_active(sc, ULD_ISCSI))
12491			(void) t4_activate_uld(sc, ULD_ISCSI);
12492
12493		pi->uld_vis++;
12494		setbit(&sc->offload_map, pi->port_id);
12495	} else {
12496		pi->uld_vis--;
12497
12498		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12499			return (0);
12500
12501		KASSERT(uld_active(sc, ULD_TOM),
12502		    ("%s: TOM never initialized?", __func__));
12503		clrbit(&sc->offload_map, pi->port_id);
12504	}
12505
12506	return (0);
12507}
12508
12509/*
12510 * Add an upper layer driver to the global list.
12511 */
12512int
12513t4_register_uld(struct uld_info *ui)
12514{
12515	int rc = 0;
12516	struct uld_info *u;
12517
12518	sx_xlock(&t4_uld_list_lock);
12519	SLIST_FOREACH(u, &t4_uld_list, link) {
12520	    if (u->uld_id == ui->uld_id) {
12521		    rc = EEXIST;
12522		    goto done;
12523	    }
12524	}
12525
12526	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12527	ui->refcount = 0;
12528done:
12529	sx_xunlock(&t4_uld_list_lock);
12530	return (rc);
12531}
12532
12533int
12534t4_unregister_uld(struct uld_info *ui)
12535{
12536	int rc = EINVAL;
12537	struct uld_info *u;
12538
12539	sx_xlock(&t4_uld_list_lock);
12540
12541	SLIST_FOREACH(u, &t4_uld_list, link) {
12542	    if (u == ui) {
12543		    if (ui->refcount > 0) {
12544			    rc = EBUSY;
12545			    goto done;
12546		    }
12547
12548		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12549		    rc = 0;
12550		    goto done;
12551	    }
12552	}
12553done:
12554	sx_xunlock(&t4_uld_list_lock);
12555	return (rc);
12556}
12557
12558int
12559t4_activate_uld(struct adapter *sc, int id)
12560{
12561	int rc;
12562	struct uld_info *ui;
12563
12564	ASSERT_SYNCHRONIZED_OP(sc);
12565
12566	if (id < 0 || id > ULD_MAX)
12567		return (EINVAL);
12568	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12569
12570	sx_slock(&t4_uld_list_lock);
12571
12572	SLIST_FOREACH(ui, &t4_uld_list, link) {
12573		if (ui->uld_id == id) {
12574			if (!(sc->flags & FULL_INIT_DONE)) {
12575				rc = adapter_init(sc);
12576				if (rc != 0)
12577					break;
12578			}
12579
12580			rc = ui->activate(sc);
12581			if (rc == 0) {
12582				setbit(&sc->active_ulds, id);
12583				ui->refcount++;
12584			}
12585			break;
12586		}
12587	}
12588
12589	sx_sunlock(&t4_uld_list_lock);
12590
12591	return (rc);
12592}
12593
12594int
12595t4_deactivate_uld(struct adapter *sc, int id)
12596{
12597	int rc;
12598	struct uld_info *ui;
12599
12600	ASSERT_SYNCHRONIZED_OP(sc);
12601
12602	if (id < 0 || id > ULD_MAX)
12603		return (EINVAL);
12604	rc = ENXIO;
12605
12606	sx_slock(&t4_uld_list_lock);
12607
12608	SLIST_FOREACH(ui, &t4_uld_list, link) {
12609		if (ui->uld_id == id) {
12610			rc = ui->deactivate(sc);
12611			if (rc == 0) {
12612				clrbit(&sc->active_ulds, id);
12613				ui->refcount--;
12614			}
12615			break;
12616		}
12617	}
12618
12619	sx_sunlock(&t4_uld_list_lock);
12620
12621	return (rc);
12622}
12623
12624static int
12625t4_deactivate_all_uld(struct adapter *sc)
12626{
12627	int rc;
12628	struct uld_info *ui;
12629
12630	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12631	if (rc != 0)
12632		return (ENXIO);
12633
12634	sx_slock(&t4_uld_list_lock);
12635
12636	SLIST_FOREACH(ui, &t4_uld_list, link) {
12637		if (isset(&sc->active_ulds, ui->uld_id)) {
12638			rc = ui->deactivate(sc);
12639			if (rc != 0)
12640				break;
12641			clrbit(&sc->active_ulds, ui->uld_id);
12642			ui->refcount--;
12643		}
12644	}
12645
12646	sx_sunlock(&t4_uld_list_lock);
12647	end_synchronized_op(sc, 0);
12648
12649	return (rc);
12650}
12651
12652static void
12653t4_async_event(struct adapter *sc)
12654{
12655	struct uld_info *ui;
12656
12657	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12658		return;
12659	sx_slock(&t4_uld_list_lock);
12660	SLIST_FOREACH(ui, &t4_uld_list, link) {
12661		if (ui->uld_id == ULD_IWARP) {
12662			ui->async_event(sc);
12663			break;
12664		}
12665	}
12666	sx_sunlock(&t4_uld_list_lock);
12667	end_synchronized_op(sc, 0);
12668}
12669
12670int
12671uld_active(struct adapter *sc, int uld_id)
12672{
12673
12674	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12675
12676	return (isset(&sc->active_ulds, uld_id));
12677}
12678#endif
12679
12680#ifdef KERN_TLS
12681static int
12682ktls_capability(struct adapter *sc, bool enable)
12683{
12684	ASSERT_SYNCHRONIZED_OP(sc);
12685
12686	if (!is_ktls(sc))
12687		return (ENODEV);
12688	if (!is_t6(sc))
12689		return (0);
12690	if (hw_off_limits(sc))
12691		return (ENXIO);
12692
12693	if (enable) {
12694		if (sc->flags & KERN_TLS_ON)
12695			return (0);	/* already on */
12696		if (sc->offload_map != 0) {
12697			CH_WARN(sc,
12698			    "Disable TOE on all interfaces associated with "
12699			    "this adapter before trying to enable NIC TLS.\n");
12700			return (EAGAIN);
12701		}
12702		return (t6_config_kern_tls(sc, true));
12703	} else {
12704		/*
12705		 * Nothing to do for disable.  If TOE is enabled sometime later
12706		 * then toe_capability will reconfigure the hardware.
12707		 */
12708		return (0);
12709	}
12710}
12711#endif
12712
12713/*
12714 * t  = ptr to tunable.
12715 * nc = number of CPUs.
12716 * c  = compiled in default for that tunable.
12717 */
12718static void
12719calculate_nqueues(int *t, int nc, const int c)
12720{
12721	int nq;
12722
12723	if (*t > 0)
12724		return;
12725	nq = *t < 0 ? -*t : c;
12726	*t = min(nc, nq);
12727}
12728
12729/*
12730 * Come up with reasonable defaults for some of the tunables, provided they're
12731 * not set by the user (in which case we'll use the values as is).
12732 */
12733static void
12734tweak_tunables(void)
12735{
12736	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12737
12738	if (t4_ntxq < 1) {
12739#ifdef RSS
12740		t4_ntxq = rss_getnumbuckets();
12741#else
12742		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12743#endif
12744	}
12745
12746	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12747
12748	if (t4_nrxq < 1) {
12749#ifdef RSS
12750		t4_nrxq = rss_getnumbuckets();
12751#else
12752		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12753#endif
12754	}
12755
12756	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12757
12758#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12759	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12760	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12761#endif
12762#ifdef TCP_OFFLOAD
12763	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12764	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12765#endif
12766
12767#if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12768	if (t4_toecaps_allowed == -1)
12769		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12770#else
12771	if (t4_toecaps_allowed == -1)
12772		t4_toecaps_allowed = 0;
12773#endif
12774
12775#ifdef TCP_OFFLOAD
12776	if (t4_rdmacaps_allowed == -1) {
12777		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12778		    FW_CAPS_CONFIG_RDMA_RDMAC;
12779	}
12780
12781	if (t4_iscsicaps_allowed == -1) {
12782		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12783		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12784		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12785	}
12786
12787	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12788		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12789
12790	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12791		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12792#else
12793	if (t4_rdmacaps_allowed == -1)
12794		t4_rdmacaps_allowed = 0;
12795
12796	if (t4_iscsicaps_allowed == -1)
12797		t4_iscsicaps_allowed = 0;
12798#endif
12799
12800#ifdef DEV_NETMAP
12801	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12802	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12803	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12804	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12805#endif
12806
12807	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12808		t4_tmr_idx = TMR_IDX;
12809
12810	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12811		t4_pktc_idx = PKTC_IDX;
12812
12813	if (t4_qsize_txq < 128)
12814		t4_qsize_txq = 128;
12815
12816	if (t4_qsize_rxq < 128)
12817		t4_qsize_rxq = 128;
12818	while (t4_qsize_rxq & 7)
12819		t4_qsize_rxq++;
12820
12821	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12822
12823	/*
12824	 * Number of VIs to create per-port.  The first VI is the "main" regular
12825	 * VI for the port.  The rest are additional virtual interfaces on the
12826	 * same physical port.  Note that the main VI does not have native
12827	 * netmap support but the extra VIs do.
12828	 *
12829	 * Limit the number of VIs per port to the number of available
12830	 * MAC addresses per port.
12831	 */
12832	if (t4_num_vis < 1)
12833		t4_num_vis = 1;
12834	if (t4_num_vis > nitems(vi_mac_funcs)) {
12835		t4_num_vis = nitems(vi_mac_funcs);
12836		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12837	}
12838
12839	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12840		pcie_relaxed_ordering = 1;
12841#if defined(__i386__) || defined(__amd64__)
12842		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12843			pcie_relaxed_ordering = 0;
12844#endif
12845	}
12846}
12847
12848#ifdef DDB
12849static void
12850t4_dump_tcb(struct adapter *sc, int tid)
12851{
12852	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12853
12854	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12855	save = t4_read_reg(sc, reg);
12856	base = sc->memwin[2].mw_base;
12857
12858	/* Dump TCB for the tid */
12859	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12860	tcb_addr += tid * TCB_SIZE;
12861
12862	if (is_t4(sc)) {
12863		pf = 0;
12864		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12865	} else {
12866		pf = V_PFNUM(sc->pf);
12867		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12868	}
12869	t4_write_reg(sc, reg, win_pos | pf);
12870	t4_read_reg(sc, reg);
12871
12872	off = tcb_addr - win_pos;
12873	for (i = 0; i < 4; i++) {
12874		uint32_t buf[8];
12875		for (j = 0; j < 8; j++, off += 4)
12876			buf[j] = htonl(t4_read_reg(sc, base + off));
12877
12878		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12879		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12880		    buf[7]);
12881	}
12882
12883	t4_write_reg(sc, reg, save);
12884	t4_read_reg(sc, reg);
12885}
12886
12887static void
12888t4_dump_devlog(struct adapter *sc)
12889{
12890	struct devlog_params *dparams = &sc->params.devlog;
12891	struct fw_devlog_e e;
12892	int i, first, j, m, nentries, rc;
12893	uint64_t ftstamp = UINT64_MAX;
12894
12895	if (dparams->start == 0) {
12896		db_printf("devlog params not valid\n");
12897		return;
12898	}
12899
12900	nentries = dparams->size / sizeof(struct fw_devlog_e);
12901	m = fwmtype_to_hwmtype(dparams->memtype);
12902
12903	/* Find the first entry. */
12904	first = -1;
12905	for (i = 0; i < nentries && !db_pager_quit; i++) {
12906		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12907		    sizeof(e), (void *)&e);
12908		if (rc != 0)
12909			break;
12910
12911		if (e.timestamp == 0)
12912			break;
12913
12914		e.timestamp = be64toh(e.timestamp);
12915		if (e.timestamp < ftstamp) {
12916			ftstamp = e.timestamp;
12917			first = i;
12918		}
12919	}
12920
12921	if (first == -1)
12922		return;
12923
12924	i = first;
12925	do {
12926		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12927		    sizeof(e), (void *)&e);
12928		if (rc != 0)
12929			return;
12930
12931		if (e.timestamp == 0)
12932			return;
12933
12934		e.timestamp = be64toh(e.timestamp);
12935		e.seqno = be32toh(e.seqno);
12936		for (j = 0; j < 8; j++)
12937			e.params[j] = be32toh(e.params[j]);
12938
12939		db_printf("%10d  %15ju  %8s  %8s  ",
12940		    e.seqno, e.timestamp,
12941		    (e.level < nitems(devlog_level_strings) ?
12942			devlog_level_strings[e.level] : "UNKNOWN"),
12943		    (e.facility < nitems(devlog_facility_strings) ?
12944			devlog_facility_strings[e.facility] : "UNKNOWN"));
12945		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12946		    e.params[3], e.params[4], e.params[5], e.params[6],
12947		    e.params[7]);
12948
12949		if (++i == nentries)
12950			i = 0;
12951	} while (i != first && !db_pager_quit);
12952}
12953
12954static DB_DEFINE_TABLE(show, t4, show_t4);
12955
12956DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12957{
12958	device_t dev;
12959	int t;
12960	bool valid;
12961
12962	valid = false;
12963	t = db_read_token();
12964	if (t == tIDENT) {
12965		dev = device_lookup_by_name(db_tok_string);
12966		valid = true;
12967	}
12968	db_skip_to_eol();
12969	if (!valid) {
12970		db_printf("usage: show t4 devlog <nexus>\n");
12971		return;
12972	}
12973
12974	if (dev == NULL) {
12975		db_printf("device not found\n");
12976		return;
12977	}
12978
12979	t4_dump_devlog(device_get_softc(dev));
12980}
12981
12982DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12983{
12984	device_t dev;
12985	int radix, tid, t;
12986	bool valid;
12987
12988	valid = false;
12989	radix = db_radix;
12990	db_radix = 10;
12991	t = db_read_token();
12992	if (t == tIDENT) {
12993		dev = device_lookup_by_name(db_tok_string);
12994		t = db_read_token();
12995		if (t == tNUMBER) {
12996			tid = db_tok_number;
12997			valid = true;
12998		}
12999	}
13000	db_radix = radix;
13001	db_skip_to_eol();
13002	if (!valid) {
13003		db_printf("usage: show t4 tcb <nexus> <tid>\n");
13004		return;
13005	}
13006
13007	if (dev == NULL) {
13008		db_printf("device not found\n");
13009		return;
13010	}
13011	if (tid < 0) {
13012		db_printf("invalid tid\n");
13013		return;
13014	}
13015
13016	t4_dump_tcb(device_get_softc(dev), tid);
13017}
13018#endif
13019
13020static eventhandler_tag vxlan_start_evtag;
13021static eventhandler_tag vxlan_stop_evtag;
13022
13023struct vxlan_evargs {
13024	if_t ifp;
13025	uint16_t port;
13026};
13027
13028static void
13029enable_vxlan_rx(struct adapter *sc)
13030{
13031	int i, rc;
13032	struct port_info *pi;
13033	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13034
13035	ASSERT_SYNCHRONIZED_OP(sc);
13036
13037	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13038	    F_VXLAN_EN);
13039	for_each_port(sc, i) {
13040		pi = sc->port[i];
13041		if (pi->vxlan_tcam_entry == true)
13042			continue;
13043		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13044		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13045		    true);
13046		if (rc < 0) {
13047			rc = -rc;
13048			CH_ERR(&pi->vi[0],
13049			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13050		} else {
13051			MPASS(rc == sc->rawf_base + pi->port_id);
13052			pi->vxlan_tcam_entry = true;
13053		}
13054	}
13055}
13056
13057static void
13058t4_vxlan_start(struct adapter *sc, void *arg)
13059{
13060	struct vxlan_evargs *v = arg;
13061
13062	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13063		return;
13064	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13065		return;
13066
13067	if (sc->vxlan_refcount == 0) {
13068		sc->vxlan_port = v->port;
13069		sc->vxlan_refcount = 1;
13070		if (!hw_off_limits(sc))
13071			enable_vxlan_rx(sc);
13072	} else if (sc->vxlan_port == v->port) {
13073		sc->vxlan_refcount++;
13074	} else {
13075		CH_ERR(sc, "VXLAN already configured on port  %d; "
13076		    "ignoring attempt to configure it on port %d\n",
13077		    sc->vxlan_port, v->port);
13078	}
13079	end_synchronized_op(sc, 0);
13080}
13081
13082static void
13083t4_vxlan_stop(struct adapter *sc, void *arg)
13084{
13085	struct vxlan_evargs *v = arg;
13086
13087	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13088		return;
13089	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13090		return;
13091
13092	/*
13093	 * VXLANs may have been configured before the driver was loaded so we
13094	 * may see more stops than starts.  This is not handled cleanly but at
13095	 * least we keep the refcount sane.
13096	 */
13097	if (sc->vxlan_port != v->port)
13098		goto done;
13099	if (sc->vxlan_refcount == 0) {
13100		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13101		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13102	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13103		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13104done:
13105	end_synchronized_op(sc, 0);
13106}
13107
13108static void
13109t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13110    sa_family_t family, u_int port)
13111{
13112	struct vxlan_evargs v;
13113
13114	MPASS(family == AF_INET || family == AF_INET6);
13115	v.ifp = ifp;
13116	v.port = port;
13117
13118	t4_iterate(t4_vxlan_start, &v);
13119}
13120
13121static void
13122t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13123    u_int port)
13124{
13125	struct vxlan_evargs v;
13126
13127	MPASS(family == AF_INET || family == AF_INET6);
13128	v.ifp = ifp;
13129	v.port = port;
13130
13131	t4_iterate(t4_vxlan_stop, &v);
13132}
13133
13134
13135static struct sx mlu;	/* mod load unload */
13136SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13137
13138static int
13139mod_event(module_t mod, int cmd, void *arg)
13140{
13141	int rc = 0;
13142	static int loaded = 0;
13143
13144	switch (cmd) {
13145	case MOD_LOAD:
13146		sx_xlock(&mlu);
13147		if (loaded++ == 0) {
13148			t4_sge_modload();
13149			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13150			    t4_filter_rpl, CPL_COOKIE_FILTER);
13151			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13152			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13153			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13154			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13155			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13156			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13157			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13158			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13159			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13160			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13161			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13162			    do_smt_write_rpl);
13163			sx_init(&t4_list_lock, "T4/T5 adapters");
13164			SLIST_INIT(&t4_list);
13165			callout_init(&fatal_callout, 1);
13166#ifdef TCP_OFFLOAD
13167			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13168			SLIST_INIT(&t4_uld_list);
13169#endif
13170#ifdef INET6
13171			t4_clip_modload();
13172#endif
13173#ifdef KERN_TLS
13174			t6_ktls_modload();
13175#endif
13176			t4_tracer_modload();
13177			tweak_tunables();
13178			vxlan_start_evtag =
13179			    EVENTHANDLER_REGISTER(vxlan_start,
13180				t4_vxlan_start_handler, NULL,
13181				EVENTHANDLER_PRI_ANY);
13182			vxlan_stop_evtag =
13183			    EVENTHANDLER_REGISTER(vxlan_stop,
13184				t4_vxlan_stop_handler, NULL,
13185				EVENTHANDLER_PRI_ANY);
13186			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13187			    taskqueue_thread_enqueue, &reset_tq);
13188			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13189			    "t4_rst_thr");
13190		}
13191		sx_xunlock(&mlu);
13192		break;
13193
13194	case MOD_UNLOAD:
13195		sx_xlock(&mlu);
13196		if (--loaded == 0) {
13197			int tries;
13198
13199			taskqueue_free(reset_tq);
13200			sx_slock(&t4_list_lock);
13201			if (!SLIST_EMPTY(&t4_list)) {
13202				rc = EBUSY;
13203				sx_sunlock(&t4_list_lock);
13204				goto done_unload;
13205			}
13206#ifdef TCP_OFFLOAD
13207			sx_slock(&t4_uld_list_lock);
13208			if (!SLIST_EMPTY(&t4_uld_list)) {
13209				rc = EBUSY;
13210				sx_sunlock(&t4_uld_list_lock);
13211				sx_sunlock(&t4_list_lock);
13212				goto done_unload;
13213			}
13214#endif
13215			tries = 0;
13216			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13217				uprintf("%ju clusters with custom free routine "
13218				    "still is use.\n", t4_sge_extfree_refs());
13219				pause("t4unload", 2 * hz);
13220			}
13221#ifdef TCP_OFFLOAD
13222			sx_sunlock(&t4_uld_list_lock);
13223#endif
13224			sx_sunlock(&t4_list_lock);
13225
13226			if (t4_sge_extfree_refs() == 0) {
13227				EVENTHANDLER_DEREGISTER(vxlan_start,
13228				    vxlan_start_evtag);
13229				EVENTHANDLER_DEREGISTER(vxlan_stop,
13230				    vxlan_stop_evtag);
13231				t4_tracer_modunload();
13232#ifdef KERN_TLS
13233				t6_ktls_modunload();
13234#endif
13235#ifdef INET6
13236				t4_clip_modunload();
13237#endif
13238#ifdef TCP_OFFLOAD
13239				sx_destroy(&t4_uld_list_lock);
13240#endif
13241				sx_destroy(&t4_list_lock);
13242				t4_sge_modunload();
13243				loaded = 0;
13244			} else {
13245				rc = EBUSY;
13246				loaded++;	/* undo earlier decrement */
13247			}
13248		}
13249done_unload:
13250		sx_xunlock(&mlu);
13251		break;
13252	}
13253
13254	return (rc);
13255}
13256
13257DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13258MODULE_VERSION(t4nex, 1);
13259MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13260#ifdef DEV_NETMAP
13261MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13262#endif /* DEV_NETMAP */
13263
13264DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13265MODULE_VERSION(t5nex, 1);
13266MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13267#ifdef DEV_NETMAP
13268MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13269#endif /* DEV_NETMAP */
13270
13271DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13272MODULE_VERSION(t6nex, 1);
13273MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13274MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13275#ifdef DEV_NETMAP
13276MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13277#endif /* DEV_NETMAP */
13278
13279DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13280MODULE_VERSION(cxgbe, 1);
13281
13282DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13283MODULE_VERSION(cxl, 1);
13284
13285DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13286MODULE_VERSION(cc, 1);
13287
13288DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13289MODULE_VERSION(vcxgbe, 1);
13290
13291DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13292MODULE_VERSION(vcxl, 1);
13293
13294DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13295MODULE_VERSION(vcc, 1);
13296