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