t4_main.c revision 309560
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 309560 2016-12-05 20:43:25Z 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 read_card_mem(struct adapter *, int, struct t4_mem_range *);
542static int read_i2c(struct adapter *, struct t4_i2c_data *);
543#ifdef TCP_OFFLOAD
544static int toe_capability(struct vi_info *, int);
545#endif
546static int mod_event(module_t, int, void *);
547
548struct {
549	uint16_t device;
550	char *desc;
551} t4_pciids[] = {
552	{0xa000, "Chelsio Terminator 4 FPGA"},
553	{0x4400, "Chelsio T440-dbg"},
554	{0x4401, "Chelsio T420-CR"},
555	{0x4402, "Chelsio T422-CR"},
556	{0x4403, "Chelsio T440-CR"},
557	{0x4404, "Chelsio T420-BCH"},
558	{0x4405, "Chelsio T440-BCH"},
559	{0x4406, "Chelsio T440-CH"},
560	{0x4407, "Chelsio T420-SO"},
561	{0x4408, "Chelsio T420-CX"},
562	{0x4409, "Chelsio T420-BT"},
563	{0x440a, "Chelsio T404-BT"},
564	{0x440e, "Chelsio T440-LP-CR"},
565}, t5_pciids[] = {
566	{0xb000, "Chelsio Terminator 5 FPGA"},
567	{0x5400, "Chelsio T580-dbg"},
568	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
569	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
570	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
571	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
572	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
573	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
574	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
575	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
576	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
577	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
578	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
579	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
580	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
581#ifdef notyet
582	{0x5404,  "Chelsio T520-BCH"},
583	{0x5405,  "Chelsio T540-BCH"},
584	{0x5406,  "Chelsio T540-CH"},
585	{0x5408,  "Chelsio T520-CX"},
586	{0x540b,  "Chelsio B520-SR"},
587	{0x540c,  "Chelsio B504-BT"},
588	{0x540f,  "Chelsio Amsterdam"},
589	{0x5413,  "Chelsio T580-CHR"},
590#endif
591}, t6_pciids[] = {
592	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
593	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
594	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
595	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
596	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
597	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
598	{0x6410, "Chelsio T62100-DBG"},		/* 2 x 40/50/100G, debug */
599};
600
601#ifdef TCP_OFFLOAD
602/*
603 * service_iq() has an iq and needs the fl.  Offset of fl from the iq should be
604 * exactly the same for both rxq and ofld_rxq.
605 */
606CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
607CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
608#endif
609CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
610
611static int
612t4_probe(device_t dev)
613{
614	int i;
615	uint16_t v = pci_get_vendor(dev);
616	uint16_t d = pci_get_device(dev);
617	uint8_t f = pci_get_function(dev);
618
619	if (v != PCI_VENDOR_ID_CHELSIO)
620		return (ENXIO);
621
622	/* Attach only to PF0 of the FPGA */
623	if (d == 0xa000 && f != 0)
624		return (ENXIO);
625
626	for (i = 0; i < nitems(t4_pciids); i++) {
627		if (d == t4_pciids[i].device) {
628			device_set_desc(dev, t4_pciids[i].desc);
629			return (BUS_PROBE_DEFAULT);
630		}
631	}
632
633	return (ENXIO);
634}
635
636static int
637t5_probe(device_t dev)
638{
639	int i;
640	uint16_t v = pci_get_vendor(dev);
641	uint16_t d = pci_get_device(dev);
642	uint8_t f = pci_get_function(dev);
643
644	if (v != PCI_VENDOR_ID_CHELSIO)
645		return (ENXIO);
646
647	/* Attach only to PF0 of the FPGA */
648	if (d == 0xb000 && f != 0)
649		return (ENXIO);
650
651	for (i = 0; i < nitems(t5_pciids); i++) {
652		if (d == t5_pciids[i].device) {
653			device_set_desc(dev, t5_pciids[i].desc);
654			return (BUS_PROBE_DEFAULT);
655		}
656	}
657
658	return (ENXIO);
659}
660
661static int
662t6_probe(device_t dev)
663{
664	int i;
665	uint16_t v = pci_get_vendor(dev);
666	uint16_t d = pci_get_device(dev);
667
668	if (v != PCI_VENDOR_ID_CHELSIO)
669		return (ENXIO);
670
671	for (i = 0; i < nitems(t6_pciids); i++) {
672		if (d == t6_pciids[i].device) {
673			device_set_desc(dev, t6_pciids[i].desc);
674			return (BUS_PROBE_DEFAULT);
675		}
676	}
677
678	return (ENXIO);
679}
680
681static void
682t5_attribute_workaround(device_t dev)
683{
684	device_t root_port;
685	uint32_t v;
686
687	/*
688	 * The T5 chips do not properly echo the No Snoop and Relaxed
689	 * Ordering attributes when replying to a TLP from a Root
690	 * Port.  As a workaround, find the parent Root Port and
691	 * disable No Snoop and Relaxed Ordering.  Note that this
692	 * affects all devices under this root port.
693	 */
694	root_port = pci_find_pcie_root_port(dev);
695	if (root_port == NULL) {
696		device_printf(dev, "Unable to find parent root port\n");
697		return;
698	}
699
700	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
701	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
702	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
703	    0)
704		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
705		    device_get_nameunit(root_port));
706}
707
708static const struct devnames devnames[] = {
709	{
710		.nexus_name = "t4nex",
711		.ifnet_name = "cxgbe",
712		.vi_ifnet_name = "vcxgbe",
713		.pf03_drv_name = "t4iov",
714		.vf_nexus_name = "t4vf",
715		.vf_ifnet_name = "cxgbev"
716	}, {
717		.nexus_name = "t5nex",
718		.ifnet_name = "cxl",
719		.vi_ifnet_name = "vcxl",
720		.pf03_drv_name = "t5iov",
721		.vf_nexus_name = "t5vf",
722		.vf_ifnet_name = "cxlv"
723	}, {
724		.nexus_name = "t6nex",
725		.ifnet_name = "cc",
726		.vi_ifnet_name = "vcc",
727		.pf03_drv_name = "t6iov",
728		.vf_nexus_name = "t6vf",
729		.vf_ifnet_name = "ccv"
730	}
731};
732
733void
734t4_init_devnames(struct adapter *sc)
735{
736	int id;
737
738	id = chip_id(sc);
739	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
740		sc->names = &devnames[id - CHELSIO_T4];
741	else {
742		device_printf(sc->dev, "chip id %d is not supported.\n", id);
743		sc->names = NULL;
744	}
745}
746
747static int
748t4_attach(device_t dev)
749{
750	struct adapter *sc;
751	int rc = 0, i, j, n10g, n1g, rqidx, tqidx;
752	struct make_dev_args mda;
753	struct intrs_and_queues iaq;
754	struct sge *s;
755	uint8_t *buf;
756#ifdef TCP_OFFLOAD
757	int ofld_rqidx, ofld_tqidx;
758#endif
759#ifdef DEV_NETMAP
760	int nm_rqidx, nm_tqidx;
761#endif
762	int num_vis;
763
764	sc = device_get_softc(dev);
765	sc->dev = dev;
766	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
767
768	if ((pci_get_device(dev) & 0xff00) == 0x5400)
769		t5_attribute_workaround(dev);
770	pci_enable_busmaster(dev);
771	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
772		uint32_t v;
773
774		pci_set_max_read_req(dev, 4096);
775		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
776		v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
777		pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
778
779		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
780	}
781
782	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
783	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
784	sc->traceq = -1;
785	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
786	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
787	    device_get_nameunit(dev));
788
789	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
790	    device_get_nameunit(dev));
791	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
792	t4_add_adapter(sc);
793
794	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
795	TAILQ_INIT(&sc->sfl);
796	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
797
798	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
799
800	rc = t4_map_bars_0_and_4(sc);
801	if (rc != 0)
802		goto done; /* error message displayed already */
803
804	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
805
806	/* Prepare the adapter for operation. */
807	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
808	rc = -t4_prep_adapter(sc, buf);
809	free(buf, M_CXGBE);
810	if (rc != 0) {
811		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
812		goto done;
813	}
814
815	/*
816	 * This is the real PF# to which we're attaching.  Works from within PCI
817	 * passthrough environments too, where pci_get_function() could return a
818	 * different PF# depending on the passthrough configuration.  We need to
819	 * use the real PF# in all our communication with the firmware.
820	 */
821	j = t4_read_reg(sc, A_PL_WHOAMI);
822	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
823	sc->mbox = sc->pf;
824
825	t4_init_devnames(sc);
826	if (sc->names == NULL) {
827		rc = ENOTSUP;
828		goto done; /* error message displayed already */
829	}
830
831	/*
832	 * Do this really early, with the memory windows set up even before the
833	 * character device.  The userland tool's register i/o and mem read
834	 * will work even in "recovery mode".
835	 */
836	setup_memwin(sc);
837	if (t4_init_devlog_params(sc, 0) == 0)
838		fixup_devlog_params(sc);
839	make_dev_args_init(&mda);
840	mda.mda_devsw = &t4_cdevsw;
841	mda.mda_uid = UID_ROOT;
842	mda.mda_gid = GID_WHEEL;
843	mda.mda_mode = 0600;
844	mda.mda_si_drv1 = sc;
845	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
846	if (rc != 0)
847		device_printf(dev, "failed to create nexus char device: %d.\n",
848		    rc);
849
850	/* Go no further if recovery mode has been requested. */
851	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
852		device_printf(dev, "recovery mode.\n");
853		goto done;
854	}
855
856#if defined(__i386__)
857	if ((cpu_feature & CPUID_CX8) == 0) {
858		device_printf(dev, "64 bit atomics not available.\n");
859		rc = ENOTSUP;
860		goto done;
861	}
862#endif
863
864	/* Prepare the firmware for operation */
865	rc = prep_firmware(sc);
866	if (rc != 0)
867		goto done; /* error message displayed already */
868
869	rc = get_params__post_init(sc);
870	if (rc != 0)
871		goto done; /* error message displayed already */
872
873	rc = set_params__post_init(sc);
874	if (rc != 0)
875		goto done; /* error message displayed already */
876
877	rc = t4_map_bar_2(sc);
878	if (rc != 0)
879		goto done; /* error message displayed already */
880
881	rc = t4_create_dma_tag(sc);
882	if (rc != 0)
883		goto done; /* error message displayed already */
884
885	/*
886	 * Number of VIs to create per-port.  The first VI is the "main" regular
887	 * VI for the port.  The rest are additional virtual interfaces on the
888	 * same physical port.  Note that the main VI does not have native
889	 * netmap support but the extra VIs do.
890	 *
891	 * Limit the number of VIs per port to the number of available
892	 * MAC addresses per port.
893	 */
894	if (t4_num_vis >= 1)
895		num_vis = t4_num_vis;
896	else
897		num_vis = 1;
898	if (num_vis > nitems(vi_mac_funcs)) {
899		num_vis = nitems(vi_mac_funcs);
900		device_printf(dev, "Number of VIs limited to %d\n", num_vis);
901	}
902
903	/*
904	 * First pass over all the ports - allocate VIs and initialize some
905	 * basic parameters like mac address, port type, etc.  We also figure
906	 * out whether a port is 10G or 1G and use that information when
907	 * calculating how many interrupts to attempt to allocate.
908	 */
909	n10g = n1g = 0;
910	for_each_port(sc, i) {
911		struct port_info *pi;
912
913		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
914		sc->port[i] = pi;
915
916		/* These must be set before t4_port_init */
917		pi->adapter = sc;
918		pi->port_id = i;
919		/*
920		 * XXX: vi[0] is special so we can't delay this allocation until
921		 * pi->nvi's final value is known.
922		 */
923		pi->vi = malloc(sizeof(struct vi_info) * num_vis, M_CXGBE,
924		    M_ZERO | M_WAITOK);
925
926		/*
927		 * Allocate the "main" VI and initialize parameters
928		 * like mac addr.
929		 */
930		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
931		if (rc != 0) {
932			device_printf(dev, "unable to initialize port %d: %d\n",
933			    i, rc);
934			free(pi->vi, M_CXGBE);
935			free(pi, M_CXGBE);
936			sc->port[i] = NULL;
937			goto done;
938		}
939
940		pi->link_cfg.requested_fc &= ~(PAUSE_TX | PAUSE_RX);
941		pi->link_cfg.requested_fc |= t4_pause_settings;
942		pi->link_cfg.fc &= ~(PAUSE_TX | PAUSE_RX);
943		pi->link_cfg.fc |= t4_pause_settings;
944
945		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, &pi->link_cfg);
946		if (rc != 0) {
947			device_printf(dev, "port %d l1cfg failed: %d\n", i, rc);
948			free(pi->vi, M_CXGBE);
949			free(pi, M_CXGBE);
950			sc->port[i] = NULL;
951			goto done;
952		}
953
954		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
955		    device_get_nameunit(dev), i);
956		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
957		sc->chan_map[pi->tx_chan] = i;
958
959		pi->tc = malloc(sizeof(struct tx_sched_class) *
960		    sc->chip_params->nsched_cls, M_CXGBE, M_ZERO | M_WAITOK);
961
962		if (port_top_speed(pi) >= 10) {
963			n10g++;
964		} else {
965			n1g++;
966		}
967
968		pi->linkdnrc = -1;
969
970		pi->dev = device_add_child(dev, sc->names->ifnet_name, -1);
971		if (pi->dev == NULL) {
972			device_printf(dev,
973			    "failed to add device for port %d.\n", i);
974			rc = ENXIO;
975			goto done;
976		}
977		pi->vi[0].dev = pi->dev;
978		device_set_softc(pi->dev, pi);
979	}
980
981	/*
982	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
983	 */
984	rc = cfg_itype_and_nqueues(sc, n10g, n1g, num_vis, &iaq);
985	if (rc != 0)
986		goto done; /* error message displayed already */
987	if (iaq.nrxq_vi + iaq.nofldrxq_vi + iaq.nnmrxq_vi == 0)
988		num_vis = 1;
989
990	sc->intr_type = iaq.intr_type;
991	sc->intr_count = iaq.nirq;
992
993	s = &sc->sge;
994	s->nrxq = n10g * iaq.nrxq10g + n1g * iaq.nrxq1g;
995	s->ntxq = n10g * iaq.ntxq10g + n1g * iaq.ntxq1g;
996	if (num_vis > 1) {
997		s->nrxq += (n10g + n1g) * (num_vis - 1) * iaq.nrxq_vi;
998		s->ntxq += (n10g + n1g) * (num_vis - 1) * iaq.ntxq_vi;
999	}
1000	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1001	s->neq += sc->params.nports + 1;/* ctrl queues: 1 per port + 1 mgmt */
1002	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1003#ifdef TCP_OFFLOAD
1004	if (is_offload(sc)) {
1005		s->nofldrxq = n10g * iaq.nofldrxq10g + n1g * iaq.nofldrxq1g;
1006		s->nofldtxq = n10g * iaq.nofldtxq10g + n1g * iaq.nofldtxq1g;
1007		if (num_vis > 1) {
1008			s->nofldrxq += (n10g + n1g) * (num_vis - 1) *
1009			    iaq.nofldrxq_vi;
1010			s->nofldtxq += (n10g + n1g) * (num_vis - 1) *
1011			    iaq.nofldtxq_vi;
1012		}
1013		s->neq += s->nofldtxq + s->nofldrxq;
1014		s->niq += s->nofldrxq;
1015
1016		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1017		    M_CXGBE, M_ZERO | M_WAITOK);
1018		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_wrq),
1019		    M_CXGBE, M_ZERO | M_WAITOK);
1020	}
1021#endif
1022#ifdef DEV_NETMAP
1023	if (num_vis > 1) {
1024		s->nnmrxq = (n10g + n1g) * (num_vis - 1) * iaq.nnmrxq_vi;
1025		s->nnmtxq = (n10g + n1g) * (num_vis - 1) * iaq.nnmtxq_vi;
1026	}
1027	s->neq += s->nnmtxq + s->nnmrxq;
1028	s->niq += s->nnmrxq;
1029
1030	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1031	    M_CXGBE, M_ZERO | M_WAITOK);
1032	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1033	    M_CXGBE, M_ZERO | M_WAITOK);
1034#endif
1035
1036	s->ctrlq = malloc(sc->params.nports * sizeof(struct sge_wrq), M_CXGBE,
1037	    M_ZERO | M_WAITOK);
1038	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1039	    M_ZERO | M_WAITOK);
1040	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1041	    M_ZERO | M_WAITOK);
1042	s->iqmap = malloc(s->niq * sizeof(struct sge_iq *), M_CXGBE,
1043	    M_ZERO | M_WAITOK);
1044	s->eqmap = malloc(s->neq * sizeof(struct sge_eq *), M_CXGBE,
1045	    M_ZERO | M_WAITOK);
1046
1047	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1048	    M_ZERO | M_WAITOK);
1049
1050	t4_init_l2t(sc, M_WAITOK);
1051
1052	/*
1053	 * Second pass over the ports.  This time we know the number of rx and
1054	 * tx queues that each port should get.
1055	 */
1056	rqidx = tqidx = 0;
1057#ifdef TCP_OFFLOAD
1058	ofld_rqidx = ofld_tqidx = 0;
1059#endif
1060#ifdef DEV_NETMAP
1061	nm_rqidx = nm_tqidx = 0;
1062#endif
1063	for_each_port(sc, i) {
1064		struct port_info *pi = sc->port[i];
1065		struct vi_info *vi;
1066
1067		if (pi == NULL)
1068			continue;
1069
1070		pi->nvi = num_vis;
1071		for_each_vi(pi, j, vi) {
1072			vi->pi = pi;
1073			vi->qsize_rxq = t4_qsize_rxq;
1074			vi->qsize_txq = t4_qsize_txq;
1075
1076			vi->first_rxq = rqidx;
1077			vi->first_txq = tqidx;
1078			if (port_top_speed(pi) >= 10) {
1079				vi->tmr_idx = t4_tmr_idx_10g;
1080				vi->pktc_idx = t4_pktc_idx_10g;
1081				vi->flags |= iaq.intr_flags_10g & INTR_RXQ;
1082				vi->nrxq = j == 0 ? iaq.nrxq10g : iaq.nrxq_vi;
1083				vi->ntxq = j == 0 ? iaq.ntxq10g : iaq.ntxq_vi;
1084			} else {
1085				vi->tmr_idx = t4_tmr_idx_1g;
1086				vi->pktc_idx = t4_pktc_idx_1g;
1087				vi->flags |= iaq.intr_flags_1g & INTR_RXQ;
1088				vi->nrxq = j == 0 ? iaq.nrxq1g : iaq.nrxq_vi;
1089				vi->ntxq = j == 0 ? iaq.ntxq1g : iaq.ntxq_vi;
1090			}
1091			rqidx += vi->nrxq;
1092			tqidx += vi->ntxq;
1093
1094			if (j == 0 && vi->ntxq > 1)
1095				vi->rsrv_noflowq = iaq.rsrv_noflowq ? 1 : 0;
1096			else
1097				vi->rsrv_noflowq = 0;
1098
1099#ifdef TCP_OFFLOAD
1100			vi->first_ofld_rxq = ofld_rqidx;
1101			vi->first_ofld_txq = ofld_tqidx;
1102			if (port_top_speed(pi) >= 10) {
1103				vi->flags |= iaq.intr_flags_10g & INTR_OFLD_RXQ;
1104				vi->nofldrxq = j == 0 ? iaq.nofldrxq10g :
1105				    iaq.nofldrxq_vi;
1106				vi->nofldtxq = j == 0 ? iaq.nofldtxq10g :
1107				    iaq.nofldtxq_vi;
1108			} else {
1109				vi->flags |= iaq.intr_flags_1g & INTR_OFLD_RXQ;
1110				vi->nofldrxq = j == 0 ? iaq.nofldrxq1g :
1111				    iaq.nofldrxq_vi;
1112				vi->nofldtxq = j == 0 ? iaq.nofldtxq1g :
1113				    iaq.nofldtxq_vi;
1114			}
1115			ofld_rqidx += vi->nofldrxq;
1116			ofld_tqidx += vi->nofldtxq;
1117#endif
1118#ifdef DEV_NETMAP
1119			if (j > 0) {
1120				vi->first_nm_rxq = nm_rqidx;
1121				vi->first_nm_txq = nm_tqidx;
1122				vi->nnmrxq = iaq.nnmrxq_vi;
1123				vi->nnmtxq = iaq.nnmtxq_vi;
1124				nm_rqidx += vi->nnmrxq;
1125				nm_tqidx += vi->nnmtxq;
1126			}
1127#endif
1128		}
1129	}
1130
1131	rc = t4_setup_intr_handlers(sc);
1132	if (rc != 0) {
1133		device_printf(dev,
1134		    "failed to setup interrupt handlers: %d\n", rc);
1135		goto done;
1136	}
1137
1138	rc = bus_generic_attach(dev);
1139	if (rc != 0) {
1140		device_printf(dev,
1141		    "failed to attach all child ports: %d\n", rc);
1142		goto done;
1143	}
1144
1145	device_printf(dev,
1146	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1147	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1148	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1149	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1150	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1151
1152	t4_set_desc(sc);
1153
1154done:
1155	if (rc != 0 && sc->cdev) {
1156		/* cdev was created and so cxgbetool works; recover that way. */
1157		device_printf(dev,
1158		    "error during attach, adapter is now in recovery mode.\n");
1159		rc = 0;
1160	}
1161
1162	if (rc != 0)
1163		t4_detach_common(dev);
1164	else
1165		t4_sysctls(sc);
1166
1167	return (rc);
1168}
1169
1170/*
1171 * Idempotent
1172 */
1173static int
1174t4_detach(device_t dev)
1175{
1176	struct adapter *sc;
1177
1178	sc = device_get_softc(dev);
1179
1180	return (t4_detach_common(dev));
1181}
1182
1183int
1184t4_detach_common(device_t dev)
1185{
1186	struct adapter *sc;
1187	struct port_info *pi;
1188	int i, rc;
1189
1190	sc = device_get_softc(dev);
1191
1192	if (sc->flags & FULL_INIT_DONE) {
1193		if (!(sc->flags & IS_VF))
1194			t4_intr_disable(sc);
1195	}
1196
1197	if (sc->cdev) {
1198		destroy_dev(sc->cdev);
1199		sc->cdev = NULL;
1200	}
1201
1202	if (device_is_attached(dev)) {
1203		rc = bus_generic_detach(dev);
1204		if (rc) {
1205			device_printf(dev,
1206			    "failed to detach child devices: %d\n", rc);
1207			return (rc);
1208		}
1209	}
1210
1211	for (i = 0; i < sc->intr_count; i++)
1212		t4_free_irq(sc, &sc->irq[i]);
1213
1214	for (i = 0; i < MAX_NPORTS; i++) {
1215		pi = sc->port[i];
1216		if (pi) {
1217			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1218			if (pi->dev)
1219				device_delete_child(dev, pi->dev);
1220
1221			mtx_destroy(&pi->pi_lock);
1222			free(pi->vi, M_CXGBE);
1223			free(pi->tc, M_CXGBE);
1224			free(pi, M_CXGBE);
1225		}
1226	}
1227
1228	if (sc->flags & FULL_INIT_DONE)
1229		adapter_full_uninit(sc);
1230
1231	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1232		t4_fw_bye(sc, sc->mbox);
1233
1234	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1235		pci_release_msi(dev);
1236
1237	if (sc->regs_res)
1238		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1239		    sc->regs_res);
1240
1241	if (sc->udbs_res)
1242		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1243		    sc->udbs_res);
1244
1245	if (sc->msix_res)
1246		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1247		    sc->msix_res);
1248
1249	if (sc->l2t)
1250		t4_free_l2t(sc->l2t);
1251
1252#ifdef TCP_OFFLOAD
1253	free(sc->sge.ofld_rxq, M_CXGBE);
1254	free(sc->sge.ofld_txq, M_CXGBE);
1255#endif
1256#ifdef DEV_NETMAP
1257	free(sc->sge.nm_rxq, M_CXGBE);
1258	free(sc->sge.nm_txq, M_CXGBE);
1259#endif
1260	free(sc->irq, M_CXGBE);
1261	free(sc->sge.rxq, M_CXGBE);
1262	free(sc->sge.txq, M_CXGBE);
1263	free(sc->sge.ctrlq, M_CXGBE);
1264	free(sc->sge.iqmap, M_CXGBE);
1265	free(sc->sge.eqmap, M_CXGBE);
1266	free(sc->tids.ftid_tab, M_CXGBE);
1267	t4_destroy_dma_tag(sc);
1268	if (mtx_initialized(&sc->sc_lock)) {
1269		sx_xlock(&t4_list_lock);
1270		SLIST_REMOVE(&t4_list, sc, adapter, link);
1271		sx_xunlock(&t4_list_lock);
1272		mtx_destroy(&sc->sc_lock);
1273	}
1274
1275	callout_drain(&sc->sfl_callout);
1276	if (mtx_initialized(&sc->tids.ftid_lock))
1277		mtx_destroy(&sc->tids.ftid_lock);
1278	if (mtx_initialized(&sc->sfl_lock))
1279		mtx_destroy(&sc->sfl_lock);
1280	if (mtx_initialized(&sc->ifp_lock))
1281		mtx_destroy(&sc->ifp_lock);
1282	if (mtx_initialized(&sc->reg_lock))
1283		mtx_destroy(&sc->reg_lock);
1284
1285	for (i = 0; i < NUM_MEMWIN; i++) {
1286		struct memwin *mw = &sc->memwin[i];
1287
1288		if (rw_initialized(&mw->mw_lock))
1289			rw_destroy(&mw->mw_lock);
1290	}
1291
1292	bzero(sc, sizeof(*sc));
1293
1294	return (0);
1295}
1296
1297static int
1298cxgbe_probe(device_t dev)
1299{
1300	char buf[128];
1301	struct port_info *pi = device_get_softc(dev);
1302
1303	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
1304	device_set_desc_copy(dev, buf);
1305
1306	return (BUS_PROBE_DEFAULT);
1307}
1308
1309#define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
1310    IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
1311    IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS)
1312#define T4_CAP_ENABLE (T4_CAP)
1313
1314static int
1315cxgbe_vi_attach(device_t dev, struct vi_info *vi)
1316{
1317	struct ifnet *ifp;
1318	struct sbuf *sb;
1319
1320	vi->xact_addr_filt = -1;
1321	callout_init(&vi->tick, 1);
1322
1323	/* Allocate an ifnet and set it up */
1324	ifp = if_alloc(IFT_ETHER);
1325	if (ifp == NULL) {
1326		device_printf(dev, "Cannot allocate ifnet\n");
1327		return (ENOMEM);
1328	}
1329	vi->ifp = ifp;
1330	ifp->if_softc = vi;
1331
1332	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1333	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1334
1335	ifp->if_init = cxgbe_init;
1336	ifp->if_ioctl = cxgbe_ioctl;
1337	ifp->if_transmit = cxgbe_transmit;
1338	ifp->if_qflush = cxgbe_qflush;
1339
1340	ifp->if_capabilities = T4_CAP;
1341#ifdef TCP_OFFLOAD
1342	if (vi->nofldrxq != 0)
1343		ifp->if_capabilities |= IFCAP_TOE;
1344#endif
1345	ifp->if_capenable = T4_CAP_ENABLE;
1346	ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
1347	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
1348
1349	ifp->if_hw_tsomax = 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
1350	ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS;
1351	ifp->if_hw_tsomaxsegsize = 65536;
1352
1353	/* Initialize ifmedia for this VI */
1354	ifmedia_init(&vi->media, IFM_IMASK, cxgbe_media_change,
1355	    cxgbe_media_status);
1356	build_medialist(vi->pi, &vi->media);
1357
1358	vi->vlan_c = EVENTHANDLER_REGISTER(vlan_config, cxgbe_vlan_config, ifp,
1359	    EVENTHANDLER_PRI_ANY);
1360
1361	ether_ifattach(ifp, vi->hw_addr);
1362#ifdef DEV_NETMAP
1363	if (vi->nnmrxq != 0)
1364		cxgbe_nm_attach(vi);
1365#endif
1366	sb = sbuf_new_auto();
1367	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
1368#ifdef TCP_OFFLOAD
1369	if (ifp->if_capabilities & IFCAP_TOE)
1370		sbuf_printf(sb, "; %d txq, %d rxq (TOE)",
1371		    vi->nofldtxq, vi->nofldrxq);
1372#endif
1373#ifdef DEV_NETMAP
1374	if (ifp->if_capabilities & IFCAP_NETMAP)
1375		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
1376		    vi->nnmtxq, vi->nnmrxq);
1377#endif
1378	sbuf_finish(sb);
1379	device_printf(dev, "%s\n", sbuf_data(sb));
1380	sbuf_delete(sb);
1381
1382	vi_sysctls(vi);
1383
1384	return (0);
1385}
1386
1387static int
1388cxgbe_attach(device_t dev)
1389{
1390	struct port_info *pi = device_get_softc(dev);
1391	struct adapter *sc = pi->adapter;
1392	struct vi_info *vi;
1393	int i, rc;
1394
1395	callout_init_mtx(&pi->tick, &pi->pi_lock, 0);
1396
1397	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
1398	if (rc)
1399		return (rc);
1400
1401	for_each_vi(pi, i, vi) {
1402		if (i == 0)
1403			continue;
1404		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
1405		if (vi->dev == NULL) {
1406			device_printf(dev, "failed to add VI %d\n", i);
1407			continue;
1408		}
1409		device_set_softc(vi->dev, vi);
1410	}
1411
1412	cxgbe_sysctls(pi);
1413
1414	bus_generic_attach(dev);
1415
1416	return (0);
1417}
1418
1419static void
1420cxgbe_vi_detach(struct vi_info *vi)
1421{
1422	struct ifnet *ifp = vi->ifp;
1423
1424	ether_ifdetach(ifp);
1425
1426	if (vi->vlan_c)
1427		EVENTHANDLER_DEREGISTER(vlan_config, vi->vlan_c);
1428
1429	/* Let detach proceed even if these fail. */
1430#ifdef DEV_NETMAP
1431	if (ifp->if_capabilities & IFCAP_NETMAP)
1432		cxgbe_nm_detach(vi);
1433#endif
1434	cxgbe_uninit_synchronized(vi);
1435	callout_drain(&vi->tick);
1436	vi_full_uninit(vi);
1437
1438	ifmedia_removeall(&vi->media);
1439	if_free(vi->ifp);
1440	vi->ifp = NULL;
1441}
1442
1443static int
1444cxgbe_detach(device_t dev)
1445{
1446	struct port_info *pi = device_get_softc(dev);
1447	struct adapter *sc = pi->adapter;
1448	int rc;
1449
1450	/* Detach the extra VIs first. */
1451	rc = bus_generic_detach(dev);
1452	if (rc)
1453		return (rc);
1454	device_delete_children(dev);
1455
1456	doom_vi(sc, &pi->vi[0]);
1457
1458	if (pi->flags & HAS_TRACEQ) {
1459		sc->traceq = -1;	/* cloner should not create ifnet */
1460		t4_tracer_port_detach(sc);
1461	}
1462
1463	cxgbe_vi_detach(&pi->vi[0]);
1464	callout_drain(&pi->tick);
1465
1466	end_synchronized_op(sc, 0);
1467
1468	return (0);
1469}
1470
1471static void
1472cxgbe_init(void *arg)
1473{
1474	struct vi_info *vi = arg;
1475	struct adapter *sc = vi->pi->adapter;
1476
1477	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
1478		return;
1479	cxgbe_init_synchronized(vi);
1480	end_synchronized_op(sc, 0);
1481}
1482
1483static int
1484cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
1485{
1486	int rc = 0, mtu, flags, can_sleep;
1487	struct vi_info *vi = ifp->if_softc;
1488	struct adapter *sc = vi->pi->adapter;
1489	struct ifreq *ifr = (struct ifreq *)data;
1490	uint32_t mask;
1491
1492	switch (cmd) {
1493	case SIOCSIFMTU:
1494		mtu = ifr->ifr_mtu;
1495		if ((mtu < ETHERMIN) || (mtu > ETHERMTU_JUMBO))
1496			return (EINVAL);
1497
1498		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
1499		if (rc)
1500			return (rc);
1501		ifp->if_mtu = mtu;
1502		if (vi->flags & VI_INIT_DONE) {
1503			t4_update_fl_bufsize(ifp);
1504			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1505				rc = update_mac_settings(ifp, XGMAC_MTU);
1506		}
1507		end_synchronized_op(sc, 0);
1508		break;
1509
1510	case SIOCSIFFLAGS:
1511		can_sleep = 0;
1512redo_sifflags:
1513		rc = begin_synchronized_op(sc, vi,
1514		    can_sleep ? (SLEEP_OK | INTR_OK) : HOLD_LOCK, "t4flg");
1515		if (rc)
1516			return (rc);
1517
1518		if (ifp->if_flags & IFF_UP) {
1519			if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1520				flags = vi->if_flags;
1521				if ((ifp->if_flags ^ flags) &
1522				    (IFF_PROMISC | IFF_ALLMULTI)) {
1523					if (can_sleep == 1) {
1524						end_synchronized_op(sc, 0);
1525						can_sleep = 0;
1526						goto redo_sifflags;
1527					}
1528					rc = update_mac_settings(ifp,
1529					    XGMAC_PROMISC | XGMAC_ALLMULTI);
1530				}
1531			} else {
1532				if (can_sleep == 0) {
1533					end_synchronized_op(sc, LOCK_HELD);
1534					can_sleep = 1;
1535					goto redo_sifflags;
1536				}
1537				rc = cxgbe_init_synchronized(vi);
1538			}
1539			vi->if_flags = ifp->if_flags;
1540		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1541			if (can_sleep == 0) {
1542				end_synchronized_op(sc, LOCK_HELD);
1543				can_sleep = 1;
1544				goto redo_sifflags;
1545			}
1546			rc = cxgbe_uninit_synchronized(vi);
1547		}
1548		end_synchronized_op(sc, can_sleep ? 0 : LOCK_HELD);
1549		break;
1550
1551	case SIOCADDMULTI:
1552	case SIOCDELMULTI: /* these two are called with a mutex held :-( */
1553		rc = begin_synchronized_op(sc, vi, HOLD_LOCK, "t4multi");
1554		if (rc)
1555			return (rc);
1556		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1557			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
1558		end_synchronized_op(sc, LOCK_HELD);
1559		break;
1560
1561	case SIOCSIFCAP:
1562		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
1563		if (rc)
1564			return (rc);
1565
1566		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1567		if (mask & IFCAP_TXCSUM) {
1568			ifp->if_capenable ^= IFCAP_TXCSUM;
1569			ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
1570
1571			if (IFCAP_TSO4 & ifp->if_capenable &&
1572			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
1573				ifp->if_capenable &= ~IFCAP_TSO4;
1574				if_printf(ifp,
1575				    "tso4 disabled due to -txcsum.\n");
1576			}
1577		}
1578		if (mask & IFCAP_TXCSUM_IPV6) {
1579			ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
1580			ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
1581
1582			if (IFCAP_TSO6 & ifp->if_capenable &&
1583			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1584				ifp->if_capenable &= ~IFCAP_TSO6;
1585				if_printf(ifp,
1586				    "tso6 disabled due to -txcsum6.\n");
1587			}
1588		}
1589		if (mask & IFCAP_RXCSUM)
1590			ifp->if_capenable ^= IFCAP_RXCSUM;
1591		if (mask & IFCAP_RXCSUM_IPV6)
1592			ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
1593
1594		/*
1595		 * Note that we leave CSUM_TSO alone (it is always set).  The
1596		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
1597		 * sending a TSO request our way, so it's sufficient to toggle
1598		 * IFCAP_TSOx only.
1599		 */
1600		if (mask & IFCAP_TSO4) {
1601			if (!(IFCAP_TSO4 & ifp->if_capenable) &&
1602			    !(IFCAP_TXCSUM & ifp->if_capenable)) {
1603				if_printf(ifp, "enable txcsum first.\n");
1604				rc = EAGAIN;
1605				goto fail;
1606			}
1607			ifp->if_capenable ^= IFCAP_TSO4;
1608		}
1609		if (mask & IFCAP_TSO6) {
1610			if (!(IFCAP_TSO6 & ifp->if_capenable) &&
1611			    !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1612				if_printf(ifp, "enable txcsum6 first.\n");
1613				rc = EAGAIN;
1614				goto fail;
1615			}
1616			ifp->if_capenable ^= IFCAP_TSO6;
1617		}
1618		if (mask & IFCAP_LRO) {
1619#if defined(INET) || defined(INET6)
1620			int i;
1621			struct sge_rxq *rxq;
1622
1623			ifp->if_capenable ^= IFCAP_LRO;
1624			for_each_rxq(vi, i, rxq) {
1625				if (ifp->if_capenable & IFCAP_LRO)
1626					rxq->iq.flags |= IQ_LRO_ENABLED;
1627				else
1628					rxq->iq.flags &= ~IQ_LRO_ENABLED;
1629			}
1630#endif
1631		}
1632#ifdef TCP_OFFLOAD
1633		if (mask & IFCAP_TOE) {
1634			int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
1635
1636			rc = toe_capability(vi, enable);
1637			if (rc != 0)
1638				goto fail;
1639
1640			ifp->if_capenable ^= mask;
1641		}
1642#endif
1643		if (mask & IFCAP_VLAN_HWTAGGING) {
1644			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1645			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1646				rc = update_mac_settings(ifp, XGMAC_VLANEX);
1647		}
1648		if (mask & IFCAP_VLAN_MTU) {
1649			ifp->if_capenable ^= IFCAP_VLAN_MTU;
1650
1651			/* Need to find out how to disable auto-mtu-inflation */
1652		}
1653		if (mask & IFCAP_VLAN_HWTSO)
1654			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1655		if (mask & IFCAP_VLAN_HWCSUM)
1656			ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
1657
1658#ifdef VLAN_CAPABILITIES
1659		VLAN_CAPABILITIES(ifp);
1660#endif
1661fail:
1662		end_synchronized_op(sc, 0);
1663		break;
1664
1665	case SIOCSIFMEDIA:
1666	case SIOCGIFMEDIA:
1667	case SIOCGIFXMEDIA:
1668		ifmedia_ioctl(ifp, ifr, &vi->media, cmd);
1669		break;
1670
1671	case SIOCGI2C: {
1672		struct ifi2creq i2c;
1673
1674		rc = copyin(ifr->ifr_data, &i2c, sizeof(i2c));
1675		if (rc != 0)
1676			break;
1677		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
1678			rc = EPERM;
1679			break;
1680		}
1681		if (i2c.len > sizeof(i2c.data)) {
1682			rc = EINVAL;
1683			break;
1684		}
1685		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
1686		if (rc)
1687			return (rc);
1688		rc = -t4_i2c_rd(sc, sc->mbox, vi->pi->port_id, i2c.dev_addr,
1689		    i2c.offset, i2c.len, &i2c.data[0]);
1690		end_synchronized_op(sc, 0);
1691		if (rc == 0)
1692			rc = copyout(&i2c, ifr->ifr_data, sizeof(i2c));
1693		break;
1694	}
1695
1696	default:
1697		rc = ether_ioctl(ifp, cmd, data);
1698	}
1699
1700	return (rc);
1701}
1702
1703static int
1704cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
1705{
1706	struct vi_info *vi = ifp->if_softc;
1707	struct port_info *pi = vi->pi;
1708	struct adapter *sc = pi->adapter;
1709	struct sge_txq *txq;
1710	void *items[1];
1711	int rc;
1712
1713	M_ASSERTPKTHDR(m);
1714	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
1715
1716	if (__predict_false(pi->link_cfg.link_ok == 0)) {
1717		m_freem(m);
1718		return (ENETDOWN);
1719	}
1720
1721	rc = parse_pkt(sc, &m);
1722	if (__predict_false(rc != 0)) {
1723		MPASS(m == NULL);			/* was freed already */
1724		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
1725		return (rc);
1726	}
1727
1728	/* Select a txq. */
1729	txq = &sc->sge.txq[vi->first_txq];
1730	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
1731		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
1732		    vi->rsrv_noflowq);
1733
1734	items[0] = m;
1735	rc = mp_ring_enqueue(txq->r, items, 1, 4096);
1736	if (__predict_false(rc != 0))
1737		m_freem(m);
1738
1739	return (rc);
1740}
1741
1742static void
1743cxgbe_qflush(struct ifnet *ifp)
1744{
1745	struct vi_info *vi = ifp->if_softc;
1746	struct sge_txq *txq;
1747	int i;
1748
1749	/* queues do not exist if !VI_INIT_DONE. */
1750	if (vi->flags & VI_INIT_DONE) {
1751		for_each_txq(vi, i, txq) {
1752			TXQ_LOCK(txq);
1753			txq->eq.flags &= ~EQ_ENABLED;
1754			TXQ_UNLOCK(txq);
1755			while (!mp_ring_is_idle(txq->r)) {
1756				mp_ring_check_drainage(txq->r, 0);
1757				pause("qflush", 1);
1758			}
1759		}
1760	}
1761	if_qflush(ifp);
1762}
1763
1764static int
1765cxgbe_media_change(struct ifnet *ifp)
1766{
1767	struct vi_info *vi = ifp->if_softc;
1768
1769	device_printf(vi->dev, "%s unimplemented.\n", __func__);
1770
1771	return (EOPNOTSUPP);
1772}
1773
1774static void
1775cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1776{
1777	struct vi_info *vi = ifp->if_softc;
1778	struct port_info *pi = vi->pi;
1779	struct ifmedia_entry *cur;
1780	int speed = pi->link_cfg.speed;
1781
1782	cur = vi->media.ifm_cur;
1783
1784	ifmr->ifm_status = IFM_AVALID;
1785	if (!pi->link_cfg.link_ok)
1786		return;
1787
1788	ifmr->ifm_status |= IFM_ACTIVE;
1789
1790	/* active and current will differ iff current media is autoselect. */
1791	if (IFM_SUBTYPE(cur->ifm_media) != IFM_AUTO)
1792		return;
1793
1794	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
1795	if (speed == 10000)
1796		ifmr->ifm_active |= IFM_10G_T;
1797	else if (speed == 1000)
1798		ifmr->ifm_active |= IFM_1000_T;
1799	else if (speed == 100)
1800		ifmr->ifm_active |= IFM_100_TX;
1801	else if (speed == 10)
1802		ifmr->ifm_active |= IFM_10_T;
1803	else
1804		KASSERT(0, ("%s: link up but speed unknown (%u)", __func__,
1805			    speed));
1806}
1807
1808static int
1809vcxgbe_probe(device_t dev)
1810{
1811	char buf[128];
1812	struct vi_info *vi = device_get_softc(dev);
1813
1814	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
1815	    vi - vi->pi->vi);
1816	device_set_desc_copy(dev, buf);
1817
1818	return (BUS_PROBE_DEFAULT);
1819}
1820
1821static int
1822vcxgbe_attach(device_t dev)
1823{
1824	struct vi_info *vi;
1825	struct port_info *pi;
1826	struct adapter *sc;
1827	int func, index, rc;
1828	u32 param, val;
1829
1830	vi = device_get_softc(dev);
1831	pi = vi->pi;
1832	sc = pi->adapter;
1833
1834	index = vi - pi->vi;
1835	KASSERT(index < nitems(vi_mac_funcs),
1836	    ("%s: VI %s doesn't have a MAC func", __func__,
1837	    device_get_nameunit(dev)));
1838	func = vi_mac_funcs[index];
1839	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
1840	    vi->hw_addr, &vi->rss_size, func, 0);
1841	if (rc < 0) {
1842		device_printf(dev, "Failed to allocate virtual interface "
1843		    "for port %d: %d\n", pi->port_id, -rc);
1844		return (-rc);
1845	}
1846	vi->viid = rc;
1847	if (chip_id(sc) <= CHELSIO_T5)
1848		vi->smt_idx = (rc & 0x7f) << 1;
1849	else
1850		vi->smt_idx = (rc & 0x7f);
1851
1852	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
1853	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
1854	    V_FW_PARAMS_PARAM_YZ(vi->viid);
1855	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
1856	if (rc)
1857		vi->rss_base = 0xffff;
1858	else {
1859		/* MPASS((val >> 16) == rss_size); */
1860		vi->rss_base = val & 0xffff;
1861	}
1862
1863	rc = cxgbe_vi_attach(dev, vi);
1864	if (rc) {
1865		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
1866		return (rc);
1867	}
1868	return (0);
1869}
1870
1871static int
1872vcxgbe_detach(device_t dev)
1873{
1874	struct vi_info *vi;
1875	struct adapter *sc;
1876
1877	vi = device_get_softc(dev);
1878	sc = vi->pi->adapter;
1879
1880	doom_vi(sc, vi);
1881
1882	cxgbe_vi_detach(vi);
1883	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
1884
1885	end_synchronized_op(sc, 0);
1886
1887	return (0);
1888}
1889
1890void
1891t4_fatal_err(struct adapter *sc)
1892{
1893	t4_set_reg_field(sc, A_SGE_CONTROL, F_GLOBALENABLE, 0);
1894	t4_intr_disable(sc);
1895	log(LOG_EMERG, "%s: encountered fatal error, adapter stopped.\n",
1896	    device_get_nameunit(sc->dev));
1897}
1898
1899void
1900t4_add_adapter(struct adapter *sc)
1901{
1902	sx_xlock(&t4_list_lock);
1903	SLIST_INSERT_HEAD(&t4_list, sc, link);
1904	sx_xunlock(&t4_list_lock);
1905}
1906
1907int
1908t4_map_bars_0_and_4(struct adapter *sc)
1909{
1910	sc->regs_rid = PCIR_BAR(0);
1911	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
1912	    &sc->regs_rid, RF_ACTIVE);
1913	if (sc->regs_res == NULL) {
1914		device_printf(sc->dev, "cannot map registers.\n");
1915		return (ENXIO);
1916	}
1917	sc->bt = rman_get_bustag(sc->regs_res);
1918	sc->bh = rman_get_bushandle(sc->regs_res);
1919	sc->mmio_len = rman_get_size(sc->regs_res);
1920	setbit(&sc->doorbells, DOORBELL_KDB);
1921
1922	sc->msix_rid = PCIR_BAR(4);
1923	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
1924	    &sc->msix_rid, RF_ACTIVE);
1925	if (sc->msix_res == NULL) {
1926		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
1927		return (ENXIO);
1928	}
1929
1930	return (0);
1931}
1932
1933int
1934t4_map_bar_2(struct adapter *sc)
1935{
1936
1937	/*
1938	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
1939	 * to map it if RDMA is disabled.
1940	 */
1941	if (is_t4(sc) && sc->rdmacaps == 0)
1942		return (0);
1943
1944	sc->udbs_rid = PCIR_BAR(2);
1945	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
1946	    &sc->udbs_rid, RF_ACTIVE);
1947	if (sc->udbs_res == NULL) {
1948		device_printf(sc->dev, "cannot map doorbell BAR.\n");
1949		return (ENXIO);
1950	}
1951	sc->udbs_base = rman_get_virtual(sc->udbs_res);
1952
1953	if (chip_id(sc) >= CHELSIO_T5) {
1954		setbit(&sc->doorbells, DOORBELL_UDB);
1955#if defined(__i386__) || defined(__amd64__)
1956		if (t5_write_combine) {
1957			int rc, mode;
1958
1959			/*
1960			 * Enable write combining on BAR2.  This is the
1961			 * userspace doorbell BAR and is split into 128B
1962			 * (UDBS_SEG_SIZE) doorbell regions, each associated
1963			 * with an egress queue.  The first 64B has the doorbell
1964			 * and the second 64B can be used to submit a tx work
1965			 * request with an implicit doorbell.
1966			 */
1967
1968			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
1969			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
1970			if (rc == 0) {
1971				clrbit(&sc->doorbells, DOORBELL_UDB);
1972				setbit(&sc->doorbells, DOORBELL_WCWR);
1973				setbit(&sc->doorbells, DOORBELL_UDBWC);
1974			} else {
1975				device_printf(sc->dev,
1976				    "couldn't enable write combining: %d\n",
1977				    rc);
1978			}
1979
1980			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
1981			t4_write_reg(sc, A_SGE_STAT_CFG,
1982			    V_STATSOURCE_T5(7) | mode);
1983		}
1984#endif
1985	}
1986
1987	return (0);
1988}
1989
1990struct memwin_init {
1991	uint32_t base;
1992	uint32_t aperture;
1993};
1994
1995static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
1996	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
1997	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
1998	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
1999};
2000
2001static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
2002	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
2003	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
2004	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
2005};
2006
2007static void
2008setup_memwin(struct adapter *sc)
2009{
2010	const struct memwin_init *mw_init;
2011	struct memwin *mw;
2012	int i;
2013	uint32_t bar0;
2014
2015	if (is_t4(sc)) {
2016		/*
2017		 * Read low 32b of bar0 indirectly via the hardware backdoor
2018		 * mechanism.  Works from within PCI passthrough environments
2019		 * too, where rman_get_start() can return a different value.  We
2020		 * need to program the T4 memory window decoders with the actual
2021		 * addresses that will be coming across the PCIe link.
2022		 */
2023		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
2024		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
2025
2026		mw_init = &t4_memwin[0];
2027	} else {
2028		/* T5+ use the relative offset inside the PCIe BAR */
2029		bar0 = 0;
2030
2031		mw_init = &t5_memwin[0];
2032	}
2033
2034	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
2035		rw_init(&mw->mw_lock, "memory window access");
2036		mw->mw_base = mw_init->base;
2037		mw->mw_aperture = mw_init->aperture;
2038		mw->mw_curpos = 0;
2039		t4_write_reg(sc,
2040		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
2041		    (mw->mw_base + bar0) | V_BIR(0) |
2042		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
2043		rw_wlock(&mw->mw_lock);
2044		position_memwin(sc, i, 0);
2045		rw_wunlock(&mw->mw_lock);
2046	}
2047
2048	/* flush */
2049	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
2050}
2051
2052/*
2053 * Positions the memory window at the given address in the card's address space.
2054 * There are some alignment requirements and the actual position may be at an
2055 * address prior to the requested address.  mw->mw_curpos always has the actual
2056 * position of the window.
2057 */
2058static void
2059position_memwin(struct adapter *sc, int idx, uint32_t addr)
2060{
2061	struct memwin *mw;
2062	uint32_t pf;
2063	uint32_t reg;
2064
2065	MPASS(idx >= 0 && idx < NUM_MEMWIN);
2066	mw = &sc->memwin[idx];
2067	rw_assert(&mw->mw_lock, RA_WLOCKED);
2068
2069	if (is_t4(sc)) {
2070		pf = 0;
2071		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
2072	} else {
2073		pf = V_PFNUM(sc->pf);
2074		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
2075	}
2076	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
2077	t4_write_reg(sc, reg, mw->mw_curpos | pf);
2078	t4_read_reg(sc, reg);	/* flush */
2079}
2080
2081static int
2082rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2083    int len, int rw)
2084{
2085	struct memwin *mw;
2086	uint32_t mw_end, v;
2087
2088	MPASS(idx >= 0 && idx < NUM_MEMWIN);
2089
2090	/* Memory can only be accessed in naturally aligned 4 byte units */
2091	if (addr & 3 || len & 3 || len <= 0)
2092		return (EINVAL);
2093
2094	mw = &sc->memwin[idx];
2095	while (len > 0) {
2096		rw_rlock(&mw->mw_lock);
2097		mw_end = mw->mw_curpos + mw->mw_aperture;
2098		if (addr >= mw_end || addr < mw->mw_curpos) {
2099			/* Will need to reposition the window */
2100			if (!rw_try_upgrade(&mw->mw_lock)) {
2101				rw_runlock(&mw->mw_lock);
2102				rw_wlock(&mw->mw_lock);
2103			}
2104			rw_assert(&mw->mw_lock, RA_WLOCKED);
2105			position_memwin(sc, idx, addr);
2106			rw_downgrade(&mw->mw_lock);
2107			mw_end = mw->mw_curpos + mw->mw_aperture;
2108		}
2109		rw_assert(&mw->mw_lock, RA_RLOCKED);
2110		while (addr < mw_end && len > 0) {
2111			if (rw == 0) {
2112				v = t4_read_reg(sc, mw->mw_base + addr -
2113				    mw->mw_curpos);
2114				*val++ = le32toh(v);
2115			} else {
2116				v = *val++;
2117				t4_write_reg(sc, mw->mw_base + addr -
2118				    mw->mw_curpos, htole32(v));;
2119			}
2120			addr += 4;
2121			len -= 4;
2122		}
2123		rw_runlock(&mw->mw_lock);
2124	}
2125
2126	return (0);
2127}
2128
2129static inline int
2130read_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2131    int len)
2132{
2133
2134	return (rw_via_memwin(sc, idx, addr, val, len, 0));
2135}
2136
2137static inline int
2138write_via_memwin(struct adapter *sc, int idx, uint32_t addr,
2139    const uint32_t *val, int len)
2140{
2141
2142	return (rw_via_memwin(sc, idx, addr, (void *)(uintptr_t)val, len, 1));
2143}
2144
2145static int
2146t4_range_cmp(const void *a, const void *b)
2147{
2148	return ((const struct t4_range *)a)->start -
2149	       ((const struct t4_range *)b)->start;
2150}
2151
2152/*
2153 * Verify that the memory range specified by the addr/len pair is valid within
2154 * the card's address space.
2155 */
2156static int
2157validate_mem_range(struct adapter *sc, uint32_t addr, int len)
2158{
2159	struct t4_range mem_ranges[4], *r, *next;
2160	uint32_t em, addr_len;
2161	int i, n, remaining;
2162
2163	/* Memory can only be accessed in naturally aligned 4 byte units */
2164	if (addr & 3 || len & 3 || len <= 0)
2165		return (EINVAL);
2166
2167	/* Enabled memories */
2168	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2169
2170	r = &mem_ranges[0];
2171	n = 0;
2172	bzero(r, sizeof(mem_ranges));
2173	if (em & F_EDRAM0_ENABLE) {
2174		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2175		r->size = G_EDRAM0_SIZE(addr_len) << 20;
2176		if (r->size > 0) {
2177			r->start = G_EDRAM0_BASE(addr_len) << 20;
2178			if (addr >= r->start &&
2179			    addr + len <= r->start + r->size)
2180				return (0);
2181			r++;
2182			n++;
2183		}
2184	}
2185	if (em & F_EDRAM1_ENABLE) {
2186		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2187		r->size = G_EDRAM1_SIZE(addr_len) << 20;
2188		if (r->size > 0) {
2189			r->start = G_EDRAM1_BASE(addr_len) << 20;
2190			if (addr >= r->start &&
2191			    addr + len <= r->start + r->size)
2192				return (0);
2193			r++;
2194			n++;
2195		}
2196	}
2197	if (em & F_EXT_MEM_ENABLE) {
2198		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2199		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
2200		if (r->size > 0) {
2201			r->start = G_EXT_MEM_BASE(addr_len) << 20;
2202			if (addr >= r->start &&
2203			    addr + len <= r->start + r->size)
2204				return (0);
2205			r++;
2206			n++;
2207		}
2208	}
2209	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
2210		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2211		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
2212		if (r->size > 0) {
2213			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
2214			if (addr >= r->start &&
2215			    addr + len <= r->start + r->size)
2216				return (0);
2217			r++;
2218			n++;
2219		}
2220	}
2221	MPASS(n <= nitems(mem_ranges));
2222
2223	if (n > 1) {
2224		/* Sort and merge the ranges. */
2225		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
2226
2227		/* Start from index 0 and examine the next n - 1 entries. */
2228		r = &mem_ranges[0];
2229		for (remaining = n - 1; remaining > 0; remaining--, r++) {
2230
2231			MPASS(r->size > 0);	/* r is a valid entry. */
2232			next = r + 1;
2233			MPASS(next->size > 0);	/* and so is the next one. */
2234
2235			while (r->start + r->size >= next->start) {
2236				/* Merge the next one into the current entry. */
2237				r->size = max(r->start + r->size,
2238				    next->start + next->size) - r->start;
2239				n--;	/* One fewer entry in total. */
2240				if (--remaining == 0)
2241					goto done;	/* short circuit */
2242				next++;
2243			}
2244			if (next != r + 1) {
2245				/*
2246				 * Some entries were merged into r and next
2247				 * points to the first valid entry that couldn't
2248				 * be merged.
2249				 */
2250				MPASS(next->size > 0);	/* must be valid */
2251				memcpy(r + 1, next, remaining * sizeof(*r));
2252#ifdef INVARIANTS
2253				/*
2254				 * This so that the foo->size assertion in the
2255				 * next iteration of the loop do the right
2256				 * thing for entries that were pulled up and are
2257				 * no longer valid.
2258				 */
2259				MPASS(n < nitems(mem_ranges));
2260				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
2261				    sizeof(struct t4_range));
2262#endif
2263			}
2264		}
2265done:
2266		/* Done merging the ranges. */
2267		MPASS(n > 0);
2268		r = &mem_ranges[0];
2269		for (i = 0; i < n; i++, r++) {
2270			if (addr >= r->start &&
2271			    addr + len <= r->start + r->size)
2272				return (0);
2273		}
2274	}
2275
2276	return (EFAULT);
2277}
2278
2279static int
2280fwmtype_to_hwmtype(int mtype)
2281{
2282
2283	switch (mtype) {
2284	case FW_MEMTYPE_EDC0:
2285		return (MEM_EDC0);
2286	case FW_MEMTYPE_EDC1:
2287		return (MEM_EDC1);
2288	case FW_MEMTYPE_EXTMEM:
2289		return (MEM_MC0);
2290	case FW_MEMTYPE_EXTMEM1:
2291		return (MEM_MC1);
2292	default:
2293		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
2294	}
2295}
2296
2297/*
2298 * Verify that the memory range specified by the memtype/offset/len pair is
2299 * valid and lies entirely within the memtype specified.  The global address of
2300 * the start of the range is returned in addr.
2301 */
2302static int
2303validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, int len,
2304    uint32_t *addr)
2305{
2306	uint32_t em, addr_len, maddr;
2307
2308	/* Memory can only be accessed in naturally aligned 4 byte units */
2309	if (off & 3 || len & 3 || len == 0)
2310		return (EINVAL);
2311
2312	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2313	switch (fwmtype_to_hwmtype(mtype)) {
2314	case MEM_EDC0:
2315		if (!(em & F_EDRAM0_ENABLE))
2316			return (EINVAL);
2317		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2318		maddr = G_EDRAM0_BASE(addr_len) << 20;
2319		break;
2320	case MEM_EDC1:
2321		if (!(em & F_EDRAM1_ENABLE))
2322			return (EINVAL);
2323		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2324		maddr = G_EDRAM1_BASE(addr_len) << 20;
2325		break;
2326	case MEM_MC:
2327		if (!(em & F_EXT_MEM_ENABLE))
2328			return (EINVAL);
2329		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2330		maddr = G_EXT_MEM_BASE(addr_len) << 20;
2331		break;
2332	case MEM_MC1:
2333		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
2334			return (EINVAL);
2335		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2336		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
2337		break;
2338	default:
2339		return (EINVAL);
2340	}
2341
2342	*addr = maddr + off;	/* global address */
2343	return (validate_mem_range(sc, *addr, len));
2344}
2345
2346static int
2347fixup_devlog_params(struct adapter *sc)
2348{
2349	struct devlog_params *dparams = &sc->params.devlog;
2350	int rc;
2351
2352	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
2353	    dparams->size, &dparams->addr);
2354
2355	return (rc);
2356}
2357
2358static int
2359cfg_itype_and_nqueues(struct adapter *sc, int n10g, int n1g, int num_vis,
2360    struct intrs_and_queues *iaq)
2361{
2362	int rc, itype, navail, nrxq10g, nrxq1g, n;
2363	int nofldrxq10g = 0, nofldrxq1g = 0;
2364
2365	bzero(iaq, sizeof(*iaq));
2366
2367	iaq->ntxq10g = t4_ntxq10g;
2368	iaq->ntxq1g = t4_ntxq1g;
2369	iaq->ntxq_vi = t4_ntxq_vi;
2370	iaq->nrxq10g = nrxq10g = t4_nrxq10g;
2371	iaq->nrxq1g = nrxq1g = t4_nrxq1g;
2372	iaq->nrxq_vi = t4_nrxq_vi;
2373	iaq->rsrv_noflowq = t4_rsrv_noflowq;
2374#ifdef TCP_OFFLOAD
2375	if (is_offload(sc)) {
2376		iaq->nofldtxq10g = t4_nofldtxq10g;
2377		iaq->nofldtxq1g = t4_nofldtxq1g;
2378		iaq->nofldtxq_vi = t4_nofldtxq_vi;
2379		iaq->nofldrxq10g = nofldrxq10g = t4_nofldrxq10g;
2380		iaq->nofldrxq1g = nofldrxq1g = t4_nofldrxq1g;
2381		iaq->nofldrxq_vi = t4_nofldrxq_vi;
2382	}
2383#endif
2384#ifdef DEV_NETMAP
2385	iaq->nnmtxq_vi = t4_nnmtxq_vi;
2386	iaq->nnmrxq_vi = t4_nnmrxq_vi;
2387#endif
2388
2389	for (itype = INTR_MSIX; itype; itype >>= 1) {
2390
2391		if ((itype & t4_intr_types) == 0)
2392			continue;	/* not allowed */
2393
2394		if (itype == INTR_MSIX)
2395			navail = pci_msix_count(sc->dev);
2396		else if (itype == INTR_MSI)
2397			navail = pci_msi_count(sc->dev);
2398		else
2399			navail = 1;
2400restart:
2401		if (navail == 0)
2402			continue;
2403
2404		iaq->intr_type = itype;
2405		iaq->intr_flags_10g = 0;
2406		iaq->intr_flags_1g = 0;
2407
2408		/*
2409		 * Best option: an interrupt vector for errors, one for the
2410		 * firmware event queue, and one for every rxq (NIC and TOE) of
2411		 * every VI.  The VIs that support netmap use the same
2412		 * interrupts for the NIC rx queues and the netmap rx queues
2413		 * because only one set of queues is active at a time.
2414		 */
2415		iaq->nirq = T4_EXTRA_INTR;
2416		iaq->nirq += n10g * (nrxq10g + nofldrxq10g);
2417		iaq->nirq += n1g * (nrxq1g + nofldrxq1g);
2418		iaq->nirq += (n10g + n1g) * (num_vis - 1) *
2419		    max(iaq->nrxq_vi, iaq->nnmrxq_vi);	/* See comment above. */
2420		iaq->nirq += (n10g + n1g) * (num_vis - 1) * iaq->nofldrxq_vi;
2421		if (iaq->nirq <= navail &&
2422		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
2423			iaq->intr_flags_10g = INTR_ALL;
2424			iaq->intr_flags_1g = INTR_ALL;
2425			goto allocate;
2426		}
2427
2428		/* Disable the VIs (and netmap) if there aren't enough intrs */
2429		if (num_vis > 1) {
2430			device_printf(sc->dev, "virtual interfaces disabled "
2431			    "because num_vis=%u with current settings "
2432			    "(nrxq10g=%u, nrxq1g=%u, nofldrxq10g=%u, "
2433			    "nofldrxq1g=%u, nrxq_vi=%u nofldrxq_vi=%u, "
2434			    "nnmrxq_vi=%u) would need %u interrupts but "
2435			    "only %u are available.\n", num_vis, nrxq10g,
2436			    nrxq1g, nofldrxq10g, nofldrxq1g, iaq->nrxq_vi,
2437			    iaq->nofldrxq_vi, iaq->nnmrxq_vi, iaq->nirq,
2438			    navail);
2439			num_vis = 1;
2440			iaq->ntxq_vi = iaq->nrxq_vi = 0;
2441			iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
2442			iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
2443			goto restart;
2444		}
2445
2446		/*
2447		 * Second best option: a vector for errors, one for the firmware
2448		 * event queue, and vectors for either all the NIC rx queues or
2449		 * all the TOE rx queues.  The queues that don't get vectors
2450		 * will forward their interrupts to those that do.
2451		 */
2452		iaq->nirq = T4_EXTRA_INTR;
2453		if (nrxq10g >= nofldrxq10g) {
2454			iaq->intr_flags_10g = INTR_RXQ;
2455			iaq->nirq += n10g * nrxq10g;
2456		} else {
2457			iaq->intr_flags_10g = INTR_OFLD_RXQ;
2458			iaq->nirq += n10g * nofldrxq10g;
2459		}
2460		if (nrxq1g >= nofldrxq1g) {
2461			iaq->intr_flags_1g = INTR_RXQ;
2462			iaq->nirq += n1g * nrxq1g;
2463		} else {
2464			iaq->intr_flags_1g = INTR_OFLD_RXQ;
2465			iaq->nirq += n1g * nofldrxq1g;
2466		}
2467		if (iaq->nirq <= navail &&
2468		    (itype != INTR_MSI || powerof2(iaq->nirq)))
2469			goto allocate;
2470
2471		/*
2472		 * Next best option: an interrupt vector for errors, one for the
2473		 * firmware event queue, and at least one per main-VI.  At this
2474		 * point we know we'll have to downsize nrxq and/or nofldrxq to
2475		 * fit what's available to us.
2476		 */
2477		iaq->nirq = T4_EXTRA_INTR;
2478		iaq->nirq += n10g + n1g;
2479		if (iaq->nirq <= navail) {
2480			int leftover = navail - iaq->nirq;
2481
2482			if (n10g > 0) {
2483				int target = max(nrxq10g, nofldrxq10g);
2484
2485				iaq->intr_flags_10g = nrxq10g >= nofldrxq10g ?
2486				    INTR_RXQ : INTR_OFLD_RXQ;
2487
2488				n = 1;
2489				while (n < target && leftover >= n10g) {
2490					leftover -= n10g;
2491					iaq->nirq += n10g;
2492					n++;
2493				}
2494				iaq->nrxq10g = min(n, nrxq10g);
2495#ifdef TCP_OFFLOAD
2496				iaq->nofldrxq10g = min(n, nofldrxq10g);
2497#endif
2498			}
2499
2500			if (n1g > 0) {
2501				int target = max(nrxq1g, nofldrxq1g);
2502
2503				iaq->intr_flags_1g = nrxq1g >= nofldrxq1g ?
2504				    INTR_RXQ : INTR_OFLD_RXQ;
2505
2506				n = 1;
2507				while (n < target && leftover >= n1g) {
2508					leftover -= n1g;
2509					iaq->nirq += n1g;
2510					n++;
2511				}
2512				iaq->nrxq1g = min(n, nrxq1g);
2513#ifdef TCP_OFFLOAD
2514				iaq->nofldrxq1g = min(n, nofldrxq1g);
2515#endif
2516			}
2517
2518			if (itype != INTR_MSI || powerof2(iaq->nirq))
2519				goto allocate;
2520		}
2521
2522		/*
2523		 * Least desirable option: one interrupt vector for everything.
2524		 */
2525		iaq->nirq = iaq->nrxq10g = iaq->nrxq1g = 1;
2526		iaq->intr_flags_10g = iaq->intr_flags_1g = 0;
2527#ifdef TCP_OFFLOAD
2528		if (is_offload(sc))
2529			iaq->nofldrxq10g = iaq->nofldrxq1g = 1;
2530#endif
2531allocate:
2532		navail = iaq->nirq;
2533		rc = 0;
2534		if (itype == INTR_MSIX)
2535			rc = pci_alloc_msix(sc->dev, &navail);
2536		else if (itype == INTR_MSI)
2537			rc = pci_alloc_msi(sc->dev, &navail);
2538
2539		if (rc == 0) {
2540			if (navail == iaq->nirq)
2541				return (0);
2542
2543			/*
2544			 * Didn't get the number requested.  Use whatever number
2545			 * the kernel is willing to allocate (it's in navail).
2546			 */
2547			device_printf(sc->dev, "fewer vectors than requested, "
2548			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
2549			    itype, iaq->nirq, navail);
2550			pci_release_msi(sc->dev);
2551			goto restart;
2552		}
2553
2554		device_printf(sc->dev,
2555		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
2556		    itype, rc, iaq->nirq, navail);
2557	}
2558
2559	device_printf(sc->dev,
2560	    "failed to find a usable interrupt type.  "
2561	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
2562	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
2563
2564	return (ENXIO);
2565}
2566
2567#define FW_VERSION(chip) ( \
2568    V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
2569    V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
2570    V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
2571    V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
2572#define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
2573
2574struct fw_info {
2575	uint8_t chip;
2576	char *kld_name;
2577	char *fw_mod_name;
2578	struct fw_hdr fw_hdr;	/* XXX: waste of space, need a sparse struct */
2579} fw_info[] = {
2580	{
2581		.chip = CHELSIO_T4,
2582		.kld_name = "t4fw_cfg",
2583		.fw_mod_name = "t4fw",
2584		.fw_hdr = {
2585			.chip = FW_HDR_CHIP_T4,
2586			.fw_ver = htobe32_const(FW_VERSION(T4)),
2587			.intfver_nic = FW_INTFVER(T4, NIC),
2588			.intfver_vnic = FW_INTFVER(T4, VNIC),
2589			.intfver_ofld = FW_INTFVER(T4, OFLD),
2590			.intfver_ri = FW_INTFVER(T4, RI),
2591			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
2592			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
2593			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
2594			.intfver_fcoe = FW_INTFVER(T4, FCOE),
2595		},
2596	}, {
2597		.chip = CHELSIO_T5,
2598		.kld_name = "t5fw_cfg",
2599		.fw_mod_name = "t5fw",
2600		.fw_hdr = {
2601			.chip = FW_HDR_CHIP_T5,
2602			.fw_ver = htobe32_const(FW_VERSION(T5)),
2603			.intfver_nic = FW_INTFVER(T5, NIC),
2604			.intfver_vnic = FW_INTFVER(T5, VNIC),
2605			.intfver_ofld = FW_INTFVER(T5, OFLD),
2606			.intfver_ri = FW_INTFVER(T5, RI),
2607			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
2608			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
2609			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
2610			.intfver_fcoe = FW_INTFVER(T5, FCOE),
2611		},
2612	}, {
2613		.chip = CHELSIO_T6,
2614		.kld_name = "t6fw_cfg",
2615		.fw_mod_name = "t6fw",
2616		.fw_hdr = {
2617			.chip = FW_HDR_CHIP_T6,
2618			.fw_ver = htobe32_const(FW_VERSION(T6)),
2619			.intfver_nic = FW_INTFVER(T6, NIC),
2620			.intfver_vnic = FW_INTFVER(T6, VNIC),
2621			.intfver_ofld = FW_INTFVER(T6, OFLD),
2622			.intfver_ri = FW_INTFVER(T6, RI),
2623			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
2624			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
2625			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
2626			.intfver_fcoe = FW_INTFVER(T6, FCOE),
2627		},
2628	}
2629};
2630
2631static struct fw_info *
2632find_fw_info(int chip)
2633{
2634	int i;
2635
2636	for (i = 0; i < nitems(fw_info); i++) {
2637		if (fw_info[i].chip == chip)
2638			return (&fw_info[i]);
2639	}
2640	return (NULL);
2641}
2642
2643/*
2644 * Is the given firmware API compatible with the one the driver was compiled
2645 * with?
2646 */
2647static int
2648fw_compatible(const struct fw_hdr *hdr1, const struct fw_hdr *hdr2)
2649{
2650
2651	/* short circuit if it's the exact same firmware version */
2652	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
2653		return (1);
2654
2655	/*
2656	 * XXX: Is this too conservative?  Perhaps I should limit this to the
2657	 * features that are supported in the driver.
2658	 */
2659#define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
2660	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
2661	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
2662	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
2663		return (1);
2664#undef SAME_INTF
2665
2666	return (0);
2667}
2668
2669/*
2670 * The firmware in the KLD is usable, but should it be installed?  This routine
2671 * explains itself in detail if it indicates the KLD firmware should be
2672 * installed.
2673 */
2674static int
2675should_install_kld_fw(struct adapter *sc, int card_fw_usable, int k, int c)
2676{
2677	const char *reason;
2678
2679	if (!card_fw_usable) {
2680		reason = "incompatible or unusable";
2681		goto install;
2682	}
2683
2684	if (k > c) {
2685		reason = "older than the version bundled with this driver";
2686		goto install;
2687	}
2688
2689	if (t4_fw_install == 2 && k != c) {
2690		reason = "different than the version bundled with this driver";
2691		goto install;
2692	}
2693
2694	return (0);
2695
2696install:
2697	if (t4_fw_install == 0) {
2698		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
2699		    "but the driver is prohibited from installing a different "
2700		    "firmware on the card.\n",
2701		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2702		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
2703
2704		return (0);
2705	}
2706
2707	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
2708	    "installing firmware %u.%u.%u.%u on card.\n",
2709	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2710	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
2711	    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
2712	    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k));
2713
2714	return (1);
2715}
2716/*
2717 * Establish contact with the firmware and determine if we are the master driver
2718 * or not, and whether we are responsible for chip initialization.
2719 */
2720static int
2721prep_firmware(struct adapter *sc)
2722{
2723	const struct firmware *fw = NULL, *default_cfg;
2724	int rc, pf, card_fw_usable, kld_fw_usable, need_fw_reset = 1;
2725	enum dev_state state;
2726	struct fw_info *fw_info;
2727	struct fw_hdr *card_fw;		/* fw on the card */
2728	const struct fw_hdr *kld_fw;	/* fw in the KLD */
2729	const struct fw_hdr *drv_fw;	/* fw header the driver was compiled
2730					   against */
2731
2732	/* Contact firmware. */
2733	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
2734	if (rc < 0 || state == DEV_STATE_ERR) {
2735		rc = -rc;
2736		device_printf(sc->dev,
2737		    "failed to connect to the firmware: %d, %d.\n", rc, state);
2738		return (rc);
2739	}
2740	pf = rc;
2741	if (pf == sc->mbox)
2742		sc->flags |= MASTER_PF;
2743	else if (state == DEV_STATE_UNINIT) {
2744		/*
2745		 * We didn't get to be the master so we definitely won't be
2746		 * configuring the chip.  It's a bug if someone else hasn't
2747		 * configured it already.
2748		 */
2749		device_printf(sc->dev, "couldn't be master(%d), "
2750		    "device not already initialized either(%d).\n", rc, state);
2751		return (EDOOFUS);
2752	}
2753
2754	/* This is the firmware whose headers the driver was compiled against */
2755	fw_info = find_fw_info(chip_id(sc));
2756	if (fw_info == NULL) {
2757		device_printf(sc->dev,
2758		    "unable to look up firmware information for chip %d.\n",
2759		    chip_id(sc));
2760		return (EINVAL);
2761	}
2762	drv_fw = &fw_info->fw_hdr;
2763
2764	/*
2765	 * The firmware KLD contains many modules.  The KLD name is also the
2766	 * name of the module that contains the default config file.
2767	 */
2768	default_cfg = firmware_get(fw_info->kld_name);
2769
2770	/* Read the header of the firmware on the card */
2771	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
2772	rc = -t4_read_flash(sc, FLASH_FW_START,
2773	    sizeof (*card_fw) / sizeof (uint32_t), (uint32_t *)card_fw, 1);
2774	if (rc == 0)
2775		card_fw_usable = fw_compatible(drv_fw, (const void*)card_fw);
2776	else {
2777		device_printf(sc->dev,
2778		    "Unable to read card's firmware header: %d\n", rc);
2779		card_fw_usable = 0;
2780	}
2781
2782	/* This is the firmware in the KLD */
2783	fw = firmware_get(fw_info->fw_mod_name);
2784	if (fw != NULL) {
2785		kld_fw = (const void *)fw->data;
2786		kld_fw_usable = fw_compatible(drv_fw, kld_fw);
2787	} else {
2788		kld_fw = NULL;
2789		kld_fw_usable = 0;
2790	}
2791
2792	if (card_fw_usable && card_fw->fw_ver == drv_fw->fw_ver &&
2793	    (!kld_fw_usable || kld_fw->fw_ver == drv_fw->fw_ver)) {
2794		/*
2795		 * Common case: the firmware on the card is an exact match and
2796		 * the KLD is an exact match too, or the KLD is
2797		 * absent/incompatible.  Note that t4_fw_install = 2 is ignored
2798		 * here -- use cxgbetool loadfw if you want to reinstall the
2799		 * same firmware as the one on the card.
2800		 */
2801	} else if (kld_fw_usable && state == DEV_STATE_UNINIT &&
2802	    should_install_kld_fw(sc, card_fw_usable, be32toh(kld_fw->fw_ver),
2803	    be32toh(card_fw->fw_ver))) {
2804
2805		rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
2806		if (rc != 0) {
2807			device_printf(sc->dev,
2808			    "failed to install firmware: %d\n", rc);
2809			goto done;
2810		}
2811
2812		/* Installed successfully, update the cached header too. */
2813		memcpy(card_fw, kld_fw, sizeof(*card_fw));
2814		card_fw_usable = 1;
2815		need_fw_reset = 0;	/* already reset as part of load_fw */
2816	}
2817
2818	if (!card_fw_usable) {
2819		uint32_t d, c, k;
2820
2821		d = ntohl(drv_fw->fw_ver);
2822		c = ntohl(card_fw->fw_ver);
2823		k = kld_fw ? ntohl(kld_fw->fw_ver) : 0;
2824
2825		device_printf(sc->dev, "Cannot find a usable firmware: "
2826		    "fw_install %d, chip state %d, "
2827		    "driver compiled with %d.%d.%d.%d, "
2828		    "card has %d.%d.%d.%d, KLD has %d.%d.%d.%d\n",
2829		    t4_fw_install, state,
2830		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
2831		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d),
2832		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2833		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c),
2834		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
2835		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k));
2836		rc = EINVAL;
2837		goto done;
2838	}
2839
2840	/* Reset device */
2841	if (need_fw_reset &&
2842	    (rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST)) != 0) {
2843		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
2844		if (rc != ETIMEDOUT && rc != EIO)
2845			t4_fw_bye(sc, sc->mbox);
2846		goto done;
2847	}
2848	sc->flags |= FW_OK;
2849
2850	rc = get_params__pre_init(sc);
2851	if (rc != 0)
2852		goto done; /* error message displayed already */
2853
2854	/* Partition adapter resources as specified in the config file. */
2855	if (state == DEV_STATE_UNINIT) {
2856
2857		KASSERT(sc->flags & MASTER_PF,
2858		    ("%s: trying to change chip settings when not master.",
2859		    __func__));
2860
2861		rc = partition_resources(sc, default_cfg, fw_info->kld_name);
2862		if (rc != 0)
2863			goto done;	/* error message displayed already */
2864
2865		t4_tweak_chip_settings(sc);
2866
2867		/* get basic stuff going */
2868		rc = -t4_fw_initialize(sc, sc->mbox);
2869		if (rc != 0) {
2870			device_printf(sc->dev, "fw init failed: %d.\n", rc);
2871			goto done;
2872		}
2873	} else {
2874		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", pf);
2875		sc->cfcsum = 0;
2876	}
2877
2878done:
2879	free(card_fw, M_CXGBE);
2880	if (fw != NULL)
2881		firmware_put(fw, FIRMWARE_UNLOAD);
2882	if (default_cfg != NULL)
2883		firmware_put(default_cfg, FIRMWARE_UNLOAD);
2884
2885	return (rc);
2886}
2887
2888#define FW_PARAM_DEV(param) \
2889	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
2890	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
2891#define FW_PARAM_PFVF(param) \
2892	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
2893	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
2894
2895/*
2896 * Partition chip resources for use between various PFs, VFs, etc.
2897 */
2898static int
2899partition_resources(struct adapter *sc, const struct firmware *default_cfg,
2900    const char *name_prefix)
2901{
2902	const struct firmware *cfg = NULL;
2903	int rc = 0;
2904	struct fw_caps_config_cmd caps;
2905	uint32_t mtype, moff, finicsum, cfcsum;
2906
2907	/*
2908	 * Figure out what configuration file to use.  Pick the default config
2909	 * file for the card if the user hasn't specified one explicitly.
2910	 */
2911	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", t4_cfg_file);
2912	if (strncmp(t4_cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
2913		/* Card specific overrides go here. */
2914		if (pci_get_device(sc->dev) == 0x440a)
2915			snprintf(sc->cfg_file, sizeof(sc->cfg_file), UWIRE_CF);
2916		if (is_fpga(sc))
2917			snprintf(sc->cfg_file, sizeof(sc->cfg_file), FPGA_CF);
2918	}
2919
2920	/*
2921	 * We need to load another module if the profile is anything except
2922	 * "default" or "flash".
2923	 */
2924	if (strncmp(sc->cfg_file, DEFAULT_CF, sizeof(sc->cfg_file)) != 0 &&
2925	    strncmp(sc->cfg_file, FLASH_CF, sizeof(sc->cfg_file)) != 0) {
2926		char s[32];
2927
2928		snprintf(s, sizeof(s), "%s_%s", name_prefix, sc->cfg_file);
2929		cfg = firmware_get(s);
2930		if (cfg == NULL) {
2931			if (default_cfg != NULL) {
2932				device_printf(sc->dev,
2933				    "unable to load module \"%s\" for "
2934				    "configuration profile \"%s\", will use "
2935				    "the default config file instead.\n",
2936				    s, sc->cfg_file);
2937				snprintf(sc->cfg_file, sizeof(sc->cfg_file),
2938				    "%s", DEFAULT_CF);
2939			} else {
2940				device_printf(sc->dev,
2941				    "unable to load module \"%s\" for "
2942				    "configuration profile \"%s\", will use "
2943				    "the config file on the card's flash "
2944				    "instead.\n", s, sc->cfg_file);
2945				snprintf(sc->cfg_file, sizeof(sc->cfg_file),
2946				    "%s", FLASH_CF);
2947			}
2948		}
2949	}
2950
2951	if (strncmp(sc->cfg_file, DEFAULT_CF, sizeof(sc->cfg_file)) == 0 &&
2952	    default_cfg == NULL) {
2953		device_printf(sc->dev,
2954		    "default config file not available, will use the config "
2955		    "file on the card's flash instead.\n");
2956		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", FLASH_CF);
2957	}
2958
2959	if (strncmp(sc->cfg_file, FLASH_CF, sizeof(sc->cfg_file)) != 0) {
2960		u_int cflen;
2961		const uint32_t *cfdata;
2962		uint32_t param, val, addr;
2963
2964		KASSERT(cfg != NULL || default_cfg != NULL,
2965		    ("%s: no config to upload", __func__));
2966
2967		/*
2968		 * Ask the firmware where it wants us to upload the config file.
2969		 */
2970		param = FW_PARAM_DEV(CF);
2971		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2972		if (rc != 0) {
2973			/* No support for config file?  Shouldn't happen. */
2974			device_printf(sc->dev,
2975			    "failed to query config file location: %d.\n", rc);
2976			goto done;
2977		}
2978		mtype = G_FW_PARAMS_PARAM_Y(val);
2979		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
2980
2981		/*
2982		 * XXX: sheer laziness.  We deliberately added 4 bytes of
2983		 * useless stuffing/comments at the end of the config file so
2984		 * it's ok to simply throw away the last remaining bytes when
2985		 * the config file is not an exact multiple of 4.  This also
2986		 * helps with the validate_mt_off_len check.
2987		 */
2988		if (cfg != NULL) {
2989			cflen = cfg->datasize & ~3;
2990			cfdata = cfg->data;
2991		} else {
2992			cflen = default_cfg->datasize & ~3;
2993			cfdata = default_cfg->data;
2994		}
2995
2996		if (cflen > FLASH_CFG_MAX_SIZE) {
2997			device_printf(sc->dev,
2998			    "config file too long (%d, max allowed is %d).  "
2999			    "Will try to use the config on the card, if any.\n",
3000			    cflen, FLASH_CFG_MAX_SIZE);
3001			goto use_config_on_flash;
3002		}
3003
3004		rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
3005		if (rc != 0) {
3006			device_printf(sc->dev,
3007			    "%s: addr (%d/0x%x) or len %d is not valid: %d.  "
3008			    "Will try to use the config on the card, if any.\n",
3009			    __func__, mtype, moff, cflen, rc);
3010			goto use_config_on_flash;
3011		}
3012		write_via_memwin(sc, 2, addr, cfdata, cflen);
3013	} else {
3014use_config_on_flash:
3015		mtype = FW_MEMTYPE_FLASH;
3016		moff = t4_flash_cfg_addr(sc);
3017	}
3018
3019	bzero(&caps, sizeof(caps));
3020	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3021	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
3022	caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3023	    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3024	    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) | FW_LEN16(caps));
3025	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3026	if (rc != 0) {
3027		device_printf(sc->dev,
3028		    "failed to pre-process config file: %d "
3029		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
3030		goto done;
3031	}
3032
3033	finicsum = be32toh(caps.finicsum);
3034	cfcsum = be32toh(caps.cfcsum);
3035	if (finicsum != cfcsum) {
3036		device_printf(sc->dev,
3037		    "WARNING: config file checksum mismatch: %08x %08x\n",
3038		    finicsum, cfcsum);
3039	}
3040	sc->cfcsum = cfcsum;
3041
3042#define LIMIT_CAPS(x) do { \
3043	caps.x &= htobe16(t4_##x##_allowed); \
3044} while (0)
3045
3046	/*
3047	 * Let the firmware know what features will (not) be used so it can tune
3048	 * things accordingly.
3049	 */
3050	LIMIT_CAPS(nbmcaps);
3051	LIMIT_CAPS(linkcaps);
3052	LIMIT_CAPS(switchcaps);
3053	LIMIT_CAPS(niccaps);
3054	LIMIT_CAPS(toecaps);
3055	LIMIT_CAPS(rdmacaps);
3056	LIMIT_CAPS(cryptocaps);
3057	LIMIT_CAPS(iscsicaps);
3058	LIMIT_CAPS(fcoecaps);
3059#undef LIMIT_CAPS
3060
3061	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3062	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
3063	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3064	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
3065	if (rc != 0) {
3066		device_printf(sc->dev,
3067		    "failed to process config file: %d.\n", rc);
3068	}
3069done:
3070	if (cfg != NULL)
3071		firmware_put(cfg, FIRMWARE_UNLOAD);
3072	return (rc);
3073}
3074
3075/*
3076 * Retrieve parameters that are needed (or nice to have) very early.
3077 */
3078static int
3079get_params__pre_init(struct adapter *sc)
3080{
3081	int rc;
3082	uint32_t param[2], val[2];
3083
3084	t4_get_version_info(sc);
3085
3086	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
3087	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
3088	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
3089	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
3090	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
3091
3092	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
3093	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
3094	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
3095	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
3096	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
3097
3098	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
3099	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
3100	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
3101	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
3102	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
3103
3104	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
3105	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
3106	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
3107	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
3108	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
3109
3110	param[0] = FW_PARAM_DEV(PORTVEC);
3111	param[1] = FW_PARAM_DEV(CCLK);
3112	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3113	if (rc != 0) {
3114		device_printf(sc->dev,
3115		    "failed to query parameters (pre_init): %d.\n", rc);
3116		return (rc);
3117	}
3118
3119	sc->params.portvec = val[0];
3120	sc->params.nports = bitcount32(val[0]);
3121	sc->params.vpd.cclk = val[1];
3122
3123	/* Read device log parameters. */
3124	rc = -t4_init_devlog_params(sc, 1);
3125	if (rc == 0)
3126		fixup_devlog_params(sc);
3127	else {
3128		device_printf(sc->dev,
3129		    "failed to get devlog parameters: %d.\n", rc);
3130		rc = 0;	/* devlog isn't critical for device operation */
3131	}
3132
3133	return (rc);
3134}
3135
3136/*
3137 * Retrieve various parameters that are of interest to the driver.  The device
3138 * has been initialized by the firmware at this point.
3139 */
3140static int
3141get_params__post_init(struct adapter *sc)
3142{
3143	int rc;
3144	uint32_t param[7], val[7];
3145	struct fw_caps_config_cmd caps;
3146
3147	param[0] = FW_PARAM_PFVF(IQFLINT_START);
3148	param[1] = FW_PARAM_PFVF(EQ_START);
3149	param[2] = FW_PARAM_PFVF(FILTER_START);
3150	param[3] = FW_PARAM_PFVF(FILTER_END);
3151	param[4] = FW_PARAM_PFVF(L2T_START);
3152	param[5] = FW_PARAM_PFVF(L2T_END);
3153	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3154	if (rc != 0) {
3155		device_printf(sc->dev,
3156		    "failed to query parameters (post_init): %d.\n", rc);
3157		return (rc);
3158	}
3159
3160	sc->sge.iq_start = val[0];
3161	sc->sge.eq_start = val[1];
3162	sc->tids.ftid_base = val[2];
3163	sc->tids.nftids = val[3] - val[2] + 1;
3164	sc->params.ftid_min = val[2];
3165	sc->params.ftid_max = val[3];
3166	sc->vres.l2t.start = val[4];
3167	sc->vres.l2t.size = val[5] - val[4] + 1;
3168	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
3169	    ("%s: L2 table size (%u) larger than expected (%u)",
3170	    __func__, sc->vres.l2t.size, L2T_SIZE));
3171
3172	/* get capabilites */
3173	bzero(&caps, sizeof(caps));
3174	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3175	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
3176	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3177	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3178	if (rc != 0) {
3179		device_printf(sc->dev,
3180		    "failed to get card capabilities: %d.\n", rc);
3181		return (rc);
3182	}
3183
3184#define READ_CAPS(x) do { \
3185	sc->x = htobe16(caps.x); \
3186} while (0)
3187	READ_CAPS(nbmcaps);
3188	READ_CAPS(linkcaps);
3189	READ_CAPS(switchcaps);
3190	READ_CAPS(niccaps);
3191	READ_CAPS(toecaps);
3192	READ_CAPS(rdmacaps);
3193	READ_CAPS(cryptocaps);
3194	READ_CAPS(iscsicaps);
3195	READ_CAPS(fcoecaps);
3196
3197	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
3198		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
3199		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
3200		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3201		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
3202		if (rc != 0) {
3203			device_printf(sc->dev,
3204			    "failed to query NIC parameters: %d.\n", rc);
3205			return (rc);
3206		}
3207		sc->tids.etid_base = val[0];
3208		sc->params.etid_min = val[0];
3209		sc->tids.netids = val[1] - val[0] + 1;
3210		sc->params.netids = sc->tids.netids;
3211		sc->params.eo_wr_cred = val[2];
3212		sc->params.ethoffload = 1;
3213	}
3214
3215	if (sc->toecaps) {
3216		/* query offload-related parameters */
3217		param[0] = FW_PARAM_DEV(NTID);
3218		param[1] = FW_PARAM_PFVF(SERVER_START);
3219		param[2] = FW_PARAM_PFVF(SERVER_END);
3220		param[3] = FW_PARAM_PFVF(TDDP_START);
3221		param[4] = FW_PARAM_PFVF(TDDP_END);
3222		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3223		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3224		if (rc != 0) {
3225			device_printf(sc->dev,
3226			    "failed to query TOE parameters: %d.\n", rc);
3227			return (rc);
3228		}
3229		sc->tids.ntids = val[0];
3230		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
3231		sc->tids.stid_base = val[1];
3232		sc->tids.nstids = val[2] - val[1] + 1;
3233		sc->vres.ddp.start = val[3];
3234		sc->vres.ddp.size = val[4] - val[3] + 1;
3235		sc->params.ofldq_wr_cred = val[5];
3236		sc->params.offload = 1;
3237	}
3238	if (sc->rdmacaps) {
3239		param[0] = FW_PARAM_PFVF(STAG_START);
3240		param[1] = FW_PARAM_PFVF(STAG_END);
3241		param[2] = FW_PARAM_PFVF(RQ_START);
3242		param[3] = FW_PARAM_PFVF(RQ_END);
3243		param[4] = FW_PARAM_PFVF(PBL_START);
3244		param[5] = FW_PARAM_PFVF(PBL_END);
3245		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3246		if (rc != 0) {
3247			device_printf(sc->dev,
3248			    "failed to query RDMA parameters(1): %d.\n", rc);
3249			return (rc);
3250		}
3251		sc->vres.stag.start = val[0];
3252		sc->vres.stag.size = val[1] - val[0] + 1;
3253		sc->vres.rq.start = val[2];
3254		sc->vres.rq.size = val[3] - val[2] + 1;
3255		sc->vres.pbl.start = val[4];
3256		sc->vres.pbl.size = val[5] - val[4] + 1;
3257
3258		param[0] = FW_PARAM_PFVF(SQRQ_START);
3259		param[1] = FW_PARAM_PFVF(SQRQ_END);
3260		param[2] = FW_PARAM_PFVF(CQ_START);
3261		param[3] = FW_PARAM_PFVF(CQ_END);
3262		param[4] = FW_PARAM_PFVF(OCQ_START);
3263		param[5] = FW_PARAM_PFVF(OCQ_END);
3264		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3265		if (rc != 0) {
3266			device_printf(sc->dev,
3267			    "failed to query RDMA parameters(2): %d.\n", rc);
3268			return (rc);
3269		}
3270		sc->vres.qp.start = val[0];
3271		sc->vres.qp.size = val[1] - val[0] + 1;
3272		sc->vres.cq.start = val[2];
3273		sc->vres.cq.size = val[3] - val[2] + 1;
3274		sc->vres.ocq.start = val[4];
3275		sc->vres.ocq.size = val[5] - val[4] + 1;
3276	}
3277	if (sc->iscsicaps) {
3278		param[0] = FW_PARAM_PFVF(ISCSI_START);
3279		param[1] = FW_PARAM_PFVF(ISCSI_END);
3280		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3281		if (rc != 0) {
3282			device_printf(sc->dev,
3283			    "failed to query iSCSI parameters: %d.\n", rc);
3284			return (rc);
3285		}
3286		sc->vres.iscsi.start = val[0];
3287		sc->vres.iscsi.size = val[1] - val[0] + 1;
3288	}
3289
3290	t4_init_sge_params(sc);
3291
3292	/*
3293	 * We've got the params we wanted to query via the firmware.  Now grab
3294	 * some others directly from the chip.
3295	 */
3296	rc = t4_read_chip_settings(sc);
3297
3298	return (rc);
3299}
3300
3301static int
3302set_params__post_init(struct adapter *sc)
3303{
3304	uint32_t param, val;
3305
3306	/* ask for encapsulated CPLs */
3307	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
3308	val = 1;
3309	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3310
3311	return (0);
3312}
3313
3314#undef FW_PARAM_PFVF
3315#undef FW_PARAM_DEV
3316
3317static void
3318t4_set_desc(struct adapter *sc)
3319{
3320	char buf[128];
3321	struct adapter_params *p = &sc->params;
3322
3323	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
3324
3325	device_set_desc_copy(sc->dev, buf);
3326}
3327
3328static void
3329build_medialist(struct port_info *pi, struct ifmedia *media)
3330{
3331	int m;
3332
3333	PORT_LOCK(pi);
3334
3335	ifmedia_removeall(media);
3336
3337	m = IFM_ETHER | IFM_FDX;
3338
3339	switch(pi->port_type) {
3340	case FW_PORT_TYPE_BT_XFI:
3341	case FW_PORT_TYPE_BT_XAUI:
3342		ifmedia_add(media, m | IFM_10G_T, 0, NULL);
3343		/* fall through */
3344
3345	case FW_PORT_TYPE_BT_SGMII:
3346		ifmedia_add(media, m | IFM_1000_T, 0, NULL);
3347		ifmedia_add(media, m | IFM_100_TX, 0, NULL);
3348		ifmedia_add(media, IFM_ETHER | IFM_AUTO, 0, NULL);
3349		ifmedia_set(media, IFM_ETHER | IFM_AUTO);
3350		break;
3351
3352	case FW_PORT_TYPE_CX4:
3353		ifmedia_add(media, m | IFM_10G_CX4, 0, NULL);
3354		ifmedia_set(media, m | IFM_10G_CX4);
3355		break;
3356
3357	case FW_PORT_TYPE_QSFP_10G:
3358	case FW_PORT_TYPE_SFP:
3359	case FW_PORT_TYPE_FIBER_XFI:
3360	case FW_PORT_TYPE_FIBER_XAUI:
3361		switch (pi->mod_type) {
3362
3363		case FW_PORT_MOD_TYPE_LR:
3364			ifmedia_add(media, m | IFM_10G_LR, 0, NULL);
3365			ifmedia_set(media, m | IFM_10G_LR);
3366			break;
3367
3368		case FW_PORT_MOD_TYPE_SR:
3369			ifmedia_add(media, m | IFM_10G_SR, 0, NULL);
3370			ifmedia_set(media, m | IFM_10G_SR);
3371			break;
3372
3373		case FW_PORT_MOD_TYPE_LRM:
3374			ifmedia_add(media, m | IFM_10G_LRM, 0, NULL);
3375			ifmedia_set(media, m | IFM_10G_LRM);
3376			break;
3377
3378		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3379		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3380			ifmedia_add(media, m | IFM_10G_TWINAX, 0, NULL);
3381			ifmedia_set(media, m | IFM_10G_TWINAX);
3382			break;
3383
3384		case FW_PORT_MOD_TYPE_NONE:
3385			m &= ~IFM_FDX;
3386			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3387			ifmedia_set(media, m | IFM_NONE);
3388			break;
3389
3390		case FW_PORT_MOD_TYPE_NA:
3391		case FW_PORT_MOD_TYPE_ER:
3392		default:
3393			device_printf(pi->dev,
3394			    "unknown port_type (%d), mod_type (%d)\n",
3395			    pi->port_type, pi->mod_type);
3396			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3397			ifmedia_set(media, m | IFM_UNKNOWN);
3398			break;
3399		}
3400		break;
3401
3402	case FW_PORT_TYPE_CR_QSFP:
3403	case FW_PORT_TYPE_CR_SFP28:
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
8455#define MAX_READ_BUF_SIZE (128 * 1024)
8456static int
8457read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
8458{
8459	uint32_t addr, remaining, n;
8460	uint32_t *buf;
8461	int rc;
8462	uint8_t *dst;
8463
8464	rc = validate_mem_range(sc, mr->addr, mr->len);
8465	if (rc != 0)
8466		return (rc);
8467
8468	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
8469	addr = mr->addr;
8470	remaining = mr->len;
8471	dst = (void *)mr->data;
8472
8473	while (remaining) {
8474		n = min(remaining, MAX_READ_BUF_SIZE);
8475		read_via_memwin(sc, 2, addr, buf, n);
8476
8477		rc = copyout(buf, dst, n);
8478		if (rc != 0)
8479			break;
8480
8481		dst += n;
8482		remaining -= n;
8483		addr += n;
8484	}
8485
8486	free(buf, M_CXGBE);
8487	return (rc);
8488}
8489#undef MAX_READ_BUF_SIZE
8490
8491static int
8492read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
8493{
8494	int rc;
8495
8496	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
8497		return (EINVAL);
8498
8499	if (i2cd->len > sizeof(i2cd->data))
8500		return (EFBIG);
8501
8502	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
8503	if (rc)
8504		return (rc);
8505	rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
8506	    i2cd->offset, i2cd->len, &i2cd->data[0]);
8507	end_synchronized_op(sc, 0);
8508
8509	return (rc);
8510}
8511
8512static int
8513in_range(int val, int lo, int hi)
8514{
8515
8516	return (val < 0 || (val <= hi && val >= lo));
8517}
8518
8519static int
8520set_sched_class_config(struct adapter *sc, int minmax)
8521{
8522	int rc;
8523
8524	if (minmax < 0)
8525		return (EINVAL);
8526
8527	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4sscc");
8528	if (rc)
8529		return (rc);
8530	rc = -t4_sched_config(sc, FW_SCHED_TYPE_PKTSCHED, minmax, 1);
8531	end_synchronized_op(sc, 0);
8532
8533	return (rc);
8534}
8535
8536static int
8537set_sched_class_params(struct adapter *sc, struct t4_sched_class_params *p,
8538    int sleep_ok)
8539{
8540	int rc, top_speed, fw_level, fw_mode, fw_rateunit, fw_ratemode;
8541	struct port_info *pi;
8542	struct tx_sched_class *tc;
8543
8544	if (p->level == SCHED_CLASS_LEVEL_CL_RL)
8545		fw_level = FW_SCHED_PARAMS_LEVEL_CL_RL;
8546	else if (p->level == SCHED_CLASS_LEVEL_CL_WRR)
8547		fw_level = FW_SCHED_PARAMS_LEVEL_CL_WRR;
8548	else if (p->level == SCHED_CLASS_LEVEL_CH_RL)
8549		fw_level = FW_SCHED_PARAMS_LEVEL_CH_RL;
8550	else
8551		return (EINVAL);
8552
8553	if (p->mode == SCHED_CLASS_MODE_CLASS)
8554		fw_mode = FW_SCHED_PARAMS_MODE_CLASS;
8555	else if (p->mode == SCHED_CLASS_MODE_FLOW)
8556		fw_mode = FW_SCHED_PARAMS_MODE_FLOW;
8557	else
8558		return (EINVAL);
8559
8560	if (p->rateunit == SCHED_CLASS_RATEUNIT_BITS)
8561		fw_rateunit = FW_SCHED_PARAMS_UNIT_BITRATE;
8562	else if (p->rateunit == SCHED_CLASS_RATEUNIT_PKTS)
8563		fw_rateunit = FW_SCHED_PARAMS_UNIT_PKTRATE;
8564	else
8565		return (EINVAL);
8566
8567	if (p->ratemode == SCHED_CLASS_RATEMODE_REL)
8568		fw_ratemode = FW_SCHED_PARAMS_RATE_REL;
8569	else if (p->ratemode == SCHED_CLASS_RATEMODE_ABS)
8570		fw_ratemode = FW_SCHED_PARAMS_RATE_ABS;
8571	else
8572		return (EINVAL);
8573
8574	/* Vet our parameters ... */
8575	if (!in_range(p->channel, 0, sc->chip_params->nchan - 1))
8576		return (ERANGE);
8577
8578	pi = sc->port[sc->chan_map[p->channel]];
8579	if (pi == NULL)
8580		return (ENXIO);
8581	MPASS(pi->tx_chan == p->channel);
8582	top_speed = port_top_speed(pi) * 1000000; /* Gbps -> Kbps */
8583
8584	if (!in_range(p->cl, 0, sc->chip_params->nsched_cls) ||
8585	    !in_range(p->minrate, 0, top_speed) ||
8586	    !in_range(p->maxrate, 0, top_speed) ||
8587	    !in_range(p->weight, 0, 100))
8588		return (ERANGE);
8589
8590	/*
8591	 * Translate any unset parameters into the firmware's
8592	 * nomenclature and/or fail the call if the parameters
8593	 * are required ...
8594	 */
8595	if (p->rateunit < 0 || p->ratemode < 0 || p->channel < 0 || p->cl < 0)
8596		return (EINVAL);
8597
8598	if (p->minrate < 0)
8599		p->minrate = 0;
8600	if (p->maxrate < 0) {
8601		if (p->level == SCHED_CLASS_LEVEL_CL_RL ||
8602		    p->level == SCHED_CLASS_LEVEL_CH_RL)
8603			return (EINVAL);
8604		else
8605			p->maxrate = 0;
8606	}
8607	if (p->weight < 0) {
8608		if (p->level == SCHED_CLASS_LEVEL_CL_WRR)
8609			return (EINVAL);
8610		else
8611			p->weight = 0;
8612	}
8613	if (p->pktsize < 0) {
8614		if (p->level == SCHED_CLASS_LEVEL_CL_RL ||
8615		    p->level == SCHED_CLASS_LEVEL_CH_RL)
8616			return (EINVAL);
8617		else
8618			p->pktsize = 0;
8619	}
8620
8621	rc = begin_synchronized_op(sc, NULL,
8622	    sleep_ok ? (SLEEP_OK | INTR_OK) : HOLD_LOCK, "t4sscp");
8623	if (rc)
8624		return (rc);
8625	tc = &pi->tc[p->cl];
8626	tc->params = *p;
8627	rc = -t4_sched_params(sc, FW_SCHED_TYPE_PKTSCHED, fw_level, fw_mode,
8628	    fw_rateunit, fw_ratemode, p->channel, p->cl, p->minrate, p->maxrate,
8629	    p->weight, p->pktsize, sleep_ok);
8630	if (rc == 0)
8631		tc->flags |= TX_SC_OK;
8632	else {
8633		/*
8634		 * Unknown state at this point, see tc->params for what was
8635		 * attempted.
8636		 */
8637		tc->flags &= ~TX_SC_OK;
8638	}
8639	end_synchronized_op(sc, sleep_ok ? 0 : LOCK_HELD);
8640
8641	return (rc);
8642}
8643
8644int
8645t4_set_sched_class(struct adapter *sc, struct t4_sched_params *p)
8646{
8647
8648	if (p->type != SCHED_CLASS_TYPE_PACKET)
8649		return (EINVAL);
8650
8651	if (p->subcmd == SCHED_CLASS_SUBCMD_CONFIG)
8652		return (set_sched_class_config(sc, p->u.config.minmax));
8653
8654	if (p->subcmd == SCHED_CLASS_SUBCMD_PARAMS)
8655		return (set_sched_class_params(sc, &p->u.params, 1));
8656
8657	return (EINVAL);
8658}
8659
8660int
8661t4_set_sched_queue(struct adapter *sc, struct t4_sched_queue *p)
8662{
8663	struct port_info *pi = NULL;
8664	struct vi_info *vi;
8665	struct sge_txq *txq;
8666	uint32_t fw_mnem, fw_queue, fw_class;
8667	int i, rc;
8668
8669	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4setsq");
8670	if (rc)
8671		return (rc);
8672
8673	if (p->port >= sc->params.nports) {
8674		rc = EINVAL;
8675		goto done;
8676	}
8677
8678	/* XXX: Only supported for the main VI. */
8679	pi = sc->port[p->port];
8680	vi = &pi->vi[0];
8681	if (!(vi->flags & VI_INIT_DONE)) {
8682		/* tx queues not set up yet */
8683		rc = EAGAIN;
8684		goto done;
8685	}
8686
8687	if (!in_range(p->queue, 0, vi->ntxq - 1) ||
8688	    !in_range(p->cl, 0, sc->chip_params->nsched_cls - 1)) {
8689		rc = EINVAL;
8690		goto done;
8691	}
8692
8693	/*
8694	 * Create a template for the FW_PARAMS_CMD mnemonic and value (TX
8695	 * Scheduling Class in this case).
8696	 */
8697	fw_mnem = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
8698	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_EQ_SCHEDCLASS_ETH));
8699	fw_class = p->cl < 0 ? 0xffffffff : p->cl;
8700
8701	/*
8702	 * If op.queue is non-negative, then we're only changing the scheduling
8703	 * on a single specified TX queue.
8704	 */
8705	if (p->queue >= 0) {
8706		txq = &sc->sge.txq[vi->first_txq + p->queue];
8707		fw_queue = (fw_mnem | V_FW_PARAMS_PARAM_YZ(txq->eq.cntxt_id));
8708		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &fw_queue,
8709		    &fw_class);
8710		goto done;
8711	}
8712
8713	/*
8714	 * Change the scheduling on all the TX queues for the
8715	 * interface.
8716	 */
8717	for_each_txq(vi, i, txq) {
8718		fw_queue = (fw_mnem | V_FW_PARAMS_PARAM_YZ(txq->eq.cntxt_id));
8719		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &fw_queue,
8720		    &fw_class);
8721		if (rc)
8722			goto done;
8723	}
8724
8725	rc = 0;
8726done:
8727	end_synchronized_op(sc, 0);
8728	return (rc);
8729}
8730
8731int
8732t4_os_find_pci_capability(struct adapter *sc, int cap)
8733{
8734	int i;
8735
8736	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
8737}
8738
8739int
8740t4_os_pci_save_state(struct adapter *sc)
8741{
8742	device_t dev;
8743	struct pci_devinfo *dinfo;
8744
8745	dev = sc->dev;
8746	dinfo = device_get_ivars(dev);
8747
8748	pci_cfg_save(dev, dinfo, 0);
8749	return (0);
8750}
8751
8752int
8753t4_os_pci_restore_state(struct adapter *sc)
8754{
8755	device_t dev;
8756	struct pci_devinfo *dinfo;
8757
8758	dev = sc->dev;
8759	dinfo = device_get_ivars(dev);
8760
8761	pci_cfg_restore(dev, dinfo);
8762	return (0);
8763}
8764
8765void
8766t4_os_portmod_changed(const struct adapter *sc, int idx)
8767{
8768	struct port_info *pi = sc->port[idx];
8769	struct vi_info *vi;
8770	struct ifnet *ifp;
8771	int v;
8772	static const char *mod_str[] = {
8773		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
8774	};
8775
8776	for_each_vi(pi, v, vi) {
8777		build_medialist(pi, &vi->media);
8778	}
8779
8780	ifp = pi->vi[0].ifp;
8781	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
8782		if_printf(ifp, "transceiver unplugged.\n");
8783	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
8784		if_printf(ifp, "unknown transceiver inserted.\n");
8785	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
8786		if_printf(ifp, "unsupported transceiver inserted.\n");
8787	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
8788		if_printf(ifp, "%s transceiver inserted.\n",
8789		    mod_str[pi->mod_type]);
8790	} else {
8791		if_printf(ifp, "transceiver (type %d) inserted.\n",
8792		    pi->mod_type);
8793	}
8794}
8795
8796void
8797t4_os_link_changed(struct adapter *sc, int idx, int link_stat, int reason)
8798{
8799	struct port_info *pi = sc->port[idx];
8800	struct vi_info *vi;
8801	struct ifnet *ifp;
8802	int v;
8803
8804	if (link_stat)
8805		pi->linkdnrc = -1;
8806	else {
8807		if (reason >= 0)
8808			pi->linkdnrc = reason;
8809	}
8810	for_each_vi(pi, v, vi) {
8811		ifp = vi->ifp;
8812		if (ifp == NULL)
8813			continue;
8814
8815		if (link_stat) {
8816			ifp->if_baudrate = IF_Mbps(pi->link_cfg.speed);
8817			if_link_state_change(ifp, LINK_STATE_UP);
8818		} else {
8819			if_link_state_change(ifp, LINK_STATE_DOWN);
8820		}
8821	}
8822}
8823
8824void
8825t4_iterate(void (*func)(struct adapter *, void *), void *arg)
8826{
8827	struct adapter *sc;
8828
8829	sx_slock(&t4_list_lock);
8830	SLIST_FOREACH(sc, &t4_list, link) {
8831		/*
8832		 * func should not make any assumptions about what state sc is
8833		 * in - the only guarantee is that sc->sc_lock is a valid lock.
8834		 */
8835		func(sc, arg);
8836	}
8837	sx_sunlock(&t4_list_lock);
8838}
8839
8840static int
8841t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
8842    struct thread *td)
8843{
8844	int rc;
8845	struct adapter *sc = dev->si_drv1;
8846
8847	rc = priv_check(td, PRIV_DRIVER);
8848	if (rc != 0)
8849		return (rc);
8850
8851	switch (cmd) {
8852	case CHELSIO_T4_GETREG: {
8853		struct t4_reg *edata = (struct t4_reg *)data;
8854
8855		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
8856			return (EFAULT);
8857
8858		if (edata->size == 4)
8859			edata->val = t4_read_reg(sc, edata->addr);
8860		else if (edata->size == 8)
8861			edata->val = t4_read_reg64(sc, edata->addr);
8862		else
8863			return (EINVAL);
8864
8865		break;
8866	}
8867	case CHELSIO_T4_SETREG: {
8868		struct t4_reg *edata = (struct t4_reg *)data;
8869
8870		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
8871			return (EFAULT);
8872
8873		if (edata->size == 4) {
8874			if (edata->val & 0xffffffff00000000)
8875				return (EINVAL);
8876			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
8877		} else if (edata->size == 8)
8878			t4_write_reg64(sc, edata->addr, edata->val);
8879		else
8880			return (EINVAL);
8881		break;
8882	}
8883	case CHELSIO_T4_REGDUMP: {
8884		struct t4_regdump *regs = (struct t4_regdump *)data;
8885		int reglen = t4_get_regs_len(sc);
8886		uint8_t *buf;
8887
8888		if (regs->len < reglen) {
8889			regs->len = reglen; /* hint to the caller */
8890			return (ENOBUFS);
8891		}
8892
8893		regs->len = reglen;
8894		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
8895		get_regs(sc, regs, buf);
8896		rc = copyout(buf, regs->data, reglen);
8897		free(buf, M_CXGBE);
8898		break;
8899	}
8900	case CHELSIO_T4_GET_FILTER_MODE:
8901		rc = get_filter_mode(sc, (uint32_t *)data);
8902		break;
8903	case CHELSIO_T4_SET_FILTER_MODE:
8904		rc = set_filter_mode(sc, *(uint32_t *)data);
8905		break;
8906	case CHELSIO_T4_GET_FILTER:
8907		rc = get_filter(sc, (struct t4_filter *)data);
8908		break;
8909	case CHELSIO_T4_SET_FILTER:
8910		rc = set_filter(sc, (struct t4_filter *)data);
8911		break;
8912	case CHELSIO_T4_DEL_FILTER:
8913		rc = del_filter(sc, (struct t4_filter *)data);
8914		break;
8915	case CHELSIO_T4_GET_SGE_CONTEXT:
8916		rc = get_sge_context(sc, (struct t4_sge_context *)data);
8917		break;
8918	case CHELSIO_T4_LOAD_FW:
8919		rc = load_fw(sc, (struct t4_data *)data);
8920		break;
8921	case CHELSIO_T4_GET_MEM:
8922		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
8923		break;
8924	case CHELSIO_T4_GET_I2C:
8925		rc = read_i2c(sc, (struct t4_i2c_data *)data);
8926		break;
8927	case CHELSIO_T4_CLEAR_STATS: {
8928		int i, v;
8929		u_int port_id = *(uint32_t *)data;
8930		struct port_info *pi;
8931		struct vi_info *vi;
8932
8933		if (port_id >= sc->params.nports)
8934			return (EINVAL);
8935		pi = sc->port[port_id];
8936		if (pi == NULL)
8937			return (EIO);
8938
8939		/* MAC stats */
8940		t4_clr_port_stats(sc, pi->tx_chan);
8941		pi->tx_parse_error = 0;
8942		mtx_lock(&sc->reg_lock);
8943		for_each_vi(pi, v, vi) {
8944			if (vi->flags & VI_INIT_DONE)
8945				t4_clr_vi_stats(sc, vi->viid);
8946		}
8947		mtx_unlock(&sc->reg_lock);
8948
8949		/*
8950		 * Since this command accepts a port, clear stats for
8951		 * all VIs on this port.
8952		 */
8953		for_each_vi(pi, v, vi) {
8954			if (vi->flags & VI_INIT_DONE) {
8955				struct sge_rxq *rxq;
8956				struct sge_txq *txq;
8957				struct sge_wrq *wrq;
8958
8959				for_each_rxq(vi, i, rxq) {
8960#if defined(INET) || defined(INET6)
8961					rxq->lro.lro_queued = 0;
8962					rxq->lro.lro_flushed = 0;
8963#endif
8964					rxq->rxcsum = 0;
8965					rxq->vlan_extraction = 0;
8966				}
8967
8968				for_each_txq(vi, i, txq) {
8969					txq->txcsum = 0;
8970					txq->tso_wrs = 0;
8971					txq->vlan_insertion = 0;
8972					txq->imm_wrs = 0;
8973					txq->sgl_wrs = 0;
8974					txq->txpkt_wrs = 0;
8975					txq->txpkts0_wrs = 0;
8976					txq->txpkts1_wrs = 0;
8977					txq->txpkts0_pkts = 0;
8978					txq->txpkts1_pkts = 0;
8979					mp_ring_reset_stats(txq->r);
8980				}
8981
8982#ifdef TCP_OFFLOAD
8983				/* nothing to clear for each ofld_rxq */
8984
8985				for_each_ofld_txq(vi, i, wrq) {
8986					wrq->tx_wrs_direct = 0;
8987					wrq->tx_wrs_copied = 0;
8988				}
8989#endif
8990
8991				if (IS_MAIN_VI(vi)) {
8992					wrq = &sc->sge.ctrlq[pi->port_id];
8993					wrq->tx_wrs_direct = 0;
8994					wrq->tx_wrs_copied = 0;
8995				}
8996			}
8997		}
8998		break;
8999	}
9000	case CHELSIO_T4_SCHED_CLASS:
9001		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
9002		break;
9003	case CHELSIO_T4_SCHED_QUEUE:
9004		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
9005		break;
9006	case CHELSIO_T4_GET_TRACER:
9007		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
9008		break;
9009	case CHELSIO_T4_SET_TRACER:
9010		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
9011		break;
9012	default:
9013		rc = ENOTTY;
9014	}
9015
9016	return (rc);
9017}
9018
9019void
9020t4_db_full(struct adapter *sc)
9021{
9022
9023	CXGBE_UNIMPLEMENTED(__func__);
9024}
9025
9026void
9027t4_db_dropped(struct adapter *sc)
9028{
9029
9030	CXGBE_UNIMPLEMENTED(__func__);
9031}
9032
9033#ifdef TCP_OFFLOAD
9034void
9035t4_iscsi_init(struct adapter *sc, u_int tag_mask, const u_int *pgsz_order)
9036{
9037
9038	t4_write_reg(sc, A_ULP_RX_ISCSI_TAGMASK, tag_mask);
9039	t4_write_reg(sc, A_ULP_RX_ISCSI_PSZ, V_HPZ0(pgsz_order[0]) |
9040		V_HPZ1(pgsz_order[1]) | V_HPZ2(pgsz_order[2]) |
9041		V_HPZ3(pgsz_order[3]));
9042}
9043
9044static int
9045toe_capability(struct vi_info *vi, int enable)
9046{
9047	int rc;
9048	struct port_info *pi = vi->pi;
9049	struct adapter *sc = pi->adapter;
9050
9051	ASSERT_SYNCHRONIZED_OP(sc);
9052
9053	if (!is_offload(sc))
9054		return (ENODEV);
9055
9056	if (enable) {
9057		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
9058			/* TOE is already enabled. */
9059			return (0);
9060		}
9061
9062		/*
9063		 * We need the port's queues around so that we're able to send
9064		 * and receive CPLs to/from the TOE even if the ifnet for this
9065		 * port has never been UP'd administratively.
9066		 */
9067		if (!(vi->flags & VI_INIT_DONE)) {
9068			rc = vi_full_init(vi);
9069			if (rc)
9070				return (rc);
9071		}
9072		if (!(pi->vi[0].flags & VI_INIT_DONE)) {
9073			rc = vi_full_init(&pi->vi[0]);
9074			if (rc)
9075				return (rc);
9076		}
9077
9078		if (isset(&sc->offload_map, pi->port_id)) {
9079			/* TOE is enabled on another VI of this port. */
9080			pi->uld_vis++;
9081			return (0);
9082		}
9083
9084		if (!uld_active(sc, ULD_TOM)) {
9085			rc = t4_activate_uld(sc, ULD_TOM);
9086			if (rc == EAGAIN) {
9087				log(LOG_WARNING,
9088				    "You must kldload t4_tom.ko before trying "
9089				    "to enable TOE on a cxgbe interface.\n");
9090			}
9091			if (rc != 0)
9092				return (rc);
9093			KASSERT(sc->tom_softc != NULL,
9094			    ("%s: TOM activated but softc NULL", __func__));
9095			KASSERT(uld_active(sc, ULD_TOM),
9096			    ("%s: TOM activated but flag not set", __func__));
9097		}
9098
9099		/* Activate iWARP and iSCSI too, if the modules are loaded. */
9100		if (!uld_active(sc, ULD_IWARP))
9101			(void) t4_activate_uld(sc, ULD_IWARP);
9102		if (!uld_active(sc, ULD_ISCSI))
9103			(void) t4_activate_uld(sc, ULD_ISCSI);
9104
9105		pi->uld_vis++;
9106		setbit(&sc->offload_map, pi->port_id);
9107	} else {
9108		pi->uld_vis--;
9109
9110		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
9111			return (0);
9112
9113		KASSERT(uld_active(sc, ULD_TOM),
9114		    ("%s: TOM never initialized?", __func__));
9115		clrbit(&sc->offload_map, pi->port_id);
9116	}
9117
9118	return (0);
9119}
9120
9121/*
9122 * Add an upper layer driver to the global list.
9123 */
9124int
9125t4_register_uld(struct uld_info *ui)
9126{
9127	int rc = 0;
9128	struct uld_info *u;
9129
9130	sx_xlock(&t4_uld_list_lock);
9131	SLIST_FOREACH(u, &t4_uld_list, link) {
9132	    if (u->uld_id == ui->uld_id) {
9133		    rc = EEXIST;
9134		    goto done;
9135	    }
9136	}
9137
9138	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
9139	ui->refcount = 0;
9140done:
9141	sx_xunlock(&t4_uld_list_lock);
9142	return (rc);
9143}
9144
9145int
9146t4_unregister_uld(struct uld_info *ui)
9147{
9148	int rc = EINVAL;
9149	struct uld_info *u;
9150
9151	sx_xlock(&t4_uld_list_lock);
9152
9153	SLIST_FOREACH(u, &t4_uld_list, link) {
9154	    if (u == ui) {
9155		    if (ui->refcount > 0) {
9156			    rc = EBUSY;
9157			    goto done;
9158		    }
9159
9160		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
9161		    rc = 0;
9162		    goto done;
9163	    }
9164	}
9165done:
9166	sx_xunlock(&t4_uld_list_lock);
9167	return (rc);
9168}
9169
9170int
9171t4_activate_uld(struct adapter *sc, int id)
9172{
9173	int rc;
9174	struct uld_info *ui;
9175
9176	ASSERT_SYNCHRONIZED_OP(sc);
9177
9178	if (id < 0 || id > ULD_MAX)
9179		return (EINVAL);
9180	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
9181
9182	sx_slock(&t4_uld_list_lock);
9183
9184	SLIST_FOREACH(ui, &t4_uld_list, link) {
9185		if (ui->uld_id == id) {
9186			if (!(sc->flags & FULL_INIT_DONE)) {
9187				rc = adapter_full_init(sc);
9188				if (rc != 0)
9189					break;
9190			}
9191
9192			rc = ui->activate(sc);
9193			if (rc == 0) {
9194				setbit(&sc->active_ulds, id);
9195				ui->refcount++;
9196			}
9197			break;
9198		}
9199	}
9200
9201	sx_sunlock(&t4_uld_list_lock);
9202
9203	return (rc);
9204}
9205
9206int
9207t4_deactivate_uld(struct adapter *sc, int id)
9208{
9209	int rc;
9210	struct uld_info *ui;
9211
9212	ASSERT_SYNCHRONIZED_OP(sc);
9213
9214	if (id < 0 || id > ULD_MAX)
9215		return (EINVAL);
9216	rc = ENXIO;
9217
9218	sx_slock(&t4_uld_list_lock);
9219
9220	SLIST_FOREACH(ui, &t4_uld_list, link) {
9221		if (ui->uld_id == id) {
9222			rc = ui->deactivate(sc);
9223			if (rc == 0) {
9224				clrbit(&sc->active_ulds, id);
9225				ui->refcount--;
9226			}
9227			break;
9228		}
9229	}
9230
9231	sx_sunlock(&t4_uld_list_lock);
9232
9233	return (rc);
9234}
9235
9236int
9237uld_active(struct adapter *sc, int uld_id)
9238{
9239
9240	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
9241
9242	return (isset(&sc->active_ulds, uld_id));
9243}
9244#endif
9245
9246/*
9247 * Come up with reasonable defaults for some of the tunables, provided they're
9248 * not set by the user (in which case we'll use the values as is).
9249 */
9250static void
9251tweak_tunables(void)
9252{
9253	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
9254
9255	if (t4_ntxq10g < 1) {
9256#ifdef RSS
9257		t4_ntxq10g = rss_getnumbuckets();
9258#else
9259		t4_ntxq10g = min(nc, NTXQ_10G);
9260#endif
9261	}
9262
9263	if (t4_ntxq1g < 1) {
9264#ifdef RSS
9265		/* XXX: way too many for 1GbE? */
9266		t4_ntxq1g = rss_getnumbuckets();
9267#else
9268		t4_ntxq1g = min(nc, NTXQ_1G);
9269#endif
9270	}
9271
9272	if (t4_ntxq_vi < 1)
9273		t4_ntxq_vi = min(nc, NTXQ_VI);
9274
9275	if (t4_nrxq10g < 1) {
9276#ifdef RSS
9277		t4_nrxq10g = rss_getnumbuckets();
9278#else
9279		t4_nrxq10g = min(nc, NRXQ_10G);
9280#endif
9281	}
9282
9283	if (t4_nrxq1g < 1) {
9284#ifdef RSS
9285		/* XXX: way too many for 1GbE? */
9286		t4_nrxq1g = rss_getnumbuckets();
9287#else
9288		t4_nrxq1g = min(nc, NRXQ_1G);
9289#endif
9290	}
9291
9292	if (t4_nrxq_vi < 1)
9293		t4_nrxq_vi = min(nc, NRXQ_VI);
9294
9295#ifdef TCP_OFFLOAD
9296	if (t4_nofldtxq10g < 1)
9297		t4_nofldtxq10g = min(nc, NOFLDTXQ_10G);
9298
9299	if (t4_nofldtxq1g < 1)
9300		t4_nofldtxq1g = min(nc, NOFLDTXQ_1G);
9301
9302	if (t4_nofldtxq_vi < 1)
9303		t4_nofldtxq_vi = min(nc, NOFLDTXQ_VI);
9304
9305	if (t4_nofldrxq10g < 1)
9306		t4_nofldrxq10g = min(nc, NOFLDRXQ_10G);
9307
9308	if (t4_nofldrxq1g < 1)
9309		t4_nofldrxq1g = min(nc, NOFLDRXQ_1G);
9310
9311	if (t4_nofldrxq_vi < 1)
9312		t4_nofldrxq_vi = min(nc, NOFLDRXQ_VI);
9313
9314	if (t4_toecaps_allowed == -1)
9315		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
9316
9317	if (t4_rdmacaps_allowed == -1) {
9318		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
9319		    FW_CAPS_CONFIG_RDMA_RDMAC;
9320	}
9321
9322	if (t4_iscsicaps_allowed == -1) {
9323		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
9324		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
9325		    FW_CAPS_CONFIG_ISCSI_T10DIF;
9326	}
9327#else
9328	if (t4_toecaps_allowed == -1)
9329		t4_toecaps_allowed = 0;
9330
9331	if (t4_rdmacaps_allowed == -1)
9332		t4_rdmacaps_allowed = 0;
9333
9334	if (t4_iscsicaps_allowed == -1)
9335		t4_iscsicaps_allowed = 0;
9336#endif
9337
9338#ifdef DEV_NETMAP
9339	if (t4_nnmtxq_vi < 1)
9340		t4_nnmtxq_vi = min(nc, NNMTXQ_VI);
9341
9342	if (t4_nnmrxq_vi < 1)
9343		t4_nnmrxq_vi = min(nc, NNMRXQ_VI);
9344#endif
9345
9346	if (t4_tmr_idx_10g < 0 || t4_tmr_idx_10g >= SGE_NTIMERS)
9347		t4_tmr_idx_10g = TMR_IDX_10G;
9348
9349	if (t4_pktc_idx_10g < -1 || t4_pktc_idx_10g >= SGE_NCOUNTERS)
9350		t4_pktc_idx_10g = PKTC_IDX_10G;
9351
9352	if (t4_tmr_idx_1g < 0 || t4_tmr_idx_1g >= SGE_NTIMERS)
9353		t4_tmr_idx_1g = TMR_IDX_1G;
9354
9355	if (t4_pktc_idx_1g < -1 || t4_pktc_idx_1g >= SGE_NCOUNTERS)
9356		t4_pktc_idx_1g = PKTC_IDX_1G;
9357
9358	if (t4_qsize_txq < 128)
9359		t4_qsize_txq = 128;
9360
9361	if (t4_qsize_rxq < 128)
9362		t4_qsize_rxq = 128;
9363	while (t4_qsize_rxq & 7)
9364		t4_qsize_rxq++;
9365
9366	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
9367}
9368
9369#ifdef DDB
9370static void
9371t4_dump_tcb(struct adapter *sc, int tid)
9372{
9373	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
9374
9375	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
9376	save = t4_read_reg(sc, reg);
9377	base = sc->memwin[2].mw_base;
9378
9379	/* Dump TCB for the tid */
9380	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9381	tcb_addr += tid * TCB_SIZE;
9382
9383	if (is_t4(sc)) {
9384		pf = 0;
9385		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
9386	} else {
9387		pf = V_PFNUM(sc->pf);
9388		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
9389	}
9390	t4_write_reg(sc, reg, win_pos | pf);
9391	t4_read_reg(sc, reg);
9392
9393	off = tcb_addr - win_pos;
9394	for (i = 0; i < 4; i++) {
9395		uint32_t buf[8];
9396		for (j = 0; j < 8; j++, off += 4)
9397			buf[j] = htonl(t4_read_reg(sc, base + off));
9398
9399		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
9400		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
9401		    buf[7]);
9402	}
9403
9404	t4_write_reg(sc, reg, save);
9405	t4_read_reg(sc, reg);
9406}
9407
9408static void
9409t4_dump_devlog(struct adapter *sc)
9410{
9411	struct devlog_params *dparams = &sc->params.devlog;
9412	struct fw_devlog_e e;
9413	int i, first, j, m, nentries, rc;
9414	uint64_t ftstamp = UINT64_MAX;
9415
9416	if (dparams->start == 0) {
9417		db_printf("devlog params not valid\n");
9418		return;
9419	}
9420
9421	nentries = dparams->size / sizeof(struct fw_devlog_e);
9422	m = fwmtype_to_hwmtype(dparams->memtype);
9423
9424	/* Find the first entry. */
9425	first = -1;
9426	for (i = 0; i < nentries && !db_pager_quit; i++) {
9427		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9428		    sizeof(e), (void *)&e);
9429		if (rc != 0)
9430			break;
9431
9432		if (e.timestamp == 0)
9433			break;
9434
9435		e.timestamp = be64toh(e.timestamp);
9436		if (e.timestamp < ftstamp) {
9437			ftstamp = e.timestamp;
9438			first = i;
9439		}
9440	}
9441
9442	if (first == -1)
9443		return;
9444
9445	i = first;
9446	do {
9447		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9448		    sizeof(e), (void *)&e);
9449		if (rc != 0)
9450			return;
9451
9452		if (e.timestamp == 0)
9453			return;
9454
9455		e.timestamp = be64toh(e.timestamp);
9456		e.seqno = be32toh(e.seqno);
9457		for (j = 0; j < 8; j++)
9458			e.params[j] = be32toh(e.params[j]);
9459
9460		db_printf("%10d  %15ju  %8s  %8s  ",
9461		    e.seqno, e.timestamp,
9462		    (e.level < nitems(devlog_level_strings) ?
9463			devlog_level_strings[e.level] : "UNKNOWN"),
9464		    (e.facility < nitems(devlog_facility_strings) ?
9465			devlog_facility_strings[e.facility] : "UNKNOWN"));
9466		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
9467		    e.params[3], e.params[4], e.params[5], e.params[6],
9468		    e.params[7]);
9469
9470		if (++i == nentries)
9471			i = 0;
9472	} while (i != first && !db_pager_quit);
9473}
9474
9475static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
9476_DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
9477
9478DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
9479{
9480	device_t dev;
9481	int t;
9482	bool valid;
9483
9484	valid = false;
9485	t = db_read_token();
9486	if (t == tIDENT) {
9487		dev = device_lookup_by_name(db_tok_string);
9488		valid = true;
9489	}
9490	db_skip_to_eol();
9491	if (!valid) {
9492		db_printf("usage: show t4 devlog <nexus>\n");
9493		return;
9494	}
9495
9496	if (dev == NULL) {
9497		db_printf("device not found\n");
9498		return;
9499	}
9500
9501	t4_dump_devlog(device_get_softc(dev));
9502}
9503
9504DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
9505{
9506	device_t dev;
9507	int radix, tid, t;
9508	bool valid;
9509
9510	valid = false;
9511	radix = db_radix;
9512	db_radix = 10;
9513	t = db_read_token();
9514	if (t == tIDENT) {
9515		dev = device_lookup_by_name(db_tok_string);
9516		t = db_read_token();
9517		if (t == tNUMBER) {
9518			tid = db_tok_number;
9519			valid = true;
9520		}
9521	}
9522	db_radix = radix;
9523	db_skip_to_eol();
9524	if (!valid) {
9525		db_printf("usage: show t4 tcb <nexus> <tid>\n");
9526		return;
9527	}
9528
9529	if (dev == NULL) {
9530		db_printf("device not found\n");
9531		return;
9532	}
9533	if (tid < 0) {
9534		db_printf("invalid tid\n");
9535		return;
9536	}
9537
9538	t4_dump_tcb(device_get_softc(dev), tid);
9539}
9540#endif
9541
9542static struct sx mlu;	/* mod load unload */
9543SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
9544
9545static int
9546mod_event(module_t mod, int cmd, void *arg)
9547{
9548	int rc = 0;
9549	static int loaded = 0;
9550
9551	switch (cmd) {
9552	case MOD_LOAD:
9553		sx_xlock(&mlu);
9554		if (loaded++ == 0) {
9555			t4_sge_modload();
9556			t4_register_cpl_handler(CPL_SET_TCB_RPL, set_tcb_rpl);
9557			t4_register_cpl_handler(CPL_L2T_WRITE_RPL, l2t_write_rpl);
9558			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
9559			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
9560			sx_init(&t4_list_lock, "T4/T5 adapters");
9561			SLIST_INIT(&t4_list);
9562#ifdef TCP_OFFLOAD
9563			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
9564			SLIST_INIT(&t4_uld_list);
9565#endif
9566			t4_tracer_modload();
9567			tweak_tunables();
9568		}
9569		sx_xunlock(&mlu);
9570		break;
9571
9572	case MOD_UNLOAD:
9573		sx_xlock(&mlu);
9574		if (--loaded == 0) {
9575			int tries;
9576
9577			sx_slock(&t4_list_lock);
9578			if (!SLIST_EMPTY(&t4_list)) {
9579				rc = EBUSY;
9580				sx_sunlock(&t4_list_lock);
9581				goto done_unload;
9582			}
9583#ifdef TCP_OFFLOAD
9584			sx_slock(&t4_uld_list_lock);
9585			if (!SLIST_EMPTY(&t4_uld_list)) {
9586				rc = EBUSY;
9587				sx_sunlock(&t4_uld_list_lock);
9588				sx_sunlock(&t4_list_lock);
9589				goto done_unload;
9590			}
9591#endif
9592			tries = 0;
9593			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
9594				uprintf("%ju clusters with custom free routine "
9595				    "still is use.\n", t4_sge_extfree_refs());
9596				pause("t4unload", 2 * hz);
9597			}
9598#ifdef TCP_OFFLOAD
9599			sx_sunlock(&t4_uld_list_lock);
9600#endif
9601			sx_sunlock(&t4_list_lock);
9602
9603			if (t4_sge_extfree_refs() == 0) {
9604				t4_tracer_modunload();
9605#ifdef TCP_OFFLOAD
9606				sx_destroy(&t4_uld_list_lock);
9607#endif
9608				sx_destroy(&t4_list_lock);
9609				t4_sge_modunload();
9610				loaded = 0;
9611			} else {
9612				rc = EBUSY;
9613				loaded++;	/* undo earlier decrement */
9614			}
9615		}
9616done_unload:
9617		sx_xunlock(&mlu);
9618		break;
9619	}
9620
9621	return (rc);
9622}
9623
9624static devclass_t t4_devclass, t5_devclass, t6_devclass;
9625static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
9626static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
9627
9628DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
9629MODULE_VERSION(t4nex, 1);
9630MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
9631
9632DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
9633MODULE_VERSION(t5nex, 1);
9634MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
9635
9636DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
9637MODULE_VERSION(t6nex, 1);
9638MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
9639#ifdef DEV_NETMAP
9640MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
9641#endif /* DEV_NETMAP */
9642
9643DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
9644MODULE_VERSION(cxgbe, 1);
9645
9646DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
9647MODULE_VERSION(cxl, 1);
9648
9649DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
9650MODULE_VERSION(cc, 1);
9651
9652DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
9653MODULE_VERSION(vcxgbe, 1);
9654
9655DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
9656MODULE_VERSION(vcxl, 1);
9657
9658DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
9659MODULE_VERSION(vcc, 1);
9660