t4_main.c revision 309724
1/*-
2 * Copyright (c) 2011 Chelsio Communications, Inc.
3 * All rights reserved.
4 * Written by: Navdeep Parhar <np@FreeBSD.org>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: stable/10/sys/dev/cxgbe/t4_main.c 309724 2016-12-09 01:44:26Z jhb $");
30
31#include "opt_ddb.h"
32#include "opt_inet.h"
33#include "opt_inet6.h"
34
35#include <sys/param.h>
36#include <sys/conf.h>
37#include <sys/priv.h>
38#include <sys/kernel.h>
39#include <sys/bus.h>
40#include <sys/systm.h>
41#include <sys/counter.h>
42#include <sys/module.h>
43#include <sys/malloc.h>
44#include <sys/queue.h>
45#include <sys/taskqueue.h>
46#include <sys/pciio.h>
47#include <dev/pci/pcireg.h>
48#include <dev/pci/pcivar.h>
49#include <dev/pci/pci_private.h>
50#include <sys/firmware.h>
51#include <sys/sbuf.h>
52#include <sys/smp.h>
53#include <sys/socket.h>
54#include <sys/sockio.h>
55#include <sys/sysctl.h>
56#include <net/ethernet.h>
57#include <net/if.h>
58#include <net/if_types.h>
59#include <net/if_dl.h>
60#include <net/if_vlan_var.h>
61#ifdef RSS
62#include <net/rss_config.h>
63#endif
64#if defined(__i386__) || defined(__amd64__)
65#include <vm/vm.h>
66#include <vm/pmap.h>
67#endif
68#ifdef DDB
69#include <ddb/ddb.h>
70#include <ddb/db_lex.h>
71#endif
72
73#include "common/common.h"
74#include "common/t4_msg.h"
75#include "common/t4_regs.h"
76#include "common/t4_regs_values.h"
77#include "t4_ioctl.h"
78#include "t4_l2t.h"
79#include "t4_mp_ring.h"
80
81/* T4 bus driver interface */
82static int t4_probe(device_t);
83static int t4_attach(device_t);
84static int t4_detach(device_t);
85static device_method_t t4_methods[] = {
86	DEVMETHOD(device_probe,		t4_probe),
87	DEVMETHOD(device_attach,	t4_attach),
88	DEVMETHOD(device_detach,	t4_detach),
89
90	DEVMETHOD_END
91};
92static driver_t t4_driver = {
93	"t4nex",
94	t4_methods,
95	sizeof(struct adapter)
96};
97
98
99/* T4 port (cxgbe) interface */
100static int cxgbe_probe(device_t);
101static int cxgbe_attach(device_t);
102static int cxgbe_detach(device_t);
103device_method_t cxgbe_methods[] = {
104	DEVMETHOD(device_probe,		cxgbe_probe),
105	DEVMETHOD(device_attach,	cxgbe_attach),
106	DEVMETHOD(device_detach,	cxgbe_detach),
107	{ 0, 0 }
108};
109static driver_t cxgbe_driver = {
110	"cxgbe",
111	cxgbe_methods,
112	sizeof(struct port_info)
113};
114
115/* T4 VI (vcxgbe) interface */
116static int vcxgbe_probe(device_t);
117static int vcxgbe_attach(device_t);
118static int vcxgbe_detach(device_t);
119static device_method_t vcxgbe_methods[] = {
120	DEVMETHOD(device_probe,		vcxgbe_probe),
121	DEVMETHOD(device_attach,	vcxgbe_attach),
122	DEVMETHOD(device_detach,	vcxgbe_detach),
123	{ 0, 0 }
124};
125static driver_t vcxgbe_driver = {
126	"vcxgbe",
127	vcxgbe_methods,
128	sizeof(struct vi_info)
129};
130
131static d_ioctl_t t4_ioctl;
132
133static struct cdevsw t4_cdevsw = {
134       .d_version = D_VERSION,
135       .d_ioctl = t4_ioctl,
136       .d_name = "t4nex",
137};
138
139/* T5 bus driver interface */
140static int t5_probe(device_t);
141static device_method_t t5_methods[] = {
142	DEVMETHOD(device_probe,		t5_probe),
143	DEVMETHOD(device_attach,	t4_attach),
144	DEVMETHOD(device_detach,	t4_detach),
145
146	DEVMETHOD_END
147};
148static driver_t t5_driver = {
149	"t5nex",
150	t5_methods,
151	sizeof(struct adapter)
152};
153
154
155/* T5 port (cxl) interface */
156static driver_t cxl_driver = {
157	"cxl",
158	cxgbe_methods,
159	sizeof(struct port_info)
160};
161
162/* T5 VI (vcxl) interface */
163static driver_t vcxl_driver = {
164	"vcxl",
165	vcxgbe_methods,
166	sizeof(struct vi_info)
167};
168
169/* T6 bus driver interface */
170static int t6_probe(device_t);
171static device_method_t t6_methods[] = {
172	DEVMETHOD(device_probe,		t6_probe),
173	DEVMETHOD(device_attach,	t4_attach),
174	DEVMETHOD(device_detach,	t4_detach),
175
176	DEVMETHOD_END
177};
178static driver_t t6_driver = {
179	"t6nex",
180	t6_methods,
181	sizeof(struct adapter)
182};
183
184
185/* T6 port (cc) interface */
186static driver_t cc_driver = {
187	"cc",
188	cxgbe_methods,
189	sizeof(struct port_info)
190};
191
192/* T6 VI (vcc) interface */
193static driver_t vcc_driver = {
194	"vcc",
195	vcxgbe_methods,
196	sizeof(struct vi_info)
197};
198
199/* ifnet + media interface */
200static void cxgbe_init(void *);
201static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
202static int cxgbe_transmit(struct ifnet *, struct mbuf *);
203static void cxgbe_qflush(struct ifnet *);
204static int cxgbe_media_change(struct ifnet *);
205static void cxgbe_media_status(struct ifnet *, struct ifmediareq *);
206
207MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
208
209/*
210 * Correct lock order when you need to acquire multiple locks is t4_list_lock,
211 * then ADAPTER_LOCK, then t4_uld_list_lock.
212 */
213static struct sx t4_list_lock;
214SLIST_HEAD(, adapter) t4_list;
215#ifdef TCP_OFFLOAD
216static struct sx t4_uld_list_lock;
217SLIST_HEAD(, uld_info) t4_uld_list;
218#endif
219
220/*
221 * Tunables.  See tweak_tunables() too.
222 *
223 * Each tunable is set to a default value here if it's known at compile-time.
224 * Otherwise it is set to -1 as an indication to tweak_tunables() that it should
225 * provide a reasonable default when the driver is loaded.
226 *
227 * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
228 * T5 are under hw.cxl.
229 */
230
231/*
232 * Number of queues for tx and rx, 10G and 1G, NIC and offload.
233 */
234#define NTXQ_10G 16
235int t4_ntxq10g = -1;
236TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq10g);
237
238#define NRXQ_10G 8
239int t4_nrxq10g = -1;
240TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq10g);
241
242#define NTXQ_1G 4
243int t4_ntxq1g = -1;
244TUNABLE_INT("hw.cxgbe.ntxq1g", &t4_ntxq1g);
245
246#define NRXQ_1G 2
247int t4_nrxq1g = -1;
248TUNABLE_INT("hw.cxgbe.nrxq1g", &t4_nrxq1g);
249
250#define NTXQ_VI 1
251static int t4_ntxq_vi = -1;
252TUNABLE_INT("hw.cxgbe.ntxq_vi", &t4_ntxq_vi);
253
254#define NRXQ_VI 1
255static int t4_nrxq_vi = -1;
256TUNABLE_INT("hw.cxgbe.nrxq_vi", &t4_nrxq_vi);
257
258static int t4_rsrv_noflowq = 0;
259TUNABLE_INT("hw.cxgbe.rsrv_noflowq", &t4_rsrv_noflowq);
260
261#ifdef TCP_OFFLOAD
262#define NOFLDTXQ_10G 8
263static int t4_nofldtxq10g = -1;
264TUNABLE_INT("hw.cxgbe.nofldtxq10g", &t4_nofldtxq10g);
265
266#define NOFLDRXQ_10G 2
267static int t4_nofldrxq10g = -1;
268TUNABLE_INT("hw.cxgbe.nofldrxq10g", &t4_nofldrxq10g);
269
270#define NOFLDTXQ_1G 2
271static int t4_nofldtxq1g = -1;
272TUNABLE_INT("hw.cxgbe.nofldtxq1g", &t4_nofldtxq1g);
273
274#define NOFLDRXQ_1G 1
275static int t4_nofldrxq1g = -1;
276TUNABLE_INT("hw.cxgbe.nofldrxq1g", &t4_nofldrxq1g);
277
278#define NOFLDTXQ_VI 1
279static int t4_nofldtxq_vi = -1;
280TUNABLE_INT("hw.cxgbe.nofldtxq_vi", &t4_nofldtxq_vi);
281
282#define NOFLDRXQ_VI 1
283static int t4_nofldrxq_vi = -1;
284TUNABLE_INT("hw.cxgbe.nofldrxq_vi", &t4_nofldrxq_vi);
285#endif
286
287#ifdef DEV_NETMAP
288#define NNMTXQ_VI 2
289static int t4_nnmtxq_vi = -1;
290TUNABLE_INT("hw.cxgbe.nnmtxq_vi", &t4_nnmtxq_vi);
291
292#define NNMRXQ_VI 2
293static int t4_nnmrxq_vi = -1;
294TUNABLE_INT("hw.cxgbe.nnmrxq_vi", &t4_nnmrxq_vi);
295#endif
296
297/*
298 * Holdoff parameters for 10G and 1G ports.
299 */
300#define TMR_IDX_10G 1
301int t4_tmr_idx_10g = TMR_IDX_10G;
302TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx_10g);
303
304#define PKTC_IDX_10G (-1)
305int t4_pktc_idx_10g = PKTC_IDX_10G;
306TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx_10g);
307
308#define TMR_IDX_1G 1
309int t4_tmr_idx_1g = TMR_IDX_1G;
310TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_1G", &t4_tmr_idx_1g);
311
312#define PKTC_IDX_1G (-1)
313int t4_pktc_idx_1g = PKTC_IDX_1G;
314TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_1G", &t4_pktc_idx_1g);
315
316/*
317 * Size (# of entries) of each tx and rx queue.
318 */
319unsigned int t4_qsize_txq = TX_EQ_QSIZE;
320TUNABLE_INT("hw.cxgbe.qsize_txq", &t4_qsize_txq);
321
322unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
323TUNABLE_INT("hw.cxgbe.qsize_rxq", &t4_qsize_rxq);
324
325/*
326 * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
327 */
328int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
329TUNABLE_INT("hw.cxgbe.interrupt_types", &t4_intr_types);
330
331/*
332 * Configuration file.
333 */
334#define DEFAULT_CF	"default"
335#define FLASH_CF	"flash"
336#define UWIRE_CF	"uwire"
337#define FPGA_CF		"fpga"
338static char t4_cfg_file[32] = DEFAULT_CF;
339TUNABLE_STR("hw.cxgbe.config_file", t4_cfg_file, sizeof(t4_cfg_file));
340
341/*
342 * PAUSE settings (bit 0, 1 = rx_pause, tx_pause respectively).
343 * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
344 * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
345 *            mark or when signalled to do so, 0 to never emit PAUSE.
346 */
347static int t4_pause_settings = PAUSE_TX | PAUSE_RX;
348TUNABLE_INT("hw.cxgbe.pause_settings", &t4_pause_settings);
349
350/*
351 * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
352 * encouraged respectively).
353 */
354static unsigned int t4_fw_install = 1;
355TUNABLE_INT("hw.cxgbe.fw_install", &t4_fw_install);
356
357/*
358 * ASIC features that will be used.  Disable the ones you don't want so that the
359 * chip resources aren't wasted on features that will not be used.
360 */
361static int t4_nbmcaps_allowed = 0;
362TUNABLE_INT("hw.cxgbe.nbmcaps_allowed", &t4_nbmcaps_allowed);
363
364static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
365TUNABLE_INT("hw.cxgbe.linkcaps_allowed", &t4_linkcaps_allowed);
366
367static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
368    FW_CAPS_CONFIG_SWITCH_EGRESS;
369TUNABLE_INT("hw.cxgbe.switchcaps_allowed", &t4_switchcaps_allowed);
370
371static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC;
372TUNABLE_INT("hw.cxgbe.niccaps_allowed", &t4_niccaps_allowed);
373
374static int t4_toecaps_allowed = -1;
375TUNABLE_INT("hw.cxgbe.toecaps_allowed", &t4_toecaps_allowed);
376
377static int t4_rdmacaps_allowed = -1;
378TUNABLE_INT("hw.cxgbe.rdmacaps_allowed", &t4_rdmacaps_allowed);
379
380static int t4_cryptocaps_allowed = 0;
381TUNABLE_INT("hw.cxgbe.cryptocaps_allowed", &t4_cryptocaps_allowed);
382
383static int t4_iscsicaps_allowed = -1;
384TUNABLE_INT("hw.cxgbe.iscsicaps_allowed", &t4_iscsicaps_allowed);
385
386static int t4_fcoecaps_allowed = 0;
387TUNABLE_INT("hw.cxgbe.fcoecaps_allowed", &t4_fcoecaps_allowed);
388
389static int t5_write_combine = 0;
390TUNABLE_INT("hw.cxl.write_combine", &t5_write_combine);
391
392static int t4_num_vis = 1;
393TUNABLE_INT("hw.cxgbe.num_vis", &t4_num_vis);
394
395/* Functions used by extra VIs to obtain unique MAC addresses for each VI. */
396static int vi_mac_funcs[] = {
397	FW_VI_FUNC_OFLD,
398	FW_VI_FUNC_IWARP,
399	FW_VI_FUNC_OPENISCSI,
400	FW_VI_FUNC_OPENFCOE,
401	FW_VI_FUNC_FOISCSI,
402	FW_VI_FUNC_FOFCOE,
403};
404
405struct intrs_and_queues {
406	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
407	uint16_t nirq;		/* Total # of vectors */
408	uint16_t intr_flags_10g;/* Interrupt flags for each 10G port */
409	uint16_t intr_flags_1g;	/* Interrupt flags for each 1G port */
410	uint16_t ntxq10g;	/* # of NIC txq's for each 10G port */
411	uint16_t nrxq10g;	/* # of NIC rxq's for each 10G port */
412	uint16_t ntxq1g;	/* # of NIC txq's for each 1G port */
413	uint16_t nrxq1g;	/* # of NIC rxq's for each 1G port */
414	uint16_t rsrv_noflowq;	/* Flag whether to reserve queue 0 */
415	uint16_t nofldtxq10g;	/* # of TOE txq's for each 10G port */
416	uint16_t nofldrxq10g;	/* # of TOE rxq's for each 10G port */
417	uint16_t nofldtxq1g;	/* # of TOE txq's for each 1G port */
418	uint16_t nofldrxq1g;	/* # of TOE rxq's for each 1G port */
419
420	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
421	uint16_t ntxq_vi;	/* # of NIC txq's */
422	uint16_t nrxq_vi;	/* # of NIC rxq's */
423	uint16_t nofldtxq_vi;	/* # of TOE txq's */
424	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
425	uint16_t nnmtxq_vi;	/* # of netmap txq's */
426	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
427};
428
429struct filter_entry {
430        uint32_t valid:1;	/* filter allocated and valid */
431        uint32_t locked:1;	/* filter is administratively locked */
432        uint32_t pending:1;	/* filter action is pending firmware reply */
433	uint32_t smtidx:8;	/* Source MAC Table index for smac */
434	struct l2t_entry *l2t;	/* Layer Two Table entry for dmac */
435
436        struct t4_filter_specification fs;
437};
438
439static void setup_memwin(struct adapter *);
440static void position_memwin(struct adapter *, int, uint32_t);
441static int rw_via_memwin(struct adapter *, int, uint32_t, uint32_t *, int, int);
442static inline int read_via_memwin(struct adapter *, int, uint32_t, uint32_t *,
443    int);
444static inline int write_via_memwin(struct adapter *, int, uint32_t,
445    const uint32_t *, int);
446static int validate_mem_range(struct adapter *, uint32_t, int);
447static int fwmtype_to_hwmtype(int);
448static int validate_mt_off_len(struct adapter *, int, uint32_t, int,
449    uint32_t *);
450static int fixup_devlog_params(struct adapter *);
451static int cfg_itype_and_nqueues(struct adapter *, int, int, int,
452    struct intrs_and_queues *);
453static int prep_firmware(struct adapter *);
454static int partition_resources(struct adapter *, const struct firmware *,
455    const char *);
456static int get_params__pre_init(struct adapter *);
457static int get_params__post_init(struct adapter *);
458static int set_params__post_init(struct adapter *);
459static void t4_set_desc(struct adapter *);
460static void build_medialist(struct port_info *, struct ifmedia *);
461static int cxgbe_init_synchronized(struct vi_info *);
462static int cxgbe_uninit_synchronized(struct vi_info *);
463static void quiesce_txq(struct adapter *, struct sge_txq *);
464static void quiesce_wrq(struct adapter *, struct sge_wrq *);
465static void quiesce_iq(struct adapter *, struct sge_iq *);
466static void quiesce_fl(struct adapter *, struct sge_fl *);
467static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
468    driver_intr_t *, void *, char *);
469static int t4_free_irq(struct adapter *, struct irq *);
470static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
471static void vi_refresh_stats(struct adapter *, struct vi_info *);
472static void cxgbe_refresh_stats(struct adapter *, struct port_info *);
473static void cxgbe_tick(void *);
474static void cxgbe_vlan_config(void *, struct ifnet *, uint16_t);
475static void cxgbe_sysctls(struct port_info *);
476static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
477static int sysctl_bitfield(SYSCTL_HANDLER_ARGS);
478static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
479static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
480static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
481static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
482static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
483static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
484static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
485static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
486static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
487#ifdef SBUF_DRAIN
488static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
489static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
490static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
491static int sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS);
492static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
493static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
494static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
495static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
496static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
497static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
498static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
499static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
500static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
501static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
502static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
503static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
504static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
505static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
506static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
507static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
508static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
509static int sysctl_tids(SYSCTL_HANDLER_ARGS);
510static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
511static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
512static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
513static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
514static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
515static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
516static int sysctl_tc_params(SYSCTL_HANDLER_ARGS);
517#endif
518#ifdef TCP_OFFLOAD
519static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
520static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
521static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
522#endif
523static uint32_t fconf_iconf_to_mode(uint32_t, uint32_t);
524static uint32_t mode_to_fconf(uint32_t);
525static uint32_t mode_to_iconf(uint32_t);
526static int check_fspec_against_fconf_iconf(struct adapter *,
527    struct t4_filter_specification *);
528static int get_filter_mode(struct adapter *, uint32_t *);
529static int set_filter_mode(struct adapter *, uint32_t);
530static inline uint64_t get_filter_hits(struct adapter *, uint32_t);
531static int get_filter(struct adapter *, struct t4_filter *);
532static int set_filter(struct adapter *, struct t4_filter *);
533static int del_filter(struct adapter *, struct t4_filter *);
534static void clear_filter(struct filter_entry *);
535static int set_filter_wr(struct adapter *, int);
536static int del_filter_wr(struct adapter *, int);
537static int set_tcb_rpl(struct sge_iq *, const struct rss_header *,
538    struct mbuf *);
539static int get_sge_context(struct adapter *, struct t4_sge_context *);
540static int load_fw(struct adapter *, struct t4_data *);
541static int load_cfg(struct adapter *, struct t4_data *);
542static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
543static int read_i2c(struct adapter *, struct t4_i2c_data *);
544#ifdef TCP_OFFLOAD
545static int toe_capability(struct vi_info *, int);
546#endif
547static int mod_event(module_t, int, void *);
548
549struct {
550	uint16_t device;
551	char *desc;
552} t4_pciids[] = {
553	{0xa000, "Chelsio Terminator 4 FPGA"},
554	{0x4400, "Chelsio T440-dbg"},
555	{0x4401, "Chelsio T420-CR"},
556	{0x4402, "Chelsio T422-CR"},
557	{0x4403, "Chelsio T440-CR"},
558	{0x4404, "Chelsio T420-BCH"},
559	{0x4405, "Chelsio T440-BCH"},
560	{0x4406, "Chelsio T440-CH"},
561	{0x4407, "Chelsio T420-SO"},
562	{0x4408, "Chelsio T420-CX"},
563	{0x4409, "Chelsio T420-BT"},
564	{0x440a, "Chelsio T404-BT"},
565	{0x440e, "Chelsio T440-LP-CR"},
566}, t5_pciids[] = {
567	{0xb000, "Chelsio Terminator 5 FPGA"},
568	{0x5400, "Chelsio T580-dbg"},
569	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
570	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
571	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
572	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
573	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
574	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
575	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
576	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
577	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
578	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
579	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
580	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
581	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
582#ifdef notyet
583	{0x5404,  "Chelsio T520-BCH"},
584	{0x5405,  "Chelsio T540-BCH"},
585	{0x5406,  "Chelsio T540-CH"},
586	{0x5408,  "Chelsio T520-CX"},
587	{0x540b,  "Chelsio B520-SR"},
588	{0x540c,  "Chelsio B504-BT"},
589	{0x540f,  "Chelsio Amsterdam"},
590	{0x5413,  "Chelsio T580-CHR"},
591#endif
592}, t6_pciids[] = {
593	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
594	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
595	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
596	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
597	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
598	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
599	{0x6410, "Chelsio T62100-DBG"},		/* 2 x 40/50/100G, debug */
600};
601
602#ifdef TCP_OFFLOAD
603/*
604 * service_iq() has an iq and needs the fl.  Offset of fl from the iq should be
605 * exactly the same for both rxq and ofld_rxq.
606 */
607CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
608CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
609#endif
610CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
611
612static int
613t4_probe(device_t dev)
614{
615	int i;
616	uint16_t v = pci_get_vendor(dev);
617	uint16_t d = pci_get_device(dev);
618	uint8_t f = pci_get_function(dev);
619
620	if (v != PCI_VENDOR_ID_CHELSIO)
621		return (ENXIO);
622
623	/* Attach only to PF0 of the FPGA */
624	if (d == 0xa000 && f != 0)
625		return (ENXIO);
626
627	for (i = 0; i < nitems(t4_pciids); i++) {
628		if (d == t4_pciids[i].device) {
629			device_set_desc(dev, t4_pciids[i].desc);
630			return (BUS_PROBE_DEFAULT);
631		}
632	}
633
634	return (ENXIO);
635}
636
637static int
638t5_probe(device_t dev)
639{
640	int i;
641	uint16_t v = pci_get_vendor(dev);
642	uint16_t d = pci_get_device(dev);
643	uint8_t f = pci_get_function(dev);
644
645	if (v != PCI_VENDOR_ID_CHELSIO)
646		return (ENXIO);
647
648	/* Attach only to PF0 of the FPGA */
649	if (d == 0xb000 && f != 0)
650		return (ENXIO);
651
652	for (i = 0; i < nitems(t5_pciids); i++) {
653		if (d == t5_pciids[i].device) {
654			device_set_desc(dev, t5_pciids[i].desc);
655			return (BUS_PROBE_DEFAULT);
656		}
657	}
658
659	return (ENXIO);
660}
661
662static int
663t6_probe(device_t dev)
664{
665	int i;
666	uint16_t v = pci_get_vendor(dev);
667	uint16_t d = pci_get_device(dev);
668
669	if (v != PCI_VENDOR_ID_CHELSIO)
670		return (ENXIO);
671
672	for (i = 0; i < nitems(t6_pciids); i++) {
673		if (d == t6_pciids[i].device) {
674			device_set_desc(dev, t6_pciids[i].desc);
675			return (BUS_PROBE_DEFAULT);
676		}
677	}
678
679	return (ENXIO);
680}
681
682static void
683t5_attribute_workaround(device_t dev)
684{
685	device_t root_port;
686	uint32_t v;
687
688	/*
689	 * The T5 chips do not properly echo the No Snoop and Relaxed
690	 * Ordering attributes when replying to a TLP from a Root
691	 * Port.  As a workaround, find the parent Root Port and
692	 * disable No Snoop and Relaxed Ordering.  Note that this
693	 * affects all devices under this root port.
694	 */
695	root_port = pci_find_pcie_root_port(dev);
696	if (root_port == NULL) {
697		device_printf(dev, "Unable to find parent root port\n");
698		return;
699	}
700
701	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
702	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
703	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
704	    0)
705		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
706		    device_get_nameunit(root_port));
707}
708
709static const struct devnames devnames[] = {
710	{
711		.nexus_name = "t4nex",
712		.ifnet_name = "cxgbe",
713		.vi_ifnet_name = "vcxgbe",
714		.pf03_drv_name = "t4iov",
715		.vf_nexus_name = "t4vf",
716		.vf_ifnet_name = "cxgbev"
717	}, {
718		.nexus_name = "t5nex",
719		.ifnet_name = "cxl",
720		.vi_ifnet_name = "vcxl",
721		.pf03_drv_name = "t5iov",
722		.vf_nexus_name = "t5vf",
723		.vf_ifnet_name = "cxlv"
724	}, {
725		.nexus_name = "t6nex",
726		.ifnet_name = "cc",
727		.vi_ifnet_name = "vcc",
728		.pf03_drv_name = "t6iov",
729		.vf_nexus_name = "t6vf",
730		.vf_ifnet_name = "ccv"
731	}
732};
733
734void
735t4_init_devnames(struct adapter *sc)
736{
737	int id;
738
739	id = chip_id(sc);
740	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
741		sc->names = &devnames[id - CHELSIO_T4];
742	else {
743		device_printf(sc->dev, "chip id %d is not supported.\n", id);
744		sc->names = NULL;
745	}
746}
747
748static int
749t4_attach(device_t dev)
750{
751	struct adapter *sc;
752	int rc = 0, i, j, n10g, n1g, rqidx, tqidx;
753	struct make_dev_args mda;
754	struct intrs_and_queues iaq;
755	struct sge *s;
756	uint8_t *buf;
757#ifdef TCP_OFFLOAD
758	int ofld_rqidx, ofld_tqidx;
759#endif
760#ifdef DEV_NETMAP
761	int nm_rqidx, nm_tqidx;
762#endif
763	int num_vis;
764
765	sc = device_get_softc(dev);
766	sc->dev = dev;
767	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
768
769	if ((pci_get_device(dev) & 0xff00) == 0x5400)
770		t5_attribute_workaround(dev);
771	pci_enable_busmaster(dev);
772	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
773		uint32_t v;
774
775		pci_set_max_read_req(dev, 4096);
776		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
777		v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
778		pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
779
780		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
781	}
782
783	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
784	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
785	sc->traceq = -1;
786	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
787	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
788	    device_get_nameunit(dev));
789
790	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
791	    device_get_nameunit(dev));
792	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
793	t4_add_adapter(sc);
794
795	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
796	TAILQ_INIT(&sc->sfl);
797	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
798
799	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
800
801	rc = t4_map_bars_0_and_4(sc);
802	if (rc != 0)
803		goto done; /* error message displayed already */
804
805	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
806
807	/* Prepare the adapter for operation. */
808	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
809	rc = -t4_prep_adapter(sc, buf);
810	free(buf, M_CXGBE);
811	if (rc != 0) {
812		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
813		goto done;
814	}
815
816	/*
817	 * This is the real PF# to which we're attaching.  Works from within PCI
818	 * passthrough environments too, where pci_get_function() could return a
819	 * different PF# depending on the passthrough configuration.  We need to
820	 * use the real PF# in all our communication with the firmware.
821	 */
822	j = t4_read_reg(sc, A_PL_WHOAMI);
823	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
824	sc->mbox = sc->pf;
825
826	t4_init_devnames(sc);
827	if (sc->names == NULL) {
828		rc = ENOTSUP;
829		goto done; /* error message displayed already */
830	}
831
832	/*
833	 * Do this really early, with the memory windows set up even before the
834	 * character device.  The userland tool's register i/o and mem read
835	 * will work even in "recovery mode".
836	 */
837	setup_memwin(sc);
838	if (t4_init_devlog_params(sc, 0) == 0)
839		fixup_devlog_params(sc);
840	make_dev_args_init(&mda);
841	mda.mda_devsw = &t4_cdevsw;
842	mda.mda_uid = UID_ROOT;
843	mda.mda_gid = GID_WHEEL;
844	mda.mda_mode = 0600;
845	mda.mda_si_drv1 = sc;
846	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
847	if (rc != 0)
848		device_printf(dev, "failed to create nexus char device: %d.\n",
849		    rc);
850
851	/* Go no further if recovery mode has been requested. */
852	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
853		device_printf(dev, "recovery mode.\n");
854		goto done;
855	}
856
857#if defined(__i386__)
858	if ((cpu_feature & CPUID_CX8) == 0) {
859		device_printf(dev, "64 bit atomics not available.\n");
860		rc = ENOTSUP;
861		goto done;
862	}
863#endif
864
865	/* Prepare the firmware for operation */
866	rc = prep_firmware(sc);
867	if (rc != 0)
868		goto done; /* error message displayed already */
869
870	rc = get_params__post_init(sc);
871	if (rc != 0)
872		goto done; /* error message displayed already */
873
874	rc = set_params__post_init(sc);
875	if (rc != 0)
876		goto done; /* error message displayed already */
877
878	rc = t4_map_bar_2(sc);
879	if (rc != 0)
880		goto done; /* error message displayed already */
881
882	rc = t4_create_dma_tag(sc);
883	if (rc != 0)
884		goto done; /* error message displayed already */
885
886	/*
887	 * Number of VIs to create per-port.  The first VI is the "main" regular
888	 * VI for the port.  The rest are additional virtual interfaces on the
889	 * same physical port.  Note that the main VI does not have native
890	 * netmap support but the extra VIs do.
891	 *
892	 * Limit the number of VIs per port to the number of available
893	 * MAC addresses per port.
894	 */
895	if (t4_num_vis >= 1)
896		num_vis = t4_num_vis;
897	else
898		num_vis = 1;
899	if (num_vis > nitems(vi_mac_funcs)) {
900		num_vis = nitems(vi_mac_funcs);
901		device_printf(dev, "Number of VIs limited to %d\n", num_vis);
902	}
903
904	/*
905	 * First pass over all the ports - allocate VIs and initialize some
906	 * basic parameters like mac address, port type, etc.  We also figure
907	 * out whether a port is 10G or 1G and use that information when
908	 * calculating how many interrupts to attempt to allocate.
909	 */
910	n10g = n1g = 0;
911	for_each_port(sc, i) {
912		struct port_info *pi;
913
914		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
915		sc->port[i] = pi;
916
917		/* These must be set before t4_port_init */
918		pi->adapter = sc;
919		pi->port_id = i;
920		/*
921		 * XXX: vi[0] is special so we can't delay this allocation until
922		 * pi->nvi's final value is known.
923		 */
924		pi->vi = malloc(sizeof(struct vi_info) * num_vis, M_CXGBE,
925		    M_ZERO | M_WAITOK);
926
927		/*
928		 * Allocate the "main" VI and initialize parameters
929		 * like mac addr.
930		 */
931		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
932		if (rc != 0) {
933			device_printf(dev, "unable to initialize port %d: %d\n",
934			    i, rc);
935			free(pi->vi, M_CXGBE);
936			free(pi, M_CXGBE);
937			sc->port[i] = NULL;
938			goto done;
939		}
940
941		pi->link_cfg.requested_fc &= ~(PAUSE_TX | PAUSE_RX);
942		pi->link_cfg.requested_fc |= t4_pause_settings;
943		pi->link_cfg.fc &= ~(PAUSE_TX | PAUSE_RX);
944		pi->link_cfg.fc |= t4_pause_settings;
945
946		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, &pi->link_cfg);
947		if (rc != 0) {
948			device_printf(dev, "port %d l1cfg failed: %d\n", i, rc);
949			free(pi->vi, M_CXGBE);
950			free(pi, M_CXGBE);
951			sc->port[i] = NULL;
952			goto done;
953		}
954
955		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
956		    device_get_nameunit(dev), i);
957		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
958		sc->chan_map[pi->tx_chan] = i;
959
960		pi->tc = malloc(sizeof(struct tx_sched_class) *
961		    sc->chip_params->nsched_cls, M_CXGBE, M_ZERO | M_WAITOK);
962
963		if (port_top_speed(pi) >= 10) {
964			n10g++;
965		} else {
966			n1g++;
967		}
968
969		pi->linkdnrc = -1;
970
971		pi->dev = device_add_child(dev, sc->names->ifnet_name, -1);
972		if (pi->dev == NULL) {
973			device_printf(dev,
974			    "failed to add device for port %d.\n", i);
975			rc = ENXIO;
976			goto done;
977		}
978		pi->vi[0].dev = pi->dev;
979		device_set_softc(pi->dev, pi);
980	}
981
982	/*
983	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
984	 */
985	rc = cfg_itype_and_nqueues(sc, n10g, n1g, num_vis, &iaq);
986	if (rc != 0)
987		goto done; /* error message displayed already */
988	if (iaq.nrxq_vi + iaq.nofldrxq_vi + iaq.nnmrxq_vi == 0)
989		num_vis = 1;
990
991	sc->intr_type = iaq.intr_type;
992	sc->intr_count = iaq.nirq;
993
994	s = &sc->sge;
995	s->nrxq = n10g * iaq.nrxq10g + n1g * iaq.nrxq1g;
996	s->ntxq = n10g * iaq.ntxq10g + n1g * iaq.ntxq1g;
997	if (num_vis > 1) {
998		s->nrxq += (n10g + n1g) * (num_vis - 1) * iaq.nrxq_vi;
999		s->ntxq += (n10g + n1g) * (num_vis - 1) * iaq.ntxq_vi;
1000	}
1001	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1002	s->neq += sc->params.nports + 1;/* ctrl queues: 1 per port + 1 mgmt */
1003	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1004#ifdef TCP_OFFLOAD
1005	if (is_offload(sc)) {
1006		s->nofldrxq = n10g * iaq.nofldrxq10g + n1g * iaq.nofldrxq1g;
1007		s->nofldtxq = n10g * iaq.nofldtxq10g + n1g * iaq.nofldtxq1g;
1008		if (num_vis > 1) {
1009			s->nofldrxq += (n10g + n1g) * (num_vis - 1) *
1010			    iaq.nofldrxq_vi;
1011			s->nofldtxq += (n10g + n1g) * (num_vis - 1) *
1012			    iaq.nofldtxq_vi;
1013		}
1014		s->neq += s->nofldtxq + s->nofldrxq;
1015		s->niq += s->nofldrxq;
1016
1017		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1018		    M_CXGBE, M_ZERO | M_WAITOK);
1019		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_wrq),
1020		    M_CXGBE, M_ZERO | M_WAITOK);
1021	}
1022#endif
1023#ifdef DEV_NETMAP
1024	if (num_vis > 1) {
1025		s->nnmrxq = (n10g + n1g) * (num_vis - 1) * iaq.nnmrxq_vi;
1026		s->nnmtxq = (n10g + n1g) * (num_vis - 1) * iaq.nnmtxq_vi;
1027	}
1028	s->neq += s->nnmtxq + s->nnmrxq;
1029	s->niq += s->nnmrxq;
1030
1031	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1032	    M_CXGBE, M_ZERO | M_WAITOK);
1033	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1034	    M_CXGBE, M_ZERO | M_WAITOK);
1035#endif
1036
1037	s->ctrlq = malloc(sc->params.nports * sizeof(struct sge_wrq), M_CXGBE,
1038	    M_ZERO | M_WAITOK);
1039	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1040	    M_ZERO | M_WAITOK);
1041	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1042	    M_ZERO | M_WAITOK);
1043	s->iqmap = malloc(s->niq * sizeof(struct sge_iq *), M_CXGBE,
1044	    M_ZERO | M_WAITOK);
1045	s->eqmap = malloc(s->neq * sizeof(struct sge_eq *), M_CXGBE,
1046	    M_ZERO | M_WAITOK);
1047
1048	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1049	    M_ZERO | M_WAITOK);
1050
1051	t4_init_l2t(sc, M_WAITOK);
1052
1053	/*
1054	 * Second pass over the ports.  This time we know the number of rx and
1055	 * tx queues that each port should get.
1056	 */
1057	rqidx = tqidx = 0;
1058#ifdef TCP_OFFLOAD
1059	ofld_rqidx = ofld_tqidx = 0;
1060#endif
1061#ifdef DEV_NETMAP
1062	nm_rqidx = nm_tqidx = 0;
1063#endif
1064	for_each_port(sc, i) {
1065		struct port_info *pi = sc->port[i];
1066		struct vi_info *vi;
1067
1068		if (pi == NULL)
1069			continue;
1070
1071		pi->nvi = num_vis;
1072		for_each_vi(pi, j, vi) {
1073			vi->pi = pi;
1074			vi->qsize_rxq = t4_qsize_rxq;
1075			vi->qsize_txq = t4_qsize_txq;
1076
1077			vi->first_rxq = rqidx;
1078			vi->first_txq = tqidx;
1079			if (port_top_speed(pi) >= 10) {
1080				vi->tmr_idx = t4_tmr_idx_10g;
1081				vi->pktc_idx = t4_pktc_idx_10g;
1082				vi->flags |= iaq.intr_flags_10g & INTR_RXQ;
1083				vi->nrxq = j == 0 ? iaq.nrxq10g : iaq.nrxq_vi;
1084				vi->ntxq = j == 0 ? iaq.ntxq10g : iaq.ntxq_vi;
1085			} else {
1086				vi->tmr_idx = t4_tmr_idx_1g;
1087				vi->pktc_idx = t4_pktc_idx_1g;
1088				vi->flags |= iaq.intr_flags_1g & INTR_RXQ;
1089				vi->nrxq = j == 0 ? iaq.nrxq1g : iaq.nrxq_vi;
1090				vi->ntxq = j == 0 ? iaq.ntxq1g : iaq.ntxq_vi;
1091			}
1092			rqidx += vi->nrxq;
1093			tqidx += vi->ntxq;
1094
1095			if (j == 0 && vi->ntxq > 1)
1096				vi->rsrv_noflowq = iaq.rsrv_noflowq ? 1 : 0;
1097			else
1098				vi->rsrv_noflowq = 0;
1099
1100#ifdef TCP_OFFLOAD
1101			vi->first_ofld_rxq = ofld_rqidx;
1102			vi->first_ofld_txq = ofld_tqidx;
1103			if (port_top_speed(pi) >= 10) {
1104				vi->flags |= iaq.intr_flags_10g & INTR_OFLD_RXQ;
1105				vi->nofldrxq = j == 0 ? iaq.nofldrxq10g :
1106				    iaq.nofldrxq_vi;
1107				vi->nofldtxq = j == 0 ? iaq.nofldtxq10g :
1108				    iaq.nofldtxq_vi;
1109			} else {
1110				vi->flags |= iaq.intr_flags_1g & INTR_OFLD_RXQ;
1111				vi->nofldrxq = j == 0 ? iaq.nofldrxq1g :
1112				    iaq.nofldrxq_vi;
1113				vi->nofldtxq = j == 0 ? iaq.nofldtxq1g :
1114				    iaq.nofldtxq_vi;
1115			}
1116			ofld_rqidx += vi->nofldrxq;
1117			ofld_tqidx += vi->nofldtxq;
1118#endif
1119#ifdef DEV_NETMAP
1120			if (j > 0) {
1121				vi->first_nm_rxq = nm_rqidx;
1122				vi->first_nm_txq = nm_tqidx;
1123				vi->nnmrxq = iaq.nnmrxq_vi;
1124				vi->nnmtxq = iaq.nnmtxq_vi;
1125				nm_rqidx += vi->nnmrxq;
1126				nm_tqidx += vi->nnmtxq;
1127			}
1128#endif
1129		}
1130	}
1131
1132	rc = t4_setup_intr_handlers(sc);
1133	if (rc != 0) {
1134		device_printf(dev,
1135		    "failed to setup interrupt handlers: %d\n", rc);
1136		goto done;
1137	}
1138
1139	rc = bus_generic_attach(dev);
1140	if (rc != 0) {
1141		device_printf(dev,
1142		    "failed to attach all child ports: %d\n", rc);
1143		goto done;
1144	}
1145
1146	device_printf(dev,
1147	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1148	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1149	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1150	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1151	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1152
1153	t4_set_desc(sc);
1154
1155done:
1156	if (rc != 0 && sc->cdev) {
1157		/* cdev was created and so cxgbetool works; recover that way. */
1158		device_printf(dev,
1159		    "error during attach, adapter is now in recovery mode.\n");
1160		rc = 0;
1161	}
1162
1163	if (rc != 0)
1164		t4_detach_common(dev);
1165	else
1166		t4_sysctls(sc);
1167
1168	return (rc);
1169}
1170
1171/*
1172 * Idempotent
1173 */
1174static int
1175t4_detach(device_t dev)
1176{
1177	struct adapter *sc;
1178
1179	sc = device_get_softc(dev);
1180
1181	return (t4_detach_common(dev));
1182}
1183
1184int
1185t4_detach_common(device_t dev)
1186{
1187	struct adapter *sc;
1188	struct port_info *pi;
1189	int i, rc;
1190
1191	sc = device_get_softc(dev);
1192
1193	if (sc->flags & FULL_INIT_DONE) {
1194		if (!(sc->flags & IS_VF))
1195			t4_intr_disable(sc);
1196	}
1197
1198	if (sc->cdev) {
1199		destroy_dev(sc->cdev);
1200		sc->cdev = NULL;
1201	}
1202
1203	if (device_is_attached(dev)) {
1204		rc = bus_generic_detach(dev);
1205		if (rc) {
1206			device_printf(dev,
1207			    "failed to detach child devices: %d\n", rc);
1208			return (rc);
1209		}
1210	}
1211
1212	for (i = 0; i < sc->intr_count; i++)
1213		t4_free_irq(sc, &sc->irq[i]);
1214
1215	for (i = 0; i < MAX_NPORTS; i++) {
1216		pi = sc->port[i];
1217		if (pi) {
1218			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1219			if (pi->dev)
1220				device_delete_child(dev, pi->dev);
1221
1222			mtx_destroy(&pi->pi_lock);
1223			free(pi->vi, M_CXGBE);
1224			free(pi->tc, M_CXGBE);
1225			free(pi, M_CXGBE);
1226		}
1227	}
1228
1229	if (sc->flags & FULL_INIT_DONE)
1230		adapter_full_uninit(sc);
1231
1232	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1233		t4_fw_bye(sc, sc->mbox);
1234
1235	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1236		pci_release_msi(dev);
1237
1238	if (sc->regs_res)
1239		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1240		    sc->regs_res);
1241
1242	if (sc->udbs_res)
1243		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1244		    sc->udbs_res);
1245
1246	if (sc->msix_res)
1247		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1248		    sc->msix_res);
1249
1250	if (sc->l2t)
1251		t4_free_l2t(sc->l2t);
1252
1253#ifdef TCP_OFFLOAD
1254	free(sc->sge.ofld_rxq, M_CXGBE);
1255	free(sc->sge.ofld_txq, M_CXGBE);
1256#endif
1257#ifdef DEV_NETMAP
1258	free(sc->sge.nm_rxq, M_CXGBE);
1259	free(sc->sge.nm_txq, M_CXGBE);
1260#endif
1261	free(sc->irq, M_CXGBE);
1262	free(sc->sge.rxq, M_CXGBE);
1263	free(sc->sge.txq, M_CXGBE);
1264	free(sc->sge.ctrlq, M_CXGBE);
1265	free(sc->sge.iqmap, M_CXGBE);
1266	free(sc->sge.eqmap, M_CXGBE);
1267	free(sc->tids.ftid_tab, M_CXGBE);
1268	t4_destroy_dma_tag(sc);
1269	if (mtx_initialized(&sc->sc_lock)) {
1270		sx_xlock(&t4_list_lock);
1271		SLIST_REMOVE(&t4_list, sc, adapter, link);
1272		sx_xunlock(&t4_list_lock);
1273		mtx_destroy(&sc->sc_lock);
1274	}
1275
1276	callout_drain(&sc->sfl_callout);
1277	if (mtx_initialized(&sc->tids.ftid_lock))
1278		mtx_destroy(&sc->tids.ftid_lock);
1279	if (mtx_initialized(&sc->sfl_lock))
1280		mtx_destroy(&sc->sfl_lock);
1281	if (mtx_initialized(&sc->ifp_lock))
1282		mtx_destroy(&sc->ifp_lock);
1283	if (mtx_initialized(&sc->reg_lock))
1284		mtx_destroy(&sc->reg_lock);
1285
1286	for (i = 0; i < NUM_MEMWIN; i++) {
1287		struct memwin *mw = &sc->memwin[i];
1288
1289		if (rw_initialized(&mw->mw_lock))
1290			rw_destroy(&mw->mw_lock);
1291	}
1292
1293	bzero(sc, sizeof(*sc));
1294
1295	return (0);
1296}
1297
1298static int
1299cxgbe_probe(device_t dev)
1300{
1301	char buf[128];
1302	struct port_info *pi = device_get_softc(dev);
1303
1304	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
1305	device_set_desc_copy(dev, buf);
1306
1307	return (BUS_PROBE_DEFAULT);
1308}
1309
1310#define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
1311    IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
1312    IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS)
1313#define T4_CAP_ENABLE (T4_CAP)
1314
1315static int
1316cxgbe_vi_attach(device_t dev, struct vi_info *vi)
1317{
1318	struct ifnet *ifp;
1319	struct sbuf *sb;
1320
1321	vi->xact_addr_filt = -1;
1322	callout_init(&vi->tick, 1);
1323
1324	/* Allocate an ifnet and set it up */
1325	ifp = if_alloc(IFT_ETHER);
1326	if (ifp == NULL) {
1327		device_printf(dev, "Cannot allocate ifnet\n");
1328		return (ENOMEM);
1329	}
1330	vi->ifp = ifp;
1331	ifp->if_softc = vi;
1332
1333	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1334	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1335
1336	ifp->if_init = cxgbe_init;
1337	ifp->if_ioctl = cxgbe_ioctl;
1338	ifp->if_transmit = cxgbe_transmit;
1339	ifp->if_qflush = cxgbe_qflush;
1340
1341	ifp->if_capabilities = T4_CAP;
1342#ifdef TCP_OFFLOAD
1343	if (vi->nofldrxq != 0)
1344		ifp->if_capabilities |= IFCAP_TOE;
1345#endif
1346	ifp->if_capenable = T4_CAP_ENABLE;
1347	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
1348	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
1349
1350	ifp->if_hw_tsomax = 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
1351	ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS;
1352	ifp->if_hw_tsomaxsegsize = 65536;
1353
1354	/* Initialize ifmedia for this VI */
1355	ifmedia_init(&vi->media, IFM_IMASK, cxgbe_media_change,
1356	    cxgbe_media_status);
1357	build_medialist(vi->pi, &vi->media);
1358
1359	vi->vlan_c = EVENTHANDLER_REGISTER(vlan_config, cxgbe_vlan_config, ifp,
1360	    EVENTHANDLER_PRI_ANY);
1361
1362	ether_ifattach(ifp, vi->hw_addr);
1363#ifdef DEV_NETMAP
1364	if (vi->nnmrxq != 0)
1365		cxgbe_nm_attach(vi);
1366#endif
1367	sb = sbuf_new_auto();
1368	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
1369#ifdef TCP_OFFLOAD
1370	if (ifp->if_capabilities & IFCAP_TOE)
1371		sbuf_printf(sb, "; %d txq, %d rxq (TOE)",
1372		    vi->nofldtxq, vi->nofldrxq);
1373#endif
1374#ifdef DEV_NETMAP
1375	if (ifp->if_capabilities & IFCAP_NETMAP)
1376		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
1377		    vi->nnmtxq, vi->nnmrxq);
1378#endif
1379	sbuf_finish(sb);
1380	device_printf(dev, "%s\n", sbuf_data(sb));
1381	sbuf_delete(sb);
1382
1383	vi_sysctls(vi);
1384
1385	return (0);
1386}
1387
1388static int
1389cxgbe_attach(device_t dev)
1390{
1391	struct port_info *pi = device_get_softc(dev);
1392	struct adapter *sc = pi->adapter;
1393	struct vi_info *vi;
1394	int i, rc;
1395
1396	callout_init_mtx(&pi->tick, &pi->pi_lock, 0);
1397
1398	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
1399	if (rc)
1400		return (rc);
1401
1402	for_each_vi(pi, i, vi) {
1403		if (i == 0)
1404			continue;
1405		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
1406		if (vi->dev == NULL) {
1407			device_printf(dev, "failed to add VI %d\n", i);
1408			continue;
1409		}
1410		device_set_softc(vi->dev, vi);
1411	}
1412
1413	cxgbe_sysctls(pi);
1414
1415	bus_generic_attach(dev);
1416
1417	return (0);
1418}
1419
1420static void
1421cxgbe_vi_detach(struct vi_info *vi)
1422{
1423	struct ifnet *ifp = vi->ifp;
1424
1425	ether_ifdetach(ifp);
1426
1427	if (vi->vlan_c)
1428		EVENTHANDLER_DEREGISTER(vlan_config, vi->vlan_c);
1429
1430	/* Let detach proceed even if these fail. */
1431#ifdef DEV_NETMAP
1432	if (ifp->if_capabilities & IFCAP_NETMAP)
1433		cxgbe_nm_detach(vi);
1434#endif
1435	cxgbe_uninit_synchronized(vi);
1436	callout_drain(&vi->tick);
1437	vi_full_uninit(vi);
1438
1439	ifmedia_removeall(&vi->media);
1440	if_free(vi->ifp);
1441	vi->ifp = NULL;
1442}
1443
1444static int
1445cxgbe_detach(device_t dev)
1446{
1447	struct port_info *pi = device_get_softc(dev);
1448	struct adapter *sc = pi->adapter;
1449	int rc;
1450
1451	/* Detach the extra VIs first. */
1452	rc = bus_generic_detach(dev);
1453	if (rc)
1454		return (rc);
1455	device_delete_children(dev);
1456
1457	doom_vi(sc, &pi->vi[0]);
1458
1459	if (pi->flags & HAS_TRACEQ) {
1460		sc->traceq = -1;	/* cloner should not create ifnet */
1461		t4_tracer_port_detach(sc);
1462	}
1463
1464	cxgbe_vi_detach(&pi->vi[0]);
1465	callout_drain(&pi->tick);
1466
1467	end_synchronized_op(sc, 0);
1468
1469	return (0);
1470}
1471
1472static void
1473cxgbe_init(void *arg)
1474{
1475	struct vi_info *vi = arg;
1476	struct adapter *sc = vi->pi->adapter;
1477
1478	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
1479		return;
1480	cxgbe_init_synchronized(vi);
1481	end_synchronized_op(sc, 0);
1482}
1483
1484static int
1485cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
1486{
1487	int rc = 0, mtu, flags, can_sleep;
1488	struct vi_info *vi = ifp->if_softc;
1489	struct adapter *sc = vi->pi->adapter;
1490	struct ifreq *ifr = (struct ifreq *)data;
1491	uint32_t mask;
1492
1493	switch (cmd) {
1494	case SIOCSIFMTU:
1495		mtu = ifr->ifr_mtu;
1496		if (mtu < ETHERMIN || mtu > MAX_MTU)
1497			return (EINVAL);
1498
1499		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
1500		if (rc)
1501			return (rc);
1502		ifp->if_mtu = mtu;
1503		if (vi->flags & VI_INIT_DONE) {
1504			t4_update_fl_bufsize(ifp);
1505			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1506				rc = update_mac_settings(ifp, XGMAC_MTU);
1507		}
1508		end_synchronized_op(sc, 0);
1509		break;
1510
1511	case SIOCSIFFLAGS:
1512		can_sleep = 0;
1513redo_sifflags:
1514		rc = begin_synchronized_op(sc, vi,
1515		    can_sleep ? (SLEEP_OK | INTR_OK) : HOLD_LOCK, "t4flg");
1516		if (rc)
1517			return (rc);
1518
1519		if (ifp->if_flags & IFF_UP) {
1520			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1521				flags = vi->if_flags;
1522				if ((ifp->if_flags ^ flags) &
1523				    (IFF_PROMISC | IFF_ALLMULTI)) {
1524					if (can_sleep == 1) {
1525						end_synchronized_op(sc, 0);
1526						can_sleep = 0;
1527						goto redo_sifflags;
1528					}
1529					rc = update_mac_settings(ifp,
1530					    XGMAC_PROMISC | XGMAC_ALLMULTI);
1531				}
1532			} else {
1533				if (can_sleep == 0) {
1534					end_synchronized_op(sc, LOCK_HELD);
1535					can_sleep = 1;
1536					goto redo_sifflags;
1537				}
1538				rc = cxgbe_init_synchronized(vi);
1539			}
1540			vi->if_flags = ifp->if_flags;
1541		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1542			if (can_sleep == 0) {
1543				end_synchronized_op(sc, LOCK_HELD);
1544				can_sleep = 1;
1545				goto redo_sifflags;
1546			}
1547			rc = cxgbe_uninit_synchronized(vi);
1548		}
1549		end_synchronized_op(sc, can_sleep ? 0 : LOCK_HELD);
1550		break;
1551
1552	case SIOCADDMULTI:
1553	case SIOCDELMULTI: /* these two are called with a mutex held :-( */
1554		rc = begin_synchronized_op(sc, vi, HOLD_LOCK, "t4multi");
1555		if (rc)
1556			return (rc);
1557		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1558			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
1559		end_synchronized_op(sc, LOCK_HELD);
1560		break;
1561
1562	case SIOCSIFCAP:
1563		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
1564		if (rc)
1565			return (rc);
1566
1567		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1568		if (mask & IFCAP_TXCSUM) {
1569			ifp->if_capenable ^= IFCAP_TXCSUM;
1570			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
1571
1572			if (IFCAP_TSO4 & ifp->if_capenable &&
1573			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
1574				ifp->if_capenable &= ~IFCAP_TSO4;
1575				if_printf(ifp,
1576				    "tso4 disabled due to -txcsum.\n");
1577			}
1578		}
1579		if (mask & IFCAP_TXCSUM_IPV6) {
1580			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
1581			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
1582
1583			if (IFCAP_TSO6 & ifp->if_capenable &&
1584			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1585				ifp->if_capenable &= ~IFCAP_TSO6;
1586				if_printf(ifp,
1587				    "tso6 disabled due to -txcsum6.\n");
1588			}
1589		}
1590		if (mask & IFCAP_RXCSUM)
1591			ifp->if_capenable ^= IFCAP_RXCSUM;
1592		if (mask & IFCAP_RXCSUM_IPV6)
1593			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
1594
1595		/*
1596		 * Note that we leave CSUM_TSO alone (it is always set).  The
1597		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
1598		 * sending a TSO request our way, so it's sufficient to toggle
1599		 * IFCAP_TSOx only.
1600		 */
1601		if (mask & IFCAP_TSO4) {
1602			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
1603			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
1604				if_printf(ifp, "enable txcsum first.\n");
1605				rc = EAGAIN;
1606				goto fail;
1607			}
1608			ifp->if_capenable ^= IFCAP_TSO4;
1609		}
1610		if (mask & IFCAP_TSO6) {
1611			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
1612			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1613				if_printf(ifp, "enable txcsum6 first.\n");
1614				rc = EAGAIN;
1615				goto fail;
1616			}
1617			ifp->if_capenable ^= IFCAP_TSO6;
1618		}
1619		if (mask & IFCAP_LRO) {
1620#if defined(INET) || defined(INET6)
1621			int i;
1622			struct sge_rxq *rxq;
1623
1624			ifp->if_capenable ^= IFCAP_LRO;
1625			for_each_rxq(vi, i, rxq) {
1626				if (ifp->if_capenable & IFCAP_LRO)
1627					rxq->iq.flags |= IQ_LRO_ENABLED;
1628				else
1629					rxq->iq.flags &= ~IQ_LRO_ENABLED;
1630			}
1631#endif
1632		}
1633#ifdef TCP_OFFLOAD
1634		if (mask & IFCAP_TOE) {
1635			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
1636
1637			rc = toe_capability(vi, enable);
1638			if (rc != 0)
1639				goto fail;
1640
1641			ifp->if_capenable ^= mask;
1642		}
1643#endif
1644		if (mask & IFCAP_VLAN_HWTAGGING) {
1645			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1646			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1647				rc = update_mac_settings(ifp, XGMAC_VLANEX);
1648		}
1649		if (mask & IFCAP_VLAN_MTU) {
1650			ifp->if_capenable ^= IFCAP_VLAN_MTU;
1651
1652			/* Need to find out how to disable auto-mtu-inflation */
1653		}
1654		if (mask & IFCAP_VLAN_HWTSO)
1655			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1656		if (mask & IFCAP_VLAN_HWCSUM)
1657			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
1658
1659#ifdef VLAN_CAPABILITIES
1660		VLAN_CAPABILITIES(ifp);
1661#endif
1662fail:
1663		end_synchronized_op(sc, 0);
1664		break;
1665
1666	case SIOCSIFMEDIA:
1667	case SIOCGIFMEDIA:
1668	case SIOCGIFXMEDIA:
1669		ifmedia_ioctl(ifp, ifr, &vi->media, cmd);
1670		break;
1671
1672	case SIOCGI2C: {
1673		struct ifi2creq i2c;
1674
1675		rc = copyin(ifr->ifr_data, &i2c, sizeof(i2c));
1676		if (rc != 0)
1677			break;
1678		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
1679			rc = EPERM;
1680			break;
1681		}
1682		if (i2c.len > sizeof(i2c.data)) {
1683			rc = EINVAL;
1684			break;
1685		}
1686		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
1687		if (rc)
1688			return (rc);
1689		rc = -t4_i2c_rd(sc, sc->mbox, vi->pi->port_id, i2c.dev_addr,
1690		    i2c.offset, i2c.len, &i2c.data[0]);
1691		end_synchronized_op(sc, 0);
1692		if (rc == 0)
1693			rc = copyout(&i2c, ifr->ifr_data, sizeof(i2c));
1694		break;
1695	}
1696
1697	default:
1698		rc = ether_ioctl(ifp, cmd, data);
1699	}
1700
1701	return (rc);
1702}
1703
1704static int
1705cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
1706{
1707	struct vi_info *vi = ifp->if_softc;
1708	struct port_info *pi = vi->pi;
1709	struct adapter *sc = pi->adapter;
1710	struct sge_txq *txq;
1711	void *items[1];
1712	int rc;
1713
1714	M_ASSERTPKTHDR(m);
1715	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
1716
1717	if (__predict_false(pi->link_cfg.link_ok == 0)) {
1718		m_freem(m);
1719		return (ENETDOWN);
1720	}
1721
1722	rc = parse_pkt(sc, &m);
1723	if (__predict_false(rc != 0)) {
1724		MPASS(m == NULL);			/* was freed already */
1725		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
1726		return (rc);
1727	}
1728
1729	/* Select a txq. */
1730	txq = &sc->sge.txq[vi->first_txq];
1731	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
1732		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
1733		    vi->rsrv_noflowq);
1734
1735	items[0] = m;
1736	rc = mp_ring_enqueue(txq->r, items, 1, 4096);
1737	if (__predict_false(rc != 0))
1738		m_freem(m);
1739
1740	return (rc);
1741}
1742
1743static void
1744cxgbe_qflush(struct ifnet *ifp)
1745{
1746	struct vi_info *vi = ifp->if_softc;
1747	struct sge_txq *txq;
1748	int i;
1749
1750	/* queues do not exist if !VI_INIT_DONE. */
1751	if (vi->flags & VI_INIT_DONE) {
1752		for_each_txq(vi, i, txq) {
1753			TXQ_LOCK(txq);
1754			txq->eq.flags &= ~EQ_ENABLED;
1755			TXQ_UNLOCK(txq);
1756			while (!mp_ring_is_idle(txq->r)) {
1757				mp_ring_check_drainage(txq->r, 0);
1758				pause("qflush", 1);
1759			}
1760		}
1761	}
1762	if_qflush(ifp);
1763}
1764
1765static int
1766cxgbe_media_change(struct ifnet *ifp)
1767{
1768	struct vi_info *vi = ifp->if_softc;
1769
1770	device_printf(vi->dev, "%s unimplemented.\n", __func__);
1771
1772	return (EOPNOTSUPP);
1773}
1774
1775static void
1776cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1777{
1778	struct vi_info *vi = ifp->if_softc;
1779	struct port_info *pi = vi->pi;
1780	struct ifmedia_entry *cur;
1781	int speed = pi->link_cfg.speed;
1782
1783	cur = vi->media.ifm_cur;
1784
1785	ifmr->ifm_status = IFM_AVALID;
1786	if (!pi->link_cfg.link_ok)
1787		return;
1788
1789	ifmr->ifm_status |= IFM_ACTIVE;
1790
1791	/* active and current will differ iff current media is autoselect. */
1792	if (IFM_SUBTYPE(cur->ifm_media) != IFM_AUTO)
1793		return;
1794
1795	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
1796	if (speed == 10000)
1797		ifmr->ifm_active |= IFM_10G_T;
1798	else if (speed == 1000)
1799		ifmr->ifm_active |= IFM_1000_T;
1800	else if (speed == 100)
1801		ifmr->ifm_active |= IFM_100_TX;
1802	else if (speed == 10)
1803		ifmr->ifm_active |= IFM_10_T;
1804	else
1805		KASSERT(0, ("%s: link up but speed unknown (%u)", __func__,
1806			    speed));
1807}
1808
1809static int
1810vcxgbe_probe(device_t dev)
1811{
1812	char buf[128];
1813	struct vi_info *vi = device_get_softc(dev);
1814
1815	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
1816	    vi - vi->pi->vi);
1817	device_set_desc_copy(dev, buf);
1818
1819	return (BUS_PROBE_DEFAULT);
1820}
1821
1822static int
1823vcxgbe_attach(device_t dev)
1824{
1825	struct vi_info *vi;
1826	struct port_info *pi;
1827	struct adapter *sc;
1828	int func, index, rc;
1829	u32 param, val;
1830
1831	vi = device_get_softc(dev);
1832	pi = vi->pi;
1833	sc = pi->adapter;
1834
1835	index = vi - pi->vi;
1836	KASSERT(index < nitems(vi_mac_funcs),
1837	    ("%s: VI %s doesn't have a MAC func", __func__,
1838	    device_get_nameunit(dev)));
1839	func = vi_mac_funcs[index];
1840	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
1841	    vi->hw_addr, &vi->rss_size, func, 0);
1842	if (rc < 0) {
1843		device_printf(dev, "Failed to allocate virtual interface "
1844		    "for port %d: %d\n", pi->port_id, -rc);
1845		return (-rc);
1846	}
1847	vi->viid = rc;
1848	if (chip_id(sc) <= CHELSIO_T5)
1849		vi->smt_idx = (rc & 0x7f) << 1;
1850	else
1851		vi->smt_idx = (rc & 0x7f);
1852
1853	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
1854	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
1855	    V_FW_PARAMS_PARAM_YZ(vi->viid);
1856	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
1857	if (rc)
1858		vi->rss_base = 0xffff;
1859	else {
1860		/* MPASS((val >> 16) == rss_size); */
1861		vi->rss_base = val & 0xffff;
1862	}
1863
1864	rc = cxgbe_vi_attach(dev, vi);
1865	if (rc) {
1866		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
1867		return (rc);
1868	}
1869	return (0);
1870}
1871
1872static int
1873vcxgbe_detach(device_t dev)
1874{
1875	struct vi_info *vi;
1876	struct adapter *sc;
1877
1878	vi = device_get_softc(dev);
1879	sc = vi->pi->adapter;
1880
1881	doom_vi(sc, vi);
1882
1883	cxgbe_vi_detach(vi);
1884	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
1885
1886	end_synchronized_op(sc, 0);
1887
1888	return (0);
1889}
1890
1891void
1892t4_fatal_err(struct adapter *sc)
1893{
1894	t4_set_reg_field(sc, A_SGE_CONTROL, F_GLOBALENABLE, 0);
1895	t4_intr_disable(sc);
1896	log(LOG_EMERG, "%s: encountered fatal error, adapter stopped.\n",
1897	    device_get_nameunit(sc->dev));
1898}
1899
1900void
1901t4_add_adapter(struct adapter *sc)
1902{
1903	sx_xlock(&t4_list_lock);
1904	SLIST_INSERT_HEAD(&t4_list, sc, link);
1905	sx_xunlock(&t4_list_lock);
1906}
1907
1908int
1909t4_map_bars_0_and_4(struct adapter *sc)
1910{
1911	sc->regs_rid = PCIR_BAR(0);
1912	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
1913	    &sc->regs_rid, RF_ACTIVE);
1914	if (sc->regs_res == NULL) {
1915		device_printf(sc->dev, "cannot map registers.\n");
1916		return (ENXIO);
1917	}
1918	sc->bt = rman_get_bustag(sc->regs_res);
1919	sc->bh = rman_get_bushandle(sc->regs_res);
1920	sc->mmio_len = rman_get_size(sc->regs_res);
1921	setbit(&sc->doorbells, DOORBELL_KDB);
1922
1923	sc->msix_rid = PCIR_BAR(4);
1924	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
1925	    &sc->msix_rid, RF_ACTIVE);
1926	if (sc->msix_res == NULL) {
1927		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
1928		return (ENXIO);
1929	}
1930
1931	return (0);
1932}
1933
1934int
1935t4_map_bar_2(struct adapter *sc)
1936{
1937
1938	/*
1939	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
1940	 * to map it if RDMA is disabled.
1941	 */
1942	if (is_t4(sc) && sc->rdmacaps == 0)
1943		return (0);
1944
1945	sc->udbs_rid = PCIR_BAR(2);
1946	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
1947	    &sc->udbs_rid, RF_ACTIVE);
1948	if (sc->udbs_res == NULL) {
1949		device_printf(sc->dev, "cannot map doorbell BAR.\n");
1950		return (ENXIO);
1951	}
1952	sc->udbs_base = rman_get_virtual(sc->udbs_res);
1953
1954	if (chip_id(sc) >= CHELSIO_T5) {
1955		setbit(&sc->doorbells, DOORBELL_UDB);
1956#if defined(__i386__) || defined(__amd64__)
1957		if (t5_write_combine) {
1958			int rc, mode;
1959
1960			/*
1961			 * Enable write combining on BAR2.  This is the
1962			 * userspace doorbell BAR and is split into 128B
1963			 * (UDBS_SEG_SIZE) doorbell regions, each associated
1964			 * with an egress queue.  The first 64B has the doorbell
1965			 * and the second 64B can be used to submit a tx work
1966			 * request with an implicit doorbell.
1967			 */
1968
1969			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
1970			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
1971			if (rc == 0) {
1972				clrbit(&sc->doorbells, DOORBELL_UDB);
1973				setbit(&sc->doorbells, DOORBELL_WCWR);
1974				setbit(&sc->doorbells, DOORBELL_UDBWC);
1975			} else {
1976				device_printf(sc->dev,
1977				    "couldn't enable write combining: %d\n",
1978				    rc);
1979			}
1980
1981			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
1982			t4_write_reg(sc, A_SGE_STAT_CFG,
1983			    V_STATSOURCE_T5(7) | mode);
1984		}
1985#endif
1986	}
1987
1988	return (0);
1989}
1990
1991struct memwin_init {
1992	uint32_t base;
1993	uint32_t aperture;
1994};
1995
1996static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
1997	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
1998	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
1999	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
2000};
2001
2002static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
2003	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
2004	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
2005	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
2006};
2007
2008static void
2009setup_memwin(struct adapter *sc)
2010{
2011	const struct memwin_init *mw_init;
2012	struct memwin *mw;
2013	int i;
2014	uint32_t bar0;
2015
2016	if (is_t4(sc)) {
2017		/*
2018		 * Read low 32b of bar0 indirectly via the hardware backdoor
2019		 * mechanism.  Works from within PCI passthrough environments
2020		 * too, where rman_get_start() can return a different value.  We
2021		 * need to program the T4 memory window decoders with the actual
2022		 * addresses that will be coming across the PCIe link.
2023		 */
2024		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
2025		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
2026
2027		mw_init = &t4_memwin[0];
2028	} else {
2029		/* T5+ use the relative offset inside the PCIe BAR */
2030		bar0 = 0;
2031
2032		mw_init = &t5_memwin[0];
2033	}
2034
2035	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
2036		rw_init(&mw->mw_lock, "memory window access");
2037		mw->mw_base = mw_init->base;
2038		mw->mw_aperture = mw_init->aperture;
2039		mw->mw_curpos = 0;
2040		t4_write_reg(sc,
2041		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
2042		    (mw->mw_base + bar0) | V_BIR(0) |
2043		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
2044		rw_wlock(&mw->mw_lock);
2045		position_memwin(sc, i, 0);
2046		rw_wunlock(&mw->mw_lock);
2047	}
2048
2049	/* flush */
2050	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
2051}
2052
2053/*
2054 * Positions the memory window at the given address in the card's address space.
2055 * There are some alignment requirements and the actual position may be at an
2056 * address prior to the requested address.  mw->mw_curpos always has the actual
2057 * position of the window.
2058 */
2059static void
2060position_memwin(struct adapter *sc, int idx, uint32_t addr)
2061{
2062	struct memwin *mw;
2063	uint32_t pf;
2064	uint32_t reg;
2065
2066	MPASS(idx >= 0 && idx < NUM_MEMWIN);
2067	mw = &sc->memwin[idx];
2068	rw_assert(&mw->mw_lock, RA_WLOCKED);
2069
2070	if (is_t4(sc)) {
2071		pf = 0;
2072		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
2073	} else {
2074		pf = V_PFNUM(sc->pf);
2075		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
2076	}
2077	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
2078	t4_write_reg(sc, reg, mw->mw_curpos | pf);
2079	t4_read_reg(sc, reg);	/* flush */
2080}
2081
2082static int
2083rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2084    int len, int rw)
2085{
2086	struct memwin *mw;
2087	uint32_t mw_end, v;
2088
2089	MPASS(idx >= 0 && idx < NUM_MEMWIN);
2090
2091	/* Memory can only be accessed in naturally aligned 4 byte units */
2092	if (addr & 3 || len & 3 || len <= 0)
2093		return (EINVAL);
2094
2095	mw = &sc->memwin[idx];
2096	while (len > 0) {
2097		rw_rlock(&mw->mw_lock);
2098		mw_end = mw->mw_curpos + mw->mw_aperture;
2099		if (addr >= mw_end || addr < mw->mw_curpos) {
2100			/* Will need to reposition the window */
2101			if (!rw_try_upgrade(&mw->mw_lock)) {
2102				rw_runlock(&mw->mw_lock);
2103				rw_wlock(&mw->mw_lock);
2104			}
2105			rw_assert(&mw->mw_lock, RA_WLOCKED);
2106			position_memwin(sc, idx, addr);
2107			rw_downgrade(&mw->mw_lock);
2108			mw_end = mw->mw_curpos + mw->mw_aperture;
2109		}
2110		rw_assert(&mw->mw_lock, RA_RLOCKED);
2111		while (addr < mw_end && len > 0) {
2112			if (rw == 0) {
2113				v = t4_read_reg(sc, mw->mw_base + addr -
2114				    mw->mw_curpos);
2115				*val++ = le32toh(v);
2116			} else {
2117				v = *val++;
2118				t4_write_reg(sc, mw->mw_base + addr -
2119				    mw->mw_curpos, htole32(v));;
2120			}
2121			addr += 4;
2122			len -= 4;
2123		}
2124		rw_runlock(&mw->mw_lock);
2125	}
2126
2127	return (0);
2128}
2129
2130static inline int
2131read_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2132    int len)
2133{
2134
2135	return (rw_via_memwin(sc, idx, addr, val, len, 0));
2136}
2137
2138static inline int
2139write_via_memwin(struct adapter *sc, int idx, uint32_t addr,
2140    const uint32_t *val, int len)
2141{
2142
2143	return (rw_via_memwin(sc, idx, addr, (void *)(uintptr_t)val, len, 1));
2144}
2145
2146static int
2147t4_range_cmp(const void *a, const void *b)
2148{
2149	return ((const struct t4_range *)a)->start -
2150	       ((const struct t4_range *)b)->start;
2151}
2152
2153/*
2154 * Verify that the memory range specified by the addr/len pair is valid within
2155 * the card's address space.
2156 */
2157static int
2158validate_mem_range(struct adapter *sc, uint32_t addr, int len)
2159{
2160	struct t4_range mem_ranges[4], *r, *next;
2161	uint32_t em, addr_len;
2162	int i, n, remaining;
2163
2164	/* Memory can only be accessed in naturally aligned 4 byte units */
2165	if (addr & 3 || len & 3 || len <= 0)
2166		return (EINVAL);
2167
2168	/* Enabled memories */
2169	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2170
2171	r = &mem_ranges[0];
2172	n = 0;
2173	bzero(r, sizeof(mem_ranges));
2174	if (em & F_EDRAM0_ENABLE) {
2175		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2176		r->size = G_EDRAM0_SIZE(addr_len) << 20;
2177		if (r->size > 0) {
2178			r->start = G_EDRAM0_BASE(addr_len) << 20;
2179			if (addr >= r->start &&
2180			    addr + len <= r->start + r->size)
2181				return (0);
2182			r++;
2183			n++;
2184		}
2185	}
2186	if (em & F_EDRAM1_ENABLE) {
2187		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2188		r->size = G_EDRAM1_SIZE(addr_len) << 20;
2189		if (r->size > 0) {
2190			r->start = G_EDRAM1_BASE(addr_len) << 20;
2191			if (addr >= r->start &&
2192			    addr + len <= r->start + r->size)
2193				return (0);
2194			r++;
2195			n++;
2196		}
2197	}
2198	if (em & F_EXT_MEM_ENABLE) {
2199		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2200		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
2201		if (r->size > 0) {
2202			r->start = G_EXT_MEM_BASE(addr_len) << 20;
2203			if (addr >= r->start &&
2204			    addr + len <= r->start + r->size)
2205				return (0);
2206			r++;
2207			n++;
2208		}
2209	}
2210	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
2211		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2212		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
2213		if (r->size > 0) {
2214			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
2215			if (addr >= r->start &&
2216			    addr + len <= r->start + r->size)
2217				return (0);
2218			r++;
2219			n++;
2220		}
2221	}
2222	MPASS(n <= nitems(mem_ranges));
2223
2224	if (n > 1) {
2225		/* Sort and merge the ranges. */
2226		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
2227
2228		/* Start from index 0 and examine the next n - 1 entries. */
2229		r = &mem_ranges[0];
2230		for (remaining = n - 1; remaining > 0; remaining--, r++) {
2231
2232			MPASS(r->size > 0);	/* r is a valid entry. */
2233			next = r + 1;
2234			MPASS(next->size > 0);	/* and so is the next one. */
2235
2236			while (r->start + r->size >= next->start) {
2237				/* Merge the next one into the current entry. */
2238				r->size = max(r->start + r->size,
2239				    next->start + next->size) - r->start;
2240				n--;	/* One fewer entry in total. */
2241				if (--remaining == 0)
2242					goto done;	/* short circuit */
2243				next++;
2244			}
2245			if (next != r + 1) {
2246				/*
2247				 * Some entries were merged into r and next
2248				 * points to the first valid entry that couldn't
2249				 * be merged.
2250				 */
2251				MPASS(next->size > 0);	/* must be valid */
2252				memcpy(r + 1, next, remaining * sizeof(*r));
2253#ifdef INVARIANTS
2254				/*
2255				 * This so that the foo->size assertion in the
2256				 * next iteration of the loop do the right
2257				 * thing for entries that were pulled up and are
2258				 * no longer valid.
2259				 */
2260				MPASS(n < nitems(mem_ranges));
2261				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
2262				    sizeof(struct t4_range));
2263#endif
2264			}
2265		}
2266done:
2267		/* Done merging the ranges. */
2268		MPASS(n > 0);
2269		r = &mem_ranges[0];
2270		for (i = 0; i < n; i++, r++) {
2271			if (addr >= r->start &&
2272			    addr + len <= r->start + r->size)
2273				return (0);
2274		}
2275	}
2276
2277	return (EFAULT);
2278}
2279
2280static int
2281fwmtype_to_hwmtype(int mtype)
2282{
2283
2284	switch (mtype) {
2285	case FW_MEMTYPE_EDC0:
2286		return (MEM_EDC0);
2287	case FW_MEMTYPE_EDC1:
2288		return (MEM_EDC1);
2289	case FW_MEMTYPE_EXTMEM:
2290		return (MEM_MC0);
2291	case FW_MEMTYPE_EXTMEM1:
2292		return (MEM_MC1);
2293	default:
2294		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
2295	}
2296}
2297
2298/*
2299 * Verify that the memory range specified by the memtype/offset/len pair is
2300 * valid and lies entirely within the memtype specified.  The global address of
2301 * the start of the range is returned in addr.
2302 */
2303static int
2304validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, int len,
2305    uint32_t *addr)
2306{
2307	uint32_t em, addr_len, maddr;
2308
2309	/* Memory can only be accessed in naturally aligned 4 byte units */
2310	if (off & 3 || len & 3 || len == 0)
2311		return (EINVAL);
2312
2313	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2314	switch (fwmtype_to_hwmtype(mtype)) {
2315	case MEM_EDC0:
2316		if (!(em & F_EDRAM0_ENABLE))
2317			return (EINVAL);
2318		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2319		maddr = G_EDRAM0_BASE(addr_len) << 20;
2320		break;
2321	case MEM_EDC1:
2322		if (!(em & F_EDRAM1_ENABLE))
2323			return (EINVAL);
2324		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2325		maddr = G_EDRAM1_BASE(addr_len) << 20;
2326		break;
2327	case MEM_MC:
2328		if (!(em & F_EXT_MEM_ENABLE))
2329			return (EINVAL);
2330		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2331		maddr = G_EXT_MEM_BASE(addr_len) << 20;
2332		break;
2333	case MEM_MC1:
2334		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
2335			return (EINVAL);
2336		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2337		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
2338		break;
2339	default:
2340		return (EINVAL);
2341	}
2342
2343	*addr = maddr + off;	/* global address */
2344	return (validate_mem_range(sc, *addr, len));
2345}
2346
2347static int
2348fixup_devlog_params(struct adapter *sc)
2349{
2350	struct devlog_params *dparams = &sc->params.devlog;
2351	int rc;
2352
2353	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
2354	    dparams->size, &dparams->addr);
2355
2356	return (rc);
2357}
2358
2359static int
2360cfg_itype_and_nqueues(struct adapter *sc, int n10g, int n1g, int num_vis,
2361    struct intrs_and_queues *iaq)
2362{
2363	int rc, itype, navail, nrxq10g, nrxq1g, n;
2364	int nofldrxq10g = 0, nofldrxq1g = 0;
2365
2366	bzero(iaq, sizeof(*iaq));
2367
2368	iaq->ntxq10g = t4_ntxq10g;
2369	iaq->ntxq1g = t4_ntxq1g;
2370	iaq->ntxq_vi = t4_ntxq_vi;
2371	iaq->nrxq10g = nrxq10g = t4_nrxq10g;
2372	iaq->nrxq1g = nrxq1g = t4_nrxq1g;
2373	iaq->nrxq_vi = t4_nrxq_vi;
2374	iaq->rsrv_noflowq = t4_rsrv_noflowq;
2375#ifdef TCP_OFFLOAD
2376	if (is_offload(sc)) {
2377		iaq->nofldtxq10g = t4_nofldtxq10g;
2378		iaq->nofldtxq1g = t4_nofldtxq1g;
2379		iaq->nofldtxq_vi = t4_nofldtxq_vi;
2380		iaq->nofldrxq10g = nofldrxq10g = t4_nofldrxq10g;
2381		iaq->nofldrxq1g = nofldrxq1g = t4_nofldrxq1g;
2382		iaq->nofldrxq_vi = t4_nofldrxq_vi;
2383	}
2384#endif
2385#ifdef DEV_NETMAP
2386	iaq->nnmtxq_vi = t4_nnmtxq_vi;
2387	iaq->nnmrxq_vi = t4_nnmrxq_vi;
2388#endif
2389
2390	for (itype = INTR_MSIX; itype; itype >>= 1) {
2391
2392		if ((itype & t4_intr_types) == 0)
2393			continue;	/* not allowed */
2394
2395		if (itype == INTR_MSIX)
2396			navail = pci_msix_count(sc->dev);
2397		else if (itype == INTR_MSI)
2398			navail = pci_msi_count(sc->dev);
2399		else
2400			navail = 1;
2401restart:
2402		if (navail == 0)
2403			continue;
2404
2405		iaq->intr_type = itype;
2406		iaq->intr_flags_10g = 0;
2407		iaq->intr_flags_1g = 0;
2408
2409		/*
2410		 * Best option: an interrupt vector for errors, one for the
2411		 * firmware event queue, and one for every rxq (NIC and TOE) of
2412		 * every VI.  The VIs that support netmap use the same
2413		 * interrupts for the NIC rx queues and the netmap rx queues
2414		 * because only one set of queues is active at a time.
2415		 */
2416		iaq->nirq = T4_EXTRA_INTR;
2417		iaq->nirq += n10g * (nrxq10g + nofldrxq10g);
2418		iaq->nirq += n1g * (nrxq1g + nofldrxq1g);
2419		iaq->nirq += (n10g + n1g) * (num_vis - 1) *
2420		    max(iaq->nrxq_vi, iaq->nnmrxq_vi);	/* See comment above. */
2421		iaq->nirq += (n10g + n1g) * (num_vis - 1) * iaq->nofldrxq_vi;
2422		if (iaq->nirq <= navail &&
2423		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
2424			iaq->intr_flags_10g = INTR_ALL;
2425			iaq->intr_flags_1g = INTR_ALL;
2426			goto allocate;
2427		}
2428
2429		/* Disable the VIs (and netmap) if there aren't enough intrs */
2430		if (num_vis > 1) {
2431			device_printf(sc->dev, "virtual interfaces disabled "
2432			    "because num_vis=%u with current settings "
2433			    "(nrxq10g=%u, nrxq1g=%u, nofldrxq10g=%u, "
2434			    "nofldrxq1g=%u, nrxq_vi=%u nofldrxq_vi=%u, "
2435			    "nnmrxq_vi=%u) would need %u interrupts but "
2436			    "only %u are available.\n", num_vis, nrxq10g,
2437			    nrxq1g, nofldrxq10g, nofldrxq1g, iaq->nrxq_vi,
2438			    iaq->nofldrxq_vi, iaq->nnmrxq_vi, iaq->nirq,
2439			    navail);
2440			num_vis = 1;
2441			iaq->ntxq_vi = iaq->nrxq_vi = 0;
2442			iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
2443			iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
2444			goto restart;
2445		}
2446
2447		/*
2448		 * Second best option: a vector for errors, one for the firmware
2449		 * event queue, and vectors for either all the NIC rx queues or
2450		 * all the TOE rx queues.  The queues that don't get vectors
2451		 * will forward their interrupts to those that do.
2452		 */
2453		iaq->nirq = T4_EXTRA_INTR;
2454		if (nrxq10g >= nofldrxq10g) {
2455			iaq->intr_flags_10g = INTR_RXQ;
2456			iaq->nirq += n10g * nrxq10g;
2457		} else {
2458			iaq->intr_flags_10g = INTR_OFLD_RXQ;
2459			iaq->nirq += n10g * nofldrxq10g;
2460		}
2461		if (nrxq1g >= nofldrxq1g) {
2462			iaq->intr_flags_1g = INTR_RXQ;
2463			iaq->nirq += n1g * nrxq1g;
2464		} else {
2465			iaq->intr_flags_1g = INTR_OFLD_RXQ;
2466			iaq->nirq += n1g * nofldrxq1g;
2467		}
2468		if (iaq->nirq <= navail &&
2469		    (itype != INTR_MSI || powerof2(iaq->nirq)))
2470			goto allocate;
2471
2472		/*
2473		 * Next best option: an interrupt vector for errors, one for the
2474		 * firmware event queue, and at least one per main-VI.  At this
2475		 * point we know we'll have to downsize nrxq and/or nofldrxq to
2476		 * fit what's available to us.
2477		 */
2478		iaq->nirq = T4_EXTRA_INTR;
2479		iaq->nirq += n10g + n1g;
2480		if (iaq->nirq <= navail) {
2481			int leftover = navail - iaq->nirq;
2482
2483			if (n10g > 0) {
2484				int target = max(nrxq10g, nofldrxq10g);
2485
2486				iaq->intr_flags_10g = nrxq10g >= nofldrxq10g ?
2487				    INTR_RXQ : INTR_OFLD_RXQ;
2488
2489				n = 1;
2490				while (n < target && leftover >= n10g) {
2491					leftover -= n10g;
2492					iaq->nirq += n10g;
2493					n++;
2494				}
2495				iaq->nrxq10g = min(n, nrxq10g);
2496#ifdef TCP_OFFLOAD
2497				iaq->nofldrxq10g = min(n, nofldrxq10g);
2498#endif
2499			}
2500
2501			if (n1g > 0) {
2502				int target = max(nrxq1g, nofldrxq1g);
2503
2504				iaq->intr_flags_1g = nrxq1g >= nofldrxq1g ?
2505				    INTR_RXQ : INTR_OFLD_RXQ;
2506
2507				n = 1;
2508				while (n < target && leftover >= n1g) {
2509					leftover -= n1g;
2510					iaq->nirq += n1g;
2511					n++;
2512				}
2513				iaq->nrxq1g = min(n, nrxq1g);
2514#ifdef TCP_OFFLOAD
2515				iaq->nofldrxq1g = min(n, nofldrxq1g);
2516#endif
2517			}
2518
2519			if (itype != INTR_MSI || powerof2(iaq->nirq))
2520				goto allocate;
2521		}
2522
2523		/*
2524		 * Least desirable option: one interrupt vector for everything.
2525		 */
2526		iaq->nirq = iaq->nrxq10g = iaq->nrxq1g = 1;
2527		iaq->intr_flags_10g = iaq->intr_flags_1g = 0;
2528#ifdef TCP_OFFLOAD
2529		if (is_offload(sc))
2530			iaq->nofldrxq10g = iaq->nofldrxq1g = 1;
2531#endif
2532allocate:
2533		navail = iaq->nirq;
2534		rc = 0;
2535		if (itype == INTR_MSIX)
2536			rc = pci_alloc_msix(sc->dev, &navail);
2537		else if (itype == INTR_MSI)
2538			rc = pci_alloc_msi(sc->dev, &navail);
2539
2540		if (rc == 0) {
2541			if (navail == iaq->nirq)
2542				return (0);
2543
2544			/*
2545			 * Didn't get the number requested.  Use whatever number
2546			 * the kernel is willing to allocate (it's in navail).
2547			 */
2548			device_printf(sc->dev, "fewer vectors than requested, "
2549			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
2550			    itype, iaq->nirq, navail);
2551			pci_release_msi(sc->dev);
2552			goto restart;
2553		}
2554
2555		device_printf(sc->dev,
2556		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
2557		    itype, rc, iaq->nirq, navail);
2558	}
2559
2560	device_printf(sc->dev,
2561	    "failed to find a usable interrupt type.  "
2562	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
2563	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
2564
2565	return (ENXIO);
2566}
2567
2568#define FW_VERSION(chip) ( \
2569    V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
2570    V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
2571    V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
2572    V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
2573#define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
2574
2575struct fw_info {
2576	uint8_t chip;
2577	char *kld_name;
2578	char *fw_mod_name;
2579	struct fw_hdr fw_hdr;	/* XXX: waste of space, need a sparse struct */
2580} fw_info[] = {
2581	{
2582		.chip = CHELSIO_T4,
2583		.kld_name = "t4fw_cfg",
2584		.fw_mod_name = "t4fw",
2585		.fw_hdr = {
2586			.chip = FW_HDR_CHIP_T4,
2587			.fw_ver = htobe32_const(FW_VERSION(T4)),
2588			.intfver_nic = FW_INTFVER(T4, NIC),
2589			.intfver_vnic = FW_INTFVER(T4, VNIC),
2590			.intfver_ofld = FW_INTFVER(T4, OFLD),
2591			.intfver_ri = FW_INTFVER(T4, RI),
2592			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
2593			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
2594			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
2595			.intfver_fcoe = FW_INTFVER(T4, FCOE),
2596		},
2597	}, {
2598		.chip = CHELSIO_T5,
2599		.kld_name = "t5fw_cfg",
2600		.fw_mod_name = "t5fw",
2601		.fw_hdr = {
2602			.chip = FW_HDR_CHIP_T5,
2603			.fw_ver = htobe32_const(FW_VERSION(T5)),
2604			.intfver_nic = FW_INTFVER(T5, NIC),
2605			.intfver_vnic = FW_INTFVER(T5, VNIC),
2606			.intfver_ofld = FW_INTFVER(T5, OFLD),
2607			.intfver_ri = FW_INTFVER(T5, RI),
2608			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
2609			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
2610			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
2611			.intfver_fcoe = FW_INTFVER(T5, FCOE),
2612		},
2613	}, {
2614		.chip = CHELSIO_T6,
2615		.kld_name = "t6fw_cfg",
2616		.fw_mod_name = "t6fw",
2617		.fw_hdr = {
2618			.chip = FW_HDR_CHIP_T6,
2619			.fw_ver = htobe32_const(FW_VERSION(T6)),
2620			.intfver_nic = FW_INTFVER(T6, NIC),
2621			.intfver_vnic = FW_INTFVER(T6, VNIC),
2622			.intfver_ofld = FW_INTFVER(T6, OFLD),
2623			.intfver_ri = FW_INTFVER(T6, RI),
2624			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
2625			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
2626			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
2627			.intfver_fcoe = FW_INTFVER(T6, FCOE),
2628		},
2629	}
2630};
2631
2632static struct fw_info *
2633find_fw_info(int chip)
2634{
2635	int i;
2636
2637	for (i = 0; i < nitems(fw_info); i++) {
2638		if (fw_info[i].chip == chip)
2639			return (&fw_info[i]);
2640	}
2641	return (NULL);
2642}
2643
2644/*
2645 * Is the given firmware API compatible with the one the driver was compiled
2646 * with?
2647 */
2648static int
2649fw_compatible(const struct fw_hdr *hdr1, const struct fw_hdr *hdr2)
2650{
2651
2652	/* short circuit if it's the exact same firmware version */
2653	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
2654		return (1);
2655
2656	/*
2657	 * XXX: Is this too conservative?  Perhaps I should limit this to the
2658	 * features that are supported in the driver.
2659	 */
2660#define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
2661	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
2662	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
2663	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
2664		return (1);
2665#undef SAME_INTF
2666
2667	return (0);
2668}
2669
2670/*
2671 * The firmware in the KLD is usable, but should it be installed?  This routine
2672 * explains itself in detail if it indicates the KLD firmware should be
2673 * installed.
2674 */
2675static int
2676should_install_kld_fw(struct adapter *sc, int card_fw_usable, int k, int c)
2677{
2678	const char *reason;
2679
2680	if (!card_fw_usable) {
2681		reason = "incompatible or unusable";
2682		goto install;
2683	}
2684
2685	if (k > c) {
2686		reason = "older than the version bundled with this driver";
2687		goto install;
2688	}
2689
2690	if (t4_fw_install == 2 && k != c) {
2691		reason = "different than the version bundled with this driver";
2692		goto install;
2693	}
2694
2695	return (0);
2696
2697install:
2698	if (t4_fw_install == 0) {
2699		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
2700		    "but the driver is prohibited from installing a different "
2701		    "firmware on the card.\n",
2702		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2703		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
2704
2705		return (0);
2706	}
2707
2708	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
2709	    "installing firmware %u.%u.%u.%u on card.\n",
2710	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2711	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
2712	    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
2713	    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k));
2714
2715	return (1);
2716}
2717/*
2718 * Establish contact with the firmware and determine if we are the master driver
2719 * or not, and whether we are responsible for chip initialization.
2720 */
2721static int
2722prep_firmware(struct adapter *sc)
2723{
2724	const struct firmware *fw = NULL, *default_cfg;
2725	int rc, pf, card_fw_usable, kld_fw_usable, need_fw_reset = 1;
2726	enum dev_state state;
2727	struct fw_info *fw_info;
2728	struct fw_hdr *card_fw;		/* fw on the card */
2729	const struct fw_hdr *kld_fw;	/* fw in the KLD */
2730	const struct fw_hdr *drv_fw;	/* fw header the driver was compiled
2731					   against */
2732
2733	/* Contact firmware. */
2734	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
2735	if (rc < 0 || state == DEV_STATE_ERR) {
2736		rc = -rc;
2737		device_printf(sc->dev,
2738		    "failed to connect to the firmware: %d, %d.\n", rc, state);
2739		return (rc);
2740	}
2741	pf = rc;
2742	if (pf == sc->mbox)
2743		sc->flags |= MASTER_PF;
2744	else if (state == DEV_STATE_UNINIT) {
2745		/*
2746		 * We didn't get to be the master so we definitely won't be
2747		 * configuring the chip.  It's a bug if someone else hasn't
2748		 * configured it already.
2749		 */
2750		device_printf(sc->dev, "couldn't be master(%d), "
2751		    "device not already initialized either(%d).\n", rc, state);
2752		return (EDOOFUS);
2753	}
2754
2755	/* This is the firmware whose headers the driver was compiled against */
2756	fw_info = find_fw_info(chip_id(sc));
2757	if (fw_info == NULL) {
2758		device_printf(sc->dev,
2759		    "unable to look up firmware information for chip %d.\n",
2760		    chip_id(sc));
2761		return (EINVAL);
2762	}
2763	drv_fw = &fw_info->fw_hdr;
2764
2765	/*
2766	 * The firmware KLD contains many modules.  The KLD name is also the
2767	 * name of the module that contains the default config file.
2768	 */
2769	default_cfg = firmware_get(fw_info->kld_name);
2770
2771	/* Read the header of the firmware on the card */
2772	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
2773	rc = -t4_read_flash(sc, FLASH_FW_START,
2774	    sizeof (*card_fw) / sizeof (uint32_t), (uint32_t *)card_fw, 1);
2775	if (rc == 0)
2776		card_fw_usable = fw_compatible(drv_fw, (const void*)card_fw);
2777	else {
2778		device_printf(sc->dev,
2779		    "Unable to read card's firmware header: %d\n", rc);
2780		card_fw_usable = 0;
2781	}
2782
2783	/* This is the firmware in the KLD */
2784	fw = firmware_get(fw_info->fw_mod_name);
2785	if (fw != NULL) {
2786		kld_fw = (const void *)fw->data;
2787		kld_fw_usable = fw_compatible(drv_fw, kld_fw);
2788	} else {
2789		kld_fw = NULL;
2790		kld_fw_usable = 0;
2791	}
2792
2793	if (card_fw_usable && card_fw->fw_ver == drv_fw->fw_ver &&
2794	    (!kld_fw_usable || kld_fw->fw_ver == drv_fw->fw_ver)) {
2795		/*
2796		 * Common case: the firmware on the card is an exact match and
2797		 * the KLD is an exact match too, or the KLD is
2798		 * absent/incompatible.  Note that t4_fw_install = 2 is ignored
2799		 * here -- use cxgbetool loadfw if you want to reinstall the
2800		 * same firmware as the one on the card.
2801		 */
2802	} else if (kld_fw_usable && state == DEV_STATE_UNINIT &&
2803	    should_install_kld_fw(sc, card_fw_usable, be32toh(kld_fw->fw_ver),
2804	    be32toh(card_fw->fw_ver))) {
2805
2806		rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
2807		if (rc != 0) {
2808			device_printf(sc->dev,
2809			    "failed to install firmware: %d\n", rc);
2810			goto done;
2811		}
2812
2813		/* Installed successfully, update the cached header too. */
2814		memcpy(card_fw, kld_fw, sizeof(*card_fw));
2815		card_fw_usable = 1;
2816		need_fw_reset = 0;	/* already reset as part of load_fw */
2817	}
2818
2819	if (!card_fw_usable) {
2820		uint32_t d, c, k;
2821
2822		d = ntohl(drv_fw->fw_ver);
2823		c = ntohl(card_fw->fw_ver);
2824		k = kld_fw ? ntohl(kld_fw->fw_ver) : 0;
2825
2826		device_printf(sc->dev, "Cannot find a usable firmware: "
2827		    "fw_install %d, chip state %d, "
2828		    "driver compiled with %d.%d.%d.%d, "
2829		    "card has %d.%d.%d.%d, KLD has %d.%d.%d.%d\n",
2830		    t4_fw_install, state,
2831		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
2832		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d),
2833		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2834		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c),
2835		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
2836		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k));
2837		rc = EINVAL;
2838		goto done;
2839	}
2840
2841	/* Reset device */
2842	if (need_fw_reset &&
2843	    (rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST)) != 0) {
2844		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
2845		if (rc != ETIMEDOUT && rc != EIO)
2846			t4_fw_bye(sc, sc->mbox);
2847		goto done;
2848	}
2849	sc->flags |= FW_OK;
2850
2851	rc = get_params__pre_init(sc);
2852	if (rc != 0)
2853		goto done; /* error message displayed already */
2854
2855	/* Partition adapter resources as specified in the config file. */
2856	if (state == DEV_STATE_UNINIT) {
2857
2858		KASSERT(sc->flags & MASTER_PF,
2859		    ("%s: trying to change chip settings when not master.",
2860		    __func__));
2861
2862		rc = partition_resources(sc, default_cfg, fw_info->kld_name);
2863		if (rc != 0)
2864			goto done;	/* error message displayed already */
2865
2866		t4_tweak_chip_settings(sc);
2867
2868		/* get basic stuff going */
2869		rc = -t4_fw_initialize(sc, sc->mbox);
2870		if (rc != 0) {
2871			device_printf(sc->dev, "fw init failed: %d.\n", rc);
2872			goto done;
2873		}
2874	} else {
2875		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", pf);
2876		sc->cfcsum = 0;
2877	}
2878
2879done:
2880	free(card_fw, M_CXGBE);
2881	if (fw != NULL)
2882		firmware_put(fw, FIRMWARE_UNLOAD);
2883	if (default_cfg != NULL)
2884		firmware_put(default_cfg, FIRMWARE_UNLOAD);
2885
2886	return (rc);
2887}
2888
2889#define FW_PARAM_DEV(param) \
2890	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
2891	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
2892#define FW_PARAM_PFVF(param) \
2893	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
2894	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
2895
2896/*
2897 * Partition chip resources for use between various PFs, VFs, etc.
2898 */
2899static int
2900partition_resources(struct adapter *sc, const struct firmware *default_cfg,
2901    const char *name_prefix)
2902{
2903	const struct firmware *cfg = NULL;
2904	int rc = 0;
2905	struct fw_caps_config_cmd caps;
2906	uint32_t mtype, moff, finicsum, cfcsum;
2907
2908	/*
2909	 * Figure out what configuration file to use.  Pick the default config
2910	 * file for the card if the user hasn't specified one explicitly.
2911	 */
2912	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", t4_cfg_file);
2913	if (strncmp(t4_cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
2914		/* Card specific overrides go here. */
2915		if (pci_get_device(sc->dev) == 0x440a)
2916			snprintf(sc->cfg_file, sizeof(sc->cfg_file), UWIRE_CF);
2917		if (is_fpga(sc))
2918			snprintf(sc->cfg_file, sizeof(sc->cfg_file), FPGA_CF);
2919	}
2920
2921	/*
2922	 * We need to load another module if the profile is anything except
2923	 * "default" or "flash".
2924	 */
2925	if (strncmp(sc->cfg_file, DEFAULT_CF, sizeof(sc->cfg_file)) != 0 &&
2926	    strncmp(sc->cfg_file, FLASH_CF, sizeof(sc->cfg_file)) != 0) {
2927		char s[32];
2928
2929		snprintf(s, sizeof(s), "%s_%s", name_prefix, sc->cfg_file);
2930		cfg = firmware_get(s);
2931		if (cfg == NULL) {
2932			if (default_cfg != NULL) {
2933				device_printf(sc->dev,
2934				    "unable to load module \"%s\" for "
2935				    "configuration profile \"%s\", will use "
2936				    "the default config file instead.\n",
2937				    s, sc->cfg_file);
2938				snprintf(sc->cfg_file, sizeof(sc->cfg_file),
2939				    "%s", DEFAULT_CF);
2940			} else {
2941				device_printf(sc->dev,
2942				    "unable to load module \"%s\" for "
2943				    "configuration profile \"%s\", will use "
2944				    "the config file on the card's flash "
2945				    "instead.\n", s, sc->cfg_file);
2946				snprintf(sc->cfg_file, sizeof(sc->cfg_file),
2947				    "%s", FLASH_CF);
2948			}
2949		}
2950	}
2951
2952	if (strncmp(sc->cfg_file, DEFAULT_CF, sizeof(sc->cfg_file)) == 0 &&
2953	    default_cfg == NULL) {
2954		device_printf(sc->dev,
2955		    "default config file not available, will use the config "
2956		    "file on the card's flash instead.\n");
2957		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", FLASH_CF);
2958	}
2959
2960	if (strncmp(sc->cfg_file, FLASH_CF, sizeof(sc->cfg_file)) != 0) {
2961		u_int cflen;
2962		const uint32_t *cfdata;
2963		uint32_t param, val, addr;
2964
2965		KASSERT(cfg != NULL || default_cfg != NULL,
2966		    ("%s: no config to upload", __func__));
2967
2968		/*
2969		 * Ask the firmware where it wants us to upload the config file.
2970		 */
2971		param = FW_PARAM_DEV(CF);
2972		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2973		if (rc != 0) {
2974			/* No support for config file?  Shouldn't happen. */
2975			device_printf(sc->dev,
2976			    "failed to query config file location: %d.\n", rc);
2977			goto done;
2978		}
2979		mtype = G_FW_PARAMS_PARAM_Y(val);
2980		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
2981
2982		/*
2983		 * XXX: sheer laziness.  We deliberately added 4 bytes of
2984		 * useless stuffing/comments at the end of the config file so
2985		 * it's ok to simply throw away the last remaining bytes when
2986		 * the config file is not an exact multiple of 4.  This also
2987		 * helps with the validate_mt_off_len check.
2988		 */
2989		if (cfg != NULL) {
2990			cflen = cfg->datasize & ~3;
2991			cfdata = cfg->data;
2992		} else {
2993			cflen = default_cfg->datasize & ~3;
2994			cfdata = default_cfg->data;
2995		}
2996
2997		if (cflen > FLASH_CFG_MAX_SIZE) {
2998			device_printf(sc->dev,
2999			    "config file too long (%d, max allowed is %d).  "
3000			    "Will try to use the config on the card, if any.\n",
3001			    cflen, FLASH_CFG_MAX_SIZE);
3002			goto use_config_on_flash;
3003		}
3004
3005		rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
3006		if (rc != 0) {
3007			device_printf(sc->dev,
3008			    "%s: addr (%d/0x%x) or len %d is not valid: %d.  "
3009			    "Will try to use the config on the card, if any.\n",
3010			    __func__, mtype, moff, cflen, rc);
3011			goto use_config_on_flash;
3012		}
3013		write_via_memwin(sc, 2, addr, cfdata, cflen);
3014	} else {
3015use_config_on_flash:
3016		mtype = FW_MEMTYPE_FLASH;
3017		moff = t4_flash_cfg_addr(sc);
3018	}
3019
3020	bzero(&caps, sizeof(caps));
3021	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3022	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
3023	caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3024	    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3025	    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) | FW_LEN16(caps));
3026	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3027	if (rc != 0) {
3028		device_printf(sc->dev,
3029		    "failed to pre-process config file: %d "
3030		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
3031		goto done;
3032	}
3033
3034	finicsum = be32toh(caps.finicsum);
3035	cfcsum = be32toh(caps.cfcsum);
3036	if (finicsum != cfcsum) {
3037		device_printf(sc->dev,
3038		    "WARNING: config file checksum mismatch: %08x %08x\n",
3039		    finicsum, cfcsum);
3040	}
3041	sc->cfcsum = cfcsum;
3042
3043#define LIMIT_CAPS(x) do { \
3044	caps.x &= htobe16(t4_##x##_allowed); \
3045} while (0)
3046
3047	/*
3048	 * Let the firmware know what features will (not) be used so it can tune
3049	 * things accordingly.
3050	 */
3051	LIMIT_CAPS(nbmcaps);
3052	LIMIT_CAPS(linkcaps);
3053	LIMIT_CAPS(switchcaps);
3054	LIMIT_CAPS(niccaps);
3055	LIMIT_CAPS(toecaps);
3056	LIMIT_CAPS(rdmacaps);
3057	LIMIT_CAPS(cryptocaps);
3058	LIMIT_CAPS(iscsicaps);
3059	LIMIT_CAPS(fcoecaps);
3060#undef LIMIT_CAPS
3061
3062	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3063	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
3064	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3065	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
3066	if (rc != 0) {
3067		device_printf(sc->dev,
3068		    "failed to process config file: %d.\n", rc);
3069	}
3070done:
3071	if (cfg != NULL)
3072		firmware_put(cfg, FIRMWARE_UNLOAD);
3073	return (rc);
3074}
3075
3076/*
3077 * Retrieve parameters that are needed (or nice to have) very early.
3078 */
3079static int
3080get_params__pre_init(struct adapter *sc)
3081{
3082	int rc;
3083	uint32_t param[2], val[2];
3084
3085	t4_get_version_info(sc);
3086
3087	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
3088	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
3089	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
3090	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
3091	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
3092
3093	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
3094	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
3095	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
3096	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
3097	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
3098
3099	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
3100	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
3101	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
3102	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
3103	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
3104
3105	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
3106	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
3107	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
3108	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
3109	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
3110
3111	param[0] = FW_PARAM_DEV(PORTVEC);
3112	param[1] = FW_PARAM_DEV(CCLK);
3113	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3114	if (rc != 0) {
3115		device_printf(sc->dev,
3116		    "failed to query parameters (pre_init): %d.\n", rc);
3117		return (rc);
3118	}
3119
3120	sc->params.portvec = val[0];
3121	sc->params.nports = bitcount32(val[0]);
3122	sc->params.vpd.cclk = val[1];
3123
3124	/* Read device log parameters. */
3125	rc = -t4_init_devlog_params(sc, 1);
3126	if (rc == 0)
3127		fixup_devlog_params(sc);
3128	else {
3129		device_printf(sc->dev,
3130		    "failed to get devlog parameters: %d.\n", rc);
3131		rc = 0;	/* devlog isn't critical for device operation */
3132	}
3133
3134	return (rc);
3135}
3136
3137/*
3138 * Retrieve various parameters that are of interest to the driver.  The device
3139 * has been initialized by the firmware at this point.
3140 */
3141static int
3142get_params__post_init(struct adapter *sc)
3143{
3144	int rc;
3145	uint32_t param[7], val[7];
3146	struct fw_caps_config_cmd caps;
3147
3148	param[0] = FW_PARAM_PFVF(IQFLINT_START);
3149	param[1] = FW_PARAM_PFVF(EQ_START);
3150	param[2] = FW_PARAM_PFVF(FILTER_START);
3151	param[3] = FW_PARAM_PFVF(FILTER_END);
3152	param[4] = FW_PARAM_PFVF(L2T_START);
3153	param[5] = FW_PARAM_PFVF(L2T_END);
3154	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3155	if (rc != 0) {
3156		device_printf(sc->dev,
3157		    "failed to query parameters (post_init): %d.\n", rc);
3158		return (rc);
3159	}
3160
3161	sc->sge.iq_start = val[0];
3162	sc->sge.eq_start = val[1];
3163	sc->tids.ftid_base = val[2];
3164	sc->tids.nftids = val[3] - val[2] + 1;
3165	sc->params.ftid_min = val[2];
3166	sc->params.ftid_max = val[3];
3167	sc->vres.l2t.start = val[4];
3168	sc->vres.l2t.size = val[5] - val[4] + 1;
3169	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
3170	    ("%s: L2 table size (%u) larger than expected (%u)",
3171	    __func__, sc->vres.l2t.size, L2T_SIZE));
3172
3173	/* get capabilites */
3174	bzero(&caps, sizeof(caps));
3175	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3176	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
3177	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3178	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3179	if (rc != 0) {
3180		device_printf(sc->dev,
3181		    "failed to get card capabilities: %d.\n", rc);
3182		return (rc);
3183	}
3184
3185#define READ_CAPS(x) do { \
3186	sc->x = htobe16(caps.x); \
3187} while (0)
3188	READ_CAPS(nbmcaps);
3189	READ_CAPS(linkcaps);
3190	READ_CAPS(switchcaps);
3191	READ_CAPS(niccaps);
3192	READ_CAPS(toecaps);
3193	READ_CAPS(rdmacaps);
3194	READ_CAPS(cryptocaps);
3195	READ_CAPS(iscsicaps);
3196	READ_CAPS(fcoecaps);
3197
3198	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
3199		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
3200		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
3201		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3202		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
3203		if (rc != 0) {
3204			device_printf(sc->dev,
3205			    "failed to query NIC parameters: %d.\n", rc);
3206			return (rc);
3207		}
3208		sc->tids.etid_base = val[0];
3209		sc->params.etid_min = val[0];
3210		sc->tids.netids = val[1] - val[0] + 1;
3211		sc->params.netids = sc->tids.netids;
3212		sc->params.eo_wr_cred = val[2];
3213		sc->params.ethoffload = 1;
3214	}
3215
3216	if (sc->toecaps) {
3217		/* query offload-related parameters */
3218		param[0] = FW_PARAM_DEV(NTID);
3219		param[1] = FW_PARAM_PFVF(SERVER_START);
3220		param[2] = FW_PARAM_PFVF(SERVER_END);
3221		param[3] = FW_PARAM_PFVF(TDDP_START);
3222		param[4] = FW_PARAM_PFVF(TDDP_END);
3223		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3224		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3225		if (rc != 0) {
3226			device_printf(sc->dev,
3227			    "failed to query TOE parameters: %d.\n", rc);
3228			return (rc);
3229		}
3230		sc->tids.ntids = val[0];
3231		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
3232		sc->tids.stid_base = val[1];
3233		sc->tids.nstids = val[2] - val[1] + 1;
3234		sc->vres.ddp.start = val[3];
3235		sc->vres.ddp.size = val[4] - val[3] + 1;
3236		sc->params.ofldq_wr_cred = val[5];
3237		sc->params.offload = 1;
3238	}
3239	if (sc->rdmacaps) {
3240		param[0] = FW_PARAM_PFVF(STAG_START);
3241		param[1] = FW_PARAM_PFVF(STAG_END);
3242		param[2] = FW_PARAM_PFVF(RQ_START);
3243		param[3] = FW_PARAM_PFVF(RQ_END);
3244		param[4] = FW_PARAM_PFVF(PBL_START);
3245		param[5] = FW_PARAM_PFVF(PBL_END);
3246		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3247		if (rc != 0) {
3248			device_printf(sc->dev,
3249			    "failed to query RDMA parameters(1): %d.\n", rc);
3250			return (rc);
3251		}
3252		sc->vres.stag.start = val[0];
3253		sc->vres.stag.size = val[1] - val[0] + 1;
3254		sc->vres.rq.start = val[2];
3255		sc->vres.rq.size = val[3] - val[2] + 1;
3256		sc->vres.pbl.start = val[4];
3257		sc->vres.pbl.size = val[5] - val[4] + 1;
3258
3259		param[0] = FW_PARAM_PFVF(SQRQ_START);
3260		param[1] = FW_PARAM_PFVF(SQRQ_END);
3261		param[2] = FW_PARAM_PFVF(CQ_START);
3262		param[3] = FW_PARAM_PFVF(CQ_END);
3263		param[4] = FW_PARAM_PFVF(OCQ_START);
3264		param[5] = FW_PARAM_PFVF(OCQ_END);
3265		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3266		if (rc != 0) {
3267			device_printf(sc->dev,
3268			    "failed to query RDMA parameters(2): %d.\n", rc);
3269			return (rc);
3270		}
3271		sc->vres.qp.start = val[0];
3272		sc->vres.qp.size = val[1] - val[0] + 1;
3273		sc->vres.cq.start = val[2];
3274		sc->vres.cq.size = val[3] - val[2] + 1;
3275		sc->vres.ocq.start = val[4];
3276		sc->vres.ocq.size = val[5] - val[4] + 1;
3277	}
3278	if (sc->iscsicaps) {
3279		param[0] = FW_PARAM_PFVF(ISCSI_START);
3280		param[1] = FW_PARAM_PFVF(ISCSI_END);
3281		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3282		if (rc != 0) {
3283			device_printf(sc->dev,
3284			    "failed to query iSCSI parameters: %d.\n", rc);
3285			return (rc);
3286		}
3287		sc->vres.iscsi.start = val[0];
3288		sc->vres.iscsi.size = val[1] - val[0] + 1;
3289	}
3290
3291	t4_init_sge_params(sc);
3292
3293	/*
3294	 * We've got the params we wanted to query via the firmware.  Now grab
3295	 * some others directly from the chip.
3296	 */
3297	rc = t4_read_chip_settings(sc);
3298
3299	return (rc);
3300}
3301
3302static int
3303set_params__post_init(struct adapter *sc)
3304{
3305	uint32_t param, val;
3306
3307	/* ask for encapsulated CPLs */
3308	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
3309	val = 1;
3310	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3311
3312	return (0);
3313}
3314
3315#undef FW_PARAM_PFVF
3316#undef FW_PARAM_DEV
3317
3318static void
3319t4_set_desc(struct adapter *sc)
3320{
3321	char buf[128];
3322	struct adapter_params *p = &sc->params;
3323
3324	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
3325
3326	device_set_desc_copy(sc->dev, buf);
3327}
3328
3329static void
3330build_medialist(struct port_info *pi, struct ifmedia *media)
3331{
3332	int m;
3333
3334	PORT_LOCK(pi);
3335
3336	ifmedia_removeall(media);
3337
3338	m = IFM_ETHER | IFM_FDX;
3339
3340	switch(pi->port_type) {
3341	case FW_PORT_TYPE_BT_XFI:
3342	case FW_PORT_TYPE_BT_XAUI:
3343		ifmedia_add(media, m | IFM_10G_T, 0, NULL);
3344		/* fall through */
3345
3346	case FW_PORT_TYPE_BT_SGMII:
3347		ifmedia_add(media, m | IFM_1000_T, 0, NULL);
3348		ifmedia_add(media, m | IFM_100_TX, 0, NULL);
3349		ifmedia_add(media, IFM_ETHER | IFM_AUTO, 0, NULL);
3350		ifmedia_set(media, IFM_ETHER | IFM_AUTO);
3351		break;
3352
3353	case FW_PORT_TYPE_CX4:
3354		ifmedia_add(media, m | IFM_10G_CX4, 0, NULL);
3355		ifmedia_set(media, m | IFM_10G_CX4);
3356		break;
3357
3358	case FW_PORT_TYPE_QSFP_10G:
3359	case FW_PORT_TYPE_SFP:
3360	case FW_PORT_TYPE_FIBER_XFI:
3361	case FW_PORT_TYPE_FIBER_XAUI:
3362		switch (pi->mod_type) {
3363
3364		case FW_PORT_MOD_TYPE_LR:
3365			ifmedia_add(media, m | IFM_10G_LR, 0, NULL);
3366			ifmedia_set(media, m | IFM_10G_LR);
3367			break;
3368
3369		case FW_PORT_MOD_TYPE_SR:
3370			ifmedia_add(media, m | IFM_10G_SR, 0, NULL);
3371			ifmedia_set(media, m | IFM_10G_SR);
3372			break;
3373
3374		case FW_PORT_MOD_TYPE_LRM:
3375			ifmedia_add(media, m | IFM_10G_LRM, 0, NULL);
3376			ifmedia_set(media, m | IFM_10G_LRM);
3377			break;
3378
3379		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3380		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3381			ifmedia_add(media, m | IFM_10G_TWINAX, 0, NULL);
3382			ifmedia_set(media, m | IFM_10G_TWINAX);
3383			break;
3384
3385		case FW_PORT_MOD_TYPE_NONE:
3386			m &= ~IFM_FDX;
3387			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3388			ifmedia_set(media, m | IFM_NONE);
3389			break;
3390
3391		case FW_PORT_MOD_TYPE_NA:
3392		case FW_PORT_MOD_TYPE_ER:
3393		default:
3394			device_printf(pi->dev,
3395			    "unknown port_type (%d), mod_type (%d)\n",
3396			    pi->port_type, pi->mod_type);
3397			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3398			ifmedia_set(media, m | IFM_UNKNOWN);
3399			break;
3400		}
3401		break;
3402
3403	case FW_PORT_TYPE_CR_QSFP:
3404	case FW_PORT_TYPE_SFP28:
3405	case FW_PORT_TYPE_KR_SFP28:
3406		switch (pi->mod_type) {
3407
3408		case FW_PORT_MOD_TYPE_SR:
3409			ifmedia_add(media, m | IFM_25G_SR, 0, NULL);
3410			ifmedia_set(media, m | IFM_25G_SR);
3411			break;
3412
3413		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3414		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3415			ifmedia_add(media, m | IFM_25G_CR, 0, NULL);
3416			ifmedia_set(media, m | IFM_25G_CR);
3417			break;
3418
3419		case FW_PORT_MOD_TYPE_NONE:
3420			m &= ~IFM_FDX;
3421			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3422			ifmedia_set(media, m | IFM_NONE);
3423			break;
3424
3425		default:
3426			device_printf(pi->dev,
3427			    "unknown port_type (%d), mod_type (%d)\n",
3428			    pi->port_type, pi->mod_type);
3429			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3430			ifmedia_set(media, m | IFM_UNKNOWN);
3431			break;
3432		}
3433		break;
3434
3435	case FW_PORT_TYPE_QSFP:
3436		switch (pi->mod_type) {
3437
3438		case FW_PORT_MOD_TYPE_LR:
3439			ifmedia_add(media, m | IFM_40G_LR4, 0, NULL);
3440			ifmedia_set(media, m | IFM_40G_LR4);
3441			break;
3442
3443		case FW_PORT_MOD_TYPE_SR:
3444			ifmedia_add(media, m | IFM_40G_SR4, 0, NULL);
3445			ifmedia_set(media, m | IFM_40G_SR4);
3446			break;
3447
3448		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3449		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3450			ifmedia_add(media, m | IFM_40G_CR4, 0, NULL);
3451			ifmedia_set(media, m | IFM_40G_CR4);
3452			break;
3453
3454		case FW_PORT_MOD_TYPE_NONE:
3455			m &= ~IFM_FDX;
3456			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3457			ifmedia_set(media, m | IFM_NONE);
3458			break;
3459
3460		default:
3461			device_printf(pi->dev,
3462			    "unknown port_type (%d), mod_type (%d)\n",
3463			    pi->port_type, pi->mod_type);
3464			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3465			ifmedia_set(media, m | IFM_UNKNOWN);
3466			break;
3467		}
3468		break;
3469
3470	case FW_PORT_TYPE_KR4_100G:
3471	case FW_PORT_TYPE_CR4_QSFP:
3472		switch (pi->mod_type) {
3473
3474		case FW_PORT_MOD_TYPE_LR:
3475			ifmedia_add(media, m | IFM_100G_LR4, 0, NULL);
3476			ifmedia_set(media, m | IFM_100G_LR4);
3477			break;
3478
3479		case FW_PORT_MOD_TYPE_SR:
3480			ifmedia_add(media, m | IFM_100G_SR4, 0, NULL);
3481			ifmedia_set(media, m | IFM_100G_SR4);
3482			break;
3483
3484		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3485		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3486			ifmedia_add(media, m | IFM_100G_CR4, 0, NULL);
3487			ifmedia_set(media, m | IFM_100G_CR4);
3488			break;
3489
3490		case FW_PORT_MOD_TYPE_NONE:
3491			m &= ~IFM_FDX;
3492			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3493			ifmedia_set(media, m | IFM_NONE);
3494			break;
3495
3496		default:
3497			device_printf(pi->dev,
3498			    "unknown port_type (%d), mod_type (%d)\n",
3499			    pi->port_type, pi->mod_type);
3500			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3501			ifmedia_set(media, m | IFM_UNKNOWN);
3502			break;
3503		}
3504		break;
3505
3506	default:
3507		device_printf(pi->dev,
3508		    "unknown port_type (%d), mod_type (%d)\n", pi->port_type,
3509		    pi->mod_type);
3510		ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3511		ifmedia_set(media, m | IFM_UNKNOWN);
3512		break;
3513	}
3514
3515	PORT_UNLOCK(pi);
3516}
3517
3518#define FW_MAC_EXACT_CHUNK	7
3519
3520/*
3521 * Program the port's XGMAC based on parameters in ifnet.  The caller also
3522 * indicates which parameters should be programmed (the rest are left alone).
3523 */
3524int
3525update_mac_settings(struct ifnet *ifp, int flags)
3526{
3527	int rc = 0;
3528	struct vi_info *vi = ifp->if_softc;
3529	struct port_info *pi = vi->pi;
3530	struct adapter *sc = pi->adapter;
3531	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
3532
3533	ASSERT_SYNCHRONIZED_OP(sc);
3534	KASSERT(flags, ("%s: not told what to update.", __func__));
3535
3536	if (flags & XGMAC_MTU)
3537		mtu = ifp->if_mtu;
3538
3539	if (flags & XGMAC_PROMISC)
3540		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
3541
3542	if (flags & XGMAC_ALLMULTI)
3543		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
3544
3545	if (flags & XGMAC_VLANEX)
3546		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
3547
3548	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
3549		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
3550		    allmulti, 1, vlanex, false);
3551		if (rc) {
3552			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
3553			    rc);
3554			return (rc);
3555		}
3556	}
3557
3558	if (flags & XGMAC_UCADDR) {
3559		uint8_t ucaddr[ETHER_ADDR_LEN];
3560
3561		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
3562		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
3563		    ucaddr, true, true);
3564		if (rc < 0) {
3565			rc = -rc;
3566			if_printf(ifp, "change_mac failed: %d\n", rc);
3567			return (rc);
3568		} else {
3569			vi->xact_addr_filt = rc;
3570			rc = 0;
3571		}
3572	}
3573
3574	if (flags & XGMAC_MCADDRS) {
3575		const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
3576		int del = 1;
3577		uint64_t hash = 0;
3578		struct ifmultiaddr *ifma;
3579		int i = 0, j;
3580
3581		if_maddr_rlock(ifp);
3582		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3583			if (ifma->ifma_addr->sa_family != AF_LINK)
3584				continue;
3585			mcaddr[i] =
3586			    LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
3587			MPASS(ETHER_IS_MULTICAST(mcaddr[i]));
3588			i++;
3589
3590			if (i == FW_MAC_EXACT_CHUNK) {
3591				rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
3592				    del, i, mcaddr, NULL, &hash, 0);
3593				if (rc < 0) {
3594					rc = -rc;
3595					for (j = 0; j < i; j++) {
3596						if_printf(ifp,
3597						    "failed to add mc address"
3598						    " %02x:%02x:%02x:"
3599						    "%02x:%02x:%02x rc=%d\n",
3600						    mcaddr[j][0], mcaddr[j][1],
3601						    mcaddr[j][2], mcaddr[j][3],
3602						    mcaddr[j][4], mcaddr[j][5],
3603						    rc);
3604					}
3605					goto mcfail;
3606				}
3607				del = 0;
3608				i = 0;
3609			}
3610		}
3611		if (i > 0) {
3612			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, del, i,
3613			    mcaddr, NULL, &hash, 0);
3614			if (rc < 0) {
3615				rc = -rc;
3616				for (j = 0; j < i; j++) {
3617					if_printf(ifp,
3618					    "failed to add mc address"
3619					    " %02x:%02x:%02x:"
3620					    "%02x:%02x:%02x rc=%d\n",
3621					    mcaddr[j][0], mcaddr[j][1],
3622					    mcaddr[j][2], mcaddr[j][3],
3623					    mcaddr[j][4], mcaddr[j][5],
3624					    rc);
3625				}
3626				goto mcfail;
3627			}
3628		}
3629
3630		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, hash, 0);
3631		if (rc != 0)
3632			if_printf(ifp, "failed to set mc address hash: %d", rc);
3633mcfail:
3634		if_maddr_runlock(ifp);
3635	}
3636
3637	return (rc);
3638}
3639
3640/*
3641 * {begin|end}_synchronized_op must be called from the same thread.
3642 */
3643int
3644begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
3645    char *wmesg)
3646{
3647	int rc, pri;
3648
3649#ifdef WITNESS
3650	/* the caller thinks it's ok to sleep, but is it really? */
3651	if (flags & SLEEP_OK)
3652		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3653		    "begin_synchronized_op");
3654#endif
3655
3656	if (INTR_OK)
3657		pri = PCATCH;
3658	else
3659		pri = 0;
3660
3661	ADAPTER_LOCK(sc);
3662	for (;;) {
3663
3664		if (vi && IS_DOOMED(vi)) {
3665			rc = ENXIO;
3666			goto done;
3667		}
3668
3669		if (!IS_BUSY(sc)) {
3670			rc = 0;
3671			break;
3672		}
3673
3674		if (!(flags & SLEEP_OK)) {
3675			rc = EBUSY;
3676			goto done;
3677		}
3678
3679		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
3680			rc = EINTR;
3681			goto done;
3682		}
3683	}
3684
3685	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
3686	SET_BUSY(sc);
3687#ifdef INVARIANTS
3688	sc->last_op = wmesg;
3689	sc->last_op_thr = curthread;
3690	sc->last_op_flags = flags;
3691#endif
3692
3693done:
3694	if (!(flags & HOLD_LOCK) || rc)
3695		ADAPTER_UNLOCK(sc);
3696
3697	return (rc);
3698}
3699
3700/*
3701 * Tell if_ioctl and if_init that the VI is going away.  This is
3702 * special variant of begin_synchronized_op and must be paired with a
3703 * call to end_synchronized_op.
3704 */
3705void
3706doom_vi(struct adapter *sc, struct vi_info *vi)
3707{
3708
3709	ADAPTER_LOCK(sc);
3710	SET_DOOMED(vi);
3711	wakeup(&sc->flags);
3712	while (IS_BUSY(sc))
3713		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
3714	SET_BUSY(sc);
3715#ifdef INVARIANTS
3716	sc->last_op = "t4detach";
3717	sc->last_op_thr = curthread;
3718	sc->last_op_flags = 0;
3719#endif
3720	ADAPTER_UNLOCK(sc);
3721}
3722
3723/*
3724 * {begin|end}_synchronized_op must be called from the same thread.
3725 */
3726void
3727end_synchronized_op(struct adapter *sc, int flags)
3728{
3729
3730	if (flags & LOCK_HELD)
3731		ADAPTER_LOCK_ASSERT_OWNED(sc);
3732	else
3733		ADAPTER_LOCK(sc);
3734
3735	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
3736	CLR_BUSY(sc);
3737	wakeup(&sc->flags);
3738	ADAPTER_UNLOCK(sc);
3739}
3740
3741static int
3742cxgbe_init_synchronized(struct vi_info *vi)
3743{
3744	struct port_info *pi = vi->pi;
3745	struct adapter *sc = pi->adapter;
3746	struct ifnet *ifp = vi->ifp;
3747	int rc = 0, i;
3748	struct sge_txq *txq;
3749
3750	ASSERT_SYNCHRONIZED_OP(sc);
3751
3752	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
3753		return (0);	/* already running */
3754
3755	if (!(sc->flags & FULL_INIT_DONE) &&
3756	    ((rc = adapter_full_init(sc)) != 0))
3757		return (rc);	/* error message displayed already */
3758
3759	if (!(vi->flags & VI_INIT_DONE) &&
3760	    ((rc = vi_full_init(vi)) != 0))
3761		return (rc); /* error message displayed already */
3762
3763	rc = update_mac_settings(ifp, XGMAC_ALL);
3764	if (rc)
3765		goto done;	/* error message displayed already */
3766
3767	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
3768	if (rc != 0) {
3769		if_printf(ifp, "enable_vi failed: %d\n", rc);
3770		goto done;
3771	}
3772
3773	/*
3774	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
3775	 * if this changes.
3776	 */
3777
3778	for_each_txq(vi, i, txq) {
3779		TXQ_LOCK(txq);
3780		txq->eq.flags |= EQ_ENABLED;
3781		TXQ_UNLOCK(txq);
3782	}
3783
3784	/*
3785	 * The first iq of the first port to come up is used for tracing.
3786	 */
3787	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
3788		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
3789		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
3790		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
3791		    V_QUEUENUMBER(sc->traceq));
3792		pi->flags |= HAS_TRACEQ;
3793	}
3794
3795	/* all ok */
3796	PORT_LOCK(pi);
3797	ifp->if_drv_flags |= IFF_DRV_RUNNING;
3798	pi->up_vis++;
3799
3800	if (pi->nvi > 1 || sc->flags & IS_VF)
3801		callout_reset(&vi->tick, hz, vi_tick, vi);
3802	else
3803		callout_reset(&pi->tick, hz, cxgbe_tick, pi);
3804	PORT_UNLOCK(pi);
3805done:
3806	if (rc != 0)
3807		cxgbe_uninit_synchronized(vi);
3808
3809	return (rc);
3810}
3811
3812/*
3813 * Idempotent.
3814 */
3815static int
3816cxgbe_uninit_synchronized(struct vi_info *vi)
3817{
3818	struct port_info *pi = vi->pi;
3819	struct adapter *sc = pi->adapter;
3820	struct ifnet *ifp = vi->ifp;
3821	int rc, i;
3822	struct sge_txq *txq;
3823
3824	ASSERT_SYNCHRONIZED_OP(sc);
3825
3826	if (!(vi->flags & VI_INIT_DONE)) {
3827		KASSERT(!(ifp->if_drv_flags & IFF_DRV_RUNNING),
3828		    ("uninited VI is running"));
3829		return (0);
3830	}
3831
3832	/*
3833	 * Disable the VI so that all its data in either direction is discarded
3834	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
3835	 * tick) intact as the TP can deliver negative advice or data that it's
3836	 * holding in its RAM (for an offloaded connection) even after the VI is
3837	 * disabled.
3838	 */
3839	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
3840	if (rc) {
3841		if_printf(ifp, "disable_vi failed: %d\n", rc);
3842		return (rc);
3843	}
3844
3845	for_each_txq(vi, i, txq) {
3846		TXQ_LOCK(txq);
3847		txq->eq.flags &= ~EQ_ENABLED;
3848		TXQ_UNLOCK(txq);
3849	}
3850
3851	PORT_LOCK(pi);
3852	if (pi->nvi > 1 || sc->flags & IS_VF)
3853		callout_stop(&vi->tick);
3854	else
3855		callout_stop(&pi->tick);
3856	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3857		PORT_UNLOCK(pi);
3858		return (0);
3859	}
3860	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
3861	pi->up_vis--;
3862	if (pi->up_vis > 0) {
3863		PORT_UNLOCK(pi);
3864		return (0);
3865	}
3866	PORT_UNLOCK(pi);
3867
3868	pi->link_cfg.link_ok = 0;
3869	pi->link_cfg.speed = 0;
3870	pi->linkdnrc = -1;
3871	t4_os_link_changed(sc, pi->port_id, 0, -1);
3872
3873	return (0);
3874}
3875
3876/*
3877 * It is ok for this function to fail midway and return right away.  t4_detach
3878 * will walk the entire sc->irq list and clean up whatever is valid.
3879 */
3880int
3881t4_setup_intr_handlers(struct adapter *sc)
3882{
3883	int rc, rid, p, q, v;
3884	char s[8];
3885	struct irq *irq;
3886	struct port_info *pi;
3887	struct vi_info *vi;
3888	struct sge *sge = &sc->sge;
3889	struct sge_rxq *rxq;
3890#ifdef TCP_OFFLOAD
3891	struct sge_ofld_rxq *ofld_rxq;
3892#endif
3893#ifdef DEV_NETMAP
3894	struct sge_nm_rxq *nm_rxq;
3895#endif
3896
3897	/*
3898	 * Setup interrupts.
3899	 */
3900	irq = &sc->irq[0];
3901	rid = sc->intr_type == INTR_INTX ? 0 : 1;
3902	if (sc->intr_count == 1)
3903		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
3904
3905	/* Multiple interrupts. */
3906	if (sc->flags & IS_VF)
3907		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
3908		    ("%s: too few intr.", __func__));
3909	else
3910		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
3911		    ("%s: too few intr.", __func__));
3912
3913	/* The first one is always error intr on PFs */
3914	if (!(sc->flags & IS_VF)) {
3915		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
3916		if (rc != 0)
3917			return (rc);
3918		irq++;
3919		rid++;
3920	}
3921
3922	/* The second one is always the firmware event queue (first on VFs) */
3923	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
3924	if (rc != 0)
3925		return (rc);
3926	irq++;
3927	rid++;
3928
3929	for_each_port(sc, p) {
3930		pi = sc->port[p];
3931		for_each_vi(pi, v, vi) {
3932			vi->first_intr = rid - 1;
3933
3934			if (vi->nnmrxq > 0) {
3935				int n = max(vi->nrxq, vi->nnmrxq);
3936
3937				MPASS(vi->flags & INTR_RXQ);
3938
3939				rxq = &sge->rxq[vi->first_rxq];
3940#ifdef DEV_NETMAP
3941				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
3942#endif
3943				for (q = 0; q < n; q++) {
3944					snprintf(s, sizeof(s), "%x%c%x", p,
3945					    'a' + v, q);
3946					if (q < vi->nrxq)
3947						irq->rxq = rxq++;
3948#ifdef DEV_NETMAP
3949					if (q < vi->nnmrxq)
3950						irq->nm_rxq = nm_rxq++;
3951#endif
3952					rc = t4_alloc_irq(sc, irq, rid,
3953					    t4_vi_intr, irq, s);
3954					if (rc != 0)
3955						return (rc);
3956					irq++;
3957					rid++;
3958					vi->nintr++;
3959				}
3960			} else if (vi->flags & INTR_RXQ) {
3961				for_each_rxq(vi, q, rxq) {
3962					snprintf(s, sizeof(s), "%x%c%x", p,
3963					    'a' + v, q);
3964					rc = t4_alloc_irq(sc, irq, rid,
3965					    t4_intr, rxq, s);
3966					if (rc != 0)
3967						return (rc);
3968					irq++;
3969					rid++;
3970					vi->nintr++;
3971				}
3972			}
3973#ifdef TCP_OFFLOAD
3974			if (vi->flags & INTR_OFLD_RXQ) {
3975				for_each_ofld_rxq(vi, q, ofld_rxq) {
3976					snprintf(s, sizeof(s), "%x%c%x", p,
3977					    'A' + v, q);
3978					rc = t4_alloc_irq(sc, irq, rid,
3979					    t4_intr, ofld_rxq, s);
3980					if (rc != 0)
3981						return (rc);
3982					irq++;
3983					rid++;
3984					vi->nintr++;
3985				}
3986			}
3987#endif
3988		}
3989	}
3990	MPASS(irq == &sc->irq[sc->intr_count]);
3991
3992	return (0);
3993}
3994
3995int
3996adapter_full_init(struct adapter *sc)
3997{
3998	int rc, i;
3999
4000	ASSERT_SYNCHRONIZED_OP(sc);
4001	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
4002	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
4003	    ("%s: FULL_INIT_DONE already", __func__));
4004
4005	/*
4006	 * queues that belong to the adapter (not any particular port).
4007	 */
4008	rc = t4_setup_adapter_queues(sc);
4009	if (rc != 0)
4010		goto done;
4011
4012	for (i = 0; i < nitems(sc->tq); i++) {
4013		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
4014		    taskqueue_thread_enqueue, &sc->tq[i]);
4015		if (sc->tq[i] == NULL) {
4016			device_printf(sc->dev,
4017			    "failed to allocate task queue %d\n", i);
4018			rc = ENOMEM;
4019			goto done;
4020		}
4021		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
4022		    device_get_nameunit(sc->dev), i);
4023	}
4024
4025	if (!(sc->flags & IS_VF))
4026		t4_intr_enable(sc);
4027	sc->flags |= FULL_INIT_DONE;
4028done:
4029	if (rc != 0)
4030		adapter_full_uninit(sc);
4031
4032	return (rc);
4033}
4034
4035int
4036adapter_full_uninit(struct adapter *sc)
4037{
4038	int i;
4039
4040	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
4041
4042	t4_teardown_adapter_queues(sc);
4043
4044	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
4045		taskqueue_free(sc->tq[i]);
4046		sc->tq[i] = NULL;
4047	}
4048
4049	sc->flags &= ~FULL_INIT_DONE;
4050
4051	return (0);
4052}
4053
4054#ifdef RSS
4055#define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
4056    RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
4057    RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
4058    RSS_HASHTYPE_RSS_UDP_IPV6)
4059
4060/* Translates kernel hash types to hardware. */
4061static int
4062hashconfig_to_hashen(int hashconfig)
4063{
4064	int hashen = 0;
4065
4066	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
4067		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
4068	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
4069		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
4070	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
4071		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
4072		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
4073	}
4074	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
4075		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
4076		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
4077	}
4078	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
4079		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
4080	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
4081		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
4082
4083	return (hashen);
4084}
4085
4086/* Translates hardware hash types to kernel. */
4087static int
4088hashen_to_hashconfig(int hashen)
4089{
4090	int hashconfig = 0;
4091
4092	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
4093		/*
4094		 * If UDP hashing was enabled it must have been enabled for
4095		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
4096		 * enabling any 4-tuple hash is nonsense configuration.
4097		 */
4098		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
4099		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
4100
4101		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
4102			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
4103		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
4104			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
4105	}
4106	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
4107		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
4108	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
4109		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
4110	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
4111		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
4112	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
4113		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
4114
4115	return (hashconfig);
4116}
4117#endif
4118
4119int
4120vi_full_init(struct vi_info *vi)
4121{
4122	struct adapter *sc = vi->pi->adapter;
4123	struct ifnet *ifp = vi->ifp;
4124	uint16_t *rss;
4125	struct sge_rxq *rxq;
4126	int rc, i, j, hashen;
4127#ifdef RSS
4128	int nbuckets = rss_getnumbuckets();
4129	int hashconfig = rss_gethashconfig();
4130	int extra;
4131	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
4132	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
4133#endif
4134
4135	ASSERT_SYNCHRONIZED_OP(sc);
4136	KASSERT((vi->flags & VI_INIT_DONE) == 0,
4137	    ("%s: VI_INIT_DONE already", __func__));
4138
4139	sysctl_ctx_init(&vi->ctx);
4140	vi->flags |= VI_SYSCTL_CTX;
4141
4142	/*
4143	 * Allocate tx/rx/fl queues for this VI.
4144	 */
4145	rc = t4_setup_vi_queues(vi);
4146	if (rc != 0)
4147		goto done;	/* error message displayed already */
4148
4149	/*
4150	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
4151	 */
4152	if (vi->nrxq > vi->rss_size) {
4153		if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
4154		    "some queues will never receive traffic.\n", vi->nrxq,
4155		    vi->rss_size);
4156	} else if (vi->rss_size % vi->nrxq) {
4157		if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
4158		    "expect uneven traffic distribution.\n", vi->nrxq,
4159		    vi->rss_size);
4160	}
4161#ifdef RSS
4162	MPASS(RSS_KEYSIZE == 40);
4163	if (vi->nrxq != nbuckets) {
4164		if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
4165		    "performance will be impacted.\n", vi->nrxq, nbuckets);
4166	}
4167
4168	rss_getkey((void *)&raw_rss_key[0]);
4169	for (i = 0; i < nitems(rss_key); i++) {
4170		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
4171	}
4172	t4_write_rss_key(sc, &rss_key[0], -1);
4173#endif
4174	rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
4175	for (i = 0; i < vi->rss_size;) {
4176#ifdef RSS
4177		j = rss_get_indirection_to_bucket(i);
4178		j %= vi->nrxq;
4179		rxq = &sc->sge.rxq[vi->first_rxq + j];
4180		rss[i++] = rxq->iq.abs_id;
4181#else
4182		for_each_rxq(vi, j, rxq) {
4183			rss[i++] = rxq->iq.abs_id;
4184			if (i == vi->rss_size)
4185				break;
4186		}
4187#endif
4188	}
4189
4190	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
4191	    vi->rss_size);
4192	if (rc != 0) {
4193		if_printf(ifp, "rss_config failed: %d\n", rc);
4194		goto done;
4195	}
4196
4197#ifdef RSS
4198	hashen = hashconfig_to_hashen(hashconfig);
4199
4200	/*
4201	 * We may have had to enable some hashes even though the global config
4202	 * wants them disabled.  This is a potential problem that must be
4203	 * reported to the user.
4204	 */
4205	extra = hashen_to_hashconfig(hashen) ^ hashconfig;
4206
4207	/*
4208	 * If we consider only the supported hash types, then the enabled hashes
4209	 * are a superset of the requested hashes.  In other words, there cannot
4210	 * be any supported hash that was requested but not enabled, but there
4211	 * can be hashes that were not requested but had to be enabled.
4212	 */
4213	extra &= SUPPORTED_RSS_HASHTYPES;
4214	MPASS((extra & hashconfig) == 0);
4215
4216	if (extra) {
4217		if_printf(ifp,
4218		    "global RSS config (0x%x) cannot be accomodated.\n",
4219		    hashconfig);
4220	}
4221	if (extra & RSS_HASHTYPE_RSS_IPV4)
4222		if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
4223	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
4224		if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
4225	if (extra & RSS_HASHTYPE_RSS_IPV6)
4226		if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
4227	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
4228		if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
4229	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
4230		if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
4231	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
4232		if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
4233#else
4234	hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
4235	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
4236	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
4237	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
4238#endif
4239	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, hashen, rss[0], 0, 0);
4240	if (rc != 0) {
4241		if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
4242		goto done;
4243	}
4244
4245	vi->rss = rss;
4246	vi->flags |= VI_INIT_DONE;
4247done:
4248	if (rc != 0)
4249		vi_full_uninit(vi);
4250
4251	return (rc);
4252}
4253
4254/*
4255 * Idempotent.
4256 */
4257int
4258vi_full_uninit(struct vi_info *vi)
4259{
4260	struct port_info *pi = vi->pi;
4261	struct adapter *sc = pi->adapter;
4262	int i;
4263	struct sge_rxq *rxq;
4264	struct sge_txq *txq;
4265#ifdef TCP_OFFLOAD
4266	struct sge_ofld_rxq *ofld_rxq;
4267	struct sge_wrq *ofld_txq;
4268#endif
4269
4270	if (vi->flags & VI_INIT_DONE) {
4271
4272		/* Need to quiesce queues.  */
4273
4274		/* XXX: Only for the first VI? */
4275		if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
4276			quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
4277
4278		for_each_txq(vi, i, txq) {
4279			quiesce_txq(sc, txq);
4280		}
4281
4282#ifdef TCP_OFFLOAD
4283		for_each_ofld_txq(vi, i, ofld_txq) {
4284			quiesce_wrq(sc, ofld_txq);
4285		}
4286#endif
4287
4288		for_each_rxq(vi, i, rxq) {
4289			quiesce_iq(sc, &rxq->iq);
4290			quiesce_fl(sc, &rxq->fl);
4291		}
4292
4293#ifdef TCP_OFFLOAD
4294		for_each_ofld_rxq(vi, i, ofld_rxq) {
4295			quiesce_iq(sc, &ofld_rxq->iq);
4296			quiesce_fl(sc, &ofld_rxq->fl);
4297		}
4298#endif
4299		free(vi->rss, M_CXGBE);
4300		free(vi->nm_rss, M_CXGBE);
4301	}
4302
4303	t4_teardown_vi_queues(vi);
4304	vi->flags &= ~VI_INIT_DONE;
4305
4306	return (0);
4307}
4308
4309static void
4310quiesce_txq(struct adapter *sc, struct sge_txq *txq)
4311{
4312	struct sge_eq *eq = &txq->eq;
4313	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
4314
4315	(void) sc;	/* unused */
4316
4317#ifdef INVARIANTS
4318	TXQ_LOCK(txq);
4319	MPASS((eq->flags & EQ_ENABLED) == 0);
4320	TXQ_UNLOCK(txq);
4321#endif
4322
4323	/* Wait for the mp_ring to empty. */
4324	while (!mp_ring_is_idle(txq->r)) {
4325		mp_ring_check_drainage(txq->r, 0);
4326		pause("rquiesce", 1);
4327	}
4328
4329	/* Then wait for the hardware to finish. */
4330	while (spg->cidx != htobe16(eq->pidx))
4331		pause("equiesce", 1);
4332
4333	/* Finally, wait for the driver to reclaim all descriptors. */
4334	while (eq->cidx != eq->pidx)
4335		pause("dquiesce", 1);
4336}
4337
4338static void
4339quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
4340{
4341
4342	/* XXXTX */
4343}
4344
4345static void
4346quiesce_iq(struct adapter *sc, struct sge_iq *iq)
4347{
4348	(void) sc;	/* unused */
4349
4350	/* Synchronize with the interrupt handler */
4351	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
4352		pause("iqfree", 1);
4353}
4354
4355static void
4356quiesce_fl(struct adapter *sc, struct sge_fl *fl)
4357{
4358	mtx_lock(&sc->sfl_lock);
4359	FL_LOCK(fl);
4360	fl->flags |= FL_DOOMED;
4361	FL_UNLOCK(fl);
4362	callout_stop(&sc->sfl_callout);
4363	mtx_unlock(&sc->sfl_lock);
4364
4365	KASSERT((fl->flags & FL_STARVING) == 0,
4366	    ("%s: still starving", __func__));
4367}
4368
4369static int
4370t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
4371    driver_intr_t *handler, void *arg, char *name)
4372{
4373	int rc;
4374
4375	irq->rid = rid;
4376	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
4377	    RF_SHAREABLE | RF_ACTIVE);
4378	if (irq->res == NULL) {
4379		device_printf(sc->dev,
4380		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
4381		return (ENOMEM);
4382	}
4383
4384	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
4385	    NULL, handler, arg, &irq->tag);
4386	if (rc != 0) {
4387		device_printf(sc->dev,
4388		    "failed to setup interrupt for rid %d, name %s: %d\n",
4389		    rid, name, rc);
4390	} else if (name)
4391		bus_describe_intr(sc->dev, irq->res, irq->tag, name);
4392
4393	return (rc);
4394}
4395
4396static int
4397t4_free_irq(struct adapter *sc, struct irq *irq)
4398{
4399	if (irq->tag)
4400		bus_teardown_intr(sc->dev, irq->res, irq->tag);
4401	if (irq->res)
4402		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
4403
4404	bzero(irq, sizeof(*irq));
4405
4406	return (0);
4407}
4408
4409static void
4410get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
4411{
4412
4413	regs->version = chip_id(sc) | chip_rev(sc) << 10;
4414	t4_get_regs(sc, buf, regs->len);
4415}
4416
4417#define	A_PL_INDIR_CMD	0x1f8
4418
4419#define	S_PL_AUTOINC	31
4420#define	M_PL_AUTOINC	0x1U
4421#define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
4422#define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
4423
4424#define	S_PL_VFID	20
4425#define	M_PL_VFID	0xffU
4426#define	V_PL_VFID(x)	((x) << S_PL_VFID)
4427#define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
4428
4429#define	S_PL_ADDR	0
4430#define	M_PL_ADDR	0xfffffU
4431#define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
4432#define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
4433
4434#define	A_PL_INDIR_DATA	0x1fc
4435
4436static uint64_t
4437read_vf_stat(struct adapter *sc, unsigned int viid, int reg)
4438{
4439	u32 stats[2];
4440
4441	mtx_assert(&sc->reg_lock, MA_OWNED);
4442	if (sc->flags & IS_VF) {
4443		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
4444		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
4445	} else {
4446		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
4447		    V_PL_VFID(G_FW_VIID_VIN(viid)) |
4448		    V_PL_ADDR(VF_MPS_REG(reg)));
4449		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
4450		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
4451	}
4452	return (((uint64_t)stats[1]) << 32 | stats[0]);
4453}
4454
4455static void
4456t4_get_vi_stats(struct adapter *sc, unsigned int viid,
4457    struct fw_vi_stats_vf *stats)
4458{
4459
4460#define GET_STAT(name) \
4461	read_vf_stat(sc, viid, A_MPS_VF_STAT_##name##_L)
4462
4463	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
4464	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
4465	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
4466	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
4467	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
4468	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
4469	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
4470	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
4471	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
4472	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
4473	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
4474	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
4475	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
4476	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
4477	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
4478	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
4479
4480#undef GET_STAT
4481}
4482
4483static void
4484t4_clr_vi_stats(struct adapter *sc, unsigned int viid)
4485{
4486	int reg;
4487
4488	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
4489	    V_PL_VFID(G_FW_VIID_VIN(viid)) |
4490	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
4491	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
4492	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
4493		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
4494}
4495
4496static void
4497vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
4498{
4499	struct ifnet *ifp = vi->ifp;
4500	struct sge_txq *txq;
4501	int i, drops;
4502	struct fw_vi_stats_vf *s = &vi->stats;
4503	struct timeval tv;
4504	const struct timeval interval = {0, 250000};	/* 250ms */
4505
4506	if (!(vi->flags & VI_INIT_DONE))
4507		return;
4508
4509	getmicrotime(&tv);
4510	timevalsub(&tv, &interval);
4511	if (timevalcmp(&tv, &vi->last_refreshed, <))
4512		return;
4513
4514	mtx_lock(&sc->reg_lock);
4515	t4_get_vi_stats(sc, vi->viid, &vi->stats);
4516
4517	ifp->if_ipackets = s->rx_bcast_frames + s->rx_mcast_frames +
4518	    s->rx_ucast_frames;
4519	ifp->if_ierrors = s->rx_err_frames;
4520	ifp->if_opackets = s->tx_bcast_frames + s->tx_mcast_frames +
4521	    s->tx_ucast_frames + s->tx_offload_frames;
4522	ifp->if_oerrors = s->tx_drop_frames;
4523	ifp->if_ibytes = s->rx_bcast_bytes + s->rx_mcast_bytes +
4524	    s->rx_ucast_bytes;
4525	ifp->if_obytes = s->tx_bcast_bytes + s->tx_mcast_bytes +
4526	    s->tx_ucast_bytes + s->tx_offload_bytes;
4527	ifp->if_imcasts = s->rx_mcast_frames;
4528	ifp->if_omcasts = s->tx_mcast_frames;
4529
4530	drops = 0;
4531	for_each_txq(vi, i, txq)
4532		drops += counter_u64_fetch(txq->r->drops);
4533	ifp->if_snd.ifq_drops = drops;
4534
4535	getmicrotime(&vi->last_refreshed);
4536	mtx_unlock(&sc->reg_lock);
4537}
4538
4539static void
4540cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
4541{
4542	struct vi_info *vi = &pi->vi[0];
4543	struct ifnet *ifp = vi->ifp;
4544	struct sge_txq *txq;
4545	int i, drops;
4546	struct port_stats *s = &pi->stats;
4547	struct timeval tv;
4548	const struct timeval interval = {0, 250000};	/* 250ms */
4549
4550	getmicrotime(&tv);
4551	timevalsub(&tv, &interval);
4552	if (timevalcmp(&tv, &pi->last_refreshed, <))
4553		return;
4554
4555	t4_get_port_stats(sc, pi->tx_chan, s);
4556
4557	ifp->if_opackets = s->tx_frames;
4558	ifp->if_ipackets = s->rx_frames;
4559	ifp->if_obytes = s->tx_octets;
4560	ifp->if_ibytes = s->rx_octets;
4561	ifp->if_omcasts = s->tx_mcast_frames;
4562	ifp->if_imcasts = s->rx_mcast_frames;
4563	ifp->if_iqdrops = s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
4564	    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
4565	    s->rx_trunc3;
4566	for (i = 0; i < sc->chip_params->nchan; i++) {
4567		if (pi->rx_chan_map & (1 << i)) {
4568			uint32_t v;
4569
4570			mtx_lock(&sc->reg_lock);
4571			t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
4572			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
4573			mtx_unlock(&sc->reg_lock);
4574			ifp->if_iqdrops += v;
4575		}
4576	}
4577
4578	drops = s->tx_drop;
4579	for_each_txq(vi, i, txq)
4580		drops += counter_u64_fetch(txq->r->drops);
4581	ifp->if_snd.ifq_drops = drops;
4582
4583	ifp->if_oerrors = s->tx_error_frames;
4584	ifp->if_ierrors = s->rx_jabber + s->rx_runt + s->rx_too_long +
4585	    s->rx_fcs_err + s->rx_len_err;
4586
4587	getmicrotime(&pi->last_refreshed);
4588}
4589
4590static void
4591cxgbe_tick(void *arg)
4592{
4593	struct port_info *pi = arg;
4594	struct adapter *sc = pi->adapter;
4595
4596	PORT_LOCK_ASSERT_OWNED(pi);
4597	cxgbe_refresh_stats(sc, pi);
4598
4599	callout_schedule(&pi->tick, hz);
4600}
4601
4602void
4603vi_tick(void *arg)
4604{
4605	struct vi_info *vi = arg;
4606	struct adapter *sc = vi->pi->adapter;
4607
4608	vi_refresh_stats(sc, vi);
4609
4610	callout_schedule(&vi->tick, hz);
4611}
4612
4613static void
4614cxgbe_vlan_config(void *arg, struct ifnet *ifp, uint16_t vid)
4615{
4616	struct ifnet *vlan;
4617
4618	if (arg != ifp || ifp->if_type != IFT_ETHER)
4619		return;
4620
4621	vlan = VLAN_DEVAT(ifp, vid);
4622	VLAN_SETCOOKIE(vlan, ifp);
4623}
4624
4625/*
4626 * Should match fw_caps_config_<foo> enums in t4fw_interface.h
4627 */
4628static char *caps_decoder[] = {
4629	"\20\001IPMI\002NCSI",				/* 0: NBM */
4630	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
4631	"\20\001INGRESS\002EGRESS",			/* 2: switch */
4632	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
4633	    "\006HASHFILTER\007ETHOFLD",
4634	"\20\001TOE",					/* 4: TOE */
4635	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
4636	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
4637	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
4638	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
4639	    "\007T10DIF"
4640	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
4641	"\20\001LOOKASIDE\002TLSKEYS",			/* 7: Crypto */
4642	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
4643		    "\004PO_INITIATOR\005PO_TARGET",
4644};
4645
4646void
4647t4_sysctls(struct adapter *sc)
4648{
4649	struct sysctl_ctx_list *ctx;
4650	struct sysctl_oid *oid;
4651	struct sysctl_oid_list *children, *c0;
4652	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
4653
4654	ctx = device_get_sysctl_ctx(sc->dev);
4655
4656	/*
4657	 * dev.t4nex.X.
4658	 */
4659	oid = device_get_sysctl_tree(sc->dev);
4660	c0 = children = SYSCTL_CHILDREN(oid);
4661
4662	sc->sc_do_rxcopy = 1;
4663	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
4664	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
4665
4666	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
4667	    sc->params.nports, "# of ports");
4668
4669	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
4670	    CTLTYPE_STRING | CTLFLAG_RD, doorbells, sc->doorbells,
4671	    sysctl_bitfield, "A", "available doorbells");
4672
4673	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
4674	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
4675
4676	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
4677	    CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.timer_val,
4678	    sizeof(sc->params.sge.timer_val), sysctl_int_array, "A",
4679	    "interrupt holdoff timer values (us)");
4680
4681	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
4682	    CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.counter_val,
4683	    sizeof(sc->params.sge.counter_val), sysctl_int_array, "A",
4684	    "interrupt holdoff packet counter values");
4685
4686	t4_sge_sysctls(sc, ctx, children);
4687
4688	sc->lro_timeout = 100;
4689	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
4690	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
4691
4692	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
4693	    &sc->debug_flags, 0, "flags to enable runtime debugging");
4694
4695	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
4696	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
4697
4698	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
4699	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
4700
4701	if (sc->flags & IS_VF)
4702		return;
4703
4704	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
4705	    NULL, chip_rev(sc), "chip hardware revision");
4706
4707	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
4708	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
4709
4710	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
4711	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
4712
4713	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
4714	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
4715
4716	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
4717	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
4718
4719	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
4720	    sc->er_version, 0, "expansion ROM version");
4721
4722	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
4723	    sc->bs_version, 0, "bootstrap firmware version");
4724
4725	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
4726	    NULL, sc->params.scfg_vers, "serial config version");
4727
4728	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
4729	    NULL, sc->params.vpd_vers, "VPD version");
4730
4731	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
4732	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
4733
4734	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
4735	    sc->cfcsum, "config file checksum");
4736
4737#define SYSCTL_CAP(name, n, text) \
4738	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
4739	    CTLTYPE_STRING | CTLFLAG_RD, caps_decoder[n], sc->name, \
4740	    sysctl_bitfield, "A", "available " text " capabilities")
4741
4742	SYSCTL_CAP(nbmcaps, 0, "NBM");
4743	SYSCTL_CAP(linkcaps, 1, "link");
4744	SYSCTL_CAP(switchcaps, 2, "switch");
4745	SYSCTL_CAP(niccaps, 3, "NIC");
4746	SYSCTL_CAP(toecaps, 4, "TCP offload");
4747	SYSCTL_CAP(rdmacaps, 5, "RDMA");
4748	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
4749	SYSCTL_CAP(cryptocaps, 7, "crypto");
4750	SYSCTL_CAP(fcoecaps, 8, "FCoE");
4751#undef SYSCTL_CAP
4752
4753	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
4754	    NULL, sc->tids.nftids, "number of filters");
4755
4756	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature", CTLTYPE_INT |
4757	    CTLFLAG_RD, sc, 0, sysctl_temperature, "I",
4758	    "chip temperature (in Celsius)");
4759
4760#ifdef SBUF_DRAIN
4761	/*
4762	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
4763	 */
4764	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
4765	    CTLFLAG_RD | CTLFLAG_SKIP, NULL,
4766	    "logs and miscellaneous information");
4767	children = SYSCTL_CHILDREN(oid);
4768
4769	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
4770	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4771	    sysctl_cctrl, "A", "congestion control");
4772
4773	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
4774	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4775	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
4776
4777	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
4778	    CTLTYPE_STRING | CTLFLAG_RD, sc, 1,
4779	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
4780
4781	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
4782	    CTLTYPE_STRING | CTLFLAG_RD, sc, 2,
4783	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
4784
4785	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
4786	    CTLTYPE_STRING | CTLFLAG_RD, sc, 3,
4787	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
4788
4789	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
4790	    CTLTYPE_STRING | CTLFLAG_RD, sc, 4,
4791	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
4792
4793	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
4794	    CTLTYPE_STRING | CTLFLAG_RD, sc, 5,
4795	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
4796
4797	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
4798	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4799	    chip_id(sc) <= CHELSIO_T5 ? sysctl_cim_la : sysctl_cim_la_t6,
4800	    "A", "CIM logic analyzer");
4801
4802	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
4803	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4804	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
4805
4806	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
4807	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0 + CIM_NUM_IBQ,
4808	    sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
4809
4810	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
4811	    CTLTYPE_STRING | CTLFLAG_RD, sc, 1 + CIM_NUM_IBQ,
4812	    sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
4813
4814	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
4815	    CTLTYPE_STRING | CTLFLAG_RD, sc, 2 + CIM_NUM_IBQ,
4816	    sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
4817
4818	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
4819	    CTLTYPE_STRING | CTLFLAG_RD, sc, 3 + CIM_NUM_IBQ,
4820	    sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
4821
4822	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
4823	    CTLTYPE_STRING | CTLFLAG_RD, sc, 4 + CIM_NUM_IBQ,
4824	    sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
4825
4826	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
4827	    CTLTYPE_STRING | CTLFLAG_RD, sc, 5 + CIM_NUM_IBQ,
4828	    sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
4829
4830	if (chip_id(sc) > CHELSIO_T4) {
4831		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
4832		    CTLTYPE_STRING | CTLFLAG_RD, sc, 6 + CIM_NUM_IBQ,
4833		    sysctl_cim_ibq_obq, "A", "CIM OBQ 6 (SGE0-RX)");
4834
4835		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
4836		    CTLTYPE_STRING | CTLFLAG_RD, sc, 7 + CIM_NUM_IBQ,
4837		    sysctl_cim_ibq_obq, "A", "CIM OBQ 7 (SGE1-RX)");
4838	}
4839
4840	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
4841	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4842	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
4843
4844	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
4845	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4846	    sysctl_cim_qcfg, "A", "CIM queue configuration");
4847
4848	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
4849	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4850	    sysctl_cpl_stats, "A", "CPL statistics");
4851
4852	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
4853	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4854	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
4855
4856	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
4857	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4858	    sysctl_devlog, "A", "firmware's device log");
4859
4860	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
4861	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4862	    sysctl_fcoe_stats, "A", "FCoE statistics");
4863
4864	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
4865	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4866	    sysctl_hw_sched, "A", "hardware scheduler ");
4867
4868	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
4869	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4870	    sysctl_l2t, "A", "hardware L2 table");
4871
4872	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
4873	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4874	    sysctl_lb_stats, "A", "loopback statistics");
4875
4876	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
4877	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4878	    sysctl_meminfo, "A", "memory regions");
4879
4880	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
4881	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4882	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
4883	    "A", "MPS TCAM entries");
4884
4885	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
4886	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4887	    sysctl_path_mtus, "A", "path MTUs");
4888
4889	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
4890	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4891	    sysctl_pm_stats, "A", "PM statistics");
4892
4893	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
4894	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4895	    sysctl_rdma_stats, "A", "RDMA statistics");
4896
4897	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
4898	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4899	    sysctl_tcp_stats, "A", "TCP statistics");
4900
4901	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
4902	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4903	    sysctl_tids, "A", "TID information");
4904
4905	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
4906	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4907	    sysctl_tp_err_stats, "A", "TP error statistics");
4908
4909	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
4910	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tp_la_mask, "I",
4911	    "TP logic analyzer event capture mask");
4912
4913	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
4914	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4915	    sysctl_tp_la, "A", "TP logic analyzer");
4916
4917	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
4918	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4919	    sysctl_tx_rate, "A", "Tx rate");
4920
4921	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
4922	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4923	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
4924
4925	if (chip_id(sc) >= CHELSIO_T5) {
4926		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
4927		    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
4928		    sysctl_wcwr_stats, "A", "write combined work requests");
4929	}
4930#endif
4931
4932#ifdef TCP_OFFLOAD
4933	if (is_offload(sc)) {
4934		/*
4935		 * dev.t4nex.X.toe.
4936		 */
4937		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe", CTLFLAG_RD,
4938		    NULL, "TOE parameters");
4939		children = SYSCTL_CHILDREN(oid);
4940
4941		sc->tt.sndbuf = 256 * 1024;
4942		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
4943		    &sc->tt.sndbuf, 0, "max hardware send buffer size");
4944
4945		sc->tt.ddp = 0;
4946		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp", CTLFLAG_RW,
4947		    &sc->tt.ddp, 0, "DDP allowed");
4948
4949		sc->tt.indsz = G_INDICATESIZE(t4_read_reg(sc, A_TP_PARA_REG5));
4950		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "indsz", CTLFLAG_RW,
4951		    &sc->tt.indsz, 0, "DDP max indicate size allowed");
4952
4953		sc->tt.ddp_thres =
4954		    G_RXCOALESCESIZE(t4_read_reg(sc, A_TP_PARA_REG2));
4955		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp_thres", CTLFLAG_RW,
4956		    &sc->tt.ddp_thres, 0, "DDP threshold");
4957
4958		sc->tt.rx_coalesce = 1;
4959		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
4960		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
4961
4962		sc->tt.tx_align = 1;
4963		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
4964		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
4965
4966		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
4967		    CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_tp_tick, "A",
4968		    "TP timer tick (us)");
4969
4970		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
4971		    CTLTYPE_STRING | CTLFLAG_RD, sc, 1, sysctl_tp_tick, "A",
4972		    "TCP timestamp tick (us)");
4973
4974		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
4975		    CTLTYPE_STRING | CTLFLAG_RD, sc, 2, sysctl_tp_tick, "A",
4976		    "DACK tick (us)");
4977
4978		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
4979		    CTLTYPE_UINT | CTLFLAG_RD, sc, 0, sysctl_tp_dack_timer,
4980		    "IU", "DACK timer (us)");
4981
4982		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
4983		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MIN,
4984		    sysctl_tp_timer, "LU", "Retransmit min (us)");
4985
4986		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
4987		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MAX,
4988		    sysctl_tp_timer, "LU", "Retransmit max (us)");
4989
4990		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
4991		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MIN,
4992		    sysctl_tp_timer, "LU", "Persist timer min (us)");
4993
4994		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
4995		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MAX,
4996		    sysctl_tp_timer, "LU", "Persist timer max (us)");
4997
4998		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
4999		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_IDLE,
5000		    sysctl_tp_timer, "LU", "Keepidle idle timer (us)");
5001
5002		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_intvl",
5003		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_INTVL,
5004		    sysctl_tp_timer, "LU", "Keepidle interval (us)");
5005
5006		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
5007		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_INIT_SRTT,
5008		    sysctl_tp_timer, "LU", "Initial SRTT (us)");
5009
5010		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
5011		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_FINWAIT2_TIMER,
5012		    sysctl_tp_timer, "LU", "FINWAIT2 timer (us)");
5013	}
5014#endif
5015}
5016
5017void
5018vi_sysctls(struct vi_info *vi)
5019{
5020	struct sysctl_ctx_list *ctx;
5021	struct sysctl_oid *oid;
5022	struct sysctl_oid_list *children;
5023
5024	ctx = device_get_sysctl_ctx(vi->dev);
5025
5026	/*
5027	 * dev.v?(cxgbe|cxl).X.
5028	 */
5029	oid = device_get_sysctl_tree(vi->dev);
5030	children = SYSCTL_CHILDREN(oid);
5031
5032	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
5033	    vi->viid, "VI identifer");
5034	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
5035	    &vi->nrxq, 0, "# of rx queues");
5036	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
5037	    &vi->ntxq, 0, "# of tx queues");
5038	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
5039	    &vi->first_rxq, 0, "index of first rx queue");
5040	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
5041	    &vi->first_txq, 0, "index of first tx queue");
5042	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
5043	    vi->rss_size, "size of RSS indirection table");
5044
5045	if (IS_MAIN_VI(vi)) {
5046		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
5047		    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_noflowq, "IU",
5048		    "Reserve queue 0 for non-flowid packets");
5049	}
5050
5051#ifdef TCP_OFFLOAD
5052	if (vi->nofldrxq != 0) {
5053		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
5054		    &vi->nofldrxq, 0,
5055		    "# of rx queues for offloaded TCP connections");
5056		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
5057		    &vi->nofldtxq, 0,
5058		    "# of tx queues for offloaded TCP connections");
5059		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
5060		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
5061		    "index of first TOE rx queue");
5062		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
5063		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
5064		    "index of first TOE tx queue");
5065	}
5066#endif
5067#ifdef DEV_NETMAP
5068	if (vi->nnmrxq != 0) {
5069		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
5070		    &vi->nnmrxq, 0, "# of netmap rx queues");
5071		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
5072		    &vi->nnmtxq, 0, "# of netmap tx queues");
5073		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
5074		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
5075		    "index of first netmap rx queue");
5076		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
5077		    CTLFLAG_RD, &vi->first_nm_txq, 0,
5078		    "index of first netmap tx queue");
5079	}
5080#endif
5081
5082	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
5083	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_tmr_idx, "I",
5084	    "holdoff timer index");
5085	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
5086	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_pktc_idx, "I",
5087	    "holdoff packet counter index");
5088
5089	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
5090	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_rxq, "I",
5091	    "rx queue size");
5092	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
5093	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_txq, "I",
5094	    "tx queue size");
5095}
5096
5097static void
5098cxgbe_sysctls(struct port_info *pi)
5099{
5100	struct sysctl_ctx_list *ctx;
5101	struct sysctl_oid *oid;
5102	struct sysctl_oid_list *children, *children2;
5103	struct adapter *sc = pi->adapter;
5104	int i;
5105	char name[16];
5106
5107	ctx = device_get_sysctl_ctx(pi->dev);
5108
5109	/*
5110	 * dev.cxgbe.X.
5111	 */
5112	oid = device_get_sysctl_tree(pi->dev);
5113	children = SYSCTL_CHILDREN(oid);
5114
5115	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc", CTLTYPE_STRING |
5116	   CTLFLAG_RD, pi, 0, sysctl_linkdnrc, "A", "reason why link is down");
5117	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
5118		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
5119		    CTLTYPE_INT | CTLFLAG_RD, pi, 0, sysctl_btphy, "I",
5120		    "PHY temperature (in Celsius)");
5121		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
5122		    CTLTYPE_INT | CTLFLAG_RD, pi, 1, sysctl_btphy, "I",
5123		    "PHY firmware version");
5124	}
5125
5126	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
5127	    CTLTYPE_STRING | CTLFLAG_RW, pi, PAUSE_TX, sysctl_pause_settings,
5128	    "A", "PAUSE settings (bit 0 = rx_pause, bit 1 = tx_pause)");
5129
5130	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
5131	    port_top_speed(pi), "max speed (in Gbps)");
5132
5133	if (sc->flags & IS_VF)
5134		return;
5135
5136	/*
5137	 * dev.(cxgbe|cxl).X.tc.
5138	 */
5139	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc", CTLFLAG_RD, NULL,
5140	    "Tx scheduler traffic classes");
5141	for (i = 0; i < sc->chip_params->nsched_cls; i++) {
5142		struct tx_sched_class *tc = &pi->tc[i];
5143
5144		snprintf(name, sizeof(name), "%d", i);
5145		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
5146		    SYSCTL_CHILDREN(oid), OID_AUTO, name, CTLFLAG_RD, NULL,
5147		    "traffic class"));
5148		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "flags", CTLFLAG_RD,
5149		    &tc->flags, 0, "flags");
5150		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
5151		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
5152#ifdef SBUF_DRAIN
5153		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
5154		    CTLTYPE_STRING | CTLFLAG_RD, sc, (pi->port_id << 16) | i,
5155		    sysctl_tc_params, "A", "traffic class parameters");
5156#endif
5157	}
5158
5159	/*
5160	 * dev.cxgbe.X.stats.
5161	 */
5162	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats", CTLFLAG_RD,
5163	    NULL, "port statistics");
5164	children = SYSCTL_CHILDREN(oid);
5165	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
5166	    &pi->tx_parse_error, 0,
5167	    "# of tx packets with invalid length or # of segments");
5168
5169#define SYSCTL_ADD_T4_REG64(pi, name, desc, reg) \
5170	SYSCTL_ADD_OID(ctx, children, OID_AUTO, name, \
5171	    CTLTYPE_U64 | CTLFLAG_RD, sc, reg, \
5172	    sysctl_handle_t4_reg64, "QU", desc)
5173
5174	SYSCTL_ADD_T4_REG64(pi, "tx_octets", "# of octets in good frames",
5175	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BYTES_L));
5176	SYSCTL_ADD_T4_REG64(pi, "tx_frames", "total # of good frames",
5177	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_FRAMES_L));
5178	SYSCTL_ADD_T4_REG64(pi, "tx_bcast_frames", "# of broadcast frames",
5179	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BCAST_L));
5180	SYSCTL_ADD_T4_REG64(pi, "tx_mcast_frames", "# of multicast frames",
5181	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_MCAST_L));
5182	SYSCTL_ADD_T4_REG64(pi, "tx_ucast_frames", "# of unicast frames",
5183	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_UCAST_L));
5184	SYSCTL_ADD_T4_REG64(pi, "tx_error_frames", "# of error frames",
5185	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_ERROR_L));
5186	SYSCTL_ADD_T4_REG64(pi, "tx_frames_64",
5187	    "# of tx frames in this range",
5188	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_64B_L));
5189	SYSCTL_ADD_T4_REG64(pi, "tx_frames_65_127",
5190	    "# of tx frames in this range",
5191	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_65B_127B_L));
5192	SYSCTL_ADD_T4_REG64(pi, "tx_frames_128_255",
5193	    "# of tx frames in this range",
5194	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_128B_255B_L));
5195	SYSCTL_ADD_T4_REG64(pi, "tx_frames_256_511",
5196	    "# of tx frames in this range",
5197	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_256B_511B_L));
5198	SYSCTL_ADD_T4_REG64(pi, "tx_frames_512_1023",
5199	    "# of tx frames in this range",
5200	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_512B_1023B_L));
5201	SYSCTL_ADD_T4_REG64(pi, "tx_frames_1024_1518",
5202	    "# of tx frames in this range",
5203	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1024B_1518B_L));
5204	SYSCTL_ADD_T4_REG64(pi, "tx_frames_1519_max",
5205	    "# of tx frames in this range",
5206	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1519B_MAX_L));
5207	SYSCTL_ADD_T4_REG64(pi, "tx_drop", "# of dropped tx frames",
5208	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_DROP_L));
5209	SYSCTL_ADD_T4_REG64(pi, "tx_pause", "# of pause frames transmitted",
5210	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PAUSE_L));
5211	SYSCTL_ADD_T4_REG64(pi, "tx_ppp0", "# of PPP prio 0 frames transmitted",
5212	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP0_L));
5213	SYSCTL_ADD_T4_REG64(pi, "tx_ppp1", "# of PPP prio 1 frames transmitted",
5214	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP1_L));
5215	SYSCTL_ADD_T4_REG64(pi, "tx_ppp2", "# of PPP prio 2 frames transmitted",
5216	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP2_L));
5217	SYSCTL_ADD_T4_REG64(pi, "tx_ppp3", "# of PPP prio 3 frames transmitted",
5218	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP3_L));
5219	SYSCTL_ADD_T4_REG64(pi, "tx_ppp4", "# of PPP prio 4 frames transmitted",
5220	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP4_L));
5221	SYSCTL_ADD_T4_REG64(pi, "tx_ppp5", "# of PPP prio 5 frames transmitted",
5222	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP5_L));
5223	SYSCTL_ADD_T4_REG64(pi, "tx_ppp6", "# of PPP prio 6 frames transmitted",
5224	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP6_L));
5225	SYSCTL_ADD_T4_REG64(pi, "tx_ppp7", "# of PPP prio 7 frames transmitted",
5226	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP7_L));
5227
5228	SYSCTL_ADD_T4_REG64(pi, "rx_octets", "# of octets in good frames",
5229	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BYTES_L));
5230	SYSCTL_ADD_T4_REG64(pi, "rx_frames", "total # of good frames",
5231	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_FRAMES_L));
5232	SYSCTL_ADD_T4_REG64(pi, "rx_bcast_frames", "# of broadcast frames",
5233	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BCAST_L));
5234	SYSCTL_ADD_T4_REG64(pi, "rx_mcast_frames", "# of multicast frames",
5235	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MCAST_L));
5236	SYSCTL_ADD_T4_REG64(pi, "rx_ucast_frames", "# of unicast frames",
5237	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_UCAST_L));
5238	SYSCTL_ADD_T4_REG64(pi, "rx_too_long", "# of frames exceeding MTU",
5239	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_ERROR_L));
5240	SYSCTL_ADD_T4_REG64(pi, "rx_jabber", "# of jabber frames",
5241	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_CRC_ERROR_L));
5242	SYSCTL_ADD_T4_REG64(pi, "rx_fcs_err",
5243	    "# of frames received with bad FCS",
5244	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L));
5245	SYSCTL_ADD_T4_REG64(pi, "rx_len_err",
5246	    "# of frames received with length error",
5247	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LEN_ERROR_L));
5248	SYSCTL_ADD_T4_REG64(pi, "rx_symbol_err", "symbol errors",
5249	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_SYM_ERROR_L));
5250	SYSCTL_ADD_T4_REG64(pi, "rx_runt", "# of short frames received",
5251	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LESS_64B_L));
5252	SYSCTL_ADD_T4_REG64(pi, "rx_frames_64",
5253	    "# of rx frames in this range",
5254	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_64B_L));
5255	SYSCTL_ADD_T4_REG64(pi, "rx_frames_65_127",
5256	    "# of rx frames in this range",
5257	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_65B_127B_L));
5258	SYSCTL_ADD_T4_REG64(pi, "rx_frames_128_255",
5259	    "# of rx frames in this range",
5260	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_128B_255B_L));
5261	SYSCTL_ADD_T4_REG64(pi, "rx_frames_256_511",
5262	    "# of rx frames in this range",
5263	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_256B_511B_L));
5264	SYSCTL_ADD_T4_REG64(pi, "rx_frames_512_1023",
5265	    "# of rx frames in this range",
5266	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_512B_1023B_L));
5267	SYSCTL_ADD_T4_REG64(pi, "rx_frames_1024_1518",
5268	    "# of rx frames in this range",
5269	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1024B_1518B_L));
5270	SYSCTL_ADD_T4_REG64(pi, "rx_frames_1519_max",
5271	    "# of rx frames in this range",
5272	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1519B_MAX_L));
5273	SYSCTL_ADD_T4_REG64(pi, "rx_pause", "# of pause frames received",
5274	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PAUSE_L));
5275	SYSCTL_ADD_T4_REG64(pi, "rx_ppp0", "# of PPP prio 0 frames received",
5276	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP0_L));
5277	SYSCTL_ADD_T4_REG64(pi, "rx_ppp1", "# of PPP prio 1 frames received",
5278	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP1_L));
5279	SYSCTL_ADD_T4_REG64(pi, "rx_ppp2", "# of PPP prio 2 frames received",
5280	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP2_L));
5281	SYSCTL_ADD_T4_REG64(pi, "rx_ppp3", "# of PPP prio 3 frames received",
5282	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP3_L));
5283	SYSCTL_ADD_T4_REG64(pi, "rx_ppp4", "# of PPP prio 4 frames received",
5284	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP4_L));
5285	SYSCTL_ADD_T4_REG64(pi, "rx_ppp5", "# of PPP prio 5 frames received",
5286	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP5_L));
5287	SYSCTL_ADD_T4_REG64(pi, "rx_ppp6", "# of PPP prio 6 frames received",
5288	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP6_L));
5289	SYSCTL_ADD_T4_REG64(pi, "rx_ppp7", "# of PPP prio 7 frames received",
5290	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP7_L));
5291
5292#undef SYSCTL_ADD_T4_REG64
5293
5294#define SYSCTL_ADD_T4_PORTSTAT(name, desc) \
5295	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
5296	    &pi->stats.name, desc)
5297
5298	/* We get these from port_stats and they may be stale by upto 1s */
5299	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow0,
5300	    "# drops due to buffer-group 0 overflows");
5301	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow1,
5302	    "# drops due to buffer-group 1 overflows");
5303	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow2,
5304	    "# drops due to buffer-group 2 overflows");
5305	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow3,
5306	    "# drops due to buffer-group 3 overflows");
5307	SYSCTL_ADD_T4_PORTSTAT(rx_trunc0,
5308	    "# of buffer-group 0 truncated packets");
5309	SYSCTL_ADD_T4_PORTSTAT(rx_trunc1,
5310	    "# of buffer-group 1 truncated packets");
5311	SYSCTL_ADD_T4_PORTSTAT(rx_trunc2,
5312	    "# of buffer-group 2 truncated packets");
5313	SYSCTL_ADD_T4_PORTSTAT(rx_trunc3,
5314	    "# of buffer-group 3 truncated packets");
5315
5316#undef SYSCTL_ADD_T4_PORTSTAT
5317}
5318
5319static int
5320sysctl_int_array(SYSCTL_HANDLER_ARGS)
5321{
5322	int rc, *i, space = 0;
5323	struct sbuf sb;
5324
5325	sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
5326	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
5327		if (space)
5328			sbuf_printf(&sb, " ");
5329		sbuf_printf(&sb, "%d", *i);
5330		space = 1;
5331	}
5332	sbuf_finish(&sb);
5333	rc = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
5334	sbuf_delete(&sb);
5335	return (rc);
5336}
5337
5338static int
5339sysctl_bitfield(SYSCTL_HANDLER_ARGS)
5340{
5341	int rc;
5342	struct sbuf *sb;
5343
5344	rc = sysctl_wire_old_buffer(req, 0);
5345	if (rc != 0)
5346		return(rc);
5347
5348	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
5349	if (sb == NULL)
5350		return (ENOMEM);
5351
5352	sbuf_printf(sb, "%b", (int)arg2, (char *)arg1);
5353	rc = sbuf_finish(sb);
5354	sbuf_delete(sb);
5355
5356	return (rc);
5357}
5358
5359static int
5360sysctl_btphy(SYSCTL_HANDLER_ARGS)
5361{
5362	struct port_info *pi = arg1;
5363	int op = arg2;
5364	struct adapter *sc = pi->adapter;
5365	u_int v;
5366	int rc;
5367
5368	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
5369	if (rc)
5370		return (rc);
5371	/* XXX: magic numbers */
5372	rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
5373	    &v);
5374	end_synchronized_op(sc, 0);
5375	if (rc)
5376		return (rc);
5377	if (op == 0)
5378		v /= 256;
5379
5380	rc = sysctl_handle_int(oidp, &v, 0, req);
5381	return (rc);
5382}
5383
5384static int
5385sysctl_noflowq(SYSCTL_HANDLER_ARGS)
5386{
5387	struct vi_info *vi = arg1;
5388	int rc, val;
5389
5390	val = vi->rsrv_noflowq;
5391	rc = sysctl_handle_int(oidp, &val, 0, req);
5392	if (rc != 0 || req->newptr == NULL)
5393		return (rc);
5394
5395	if ((val >= 1) && (vi->ntxq > 1))
5396		vi->rsrv_noflowq = 1;
5397	else
5398		vi->rsrv_noflowq = 0;
5399
5400	return (rc);
5401}
5402
5403static int
5404sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
5405{
5406	struct vi_info *vi = arg1;
5407	struct adapter *sc = vi->pi->adapter;
5408	int idx, rc, i;
5409	struct sge_rxq *rxq;
5410#ifdef TCP_OFFLOAD
5411	struct sge_ofld_rxq *ofld_rxq;
5412#endif
5413	uint8_t v;
5414
5415	idx = vi->tmr_idx;
5416
5417	rc = sysctl_handle_int(oidp, &idx, 0, req);
5418	if (rc != 0 || req->newptr == NULL)
5419		return (rc);
5420
5421	if (idx < 0 || idx >= SGE_NTIMERS)
5422		return (EINVAL);
5423
5424	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5425	    "t4tmr");
5426	if (rc)
5427		return (rc);
5428
5429	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
5430	for_each_rxq(vi, i, rxq) {
5431#ifdef atomic_store_rel_8
5432		atomic_store_rel_8(&rxq->iq.intr_params, v);
5433#else
5434		rxq->iq.intr_params = v;
5435#endif
5436	}
5437#ifdef TCP_OFFLOAD
5438	for_each_ofld_rxq(vi, i, ofld_rxq) {
5439#ifdef atomic_store_rel_8
5440		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
5441#else
5442		ofld_rxq->iq.intr_params = v;
5443#endif
5444	}
5445#endif
5446	vi->tmr_idx = idx;
5447
5448	end_synchronized_op(sc, LOCK_HELD);
5449	return (0);
5450}
5451
5452static int
5453sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
5454{
5455	struct vi_info *vi = arg1;
5456	struct adapter *sc = vi->pi->adapter;
5457	int idx, rc;
5458
5459	idx = vi->pktc_idx;
5460
5461	rc = sysctl_handle_int(oidp, &idx, 0, req);
5462	if (rc != 0 || req->newptr == NULL)
5463		return (rc);
5464
5465	if (idx < -1 || idx >= SGE_NCOUNTERS)
5466		return (EINVAL);
5467
5468	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5469	    "t4pktc");
5470	if (rc)
5471		return (rc);
5472
5473	if (vi->flags & VI_INIT_DONE)
5474		rc = EBUSY; /* cannot be changed once the queues are created */
5475	else
5476		vi->pktc_idx = idx;
5477
5478	end_synchronized_op(sc, LOCK_HELD);
5479	return (rc);
5480}
5481
5482static int
5483sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
5484{
5485	struct vi_info *vi = arg1;
5486	struct adapter *sc = vi->pi->adapter;
5487	int qsize, rc;
5488
5489	qsize = vi->qsize_rxq;
5490
5491	rc = sysctl_handle_int(oidp, &qsize, 0, req);
5492	if (rc != 0 || req->newptr == NULL)
5493		return (rc);
5494
5495	if (qsize < 128 || (qsize & 7))
5496		return (EINVAL);
5497
5498	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5499	    "t4rxqs");
5500	if (rc)
5501		return (rc);
5502
5503	if (vi->flags & VI_INIT_DONE)
5504		rc = EBUSY; /* cannot be changed once the queues are created */
5505	else
5506		vi->qsize_rxq = qsize;
5507
5508	end_synchronized_op(sc, LOCK_HELD);
5509	return (rc);
5510}
5511
5512static int
5513sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
5514{
5515	struct vi_info *vi = arg1;
5516	struct adapter *sc = vi->pi->adapter;
5517	int qsize, rc;
5518
5519	qsize = vi->qsize_txq;
5520
5521	rc = sysctl_handle_int(oidp, &qsize, 0, req);
5522	if (rc != 0 || req->newptr == NULL)
5523		return (rc);
5524
5525	if (qsize < 128 || qsize > 65536)
5526		return (EINVAL);
5527
5528	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5529	    "t4txqs");
5530	if (rc)
5531		return (rc);
5532
5533	if (vi->flags & VI_INIT_DONE)
5534		rc = EBUSY; /* cannot be changed once the queues are created */
5535	else
5536		vi->qsize_txq = qsize;
5537
5538	end_synchronized_op(sc, LOCK_HELD);
5539	return (rc);
5540}
5541
5542static int
5543sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
5544{
5545	struct port_info *pi = arg1;
5546	struct adapter *sc = pi->adapter;
5547	struct link_config *lc = &pi->link_cfg;
5548	int rc;
5549
5550	if (req->newptr == NULL) {
5551		struct sbuf *sb;
5552		static char *bits = "\20\1PAUSE_RX\2PAUSE_TX";
5553
5554		rc = sysctl_wire_old_buffer(req, 0);
5555		if (rc != 0)
5556			return(rc);
5557
5558		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
5559		if (sb == NULL)
5560			return (ENOMEM);
5561
5562		sbuf_printf(sb, "%b", lc->fc & (PAUSE_TX | PAUSE_RX), bits);
5563		rc = sbuf_finish(sb);
5564		sbuf_delete(sb);
5565	} else {
5566		char s[2];
5567		int n;
5568
5569		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX));
5570		s[1] = 0;
5571
5572		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
5573		if (rc != 0)
5574			return(rc);
5575
5576		if (s[1] != 0)
5577			return (EINVAL);
5578		if (s[0] < '0' || s[0] > '9')
5579			return (EINVAL);	/* not a number */
5580		n = s[0] - '0';
5581		if (n & ~(PAUSE_TX | PAUSE_RX))
5582			return (EINVAL);	/* some other bit is set too */
5583
5584		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
5585		    "t4PAUSE");
5586		if (rc)
5587			return (rc);
5588		if ((lc->requested_fc & (PAUSE_TX | PAUSE_RX)) != n) {
5589			int link_ok = lc->link_ok;
5590
5591			lc->requested_fc &= ~(PAUSE_TX | PAUSE_RX);
5592			lc->requested_fc |= n;
5593			rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5594			lc->link_ok = link_ok;	/* restore */
5595		}
5596		end_synchronized_op(sc, 0);
5597	}
5598
5599	return (rc);
5600}
5601
5602static int
5603sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
5604{
5605	struct adapter *sc = arg1;
5606	int reg = arg2;
5607	uint64_t val;
5608
5609	val = t4_read_reg64(sc, reg);
5610
5611	return (sysctl_handle_64(oidp, &val, 0, req));
5612}
5613
5614static int
5615sysctl_temperature(SYSCTL_HANDLER_ARGS)
5616{
5617	struct adapter *sc = arg1;
5618	int rc, t;
5619	uint32_t param, val;
5620
5621	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
5622	if (rc)
5623		return (rc);
5624	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5625	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5626	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
5627	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5628	end_synchronized_op(sc, 0);
5629	if (rc)
5630		return (rc);
5631
5632	/* unknown is returned as 0 but we display -1 in that case */
5633	t = val == 0 ? -1 : val;
5634
5635	rc = sysctl_handle_int(oidp, &t, 0, req);
5636	return (rc);
5637}
5638
5639#ifdef SBUF_DRAIN
5640static int
5641sysctl_cctrl(SYSCTL_HANDLER_ARGS)
5642{
5643	struct adapter *sc = arg1;
5644	struct sbuf *sb;
5645	int rc, i;
5646	uint16_t incr[NMTUS][NCCTRL_WIN];
5647	static const char *dec_fac[] = {
5648		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
5649		"0.9375"
5650	};
5651
5652	rc = sysctl_wire_old_buffer(req, 0);
5653	if (rc != 0)
5654		return (rc);
5655
5656	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
5657	if (sb == NULL)
5658		return (ENOMEM);
5659
5660	t4_read_cong_tbl(sc, incr);
5661
5662	for (i = 0; i < NCCTRL_WIN; ++i) {
5663		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
5664		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
5665		    incr[5][i], incr[6][i], incr[7][i]);
5666		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
5667		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
5668		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
5669		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
5670	}
5671
5672	rc = sbuf_finish(sb);
5673	sbuf_delete(sb);
5674
5675	return (rc);
5676}
5677
5678static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
5679	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
5680	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
5681	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
5682};
5683
5684static int
5685sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
5686{
5687	struct adapter *sc = arg1;
5688	struct sbuf *sb;
5689	int rc, i, n, qid = arg2;
5690	uint32_t *buf, *p;
5691	char *qtype;
5692	u_int cim_num_obq = sc->chip_params->cim_num_obq;
5693
5694	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
5695	    ("%s: bad qid %d\n", __func__, qid));
5696
5697	if (qid < CIM_NUM_IBQ) {
5698		/* inbound queue */
5699		qtype = "IBQ";
5700		n = 4 * CIM_IBQ_SIZE;
5701		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
5702		rc = t4_read_cim_ibq(sc, qid, buf, n);
5703	} else {
5704		/* outbound queue */
5705		qtype = "OBQ";
5706		qid -= CIM_NUM_IBQ;
5707		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
5708		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
5709		rc = t4_read_cim_obq(sc, qid, buf, n);
5710	}
5711
5712	if (rc < 0) {
5713		rc = -rc;
5714		goto done;
5715	}
5716	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
5717
5718	rc = sysctl_wire_old_buffer(req, 0);
5719	if (rc != 0)
5720		goto done;
5721
5722	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
5723	if (sb == NULL) {
5724		rc = ENOMEM;
5725		goto done;
5726	}
5727
5728	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
5729	for (i = 0, p = buf; i < n; i += 16, p += 4)
5730		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
5731		    p[2], p[3]);
5732
5733	rc = sbuf_finish(sb);
5734	sbuf_delete(sb);
5735done:
5736	free(buf, M_CXGBE);
5737	return (rc);
5738}
5739
5740static int
5741sysctl_cim_la(SYSCTL_HANDLER_ARGS)
5742{
5743	struct adapter *sc = arg1;
5744	u_int cfg;
5745	struct sbuf *sb;
5746	uint32_t *buf, *p;
5747	int rc;
5748
5749	MPASS(chip_id(sc) <= CHELSIO_T5);
5750
5751	rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
5752	if (rc != 0)
5753		return (rc);
5754
5755	rc = sysctl_wire_old_buffer(req, 0);
5756	if (rc != 0)
5757		return (rc);
5758
5759	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
5760	if (sb == NULL)
5761		return (ENOMEM);
5762
5763	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
5764	    M_ZERO | M_WAITOK);
5765
5766	rc = -t4_cim_read_la(sc, buf, NULL);
5767	if (rc != 0)
5768		goto done;
5769
5770	sbuf_printf(sb, "Status   Data      PC%s",
5771	    cfg & F_UPDBGLACAPTPCONLY ? "" :
5772	    "     LS0Stat  LS0Addr             LS0Data");
5773
5774	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
5775		if (cfg & F_UPDBGLACAPTPCONLY) {
5776			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
5777			    p[6], p[7]);
5778			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
5779			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
5780			    p[4] & 0xff, p[5] >> 8);
5781			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
5782			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
5783			    p[1] & 0xf, p[2] >> 4);
5784		} else {
5785			sbuf_printf(sb,
5786			    "\n  %02x   %x%07x %x%07x %08x %08x "
5787			    "%08x%08x%08x%08x",
5788			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
5789			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
5790			    p[6], p[7]);
5791		}
5792	}
5793
5794	rc = sbuf_finish(sb);
5795	sbuf_delete(sb);
5796done:
5797	free(buf, M_CXGBE);
5798	return (rc);
5799}
5800
5801static int
5802sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS)
5803{
5804	struct adapter *sc = arg1;
5805	u_int cfg;
5806	struct sbuf *sb;
5807	uint32_t *buf, *p;
5808	int rc;
5809
5810	MPASS(chip_id(sc) > CHELSIO_T5);
5811
5812	rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
5813	if (rc != 0)
5814		return (rc);
5815
5816	rc = sysctl_wire_old_buffer(req, 0);
5817	if (rc != 0)
5818		return (rc);
5819
5820	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
5821	if (sb == NULL)
5822		return (ENOMEM);
5823
5824	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
5825	    M_ZERO | M_WAITOK);
5826
5827	rc = -t4_cim_read_la(sc, buf, NULL);
5828	if (rc != 0)
5829		goto done;
5830
5831	sbuf_printf(sb, "Status   Inst    Data      PC%s",
5832	    cfg & F_UPDBGLACAPTPCONLY ? "" :
5833	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
5834
5835	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
5836		if (cfg & F_UPDBGLACAPTPCONLY) {
5837			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
5838			    p[3] & 0xff, p[2], p[1], p[0]);
5839			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
5840			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
5841			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
5842			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
5843			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
5844			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
5845			    p[6] >> 16);
5846		} else {
5847			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
5848			    "%08x %08x %08x %08x %08x %08x",
5849			    (p[9] >> 16) & 0xff,
5850			    p[9] & 0xffff, p[8] >> 16,
5851			    p[8] & 0xffff, p[7] >> 16,
5852			    p[7] & 0xffff, p[6] >> 16,
5853			    p[2], p[1], p[0], p[5], p[4], p[3]);
5854		}
5855	}
5856
5857	rc = sbuf_finish(sb);
5858	sbuf_delete(sb);
5859done:
5860	free(buf, M_CXGBE);
5861	return (rc);
5862}
5863
5864static int
5865sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
5866{
5867	struct adapter *sc = arg1;
5868	u_int i;
5869	struct sbuf *sb;
5870	uint32_t *buf, *p;
5871	int rc;
5872
5873	rc = sysctl_wire_old_buffer(req, 0);
5874	if (rc != 0)
5875		return (rc);
5876
5877	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
5878	if (sb == NULL)
5879		return (ENOMEM);
5880
5881	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
5882	    M_ZERO | M_WAITOK);
5883
5884	t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
5885	p = buf;
5886
5887	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
5888		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
5889		    p[1], p[0]);
5890	}
5891
5892	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
5893	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
5894		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
5895		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
5896		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
5897		    (p[1] >> 2) | ((p[2] & 3) << 30),
5898		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
5899		    p[0] & 1);
5900	}
5901
5902	rc = sbuf_finish(sb);
5903	sbuf_delete(sb);
5904	free(buf, M_CXGBE);
5905	return (rc);
5906}
5907
5908static int
5909sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
5910{
5911	struct adapter *sc = arg1;
5912	u_int i;
5913	struct sbuf *sb;
5914	uint32_t *buf, *p;
5915	int rc;
5916
5917	rc = sysctl_wire_old_buffer(req, 0);
5918	if (rc != 0)
5919		return (rc);
5920
5921	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
5922	if (sb == NULL)
5923		return (ENOMEM);
5924
5925	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
5926	    M_ZERO | M_WAITOK);
5927
5928	t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
5929	p = buf;
5930
5931	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
5932	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
5933		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
5934		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
5935		    p[4], p[3], p[2], p[1], p[0]);
5936	}
5937
5938	sbuf_printf(sb, "\n\nCntl ID               Data");
5939	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
5940		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
5941		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
5942	}
5943
5944	rc = sbuf_finish(sb);
5945	sbuf_delete(sb);
5946	free(buf, M_CXGBE);
5947	return (rc);
5948}
5949
5950static int
5951sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
5952{
5953	struct adapter *sc = arg1;
5954	struct sbuf *sb;
5955	int rc, i;
5956	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
5957	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
5958	uint16_t thres[CIM_NUM_IBQ];
5959	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
5960	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
5961	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
5962
5963	cim_num_obq = sc->chip_params->cim_num_obq;
5964	if (is_t4(sc)) {
5965		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
5966		obq_rdaddr = A_UP_OBQ_0_REALADDR;
5967	} else {
5968		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
5969		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
5970	}
5971	nq = CIM_NUM_IBQ + cim_num_obq;
5972
5973	rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
5974	if (rc == 0)
5975		rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
5976	if (rc != 0)
5977		return (rc);
5978
5979	t4_read_cimq_cfg(sc, base, size, thres);
5980
5981	rc = sysctl_wire_old_buffer(req, 0);
5982	if (rc != 0)
5983		return (rc);
5984
5985	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
5986	if (sb == NULL)
5987		return (ENOMEM);
5988
5989	sbuf_printf(sb,
5990	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
5991
5992	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
5993		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
5994		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
5995		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
5996		    G_QUEREMFLITS(p[2]) * 16);
5997	for ( ; i < nq; i++, p += 4, wr += 2)
5998		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
5999		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
6000		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
6001		    G_QUEREMFLITS(p[2]) * 16);
6002
6003	rc = sbuf_finish(sb);
6004	sbuf_delete(sb);
6005
6006	return (rc);
6007}
6008
6009static int
6010sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
6011{
6012	struct adapter *sc = arg1;
6013	struct sbuf *sb;
6014	int rc;
6015	struct tp_cpl_stats stats;
6016
6017	rc = sysctl_wire_old_buffer(req, 0);
6018	if (rc != 0)
6019		return (rc);
6020
6021	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6022	if (sb == NULL)
6023		return (ENOMEM);
6024
6025	mtx_lock(&sc->reg_lock);
6026	t4_tp_get_cpl_stats(sc, &stats);
6027	mtx_unlock(&sc->reg_lock);
6028
6029	if (sc->chip_params->nchan > 2) {
6030		sbuf_printf(sb, "                 channel 0  channel 1"
6031		    "  channel 2  channel 3");
6032		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
6033		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
6034		sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
6035		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
6036	} else {
6037		sbuf_printf(sb, "                 channel 0  channel 1");
6038		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
6039		    stats.req[0], stats.req[1]);
6040		sbuf_printf(sb, "\nCPL responses:   %10u %10u",
6041		    stats.rsp[0], stats.rsp[1]);
6042	}
6043
6044	rc = sbuf_finish(sb);
6045	sbuf_delete(sb);
6046
6047	return (rc);
6048}
6049
6050static int
6051sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
6052{
6053	struct adapter *sc = arg1;
6054	struct sbuf *sb;
6055	int rc;
6056	struct tp_usm_stats stats;
6057
6058	rc = sysctl_wire_old_buffer(req, 0);
6059	if (rc != 0)
6060		return(rc);
6061
6062	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6063	if (sb == NULL)
6064		return (ENOMEM);
6065
6066	t4_get_usm_stats(sc, &stats);
6067
6068	sbuf_printf(sb, "Frames: %u\n", stats.frames);
6069	sbuf_printf(sb, "Octets: %ju\n", stats.octets);
6070	sbuf_printf(sb, "Drops:  %u", stats.drops);
6071
6072	rc = sbuf_finish(sb);
6073	sbuf_delete(sb);
6074
6075	return (rc);
6076}
6077
6078static const char * const devlog_level_strings[] = {
6079	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
6080	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
6081	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
6082	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
6083	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
6084	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
6085};
6086
6087static const char * const devlog_facility_strings[] = {
6088	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
6089	[FW_DEVLOG_FACILITY_CF]		= "CF",
6090	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
6091	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
6092	[FW_DEVLOG_FACILITY_RES]	= "RES",
6093	[FW_DEVLOG_FACILITY_HW]		= "HW",
6094	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
6095	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
6096	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
6097	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
6098	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
6099	[FW_DEVLOG_FACILITY_VI]		= "VI",
6100	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
6101	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
6102	[FW_DEVLOG_FACILITY_TM]		= "TM",
6103	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
6104	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
6105	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
6106	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
6107	[FW_DEVLOG_FACILITY_RI]		= "RI",
6108	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
6109	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
6110	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
6111	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
6112	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
6113};
6114
6115static int
6116sysctl_devlog(SYSCTL_HANDLER_ARGS)
6117{
6118	struct adapter *sc = arg1;
6119	struct devlog_params *dparams = &sc->params.devlog;
6120	struct fw_devlog_e *buf, *e;
6121	int i, j, rc, nentries, first = 0;
6122	struct sbuf *sb;
6123	uint64_t ftstamp = UINT64_MAX;
6124
6125	if (dparams->addr == 0)
6126		return (ENXIO);
6127
6128	buf = malloc(dparams->size, M_CXGBE, M_NOWAIT);
6129	if (buf == NULL)
6130		return (ENOMEM);
6131
6132	rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
6133	if (rc != 0)
6134		goto done;
6135
6136	nentries = dparams->size / sizeof(struct fw_devlog_e);
6137	for (i = 0; i < nentries; i++) {
6138		e = &buf[i];
6139
6140		if (e->timestamp == 0)
6141			break;	/* end */
6142
6143		e->timestamp = be64toh(e->timestamp);
6144		e->seqno = be32toh(e->seqno);
6145		for (j = 0; j < 8; j++)
6146			e->params[j] = be32toh(e->params[j]);
6147
6148		if (e->timestamp < ftstamp) {
6149			ftstamp = e->timestamp;
6150			first = i;
6151		}
6152	}
6153
6154	if (buf[first].timestamp == 0)
6155		goto done;	/* nothing in the log */
6156
6157	rc = sysctl_wire_old_buffer(req, 0);
6158	if (rc != 0)
6159		goto done;
6160
6161	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6162	if (sb == NULL) {
6163		rc = ENOMEM;
6164		goto done;
6165	}
6166	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
6167	    "Seq#", "Tstamp", "Level", "Facility", "Message");
6168
6169	i = first;
6170	do {
6171		e = &buf[i];
6172		if (e->timestamp == 0)
6173			break;	/* end */
6174
6175		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
6176		    e->seqno, e->timestamp,
6177		    (e->level < nitems(devlog_level_strings) ?
6178			devlog_level_strings[e->level] : "UNKNOWN"),
6179		    (e->facility < nitems(devlog_facility_strings) ?
6180			devlog_facility_strings[e->facility] : "UNKNOWN"));
6181		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
6182		    e->params[2], e->params[3], e->params[4],
6183		    e->params[5], e->params[6], e->params[7]);
6184
6185		if (++i == nentries)
6186			i = 0;
6187	} while (i != first);
6188
6189	rc = sbuf_finish(sb);
6190	sbuf_delete(sb);
6191done:
6192	free(buf, M_CXGBE);
6193	return (rc);
6194}
6195
6196static int
6197sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
6198{
6199	struct adapter *sc = arg1;
6200	struct sbuf *sb;
6201	int rc;
6202	struct tp_fcoe_stats stats[MAX_NCHAN];
6203	int i, nchan = sc->chip_params->nchan;
6204
6205	rc = sysctl_wire_old_buffer(req, 0);
6206	if (rc != 0)
6207		return (rc);
6208
6209	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6210	if (sb == NULL)
6211		return (ENOMEM);
6212
6213	for (i = 0; i < nchan; i++)
6214		t4_get_fcoe_stats(sc, i, &stats[i]);
6215
6216	if (nchan > 2) {
6217		sbuf_printf(sb, "                   channel 0        channel 1"
6218		    "        channel 2        channel 3");
6219		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
6220		    stats[0].octets_ddp, stats[1].octets_ddp,
6221		    stats[2].octets_ddp, stats[3].octets_ddp);
6222		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
6223		    stats[0].frames_ddp, stats[1].frames_ddp,
6224		    stats[2].frames_ddp, stats[3].frames_ddp);
6225		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
6226		    stats[0].frames_drop, stats[1].frames_drop,
6227		    stats[2].frames_drop, stats[3].frames_drop);
6228	} else {
6229		sbuf_printf(sb, "                   channel 0        channel 1");
6230		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
6231		    stats[0].octets_ddp, stats[1].octets_ddp);
6232		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
6233		    stats[0].frames_ddp, stats[1].frames_ddp);
6234		sbuf_printf(sb, "\nframesDrop: %16u %16u",
6235		    stats[0].frames_drop, stats[1].frames_drop);
6236	}
6237
6238	rc = sbuf_finish(sb);
6239	sbuf_delete(sb);
6240
6241	return (rc);
6242}
6243
6244static int
6245sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
6246{
6247	struct adapter *sc = arg1;
6248	struct sbuf *sb;
6249	int rc, i;
6250	unsigned int map, kbps, ipg, mode;
6251	unsigned int pace_tab[NTX_SCHED];
6252
6253	rc = sysctl_wire_old_buffer(req, 0);
6254	if (rc != 0)
6255		return (rc);
6256
6257	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6258	if (sb == NULL)
6259		return (ENOMEM);
6260
6261	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
6262	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
6263	t4_read_pace_tbl(sc, pace_tab);
6264
6265	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
6266	    "Class IPG (0.1 ns)   Flow IPG (us)");
6267
6268	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
6269		t4_get_tx_sched(sc, i, &kbps, &ipg);
6270		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
6271		    (mode & (1 << i)) ? "flow" : "class", map & 3);
6272		if (kbps)
6273			sbuf_printf(sb, "%9u     ", kbps);
6274		else
6275			sbuf_printf(sb, " disabled     ");
6276
6277		if (ipg)
6278			sbuf_printf(sb, "%13u        ", ipg);
6279		else
6280			sbuf_printf(sb, "     disabled        ");
6281
6282		if (pace_tab[i])
6283			sbuf_printf(sb, "%10u", pace_tab[i]);
6284		else
6285			sbuf_printf(sb, "  disabled");
6286	}
6287
6288	rc = sbuf_finish(sb);
6289	sbuf_delete(sb);
6290
6291	return (rc);
6292}
6293
6294static int
6295sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
6296{
6297	struct adapter *sc = arg1;
6298	struct sbuf *sb;
6299	int rc, i, j;
6300	uint64_t *p0, *p1;
6301	struct lb_port_stats s[2];
6302	static const char *stat_name[] = {
6303		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
6304		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
6305		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
6306		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
6307		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
6308		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
6309		"BG2FramesTrunc:", "BG3FramesTrunc:"
6310	};
6311
6312	rc = sysctl_wire_old_buffer(req, 0);
6313	if (rc != 0)
6314		return (rc);
6315
6316	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6317	if (sb == NULL)
6318		return (ENOMEM);
6319
6320	memset(s, 0, sizeof(s));
6321
6322	for (i = 0; i < sc->chip_params->nchan; i += 2) {
6323		t4_get_lb_stats(sc, i, &s[0]);
6324		t4_get_lb_stats(sc, i + 1, &s[1]);
6325
6326		p0 = &s[0].octets;
6327		p1 = &s[1].octets;
6328		sbuf_printf(sb, "%s                       Loopback %u"
6329		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
6330
6331		for (j = 0; j < nitems(stat_name); j++)
6332			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
6333				   *p0++, *p1++);
6334	}
6335
6336	rc = sbuf_finish(sb);
6337	sbuf_delete(sb);
6338
6339	return (rc);
6340}
6341
6342static int
6343sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
6344{
6345	int rc = 0;
6346	struct port_info *pi = arg1;
6347	struct sbuf *sb;
6348
6349	rc = sysctl_wire_old_buffer(req, 0);
6350	if (rc != 0)
6351		return(rc);
6352	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
6353	if (sb == NULL)
6354		return (ENOMEM);
6355
6356	if (pi->linkdnrc < 0)
6357		sbuf_printf(sb, "n/a");
6358	else
6359		sbuf_printf(sb, "%s", t4_link_down_rc_str(pi->linkdnrc));
6360
6361	rc = sbuf_finish(sb);
6362	sbuf_delete(sb);
6363
6364	return (rc);
6365}
6366
6367struct mem_desc {
6368	unsigned int base;
6369	unsigned int limit;
6370	unsigned int idx;
6371};
6372
6373static int
6374mem_desc_cmp(const void *a, const void *b)
6375{
6376	return ((const struct mem_desc *)a)->base -
6377	       ((const struct mem_desc *)b)->base;
6378}
6379
6380static void
6381mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
6382    unsigned int to)
6383{
6384	unsigned int size;
6385
6386	if (from == to)
6387		return;
6388
6389	size = to - from + 1;
6390	if (size == 0)
6391		return;
6392
6393	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
6394	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
6395}
6396
6397static int
6398sysctl_meminfo(SYSCTL_HANDLER_ARGS)
6399{
6400	struct adapter *sc = arg1;
6401	struct sbuf *sb;
6402	int rc, i, n;
6403	uint32_t lo, hi, used, alloc;
6404	static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
6405	static const char *region[] = {
6406		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
6407		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
6408		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
6409		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
6410		"RQUDP region:", "PBL region:", "TXPBL region:",
6411		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
6412		"On-chip queues:"
6413	};
6414	struct mem_desc avail[4];
6415	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
6416	struct mem_desc *md = mem;
6417
6418	rc = sysctl_wire_old_buffer(req, 0);
6419	if (rc != 0)
6420		return (rc);
6421
6422	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6423	if (sb == NULL)
6424		return (ENOMEM);
6425
6426	for (i = 0; i < nitems(mem); i++) {
6427		mem[i].limit = 0;
6428		mem[i].idx = i;
6429	}
6430
6431	/* Find and sort the populated memory ranges */
6432	i = 0;
6433	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
6434	if (lo & F_EDRAM0_ENABLE) {
6435		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
6436		avail[i].base = G_EDRAM0_BASE(hi) << 20;
6437		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
6438		avail[i].idx = 0;
6439		i++;
6440	}
6441	if (lo & F_EDRAM1_ENABLE) {
6442		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
6443		avail[i].base = G_EDRAM1_BASE(hi) << 20;
6444		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
6445		avail[i].idx = 1;
6446		i++;
6447	}
6448	if (lo & F_EXT_MEM_ENABLE) {
6449		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
6450		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
6451		avail[i].limit = avail[i].base +
6452		    (G_EXT_MEM_SIZE(hi) << 20);
6453		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
6454		i++;
6455	}
6456	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
6457		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
6458		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
6459		avail[i].limit = avail[i].base +
6460		    (G_EXT_MEM1_SIZE(hi) << 20);
6461		avail[i].idx = 4;
6462		i++;
6463	}
6464	if (!i)                                    /* no memory available */
6465		return 0;
6466	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
6467
6468	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
6469	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
6470	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
6471	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
6472	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
6473	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
6474	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
6475	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
6476	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
6477
6478	/* the next few have explicit upper bounds */
6479	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
6480	md->limit = md->base - 1 +
6481		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
6482		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
6483	md++;
6484
6485	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
6486	md->limit = md->base - 1 +
6487		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
6488		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
6489	md++;
6490
6491	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
6492		if (chip_id(sc) <= CHELSIO_T5)
6493			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
6494		else
6495			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
6496		md->limit = 0;
6497	} else {
6498		md->base = 0;
6499		md->idx = nitems(region);  /* hide it */
6500	}
6501	md++;
6502
6503#define ulp_region(reg) \
6504	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
6505	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
6506
6507	ulp_region(RX_ISCSI);
6508	ulp_region(RX_TDDP);
6509	ulp_region(TX_TPT);
6510	ulp_region(RX_STAG);
6511	ulp_region(RX_RQ);
6512	ulp_region(RX_RQUDP);
6513	ulp_region(RX_PBL);
6514	ulp_region(TX_PBL);
6515#undef ulp_region
6516
6517	md->base = 0;
6518	md->idx = nitems(region);
6519	if (!is_t4(sc)) {
6520		uint32_t size = 0;
6521		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
6522		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
6523
6524		if (is_t5(sc)) {
6525			if (sge_ctrl & F_VFIFO_ENABLE)
6526				size = G_DBVFIFO_SIZE(fifo_size);
6527		} else
6528			size = G_T6_DBVFIFO_SIZE(fifo_size);
6529
6530		if (size) {
6531			md->base = G_BASEADDR(t4_read_reg(sc,
6532			    A_SGE_DBVFIFO_BADDR));
6533			md->limit = md->base + (size << 2) - 1;
6534		}
6535	}
6536	md++;
6537
6538	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
6539	md->limit = 0;
6540	md++;
6541	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
6542	md->limit = 0;
6543	md++;
6544
6545	md->base = sc->vres.ocq.start;
6546	if (sc->vres.ocq.size)
6547		md->limit = md->base + sc->vres.ocq.size - 1;
6548	else
6549		md->idx = nitems(region);  /* hide it */
6550	md++;
6551
6552	/* add any address-space holes, there can be up to 3 */
6553	for (n = 0; n < i - 1; n++)
6554		if (avail[n].limit < avail[n + 1].base)
6555			(md++)->base = avail[n].limit;
6556	if (avail[n].limit)
6557		(md++)->base = avail[n].limit;
6558
6559	n = md - mem;
6560	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
6561
6562	for (lo = 0; lo < i; lo++)
6563		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
6564				avail[lo].limit - 1);
6565
6566	sbuf_printf(sb, "\n");
6567	for (i = 0; i < n; i++) {
6568		if (mem[i].idx >= nitems(region))
6569			continue;                        /* skip holes */
6570		if (!mem[i].limit)
6571			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
6572		mem_region_show(sb, region[mem[i].idx], mem[i].base,
6573				mem[i].limit);
6574	}
6575
6576	sbuf_printf(sb, "\n");
6577	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
6578	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
6579	mem_region_show(sb, "uP RAM:", lo, hi);
6580
6581	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
6582	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
6583	mem_region_show(sb, "uP Extmem2:", lo, hi);
6584
6585	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
6586	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
6587		   G_PMRXMAXPAGE(lo),
6588		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
6589		   (lo & F_PMRXNUMCHN) ? 2 : 1);
6590
6591	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
6592	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
6593	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
6594		   G_PMTXMAXPAGE(lo),
6595		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
6596		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
6597	sbuf_printf(sb, "%u p-structs\n",
6598		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
6599
6600	for (i = 0; i < 4; i++) {
6601		if (chip_id(sc) > CHELSIO_T5)
6602			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
6603		else
6604			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
6605		if (is_t5(sc)) {
6606			used = G_T5_USED(lo);
6607			alloc = G_T5_ALLOC(lo);
6608		} else {
6609			used = G_USED(lo);
6610			alloc = G_ALLOC(lo);
6611		}
6612		/* For T6 these are MAC buffer groups */
6613		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
6614		    i, used, alloc);
6615	}
6616	for (i = 0; i < sc->chip_params->nchan; i++) {
6617		if (chip_id(sc) > CHELSIO_T5)
6618			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
6619		else
6620			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
6621		if (is_t5(sc)) {
6622			used = G_T5_USED(lo);
6623			alloc = G_T5_ALLOC(lo);
6624		} else {
6625			used = G_USED(lo);
6626			alloc = G_ALLOC(lo);
6627		}
6628		/* For T6 these are MAC buffer groups */
6629		sbuf_printf(sb,
6630		    "\nLoopback %d using %u pages out of %u allocated",
6631		    i, used, alloc);
6632	}
6633
6634	rc = sbuf_finish(sb);
6635	sbuf_delete(sb);
6636
6637	return (rc);
6638}
6639
6640static inline void
6641tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
6642{
6643	*mask = x | y;
6644	y = htobe64(y);
6645	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
6646}
6647
6648static int
6649sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
6650{
6651	struct adapter *sc = arg1;
6652	struct sbuf *sb;
6653	int rc, i;
6654
6655	MPASS(chip_id(sc) <= CHELSIO_T5);
6656
6657	rc = sysctl_wire_old_buffer(req, 0);
6658	if (rc != 0)
6659		return (rc);
6660
6661	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6662	if (sb == NULL)
6663		return (ENOMEM);
6664
6665	sbuf_printf(sb,
6666	    "Idx  Ethernet address     Mask     Vld Ports PF"
6667	    "  VF              Replication             P0 P1 P2 P3  ML");
6668	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
6669		uint64_t tcamx, tcamy, mask;
6670		uint32_t cls_lo, cls_hi;
6671		uint8_t addr[ETHER_ADDR_LEN];
6672
6673		tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
6674		tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
6675		if (tcamx & tcamy)
6676			continue;
6677		tcamxy2valmask(tcamx, tcamy, addr, &mask);
6678		cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
6679		cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
6680		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
6681			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
6682			   addr[3], addr[4], addr[5], (uintmax_t)mask,
6683			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
6684			   G_PORTMAP(cls_hi), G_PF(cls_lo),
6685			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
6686
6687		if (cls_lo & F_REPLICATE) {
6688			struct fw_ldst_cmd ldst_cmd;
6689
6690			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
6691			ldst_cmd.op_to_addrspace =
6692			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
6693				F_FW_CMD_REQUEST | F_FW_CMD_READ |
6694				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
6695			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
6696			ldst_cmd.u.mps.rplc.fid_idx =
6697			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
6698				V_FW_LDST_CMD_IDX(i));
6699
6700			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
6701			    "t4mps");
6702			if (rc)
6703				break;
6704			rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
6705			    sizeof(ldst_cmd), &ldst_cmd);
6706			end_synchronized_op(sc, 0);
6707
6708			if (rc != 0) {
6709				sbuf_printf(sb, "%36d", rc);
6710				rc = 0;
6711			} else {
6712				sbuf_printf(sb, " %08x %08x %08x %08x",
6713				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
6714				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
6715				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
6716				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
6717			}
6718		} else
6719			sbuf_printf(sb, "%36s", "");
6720
6721		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
6722		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
6723		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
6724	}
6725
6726	if (rc)
6727		(void) sbuf_finish(sb);
6728	else
6729		rc = sbuf_finish(sb);
6730	sbuf_delete(sb);
6731
6732	return (rc);
6733}
6734
6735static int
6736sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
6737{
6738	struct adapter *sc = arg1;
6739	struct sbuf *sb;
6740	int rc, i;
6741
6742	MPASS(chip_id(sc) > CHELSIO_T5);
6743
6744	rc = sysctl_wire_old_buffer(req, 0);
6745	if (rc != 0)
6746		return (rc);
6747
6748	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6749	if (sb == NULL)
6750		return (ENOMEM);
6751
6752	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
6753	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
6754	    "                           Replication"
6755	    "                                    P0 P1 P2 P3  ML\n");
6756
6757	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
6758		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
6759		uint16_t ivlan;
6760		uint64_t tcamx, tcamy, val, mask;
6761		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
6762		uint8_t addr[ETHER_ADDR_LEN];
6763
6764		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
6765		if (i < 256)
6766			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
6767		else
6768			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
6769		t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
6770		val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
6771		tcamy = G_DMACH(val) << 32;
6772		tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
6773		data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
6774		lookup_type = G_DATALKPTYPE(data2);
6775		port_num = G_DATAPORTNUM(data2);
6776		if (lookup_type && lookup_type != M_DATALKPTYPE) {
6777			/* Inner header VNI */
6778			vniy = ((data2 & F_DATAVIDH2) << 23) |
6779				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
6780			dip_hit = data2 & F_DATADIPHIT;
6781			vlan_vld = 0;
6782		} else {
6783			vniy = 0;
6784			dip_hit = 0;
6785			vlan_vld = data2 & F_DATAVIDH2;
6786			ivlan = G_VIDL(val);
6787		}
6788
6789		ctl |= V_CTLXYBITSEL(1);
6790		t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
6791		val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
6792		tcamx = G_DMACH(val) << 32;
6793		tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
6794		data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
6795		if (lookup_type && lookup_type != M_DATALKPTYPE) {
6796			/* Inner header VNI mask */
6797			vnix = ((data2 & F_DATAVIDH2) << 23) |
6798			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
6799		} else
6800			vnix = 0;
6801
6802		if (tcamx & tcamy)
6803			continue;
6804		tcamxy2valmask(tcamx, tcamy, addr, &mask);
6805
6806		cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
6807		cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
6808
6809		if (lookup_type && lookup_type != M_DATALKPTYPE) {
6810			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
6811			    "%012jx %06x %06x    -    -   %3c"
6812			    "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
6813			    addr[1], addr[2], addr[3], addr[4], addr[5],
6814			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
6815			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
6816			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
6817			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
6818		} else {
6819			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
6820			    "%012jx    -       -   ", i, addr[0], addr[1],
6821			    addr[2], addr[3], addr[4], addr[5],
6822			    (uintmax_t)mask);
6823
6824			if (vlan_vld)
6825				sbuf_printf(sb, "%4u   Y     ", ivlan);
6826			else
6827				sbuf_printf(sb, "  -    N     ");
6828
6829			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
6830			    lookup_type ? 'I' : 'O', port_num,
6831			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
6832			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
6833			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
6834		}
6835
6836
6837		if (cls_lo & F_T6_REPLICATE) {
6838			struct fw_ldst_cmd ldst_cmd;
6839
6840			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
6841			ldst_cmd.op_to_addrspace =
6842			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
6843				F_FW_CMD_REQUEST | F_FW_CMD_READ |
6844				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
6845			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
6846			ldst_cmd.u.mps.rplc.fid_idx =
6847			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
6848				V_FW_LDST_CMD_IDX(i));
6849
6850			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
6851			    "t6mps");
6852			if (rc)
6853				break;
6854			rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
6855			    sizeof(ldst_cmd), &ldst_cmd);
6856			end_synchronized_op(sc, 0);
6857
6858			if (rc != 0) {
6859				sbuf_printf(sb, "%72d", rc);
6860				rc = 0;
6861			} else {
6862				sbuf_printf(sb, " %08x %08x %08x %08x"
6863				    " %08x %08x %08x %08x",
6864				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
6865				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
6866				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
6867				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
6868				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
6869				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
6870				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
6871				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
6872			}
6873		} else
6874			sbuf_printf(sb, "%72s", "");
6875
6876		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
6877		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
6878		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
6879		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
6880	}
6881
6882	if (rc)
6883		(void) sbuf_finish(sb);
6884	else
6885		rc = sbuf_finish(sb);
6886	sbuf_delete(sb);
6887
6888	return (rc);
6889}
6890
6891static int
6892sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
6893{
6894	struct adapter *sc = arg1;
6895	struct sbuf *sb;
6896	int rc;
6897	uint16_t mtus[NMTUS];
6898
6899	rc = sysctl_wire_old_buffer(req, 0);
6900	if (rc != 0)
6901		return (rc);
6902
6903	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6904	if (sb == NULL)
6905		return (ENOMEM);
6906
6907	t4_read_mtu_tbl(sc, mtus, NULL);
6908
6909	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
6910	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
6911	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
6912	    mtus[14], mtus[15]);
6913
6914	rc = sbuf_finish(sb);
6915	sbuf_delete(sb);
6916
6917	return (rc);
6918}
6919
6920static int
6921sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
6922{
6923	struct adapter *sc = arg1;
6924	struct sbuf *sb;
6925	int rc, i;
6926	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
6927	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
6928	static const char *tx_stats[MAX_PM_NSTATS] = {
6929		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
6930		"Tx FIFO wait", NULL, "Tx latency"
6931	};
6932	static const char *rx_stats[MAX_PM_NSTATS] = {
6933		"Read:", "Write bypass:", "Write mem:", "Flush:",
6934		"Rx FIFO wait", NULL, "Rx latency"
6935	};
6936
6937	rc = sysctl_wire_old_buffer(req, 0);
6938	if (rc != 0)
6939		return (rc);
6940
6941	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6942	if (sb == NULL)
6943		return (ENOMEM);
6944
6945	t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
6946	t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
6947
6948	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
6949	for (i = 0; i < 4; i++) {
6950		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
6951		    tx_cyc[i]);
6952	}
6953
6954	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
6955	for (i = 0; i < 4; i++) {
6956		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
6957		    rx_cyc[i]);
6958	}
6959
6960	if (chip_id(sc) > CHELSIO_T5) {
6961		sbuf_printf(sb,
6962		    "\n              Total wait      Total occupancy");
6963		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
6964		    tx_cyc[i]);
6965		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
6966		    rx_cyc[i]);
6967
6968		i += 2;
6969		MPASS(i < nitems(tx_stats));
6970
6971		sbuf_printf(sb,
6972		    "\n                   Reads           Total wait");
6973		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
6974		    tx_cyc[i]);
6975		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
6976		    rx_cyc[i]);
6977	}
6978
6979	rc = sbuf_finish(sb);
6980	sbuf_delete(sb);
6981
6982	return (rc);
6983}
6984
6985static int
6986sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
6987{
6988	struct adapter *sc = arg1;
6989	struct sbuf *sb;
6990	int rc;
6991	struct tp_rdma_stats stats;
6992
6993	rc = sysctl_wire_old_buffer(req, 0);
6994	if (rc != 0)
6995		return (rc);
6996
6997	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6998	if (sb == NULL)
6999		return (ENOMEM);
7000
7001	mtx_lock(&sc->reg_lock);
7002	t4_tp_get_rdma_stats(sc, &stats);
7003	mtx_unlock(&sc->reg_lock);
7004
7005	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
7006	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
7007
7008	rc = sbuf_finish(sb);
7009	sbuf_delete(sb);
7010
7011	return (rc);
7012}
7013
7014static int
7015sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
7016{
7017	struct adapter *sc = arg1;
7018	struct sbuf *sb;
7019	int rc;
7020	struct tp_tcp_stats v4, v6;
7021
7022	rc = sysctl_wire_old_buffer(req, 0);
7023	if (rc != 0)
7024		return (rc);
7025
7026	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7027	if (sb == NULL)
7028		return (ENOMEM);
7029
7030	mtx_lock(&sc->reg_lock);
7031	t4_tp_get_tcp_stats(sc, &v4, &v6);
7032	mtx_unlock(&sc->reg_lock);
7033
7034	sbuf_printf(sb,
7035	    "                                IP                 IPv6\n");
7036	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
7037	    v4.tcp_out_rsts, v6.tcp_out_rsts);
7038	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
7039	    v4.tcp_in_segs, v6.tcp_in_segs);
7040	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
7041	    v4.tcp_out_segs, v6.tcp_out_segs);
7042	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
7043	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
7044
7045	rc = sbuf_finish(sb);
7046	sbuf_delete(sb);
7047
7048	return (rc);
7049}
7050
7051static int
7052sysctl_tids(SYSCTL_HANDLER_ARGS)
7053{
7054	struct adapter *sc = arg1;
7055	struct sbuf *sb;
7056	int rc;
7057	struct tid_info *t = &sc->tids;
7058
7059	rc = sysctl_wire_old_buffer(req, 0);
7060	if (rc != 0)
7061		return (rc);
7062
7063	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7064	if (sb == NULL)
7065		return (ENOMEM);
7066
7067	if (t->natids) {
7068		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
7069		    t->atids_in_use);
7070	}
7071
7072	if (t->ntids) {
7073		if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
7074			uint32_t b;
7075
7076			if (chip_id(sc) <= CHELSIO_T5)
7077				b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
7078			else
7079				b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
7080
7081			if (b) {
7082				sbuf_printf(sb, "TID range: 0-%u, %u-%u", b - 1,
7083				    t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4,
7084				    t->ntids - 1);
7085			} else {
7086				sbuf_printf(sb, "TID range: %u-%u",
7087				    t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4,
7088				    t->ntids - 1);
7089			}
7090		} else
7091			sbuf_printf(sb, "TID range: 0-%u", t->ntids - 1);
7092		sbuf_printf(sb, ", in use: %u\n",
7093		    atomic_load_acq_int(&t->tids_in_use));
7094	}
7095
7096	if (t->nstids) {
7097		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
7098		    t->stid_base + t->nstids - 1, t->stids_in_use);
7099	}
7100
7101	if (t->nftids) {
7102		sbuf_printf(sb, "FTID range: %u-%u\n", t->ftid_base,
7103		    t->ftid_base + t->nftids - 1);
7104	}
7105
7106	if (t->netids) {
7107		sbuf_printf(sb, "ETID range: %u-%u\n", t->etid_base,
7108		    t->etid_base + t->netids - 1);
7109	}
7110
7111	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
7112	    t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
7113	    t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
7114
7115	rc = sbuf_finish(sb);
7116	sbuf_delete(sb);
7117
7118	return (rc);
7119}
7120
7121static int
7122sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
7123{
7124	struct adapter *sc = arg1;
7125	struct sbuf *sb;
7126	int rc;
7127	struct tp_err_stats stats;
7128
7129	rc = sysctl_wire_old_buffer(req, 0);
7130	if (rc != 0)
7131		return (rc);
7132
7133	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7134	if (sb == NULL)
7135		return (ENOMEM);
7136
7137	mtx_lock(&sc->reg_lock);
7138	t4_tp_get_err_stats(sc, &stats);
7139	mtx_unlock(&sc->reg_lock);
7140
7141	if (sc->chip_params->nchan > 2) {
7142		sbuf_printf(sb, "                 channel 0  channel 1"
7143		    "  channel 2  channel 3\n");
7144		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
7145		    stats.mac_in_errs[0], stats.mac_in_errs[1],
7146		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
7147		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
7148		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
7149		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
7150		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
7151		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
7152		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
7153		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
7154		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
7155		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
7156		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
7157		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
7158		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
7159		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
7160		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
7161		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
7162		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
7163		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
7164		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
7165		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
7166		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
7167		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
7168	} else {
7169		sbuf_printf(sb, "                 channel 0  channel 1\n");
7170		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
7171		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
7172		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
7173		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
7174		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
7175		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
7176		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
7177		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
7178		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
7179		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
7180		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
7181		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
7182		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
7183		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
7184		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
7185		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
7186	}
7187
7188	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
7189	    stats.ofld_no_neigh, stats.ofld_cong_defer);
7190
7191	rc = sbuf_finish(sb);
7192	sbuf_delete(sb);
7193
7194	return (rc);
7195}
7196
7197static int
7198sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
7199{
7200	struct adapter *sc = arg1;
7201	struct tp_params *tpp = &sc->params.tp;
7202	u_int mask;
7203	int rc;
7204
7205	mask = tpp->la_mask >> 16;
7206	rc = sysctl_handle_int(oidp, &mask, 0, req);
7207	if (rc != 0 || req->newptr == NULL)
7208		return (rc);
7209	if (mask > 0xffff)
7210		return (EINVAL);
7211	tpp->la_mask = mask << 16;
7212	t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
7213
7214	return (0);
7215}
7216
7217struct field_desc {
7218	const char *name;
7219	u_int start;
7220	u_int width;
7221};
7222
7223static void
7224field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
7225{
7226	char buf[32];
7227	int line_size = 0;
7228
7229	while (f->name) {
7230		uint64_t mask = (1ULL << f->width) - 1;
7231		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
7232		    ((uintmax_t)v >> f->start) & mask);
7233
7234		if (line_size + len >= 79) {
7235			line_size = 8;
7236			sbuf_printf(sb, "\n        ");
7237		}
7238		sbuf_printf(sb, "%s ", buf);
7239		line_size += len + 1;
7240		f++;
7241	}
7242	sbuf_printf(sb, "\n");
7243}
7244
7245static const struct field_desc tp_la0[] = {
7246	{ "RcfOpCodeOut", 60, 4 },
7247	{ "State", 56, 4 },
7248	{ "WcfState", 52, 4 },
7249	{ "RcfOpcSrcOut", 50, 2 },
7250	{ "CRxError", 49, 1 },
7251	{ "ERxError", 48, 1 },
7252	{ "SanityFailed", 47, 1 },
7253	{ "SpuriousMsg", 46, 1 },
7254	{ "FlushInputMsg", 45, 1 },
7255	{ "FlushInputCpl", 44, 1 },
7256	{ "RssUpBit", 43, 1 },
7257	{ "RssFilterHit", 42, 1 },
7258	{ "Tid", 32, 10 },
7259	{ "InitTcb", 31, 1 },
7260	{ "LineNumber", 24, 7 },
7261	{ "Emsg", 23, 1 },
7262	{ "EdataOut", 22, 1 },
7263	{ "Cmsg", 21, 1 },
7264	{ "CdataOut", 20, 1 },
7265	{ "EreadPdu", 19, 1 },
7266	{ "CreadPdu", 18, 1 },
7267	{ "TunnelPkt", 17, 1 },
7268	{ "RcfPeerFin", 16, 1 },
7269	{ "RcfReasonOut", 12, 4 },
7270	{ "TxCchannel", 10, 2 },
7271	{ "RcfTxChannel", 8, 2 },
7272	{ "RxEchannel", 6, 2 },
7273	{ "RcfRxChannel", 5, 1 },
7274	{ "RcfDataOutSrdy", 4, 1 },
7275	{ "RxDvld", 3, 1 },
7276	{ "RxOoDvld", 2, 1 },
7277	{ "RxCongestion", 1, 1 },
7278	{ "TxCongestion", 0, 1 },
7279	{ NULL }
7280};
7281
7282static const struct field_desc tp_la1[] = {
7283	{ "CplCmdIn", 56, 8 },
7284	{ "CplCmdOut", 48, 8 },
7285	{ "ESynOut", 47, 1 },
7286	{ "EAckOut", 46, 1 },
7287	{ "EFinOut", 45, 1 },
7288	{ "ERstOut", 44, 1 },
7289	{ "SynIn", 43, 1 },
7290	{ "AckIn", 42, 1 },
7291	{ "FinIn", 41, 1 },
7292	{ "RstIn", 40, 1 },
7293	{ "DataIn", 39, 1 },
7294	{ "DataInVld", 38, 1 },
7295	{ "PadIn", 37, 1 },
7296	{ "RxBufEmpty", 36, 1 },
7297	{ "RxDdp", 35, 1 },
7298	{ "RxFbCongestion", 34, 1 },
7299	{ "TxFbCongestion", 33, 1 },
7300	{ "TxPktSumSrdy", 32, 1 },
7301	{ "RcfUlpType", 28, 4 },
7302	{ "Eread", 27, 1 },
7303	{ "Ebypass", 26, 1 },
7304	{ "Esave", 25, 1 },
7305	{ "Static0", 24, 1 },
7306	{ "Cread", 23, 1 },
7307	{ "Cbypass", 22, 1 },
7308	{ "Csave", 21, 1 },
7309	{ "CPktOut", 20, 1 },
7310	{ "RxPagePoolFull", 18, 2 },
7311	{ "RxLpbkPkt", 17, 1 },
7312	{ "TxLpbkPkt", 16, 1 },
7313	{ "RxVfValid", 15, 1 },
7314	{ "SynLearned", 14, 1 },
7315	{ "SetDelEntry", 13, 1 },
7316	{ "SetInvEntry", 12, 1 },
7317	{ "CpcmdDvld", 11, 1 },
7318	{ "CpcmdSave", 10, 1 },
7319	{ "RxPstructsFull", 8, 2 },
7320	{ "EpcmdDvld", 7, 1 },
7321	{ "EpcmdFlush", 6, 1 },
7322	{ "EpcmdTrimPrefix", 5, 1 },
7323	{ "EpcmdTrimPostfix", 4, 1 },
7324	{ "ERssIp4Pkt", 3, 1 },
7325	{ "ERssIp6Pkt", 2, 1 },
7326	{ "ERssTcpUdpPkt", 1, 1 },
7327	{ "ERssFceFipPkt", 0, 1 },
7328	{ NULL }
7329};
7330
7331static const struct field_desc tp_la2[] = {
7332	{ "CplCmdIn", 56, 8 },
7333	{ "MpsVfVld", 55, 1 },
7334	{ "MpsPf", 52, 3 },
7335	{ "MpsVf", 44, 8 },
7336	{ "SynIn", 43, 1 },
7337	{ "AckIn", 42, 1 },
7338	{ "FinIn", 41, 1 },
7339	{ "RstIn", 40, 1 },
7340	{ "DataIn", 39, 1 },
7341	{ "DataInVld", 38, 1 },
7342	{ "PadIn", 37, 1 },
7343	{ "RxBufEmpty", 36, 1 },
7344	{ "RxDdp", 35, 1 },
7345	{ "RxFbCongestion", 34, 1 },
7346	{ "TxFbCongestion", 33, 1 },
7347	{ "TxPktSumSrdy", 32, 1 },
7348	{ "RcfUlpType", 28, 4 },
7349	{ "Eread", 27, 1 },
7350	{ "Ebypass", 26, 1 },
7351	{ "Esave", 25, 1 },
7352	{ "Static0", 24, 1 },
7353	{ "Cread", 23, 1 },
7354	{ "Cbypass", 22, 1 },
7355	{ "Csave", 21, 1 },
7356	{ "CPktOut", 20, 1 },
7357	{ "RxPagePoolFull", 18, 2 },
7358	{ "RxLpbkPkt", 17, 1 },
7359	{ "TxLpbkPkt", 16, 1 },
7360	{ "RxVfValid", 15, 1 },
7361	{ "SynLearned", 14, 1 },
7362	{ "SetDelEntry", 13, 1 },
7363	{ "SetInvEntry", 12, 1 },
7364	{ "CpcmdDvld", 11, 1 },
7365	{ "CpcmdSave", 10, 1 },
7366	{ "RxPstructsFull", 8, 2 },
7367	{ "EpcmdDvld", 7, 1 },
7368	{ "EpcmdFlush", 6, 1 },
7369	{ "EpcmdTrimPrefix", 5, 1 },
7370	{ "EpcmdTrimPostfix", 4, 1 },
7371	{ "ERssIp4Pkt", 3, 1 },
7372	{ "ERssIp6Pkt", 2, 1 },
7373	{ "ERssTcpUdpPkt", 1, 1 },
7374	{ "ERssFceFipPkt", 0, 1 },
7375	{ NULL }
7376};
7377
7378static void
7379tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
7380{
7381
7382	field_desc_show(sb, *p, tp_la0);
7383}
7384
7385static void
7386tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
7387{
7388
7389	if (idx)
7390		sbuf_printf(sb, "\n");
7391	field_desc_show(sb, p[0], tp_la0);
7392	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
7393		field_desc_show(sb, p[1], tp_la0);
7394}
7395
7396static void
7397tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
7398{
7399
7400	if (idx)
7401		sbuf_printf(sb, "\n");
7402	field_desc_show(sb, p[0], tp_la0);
7403	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
7404		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
7405}
7406
7407static int
7408sysctl_tp_la(SYSCTL_HANDLER_ARGS)
7409{
7410	struct adapter *sc = arg1;
7411	struct sbuf *sb;
7412	uint64_t *buf, *p;
7413	int rc;
7414	u_int i, inc;
7415	void (*show_func)(struct sbuf *, uint64_t *, int);
7416
7417	rc = sysctl_wire_old_buffer(req, 0);
7418	if (rc != 0)
7419		return (rc);
7420
7421	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7422	if (sb == NULL)
7423		return (ENOMEM);
7424
7425	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
7426
7427	t4_tp_read_la(sc, buf, NULL);
7428	p = buf;
7429
7430	switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
7431	case 2:
7432		inc = 2;
7433		show_func = tp_la_show2;
7434		break;
7435	case 3:
7436		inc = 2;
7437		show_func = tp_la_show3;
7438		break;
7439	default:
7440		inc = 1;
7441		show_func = tp_la_show;
7442	}
7443
7444	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
7445		(*show_func)(sb, p, i);
7446
7447	rc = sbuf_finish(sb);
7448	sbuf_delete(sb);
7449	free(buf, M_CXGBE);
7450	return (rc);
7451}
7452
7453static int
7454sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
7455{
7456	struct adapter *sc = arg1;
7457	struct sbuf *sb;
7458	int rc;
7459	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
7460
7461	rc = sysctl_wire_old_buffer(req, 0);
7462	if (rc != 0)
7463		return (rc);
7464
7465	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7466	if (sb == NULL)
7467		return (ENOMEM);
7468
7469	t4_get_chan_txrate(sc, nrate, orate);
7470
7471	if (sc->chip_params->nchan > 2) {
7472		sbuf_printf(sb, "              channel 0   channel 1"
7473		    "   channel 2   channel 3\n");
7474		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
7475		    nrate[0], nrate[1], nrate[2], nrate[3]);
7476		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
7477		    orate[0], orate[1], orate[2], orate[3]);
7478	} else {
7479		sbuf_printf(sb, "              channel 0   channel 1\n");
7480		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
7481		    nrate[0], nrate[1]);
7482		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
7483		    orate[0], orate[1]);
7484	}
7485
7486	rc = sbuf_finish(sb);
7487	sbuf_delete(sb);
7488
7489	return (rc);
7490}
7491
7492static int
7493sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
7494{
7495	struct adapter *sc = arg1;
7496	struct sbuf *sb;
7497	uint32_t *buf, *p;
7498	int rc, i;
7499
7500	rc = sysctl_wire_old_buffer(req, 0);
7501	if (rc != 0)
7502		return (rc);
7503
7504	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7505	if (sb == NULL)
7506		return (ENOMEM);
7507
7508	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
7509	    M_ZERO | M_WAITOK);
7510
7511	t4_ulprx_read_la(sc, buf);
7512	p = buf;
7513
7514	sbuf_printf(sb, "      Pcmd        Type   Message"
7515	    "                Data");
7516	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
7517		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
7518		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
7519	}
7520
7521	rc = sbuf_finish(sb);
7522	sbuf_delete(sb);
7523	free(buf, M_CXGBE);
7524	return (rc);
7525}
7526
7527static int
7528sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
7529{
7530	struct adapter *sc = arg1;
7531	struct sbuf *sb;
7532	int rc, v;
7533
7534	MPASS(chip_id(sc) >= CHELSIO_T5);
7535
7536	rc = sysctl_wire_old_buffer(req, 0);
7537	if (rc != 0)
7538		return (rc);
7539
7540	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7541	if (sb == NULL)
7542		return (ENOMEM);
7543
7544	v = t4_read_reg(sc, A_SGE_STAT_CFG);
7545	if (G_STATSOURCE_T5(v) == 7) {
7546		int mode;
7547
7548		mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
7549		if (mode == 0) {
7550			sbuf_printf(sb, "total %d, incomplete %d",
7551			    t4_read_reg(sc, A_SGE_STAT_TOTAL),
7552			    t4_read_reg(sc, A_SGE_STAT_MATCH));
7553		} else if (mode == 1) {
7554			sbuf_printf(sb, "total %d, data overflow %d",
7555			    t4_read_reg(sc, A_SGE_STAT_TOTAL),
7556			    t4_read_reg(sc, A_SGE_STAT_MATCH));
7557		} else {
7558			sbuf_printf(sb, "unknown mode %d", mode);
7559		}
7560	}
7561	rc = sbuf_finish(sb);
7562	sbuf_delete(sb);
7563
7564	return (rc);
7565}
7566
7567static int
7568sysctl_tc_params(SYSCTL_HANDLER_ARGS)
7569{
7570	struct adapter *sc = arg1;
7571	struct tx_sched_class *tc;
7572	struct t4_sched_class_params p;
7573	struct sbuf *sb;
7574	int i, rc, port_id, flags, mbps, gbps;
7575
7576	rc = sysctl_wire_old_buffer(req, 0);
7577	if (rc != 0)
7578		return (rc);
7579
7580	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7581	if (sb == NULL)
7582		return (ENOMEM);
7583
7584	port_id = arg2 >> 16;
7585	MPASS(port_id < sc->params.nports);
7586	MPASS(sc->port[port_id] != NULL);
7587	i = arg2 & 0xffff;
7588	MPASS(i < sc->chip_params->nsched_cls);
7589	tc = &sc->port[port_id]->tc[i];
7590
7591	rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
7592	    "t4tc_p");
7593	if (rc)
7594		goto done;
7595	flags = tc->flags;
7596	p = tc->params;
7597	end_synchronized_op(sc, LOCK_HELD);
7598
7599	if ((flags & TX_SC_OK) == 0) {
7600		sbuf_printf(sb, "none");
7601		goto done;
7602	}
7603
7604	if (p.level == SCHED_CLASS_LEVEL_CL_WRR) {
7605		sbuf_printf(sb, "cl-wrr weight %u", p.weight);
7606		goto done;
7607	} else if (p.level == SCHED_CLASS_LEVEL_CL_RL)
7608		sbuf_printf(sb, "cl-rl");
7609	else if (p.level == SCHED_CLASS_LEVEL_CH_RL)
7610		sbuf_printf(sb, "ch-rl");
7611	else {
7612		rc = ENXIO;
7613		goto done;
7614	}
7615
7616	if (p.ratemode == SCHED_CLASS_RATEMODE_REL) {
7617		/* XXX: top speed or actual link speed? */
7618		gbps = port_top_speed(sc->port[port_id]);
7619		sbuf_printf(sb, " %u%% of %uGbps", p.maxrate, gbps);
7620	}
7621	else if (p.ratemode == SCHED_CLASS_RATEMODE_ABS) {
7622		switch (p.rateunit) {
7623		case SCHED_CLASS_RATEUNIT_BITS:
7624			mbps = p.maxrate / 1000;
7625			gbps = p.maxrate / 1000000;
7626			if (p.maxrate == gbps * 1000000)
7627				sbuf_printf(sb, " %uGbps", gbps);
7628			else if (p.maxrate == mbps * 1000)
7629				sbuf_printf(sb, " %uMbps", mbps);
7630			else
7631				sbuf_printf(sb, " %uKbps", p.maxrate);
7632			break;
7633		case SCHED_CLASS_RATEUNIT_PKTS:
7634			sbuf_printf(sb, " %upps", p.maxrate);
7635			break;
7636		default:
7637			rc = ENXIO;
7638			goto done;
7639		}
7640	}
7641
7642	switch (p.mode) {
7643	case SCHED_CLASS_MODE_CLASS:
7644		sbuf_printf(sb, " aggregate");
7645		break;
7646	case SCHED_CLASS_MODE_FLOW:
7647		sbuf_printf(sb, " per-flow");
7648		break;
7649	default:
7650		rc = ENXIO;
7651		goto done;
7652	}
7653
7654done:
7655	if (rc == 0)
7656		rc = sbuf_finish(sb);
7657	sbuf_delete(sb);
7658
7659	return (rc);
7660}
7661#endif
7662
7663#ifdef TCP_OFFLOAD
7664static void
7665unit_conv(char *buf, size_t len, u_int val, u_int factor)
7666{
7667	u_int rem = val % factor;
7668
7669	if (rem == 0)
7670		snprintf(buf, len, "%u", val / factor);
7671	else {
7672		while (rem % 10 == 0)
7673			rem /= 10;
7674		snprintf(buf, len, "%u.%u", val / factor, rem);
7675	}
7676}
7677
7678static int
7679sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
7680{
7681	struct adapter *sc = arg1;
7682	char buf[16];
7683	u_int res, re;
7684	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
7685
7686	res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
7687	switch (arg2) {
7688	case 0:
7689		/* timer_tick */
7690		re = G_TIMERRESOLUTION(res);
7691		break;
7692	case 1:
7693		/* TCP timestamp tick */
7694		re = G_TIMESTAMPRESOLUTION(res);
7695		break;
7696	case 2:
7697		/* DACK tick */
7698		re = G_DELAYEDACKRESOLUTION(res);
7699		break;
7700	default:
7701		return (EDOOFUS);
7702	}
7703
7704	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
7705
7706	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
7707}
7708
7709static int
7710sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
7711{
7712	struct adapter *sc = arg1;
7713	u_int res, dack_re, v;
7714	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
7715
7716	res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
7717	dack_re = G_DELAYEDACKRESOLUTION(res);
7718	v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
7719
7720	return (sysctl_handle_int(oidp, &v, 0, req));
7721}
7722
7723static int
7724sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
7725{
7726	struct adapter *sc = arg1;
7727	int reg = arg2;
7728	u_int tre;
7729	u_long tp_tick_us, v;
7730	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
7731
7732	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
7733	    reg == A_TP_PERS_MIN || reg == A_TP_PERS_MAX ||
7734	    reg == A_TP_KEEP_IDLE || A_TP_KEEP_INTVL || reg == A_TP_INIT_SRTT ||
7735	    reg == A_TP_FINWAIT2_TIMER);
7736
7737	tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
7738	tp_tick_us = (cclk_ps << tre) / 1000000;
7739
7740	if (reg == A_TP_INIT_SRTT)
7741		v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
7742	else
7743		v = tp_tick_us * t4_read_reg(sc, reg);
7744
7745	return (sysctl_handle_long(oidp, &v, 0, req));
7746}
7747#endif
7748
7749static uint32_t
7750fconf_iconf_to_mode(uint32_t fconf, uint32_t iconf)
7751{
7752	uint32_t mode;
7753
7754	mode = T4_FILTER_IPv4 | T4_FILTER_IPv6 | T4_FILTER_IP_SADDR |
7755	    T4_FILTER_IP_DADDR | T4_FILTER_IP_SPORT | T4_FILTER_IP_DPORT;
7756
7757	if (fconf & F_FRAGMENTATION)
7758		mode |= T4_FILTER_IP_FRAGMENT;
7759
7760	if (fconf & F_MPSHITTYPE)
7761		mode |= T4_FILTER_MPS_HIT_TYPE;
7762
7763	if (fconf & F_MACMATCH)
7764		mode |= T4_FILTER_MAC_IDX;
7765
7766	if (fconf & F_ETHERTYPE)
7767		mode |= T4_FILTER_ETH_TYPE;
7768
7769	if (fconf & F_PROTOCOL)
7770		mode |= T4_FILTER_IP_PROTO;
7771
7772	if (fconf & F_TOS)
7773		mode |= T4_FILTER_IP_TOS;
7774
7775	if (fconf & F_VLAN)
7776		mode |= T4_FILTER_VLAN;
7777
7778	if (fconf & F_VNIC_ID) {
7779		mode |= T4_FILTER_VNIC;
7780		if (iconf & F_VNIC)
7781			mode |= T4_FILTER_IC_VNIC;
7782	}
7783
7784	if (fconf & F_PORT)
7785		mode |= T4_FILTER_PORT;
7786
7787	if (fconf & F_FCOE)
7788		mode |= T4_FILTER_FCoE;
7789
7790	return (mode);
7791}
7792
7793static uint32_t
7794mode_to_fconf(uint32_t mode)
7795{
7796	uint32_t fconf = 0;
7797
7798	if (mode & T4_FILTER_IP_FRAGMENT)
7799		fconf |= F_FRAGMENTATION;
7800
7801	if (mode & T4_FILTER_MPS_HIT_TYPE)
7802		fconf |= F_MPSHITTYPE;
7803
7804	if (mode & T4_FILTER_MAC_IDX)
7805		fconf |= F_MACMATCH;
7806
7807	if (mode & T4_FILTER_ETH_TYPE)
7808		fconf |= F_ETHERTYPE;
7809
7810	if (mode & T4_FILTER_IP_PROTO)
7811		fconf |= F_PROTOCOL;
7812
7813	if (mode & T4_FILTER_IP_TOS)
7814		fconf |= F_TOS;
7815
7816	if (mode & T4_FILTER_VLAN)
7817		fconf |= F_VLAN;
7818
7819	if (mode & T4_FILTER_VNIC)
7820		fconf |= F_VNIC_ID;
7821
7822	if (mode & T4_FILTER_PORT)
7823		fconf |= F_PORT;
7824
7825	if (mode & T4_FILTER_FCoE)
7826		fconf |= F_FCOE;
7827
7828	return (fconf);
7829}
7830
7831static uint32_t
7832mode_to_iconf(uint32_t mode)
7833{
7834
7835	if (mode & T4_FILTER_IC_VNIC)
7836		return (F_VNIC);
7837	return (0);
7838}
7839
7840static int check_fspec_against_fconf_iconf(struct adapter *sc,
7841    struct t4_filter_specification *fs)
7842{
7843	struct tp_params *tpp = &sc->params.tp;
7844	uint32_t fconf = 0;
7845
7846	if (fs->val.frag || fs->mask.frag)
7847		fconf |= F_FRAGMENTATION;
7848
7849	if (fs->val.matchtype || fs->mask.matchtype)
7850		fconf |= F_MPSHITTYPE;
7851
7852	if (fs->val.macidx || fs->mask.macidx)
7853		fconf |= F_MACMATCH;
7854
7855	if (fs->val.ethtype || fs->mask.ethtype)
7856		fconf |= F_ETHERTYPE;
7857
7858	if (fs->val.proto || fs->mask.proto)
7859		fconf |= F_PROTOCOL;
7860
7861	if (fs->val.tos || fs->mask.tos)
7862		fconf |= F_TOS;
7863
7864	if (fs->val.vlan_vld || fs->mask.vlan_vld)
7865		fconf |= F_VLAN;
7866
7867	if (fs->val.ovlan_vld || fs->mask.ovlan_vld) {
7868		fconf |= F_VNIC_ID;
7869		if (tpp->ingress_config & F_VNIC)
7870			return (EINVAL);
7871	}
7872
7873	if (fs->val.pfvf_vld || fs->mask.pfvf_vld) {
7874		fconf |= F_VNIC_ID;
7875		if ((tpp->ingress_config & F_VNIC) == 0)
7876			return (EINVAL);
7877	}
7878
7879	if (fs->val.iport || fs->mask.iport)
7880		fconf |= F_PORT;
7881
7882	if (fs->val.fcoe || fs->mask.fcoe)
7883		fconf |= F_FCOE;
7884
7885	if ((tpp->vlan_pri_map | fconf) != tpp->vlan_pri_map)
7886		return (E2BIG);
7887
7888	return (0);
7889}
7890
7891static int
7892get_filter_mode(struct adapter *sc, uint32_t *mode)
7893{
7894	struct tp_params *tpp = &sc->params.tp;
7895
7896	/*
7897	 * We trust the cached values of the relevant TP registers.  This means
7898	 * things work reliably only if writes to those registers are always via
7899	 * t4_set_filter_mode.
7900	 */
7901	*mode = fconf_iconf_to_mode(tpp->vlan_pri_map, tpp->ingress_config);
7902
7903	return (0);
7904}
7905
7906static int
7907set_filter_mode(struct adapter *sc, uint32_t mode)
7908{
7909	struct tp_params *tpp = &sc->params.tp;
7910	uint32_t fconf, iconf;
7911	int rc;
7912
7913	iconf = mode_to_iconf(mode);
7914	if ((iconf ^ tpp->ingress_config) & F_VNIC) {
7915		/*
7916		 * For now we just complain if A_TP_INGRESS_CONFIG is not
7917		 * already set to the correct value for the requested filter
7918		 * mode.  It's not clear if it's safe to write to this register
7919		 * on the fly.  (And we trust the cached value of the register).
7920		 */
7921		return (EBUSY);
7922	}
7923
7924	fconf = mode_to_fconf(mode);
7925
7926	rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
7927	    "t4setfm");
7928	if (rc)
7929		return (rc);
7930
7931	if (sc->tids.ftids_in_use > 0) {
7932		rc = EBUSY;
7933		goto done;
7934	}
7935
7936#ifdef TCP_OFFLOAD
7937	if (uld_active(sc, ULD_TOM)) {
7938		rc = EBUSY;
7939		goto done;
7940	}
7941#endif
7942
7943	rc = -t4_set_filter_mode(sc, fconf);
7944done:
7945	end_synchronized_op(sc, LOCK_HELD);
7946	return (rc);
7947}
7948
7949static inline uint64_t
7950get_filter_hits(struct adapter *sc, uint32_t fid)
7951{
7952	uint32_t tcb_addr;
7953
7954	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE) +
7955	    (fid + sc->tids.ftid_base) * TCB_SIZE;
7956
7957	if (is_t4(sc)) {
7958		uint64_t hits;
7959
7960		read_via_memwin(sc, 0, tcb_addr + 16, (uint32_t *)&hits, 8);
7961		return (be64toh(hits));
7962	} else {
7963		uint32_t hits;
7964
7965		read_via_memwin(sc, 0, tcb_addr + 24, &hits, 4);
7966		return (be32toh(hits));
7967	}
7968}
7969
7970static int
7971get_filter(struct adapter *sc, struct t4_filter *t)
7972{
7973	int i, rc, nfilters = sc->tids.nftids;
7974	struct filter_entry *f;
7975
7976	rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
7977	    "t4getf");
7978	if (rc)
7979		return (rc);
7980
7981	if (sc->tids.ftids_in_use == 0 || sc->tids.ftid_tab == NULL ||
7982	    t->idx >= nfilters) {
7983		t->idx = 0xffffffff;
7984		goto done;
7985	}
7986
7987	f = &sc->tids.ftid_tab[t->idx];
7988	for (i = t->idx; i < nfilters; i++, f++) {
7989		if (f->valid) {
7990			t->idx = i;
7991			t->l2tidx = f->l2t ? f->l2t->idx : 0;
7992			t->smtidx = f->smtidx;
7993			if (f->fs.hitcnts)
7994				t->hits = get_filter_hits(sc, t->idx);
7995			else
7996				t->hits = UINT64_MAX;
7997			t->fs = f->fs;
7998
7999			goto done;
8000		}
8001	}
8002
8003	t->idx = 0xffffffff;
8004done:
8005	end_synchronized_op(sc, LOCK_HELD);
8006	return (0);
8007}
8008
8009static int
8010set_filter(struct adapter *sc, struct t4_filter *t)
8011{
8012	unsigned int nfilters, nports;
8013	struct filter_entry *f;
8014	int i, rc;
8015
8016	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4setf");
8017	if (rc)
8018		return (rc);
8019
8020	nfilters = sc->tids.nftids;
8021	nports = sc->params.nports;
8022
8023	if (nfilters == 0) {
8024		rc = ENOTSUP;
8025		goto done;
8026	}
8027
8028	if (t->idx >= nfilters) {
8029		rc = EINVAL;
8030		goto done;
8031	}
8032
8033	/* Validate against the global filter mode and ingress config */
8034	rc = check_fspec_against_fconf_iconf(sc, &t->fs);
8035	if (rc != 0)
8036		goto done;
8037
8038	if (t->fs.action == FILTER_SWITCH && t->fs.eport >= nports) {
8039		rc = EINVAL;
8040		goto done;
8041	}
8042
8043	if (t->fs.val.iport >= nports) {
8044		rc = EINVAL;
8045		goto done;
8046	}
8047
8048	/* Can't specify an iq if not steering to it */
8049	if (!t->fs.dirsteer && t->fs.iq) {
8050		rc = EINVAL;
8051		goto done;
8052	}
8053
8054	/* IPv6 filter idx must be 4 aligned */
8055	if (t->fs.type == 1 &&
8056	    ((t->idx & 0x3) || t->idx + 4 >= nfilters)) {
8057		rc = EINVAL;
8058		goto done;
8059	}
8060
8061	if (!(sc->flags & FULL_INIT_DONE) &&
8062	    ((rc = adapter_full_init(sc)) != 0))
8063		goto done;
8064
8065	if (sc->tids.ftid_tab == NULL) {
8066		KASSERT(sc->tids.ftids_in_use == 0,
8067		    ("%s: no memory allocated but filters_in_use > 0",
8068		    __func__));
8069
8070		sc->tids.ftid_tab = malloc(sizeof (struct filter_entry) *
8071		    nfilters, M_CXGBE, M_NOWAIT | M_ZERO);
8072		if (sc->tids.ftid_tab == NULL) {
8073			rc = ENOMEM;
8074			goto done;
8075		}
8076		mtx_init(&sc->tids.ftid_lock, "T4 filters", 0, MTX_DEF);
8077	}
8078
8079	for (i = 0; i < 4; i++) {
8080		f = &sc->tids.ftid_tab[t->idx + i];
8081
8082		if (f->pending || f->valid) {
8083			rc = EBUSY;
8084			goto done;
8085		}
8086		if (f->locked) {
8087			rc = EPERM;
8088			goto done;
8089		}
8090
8091		if (t->fs.type == 0)
8092			break;
8093	}
8094
8095	f = &sc->tids.ftid_tab[t->idx];
8096	f->fs = t->fs;
8097
8098	rc = set_filter_wr(sc, t->idx);
8099done:
8100	end_synchronized_op(sc, 0);
8101
8102	if (rc == 0) {
8103		mtx_lock(&sc->tids.ftid_lock);
8104		for (;;) {
8105			if (f->pending == 0) {
8106				rc = f->valid ? 0 : EIO;
8107				break;
8108			}
8109
8110			if (mtx_sleep(&sc->tids.ftid_tab, &sc->tids.ftid_lock,
8111			    PCATCH, "t4setfw", 0)) {
8112				rc = EINPROGRESS;
8113				break;
8114			}
8115		}
8116		mtx_unlock(&sc->tids.ftid_lock);
8117	}
8118	return (rc);
8119}
8120
8121static int
8122del_filter(struct adapter *sc, struct t4_filter *t)
8123{
8124	unsigned int nfilters;
8125	struct filter_entry *f;
8126	int rc;
8127
8128	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4delf");
8129	if (rc)
8130		return (rc);
8131
8132	nfilters = sc->tids.nftids;
8133
8134	if (nfilters == 0) {
8135		rc = ENOTSUP;
8136		goto done;
8137	}
8138
8139	if (sc->tids.ftid_tab == NULL || sc->tids.ftids_in_use == 0 ||
8140	    t->idx >= nfilters) {
8141		rc = EINVAL;
8142		goto done;
8143	}
8144
8145	if (!(sc->flags & FULL_INIT_DONE)) {
8146		rc = EAGAIN;
8147		goto done;
8148	}
8149
8150	f = &sc->tids.ftid_tab[t->idx];
8151
8152	if (f->pending) {
8153		rc = EBUSY;
8154		goto done;
8155	}
8156	if (f->locked) {
8157		rc = EPERM;
8158		goto done;
8159	}
8160
8161	if (f->valid) {
8162		t->fs = f->fs;	/* extra info for the caller */
8163		rc = del_filter_wr(sc, t->idx);
8164	}
8165
8166done:
8167	end_synchronized_op(sc, 0);
8168
8169	if (rc == 0) {
8170		mtx_lock(&sc->tids.ftid_lock);
8171		for (;;) {
8172			if (f->pending == 0) {
8173				rc = f->valid ? EIO : 0;
8174				break;
8175			}
8176
8177			if (mtx_sleep(&sc->tids.ftid_tab, &sc->tids.ftid_lock,
8178			    PCATCH, "t4delfw", 0)) {
8179				rc = EINPROGRESS;
8180				break;
8181			}
8182		}
8183		mtx_unlock(&sc->tids.ftid_lock);
8184	}
8185
8186	return (rc);
8187}
8188
8189static void
8190clear_filter(struct filter_entry *f)
8191{
8192	if (f->l2t)
8193		t4_l2t_release(f->l2t);
8194
8195	bzero(f, sizeof (*f));
8196}
8197
8198static int
8199set_filter_wr(struct adapter *sc, int fidx)
8200{
8201	struct filter_entry *f = &sc->tids.ftid_tab[fidx];
8202	struct fw_filter_wr *fwr;
8203	unsigned int ftid, vnic_vld, vnic_vld_mask;
8204	struct wrq_cookie cookie;
8205
8206	ASSERT_SYNCHRONIZED_OP(sc);
8207
8208	if (f->fs.newdmac || f->fs.newvlan) {
8209		/* This filter needs an L2T entry; allocate one. */
8210		f->l2t = t4_l2t_alloc_switching(sc->l2t);
8211		if (f->l2t == NULL)
8212			return (EAGAIN);
8213		if (t4_l2t_set_switching(sc, f->l2t, f->fs.vlan, f->fs.eport,
8214		    f->fs.dmac)) {
8215			t4_l2t_release(f->l2t);
8216			f->l2t = NULL;
8217			return (ENOMEM);
8218		}
8219	}
8220
8221	/* Already validated against fconf, iconf */
8222	MPASS((f->fs.val.pfvf_vld & f->fs.val.ovlan_vld) == 0);
8223	MPASS((f->fs.mask.pfvf_vld & f->fs.mask.ovlan_vld) == 0);
8224	if (f->fs.val.pfvf_vld || f->fs.val.ovlan_vld)
8225		vnic_vld = 1;
8226	else
8227		vnic_vld = 0;
8228	if (f->fs.mask.pfvf_vld || f->fs.mask.ovlan_vld)
8229		vnic_vld_mask = 1;
8230	else
8231		vnic_vld_mask = 0;
8232
8233	ftid = sc->tids.ftid_base + fidx;
8234
8235	fwr = start_wrq_wr(&sc->sge.mgmtq, howmany(sizeof(*fwr), 16), &cookie);
8236	if (fwr == NULL)
8237		return (ENOMEM);
8238	bzero(fwr, sizeof(*fwr));
8239
8240	fwr->op_pkd = htobe32(V_FW_WR_OP(FW_FILTER_WR));
8241	fwr->len16_pkd = htobe32(FW_LEN16(*fwr));
8242	fwr->tid_to_iq =
8243	    htobe32(V_FW_FILTER_WR_TID(ftid) |
8244		V_FW_FILTER_WR_RQTYPE(f->fs.type) |
8245		V_FW_FILTER_WR_NOREPLY(0) |
8246		V_FW_FILTER_WR_IQ(f->fs.iq));
8247	fwr->del_filter_to_l2tix =
8248	    htobe32(V_FW_FILTER_WR_RPTTID(f->fs.rpttid) |
8249		V_FW_FILTER_WR_DROP(f->fs.action == FILTER_DROP) |
8250		V_FW_FILTER_WR_DIRSTEER(f->fs.dirsteer) |
8251		V_FW_FILTER_WR_MASKHASH(f->fs.maskhash) |
8252		V_FW_FILTER_WR_DIRSTEERHASH(f->fs.dirsteerhash) |
8253		V_FW_FILTER_WR_LPBK(f->fs.action == FILTER_SWITCH) |
8254		V_FW_FILTER_WR_DMAC(f->fs.newdmac) |
8255		V_FW_FILTER_WR_SMAC(f->fs.newsmac) |
8256		V_FW_FILTER_WR_INSVLAN(f->fs.newvlan == VLAN_INSERT ||
8257		    f->fs.newvlan == VLAN_REWRITE) |
8258		V_FW_FILTER_WR_RMVLAN(f->fs.newvlan == VLAN_REMOVE ||
8259		    f->fs.newvlan == VLAN_REWRITE) |
8260		V_FW_FILTER_WR_HITCNTS(f->fs.hitcnts) |
8261		V_FW_FILTER_WR_TXCHAN(f->fs.eport) |
8262		V_FW_FILTER_WR_PRIO(f->fs.prio) |
8263		V_FW_FILTER_WR_L2TIX(f->l2t ? f->l2t->idx : 0));
8264	fwr->ethtype = htobe16(f->fs.val.ethtype);
8265	fwr->ethtypem = htobe16(f->fs.mask.ethtype);
8266	fwr->frag_to_ovlan_vldm =
8267	    (V_FW_FILTER_WR_FRAG(f->fs.val.frag) |
8268		V_FW_FILTER_WR_FRAGM(f->fs.mask.frag) |
8269		V_FW_FILTER_WR_IVLAN_VLD(f->fs.val.vlan_vld) |
8270		V_FW_FILTER_WR_OVLAN_VLD(vnic_vld) |
8271		V_FW_FILTER_WR_IVLAN_VLDM(f->fs.mask.vlan_vld) |
8272		V_FW_FILTER_WR_OVLAN_VLDM(vnic_vld_mask));
8273	fwr->smac_sel = 0;
8274	fwr->rx_chan_rx_rpl_iq = htobe16(V_FW_FILTER_WR_RX_CHAN(0) |
8275	    V_FW_FILTER_WR_RX_RPL_IQ(sc->sge.fwq.abs_id));
8276	fwr->maci_to_matchtypem =
8277	    htobe32(V_FW_FILTER_WR_MACI(f->fs.val.macidx) |
8278		V_FW_FILTER_WR_MACIM(f->fs.mask.macidx) |
8279		V_FW_FILTER_WR_FCOE(f->fs.val.fcoe) |
8280		V_FW_FILTER_WR_FCOEM(f->fs.mask.fcoe) |
8281		V_FW_FILTER_WR_PORT(f->fs.val.iport) |
8282		V_FW_FILTER_WR_PORTM(f->fs.mask.iport) |
8283		V_FW_FILTER_WR_MATCHTYPE(f->fs.val.matchtype) |
8284		V_FW_FILTER_WR_MATCHTYPEM(f->fs.mask.matchtype));
8285	fwr->ptcl = f->fs.val.proto;
8286	fwr->ptclm = f->fs.mask.proto;
8287	fwr->ttyp = f->fs.val.tos;
8288	fwr->ttypm = f->fs.mask.tos;
8289	fwr->ivlan = htobe16(f->fs.val.vlan);
8290	fwr->ivlanm = htobe16(f->fs.mask.vlan);
8291	fwr->ovlan = htobe16(f->fs.val.vnic);
8292	fwr->ovlanm = htobe16(f->fs.mask.vnic);
8293	bcopy(f->fs.val.dip, fwr->lip, sizeof (fwr->lip));
8294	bcopy(f->fs.mask.dip, fwr->lipm, sizeof (fwr->lipm));
8295	bcopy(f->fs.val.sip, fwr->fip, sizeof (fwr->fip));
8296	bcopy(f->fs.mask.sip, fwr->fipm, sizeof (fwr->fipm));
8297	fwr->lp = htobe16(f->fs.val.dport);
8298	fwr->lpm = htobe16(f->fs.mask.dport);
8299	fwr->fp = htobe16(f->fs.val.sport);
8300	fwr->fpm = htobe16(f->fs.mask.sport);
8301	if (f->fs.newsmac)
8302		bcopy(f->fs.smac, fwr->sma, sizeof (fwr->sma));
8303
8304	f->pending = 1;
8305	sc->tids.ftids_in_use++;
8306
8307	commit_wrq_wr(&sc->sge.mgmtq, fwr, &cookie);
8308	return (0);
8309}
8310
8311static int
8312del_filter_wr(struct adapter *sc, int fidx)
8313{
8314	struct filter_entry *f = &sc->tids.ftid_tab[fidx];
8315	struct fw_filter_wr *fwr;
8316	unsigned int ftid;
8317	struct wrq_cookie cookie;
8318
8319	ftid = sc->tids.ftid_base + fidx;
8320
8321	fwr = start_wrq_wr(&sc->sge.mgmtq, howmany(sizeof(*fwr), 16), &cookie);
8322	if (fwr == NULL)
8323		return (ENOMEM);
8324	bzero(fwr, sizeof (*fwr));
8325
8326	t4_mk_filtdelwr(ftid, fwr, sc->sge.fwq.abs_id);
8327
8328	f->pending = 1;
8329	commit_wrq_wr(&sc->sge.mgmtq, fwr, &cookie);
8330	return (0);
8331}
8332
8333int
8334t4_filter_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8335{
8336	struct adapter *sc = iq->adapter;
8337	const struct cpl_set_tcb_rpl *rpl = (const void *)(rss + 1);
8338	unsigned int idx = GET_TID(rpl);
8339	unsigned int rc;
8340	struct filter_entry *f;
8341
8342	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
8343	    rss->opcode));
8344	MPASS(iq == &sc->sge.fwq);
8345	MPASS(is_ftid(sc, idx));
8346
8347	idx -= sc->tids.ftid_base;
8348	f = &sc->tids.ftid_tab[idx];
8349	rc = G_COOKIE(rpl->cookie);
8350
8351	mtx_lock(&sc->tids.ftid_lock);
8352	if (rc == FW_FILTER_WR_FLT_ADDED) {
8353		KASSERT(f->pending, ("%s: filter[%u] isn't pending.",
8354		    __func__, idx));
8355		f->smtidx = (be64toh(rpl->oldval) >> 24) & 0xff;
8356		f->pending = 0;  /* asynchronous setup completed */
8357		f->valid = 1;
8358	} else {
8359		if (rc != FW_FILTER_WR_FLT_DELETED) {
8360			/* Add or delete failed, display an error */
8361			log(LOG_ERR,
8362			    "filter %u setup failed with error %u\n",
8363			    idx, rc);
8364		}
8365
8366		clear_filter(f);
8367		sc->tids.ftids_in_use--;
8368	}
8369	wakeup(&sc->tids.ftid_tab);
8370	mtx_unlock(&sc->tids.ftid_lock);
8371
8372	return (0);
8373}
8374
8375static int
8376set_tcb_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8377{
8378
8379	MPASS(iq->set_tcb_rpl != NULL);
8380	return (iq->set_tcb_rpl(iq, rss, m));
8381}
8382
8383static int
8384l2t_write_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8385{
8386
8387	MPASS(iq->l2t_write_rpl != NULL);
8388	return (iq->l2t_write_rpl(iq, rss, m));
8389}
8390
8391static int
8392get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
8393{
8394	int rc;
8395
8396	if (cntxt->cid > M_CTXTQID)
8397		return (EINVAL);
8398
8399	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
8400	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
8401		return (EINVAL);
8402
8403	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
8404	if (rc)
8405		return (rc);
8406
8407	if (sc->flags & FW_OK) {
8408		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
8409		    &cntxt->data[0]);
8410		if (rc == 0)
8411			goto done;
8412	}
8413
8414	/*
8415	 * Read via firmware failed or wasn't even attempted.  Read directly via
8416	 * the backdoor.
8417	 */
8418	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
8419done:
8420	end_synchronized_op(sc, 0);
8421	return (rc);
8422}
8423
8424static int
8425load_fw(struct adapter *sc, struct t4_data *fw)
8426{
8427	int rc;
8428	uint8_t *fw_data;
8429
8430	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
8431	if (rc)
8432		return (rc);
8433
8434	if (sc->flags & FULL_INIT_DONE) {
8435		rc = EBUSY;
8436		goto done;
8437	}
8438
8439	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
8440	if (fw_data == NULL) {
8441		rc = ENOMEM;
8442		goto done;
8443	}
8444
8445	rc = copyin(fw->data, fw_data, fw->len);
8446	if (rc == 0)
8447		rc = -t4_load_fw(sc, fw_data, fw->len);
8448
8449	free(fw_data, M_CXGBE);
8450done:
8451	end_synchronized_op(sc, 0);
8452	return (rc);
8453}
8454
8455static int
8456load_cfg(struct adapter *sc, struct t4_data *cfg)
8457{
8458	int rc;
8459	uint8_t *cfg_data = NULL;
8460
8461	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
8462	if (rc)
8463		return (rc);
8464
8465	if (cfg->len == 0) {
8466		/* clear */
8467		rc = -t4_load_cfg(sc, NULL, 0);
8468		goto done;
8469	}
8470
8471	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
8472	if (cfg_data == NULL) {
8473		rc = ENOMEM;
8474		goto done;
8475	}
8476
8477	rc = copyin(cfg->data, cfg_data, cfg->len);
8478	if (rc == 0)
8479		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
8480
8481	free(cfg_data, M_CXGBE);
8482done:
8483	end_synchronized_op(sc, 0);
8484	return (rc);
8485}
8486
8487#define MAX_READ_BUF_SIZE (128 * 1024)
8488static int
8489read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
8490{
8491	uint32_t addr, remaining, n;
8492	uint32_t *buf;
8493	int rc;
8494	uint8_t *dst;
8495
8496	rc = validate_mem_range(sc, mr->addr, mr->len);
8497	if (rc != 0)
8498		return (rc);
8499
8500	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
8501	addr = mr->addr;
8502	remaining = mr->len;
8503	dst = (void *)mr->data;
8504
8505	while (remaining) {
8506		n = min(remaining, MAX_READ_BUF_SIZE);
8507		read_via_memwin(sc, 2, addr, buf, n);
8508
8509		rc = copyout(buf, dst, n);
8510		if (rc != 0)
8511			break;
8512
8513		dst += n;
8514		remaining -= n;
8515		addr += n;
8516	}
8517
8518	free(buf, M_CXGBE);
8519	return (rc);
8520}
8521#undef MAX_READ_BUF_SIZE
8522
8523static int
8524read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
8525{
8526	int rc;
8527
8528	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
8529		return (EINVAL);
8530
8531	if (i2cd->len > sizeof(i2cd->data))
8532		return (EFBIG);
8533
8534	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
8535	if (rc)
8536		return (rc);
8537	rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
8538	    i2cd->offset, i2cd->len, &i2cd->data[0]);
8539	end_synchronized_op(sc, 0);
8540
8541	return (rc);
8542}
8543
8544static int
8545in_range(int val, int lo, int hi)
8546{
8547
8548	return (val < 0 || (val <= hi && val >= lo));
8549}
8550
8551static int
8552set_sched_class_config(struct adapter *sc, int minmax)
8553{
8554	int rc;
8555
8556	if (minmax < 0)
8557		return (EINVAL);
8558
8559	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4sscc");
8560	if (rc)
8561		return (rc);
8562	rc = -t4_sched_config(sc, FW_SCHED_TYPE_PKTSCHED, minmax, 1);
8563	end_synchronized_op(sc, 0);
8564
8565	return (rc);
8566}
8567
8568static int
8569set_sched_class_params(struct adapter *sc, struct t4_sched_class_params *p,
8570    int sleep_ok)
8571{
8572	int rc, top_speed, fw_level, fw_mode, fw_rateunit, fw_ratemode;
8573	struct port_info *pi;
8574	struct tx_sched_class *tc;
8575
8576	if (p->level == SCHED_CLASS_LEVEL_CL_RL)
8577		fw_level = FW_SCHED_PARAMS_LEVEL_CL_RL;
8578	else if (p->level == SCHED_CLASS_LEVEL_CL_WRR)
8579		fw_level = FW_SCHED_PARAMS_LEVEL_CL_WRR;
8580	else if (p->level == SCHED_CLASS_LEVEL_CH_RL)
8581		fw_level = FW_SCHED_PARAMS_LEVEL_CH_RL;
8582	else
8583		return (EINVAL);
8584
8585	if (p->mode == SCHED_CLASS_MODE_CLASS)
8586		fw_mode = FW_SCHED_PARAMS_MODE_CLASS;
8587	else if (p->mode == SCHED_CLASS_MODE_FLOW)
8588		fw_mode = FW_SCHED_PARAMS_MODE_FLOW;
8589	else
8590		return (EINVAL);
8591
8592	if (p->rateunit == SCHED_CLASS_RATEUNIT_BITS)
8593		fw_rateunit = FW_SCHED_PARAMS_UNIT_BITRATE;
8594	else if (p->rateunit == SCHED_CLASS_RATEUNIT_PKTS)
8595		fw_rateunit = FW_SCHED_PARAMS_UNIT_PKTRATE;
8596	else
8597		return (EINVAL);
8598
8599	if (p->ratemode == SCHED_CLASS_RATEMODE_REL)
8600		fw_ratemode = FW_SCHED_PARAMS_RATE_REL;
8601	else if (p->ratemode == SCHED_CLASS_RATEMODE_ABS)
8602		fw_ratemode = FW_SCHED_PARAMS_RATE_ABS;
8603	else
8604		return (EINVAL);
8605
8606	/* Vet our parameters ... */
8607	if (!in_range(p->channel, 0, sc->chip_params->nchan - 1))
8608		return (ERANGE);
8609
8610	pi = sc->port[sc->chan_map[p->channel]];
8611	if (pi == NULL)
8612		return (ENXIO);
8613	MPASS(pi->tx_chan == p->channel);
8614	top_speed = port_top_speed(pi) * 1000000; /* Gbps -> Kbps */
8615
8616	if (!in_range(p->cl, 0, sc->chip_params->nsched_cls) ||
8617	    !in_range(p->minrate, 0, top_speed) ||
8618	    !in_range(p->maxrate, 0, top_speed) ||
8619	    !in_range(p->weight, 0, 100))
8620		return (ERANGE);
8621
8622	/*
8623	 * Translate any unset parameters into the firmware's
8624	 * nomenclature and/or fail the call if the parameters
8625	 * are required ...
8626	 */
8627	if (p->rateunit < 0 || p->ratemode < 0 || p->channel < 0 || p->cl < 0)
8628		return (EINVAL);
8629
8630	if (p->minrate < 0)
8631		p->minrate = 0;
8632	if (p->maxrate < 0) {
8633		if (p->level == SCHED_CLASS_LEVEL_CL_RL ||
8634		    p->level == SCHED_CLASS_LEVEL_CH_RL)
8635			return (EINVAL);
8636		else
8637			p->maxrate = 0;
8638	}
8639	if (p->weight < 0) {
8640		if (p->level == SCHED_CLASS_LEVEL_CL_WRR)
8641			return (EINVAL);
8642		else
8643			p->weight = 0;
8644	}
8645	if (p->pktsize < 0) {
8646		if (p->level == SCHED_CLASS_LEVEL_CL_RL ||
8647		    p->level == SCHED_CLASS_LEVEL_CH_RL)
8648			return (EINVAL);
8649		else
8650			p->pktsize = 0;
8651	}
8652
8653	rc = begin_synchronized_op(sc, NULL,
8654	    sleep_ok ? (SLEEP_OK | INTR_OK) : HOLD_LOCK, "t4sscp");
8655	if (rc)
8656		return (rc);
8657	tc = &pi->tc[p->cl];
8658	tc->params = *p;
8659	rc = -t4_sched_params(sc, FW_SCHED_TYPE_PKTSCHED, fw_level, fw_mode,
8660	    fw_rateunit, fw_ratemode, p->channel, p->cl, p->minrate, p->maxrate,
8661	    p->weight, p->pktsize, sleep_ok);
8662	if (rc == 0)
8663		tc->flags |= TX_SC_OK;
8664	else {
8665		/*
8666		 * Unknown state at this point, see tc->params for what was
8667		 * attempted.
8668		 */
8669		tc->flags &= ~TX_SC_OK;
8670	}
8671	end_synchronized_op(sc, sleep_ok ? 0 : LOCK_HELD);
8672
8673	return (rc);
8674}
8675
8676int
8677t4_set_sched_class(struct adapter *sc, struct t4_sched_params *p)
8678{
8679
8680	if (p->type != SCHED_CLASS_TYPE_PACKET)
8681		return (EINVAL);
8682
8683	if (p->subcmd == SCHED_CLASS_SUBCMD_CONFIG)
8684		return (set_sched_class_config(sc, p->u.config.minmax));
8685
8686	if (p->subcmd == SCHED_CLASS_SUBCMD_PARAMS)
8687		return (set_sched_class_params(sc, &p->u.params, 1));
8688
8689	return (EINVAL);
8690}
8691
8692int
8693t4_set_sched_queue(struct adapter *sc, struct t4_sched_queue *p)
8694{
8695	struct port_info *pi = NULL;
8696	struct vi_info *vi;
8697	struct sge_txq *txq;
8698	uint32_t fw_mnem, fw_queue, fw_class;
8699	int i, rc;
8700
8701	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4setsq");
8702	if (rc)
8703		return (rc);
8704
8705	if (p->port >= sc->params.nports) {
8706		rc = EINVAL;
8707		goto done;
8708	}
8709
8710	/* XXX: Only supported for the main VI. */
8711	pi = sc->port[p->port];
8712	vi = &pi->vi[0];
8713	if (!(vi->flags & VI_INIT_DONE)) {
8714		/* tx queues not set up yet */
8715		rc = EAGAIN;
8716		goto done;
8717	}
8718
8719	if (!in_range(p->queue, 0, vi->ntxq - 1) ||
8720	    !in_range(p->cl, 0, sc->chip_params->nsched_cls - 1)) {
8721		rc = EINVAL;
8722		goto done;
8723	}
8724
8725	/*
8726	 * Create a template for the FW_PARAMS_CMD mnemonic and value (TX
8727	 * Scheduling Class in this case).
8728	 */
8729	fw_mnem = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
8730	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_EQ_SCHEDCLASS_ETH));
8731	fw_class = p->cl < 0 ? 0xffffffff : p->cl;
8732
8733	/*
8734	 * If op.queue is non-negative, then we're only changing the scheduling
8735	 * on a single specified TX queue.
8736	 */
8737	if (p->queue >= 0) {
8738		txq = &sc->sge.txq[vi->first_txq + p->queue];
8739		fw_queue = (fw_mnem | V_FW_PARAMS_PARAM_YZ(txq->eq.cntxt_id));
8740		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &fw_queue,
8741		    &fw_class);
8742		goto done;
8743	}
8744
8745	/*
8746	 * Change the scheduling on all the TX queues for the
8747	 * interface.
8748	 */
8749	for_each_txq(vi, i, txq) {
8750		fw_queue = (fw_mnem | V_FW_PARAMS_PARAM_YZ(txq->eq.cntxt_id));
8751		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &fw_queue,
8752		    &fw_class);
8753		if (rc)
8754			goto done;
8755	}
8756
8757	rc = 0;
8758done:
8759	end_synchronized_op(sc, 0);
8760	return (rc);
8761}
8762
8763int
8764t4_os_find_pci_capability(struct adapter *sc, int cap)
8765{
8766	int i;
8767
8768	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
8769}
8770
8771int
8772t4_os_pci_save_state(struct adapter *sc)
8773{
8774	device_t dev;
8775	struct pci_devinfo *dinfo;
8776
8777	dev = sc->dev;
8778	dinfo = device_get_ivars(dev);
8779
8780	pci_cfg_save(dev, dinfo, 0);
8781	return (0);
8782}
8783
8784int
8785t4_os_pci_restore_state(struct adapter *sc)
8786{
8787	device_t dev;
8788	struct pci_devinfo *dinfo;
8789
8790	dev = sc->dev;
8791	dinfo = device_get_ivars(dev);
8792
8793	pci_cfg_restore(dev, dinfo);
8794	return (0);
8795}
8796
8797void
8798t4_os_portmod_changed(const struct adapter *sc, int idx)
8799{
8800	struct port_info *pi = sc->port[idx];
8801	struct vi_info *vi;
8802	struct ifnet *ifp;
8803	int v;
8804	static const char *mod_str[] = {
8805		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
8806	};
8807
8808	for_each_vi(pi, v, vi) {
8809		build_medialist(pi, &vi->media);
8810	}
8811
8812	ifp = pi->vi[0].ifp;
8813	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
8814		if_printf(ifp, "transceiver unplugged.\n");
8815	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
8816		if_printf(ifp, "unknown transceiver inserted.\n");
8817	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
8818		if_printf(ifp, "unsupported transceiver inserted.\n");
8819	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
8820		if_printf(ifp, "%s transceiver inserted.\n",
8821		    mod_str[pi->mod_type]);
8822	} else {
8823		if_printf(ifp, "transceiver (type %d) inserted.\n",
8824		    pi->mod_type);
8825	}
8826}
8827
8828void
8829t4_os_link_changed(struct adapter *sc, int idx, int link_stat, int reason)
8830{
8831	struct port_info *pi = sc->port[idx];
8832	struct vi_info *vi;
8833	struct ifnet *ifp;
8834	int v;
8835
8836	if (link_stat)
8837		pi->linkdnrc = -1;
8838	else {
8839		if (reason >= 0)
8840			pi->linkdnrc = reason;
8841	}
8842	for_each_vi(pi, v, vi) {
8843		ifp = vi->ifp;
8844		if (ifp == NULL)
8845			continue;
8846
8847		if (link_stat) {
8848			ifp->if_baudrate = IF_Mbps(pi->link_cfg.speed);
8849			if_link_state_change(ifp, LINK_STATE_UP);
8850		} else {
8851			if_link_state_change(ifp, LINK_STATE_DOWN);
8852		}
8853	}
8854}
8855
8856void
8857t4_iterate(void (*func)(struct adapter *, void *), void *arg)
8858{
8859	struct adapter *sc;
8860
8861	sx_slock(&t4_list_lock);
8862	SLIST_FOREACH(sc, &t4_list, link) {
8863		/*
8864		 * func should not make any assumptions about what state sc is
8865		 * in - the only guarantee is that sc->sc_lock is a valid lock.
8866		 */
8867		func(sc, arg);
8868	}
8869	sx_sunlock(&t4_list_lock);
8870}
8871
8872static int
8873t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
8874    struct thread *td)
8875{
8876	int rc;
8877	struct adapter *sc = dev->si_drv1;
8878
8879	rc = priv_check(td, PRIV_DRIVER);
8880	if (rc != 0)
8881		return (rc);
8882
8883	switch (cmd) {
8884	case CHELSIO_T4_GETREG: {
8885		struct t4_reg *edata = (struct t4_reg *)data;
8886
8887		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
8888			return (EFAULT);
8889
8890		if (edata->size == 4)
8891			edata->val = t4_read_reg(sc, edata->addr);
8892		else if (edata->size == 8)
8893			edata->val = t4_read_reg64(sc, edata->addr);
8894		else
8895			return (EINVAL);
8896
8897		break;
8898	}
8899	case CHELSIO_T4_SETREG: {
8900		struct t4_reg *edata = (struct t4_reg *)data;
8901
8902		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
8903			return (EFAULT);
8904
8905		if (edata->size == 4) {
8906			if (edata->val & 0xffffffff00000000)
8907				return (EINVAL);
8908			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
8909		} else if (edata->size == 8)
8910			t4_write_reg64(sc, edata->addr, edata->val);
8911		else
8912			return (EINVAL);
8913		break;
8914	}
8915	case CHELSIO_T4_REGDUMP: {
8916		struct t4_regdump *regs = (struct t4_regdump *)data;
8917		int reglen = t4_get_regs_len(sc);
8918		uint8_t *buf;
8919
8920		if (regs->len < reglen) {
8921			regs->len = reglen; /* hint to the caller */
8922			return (ENOBUFS);
8923		}
8924
8925		regs->len = reglen;
8926		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
8927		get_regs(sc, regs, buf);
8928		rc = copyout(buf, regs->data, reglen);
8929		free(buf, M_CXGBE);
8930		break;
8931	}
8932	case CHELSIO_T4_GET_FILTER_MODE:
8933		rc = get_filter_mode(sc, (uint32_t *)data);
8934		break;
8935	case CHELSIO_T4_SET_FILTER_MODE:
8936		rc = set_filter_mode(sc, *(uint32_t *)data);
8937		break;
8938	case CHELSIO_T4_GET_FILTER:
8939		rc = get_filter(sc, (struct t4_filter *)data);
8940		break;
8941	case CHELSIO_T4_SET_FILTER:
8942		rc = set_filter(sc, (struct t4_filter *)data);
8943		break;
8944	case CHELSIO_T4_DEL_FILTER:
8945		rc = del_filter(sc, (struct t4_filter *)data);
8946		break;
8947	case CHELSIO_T4_GET_SGE_CONTEXT:
8948		rc = get_sge_context(sc, (struct t4_sge_context *)data);
8949		break;
8950	case CHELSIO_T4_LOAD_FW:
8951		rc = load_fw(sc, (struct t4_data *)data);
8952		break;
8953	case CHELSIO_T4_GET_MEM:
8954		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
8955		break;
8956	case CHELSIO_T4_GET_I2C:
8957		rc = read_i2c(sc, (struct t4_i2c_data *)data);
8958		break;
8959	case CHELSIO_T4_CLEAR_STATS: {
8960		int i, v;
8961		u_int port_id = *(uint32_t *)data;
8962		struct port_info *pi;
8963		struct vi_info *vi;
8964
8965		if (port_id >= sc->params.nports)
8966			return (EINVAL);
8967		pi = sc->port[port_id];
8968		if (pi == NULL)
8969			return (EIO);
8970
8971		/* MAC stats */
8972		t4_clr_port_stats(sc, pi->tx_chan);
8973		pi->tx_parse_error = 0;
8974		mtx_lock(&sc->reg_lock);
8975		for_each_vi(pi, v, vi) {
8976			if (vi->flags & VI_INIT_DONE)
8977				t4_clr_vi_stats(sc, vi->viid);
8978		}
8979		mtx_unlock(&sc->reg_lock);
8980
8981		/*
8982		 * Since this command accepts a port, clear stats for
8983		 * all VIs on this port.
8984		 */
8985		for_each_vi(pi, v, vi) {
8986			if (vi->flags & VI_INIT_DONE) {
8987				struct sge_rxq *rxq;
8988				struct sge_txq *txq;
8989				struct sge_wrq *wrq;
8990
8991				for_each_rxq(vi, i, rxq) {
8992#if defined(INET) || defined(INET6)
8993					rxq->lro.lro_queued = 0;
8994					rxq->lro.lro_flushed = 0;
8995#endif
8996					rxq->rxcsum = 0;
8997					rxq->vlan_extraction = 0;
8998				}
8999
9000				for_each_txq(vi, i, txq) {
9001					txq->txcsum = 0;
9002					txq->tso_wrs = 0;
9003					txq->vlan_insertion = 0;
9004					txq->imm_wrs = 0;
9005					txq->sgl_wrs = 0;
9006					txq->txpkt_wrs = 0;
9007					txq->txpkts0_wrs = 0;
9008					txq->txpkts1_wrs = 0;
9009					txq->txpkts0_pkts = 0;
9010					txq->txpkts1_pkts = 0;
9011					mp_ring_reset_stats(txq->r);
9012				}
9013
9014#ifdef TCP_OFFLOAD
9015				/* nothing to clear for each ofld_rxq */
9016
9017				for_each_ofld_txq(vi, i, wrq) {
9018					wrq->tx_wrs_direct = 0;
9019					wrq->tx_wrs_copied = 0;
9020				}
9021#endif
9022
9023				if (IS_MAIN_VI(vi)) {
9024					wrq = &sc->sge.ctrlq[pi->port_id];
9025					wrq->tx_wrs_direct = 0;
9026					wrq->tx_wrs_copied = 0;
9027				}
9028			}
9029		}
9030		break;
9031	}
9032	case CHELSIO_T4_SCHED_CLASS:
9033		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
9034		break;
9035	case CHELSIO_T4_SCHED_QUEUE:
9036		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
9037		break;
9038	case CHELSIO_T4_GET_TRACER:
9039		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
9040		break;
9041	case CHELSIO_T4_SET_TRACER:
9042		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
9043		break;
9044	case CHELSIO_T4_LOAD_CFG:
9045		rc = load_cfg(sc, (struct t4_data *)data);
9046		break;
9047	default:
9048		rc = ENOTTY;
9049	}
9050
9051	return (rc);
9052}
9053
9054void
9055t4_db_full(struct adapter *sc)
9056{
9057
9058	CXGBE_UNIMPLEMENTED(__func__);
9059}
9060
9061void
9062t4_db_dropped(struct adapter *sc)
9063{
9064
9065	CXGBE_UNIMPLEMENTED(__func__);
9066}
9067
9068#ifdef TCP_OFFLOAD
9069void
9070t4_iscsi_init(struct adapter *sc, u_int tag_mask, const u_int *pgsz_order)
9071{
9072
9073	t4_write_reg(sc, A_ULP_RX_ISCSI_TAGMASK, tag_mask);
9074	t4_write_reg(sc, A_ULP_RX_ISCSI_PSZ, V_HPZ0(pgsz_order[0]) |
9075		V_HPZ1(pgsz_order[1]) | V_HPZ2(pgsz_order[2]) |
9076		V_HPZ3(pgsz_order[3]));
9077}
9078
9079static int
9080toe_capability(struct vi_info *vi, int enable)
9081{
9082	int rc;
9083	struct port_info *pi = vi->pi;
9084	struct adapter *sc = pi->adapter;
9085
9086	ASSERT_SYNCHRONIZED_OP(sc);
9087
9088	if (!is_offload(sc))
9089		return (ENODEV);
9090
9091	if (enable) {
9092		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
9093			/* TOE is already enabled. */
9094			return (0);
9095		}
9096
9097		/*
9098		 * We need the port's queues around so that we're able to send
9099		 * and receive CPLs to/from the TOE even if the ifnet for this
9100		 * port has never been UP'd administratively.
9101		 */
9102		if (!(vi->flags & VI_INIT_DONE)) {
9103			rc = vi_full_init(vi);
9104			if (rc)
9105				return (rc);
9106		}
9107		if (!(pi->vi[0].flags & VI_INIT_DONE)) {
9108			rc = vi_full_init(&pi->vi[0]);
9109			if (rc)
9110				return (rc);
9111		}
9112
9113		if (isset(&sc->offload_map, pi->port_id)) {
9114			/* TOE is enabled on another VI of this port. */
9115			pi->uld_vis++;
9116			return (0);
9117		}
9118
9119		if (!uld_active(sc, ULD_TOM)) {
9120			rc = t4_activate_uld(sc, ULD_TOM);
9121			if (rc == EAGAIN) {
9122				log(LOG_WARNING,
9123				    "You must kldload t4_tom.ko before trying "
9124				    "to enable TOE on a cxgbe interface.\n");
9125			}
9126			if (rc != 0)
9127				return (rc);
9128			KASSERT(sc->tom_softc != NULL,
9129			    ("%s: TOM activated but softc NULL", __func__));
9130			KASSERT(uld_active(sc, ULD_TOM),
9131			    ("%s: TOM activated but flag not set", __func__));
9132		}
9133
9134		/* Activate iWARP and iSCSI too, if the modules are loaded. */
9135		if (!uld_active(sc, ULD_IWARP))
9136			(void) t4_activate_uld(sc, ULD_IWARP);
9137		if (!uld_active(sc, ULD_ISCSI))
9138			(void) t4_activate_uld(sc, ULD_ISCSI);
9139
9140		pi->uld_vis++;
9141		setbit(&sc->offload_map, pi->port_id);
9142	} else {
9143		pi->uld_vis--;
9144
9145		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
9146			return (0);
9147
9148		KASSERT(uld_active(sc, ULD_TOM),
9149		    ("%s: TOM never initialized?", __func__));
9150		clrbit(&sc->offload_map, pi->port_id);
9151	}
9152
9153	return (0);
9154}
9155
9156/*
9157 * Add an upper layer driver to the global list.
9158 */
9159int
9160t4_register_uld(struct uld_info *ui)
9161{
9162	int rc = 0;
9163	struct uld_info *u;
9164
9165	sx_xlock(&t4_uld_list_lock);
9166	SLIST_FOREACH(u, &t4_uld_list, link) {
9167	    if (u->uld_id == ui->uld_id) {
9168		    rc = EEXIST;
9169		    goto done;
9170	    }
9171	}
9172
9173	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
9174	ui->refcount = 0;
9175done:
9176	sx_xunlock(&t4_uld_list_lock);
9177	return (rc);
9178}
9179
9180int
9181t4_unregister_uld(struct uld_info *ui)
9182{
9183	int rc = EINVAL;
9184	struct uld_info *u;
9185
9186	sx_xlock(&t4_uld_list_lock);
9187
9188	SLIST_FOREACH(u, &t4_uld_list, link) {
9189	    if (u == ui) {
9190		    if (ui->refcount > 0) {
9191			    rc = EBUSY;
9192			    goto done;
9193		    }
9194
9195		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
9196		    rc = 0;
9197		    goto done;
9198	    }
9199	}
9200done:
9201	sx_xunlock(&t4_uld_list_lock);
9202	return (rc);
9203}
9204
9205int
9206t4_activate_uld(struct adapter *sc, int id)
9207{
9208	int rc;
9209	struct uld_info *ui;
9210
9211	ASSERT_SYNCHRONIZED_OP(sc);
9212
9213	if (id < 0 || id > ULD_MAX)
9214		return (EINVAL);
9215	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
9216
9217	sx_slock(&t4_uld_list_lock);
9218
9219	SLIST_FOREACH(ui, &t4_uld_list, link) {
9220		if (ui->uld_id == id) {
9221			if (!(sc->flags & FULL_INIT_DONE)) {
9222				rc = adapter_full_init(sc);
9223				if (rc != 0)
9224					break;
9225			}
9226
9227			rc = ui->activate(sc);
9228			if (rc == 0) {
9229				setbit(&sc->active_ulds, id);
9230				ui->refcount++;
9231			}
9232			break;
9233		}
9234	}
9235
9236	sx_sunlock(&t4_uld_list_lock);
9237
9238	return (rc);
9239}
9240
9241int
9242t4_deactivate_uld(struct adapter *sc, int id)
9243{
9244	int rc;
9245	struct uld_info *ui;
9246
9247	ASSERT_SYNCHRONIZED_OP(sc);
9248
9249	if (id < 0 || id > ULD_MAX)
9250		return (EINVAL);
9251	rc = ENXIO;
9252
9253	sx_slock(&t4_uld_list_lock);
9254
9255	SLIST_FOREACH(ui, &t4_uld_list, link) {
9256		if (ui->uld_id == id) {
9257			rc = ui->deactivate(sc);
9258			if (rc == 0) {
9259				clrbit(&sc->active_ulds, id);
9260				ui->refcount--;
9261			}
9262			break;
9263		}
9264	}
9265
9266	sx_sunlock(&t4_uld_list_lock);
9267
9268	return (rc);
9269}
9270
9271int
9272uld_active(struct adapter *sc, int uld_id)
9273{
9274
9275	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
9276
9277	return (isset(&sc->active_ulds, uld_id));
9278}
9279#endif
9280
9281/*
9282 * Come up with reasonable defaults for some of the tunables, provided they're
9283 * not set by the user (in which case we'll use the values as is).
9284 */
9285static void
9286tweak_tunables(void)
9287{
9288	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
9289
9290	if (t4_ntxq10g < 1) {
9291#ifdef RSS
9292		t4_ntxq10g = rss_getnumbuckets();
9293#else
9294		t4_ntxq10g = min(nc, NTXQ_10G);
9295#endif
9296	}
9297
9298	if (t4_ntxq1g < 1) {
9299#ifdef RSS
9300		/* XXX: way too many for 1GbE? */
9301		t4_ntxq1g = rss_getnumbuckets();
9302#else
9303		t4_ntxq1g = min(nc, NTXQ_1G);
9304#endif
9305	}
9306
9307	if (t4_ntxq_vi < 1)
9308		t4_ntxq_vi = min(nc, NTXQ_VI);
9309
9310	if (t4_nrxq10g < 1) {
9311#ifdef RSS
9312		t4_nrxq10g = rss_getnumbuckets();
9313#else
9314		t4_nrxq10g = min(nc, NRXQ_10G);
9315#endif
9316	}
9317
9318	if (t4_nrxq1g < 1) {
9319#ifdef RSS
9320		/* XXX: way too many for 1GbE? */
9321		t4_nrxq1g = rss_getnumbuckets();
9322#else
9323		t4_nrxq1g = min(nc, NRXQ_1G);
9324#endif
9325	}
9326
9327	if (t4_nrxq_vi < 1)
9328		t4_nrxq_vi = min(nc, NRXQ_VI);
9329
9330#ifdef TCP_OFFLOAD
9331	if (t4_nofldtxq10g < 1)
9332		t4_nofldtxq10g = min(nc, NOFLDTXQ_10G);
9333
9334	if (t4_nofldtxq1g < 1)
9335		t4_nofldtxq1g = min(nc, NOFLDTXQ_1G);
9336
9337	if (t4_nofldtxq_vi < 1)
9338		t4_nofldtxq_vi = min(nc, NOFLDTXQ_VI);
9339
9340	if (t4_nofldrxq10g < 1)
9341		t4_nofldrxq10g = min(nc, NOFLDRXQ_10G);
9342
9343	if (t4_nofldrxq1g < 1)
9344		t4_nofldrxq1g = min(nc, NOFLDRXQ_1G);
9345
9346	if (t4_nofldrxq_vi < 1)
9347		t4_nofldrxq_vi = min(nc, NOFLDRXQ_VI);
9348
9349	if (t4_toecaps_allowed == -1)
9350		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
9351
9352	if (t4_rdmacaps_allowed == -1) {
9353		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
9354		    FW_CAPS_CONFIG_RDMA_RDMAC;
9355	}
9356
9357	if (t4_iscsicaps_allowed == -1) {
9358		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
9359		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
9360		    FW_CAPS_CONFIG_ISCSI_T10DIF;
9361	}
9362#else
9363	if (t4_toecaps_allowed == -1)
9364		t4_toecaps_allowed = 0;
9365
9366	if (t4_rdmacaps_allowed == -1)
9367		t4_rdmacaps_allowed = 0;
9368
9369	if (t4_iscsicaps_allowed == -1)
9370		t4_iscsicaps_allowed = 0;
9371#endif
9372
9373#ifdef DEV_NETMAP
9374	if (t4_nnmtxq_vi < 1)
9375		t4_nnmtxq_vi = min(nc, NNMTXQ_VI);
9376
9377	if (t4_nnmrxq_vi < 1)
9378		t4_nnmrxq_vi = min(nc, NNMRXQ_VI);
9379#endif
9380
9381	if (t4_tmr_idx_10g < 0 || t4_tmr_idx_10g >= SGE_NTIMERS)
9382		t4_tmr_idx_10g = TMR_IDX_10G;
9383
9384	if (t4_pktc_idx_10g < -1 || t4_pktc_idx_10g >= SGE_NCOUNTERS)
9385		t4_pktc_idx_10g = PKTC_IDX_10G;
9386
9387	if (t4_tmr_idx_1g < 0 || t4_tmr_idx_1g >= SGE_NTIMERS)
9388		t4_tmr_idx_1g = TMR_IDX_1G;
9389
9390	if (t4_pktc_idx_1g < -1 || t4_pktc_idx_1g >= SGE_NCOUNTERS)
9391		t4_pktc_idx_1g = PKTC_IDX_1G;
9392
9393	if (t4_qsize_txq < 128)
9394		t4_qsize_txq = 128;
9395
9396	if (t4_qsize_rxq < 128)
9397		t4_qsize_rxq = 128;
9398	while (t4_qsize_rxq & 7)
9399		t4_qsize_rxq++;
9400
9401	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
9402}
9403
9404#ifdef DDB
9405static void
9406t4_dump_tcb(struct adapter *sc, int tid)
9407{
9408	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
9409
9410	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
9411	save = t4_read_reg(sc, reg);
9412	base = sc->memwin[2].mw_base;
9413
9414	/* Dump TCB for the tid */
9415	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9416	tcb_addr += tid * TCB_SIZE;
9417
9418	if (is_t4(sc)) {
9419		pf = 0;
9420		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
9421	} else {
9422		pf = V_PFNUM(sc->pf);
9423		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
9424	}
9425	t4_write_reg(sc, reg, win_pos | pf);
9426	t4_read_reg(sc, reg);
9427
9428	off = tcb_addr - win_pos;
9429	for (i = 0; i < 4; i++) {
9430		uint32_t buf[8];
9431		for (j = 0; j < 8; j++, off += 4)
9432			buf[j] = htonl(t4_read_reg(sc, base + off));
9433
9434		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
9435		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
9436		    buf[7]);
9437	}
9438
9439	t4_write_reg(sc, reg, save);
9440	t4_read_reg(sc, reg);
9441}
9442
9443static void
9444t4_dump_devlog(struct adapter *sc)
9445{
9446	struct devlog_params *dparams = &sc->params.devlog;
9447	struct fw_devlog_e e;
9448	int i, first, j, m, nentries, rc;
9449	uint64_t ftstamp = UINT64_MAX;
9450
9451	if (dparams->start == 0) {
9452		db_printf("devlog params not valid\n");
9453		return;
9454	}
9455
9456	nentries = dparams->size / sizeof(struct fw_devlog_e);
9457	m = fwmtype_to_hwmtype(dparams->memtype);
9458
9459	/* Find the first entry. */
9460	first = -1;
9461	for (i = 0; i < nentries && !db_pager_quit; i++) {
9462		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9463		    sizeof(e), (void *)&e);
9464		if (rc != 0)
9465			break;
9466
9467		if (e.timestamp == 0)
9468			break;
9469
9470		e.timestamp = be64toh(e.timestamp);
9471		if (e.timestamp < ftstamp) {
9472			ftstamp = e.timestamp;
9473			first = i;
9474		}
9475	}
9476
9477	if (first == -1)
9478		return;
9479
9480	i = first;
9481	do {
9482		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9483		    sizeof(e), (void *)&e);
9484		if (rc != 0)
9485			return;
9486
9487		if (e.timestamp == 0)
9488			return;
9489
9490		e.timestamp = be64toh(e.timestamp);
9491		e.seqno = be32toh(e.seqno);
9492		for (j = 0; j < 8; j++)
9493			e.params[j] = be32toh(e.params[j]);
9494
9495		db_printf("%10d  %15ju  %8s  %8s  ",
9496		    e.seqno, e.timestamp,
9497		    (e.level < nitems(devlog_level_strings) ?
9498			devlog_level_strings[e.level] : "UNKNOWN"),
9499		    (e.facility < nitems(devlog_facility_strings) ?
9500			devlog_facility_strings[e.facility] : "UNKNOWN"));
9501		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
9502		    e.params[3], e.params[4], e.params[5], e.params[6],
9503		    e.params[7]);
9504
9505		if (++i == nentries)
9506			i = 0;
9507	} while (i != first && !db_pager_quit);
9508}
9509
9510static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
9511_DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
9512
9513DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
9514{
9515	device_t dev;
9516	int t;
9517	bool valid;
9518
9519	valid = false;
9520	t = db_read_token();
9521	if (t == tIDENT) {
9522		dev = device_lookup_by_name(db_tok_string);
9523		valid = true;
9524	}
9525	db_skip_to_eol();
9526	if (!valid) {
9527		db_printf("usage: show t4 devlog <nexus>\n");
9528		return;
9529	}
9530
9531	if (dev == NULL) {
9532		db_printf("device not found\n");
9533		return;
9534	}
9535
9536	t4_dump_devlog(device_get_softc(dev));
9537}
9538
9539DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
9540{
9541	device_t dev;
9542	int radix, tid, t;
9543	bool valid;
9544
9545	valid = false;
9546	radix = db_radix;
9547	db_radix = 10;
9548	t = db_read_token();
9549	if (t == tIDENT) {
9550		dev = device_lookup_by_name(db_tok_string);
9551		t = db_read_token();
9552		if (t == tNUMBER) {
9553			tid = db_tok_number;
9554			valid = true;
9555		}
9556	}
9557	db_radix = radix;
9558	db_skip_to_eol();
9559	if (!valid) {
9560		db_printf("usage: show t4 tcb <nexus> <tid>\n");
9561		return;
9562	}
9563
9564	if (dev == NULL) {
9565		db_printf("device not found\n");
9566		return;
9567	}
9568	if (tid < 0) {
9569		db_printf("invalid tid\n");
9570		return;
9571	}
9572
9573	t4_dump_tcb(device_get_softc(dev), tid);
9574}
9575#endif
9576
9577static struct sx mlu;	/* mod load unload */
9578SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
9579
9580static int
9581mod_event(module_t mod, int cmd, void *arg)
9582{
9583	int rc = 0;
9584	static int loaded = 0;
9585
9586	switch (cmd) {
9587	case MOD_LOAD:
9588		sx_xlock(&mlu);
9589		if (loaded++ == 0) {
9590			t4_sge_modload();
9591			t4_register_cpl_handler(CPL_SET_TCB_RPL, set_tcb_rpl);
9592			t4_register_cpl_handler(CPL_L2T_WRITE_RPL, l2t_write_rpl);
9593			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
9594			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
9595			sx_init(&t4_list_lock, "T4/T5 adapters");
9596			SLIST_INIT(&t4_list);
9597#ifdef TCP_OFFLOAD
9598			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
9599			SLIST_INIT(&t4_uld_list);
9600#endif
9601			t4_tracer_modload();
9602			tweak_tunables();
9603		}
9604		sx_xunlock(&mlu);
9605		break;
9606
9607	case MOD_UNLOAD:
9608		sx_xlock(&mlu);
9609		if (--loaded == 0) {
9610			int tries;
9611
9612			sx_slock(&t4_list_lock);
9613			if (!SLIST_EMPTY(&t4_list)) {
9614				rc = EBUSY;
9615				sx_sunlock(&t4_list_lock);
9616				goto done_unload;
9617			}
9618#ifdef TCP_OFFLOAD
9619			sx_slock(&t4_uld_list_lock);
9620			if (!SLIST_EMPTY(&t4_uld_list)) {
9621				rc = EBUSY;
9622				sx_sunlock(&t4_uld_list_lock);
9623				sx_sunlock(&t4_list_lock);
9624				goto done_unload;
9625			}
9626#endif
9627			tries = 0;
9628			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
9629				uprintf("%ju clusters with custom free routine "
9630				    "still is use.\n", t4_sge_extfree_refs());
9631				pause("t4unload", 2 * hz);
9632			}
9633#ifdef TCP_OFFLOAD
9634			sx_sunlock(&t4_uld_list_lock);
9635#endif
9636			sx_sunlock(&t4_list_lock);
9637
9638			if (t4_sge_extfree_refs() == 0) {
9639				t4_tracer_modunload();
9640#ifdef TCP_OFFLOAD
9641				sx_destroy(&t4_uld_list_lock);
9642#endif
9643				sx_destroy(&t4_list_lock);
9644				t4_sge_modunload();
9645				loaded = 0;
9646			} else {
9647				rc = EBUSY;
9648				loaded++;	/* undo earlier decrement */
9649			}
9650		}
9651done_unload:
9652		sx_xunlock(&mlu);
9653		break;
9654	}
9655
9656	return (rc);
9657}
9658
9659static devclass_t t4_devclass, t5_devclass, t6_devclass;
9660static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
9661static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
9662
9663DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
9664MODULE_VERSION(t4nex, 1);
9665MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
9666
9667DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
9668MODULE_VERSION(t5nex, 1);
9669MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
9670
9671DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
9672MODULE_VERSION(t6nex, 1);
9673MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
9674#ifdef DEV_NETMAP
9675MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
9676#endif /* DEV_NETMAP */
9677
9678DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
9679MODULE_VERSION(cxgbe, 1);
9680
9681DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
9682MODULE_VERSION(cxl, 1);
9683
9684DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
9685MODULE_VERSION(cc, 1);
9686
9687DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
9688MODULE_VERSION(vcxgbe, 1);
9689
9690DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
9691MODULE_VERSION(vcxl, 1);
9692
9693DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
9694MODULE_VERSION(vcc, 1);
9695