t4_sge.c revision 255050
1249259Sdim/*-
2249259Sdim * Copyright (c) 2011 Chelsio Communications, Inc.
3249259Sdim * All rights reserved.
4249259Sdim * Written by: Navdeep Parhar <np@FreeBSD.org>
5249259Sdim *
6249259Sdim * Redistribution and use in source and binary forms, with or without
7249259Sdim * modification, are permitted provided that the following conditions
8249259Sdim * are met:
9249259Sdim * 1. Redistributions of source code must retain the above copyright
10249259Sdim *    notice, this list of conditions and the following disclaimer.
11249259Sdim * 2. Redistributions in binary form must reproduce the above copyright
12249259Sdim *    notice, this list of conditions and the following disclaimer in the
13249259Sdim *    documentation and/or other materials provided with the distribution.
14249259Sdim *
15249259Sdim * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16249259Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17249259Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18249259Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19249259Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20249259Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21249259Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22249259Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23249259Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24249259Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25249259Sdim * SUCH DAMAGE.
26249259Sdim */
27249259Sdim
28249259Sdim#include <sys/cdefs.h>
29249259Sdim__FBSDID("$FreeBSD: head/sys/dev/cxgbe/t4_sge.c 255050 2013-08-30 01:45:36Z np $");
30249259Sdim
31249259Sdim#include "opt_inet.h"
32249259Sdim#include "opt_inet6.h"
33249259Sdim
34249259Sdim#include <sys/types.h>
35249259Sdim#include <sys/mbuf.h>
36249259Sdim#include <sys/socket.h>
37249259Sdim#include <sys/kernel.h>
38249259Sdim#include <sys/kdb.h>
39249259Sdim#include <sys/malloc.h>
40249259Sdim#include <sys/queue.h>
41249259Sdim#include <sys/taskqueue.h>
42249259Sdim#include <sys/time.h>
43249259Sdim#include <sys/sysctl.h>
44249259Sdim#include <sys/smp.h>
45249259Sdim#include <net/bpf.h>
46249259Sdim#include <net/ethernet.h>
47249259Sdim#include <net/if.h>
48249259Sdim#include <net/if_vlan_var.h>
49249259Sdim#include <netinet/in.h>
50249259Sdim#include <netinet/ip.h>
51249259Sdim#include <netinet/ip6.h>
52249259Sdim#include <netinet/tcp.h>
53249259Sdim
54249259Sdim#include "common/common.h"
55249259Sdim#include "common/t4_regs.h"
56249259Sdim#include "common/t4_regs_values.h"
57249259Sdim#include "common/t4_msg.h"
58249259Sdim
59249259Sdim#ifdef T4_PKT_TIMESTAMP
60249259Sdim#define RX_COPY_THRESHOLD (MINCLSIZE - 8)
61249259Sdim#else
62249259Sdim#define RX_COPY_THRESHOLD MINCLSIZE
63249259Sdim#endif
64249259Sdim
65249259Sdim/*
66249259Sdim * Ethernet frames are DMA'd at this byte offset into the freelist buffer.
67249259Sdim * 0-7 are valid values.
68249259Sdim */
69249259Sdimstatic int fl_pktshift = 2;
70249259SdimTUNABLE_INT("hw.cxgbe.fl_pktshift", &fl_pktshift);
71249259Sdim
72249259Sdim/*
73249259Sdim * Pad ethernet payload up to this boundary.
74249259Sdim * -1: driver should figure out a good value.
75249259Sdim *  0: disable padding.
76249259Sdim *  Any power of 2 from 32 to 4096 (both inclusive) is also a valid value.
77249259Sdim */
78249259Sdimstatic int fl_pad = -1;
79249259SdimTUNABLE_INT("hw.cxgbe.fl_pad", &fl_pad);
80249259Sdim
81249259Sdim/*
82249259Sdim * Status page length.
83249259Sdim * -1: driver should figure out a good value.
84249259Sdim *  64 or 128 are the only other valid values.
85249259Sdim */
86249259Sdimstatic int spg_len = -1;
87249259SdimTUNABLE_INT("hw.cxgbe.spg_len", &spg_len);
88249259Sdim
89249259Sdim/*
90249259Sdim * Congestion drops.
91249259Sdim * -1: no congestion feedback (not recommended).
92249259Sdim *  0: backpressure the channel instead of dropping packets right away.
93249259Sdim *  1: no backpressure, drop packets for the congested queue immediately.
94249259Sdim */
95249259Sdimstatic int cong_drop = 0;
96249259SdimTUNABLE_INT("hw.cxgbe.cong_drop", &cong_drop);
97249259Sdim
98249259Sdim/*
99249259Sdim * Deliver multiple frames in the same free list buffer if they fit.
100249259Sdim * -1: let the driver decide whether to enable buffer packing or not.
101249259Sdim *  0: disable buffer packing.
102249259Sdim *  1: enable buffer packing.
103249259Sdim */
104249259Sdimstatic int buffer_packing = -1;
105249259SdimTUNABLE_INT("hw.cxgbe.buffer_packing", &buffer_packing);
106249259Sdim
107249259Sdim/*
108249259Sdim * Start next frame in a packed buffer at this boundary.
109249259Sdim * -1: driver should figure out a good value.
110249259Sdim * T4:
111249259Sdim * ---
112249259Sdim * if fl_pad != 0
113249259Sdim * 	value specified here will be overridden by fl_pad.
114249259Sdim * else
115249259Sdim * 	power of 2 from 32 to 4096 (both inclusive) is a valid value here.
116249259Sdim * T5:
117249259Sdim * ---
118249259Sdim * 16, or a power of 2 from 64 to 4096 (both inclusive) is a valid value.
119249259Sdim */
120249259Sdimstatic int fl_pack = -1;
121249259Sdimstatic int t4_fl_pack;
122249259Sdimstatic int t5_fl_pack;
123249259SdimTUNABLE_INT("hw.cxgbe.fl_pack", &fl_pack);
124249259Sdim
125249259Sdim/* Used to track coalesced tx work request */
126249259Sdimstruct txpkts {
127249259Sdim	uint64_t *flitp;	/* ptr to flit where next pkt should start */
128249259Sdim	uint8_t npkt;		/* # of packets in this work request */
129249259Sdim	uint8_t nflits;		/* # of flits used by this work request */
130249259Sdim	uint16_t plen;		/* total payload (sum of all packets) */
131249259Sdim};
132249259Sdim
133249259Sdim/* A packet's SGL.  This + m_pkthdr has all info needed for tx */
134249259Sdimstruct sgl {
135249259Sdim	int nsegs;		/* # of segments in the SGL, 0 means imm. tx */
136249259Sdim	int nflits;		/* # of flits needed for the SGL */
137249259Sdim	bus_dma_segment_t seg[TX_SGL_SEGS];
138249259Sdim};
139249259Sdim
140249259Sdimstatic int service_iq(struct sge_iq *, int);
141249259Sdimstatic struct mbuf *get_fl_payload1(struct adapter *, struct sge_fl *, uint32_t,
142249259Sdim    int *);
143249259Sdimstatic struct mbuf *get_fl_payload2(struct adapter *, struct sge_fl *, uint32_t,
144249259Sdim    int *);
145249259Sdimstatic int t4_eth_rx(struct sge_iq *, const struct rss_header *, struct mbuf *);
146249259Sdimstatic inline void init_iq(struct sge_iq *, struct adapter *, int, int, int,
147249259Sdim    int);
148249259Sdimstatic inline void init_fl(struct adapter *, struct sge_fl *, int, int, int,
149249259Sdim    char *);
150249259Sdimstatic inline void init_eq(struct sge_eq *, int, int, uint8_t, uint16_t,
151249259Sdim    char *);
152249259Sdimstatic int alloc_ring(struct adapter *, size_t, bus_dma_tag_t *, bus_dmamap_t *,
153249259Sdim    bus_addr_t *, void **);
154249259Sdimstatic int free_ring(struct adapter *, bus_dma_tag_t, bus_dmamap_t, bus_addr_t,
155249259Sdim    void *);
156249259Sdimstatic int alloc_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *,
157249259Sdim    int, int);
158249259Sdimstatic int free_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *);
159249259Sdimstatic int alloc_fwq(struct adapter *);
160249259Sdimstatic int free_fwq(struct adapter *);
161249259Sdimstatic int alloc_mgmtq(struct adapter *);
162249259Sdimstatic int free_mgmtq(struct adapter *);
163249259Sdimstatic int alloc_rxq(struct port_info *, struct sge_rxq *, int, int,
164249259Sdim    struct sysctl_oid *);
165249259Sdimstatic int free_rxq(struct port_info *, struct sge_rxq *);
166249259Sdim#ifdef TCP_OFFLOAD
167249259Sdimstatic int alloc_ofld_rxq(struct port_info *, struct sge_ofld_rxq *, int, int,
168249259Sdim    struct sysctl_oid *);
169249259Sdimstatic int free_ofld_rxq(struct port_info *, struct sge_ofld_rxq *);
170249259Sdim#endif
171249259Sdimstatic int ctrl_eq_alloc(struct adapter *, struct sge_eq *);
172249259Sdimstatic int eth_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
173249259Sdim#ifdef TCP_OFFLOAD
174249259Sdimstatic int ofld_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
175249259Sdim#endif
176249259Sdimstatic int alloc_eq(struct adapter *, struct port_info *, struct sge_eq *);
177249259Sdimstatic int free_eq(struct adapter *, struct sge_eq *);
178249259Sdimstatic int alloc_wrq(struct adapter *, struct port_info *, struct sge_wrq *,
179249259Sdim    struct sysctl_oid *);
180249259Sdimstatic int free_wrq(struct adapter *, struct sge_wrq *);
181249259Sdimstatic int alloc_txq(struct port_info *, struct sge_txq *, int,
182249259Sdim    struct sysctl_oid *);
183249259Sdimstatic int free_txq(struct port_info *, struct sge_txq *);
184249259Sdimstatic void oneseg_dma_callback(void *, bus_dma_segment_t *, int, int);
185249259Sdimstatic inline bool is_new_response(const struct sge_iq *, struct rsp_ctrl **);
186249259Sdimstatic inline void iq_next(struct sge_iq *);
187249259Sdimstatic inline void ring_fl_db(struct adapter *, struct sge_fl *);
188249259Sdimstatic int refill_fl(struct adapter *, struct sge_fl *, int);
189249259Sdimstatic void refill_sfl(void *);
190249259Sdimstatic int alloc_fl_sdesc(struct sge_fl *);
191249259Sdimstatic void free_fl_sdesc(struct adapter *, struct sge_fl *);
192249259Sdimstatic void set_fl_tag_idx(struct adapter *, struct sge_fl *, int);
193249259Sdimstatic void add_fl_to_sfl(struct adapter *, struct sge_fl *);
194249259Sdim
195249259Sdimstatic int get_pkt_sgl(struct sge_txq *, struct mbuf **, struct sgl *, int);
196249259Sdimstatic int free_pkt_sgl(struct sge_txq *, struct sgl *);
197249259Sdimstatic int write_txpkt_wr(struct port_info *, struct sge_txq *, struct mbuf *,
198249259Sdim    struct sgl *);
199249259Sdimstatic int add_to_txpkts(struct port_info *, struct sge_txq *, struct txpkts *,
200249259Sdim    struct mbuf *, struct sgl *);
201249259Sdimstatic void write_txpkts_wr(struct sge_txq *, struct txpkts *);
202249259Sdimstatic inline void write_ulp_cpl_sgl(struct port_info *, struct sge_txq *,
203249259Sdim    struct txpkts *, struct mbuf *, struct sgl *);
204249259Sdimstatic int write_sgl_to_txd(struct sge_eq *, struct sgl *, caddr_t *);
205249259Sdimstatic inline void copy_to_txd(struct sge_eq *, caddr_t, caddr_t *, int);
206249259Sdimstatic inline void ring_eq_db(struct adapter *, struct sge_eq *);
207249259Sdimstatic inline int reclaimable(struct sge_eq *);
208249259Sdimstatic int reclaim_tx_descs(struct sge_txq *, int, int);
209249259Sdimstatic void write_eqflush_wr(struct sge_eq *);
210249259Sdimstatic __be64 get_flit(bus_dma_segment_t *, int, int);
211249259Sdimstatic int handle_sge_egr_update(struct sge_iq *, const struct rss_header *,
212249259Sdim    struct mbuf *);
213249259Sdimstatic int handle_fw_msg(struct sge_iq *, const struct rss_header *,
214249259Sdim    struct mbuf *);
215249259Sdim
216249259Sdimstatic int sysctl_uint16(SYSCTL_HANDLER_ARGS);
217249259Sdim
218249259Sdim#if defined(__i386__) || defined(__amd64__)
219249259Sdimextern u_int cpu_clflush_line_size;
220249259Sdim#endif
221249259Sdim
222249259Sdim/*
223249259Sdim * Called on MOD_LOAD.  Validates and calculates the SGE tunables.
224249259Sdim */
225249259Sdimvoid
226249259Sdimt4_sge_modload(void)
227249259Sdim{
228249259Sdim	int pad;
229249259Sdim
230249259Sdim	/* set pad to a reasonable powerof2 between 16 and 4096 (inclusive) */
231249259Sdim#if defined(__i386__) || defined(__amd64__)
232249259Sdim	pad = max(cpu_clflush_line_size, 16);
233249259Sdim#else
234249259Sdim	pad = max(CACHE_LINE_SIZE, 16);
235249259Sdim#endif
236249259Sdim	pad = min(pad, 4096);
237249259Sdim
238249259Sdim	if (fl_pktshift < 0 || fl_pktshift > 7) {
239249259Sdim		printf("Invalid hw.cxgbe.fl_pktshift value (%d),"
240249259Sdim		    " using 2 instead.\n", fl_pktshift);
241249259Sdim		fl_pktshift = 2;
242249259Sdim	}
243249259Sdim
244249259Sdim	if (fl_pad != 0 &&
245249259Sdim	    (fl_pad < 32 || fl_pad > 4096 || !powerof2(fl_pad))) {
246249259Sdim
247249259Sdim		if (fl_pad != -1) {
248249259Sdim			printf("Invalid hw.cxgbe.fl_pad value (%d),"
249249259Sdim			    " using %d instead.\n", fl_pad, max(pad, 32));
250249259Sdim		}
251249259Sdim		fl_pad = max(pad, 32);
252249259Sdim	}
253249259Sdim
254249259Sdim	/*
255249259Sdim	 * T4 has the same pad and pack boundary.  If a pad boundary is set,
256249259Sdim	 * pack boundary must be set to the same value.  Otherwise take the
257249259Sdim	 * specified value or auto-calculate something reasonable.
258249259Sdim	 */
259249259Sdim	if (fl_pad)
260249259Sdim		t4_fl_pack = fl_pad;
261249259Sdim	else if (fl_pack < 32 || fl_pack > 4096 || !powerof2(fl_pack))
262249259Sdim		t4_fl_pack = max(pad, 32);
263249259Sdim	else
264249259Sdim		t4_fl_pack = fl_pack;
265249259Sdim
266249259Sdim	/* T5's pack boundary is independent of the pad boundary. */
267249259Sdim	if (fl_pack < 16 || fl_pack == 32 || fl_pack > 4096 ||
268249259Sdim	    !powerof2(fl_pack))
269249259Sdim	       t5_fl_pack = max(pad, 64);
270249259Sdim	else
271249259Sdim	       t5_fl_pack = fl_pack;
272249259Sdim
273249259Sdim	if (spg_len != 64 && spg_len != 128) {
274249259Sdim		int len;
275249259Sdim
276249259Sdim#if defined(__i386__) || defined(__amd64__)
277249259Sdim		len = cpu_clflush_line_size > 64 ? 128 : 64;
278249259Sdim#else
279249259Sdim		len = 64;
280249259Sdim#endif
281249259Sdim		if (spg_len != -1) {
282249259Sdim			printf("Invalid hw.cxgbe.spg_len value (%d),"
283249259Sdim			    " using %d instead.\n", spg_len, len);
284249259Sdim		}
285249259Sdim		spg_len = len;
286249259Sdim	}
287249259Sdim
288249259Sdim	if (cong_drop < -1 || cong_drop > 1) {
289249259Sdim		printf("Invalid hw.cxgbe.cong_drop value (%d),"
290249259Sdim		    " using 0 instead.\n", cong_drop);
291249259Sdim		cong_drop = 0;
292249259Sdim	}
293249259Sdim}
294249259Sdim
295249259Sdimvoid
296249259Sdimt4_init_sge_cpl_handlers(struct adapter *sc)
297249259Sdim{
298249259Sdim
299249259Sdim	t4_register_cpl_handler(sc, CPL_FW4_MSG, handle_fw_msg);
300249259Sdim	t4_register_cpl_handler(sc, CPL_FW6_MSG, handle_fw_msg);
301249259Sdim	t4_register_cpl_handler(sc, CPL_SGE_EGR_UPDATE, handle_sge_egr_update);
302249259Sdim	t4_register_cpl_handler(sc, CPL_RX_PKT, t4_eth_rx);
303249259Sdim	t4_register_fw_msg_handler(sc, FW6_TYPE_CMD_RPL, t4_handle_fw_rpl);
304249259Sdim}
305249259Sdim
306249259Sdim/*
307249259Sdim * adap->params.vpd.cclk must be set up before this is called.
308249259Sdim */
309249259Sdimvoid
310249259Sdimt4_tweak_chip_settings(struct adapter *sc)
311249259Sdim{
312249259Sdim	int i;
313249259Sdim	uint32_t v, m;
314249259Sdim	int intr_timer[SGE_NTIMERS] = {1, 5, 10, 50, 100, 200};
315249259Sdim	int timer_max = M_TIMERVALUE0 * 1000 / sc->params.vpd.cclk;
316249259Sdim	int intr_pktcount[SGE_NCOUNTERS] = {1, 8, 16, 32}; /* 63 max */
317249259Sdim	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
318249259Sdim	int sw_flbuf_sizes[] = {
319249259Sdim		MCLBYTES,
320249259Sdim#if MJUMPAGESIZE != MCLBYTES
321249259Sdim		MJUMPAGESIZE,
322249259Sdim#endif
323249259Sdim		MJUM9BYTES,
324249259Sdim		MJUM16BYTES,
325249259Sdim		MJUMPAGESIZE - MSIZE
326249259Sdim	};
327249259Sdim
328249259Sdim	KASSERT(sc->flags & MASTER_PF,
329249259Sdim	    ("%s: trying to change chip settings when not master.", __func__));
330249259Sdim
331249259Sdim	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE | F_EGRSTATUSPAGESIZE;
332249259Sdim	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
333249259Sdim	    V_EGRSTATUSPAGESIZE(spg_len == 128);
334249259Sdim	if (is_t4(sc) && (fl_pad || buffer_packing)) {
335249259Sdim		/* t4_fl_pack has the correct value even when fl_pad = 0 */
336249259Sdim		m |= V_INGPADBOUNDARY(M_INGPADBOUNDARY);
337249259Sdim		v |= V_INGPADBOUNDARY(ilog2(t4_fl_pack) - 5);
338249259Sdim	} else if (is_t5(sc) && fl_pad) {
339249259Sdim		m |= V_INGPADBOUNDARY(M_INGPADBOUNDARY);
340249259Sdim		v |= V_INGPADBOUNDARY(ilog2(fl_pad) - 5);
341249259Sdim	}
342249259Sdim	t4_set_reg_field(sc, A_SGE_CONTROL, m, v);
343249259Sdim
344249259Sdim	if (is_t5(sc) && buffer_packing) {
345249259Sdim		m = V_INGPACKBOUNDARY(M_INGPACKBOUNDARY);
346249259Sdim		if (t5_fl_pack == 16)
347249259Sdim			v = V_INGPACKBOUNDARY(0);
348249259Sdim		else
349249259Sdim			v = V_INGPACKBOUNDARY(ilog2(t5_fl_pack) - 5);
350249259Sdim		t4_set_reg_field(sc, A_SGE_CONTROL2, m, v);
351249259Sdim	}
352249259Sdim
353249259Sdim	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
354249259Sdim	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
355249259Sdim	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
356249259Sdim	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
357249259Sdim	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
358249259Sdim	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
359249259Sdim	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
360249259Sdim	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
361249259Sdim	t4_write_reg(sc, A_SGE_HOST_PAGE_SIZE, v);
362249259Sdim
363249259Sdim	for (i = 0; i < min(nitems(sw_flbuf_sizes), 16); i++) {
364249259Sdim		t4_write_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i),
365249259Sdim		    sw_flbuf_sizes[i]);
366249259Sdim	}
367249259Sdim
368249259Sdim	v = V_THRESHOLD_0(intr_pktcount[0]) | V_THRESHOLD_1(intr_pktcount[1]) |
369249259Sdim	    V_THRESHOLD_2(intr_pktcount[2]) | V_THRESHOLD_3(intr_pktcount[3]);
370249259Sdim	t4_write_reg(sc, A_SGE_INGRESS_RX_THRESHOLD, v);
371249259Sdim
372249259Sdim	KASSERT(intr_timer[0] <= timer_max,
373249259Sdim	    ("%s: not a single usable timer (%d, %d)", __func__, intr_timer[0],
374249259Sdim	    timer_max));
375249259Sdim	for (i = 1; i < nitems(intr_timer); i++) {
376249259Sdim		KASSERT(intr_timer[i] >= intr_timer[i - 1],
377249259Sdim		    ("%s: timers not listed in increasing order (%d)",
378249259Sdim		    __func__, i));
379249259Sdim
380249259Sdim		while (intr_timer[i] > timer_max) {
381249259Sdim			if (i == nitems(intr_timer) - 1) {
382249259Sdim				intr_timer[i] = timer_max;
383249259Sdim				break;
384249259Sdim			}
385249259Sdim			intr_timer[i] += intr_timer[i - 1];
386249259Sdim			intr_timer[i] /= 2;
387249259Sdim		}
388249259Sdim	}
389249259Sdim
390249259Sdim	v = V_TIMERVALUE0(us_to_core_ticks(sc, intr_timer[0])) |
391249259Sdim	    V_TIMERVALUE1(us_to_core_ticks(sc, intr_timer[1]));
392249259Sdim	t4_write_reg(sc, A_SGE_TIMER_VALUE_0_AND_1, v);
393249259Sdim	v = V_TIMERVALUE2(us_to_core_ticks(sc, intr_timer[2])) |
394249259Sdim	    V_TIMERVALUE3(us_to_core_ticks(sc, intr_timer[3]));
395249259Sdim	t4_write_reg(sc, A_SGE_TIMER_VALUE_2_AND_3, v);
396249259Sdim	v = V_TIMERVALUE4(us_to_core_ticks(sc, intr_timer[4])) |
397249259Sdim	    V_TIMERVALUE5(us_to_core_ticks(sc, intr_timer[5]));
398249259Sdim	t4_write_reg(sc, A_SGE_TIMER_VALUE_4_AND_5, v);
399249259Sdim
400249259Sdim	if (cong_drop == 0) {
401249259Sdim		m = F_TUNNELCNGDROP0 | F_TUNNELCNGDROP1 | F_TUNNELCNGDROP2 |
402249259Sdim		    F_TUNNELCNGDROP3;
403249259Sdim		t4_set_reg_field(sc, A_TP_PARA_REG3, m, 0);
404249259Sdim	}
405249259Sdim
406249259Sdim	/* 4K, 16K, 64K, 256K DDP "page sizes" */
407249259Sdim	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
408249259Sdim	t4_write_reg(sc, A_ULP_RX_TDDP_PSZ, v);
409249259Sdim
410249259Sdim	m = v = F_TDDPTAGTCB;
411249259Sdim	t4_set_reg_field(sc, A_ULP_RX_CTL, m, v);
412249259Sdim
413249259Sdim	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
414249259Sdim	    F_RESETDDPOFFSET;
415249259Sdim	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
416249259Sdim	t4_set_reg_field(sc, A_TP_PARA_REG5, m, v);
417249259Sdim}
418249259Sdim
419249259Sdim/*
420249259Sdim * XXX: driver really should be able to deal with unexpected settings.
421249259Sdim */
422249259Sdimint
423249259Sdimt4_read_chip_settings(struct adapter *sc)
424249259Sdim{
425249259Sdim	struct sge *s = &sc->sge;
426249259Sdim	int i, j, n, rc = 0;
427249259Sdim	uint32_t m, v, r;
428249259Sdim	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
429249259Sdim	uint32_t sge_flbuf_sizes[16], sw_flbuf_sizes[] = {
430249259Sdim		MCLBYTES,
431249259Sdim#if MJUMPAGESIZE != MCLBYTES
432249259Sdim		MJUMPAGESIZE,
433249259Sdim#endif
434249259Sdim		MJUM9BYTES,
435249259Sdim		MJUM16BYTES
436249259Sdim	};
437249259Sdim
438249259Sdim	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE | F_EGRSTATUSPAGESIZE;
439249259Sdim	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
440249259Sdim	    V_EGRSTATUSPAGESIZE(spg_len == 128);
441249259Sdim	if (is_t4(sc) && (fl_pad || buffer_packing)) {
442249259Sdim		m |= V_INGPADBOUNDARY(M_INGPADBOUNDARY);
443249259Sdim		v |= V_INGPADBOUNDARY(ilog2(t4_fl_pack) - 5);
444249259Sdim	} else if (is_t5(sc) && fl_pad) {
445249259Sdim		m |= V_INGPADBOUNDARY(M_INGPADBOUNDARY);
446249259Sdim		v |= V_INGPADBOUNDARY(ilog2(fl_pad) - 5);
447249259Sdim	}
448249259Sdim	r = t4_read_reg(sc, A_SGE_CONTROL);
449249259Sdim	if ((r & m) != v) {
450249259Sdim		device_printf(sc->dev, "invalid SGE_CONTROL(0x%x)\n", r);
451249259Sdim		rc = EINVAL;
452249259Sdim	}
453249259Sdim
454249259Sdim	if (is_t5(sc) && buffer_packing) {
455249259Sdim		m = V_INGPACKBOUNDARY(M_INGPACKBOUNDARY);
456249259Sdim		if (t5_fl_pack == 16)
457249259Sdim			v = V_INGPACKBOUNDARY(0);
458249259Sdim		else
459249259Sdim			v = V_INGPACKBOUNDARY(ilog2(t5_fl_pack) - 5);
460249259Sdim		r = t4_read_reg(sc, A_SGE_CONTROL2);
461249259Sdim		if ((r & m) != v) {
462249259Sdim			device_printf(sc->dev,
463249259Sdim			    "invalid SGE_CONTROL2(0x%x)\n", r);
464249259Sdim			rc = EINVAL;
465249259Sdim		}
466249259Sdim	}
467249259Sdim
468249259Sdim	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
469249259Sdim	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
470249259Sdim	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
471249259Sdim	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
472249259Sdim	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
473249259Sdim	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
474249259Sdim	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
475249259Sdim	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
476249259Sdim	r = t4_read_reg(sc, A_SGE_HOST_PAGE_SIZE);
477249259Sdim	if (r != v) {
478249259Sdim		device_printf(sc->dev, "invalid SGE_HOST_PAGE_SIZE(0x%x)\n", r);
479		rc = EINVAL;
480	}
481
482	/*
483	 * Make a list of SGE FL buffer sizes programmed in the chip and tally
484	 * it with the FL buffer sizes that we'd like to use.
485	 */
486	n = 0;
487	for (i = 0; i < nitems(sge_flbuf_sizes); i++) {
488		r = t4_read_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i));
489		sge_flbuf_sizes[i] = r;
490		if (r == MJUMPAGESIZE - MSIZE &&
491		    (sc->flags & BUF_PACKING_OK) == 0) {
492			sc->flags |= BUF_PACKING_OK;
493			FL_BUF_HWTAG(sc, n) = i;
494			FL_BUF_SIZE(sc, n) = MJUMPAGESIZE - MSIZE;
495			FL_BUF_TYPE(sc, n) = m_gettype(MJUMPAGESIZE);
496			FL_BUF_ZONE(sc, n) = m_getzone(MJUMPAGESIZE);
497			n++;
498		}
499	}
500	for (i = 0; i < nitems(sw_flbuf_sizes); i++) {
501		for (j = 0; j < nitems(sge_flbuf_sizes); j++) {
502			if (sw_flbuf_sizes[i] != sge_flbuf_sizes[j])
503				continue;
504			FL_BUF_HWTAG(sc, n) = j;
505			FL_BUF_SIZE(sc, n) = sw_flbuf_sizes[i];
506			FL_BUF_TYPE(sc, n) = m_gettype(sw_flbuf_sizes[i]);
507			FL_BUF_ZONE(sc, n) = m_getzone(sw_flbuf_sizes[i]);
508			n++;
509			break;
510		}
511	}
512	if (n == 0) {
513		device_printf(sc->dev, "no usable SGE FL buffer size.\n");
514		rc = EINVAL;
515	} else if (n == 1 && (sc->flags & BUF_PACKING_OK)) {
516		device_printf(sc->dev,
517		    "no usable SGE FL buffer size when not packing buffers.\n");
518		rc = EINVAL;
519	}
520	FL_BUF_SIZES(sc) = n;
521
522	r = t4_read_reg(sc, A_SGE_INGRESS_RX_THRESHOLD);
523	s->counter_val[0] = G_THRESHOLD_0(r);
524	s->counter_val[1] = G_THRESHOLD_1(r);
525	s->counter_val[2] = G_THRESHOLD_2(r);
526	s->counter_val[3] = G_THRESHOLD_3(r);
527
528	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_0_AND_1);
529	s->timer_val[0] = G_TIMERVALUE0(r) / core_ticks_per_usec(sc);
530	s->timer_val[1] = G_TIMERVALUE1(r) / core_ticks_per_usec(sc);
531	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_2_AND_3);
532	s->timer_val[2] = G_TIMERVALUE2(r) / core_ticks_per_usec(sc);
533	s->timer_val[3] = G_TIMERVALUE3(r) / core_ticks_per_usec(sc);
534	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_4_AND_5);
535	s->timer_val[4] = G_TIMERVALUE4(r) / core_ticks_per_usec(sc);
536	s->timer_val[5] = G_TIMERVALUE5(r) / core_ticks_per_usec(sc);
537
538	if (cong_drop == 0) {
539		m = F_TUNNELCNGDROP0 | F_TUNNELCNGDROP1 | F_TUNNELCNGDROP2 |
540		    F_TUNNELCNGDROP3;
541		r = t4_read_reg(sc, A_TP_PARA_REG3);
542		if (r & m) {
543			device_printf(sc->dev,
544			    "invalid TP_PARA_REG3(0x%x)\n", r);
545			rc = EINVAL;
546		}
547	}
548
549	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
550	r = t4_read_reg(sc, A_ULP_RX_TDDP_PSZ);
551	if (r != v) {
552		device_printf(sc->dev, "invalid ULP_RX_TDDP_PSZ(0x%x)\n", r);
553		rc = EINVAL;
554	}
555
556	m = v = F_TDDPTAGTCB;
557	r = t4_read_reg(sc, A_ULP_RX_CTL);
558	if ((r & m) != v) {
559		device_printf(sc->dev, "invalid ULP_RX_CTL(0x%x)\n", r);
560		rc = EINVAL;
561	}
562
563	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
564	    F_RESETDDPOFFSET;
565	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
566	r = t4_read_reg(sc, A_TP_PARA_REG5);
567	if ((r & m) != v) {
568		device_printf(sc->dev, "invalid TP_PARA_REG5(0x%x)\n", r);
569		rc = EINVAL;
570	}
571
572	r = t4_read_reg(sc, A_SGE_CONM_CTRL);
573	s->fl_starve_threshold = G_EGRTHRESHOLD(r) * 2 + 1;
574
575	if (is_t5(sc)) {
576		r = t4_read_reg(sc, A_SGE_EGRESS_QUEUES_PER_PAGE_PF);
577		r >>= S_QUEUESPERPAGEPF0 +
578		    (S_QUEUESPERPAGEPF1 - S_QUEUESPERPAGEPF0) * sc->pf;
579		s->s_qpp = r & M_QUEUESPERPAGEPF0;
580	}
581
582	t4_init_tp_params(sc);
583
584	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
585	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
586
587	return (rc);
588}
589
590int
591t4_create_dma_tag(struct adapter *sc)
592{
593	int rc;
594
595	rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), 1, 0,
596	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE,
597	    BUS_SPACE_UNRESTRICTED, BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL,
598	    NULL, &sc->dmat);
599	if (rc != 0) {
600		device_printf(sc->dev,
601		    "failed to create main DMA tag: %d\n", rc);
602	}
603
604	return (rc);
605}
606
607void
608t4_sge_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
609    struct sysctl_oid_list *children)
610{
611
612	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "fl_pktshift", CTLFLAG_RD,
613	    NULL, fl_pktshift, "payload DMA offset in rx buffer (bytes)");
614
615	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "fl_pad", CTLFLAG_RD,
616	    NULL, fl_pad, "payload pad boundary (bytes)");
617
618	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "spg_len", CTLFLAG_RD,
619	    NULL, spg_len, "status page size (bytes)");
620
621	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_drop", CTLFLAG_RD,
622	    NULL, cong_drop, "congestion drop setting");
623
624	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "buffer_packing", CTLFLAG_RD,
625	    NULL, sc->flags & BUF_PACKING_OK ? 1 : 0,
626	    "pack multiple frames in one fl buffer");
627
628	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "fl_pack", CTLFLAG_RD,
629	    NULL, is_t5(sc) ? t5_fl_pack : t4_fl_pack,
630	    "payload pack boundary (bytes)");
631}
632
633int
634t4_destroy_dma_tag(struct adapter *sc)
635{
636	if (sc->dmat)
637		bus_dma_tag_destroy(sc->dmat);
638
639	return (0);
640}
641
642/*
643 * Allocate and initialize the firmware event queue and the management queue.
644 *
645 * Returns errno on failure.  Resources allocated up to that point may still be
646 * allocated.  Caller is responsible for cleanup in case this function fails.
647 */
648int
649t4_setup_adapter_queues(struct adapter *sc)
650{
651	int rc;
652
653	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
654
655	sysctl_ctx_init(&sc->ctx);
656	sc->flags |= ADAP_SYSCTL_CTX;
657
658	/*
659	 * Firmware event queue
660	 */
661	rc = alloc_fwq(sc);
662	if (rc != 0)
663		return (rc);
664
665	/*
666	 * Management queue.  This is just a control queue that uses the fwq as
667	 * its associated iq.
668	 */
669	rc = alloc_mgmtq(sc);
670
671	return (rc);
672}
673
674/*
675 * Idempotent
676 */
677int
678t4_teardown_adapter_queues(struct adapter *sc)
679{
680
681	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
682
683	/* Do this before freeing the queue */
684	if (sc->flags & ADAP_SYSCTL_CTX) {
685		sysctl_ctx_free(&sc->ctx);
686		sc->flags &= ~ADAP_SYSCTL_CTX;
687	}
688
689	free_mgmtq(sc);
690	free_fwq(sc);
691
692	return (0);
693}
694
695static inline int
696first_vector(struct port_info *pi)
697{
698	struct adapter *sc = pi->adapter;
699	int rc = T4_EXTRA_INTR, i;
700
701	if (sc->intr_count == 1)
702		return (0);
703
704	for_each_port(sc, i) {
705		struct port_info *p = sc->port[i];
706
707		if (i == pi->port_id)
708			break;
709
710#ifdef TCP_OFFLOAD
711		if (sc->flags & INTR_DIRECT)
712			rc += p->nrxq + p->nofldrxq;
713		else
714			rc += max(p->nrxq, p->nofldrxq);
715#else
716		/*
717		 * Not compiled with offload support and intr_count > 1.  Only
718		 * NIC queues exist and they'd better be taking direct
719		 * interrupts.
720		 */
721		KASSERT(sc->flags & INTR_DIRECT,
722		    ("%s: intr_count %d, !INTR_DIRECT", __func__,
723		    sc->intr_count));
724
725		rc += p->nrxq;
726#endif
727	}
728
729	return (rc);
730}
731
732/*
733 * Given an arbitrary "index," come up with an iq that can be used by other
734 * queues (of this port) for interrupt forwarding, SGE egress updates, etc.
735 * The iq returned is guaranteed to be something that takes direct interrupts.
736 */
737static struct sge_iq *
738port_intr_iq(struct port_info *pi, int idx)
739{
740	struct adapter *sc = pi->adapter;
741	struct sge *s = &sc->sge;
742	struct sge_iq *iq = NULL;
743
744	if (sc->intr_count == 1)
745		return (&sc->sge.fwq);
746
747#ifdef TCP_OFFLOAD
748	if (sc->flags & INTR_DIRECT) {
749		idx %= pi->nrxq + pi->nofldrxq;
750
751		if (idx >= pi->nrxq) {
752			idx -= pi->nrxq;
753			iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
754		} else
755			iq = &s->rxq[pi->first_rxq + idx].iq;
756
757	} else {
758		idx %= max(pi->nrxq, pi->nofldrxq);
759
760		if (pi->nrxq >= pi->nofldrxq)
761			iq = &s->rxq[pi->first_rxq + idx].iq;
762		else
763			iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
764	}
765#else
766	/*
767	 * Not compiled with offload support and intr_count > 1.  Only NIC
768	 * queues exist and they'd better be taking direct interrupts.
769	 */
770	KASSERT(sc->flags & INTR_DIRECT,
771	    ("%s: intr_count %d, !INTR_DIRECT", __func__, sc->intr_count));
772
773	idx %= pi->nrxq;
774	iq = &s->rxq[pi->first_rxq + idx].iq;
775#endif
776
777	KASSERT(iq->flags & IQ_INTR, ("%s: EDOOFUS", __func__));
778	return (iq);
779}
780
781static inline int
782mtu_to_bufsize(int mtu)
783{
784	int bufsize;
785
786	/* large enough for a frame even when VLAN extraction is disabled */
787	bufsize = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN + mtu;
788	bufsize = roundup2(bufsize + fl_pktshift, fl_pad);
789
790	return (bufsize);
791}
792
793#ifdef TCP_OFFLOAD
794static inline int
795mtu_to_bufsize_toe(struct adapter *sc, int mtu)
796{
797
798	if (sc->tt.rx_coalesce)
799		return (G_RXCOALESCESIZE(t4_read_reg(sc, A_TP_PARA_REG2)));
800
801	return (mtu);
802}
803#endif
804
805int
806t4_setup_port_queues(struct port_info *pi)
807{
808	int rc = 0, i, j, intr_idx, iqid;
809	struct sge_rxq *rxq;
810	struct sge_txq *txq;
811	struct sge_wrq *ctrlq;
812#ifdef TCP_OFFLOAD
813	struct sge_ofld_rxq *ofld_rxq;
814	struct sge_wrq *ofld_txq;
815	struct sysctl_oid *oid2 = NULL;
816#endif
817	char name[16];
818	struct adapter *sc = pi->adapter;
819	struct ifnet *ifp = pi->ifp;
820	struct sysctl_oid *oid = device_get_sysctl_tree(pi->dev);
821	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
822	int bufsize, pack;
823
824	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "rxq", CTLFLAG_RD,
825	    NULL, "rx queues");
826
827#ifdef TCP_OFFLOAD
828	if (is_offload(sc)) {
829		oid2 = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_rxq",
830		    CTLFLAG_RD, NULL,
831		    "rx queues for offloaded TCP connections");
832	}
833#endif
834
835	/* Interrupt vector to start from (when using multiple vectors) */
836	intr_idx = first_vector(pi);
837
838	/*
839	 * First pass over all rx queues (NIC and TOE):
840	 * a) initialize iq and fl
841	 * b) allocate queue iff it will take direct interrupts.
842	 */
843	bufsize = mtu_to_bufsize(ifp->if_mtu);
844	if (sc->flags & BUF_PACKING_OK &&
845	    ((is_t5(sc) && buffer_packing) ||	/* 1 or -1 both ok for T5 */
846	    (is_t4(sc) && buffer_packing == 1)))
847		pack = 1;
848	else
849		pack = 0;
850	for_each_rxq(pi, i, rxq) {
851
852		init_iq(&rxq->iq, sc, pi->tmr_idx, pi->pktc_idx, pi->qsize_rxq,
853		    RX_IQ_ESIZE);
854
855		snprintf(name, sizeof(name), "%s rxq%d-fl",
856		    device_get_nameunit(pi->dev), i);
857		init_fl(sc, &rxq->fl, pi->qsize_rxq / 8, bufsize, pack, name);
858
859		if (sc->flags & INTR_DIRECT
860#ifdef TCP_OFFLOAD
861		    || (sc->intr_count > 1 && pi->nrxq >= pi->nofldrxq)
862#endif
863		   ) {
864			rxq->iq.flags |= IQ_INTR;
865			rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
866			if (rc != 0)
867				goto done;
868			intr_idx++;
869		}
870	}
871
872#ifdef TCP_OFFLOAD
873	bufsize = mtu_to_bufsize_toe(sc, ifp->if_mtu);
874	pack = 0;	/* XXX: think about this some more */
875	for_each_ofld_rxq(pi, i, ofld_rxq) {
876
877		init_iq(&ofld_rxq->iq, sc, pi->tmr_idx, pi->pktc_idx,
878		    pi->qsize_rxq, RX_IQ_ESIZE);
879
880		snprintf(name, sizeof(name), "%s ofld_rxq%d-fl",
881		    device_get_nameunit(pi->dev), i);
882		init_fl(sc, &ofld_rxq->fl, pi->qsize_rxq / 8, bufsize, pack,
883		    name);
884
885		if (sc->flags & INTR_DIRECT ||
886		    (sc->intr_count > 1 && pi->nofldrxq > pi->nrxq)) {
887			ofld_rxq->iq.flags |= IQ_INTR;
888			rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
889			if (rc != 0)
890				goto done;
891			intr_idx++;
892		}
893	}
894#endif
895
896	/*
897	 * Second pass over all rx queues (NIC and TOE).  The queues forwarding
898	 * their interrupts are allocated now.
899	 */
900	j = 0;
901	for_each_rxq(pi, i, rxq) {
902		if (rxq->iq.flags & IQ_INTR)
903			continue;
904
905		intr_idx = port_intr_iq(pi, j)->abs_id;
906
907		rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
908		if (rc != 0)
909			goto done;
910		j++;
911	}
912
913#ifdef TCP_OFFLOAD
914	for_each_ofld_rxq(pi, i, ofld_rxq) {
915		if (ofld_rxq->iq.flags & IQ_INTR)
916			continue;
917
918		intr_idx = port_intr_iq(pi, j)->abs_id;
919
920		rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
921		if (rc != 0)
922			goto done;
923		j++;
924	}
925#endif
926
927	/*
928	 * Now the tx queues.  Only one pass needed.
929	 */
930	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "txq", CTLFLAG_RD,
931	    NULL, "tx queues");
932	j = 0;
933	for_each_txq(pi, i, txq) {
934		uint16_t iqid;
935
936		iqid = port_intr_iq(pi, j)->cntxt_id;
937
938		snprintf(name, sizeof(name), "%s txq%d",
939		    device_get_nameunit(pi->dev), i);
940		init_eq(&txq->eq, EQ_ETH, pi->qsize_txq, pi->tx_chan, iqid,
941		    name);
942
943		rc = alloc_txq(pi, txq, i, oid);
944		if (rc != 0)
945			goto done;
946		j++;
947	}
948
949#ifdef TCP_OFFLOAD
950	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_txq",
951	    CTLFLAG_RD, NULL, "tx queues for offloaded TCP connections");
952	for_each_ofld_txq(pi, i, ofld_txq) {
953		uint16_t iqid;
954
955		iqid = port_intr_iq(pi, j)->cntxt_id;
956
957		snprintf(name, sizeof(name), "%s ofld_txq%d",
958		    device_get_nameunit(pi->dev), i);
959		init_eq(&ofld_txq->eq, EQ_OFLD, pi->qsize_txq, pi->tx_chan,
960		    iqid, name);
961
962		snprintf(name, sizeof(name), "%d", i);
963		oid2 = SYSCTL_ADD_NODE(&pi->ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
964		    name, CTLFLAG_RD, NULL, "offload tx queue");
965
966		rc = alloc_wrq(sc, pi, ofld_txq, oid2);
967		if (rc != 0)
968			goto done;
969		j++;
970	}
971#endif
972
973	/*
974	 * Finally, the control queue.
975	 */
976	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ctrlq", CTLFLAG_RD,
977	    NULL, "ctrl queue");
978	ctrlq = &sc->sge.ctrlq[pi->port_id];
979	iqid = port_intr_iq(pi, 0)->cntxt_id;
980	snprintf(name, sizeof(name), "%s ctrlq", device_get_nameunit(pi->dev));
981	init_eq(&ctrlq->eq, EQ_CTRL, CTRL_EQ_QSIZE, pi->tx_chan, iqid, name);
982	rc = alloc_wrq(sc, pi, ctrlq, oid);
983
984done:
985	if (rc)
986		t4_teardown_port_queues(pi);
987
988	return (rc);
989}
990
991/*
992 * Idempotent
993 */
994int
995t4_teardown_port_queues(struct port_info *pi)
996{
997	int i;
998	struct adapter *sc = pi->adapter;
999	struct sge_rxq *rxq;
1000	struct sge_txq *txq;
1001#ifdef TCP_OFFLOAD
1002	struct sge_ofld_rxq *ofld_rxq;
1003	struct sge_wrq *ofld_txq;
1004#endif
1005
1006	/* Do this before freeing the queues */
1007	if (pi->flags & PORT_SYSCTL_CTX) {
1008		sysctl_ctx_free(&pi->ctx);
1009		pi->flags &= ~PORT_SYSCTL_CTX;
1010	}
1011
1012	/*
1013	 * Take down all the tx queues first, as they reference the rx queues
1014	 * (for egress updates, etc.).
1015	 */
1016
1017	free_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
1018
1019	for_each_txq(pi, i, txq) {
1020		free_txq(pi, txq);
1021	}
1022
1023#ifdef TCP_OFFLOAD
1024	for_each_ofld_txq(pi, i, ofld_txq) {
1025		free_wrq(sc, ofld_txq);
1026	}
1027#endif
1028
1029	/*
1030	 * Then take down the rx queues that forward their interrupts, as they
1031	 * reference other rx queues.
1032	 */
1033
1034	for_each_rxq(pi, i, rxq) {
1035		if ((rxq->iq.flags & IQ_INTR) == 0)
1036			free_rxq(pi, rxq);
1037	}
1038
1039#ifdef TCP_OFFLOAD
1040	for_each_ofld_rxq(pi, i, ofld_rxq) {
1041		if ((ofld_rxq->iq.flags & IQ_INTR) == 0)
1042			free_ofld_rxq(pi, ofld_rxq);
1043	}
1044#endif
1045
1046	/*
1047	 * Then take down the rx queues that take direct interrupts.
1048	 */
1049
1050	for_each_rxq(pi, i, rxq) {
1051		if (rxq->iq.flags & IQ_INTR)
1052			free_rxq(pi, rxq);
1053	}
1054
1055#ifdef TCP_OFFLOAD
1056	for_each_ofld_rxq(pi, i, ofld_rxq) {
1057		if (ofld_rxq->iq.flags & IQ_INTR)
1058			free_ofld_rxq(pi, ofld_rxq);
1059	}
1060#endif
1061
1062	return (0);
1063}
1064
1065/*
1066 * Deals with errors and the firmware event queue.  All data rx queues forward
1067 * their interrupt to the firmware event queue.
1068 */
1069void
1070t4_intr_all(void *arg)
1071{
1072	struct adapter *sc = arg;
1073	struct sge_iq *fwq = &sc->sge.fwq;
1074
1075	t4_intr_err(arg);
1076	if (atomic_cmpset_int(&fwq->state, IQS_IDLE, IQS_BUSY)) {
1077		service_iq(fwq, 0);
1078		atomic_cmpset_int(&fwq->state, IQS_BUSY, IQS_IDLE);
1079	}
1080}
1081
1082/* Deals with error interrupts */
1083void
1084t4_intr_err(void *arg)
1085{
1086	struct adapter *sc = arg;
1087
1088	t4_write_reg(sc, MYPF_REG(A_PCIE_PF_CLI), 0);
1089	t4_slow_intr_handler(sc);
1090}
1091
1092void
1093t4_intr_evt(void *arg)
1094{
1095	struct sge_iq *iq = arg;
1096
1097	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
1098		service_iq(iq, 0);
1099		atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
1100	}
1101}
1102
1103void
1104t4_intr(void *arg)
1105{
1106	struct sge_iq *iq = arg;
1107
1108	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
1109		service_iq(iq, 0);
1110		atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
1111	}
1112}
1113
1114/*
1115 * Deals with anything and everything on the given ingress queue.
1116 */
1117static int
1118service_iq(struct sge_iq *iq, int budget)
1119{
1120	struct sge_iq *q;
1121	struct sge_rxq *rxq = iq_to_rxq(iq);	/* Use iff iq is part of rxq */
1122	struct sge_fl *fl = &rxq->fl;		/* Use iff IQ_HAS_FL */
1123	struct adapter *sc = iq->adapter;
1124	struct rsp_ctrl *ctrl;
1125	const struct rss_header *rss;
1126	int ndescs = 0, limit, fl_bufs_used = 0;
1127	int rsp_type;
1128	uint32_t lq;
1129	struct mbuf *m0;
1130	STAILQ_HEAD(, sge_iq) iql = STAILQ_HEAD_INITIALIZER(iql);
1131#if defined(INET) || defined(INET6)
1132	const struct timeval lro_timeout = {0, sc->lro_timeout};
1133#endif
1134
1135	limit = budget ? budget : iq->qsize / 8;
1136
1137	KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
1138
1139	/*
1140	 * We always come back and check the descriptor ring for new indirect
1141	 * interrupts and other responses after running a single handler.
1142	 */
1143	for (;;) {
1144		while (is_new_response(iq, &ctrl)) {
1145
1146			rmb();
1147
1148			m0 = NULL;
1149			rsp_type = G_RSPD_TYPE(ctrl->u.type_gen);
1150			lq = be32toh(ctrl->pldbuflen_qid);
1151			rss = (const void *)iq->cdesc;
1152
1153			switch (rsp_type) {
1154			case X_RSPD_TYPE_FLBUF:
1155
1156				KASSERT(iq->flags & IQ_HAS_FL,
1157				    ("%s: data for an iq (%p) with no freelist",
1158				    __func__, iq));
1159
1160				m0 = fl->flags & FL_BUF_PACKING ?
1161				    get_fl_payload1(sc, fl, lq, &fl_bufs_used) :
1162				    get_fl_payload2(sc, fl, lq, &fl_bufs_used);
1163
1164				if (__predict_false(m0 == NULL))
1165					goto process_iql;
1166#ifdef T4_PKT_TIMESTAMP
1167				/*
1168				 * 60 bit timestamp for the payload is
1169				 * *(uint64_t *)m0->m_pktdat.  Note that it is
1170				 * in the leading free-space in the mbuf.  The
1171				 * kernel can clobber it during a pullup,
1172				 * m_copymdata, etc.  You need to make sure that
1173				 * the mbuf reaches you unmolested if you care
1174				 * about the timestamp.
1175				 */
1176				*(uint64_t *)m0->m_pktdat =
1177				    be64toh(ctrl->u.last_flit) &
1178				    0xfffffffffffffff;
1179#endif
1180
1181				/* fall through */
1182
1183			case X_RSPD_TYPE_CPL:
1184				KASSERT(rss->opcode < NUM_CPL_CMDS,
1185				    ("%s: bad opcode %02x.", __func__,
1186				    rss->opcode));
1187				sc->cpl_handler[rss->opcode](iq, rss, m0);
1188				break;
1189
1190			case X_RSPD_TYPE_INTR:
1191
1192				/*
1193				 * Interrupts should be forwarded only to queues
1194				 * that are not forwarding their interrupts.
1195				 * This means service_iq can recurse but only 1
1196				 * level deep.
1197				 */
1198				KASSERT(budget == 0,
1199				    ("%s: budget %u, rsp_type %u", __func__,
1200				    budget, rsp_type));
1201
1202				/*
1203				 * There are 1K interrupt-capable queues (qids 0
1204				 * through 1023).  A response type indicating a
1205				 * forwarded interrupt with a qid >= 1K is an
1206				 * iWARP async notification.
1207				 */
1208				if (lq >= 1024) {
1209                                        sc->an_handler(iq, ctrl);
1210                                        break;
1211                                }
1212
1213				q = sc->sge.iqmap[lq - sc->sge.iq_start];
1214				if (atomic_cmpset_int(&q->state, IQS_IDLE,
1215				    IQS_BUSY)) {
1216					if (service_iq(q, q->qsize / 8) == 0) {
1217						atomic_cmpset_int(&q->state,
1218						    IQS_BUSY, IQS_IDLE);
1219					} else {
1220						STAILQ_INSERT_TAIL(&iql, q,
1221						    link);
1222					}
1223				}
1224				break;
1225
1226			default:
1227				KASSERT(0,
1228				    ("%s: illegal response type %d on iq %p",
1229				    __func__, rsp_type, iq));
1230				log(LOG_ERR,
1231				    "%s: illegal response type %d on iq %p",
1232				    device_get_nameunit(sc->dev), rsp_type, iq);
1233				break;
1234			}
1235
1236			iq_next(iq);
1237			if (++ndescs == limit) {
1238				t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS),
1239				    V_CIDXINC(ndescs) |
1240				    V_INGRESSQID(iq->cntxt_id) |
1241				    V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));
1242				ndescs = 0;
1243
1244#if defined(INET) || defined(INET6)
1245				if (iq->flags & IQ_LRO_ENABLED &&
1246				    sc->lro_timeout != 0) {
1247					tcp_lro_flush_inactive(&rxq->lro,
1248					    &lro_timeout);
1249				}
1250#endif
1251
1252				if (fl_bufs_used > 0) {
1253					FL_LOCK(fl);
1254					fl->needed += fl_bufs_used;
1255					refill_fl(sc, fl, fl->cap / 8);
1256					FL_UNLOCK(fl);
1257					fl_bufs_used = 0;
1258				}
1259
1260				if (budget)
1261					return (EINPROGRESS);
1262			}
1263		}
1264
1265process_iql:
1266		if (STAILQ_EMPTY(&iql))
1267			break;
1268
1269		/*
1270		 * Process the head only, and send it to the back of the list if
1271		 * it's still not done.
1272		 */
1273		q = STAILQ_FIRST(&iql);
1274		STAILQ_REMOVE_HEAD(&iql, link);
1275		if (service_iq(q, q->qsize / 8) == 0)
1276			atomic_cmpset_int(&q->state, IQS_BUSY, IQS_IDLE);
1277		else
1278			STAILQ_INSERT_TAIL(&iql, q, link);
1279	}
1280
1281#if defined(INET) || defined(INET6)
1282	if (iq->flags & IQ_LRO_ENABLED) {
1283		struct lro_ctrl *lro = &rxq->lro;
1284		struct lro_entry *l;
1285
1286		while (!SLIST_EMPTY(&lro->lro_active)) {
1287			l = SLIST_FIRST(&lro->lro_active);
1288			SLIST_REMOVE_HEAD(&lro->lro_active, next);
1289			tcp_lro_flush(lro, l);
1290		}
1291	}
1292#endif
1293
1294	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_CIDXINC(ndescs) |
1295	    V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));
1296
1297	if (iq->flags & IQ_HAS_FL) {
1298		int starved;
1299
1300		FL_LOCK(fl);
1301		fl->needed += fl_bufs_used;
1302		starved = refill_fl(sc, fl, fl->cap / 4);
1303		FL_UNLOCK(fl);
1304		if (__predict_false(starved != 0))
1305			add_fl_to_sfl(sc, fl);
1306	}
1307
1308	return (0);
1309}
1310
1311static int
1312fill_mbuf_stash(struct sge_fl *fl)
1313{
1314	int i;
1315
1316	for (i = 0; i < nitems(fl->mstash); i++) {
1317		if (fl->mstash[i] == NULL) {
1318			struct mbuf *m;
1319			if ((m = m_get(M_NOWAIT, MT_NOINIT)) == NULL)
1320				return (ENOBUFS);
1321			fl->mstash[i] = m;
1322		}
1323	}
1324	return (0);
1325}
1326
1327static struct mbuf *
1328get_mbuf_from_stash(struct sge_fl *fl)
1329{
1330	int i;
1331
1332	for (i = 0; i < nitems(fl->mstash); i++) {
1333		if (fl->mstash[i] != NULL) {
1334			struct mbuf *m;
1335
1336			m = fl->mstash[i];
1337			fl->mstash[i] = NULL;
1338			return (m);
1339		} else
1340			fl->mstash[i] = m_get(M_NOWAIT, MT_NOINIT);
1341	}
1342
1343	return (m_get(M_NOWAIT, MT_NOINIT));
1344}
1345
1346static void
1347return_mbuf_to_stash(struct sge_fl *fl, struct mbuf *m)
1348{
1349	int i;
1350
1351	if (m == NULL)
1352		return;
1353
1354	for (i = 0; i < nitems(fl->mstash); i++) {
1355		if (fl->mstash[i] == NULL) {
1356			fl->mstash[i] = m;
1357			return;
1358		}
1359	}
1360	m_init(m, NULL, 0, M_NOWAIT, MT_DATA, 0);
1361	m_free(m);
1362}
1363
1364/* buf can be any address within the buffer */
1365static inline u_int *
1366find_buf_refcnt(caddr_t buf)
1367{
1368	uintptr_t ptr = (uintptr_t)buf;
1369
1370	return ((u_int *)((ptr & ~(MJUMPAGESIZE - 1)) + MSIZE - sizeof(u_int)));
1371}
1372
1373static inline struct mbuf *
1374find_buf_mbuf(caddr_t buf)
1375{
1376	uintptr_t ptr = (uintptr_t)buf;
1377
1378	return ((struct mbuf *)(ptr & ~(MJUMPAGESIZE - 1)));
1379}
1380
1381static int
1382rxb_free(struct mbuf *m, void *arg1, void *arg2)
1383{
1384	uma_zone_t zone = arg1;
1385	caddr_t cl = arg2;
1386#ifdef INVARIANTS
1387	u_int refcount;
1388
1389	refcount = *find_buf_refcnt(cl);
1390	KASSERT(refcount == 0, ("%s: cl %p refcount is %u", __func__,
1391	    cl - MSIZE, refcount));
1392#endif
1393	cl -= MSIZE;
1394	uma_zfree(zone, cl);
1395
1396	return (EXT_FREE_OK);
1397}
1398
1399static struct mbuf *
1400get_fl_payload1(struct adapter *sc, struct sge_fl *fl, uint32_t len_newbuf,
1401    int *fl_bufs_used)
1402{
1403	struct mbuf *m0, *m;
1404	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
1405	unsigned int nbuf, len;
1406	int pack_boundary = is_t4(sc) ? t4_fl_pack : t5_fl_pack;
1407
1408	/*
1409	 * No assertion for the fl lock because we don't need it.  This routine
1410	 * is called only from the rx interrupt handler and it only updates
1411	 * fl->cidx.  (Contrast that with fl->pidx/fl->needed which could be
1412	 * updated in the rx interrupt handler or the starvation helper routine.
1413	 * That's why code that manipulates fl->pidx/fl->needed needs the fl
1414	 * lock but this routine does not).
1415	 */
1416
1417	KASSERT(fl->flags & FL_BUF_PACKING,
1418	    ("%s: buffer packing disabled for fl %p", __func__, fl));
1419
1420	len = G_RSPD_LEN(len_newbuf);
1421
1422	if ((len_newbuf & F_RSPD_NEWBUF) == 0) {
1423		KASSERT(fl->rx_offset > 0,
1424		    ("%s: packed frame but driver at offset=0", __func__));
1425
1426		/* A packed frame is guaranteed to fit entirely in this buf. */
1427		KASSERT(FL_BUF_SIZE(sc, sd->tag_idx) - fl->rx_offset >= len,
1428		    ("%s: packing error.  bufsz=%u, offset=%u, len=%u",
1429		    __func__, FL_BUF_SIZE(sc, sd->tag_idx), fl->rx_offset,
1430		    len));
1431
1432		m0 = get_mbuf_from_stash(fl);
1433		if (m0 == NULL ||
1434		    m_init(m0, NULL, 0, M_NOWAIT, MT_DATA, M_PKTHDR) != 0) {
1435			return_mbuf_to_stash(fl, m0);
1436			return (NULL);
1437		}
1438
1439		bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map,
1440		    BUS_DMASYNC_POSTREAD);
1441		if (len < RX_COPY_THRESHOLD) {
1442#ifdef T4_PKT_TIMESTAMP
1443			/* Leave room for a timestamp */
1444			m0->m_data += 8;
1445#endif
1446			bcopy(sd->cl + fl->rx_offset, mtod(m0, caddr_t), len);
1447			m0->m_pkthdr.len = len;
1448			m0->m_len = len;
1449		} else {
1450			m0->m_pkthdr.len = len;
1451			m0->m_len = len;
1452			m_extaddref(m0, sd->cl + fl->rx_offset,
1453			    roundup2(m0->m_len, fl_pad),
1454			    find_buf_refcnt(sd->cl), rxb_free,
1455			    FL_BUF_ZONE(sc, sd->tag_idx), sd->cl);
1456		}
1457		fl->rx_offset += len;
1458		fl->rx_offset = roundup2(fl->rx_offset, fl_pad);
1459		fl->rx_offset = roundup2(fl->rx_offset, pack_boundary);
1460		if (fl->rx_offset >= FL_BUF_SIZE(sc, sd->tag_idx)) {
1461			fl->rx_offset = 0;
1462			(*fl_bufs_used) += 1;
1463			if (__predict_false(++fl->cidx == fl->cap))
1464				fl->cidx = 0;
1465		}
1466
1467		return (m0);
1468	}
1469
1470	KASSERT(len_newbuf & F_RSPD_NEWBUF,
1471	    ("%s: only new buffer handled here", __func__));
1472
1473	nbuf = 0;
1474
1475	/*
1476	 * Move to the start of the next buffer if we are still in the middle of
1477	 * some buffer.  This is the case where there was some room left in the
1478	 * previous buffer but not enough to fit this frame in its entirety.
1479	 */
1480	if (fl->rx_offset > 0) {
1481		KASSERT(roundup2(len, fl_pad) > FL_BUF_SIZE(sc, sd->tag_idx) -
1482		    fl->rx_offset, ("%s: frame (%u bytes) should have fit at "
1483		    "cidx %u offset %u bufsize %u", __func__, len, fl->cidx,
1484		    fl->rx_offset, FL_BUF_SIZE(sc, sd->tag_idx)));
1485		nbuf++;
1486		fl->rx_offset = 0;
1487		sd++;
1488		if (__predict_false(++fl->cidx == fl->cap)) {
1489			sd = fl->sdesc;
1490			fl->cidx = 0;
1491		}
1492	}
1493
1494	m0 = find_buf_mbuf(sd->cl);
1495	if (m_init(m0, NULL, 0, M_NOWAIT, MT_DATA, M_PKTHDR | M_NOFREE))
1496		goto done;
1497	bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map, BUS_DMASYNC_POSTREAD);
1498	m0->m_len = min(len, FL_BUF_SIZE(sc, sd->tag_idx));
1499	m_extaddref(m0, sd->cl, roundup2(m0->m_len, fl_pad),
1500	    find_buf_refcnt(sd->cl), rxb_free, FL_BUF_ZONE(sc, sd->tag_idx),
1501	    sd->cl);
1502	m0->m_pkthdr.len = len;
1503
1504	fl->rx_offset = roundup2(m0->m_len, fl_pad);
1505	fl->rx_offset = roundup2(fl->rx_offset, pack_boundary);
1506	if (fl->rx_offset >= FL_BUF_SIZE(sc, sd->tag_idx)) {
1507		fl->rx_offset = 0;
1508		nbuf++;
1509		sd++;
1510		if (__predict_false(++fl->cidx == fl->cap)) {
1511			sd = fl->sdesc;
1512			fl->cidx = 0;
1513		}
1514	}
1515
1516	m = m0;
1517	len -= m->m_len;
1518
1519	while (len > 0) {
1520		m->m_next = find_buf_mbuf(sd->cl);
1521		m = m->m_next;
1522
1523		bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map,
1524		    BUS_DMASYNC_POSTREAD);
1525
1526		/* m_init for !M_PKTHDR can't fail so don't bother */
1527		m_init(m, NULL, 0, M_NOWAIT, MT_DATA, M_NOFREE);
1528		m->m_len = min(len, FL_BUF_SIZE(sc, sd->tag_idx));
1529		m_extaddref(m, sd->cl, roundup2(m->m_len, fl_pad),
1530		    find_buf_refcnt(sd->cl), rxb_free,
1531		    FL_BUF_ZONE(sc, sd->tag_idx), sd->cl);
1532
1533		fl->rx_offset = roundup2(m->m_len, fl_pad);
1534		fl->rx_offset = roundup2(fl->rx_offset, pack_boundary);
1535		if (fl->rx_offset >= FL_BUF_SIZE(sc, sd->tag_idx)) {
1536			fl->rx_offset = 0;
1537			nbuf++;
1538			sd++;
1539			if (__predict_false(++fl->cidx == fl->cap)) {
1540				sd = fl->sdesc;
1541				fl->cidx = 0;
1542			}
1543		}
1544
1545		len -= m->m_len;
1546	}
1547done:
1548	(*fl_bufs_used) += nbuf;
1549	return (m0);
1550}
1551
1552static struct mbuf *
1553get_fl_payload2(struct adapter *sc, struct sge_fl *fl, uint32_t len_newbuf,
1554    int *fl_bufs_used)
1555{
1556	struct mbuf *m0, *m;
1557	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
1558	unsigned int nbuf, len;
1559
1560	/*
1561	 * No assertion for the fl lock because we don't need it.  This routine
1562	 * is called only from the rx interrupt handler and it only updates
1563	 * fl->cidx.  (Contrast that with fl->pidx/fl->needed which could be
1564	 * updated in the rx interrupt handler or the starvation helper routine.
1565	 * That's why code that manipulates fl->pidx/fl->needed needs the fl
1566	 * lock but this routine does not).
1567	 */
1568
1569	KASSERT((fl->flags & FL_BUF_PACKING) == 0,
1570	    ("%s: buffer packing enabled for fl %p", __func__, fl));
1571	if (__predict_false((len_newbuf & F_RSPD_NEWBUF) == 0))
1572		panic("%s: cannot handle packed frames", __func__);
1573	len = G_RSPD_LEN(len_newbuf);
1574
1575	/*
1576	 * We never want to run out of mbufs in between a frame when a frame
1577	 * spans multiple fl buffers.  If the fl's mbuf stash isn't full and
1578	 * can't be filled up to the brim then fail early.
1579	 */
1580	if (len > FL_BUF_SIZE(sc, sd->tag_idx) && fill_mbuf_stash(fl) != 0)
1581		return (NULL);
1582
1583	m0 = get_mbuf_from_stash(fl);
1584	if (m0 == NULL ||
1585	    m_init(m0, NULL, 0, M_NOWAIT, MT_DATA, M_PKTHDR) != 0) {
1586		return_mbuf_to_stash(fl, m0);
1587		return (NULL);
1588	}
1589
1590	bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map, BUS_DMASYNC_POSTREAD);
1591
1592	if (len < RX_COPY_THRESHOLD) {
1593#ifdef T4_PKT_TIMESTAMP
1594		/* Leave room for a timestamp */
1595		m0->m_data += 8;
1596#endif
1597		/* copy data to mbuf, buffer will be recycled */
1598		bcopy(sd->cl, mtod(m0, caddr_t), len);
1599		m0->m_len = len;
1600	} else {
1601		bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
1602		m_cljset(m0, sd->cl, FL_BUF_TYPE(sc, sd->tag_idx));
1603		sd->cl = NULL;	/* consumed */
1604		m0->m_len = min(len, FL_BUF_SIZE(sc, sd->tag_idx));
1605	}
1606	m0->m_pkthdr.len = len;
1607
1608	sd++;
1609	if (__predict_false(++fl->cidx == fl->cap)) {
1610		sd = fl->sdesc;
1611		fl->cidx = 0;
1612	}
1613
1614	m = m0;
1615	len -= m->m_len;
1616	nbuf = 1;	/* # of fl buffers used */
1617
1618	while (len > 0) {
1619		/* Can't fail, we checked earlier that the stash was full. */
1620		m->m_next = get_mbuf_from_stash(fl);
1621		m = m->m_next;
1622
1623		bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map,
1624		    BUS_DMASYNC_POSTREAD);
1625
1626		/* m_init for !M_PKTHDR can't fail so don't bother */
1627		m_init(m, NULL, 0, M_NOWAIT, MT_DATA, 0);
1628		if (len <= MLEN) {
1629			bcopy(sd->cl, mtod(m, caddr_t), len);
1630			m->m_len = len;
1631		} else {
1632			bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
1633			m_cljset(m, sd->cl, FL_BUF_TYPE(sc, sd->tag_idx));
1634			sd->cl = NULL;	/* consumed */
1635			m->m_len = min(len, FL_BUF_SIZE(sc, sd->tag_idx));
1636		}
1637
1638		sd++;
1639		if (__predict_false(++fl->cidx == fl->cap)) {
1640			sd = fl->sdesc;
1641			fl->cidx = 0;
1642		}
1643
1644		len -= m->m_len;
1645		nbuf++;
1646	}
1647
1648	(*fl_bufs_used) += nbuf;
1649
1650	return (m0);
1651}
1652
1653static int
1654t4_eth_rx(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m0)
1655{
1656	struct sge_rxq *rxq = iq_to_rxq(iq);
1657	struct ifnet *ifp = rxq->ifp;
1658	const struct cpl_rx_pkt *cpl = (const void *)(rss + 1);
1659#if defined(INET) || defined(INET6)
1660	struct lro_ctrl *lro = &rxq->lro;
1661#endif
1662
1663	KASSERT(m0 != NULL, ("%s: no payload with opcode %02x", __func__,
1664	    rss->opcode));
1665
1666	m0->m_pkthdr.len -= fl_pktshift;
1667	m0->m_len -= fl_pktshift;
1668	m0->m_data += fl_pktshift;
1669
1670	m0->m_pkthdr.rcvif = ifp;
1671	m0->m_flags |= M_FLOWID;
1672	m0->m_pkthdr.flowid = rss->hash_val;
1673
1674	if (cpl->csum_calc && !cpl->err_vec) {
1675		if (ifp->if_capenable & IFCAP_RXCSUM &&
1676		    cpl->l2info & htobe32(F_RXF_IP)) {
1677			m0->m_pkthdr.csum_flags = (CSUM_IP_CHECKED |
1678			    CSUM_IP_VALID | CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1679			rxq->rxcsum++;
1680		} else if (ifp->if_capenable & IFCAP_RXCSUM_IPV6 &&
1681		    cpl->l2info & htobe32(F_RXF_IP6)) {
1682			m0->m_pkthdr.csum_flags = (CSUM_DATA_VALID_IPV6 |
1683			    CSUM_PSEUDO_HDR);
1684			rxq->rxcsum++;
1685		}
1686
1687		if (__predict_false(cpl->ip_frag))
1688			m0->m_pkthdr.csum_data = be16toh(cpl->csum);
1689		else
1690			m0->m_pkthdr.csum_data = 0xffff;
1691	}
1692
1693	if (cpl->vlan_ex) {
1694		m0->m_pkthdr.ether_vtag = be16toh(cpl->vlan);
1695		m0->m_flags |= M_VLANTAG;
1696		rxq->vlan_extraction++;
1697	}
1698
1699#if defined(INET) || defined(INET6)
1700	if (cpl->l2info & htobe32(F_RXF_LRO) &&
1701	    iq->flags & IQ_LRO_ENABLED &&
1702	    tcp_lro_rx(lro, m0, 0) == 0) {
1703		/* queued for LRO */
1704	} else
1705#endif
1706	ifp->if_input(ifp, m0);
1707
1708	return (0);
1709}
1710
1711/*
1712 * Doesn't fail.  Holds on to work requests it can't send right away.
1713 */
1714void
1715t4_wrq_tx_locked(struct adapter *sc, struct sge_wrq *wrq, struct wrqe *wr)
1716{
1717	struct sge_eq *eq = &wrq->eq;
1718	int can_reclaim;
1719	caddr_t dst;
1720
1721	TXQ_LOCK_ASSERT_OWNED(wrq);
1722#ifdef TCP_OFFLOAD
1723	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_OFLD ||
1724	    (eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1725	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1726#else
1727	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1728	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1729#endif
1730
1731	if (__predict_true(wr != NULL))
1732		STAILQ_INSERT_TAIL(&wrq->wr_list, wr, link);
1733
1734	can_reclaim = reclaimable(eq);
1735	if (__predict_false(eq->flags & EQ_STALLED)) {
1736		if (can_reclaim < tx_resume_threshold(eq))
1737			return;
1738		eq->flags &= ~EQ_STALLED;
1739		eq->unstalled++;
1740	}
1741	eq->cidx += can_reclaim;
1742	eq->avail += can_reclaim;
1743	if (__predict_false(eq->cidx >= eq->cap))
1744		eq->cidx -= eq->cap;
1745
1746	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
1747		int ndesc;
1748
1749		if (__predict_false(wr->wr_len < 0 ||
1750		    wr->wr_len > SGE_MAX_WR_LEN || (wr->wr_len & 0x7))) {
1751
1752#ifdef INVARIANTS
1753			panic("%s: work request with length %d", __func__,
1754			    wr->wr_len);
1755#endif
1756#ifdef KDB
1757			kdb_backtrace();
1758#endif
1759			log(LOG_ERR, "%s: %s work request with length %d",
1760			    device_get_nameunit(sc->dev), __func__, wr->wr_len);
1761			STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1762			free_wrqe(wr);
1763			continue;
1764		}
1765
1766		ndesc = howmany(wr->wr_len, EQ_ESIZE);
1767		if (eq->avail < ndesc) {
1768			wrq->no_desc++;
1769			break;
1770		}
1771
1772		dst = (void *)&eq->desc[eq->pidx];
1773		copy_to_txd(eq, wrtod(wr), &dst, wr->wr_len);
1774
1775		eq->pidx += ndesc;
1776		eq->avail -= ndesc;
1777		if (__predict_false(eq->pidx >= eq->cap))
1778			eq->pidx -= eq->cap;
1779
1780		eq->pending += ndesc;
1781		if (eq->pending >= 8)
1782			ring_eq_db(sc, eq);
1783
1784		wrq->tx_wrs++;
1785		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1786		free_wrqe(wr);
1787
1788		if (eq->avail < 8) {
1789			can_reclaim = reclaimable(eq);
1790			eq->cidx += can_reclaim;
1791			eq->avail += can_reclaim;
1792			if (__predict_false(eq->cidx >= eq->cap))
1793				eq->cidx -= eq->cap;
1794		}
1795	}
1796
1797	if (eq->pending)
1798		ring_eq_db(sc, eq);
1799
1800	if (wr != NULL) {
1801		eq->flags |= EQ_STALLED;
1802		if (callout_pending(&eq->tx_callout) == 0)
1803			callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1804	}
1805}
1806
1807/* Per-packet header in a coalesced tx WR, before the SGL starts (in flits) */
1808#define TXPKTS_PKT_HDR ((\
1809    sizeof(struct ulp_txpkt) + \
1810    sizeof(struct ulptx_idata) + \
1811    sizeof(struct cpl_tx_pkt_core) \
1812    ) / 8)
1813
1814/* Header of a coalesced tx WR, before SGL of first packet (in flits) */
1815#define TXPKTS_WR_HDR (\
1816    sizeof(struct fw_eth_tx_pkts_wr) / 8 + \
1817    TXPKTS_PKT_HDR)
1818
1819/* Header of a tx WR, before SGL of first packet (in flits) */
1820#define TXPKT_WR_HDR ((\
1821    sizeof(struct fw_eth_tx_pkt_wr) + \
1822    sizeof(struct cpl_tx_pkt_core) \
1823    ) / 8 )
1824
1825/* Header of a tx LSO WR, before SGL of first packet (in flits) */
1826#define TXPKT_LSO_WR_HDR ((\
1827    sizeof(struct fw_eth_tx_pkt_wr) + \
1828    sizeof(struct cpl_tx_pkt_lso_core) + \
1829    sizeof(struct cpl_tx_pkt_core) \
1830    ) / 8 )
1831
1832int
1833t4_eth_tx(struct ifnet *ifp, struct sge_txq *txq, struct mbuf *m)
1834{
1835	struct port_info *pi = (void *)ifp->if_softc;
1836	struct adapter *sc = pi->adapter;
1837	struct sge_eq *eq = &txq->eq;
1838	struct buf_ring *br = txq->br;
1839	struct mbuf *next;
1840	int rc, coalescing, can_reclaim;
1841	struct txpkts txpkts;
1842	struct sgl sgl;
1843
1844	TXQ_LOCK_ASSERT_OWNED(txq);
1845	KASSERT(m, ("%s: called with nothing to do.", __func__));
1846	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_ETH,
1847	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1848
1849	prefetch(&eq->desc[eq->pidx]);
1850	prefetch(&txq->sdesc[eq->pidx]);
1851
1852	txpkts.npkt = 0;/* indicates there's nothing in txpkts */
1853	coalescing = 0;
1854
1855	can_reclaim = reclaimable(eq);
1856	if (__predict_false(eq->flags & EQ_STALLED)) {
1857		if (can_reclaim < tx_resume_threshold(eq)) {
1858			txq->m = m;
1859			return (0);
1860		}
1861		eq->flags &= ~EQ_STALLED;
1862		eq->unstalled++;
1863	}
1864
1865	if (__predict_false(eq->flags & EQ_DOOMED)) {
1866		m_freem(m);
1867		while ((m = buf_ring_dequeue_sc(txq->br)) != NULL)
1868			m_freem(m);
1869		return (ENETDOWN);
1870	}
1871
1872	if (eq->avail < 8 && can_reclaim)
1873		reclaim_tx_descs(txq, can_reclaim, 32);
1874
1875	for (; m; m = next ? next : drbr_dequeue(ifp, br)) {
1876
1877		if (eq->avail < 8)
1878			break;
1879
1880		next = m->m_nextpkt;
1881		m->m_nextpkt = NULL;
1882
1883		if (next || buf_ring_peek(br))
1884			coalescing = 1;
1885
1886		rc = get_pkt_sgl(txq, &m, &sgl, coalescing);
1887		if (rc != 0) {
1888			if (rc == ENOMEM) {
1889
1890				/* Short of resources, suspend tx */
1891
1892				m->m_nextpkt = next;
1893				break;
1894			}
1895
1896			/*
1897			 * Unrecoverable error for this packet, throw it away
1898			 * and move on to the next.  get_pkt_sgl may already
1899			 * have freed m (it will be NULL in that case and the
1900			 * m_freem here is still safe).
1901			 */
1902
1903			m_freem(m);
1904			continue;
1905		}
1906
1907		if (coalescing &&
1908		    add_to_txpkts(pi, txq, &txpkts, m, &sgl) == 0) {
1909
1910			/* Successfully absorbed into txpkts */
1911
1912			write_ulp_cpl_sgl(pi, txq, &txpkts, m, &sgl);
1913			goto doorbell;
1914		}
1915
1916		/*
1917		 * We weren't coalescing to begin with, or current frame could
1918		 * not be coalesced (add_to_txpkts flushes txpkts if a frame
1919		 * given to it can't be coalesced).  Either way there should be
1920		 * nothing in txpkts.
1921		 */
1922		KASSERT(txpkts.npkt == 0,
1923		    ("%s: txpkts not empty: %d", __func__, txpkts.npkt));
1924
1925		/* We're sending out individual packets now */
1926		coalescing = 0;
1927
1928		if (eq->avail < 8)
1929			reclaim_tx_descs(txq, 0, 8);
1930		rc = write_txpkt_wr(pi, txq, m, &sgl);
1931		if (rc != 0) {
1932
1933			/* Short of hardware descriptors, suspend tx */
1934
1935			/*
1936			 * This is an unlikely but expensive failure.  We've
1937			 * done all the hard work (DMA mappings etc.) and now we
1938			 * can't send out the packet.  What's worse, we have to
1939			 * spend even more time freeing up everything in sgl.
1940			 */
1941			txq->no_desc++;
1942			free_pkt_sgl(txq, &sgl);
1943
1944			m->m_nextpkt = next;
1945			break;
1946		}
1947
1948		ETHER_BPF_MTAP(ifp, m);
1949		if (sgl.nsegs == 0)
1950			m_freem(m);
1951doorbell:
1952		if (eq->pending >= 8)
1953			ring_eq_db(sc, eq);
1954
1955		can_reclaim = reclaimable(eq);
1956		if (can_reclaim >= 32)
1957			reclaim_tx_descs(txq, can_reclaim, 64);
1958	}
1959
1960	if (txpkts.npkt > 0)
1961		write_txpkts_wr(txq, &txpkts);
1962
1963	/*
1964	 * m not NULL means there was an error but we haven't thrown it away.
1965	 * This can happen when we're short of tx descriptors (no_desc) or maybe
1966	 * even DMA maps (no_dmamap).  Either way, a credit flush and reclaim
1967	 * will get things going again.
1968	 */
1969	if (m && !(eq->flags & EQ_CRFLUSHED)) {
1970		struct tx_sdesc *txsd = &txq->sdesc[eq->pidx];
1971
1972		/*
1973		 * If EQ_CRFLUSHED is not set then we know we have at least one
1974		 * available descriptor because any WR that reduces eq->avail to
1975		 * 0 also sets EQ_CRFLUSHED.
1976		 */
1977		KASSERT(eq->avail > 0, ("%s: no space for eqflush.", __func__));
1978
1979		txsd->desc_used = 1;
1980		txsd->credits = 0;
1981		write_eqflush_wr(eq);
1982	}
1983	txq->m = m;
1984
1985	if (eq->pending)
1986		ring_eq_db(sc, eq);
1987
1988	reclaim_tx_descs(txq, 0, 128);
1989
1990	if (eq->flags & EQ_STALLED && callout_pending(&eq->tx_callout) == 0)
1991		callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1992
1993	return (0);
1994}
1995
1996void
1997t4_update_fl_bufsize(struct ifnet *ifp)
1998{
1999	struct port_info *pi = ifp->if_softc;
2000	struct adapter *sc = pi->adapter;
2001	struct sge_rxq *rxq;
2002#ifdef TCP_OFFLOAD
2003	struct sge_ofld_rxq *ofld_rxq;
2004#endif
2005	struct sge_fl *fl;
2006	int i, bufsize;
2007
2008	bufsize = mtu_to_bufsize(ifp->if_mtu);
2009	for_each_rxq(pi, i, rxq) {
2010		fl = &rxq->fl;
2011
2012		FL_LOCK(fl);
2013		set_fl_tag_idx(sc, fl, bufsize);
2014		FL_UNLOCK(fl);
2015	}
2016#ifdef TCP_OFFLOAD
2017	bufsize = mtu_to_bufsize_toe(pi->adapter, ifp->if_mtu);
2018	for_each_ofld_rxq(pi, i, ofld_rxq) {
2019		fl = &ofld_rxq->fl;
2020
2021		FL_LOCK(fl);
2022		set_fl_tag_idx(sc, fl, bufsize);
2023		FL_UNLOCK(fl);
2024	}
2025#endif
2026}
2027
2028int
2029can_resume_tx(struct sge_eq *eq)
2030{
2031	return (reclaimable(eq) >= tx_resume_threshold(eq));
2032}
2033
2034static inline void
2035init_iq(struct sge_iq *iq, struct adapter *sc, int tmr_idx, int pktc_idx,
2036    int qsize, int esize)
2037{
2038	KASSERT(tmr_idx >= 0 && tmr_idx < SGE_NTIMERS,
2039	    ("%s: bad tmr_idx %d", __func__, tmr_idx));
2040	KASSERT(pktc_idx < SGE_NCOUNTERS,	/* -ve is ok, means don't use */
2041	    ("%s: bad pktc_idx %d", __func__, pktc_idx));
2042
2043	iq->flags = 0;
2044	iq->adapter = sc;
2045	iq->intr_params = V_QINTR_TIMER_IDX(tmr_idx);
2046	iq->intr_pktc_idx = SGE_NCOUNTERS - 1;
2047	if (pktc_idx >= 0) {
2048		iq->intr_params |= F_QINTR_CNT_EN;
2049		iq->intr_pktc_idx = pktc_idx;
2050	}
2051	iq->qsize = roundup2(qsize, 16);	/* See FW_IQ_CMD/iqsize */
2052	iq->esize = max(esize, 16);		/* See FW_IQ_CMD/iqesize */
2053}
2054
2055static inline void
2056init_fl(struct adapter *sc, struct sge_fl *fl, int qsize, int bufsize, int pack,
2057    char *name)
2058{
2059
2060	fl->qsize = qsize;
2061	strlcpy(fl->lockname, name, sizeof(fl->lockname));
2062	if (pack)
2063		fl->flags |= FL_BUF_PACKING;
2064	set_fl_tag_idx(sc, fl, bufsize);
2065}
2066
2067static inline void
2068init_eq(struct sge_eq *eq, int eqtype, int qsize, uint8_t tx_chan,
2069    uint16_t iqid, char *name)
2070{
2071	KASSERT(tx_chan < NCHAN, ("%s: bad tx channel %d", __func__, tx_chan));
2072	KASSERT(eqtype <= EQ_TYPEMASK, ("%s: bad qtype %d", __func__, eqtype));
2073
2074	eq->flags = eqtype & EQ_TYPEMASK;
2075	eq->tx_chan = tx_chan;
2076	eq->iqid = iqid;
2077	eq->qsize = qsize;
2078	strlcpy(eq->lockname, name, sizeof(eq->lockname));
2079
2080	TASK_INIT(&eq->tx_task, 0, t4_tx_task, eq);
2081	callout_init(&eq->tx_callout, CALLOUT_MPSAFE);
2082}
2083
2084static int
2085alloc_ring(struct adapter *sc, size_t len, bus_dma_tag_t *tag,
2086    bus_dmamap_t *map, bus_addr_t *pa, void **va)
2087{
2088	int rc;
2089
2090	rc = bus_dma_tag_create(sc->dmat, 512, 0, BUS_SPACE_MAXADDR,
2091	    BUS_SPACE_MAXADDR, NULL, NULL, len, 1, len, 0, NULL, NULL, tag);
2092	if (rc != 0) {
2093		device_printf(sc->dev, "cannot allocate DMA tag: %d\n", rc);
2094		goto done;
2095	}
2096
2097	rc = bus_dmamem_alloc(*tag, va,
2098	    BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, map);
2099	if (rc != 0) {
2100		device_printf(sc->dev, "cannot allocate DMA memory: %d\n", rc);
2101		goto done;
2102	}
2103
2104	rc = bus_dmamap_load(*tag, *map, *va, len, oneseg_dma_callback, pa, 0);
2105	if (rc != 0) {
2106		device_printf(sc->dev, "cannot load DMA map: %d\n", rc);
2107		goto done;
2108	}
2109done:
2110	if (rc)
2111		free_ring(sc, *tag, *map, *pa, *va);
2112
2113	return (rc);
2114}
2115
2116static int
2117free_ring(struct adapter *sc, bus_dma_tag_t tag, bus_dmamap_t map,
2118    bus_addr_t pa, void *va)
2119{
2120	if (pa)
2121		bus_dmamap_unload(tag, map);
2122	if (va)
2123		bus_dmamem_free(tag, va, map);
2124	if (tag)
2125		bus_dma_tag_destroy(tag);
2126
2127	return (0);
2128}
2129
2130/*
2131 * Allocates the ring for an ingress queue and an optional freelist.  If the
2132 * freelist is specified it will be allocated and then associated with the
2133 * ingress queue.
2134 *
2135 * Returns errno on failure.  Resources allocated up to that point may still be
2136 * allocated.  Caller is responsible for cleanup in case this function fails.
2137 *
2138 * If the ingress queue will take interrupts directly (iq->flags & IQ_INTR) then
2139 * the intr_idx specifies the vector, starting from 0.  Otherwise it specifies
2140 * the abs_id of the ingress queue to which its interrupts should be forwarded.
2141 */
2142static int
2143alloc_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl,
2144    int intr_idx, int cong)
2145{
2146	int rc, i, cntxt_id;
2147	size_t len;
2148	struct fw_iq_cmd c;
2149	struct adapter *sc = iq->adapter;
2150	__be32 v = 0;
2151
2152	len = iq->qsize * iq->esize;
2153	rc = alloc_ring(sc, len, &iq->desc_tag, &iq->desc_map, &iq->ba,
2154	    (void **)&iq->desc);
2155	if (rc != 0)
2156		return (rc);
2157
2158	bzero(&c, sizeof(c));
2159	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
2160	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_IQ_CMD_PFN(sc->pf) |
2161	    V_FW_IQ_CMD_VFN(0));
2162
2163	c.alloc_to_len16 = htobe32(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
2164	    FW_LEN16(c));
2165
2166	/* Special handling for firmware event queue */
2167	if (iq == &sc->sge.fwq)
2168		v |= F_FW_IQ_CMD_IQASYNCH;
2169
2170	if (iq->flags & IQ_INTR) {
2171		KASSERT(intr_idx < sc->intr_count,
2172		    ("%s: invalid direct intr_idx %d", __func__, intr_idx));
2173	} else
2174		v |= F_FW_IQ_CMD_IQANDST;
2175	v |= V_FW_IQ_CMD_IQANDSTINDEX(intr_idx);
2176
2177	c.type_to_iqandstindex = htobe32(v |
2178	    V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
2179	    V_FW_IQ_CMD_VIID(pi->viid) |
2180	    V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT));
2181	c.iqdroprss_to_iqesize = htobe16(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
2182	    F_FW_IQ_CMD_IQGTSMODE |
2183	    V_FW_IQ_CMD_IQINTCNTTHRESH(iq->intr_pktc_idx) |
2184	    V_FW_IQ_CMD_IQESIZE(ilog2(iq->esize) - 4));
2185	c.iqsize = htobe16(iq->qsize);
2186	c.iqaddr = htobe64(iq->ba);
2187	if (cong >= 0)
2188		c.iqns_to_fl0congen = htobe32(F_FW_IQ_CMD_IQFLINTCONGEN);
2189
2190	if (fl) {
2191		mtx_init(&fl->fl_lock, fl->lockname, NULL, MTX_DEF);
2192
2193		for (i = 0; i < FL_BUF_SIZES(sc); i++) {
2194
2195			/*
2196			 * A freelist buffer must be 16 byte aligned as the SGE
2197			 * uses the low 4 bits of the bus addr to figure out the
2198			 * buffer size.
2199			 */
2200			rc = bus_dma_tag_create(sc->dmat, 16, 0,
2201			    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
2202			    FL_BUF_SIZE(sc, i), 1, FL_BUF_SIZE(sc, i),
2203			    BUS_DMA_ALLOCNOW, NULL, NULL, &fl->tag[i]);
2204			if (rc != 0) {
2205				device_printf(sc->dev,
2206				    "failed to create fl DMA tag[%d]: %d\n",
2207				    i, rc);
2208				return (rc);
2209			}
2210		}
2211		len = fl->qsize * RX_FL_ESIZE;
2212		rc = alloc_ring(sc, len, &fl->desc_tag, &fl->desc_map,
2213		    &fl->ba, (void **)&fl->desc);
2214		if (rc)
2215			return (rc);
2216
2217		/* Allocate space for one software descriptor per buffer. */
2218		fl->cap = (fl->qsize - spg_len / RX_FL_ESIZE) * 8;
2219		rc = alloc_fl_sdesc(fl);
2220		if (rc != 0) {
2221			device_printf(sc->dev,
2222			    "failed to setup fl software descriptors: %d\n",
2223			    rc);
2224			return (rc);
2225		}
2226		fl->needed = fl->cap;
2227		fl->lowat = roundup2(sc->sge.fl_starve_threshold, 8);
2228
2229		c.iqns_to_fl0congen |=
2230		    htobe32(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
2231			F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
2232			(fl_pad ? F_FW_IQ_CMD_FL0PADEN : 0) |
2233			(fl->flags & FL_BUF_PACKING ? F_FW_IQ_CMD_FL0PACKEN :
2234			    0));
2235		if (cong >= 0) {
2236			c.iqns_to_fl0congen |=
2237				htobe32(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
2238				    F_FW_IQ_CMD_FL0CONGCIF |
2239				    F_FW_IQ_CMD_FL0CONGEN);
2240		}
2241		c.fl0dcaen_to_fl0cidxfthresh =
2242		    htobe16(V_FW_IQ_CMD_FL0FBMIN(X_FETCHBURSTMIN_64B) |
2243			V_FW_IQ_CMD_FL0FBMAX(X_FETCHBURSTMAX_512B));
2244		c.fl0size = htobe16(fl->qsize);
2245		c.fl0addr = htobe64(fl->ba);
2246	}
2247
2248	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2249	if (rc != 0) {
2250		device_printf(sc->dev,
2251		    "failed to create ingress queue: %d\n", rc);
2252		return (rc);
2253	}
2254
2255	iq->cdesc = iq->desc;
2256	iq->cidx = 0;
2257	iq->gen = 1;
2258	iq->intr_next = iq->intr_params;
2259	iq->cntxt_id = be16toh(c.iqid);
2260	iq->abs_id = be16toh(c.physiqid);
2261	iq->flags |= IQ_ALLOCATED;
2262
2263	cntxt_id = iq->cntxt_id - sc->sge.iq_start;
2264	if (cntxt_id >= sc->sge.niq) {
2265		panic ("%s: iq->cntxt_id (%d) more than the max (%d)", __func__,
2266		    cntxt_id, sc->sge.niq - 1);
2267	}
2268	sc->sge.iqmap[cntxt_id] = iq;
2269
2270	if (fl) {
2271		fl->cntxt_id = be16toh(c.fl0id);
2272		fl->pidx = fl->cidx = 0;
2273
2274		cntxt_id = fl->cntxt_id - sc->sge.eq_start;
2275		if (cntxt_id >= sc->sge.neq) {
2276			panic("%s: fl->cntxt_id (%d) more than the max (%d)",
2277			    __func__, cntxt_id, sc->sge.neq - 1);
2278		}
2279		sc->sge.eqmap[cntxt_id] = (void *)fl;
2280
2281		FL_LOCK(fl);
2282		/* Enough to make sure the SGE doesn't think it's starved */
2283		refill_fl(sc, fl, fl->lowat);
2284		FL_UNLOCK(fl);
2285
2286		iq->flags |= IQ_HAS_FL;
2287	}
2288
2289	if (is_t5(sc) && cong >= 0) {
2290		uint32_t param, val;
2291
2292		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
2293		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
2294		    V_FW_PARAMS_PARAM_YZ(iq->cntxt_id);
2295		if (cong == 0)
2296			val = 1 << 19;
2297		else {
2298			val = 2 << 19;
2299			for (i = 0; i < 4; i++) {
2300				if (cong & (1 << i))
2301					val |= 1 << (i << 2);
2302			}
2303		}
2304
2305		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2306		if (rc != 0) {
2307			/* report error but carry on */
2308			device_printf(sc->dev,
2309			    "failed to set congestion manager context for "
2310			    "ingress queue %d: %d\n", iq->cntxt_id, rc);
2311		}
2312	}
2313
2314	/* Enable IQ interrupts */
2315	atomic_store_rel_int(&iq->state, IQS_IDLE);
2316	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_SEINTARM(iq->intr_params) |
2317	    V_INGRESSQID(iq->cntxt_id));
2318
2319	return (0);
2320}
2321
2322static int
2323free_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl)
2324{
2325	int i, rc;
2326	struct adapter *sc = iq->adapter;
2327	device_t dev;
2328
2329	if (sc == NULL)
2330		return (0);	/* nothing to do */
2331
2332	dev = pi ? pi->dev : sc->dev;
2333
2334	if (iq->flags & IQ_ALLOCATED) {
2335		rc = -t4_iq_free(sc, sc->mbox, sc->pf, 0,
2336		    FW_IQ_TYPE_FL_INT_CAP, iq->cntxt_id,
2337		    fl ? fl->cntxt_id : 0xffff, 0xffff);
2338		if (rc != 0) {
2339			device_printf(dev,
2340			    "failed to free queue %p: %d\n", iq, rc);
2341			return (rc);
2342		}
2343		iq->flags &= ~IQ_ALLOCATED;
2344	}
2345
2346	free_ring(sc, iq->desc_tag, iq->desc_map, iq->ba, iq->desc);
2347
2348	bzero(iq, sizeof(*iq));
2349
2350	if (fl) {
2351		free_ring(sc, fl->desc_tag, fl->desc_map, fl->ba,
2352		    fl->desc);
2353
2354		if (fl->sdesc)
2355			free_fl_sdesc(sc, fl);
2356
2357		for (i = 0; i < nitems(fl->mstash); i++) {
2358			struct mbuf *m = fl->mstash[i];
2359
2360			if (m != NULL) {
2361				m_init(m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2362				m_free(m);
2363			}
2364		}
2365
2366		if (mtx_initialized(&fl->fl_lock))
2367			mtx_destroy(&fl->fl_lock);
2368
2369		for (i = 0; i < FL_BUF_SIZES(sc); i++) {
2370			if (fl->tag[i])
2371				bus_dma_tag_destroy(fl->tag[i]);
2372		}
2373
2374		bzero(fl, sizeof(*fl));
2375	}
2376
2377	return (0);
2378}
2379
2380static int
2381alloc_fwq(struct adapter *sc)
2382{
2383	int rc, intr_idx;
2384	struct sge_iq *fwq = &sc->sge.fwq;
2385	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
2386	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2387
2388	init_iq(fwq, sc, 0, 0, FW_IQ_QSIZE, FW_IQ_ESIZE);
2389	fwq->flags |= IQ_INTR;	/* always */
2390	intr_idx = sc->intr_count > 1 ? 1 : 0;
2391	rc = alloc_iq_fl(sc->port[0], fwq, NULL, intr_idx, -1);
2392	if (rc != 0) {
2393		device_printf(sc->dev,
2394		    "failed to create firmware event queue: %d\n", rc);
2395		return (rc);
2396	}
2397
2398	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "fwq", CTLFLAG_RD,
2399	    NULL, "firmware event queue");
2400	children = SYSCTL_CHILDREN(oid);
2401
2402	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "abs_id",
2403	    CTLTYPE_INT | CTLFLAG_RD, &fwq->abs_id, 0, sysctl_uint16, "I",
2404	    "absolute id of the queue");
2405	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cntxt_id",
2406	    CTLTYPE_INT | CTLFLAG_RD, &fwq->cntxt_id, 0, sysctl_uint16, "I",
2407	    "SGE context id of the queue");
2408	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cidx",
2409	    CTLTYPE_INT | CTLFLAG_RD, &fwq->cidx, 0, sysctl_uint16, "I",
2410	    "consumer index");
2411
2412	return (0);
2413}
2414
2415static int
2416free_fwq(struct adapter *sc)
2417{
2418	return free_iq_fl(NULL, &sc->sge.fwq, NULL);
2419}
2420
2421static int
2422alloc_mgmtq(struct adapter *sc)
2423{
2424	int rc;
2425	struct sge_wrq *mgmtq = &sc->sge.mgmtq;
2426	char name[16];
2427	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
2428	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2429
2430	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "mgmtq", CTLFLAG_RD,
2431	    NULL, "management queue");
2432
2433	snprintf(name, sizeof(name), "%s mgmtq", device_get_nameunit(sc->dev));
2434	init_eq(&mgmtq->eq, EQ_CTRL, CTRL_EQ_QSIZE, sc->port[0]->tx_chan,
2435	    sc->sge.fwq.cntxt_id, name);
2436	rc = alloc_wrq(sc, NULL, mgmtq, oid);
2437	if (rc != 0) {
2438		device_printf(sc->dev,
2439		    "failed to create management queue: %d\n", rc);
2440		return (rc);
2441	}
2442
2443	return (0);
2444}
2445
2446static int
2447free_mgmtq(struct adapter *sc)
2448{
2449
2450	return free_wrq(sc, &sc->sge.mgmtq);
2451}
2452
2453static inline int
2454tnl_cong(struct port_info *pi)
2455{
2456
2457	if (cong_drop == -1)
2458		return (-1);
2459	else if (cong_drop == 1)
2460		return (0);
2461	else
2462		return (1 << pi->tx_chan);
2463}
2464
2465static int
2466alloc_rxq(struct port_info *pi, struct sge_rxq *rxq, int intr_idx, int idx,
2467    struct sysctl_oid *oid)
2468{
2469	int rc;
2470	struct sysctl_oid_list *children;
2471	char name[16];
2472
2473	rc = alloc_iq_fl(pi, &rxq->iq, &rxq->fl, intr_idx, tnl_cong(pi));
2474	if (rc != 0)
2475		return (rc);
2476
2477	FL_LOCK(&rxq->fl);
2478	refill_fl(pi->adapter, &rxq->fl, rxq->fl.needed / 8);
2479	FL_UNLOCK(&rxq->fl);
2480
2481#if defined(INET) || defined(INET6)
2482	rc = tcp_lro_init(&rxq->lro);
2483	if (rc != 0)
2484		return (rc);
2485	rxq->lro.ifp = pi->ifp; /* also indicates LRO init'ed */
2486
2487	if (pi->ifp->if_capenable & IFCAP_LRO)
2488		rxq->iq.flags |= IQ_LRO_ENABLED;
2489#endif
2490	rxq->ifp = pi->ifp;
2491
2492	children = SYSCTL_CHILDREN(oid);
2493
2494	snprintf(name, sizeof(name), "%d", idx);
2495	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2496	    NULL, "rx queue");
2497	children = SYSCTL_CHILDREN(oid);
2498
2499	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
2500	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.abs_id, 0, sysctl_uint16, "I",
2501	    "absolute id of the queue");
2502	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2503	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cntxt_id, 0, sysctl_uint16, "I",
2504	    "SGE context id of the queue");
2505	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2506	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cidx, 0, sysctl_uint16, "I",
2507	    "consumer index");
2508#if defined(INET) || defined(INET6)
2509	SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_queued", CTLFLAG_RD,
2510	    &rxq->lro.lro_queued, 0, NULL);
2511	SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_flushed", CTLFLAG_RD,
2512	    &rxq->lro.lro_flushed, 0, NULL);
2513#endif
2514	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "rxcsum", CTLFLAG_RD,
2515	    &rxq->rxcsum, "# of times hardware assisted with checksum");
2516	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_extraction",
2517	    CTLFLAG_RD, &rxq->vlan_extraction,
2518	    "# of times hardware extracted 802.1Q tag");
2519
2520	children = SYSCTL_CHILDREN(oid);
2521	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
2522	    NULL, "freelist");
2523	children = SYSCTL_CHILDREN(oid);
2524
2525	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2526	    CTLTYPE_INT | CTLFLAG_RD, &rxq->fl.cntxt_id, 0, sysctl_uint16, "I",
2527	    "SGE context id of the queue");
2528	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
2529	    &rxq->fl.cidx, 0, "consumer index");
2530	if (rxq->fl.flags & FL_BUF_PACKING) {
2531		SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "rx_offset",
2532		    CTLFLAG_RD, &rxq->fl.rx_offset, 0, "packing rx offset");
2533	}
2534	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
2535	    &rxq->fl.pidx, 0, "producer index");
2536
2537	return (rc);
2538}
2539
2540static int
2541free_rxq(struct port_info *pi, struct sge_rxq *rxq)
2542{
2543	int rc;
2544
2545#if defined(INET) || defined(INET6)
2546	if (rxq->lro.ifp) {
2547		tcp_lro_free(&rxq->lro);
2548		rxq->lro.ifp = NULL;
2549	}
2550#endif
2551
2552	rc = free_iq_fl(pi, &rxq->iq, &rxq->fl);
2553	if (rc == 0)
2554		bzero(rxq, sizeof(*rxq));
2555
2556	return (rc);
2557}
2558
2559#ifdef TCP_OFFLOAD
2560static int
2561alloc_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq,
2562    int intr_idx, int idx, struct sysctl_oid *oid)
2563{
2564	int rc;
2565	struct sysctl_oid_list *children;
2566	char name[16];
2567
2568	rc = alloc_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl, intr_idx,
2569	    1 << pi->tx_chan);
2570	if (rc != 0)
2571		return (rc);
2572
2573	children = SYSCTL_CHILDREN(oid);
2574
2575	snprintf(name, sizeof(name), "%d", idx);
2576	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2577	    NULL, "rx queue");
2578	children = SYSCTL_CHILDREN(oid);
2579
2580	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
2581	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.abs_id, 0, sysctl_uint16,
2582	    "I", "absolute id of the queue");
2583	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2584	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cntxt_id, 0, sysctl_uint16,
2585	    "I", "SGE context id of the queue");
2586	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2587	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cidx, 0, sysctl_uint16, "I",
2588	    "consumer index");
2589
2590	children = SYSCTL_CHILDREN(oid);
2591	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
2592	    NULL, "freelist");
2593	children = SYSCTL_CHILDREN(oid);
2594
2595	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2596	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->fl.cntxt_id, 0, sysctl_uint16,
2597	    "I", "SGE context id of the queue");
2598	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
2599	    &ofld_rxq->fl.cidx, 0, "consumer index");
2600	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
2601	    &ofld_rxq->fl.pidx, 0, "producer index");
2602
2603	return (rc);
2604}
2605
2606static int
2607free_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq)
2608{
2609	int rc;
2610
2611	rc = free_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl);
2612	if (rc == 0)
2613		bzero(ofld_rxq, sizeof(*ofld_rxq));
2614
2615	return (rc);
2616}
2617#endif
2618
2619static int
2620ctrl_eq_alloc(struct adapter *sc, struct sge_eq *eq)
2621{
2622	int rc, cntxt_id;
2623	struct fw_eq_ctrl_cmd c;
2624
2625	bzero(&c, sizeof(c));
2626
2627	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
2628	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_CTRL_CMD_PFN(sc->pf) |
2629	    V_FW_EQ_CTRL_CMD_VFN(0));
2630	c.alloc_to_len16 = htobe32(F_FW_EQ_CTRL_CMD_ALLOC |
2631	    F_FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
2632	c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(eq->iqid)); /* XXX */
2633	c.physeqid_pkd = htobe32(0);
2634	c.fetchszm_to_iqid =
2635	    htobe32(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2636		V_FW_EQ_CTRL_CMD_PCIECHN(eq->tx_chan) |
2637		F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(eq->iqid));
2638	c.dcaen_to_eqsize =
2639	    htobe32(V_FW_EQ_CTRL_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2640		V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2641		V_FW_EQ_CTRL_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2642		V_FW_EQ_CTRL_CMD_EQSIZE(eq->qsize));
2643	c.eqaddr = htobe64(eq->ba);
2644
2645	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2646	if (rc != 0) {
2647		device_printf(sc->dev,
2648		    "failed to create control queue %d: %d\n", eq->tx_chan, rc);
2649		return (rc);
2650	}
2651	eq->flags |= EQ_ALLOCATED;
2652
2653	eq->cntxt_id = G_FW_EQ_CTRL_CMD_EQID(be32toh(c.cmpliqid_eqid));
2654	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2655	if (cntxt_id >= sc->sge.neq)
2656	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2657		cntxt_id, sc->sge.neq - 1);
2658	sc->sge.eqmap[cntxt_id] = eq;
2659
2660	return (rc);
2661}
2662
2663static int
2664eth_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2665{
2666	int rc, cntxt_id;
2667	struct fw_eq_eth_cmd c;
2668
2669	bzero(&c, sizeof(c));
2670
2671	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
2672	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
2673	    V_FW_EQ_ETH_CMD_VFN(0));
2674	c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
2675	    F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
2676	c.viid_pkd = htobe32(V_FW_EQ_ETH_CMD_VIID(pi->viid));
2677	c.fetchszm_to_iqid =
2678	    htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2679		V_FW_EQ_ETH_CMD_PCIECHN(eq->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
2680		V_FW_EQ_ETH_CMD_IQID(eq->iqid));
2681	c.dcaen_to_eqsize = htobe32(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2682		      V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2683		      V_FW_EQ_ETH_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2684		      V_FW_EQ_ETH_CMD_EQSIZE(eq->qsize));
2685	c.eqaddr = htobe64(eq->ba);
2686
2687	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2688	if (rc != 0) {
2689		device_printf(pi->dev,
2690		    "failed to create Ethernet egress queue: %d\n", rc);
2691		return (rc);
2692	}
2693	eq->flags |= EQ_ALLOCATED;
2694
2695	eq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
2696	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2697	if (cntxt_id >= sc->sge.neq)
2698	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2699		cntxt_id, sc->sge.neq - 1);
2700	sc->sge.eqmap[cntxt_id] = eq;
2701
2702	return (rc);
2703}
2704
2705#ifdef TCP_OFFLOAD
2706static int
2707ofld_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2708{
2709	int rc, cntxt_id;
2710	struct fw_eq_ofld_cmd c;
2711
2712	bzero(&c, sizeof(c));
2713
2714	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_OFLD_CMD) | F_FW_CMD_REQUEST |
2715	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_OFLD_CMD_PFN(sc->pf) |
2716	    V_FW_EQ_OFLD_CMD_VFN(0));
2717	c.alloc_to_len16 = htonl(F_FW_EQ_OFLD_CMD_ALLOC |
2718	    F_FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
2719	c.fetchszm_to_iqid =
2720		htonl(V_FW_EQ_OFLD_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2721		    V_FW_EQ_OFLD_CMD_PCIECHN(eq->tx_chan) |
2722		    F_FW_EQ_OFLD_CMD_FETCHRO | V_FW_EQ_OFLD_CMD_IQID(eq->iqid));
2723	c.dcaen_to_eqsize =
2724	    htobe32(V_FW_EQ_OFLD_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2725		V_FW_EQ_OFLD_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2726		V_FW_EQ_OFLD_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2727		V_FW_EQ_OFLD_CMD_EQSIZE(eq->qsize));
2728	c.eqaddr = htobe64(eq->ba);
2729
2730	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2731	if (rc != 0) {
2732		device_printf(pi->dev,
2733		    "failed to create egress queue for TCP offload: %d\n", rc);
2734		return (rc);
2735	}
2736	eq->flags |= EQ_ALLOCATED;
2737
2738	eq->cntxt_id = G_FW_EQ_OFLD_CMD_EQID(be32toh(c.eqid_pkd));
2739	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2740	if (cntxt_id >= sc->sge.neq)
2741	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2742		cntxt_id, sc->sge.neq - 1);
2743	sc->sge.eqmap[cntxt_id] = eq;
2744
2745	return (rc);
2746}
2747#endif
2748
2749static int
2750alloc_eq(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2751{
2752	int rc;
2753	size_t len;
2754
2755	mtx_init(&eq->eq_lock, eq->lockname, NULL, MTX_DEF);
2756
2757	len = eq->qsize * EQ_ESIZE;
2758	rc = alloc_ring(sc, len, &eq->desc_tag, &eq->desc_map,
2759	    &eq->ba, (void **)&eq->desc);
2760	if (rc)
2761		return (rc);
2762
2763	eq->cap = eq->qsize - spg_len / EQ_ESIZE;
2764	eq->spg = (void *)&eq->desc[eq->cap];
2765	eq->avail = eq->cap - 1;	/* one less to avoid cidx = pidx */
2766	eq->pidx = eq->cidx = 0;
2767	eq->doorbells = sc->doorbells;
2768
2769	switch (eq->flags & EQ_TYPEMASK) {
2770	case EQ_CTRL:
2771		rc = ctrl_eq_alloc(sc, eq);
2772		break;
2773
2774	case EQ_ETH:
2775		rc = eth_eq_alloc(sc, pi, eq);
2776		break;
2777
2778#ifdef TCP_OFFLOAD
2779	case EQ_OFLD:
2780		rc = ofld_eq_alloc(sc, pi, eq);
2781		break;
2782#endif
2783
2784	default:
2785		panic("%s: invalid eq type %d.", __func__,
2786		    eq->flags & EQ_TYPEMASK);
2787	}
2788	if (rc != 0) {
2789		device_printf(sc->dev,
2790		    "failed to allocate egress queue(%d): %d",
2791		    eq->flags & EQ_TYPEMASK, rc);
2792	}
2793
2794	eq->tx_callout.c_cpu = eq->cntxt_id % mp_ncpus;
2795
2796	if (isset(&eq->doorbells, DOORBELL_UDB) ||
2797	    isset(&eq->doorbells, DOORBELL_UDBWC) ||
2798	    isset(&eq->doorbells, DOORBELL_WCWR)) {
2799		uint32_t s_qpp = sc->sge.s_qpp;
2800		uint32_t mask = (1 << s_qpp) - 1;
2801		volatile uint8_t *udb;
2802
2803		udb = sc->udbs_base + UDBS_DB_OFFSET;
2804		udb += (eq->cntxt_id >> s_qpp) << PAGE_SHIFT;	/* pg offset */
2805		eq->udb_qid = eq->cntxt_id & mask;		/* id in page */
2806		if (eq->udb_qid > PAGE_SIZE / UDBS_SEG_SIZE)
2807	    		clrbit(&eq->doorbells, DOORBELL_WCWR);
2808		else {
2809			udb += eq->udb_qid << UDBS_SEG_SHIFT;	/* seg offset */
2810			eq->udb_qid = 0;
2811		}
2812		eq->udb = (volatile void *)udb;
2813	}
2814
2815	return (rc);
2816}
2817
2818static int
2819free_eq(struct adapter *sc, struct sge_eq *eq)
2820{
2821	int rc;
2822
2823	if (eq->flags & EQ_ALLOCATED) {
2824		switch (eq->flags & EQ_TYPEMASK) {
2825		case EQ_CTRL:
2826			rc = -t4_ctrl_eq_free(sc, sc->mbox, sc->pf, 0,
2827			    eq->cntxt_id);
2828			break;
2829
2830		case EQ_ETH:
2831			rc = -t4_eth_eq_free(sc, sc->mbox, sc->pf, 0,
2832			    eq->cntxt_id);
2833			break;
2834
2835#ifdef TCP_OFFLOAD
2836		case EQ_OFLD:
2837			rc = -t4_ofld_eq_free(sc, sc->mbox, sc->pf, 0,
2838			    eq->cntxt_id);
2839			break;
2840#endif
2841
2842		default:
2843			panic("%s: invalid eq type %d.", __func__,
2844			    eq->flags & EQ_TYPEMASK);
2845		}
2846		if (rc != 0) {
2847			device_printf(sc->dev,
2848			    "failed to free egress queue (%d): %d\n",
2849			    eq->flags & EQ_TYPEMASK, rc);
2850			return (rc);
2851		}
2852		eq->flags &= ~EQ_ALLOCATED;
2853	}
2854
2855	free_ring(sc, eq->desc_tag, eq->desc_map, eq->ba, eq->desc);
2856
2857	if (mtx_initialized(&eq->eq_lock))
2858		mtx_destroy(&eq->eq_lock);
2859
2860	bzero(eq, sizeof(*eq));
2861	return (0);
2862}
2863
2864static int
2865alloc_wrq(struct adapter *sc, struct port_info *pi, struct sge_wrq *wrq,
2866    struct sysctl_oid *oid)
2867{
2868	int rc;
2869	struct sysctl_ctx_list *ctx = pi ? &pi->ctx : &sc->ctx;
2870	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2871
2872	rc = alloc_eq(sc, pi, &wrq->eq);
2873	if (rc)
2874		return (rc);
2875
2876	wrq->adapter = sc;
2877	STAILQ_INIT(&wrq->wr_list);
2878
2879	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2880	    &wrq->eq.cntxt_id, 0, "SGE context id of the queue");
2881	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
2882	    CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.cidx, 0, sysctl_uint16, "I",
2883	    "consumer index");
2884	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pidx",
2885	    CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.pidx, 0, sysctl_uint16, "I",
2886	    "producer index");
2887	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs", CTLFLAG_RD,
2888	    &wrq->tx_wrs, "# of work requests");
2889	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2890	    &wrq->no_desc, 0,
2891	    "# of times queue ran out of hardware descriptors");
2892	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2893	    &wrq->eq.unstalled, 0, "# of times queue recovered after stall");
2894
2895
2896	return (rc);
2897}
2898
2899static int
2900free_wrq(struct adapter *sc, struct sge_wrq *wrq)
2901{
2902	int rc;
2903
2904	rc = free_eq(sc, &wrq->eq);
2905	if (rc)
2906		return (rc);
2907
2908	bzero(wrq, sizeof(*wrq));
2909	return (0);
2910}
2911
2912static int
2913alloc_txq(struct port_info *pi, struct sge_txq *txq, int idx,
2914    struct sysctl_oid *oid)
2915{
2916	int rc;
2917	struct adapter *sc = pi->adapter;
2918	struct sge_eq *eq = &txq->eq;
2919	char name[16];
2920	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2921
2922	rc = alloc_eq(sc, pi, eq);
2923	if (rc)
2924		return (rc);
2925
2926	txq->ifp = pi->ifp;
2927
2928	txq->sdesc = malloc(eq->cap * sizeof(struct tx_sdesc), M_CXGBE,
2929	    M_ZERO | M_WAITOK);
2930	txq->br = buf_ring_alloc(eq->qsize, M_CXGBE, M_WAITOK, &eq->eq_lock);
2931
2932	rc = bus_dma_tag_create(sc->dmat, 1, 0, BUS_SPACE_MAXADDR,
2933	    BUS_SPACE_MAXADDR, NULL, NULL, 64 * 1024, TX_SGL_SEGS,
2934	    BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL, NULL, &txq->tx_tag);
2935	if (rc != 0) {
2936		device_printf(sc->dev,
2937		    "failed to create tx DMA tag: %d\n", rc);
2938		return (rc);
2939	}
2940
2941	/*
2942	 * We can stuff ~10 frames in an 8-descriptor txpkts WR (8 is the SGE
2943	 * limit for any WR).  txq->no_dmamap events shouldn't occur if maps is
2944	 * sized for the worst case.
2945	 */
2946	rc = t4_alloc_tx_maps(&txq->txmaps, txq->tx_tag, eq->qsize * 10 / 8,
2947	    M_WAITOK);
2948	if (rc != 0) {
2949		device_printf(sc->dev, "failed to setup tx DMA maps: %d\n", rc);
2950		return (rc);
2951	}
2952
2953	snprintf(name, sizeof(name), "%d", idx);
2954	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2955	    NULL, "tx queue");
2956	children = SYSCTL_CHILDREN(oid);
2957
2958	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2959	    &eq->cntxt_id, 0, "SGE context id of the queue");
2960	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2961	    CTLTYPE_INT | CTLFLAG_RD, &eq->cidx, 0, sysctl_uint16, "I",
2962	    "consumer index");
2963	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "pidx",
2964	    CTLTYPE_INT | CTLFLAG_RD, &eq->pidx, 0, sysctl_uint16, "I",
2965	    "producer index");
2966
2967	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txcsum", CTLFLAG_RD,
2968	    &txq->txcsum, "# of times hardware assisted with checksum");
2969	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_insertion",
2970	    CTLFLAG_RD, &txq->vlan_insertion,
2971	    "# of times hardware inserted 802.1Q tag");
2972	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "tso_wrs", CTLFLAG_RD,
2973	    &txq->tso_wrs, "# of TSO work requests");
2974	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "imm_wrs", CTLFLAG_RD,
2975	    &txq->imm_wrs, "# of work requests with immediate data");
2976	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "sgl_wrs", CTLFLAG_RD,
2977	    &txq->sgl_wrs, "# of work requests with direct SGL");
2978	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkt_wrs", CTLFLAG_RD,
2979	    &txq->txpkt_wrs, "# of txpkt work requests (one pkt/WR)");
2980	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_wrs", CTLFLAG_RD,
2981	    &txq->txpkts_wrs, "# of txpkts work requests (multiple pkts/WR)");
2982	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_pkts", CTLFLAG_RD,
2983	    &txq->txpkts_pkts, "# of frames tx'd using txpkts work requests");
2984
2985	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "br_drops", CTLFLAG_RD,
2986	    &txq->br->br_drops, "# of drops in the buf_ring for this queue");
2987	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_dmamap", CTLFLAG_RD,
2988	    &txq->no_dmamap, 0, "# of times txq ran out of DMA maps");
2989	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2990	    &txq->no_desc, 0, "# of times txq ran out of hardware descriptors");
2991	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "egr_update", CTLFLAG_RD,
2992	    &eq->egr_update, 0, "egress update notifications from the SGE");
2993	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2994	    &eq->unstalled, 0, "# of times txq recovered after stall");
2995
2996	return (rc);
2997}
2998
2999static int
3000free_txq(struct port_info *pi, struct sge_txq *txq)
3001{
3002	int rc;
3003	struct adapter *sc = pi->adapter;
3004	struct sge_eq *eq = &txq->eq;
3005
3006	rc = free_eq(sc, eq);
3007	if (rc)
3008		return (rc);
3009
3010	free(txq->sdesc, M_CXGBE);
3011
3012	if (txq->txmaps.maps)
3013		t4_free_tx_maps(&txq->txmaps, txq->tx_tag);
3014
3015	buf_ring_free(txq->br, M_CXGBE);
3016
3017	if (txq->tx_tag)
3018		bus_dma_tag_destroy(txq->tx_tag);
3019
3020	bzero(txq, sizeof(*txq));
3021	return (0);
3022}
3023
3024static void
3025oneseg_dma_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
3026{
3027	bus_addr_t *ba = arg;
3028
3029	KASSERT(nseg == 1,
3030	    ("%s meant for single segment mappings only.", __func__));
3031
3032	*ba = error ? 0 : segs->ds_addr;
3033}
3034
3035static inline bool
3036is_new_response(const struct sge_iq *iq, struct rsp_ctrl **ctrl)
3037{
3038	*ctrl = (void *)((uintptr_t)iq->cdesc +
3039	    (iq->esize - sizeof(struct rsp_ctrl)));
3040
3041	return (((*ctrl)->u.type_gen >> S_RSPD_GEN) == iq->gen);
3042}
3043
3044static inline void
3045iq_next(struct sge_iq *iq)
3046{
3047	iq->cdesc = (void *) ((uintptr_t)iq->cdesc + iq->esize);
3048	if (__predict_false(++iq->cidx == iq->qsize - 1)) {
3049		iq->cidx = 0;
3050		iq->gen ^= 1;
3051		iq->cdesc = iq->desc;
3052	}
3053}
3054
3055#define FL_HW_IDX(x) ((x) >> 3)
3056static inline void
3057ring_fl_db(struct adapter *sc, struct sge_fl *fl)
3058{
3059	int ndesc = fl->pending / 8;
3060	uint32_t v;
3061
3062	if (FL_HW_IDX(fl->pidx) == FL_HW_IDX(fl->cidx))
3063		ndesc--;	/* hold back one credit */
3064
3065	if (ndesc <= 0)
3066		return;		/* nothing to do */
3067
3068	v = F_DBPRIO | V_QID(fl->cntxt_id) | V_PIDX(ndesc);
3069	if (is_t5(sc))
3070		v |= F_DBTYPE;
3071
3072	wmb();
3073
3074	t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL), v);
3075	fl->pending -= ndesc * 8;
3076}
3077
3078/*
3079 * Fill up the freelist by upto nbufs and maybe ring its doorbell.
3080 *
3081 * Returns non-zero to indicate that it should be added to the list of starving
3082 * freelists.
3083 */
3084static int
3085refill_fl(struct adapter *sc, struct sge_fl *fl, int nbufs)
3086{
3087	__be64 *d = &fl->desc[fl->pidx];
3088	struct fl_sdesc *sd = &fl->sdesc[fl->pidx];
3089	bus_dma_tag_t tag;
3090	bus_addr_t pa;
3091	caddr_t cl;
3092	int rc;
3093
3094	FL_LOCK_ASSERT_OWNED(fl);
3095#ifdef INVARIANTS
3096	if (fl->flags & FL_BUF_PACKING)
3097		KASSERT(sd->tag_idx == 0,
3098		    ("%s: expected tag 0 but found tag %d at pidx %u instead",
3099		    __func__, sd->tag_idx, fl->pidx));
3100#endif
3101
3102	if (nbufs > fl->needed)
3103		nbufs = fl->needed;
3104
3105	while (nbufs--) {
3106
3107		if (sd->cl != NULL) {
3108
3109			KASSERT(*d == sd->ba_hwtag,
3110			    ("%s: recyling problem at pidx %d",
3111			    __func__, fl->pidx));
3112
3113			if (fl->flags & FL_BUF_PACKING) {
3114				u_int *refcount = find_buf_refcnt(sd->cl);
3115
3116				if (atomic_fetchadd_int(refcount, -1) == 1) {
3117					*refcount = 1;	/* reinstate */
3118					d++;
3119					goto recycled;
3120				}
3121				sd->cl = NULL;	/* gave up my reference */
3122			} else {
3123				/*
3124				 * This happens when a frame small enough to fit
3125				 * entirely in an mbuf was received in cl last
3126				 * time.  We'd held on to cl and can reuse it
3127				 * now.  Note that we reuse a cluster of the old
3128				 * size if fl->tag_idx is no longer the same as
3129				 * sd->tag_idx.
3130				 */
3131				d++;
3132				goto recycled;
3133			}
3134		}
3135
3136		if (__predict_false(fl->tag_idx != sd->tag_idx)) {
3137			bus_dmamap_t map;
3138			bus_dma_tag_t newtag = fl->tag[fl->tag_idx];
3139			bus_dma_tag_t oldtag = fl->tag[sd->tag_idx];
3140
3141			/*
3142			 * An MTU change can get us here.  Discard the old map
3143			 * which was created with the old tag, but only if
3144			 * we're able to get a new one.
3145			 */
3146			rc = bus_dmamap_create(newtag, 0, &map);
3147			if (rc == 0) {
3148				bus_dmamap_destroy(oldtag, sd->map);
3149				sd->map = map;
3150				sd->tag_idx = fl->tag_idx;
3151			}
3152		}
3153
3154		tag = fl->tag[sd->tag_idx];
3155
3156		cl = uma_zalloc(FL_BUF_ZONE(sc, sd->tag_idx), M_NOWAIT);
3157		if (cl == NULL)
3158			break;
3159		if (fl->flags & FL_BUF_PACKING) {
3160			*find_buf_refcnt(cl) = 1;
3161			cl += MSIZE;
3162		}
3163
3164		rc = bus_dmamap_load(tag, sd->map, cl,
3165		    FL_BUF_SIZE(sc, sd->tag_idx), oneseg_dma_callback, &pa, 0);
3166		if (rc != 0 || pa == 0) {
3167			fl->dmamap_failed++;
3168			if (fl->flags & FL_BUF_PACKING)
3169				cl -= MSIZE;
3170			uma_zfree(FL_BUF_ZONE(sc, sd->tag_idx), cl);
3171			break;
3172		}
3173
3174		sd->cl = cl;
3175		*d++ = htobe64(pa | FL_BUF_HWTAG(sc, sd->tag_idx));
3176
3177#ifdef INVARIANTS
3178		sd->ba_hwtag = htobe64(pa | FL_BUF_HWTAG(sc, sd->tag_idx));
3179#endif
3180
3181recycled:
3182		fl->pending++;
3183		fl->needed--;
3184		sd++;
3185		if (++fl->pidx == fl->cap) {
3186			fl->pidx = 0;
3187			sd = fl->sdesc;
3188			d = fl->desc;
3189		}
3190	}
3191
3192	if (fl->pending >= 8)
3193		ring_fl_db(sc, fl);
3194
3195	return (FL_RUNNING_LOW(fl) && !(fl->flags & FL_STARVING));
3196}
3197
3198/*
3199 * Attempt to refill all starving freelists.
3200 */
3201static void
3202refill_sfl(void *arg)
3203{
3204	struct adapter *sc = arg;
3205	struct sge_fl *fl, *fl_temp;
3206
3207	mtx_lock(&sc->sfl_lock);
3208	TAILQ_FOREACH_SAFE(fl, &sc->sfl, link, fl_temp) {
3209		FL_LOCK(fl);
3210		refill_fl(sc, fl, 64);
3211		if (FL_NOT_RUNNING_LOW(fl) || fl->flags & FL_DOOMED) {
3212			TAILQ_REMOVE(&sc->sfl, fl, link);
3213			fl->flags &= ~FL_STARVING;
3214		}
3215		FL_UNLOCK(fl);
3216	}
3217
3218	if (!TAILQ_EMPTY(&sc->sfl))
3219		callout_schedule(&sc->sfl_callout, hz / 5);
3220	mtx_unlock(&sc->sfl_lock);
3221}
3222
3223static int
3224alloc_fl_sdesc(struct sge_fl *fl)
3225{
3226	struct fl_sdesc *sd;
3227	bus_dma_tag_t tag;
3228	int i, rc;
3229
3230	fl->sdesc = malloc(fl->cap * sizeof(struct fl_sdesc), M_CXGBE,
3231	    M_ZERO | M_WAITOK);
3232
3233	tag = fl->tag[fl->tag_idx];
3234	sd = fl->sdesc;
3235	for (i = 0; i < fl->cap; i++, sd++) {
3236
3237		sd->tag_idx = fl->tag_idx;
3238		rc = bus_dmamap_create(tag, 0, &sd->map);
3239		if (rc != 0)
3240			goto failed;
3241	}
3242
3243	return (0);
3244failed:
3245	while (--i >= 0) {
3246		sd--;
3247		bus_dmamap_destroy(tag, sd->map);
3248	}
3249	KASSERT(sd == fl->sdesc, ("%s: EDOOFUS", __func__));
3250
3251	free(fl->sdesc, M_CXGBE);
3252	fl->sdesc = NULL;
3253
3254	return (rc);
3255}
3256
3257static void
3258free_fl_sdesc(struct adapter *sc, struct sge_fl *fl)
3259{
3260	struct fl_sdesc *sd;
3261	int i;
3262
3263	sd = fl->sdesc;
3264	for (i = 0; i < fl->cap; i++, sd++) {
3265
3266		if (sd->cl) {
3267			bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
3268			uma_zfree(FL_BUF_ZONE(sc, sd->tag_idx), sd->cl);
3269			sd->cl = NULL;
3270		}
3271
3272		bus_dmamap_destroy(fl->tag[sd->tag_idx], sd->map);
3273	}
3274
3275	free(fl->sdesc, M_CXGBE);
3276	fl->sdesc = NULL;
3277}
3278
3279int
3280t4_alloc_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag, int count,
3281    int flags)
3282{
3283	struct tx_map *txm;
3284	int i, rc;
3285
3286	txmaps->map_total = txmaps->map_avail = count;
3287	txmaps->map_cidx = txmaps->map_pidx = 0;
3288
3289	txmaps->maps = malloc(count * sizeof(struct tx_map), M_CXGBE,
3290	    M_ZERO | flags);
3291
3292	txm = txmaps->maps;
3293	for (i = 0; i < count; i++, txm++) {
3294		rc = bus_dmamap_create(tx_tag, 0, &txm->map);
3295		if (rc != 0)
3296			goto failed;
3297	}
3298
3299	return (0);
3300failed:
3301	while (--i >= 0) {
3302		txm--;
3303		bus_dmamap_destroy(tx_tag, txm->map);
3304	}
3305	KASSERT(txm == txmaps->maps, ("%s: EDOOFUS", __func__));
3306
3307	free(txmaps->maps, M_CXGBE);
3308	txmaps->maps = NULL;
3309
3310	return (rc);
3311}
3312
3313void
3314t4_free_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag)
3315{
3316	struct tx_map *txm;
3317	int i;
3318
3319	txm = txmaps->maps;
3320	for (i = 0; i < txmaps->map_total; i++, txm++) {
3321
3322		if (txm->m) {
3323			bus_dmamap_unload(tx_tag, txm->map);
3324			m_freem(txm->m);
3325			txm->m = NULL;
3326		}
3327
3328		bus_dmamap_destroy(tx_tag, txm->map);
3329	}
3330
3331	free(txmaps->maps, M_CXGBE);
3332	txmaps->maps = NULL;
3333}
3334
3335/*
3336 * We'll do immediate data tx for non-TSO, but only when not coalescing.  We're
3337 * willing to use upto 2 hardware descriptors which means a maximum of 96 bytes
3338 * of immediate data.
3339 */
3340#define IMM_LEN ( \
3341      2 * EQ_ESIZE \
3342    - sizeof(struct fw_eth_tx_pkt_wr) \
3343    - sizeof(struct cpl_tx_pkt_core))
3344
3345/*
3346 * Returns non-zero on failure, no need to cleanup anything in that case.
3347 *
3348 * Note 1: We always try to defrag the mbuf if required and return EFBIG only
3349 * if the resulting chain still won't fit in a tx descriptor.
3350 *
3351 * Note 2: We'll pullup the mbuf chain if TSO is requested and the first mbuf
3352 * does not have the TCP header in it.
3353 */
3354static int
3355get_pkt_sgl(struct sge_txq *txq, struct mbuf **fp, struct sgl *sgl,
3356    int sgl_only)
3357{
3358	struct mbuf *m = *fp;
3359	struct tx_maps *txmaps;
3360	struct tx_map *txm;
3361	int rc, defragged = 0, n;
3362
3363	TXQ_LOCK_ASSERT_OWNED(txq);
3364
3365	if (m->m_pkthdr.tso_segsz)
3366		sgl_only = 1;	/* Do not allow immediate data with LSO */
3367
3368start:	sgl->nsegs = 0;
3369
3370	if (m->m_pkthdr.len <= IMM_LEN && !sgl_only)
3371		return (0);	/* nsegs = 0 tells caller to use imm. tx */
3372
3373	txmaps = &txq->txmaps;
3374	if (txmaps->map_avail == 0) {
3375		txq->no_dmamap++;
3376		return (ENOMEM);
3377	}
3378	txm = &txmaps->maps[txmaps->map_pidx];
3379
3380	if (m->m_pkthdr.tso_segsz && m->m_len < 50) {
3381		*fp = m_pullup(m, 50);
3382		m = *fp;
3383		if (m == NULL)
3384			return (ENOBUFS);
3385	}
3386
3387	rc = bus_dmamap_load_mbuf_sg(txq->tx_tag, txm->map, m, sgl->seg,
3388	    &sgl->nsegs, BUS_DMA_NOWAIT);
3389	if (rc == EFBIG && defragged == 0) {
3390		m = m_defrag(m, M_NOWAIT);
3391		if (m == NULL)
3392			return (EFBIG);
3393
3394		defragged = 1;
3395		*fp = m;
3396		goto start;
3397	}
3398	if (rc != 0)
3399		return (rc);
3400
3401	txm->m = m;
3402	txmaps->map_avail--;
3403	if (++txmaps->map_pidx == txmaps->map_total)
3404		txmaps->map_pidx = 0;
3405
3406	KASSERT(sgl->nsegs > 0 && sgl->nsegs <= TX_SGL_SEGS,
3407	    ("%s: bad DMA mapping (%d segments)", __func__, sgl->nsegs));
3408
3409	/*
3410	 * Store the # of flits required to hold this frame's SGL in nflits.  An
3411	 * SGL has a (ULPTX header + len0, addr0) tuple optionally followed by
3412	 * multiple (len0 + len1, addr0, addr1) tuples.  If addr1 is not used
3413	 * then len1 must be set to 0.
3414	 */
3415	n = sgl->nsegs - 1;
3416	sgl->nflits = (3 * n) / 2 + (n & 1) + 2;
3417
3418	return (0);
3419}
3420
3421
3422/*
3423 * Releases all the txq resources used up in the specified sgl.
3424 */
3425static int
3426free_pkt_sgl(struct sge_txq *txq, struct sgl *sgl)
3427{
3428	struct tx_maps *txmaps;
3429	struct tx_map *txm;
3430
3431	TXQ_LOCK_ASSERT_OWNED(txq);
3432
3433	if (sgl->nsegs == 0)
3434		return (0);	/* didn't use any map */
3435
3436	txmaps = &txq->txmaps;
3437
3438	/* 1 pkt uses exactly 1 map, back it out */
3439
3440	txmaps->map_avail++;
3441	if (txmaps->map_pidx > 0)
3442		txmaps->map_pidx--;
3443	else
3444		txmaps->map_pidx = txmaps->map_total - 1;
3445
3446	txm = &txmaps->maps[txmaps->map_pidx];
3447	bus_dmamap_unload(txq->tx_tag, txm->map);
3448	txm->m = NULL;
3449
3450	return (0);
3451}
3452
3453static int
3454write_txpkt_wr(struct port_info *pi, struct sge_txq *txq, struct mbuf *m,
3455    struct sgl *sgl)
3456{
3457	struct sge_eq *eq = &txq->eq;
3458	struct fw_eth_tx_pkt_wr *wr;
3459	struct cpl_tx_pkt_core *cpl;
3460	uint32_t ctrl;	/* used in many unrelated places */
3461	uint64_t ctrl1;
3462	int nflits, ndesc, pktlen;
3463	struct tx_sdesc *txsd;
3464	caddr_t dst;
3465
3466	TXQ_LOCK_ASSERT_OWNED(txq);
3467
3468	pktlen = m->m_pkthdr.len;
3469
3470	/*
3471	 * Do we have enough flits to send this frame out?
3472	 */
3473	ctrl = sizeof(struct cpl_tx_pkt_core);
3474	if (m->m_pkthdr.tso_segsz) {
3475		nflits = TXPKT_LSO_WR_HDR;
3476		ctrl += sizeof(struct cpl_tx_pkt_lso_core);
3477	} else
3478		nflits = TXPKT_WR_HDR;
3479	if (sgl->nsegs > 0)
3480		nflits += sgl->nflits;
3481	else {
3482		nflits += howmany(pktlen, 8);
3483		ctrl += pktlen;
3484	}
3485	ndesc = howmany(nflits, 8);
3486	if (ndesc > eq->avail)
3487		return (ENOMEM);
3488
3489	/* Firmware work request header */
3490	wr = (void *)&eq->desc[eq->pidx];
3491	wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
3492	    V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));
3493	ctrl = V_FW_WR_LEN16(howmany(nflits, 2));
3494	if (eq->avail == ndesc) {
3495		if (!(eq->flags & EQ_CRFLUSHED)) {
3496			ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
3497			eq->flags |= EQ_CRFLUSHED;
3498		}
3499		eq->flags |= EQ_STALLED;
3500	}
3501
3502	wr->equiq_to_len16 = htobe32(ctrl);
3503	wr->r3 = 0;
3504
3505	if (m->m_pkthdr.tso_segsz) {
3506		struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
3507		struct ether_header *eh;
3508		void *l3hdr;
3509#if defined(INET) || defined(INET6)
3510		struct tcphdr *tcp;
3511#endif
3512		uint16_t eh_type;
3513
3514		ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) | F_LSO_FIRST_SLICE |
3515		    F_LSO_LAST_SLICE;
3516
3517		eh = mtod(m, struct ether_header *);
3518		eh_type = ntohs(eh->ether_type);
3519		if (eh_type == ETHERTYPE_VLAN) {
3520			struct ether_vlan_header *evh = (void *)eh;
3521
3522			ctrl |= V_LSO_ETHHDR_LEN(1);
3523			l3hdr = evh + 1;
3524			eh_type = ntohs(evh->evl_proto);
3525		} else
3526			l3hdr = eh + 1;
3527
3528		switch (eh_type) {
3529#ifdef INET6
3530		case ETHERTYPE_IPV6:
3531		{
3532			struct ip6_hdr *ip6 = l3hdr;
3533
3534			/*
3535			 * XXX-BZ For now we do not pretend to support
3536			 * IPv6 extension headers.
3537			 */
3538			KASSERT(ip6->ip6_nxt == IPPROTO_TCP, ("%s: CSUM_TSO "
3539			    "with ip6_nxt != TCP: %u", __func__, ip6->ip6_nxt));
3540			tcp = (struct tcphdr *)(ip6 + 1);
3541			ctrl |= F_LSO_IPV6;
3542			ctrl |= V_LSO_IPHDR_LEN(sizeof(*ip6) >> 2) |
3543			    V_LSO_TCPHDR_LEN(tcp->th_off);
3544			break;
3545		}
3546#endif
3547#ifdef INET
3548		case ETHERTYPE_IP:
3549		{
3550			struct ip *ip = l3hdr;
3551
3552			tcp = (void *)((uintptr_t)ip + ip->ip_hl * 4);
3553			ctrl |= V_LSO_IPHDR_LEN(ip->ip_hl) |
3554			    V_LSO_TCPHDR_LEN(tcp->th_off);
3555			break;
3556		}
3557#endif
3558		default:
3559			panic("%s: CSUM_TSO but no supported IP version "
3560			    "(0x%04x)", __func__, eh_type);
3561		}
3562
3563		lso->lso_ctrl = htobe32(ctrl);
3564		lso->ipid_ofst = htobe16(0);
3565		lso->mss = htobe16(m->m_pkthdr.tso_segsz);
3566		lso->seqno_offset = htobe32(0);
3567		lso->len = htobe32(pktlen);
3568
3569		cpl = (void *)(lso + 1);
3570
3571		txq->tso_wrs++;
3572	} else
3573		cpl = (void *)(wr + 1);
3574
3575	/* Checksum offload */
3576	ctrl1 = 0;
3577	if (!(m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO)))
3578		ctrl1 |= F_TXPKT_IPCSUM_DIS;
3579	if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
3580	    CSUM_TCP_IPV6 | CSUM_TSO)))
3581		ctrl1 |= F_TXPKT_L4CSUM_DIS;
3582	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3583	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3584		txq->txcsum++;	/* some hardware assistance provided */
3585
3586	/* VLAN tag insertion */
3587	if (m->m_flags & M_VLANTAG) {
3588		ctrl1 |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3589		txq->vlan_insertion++;
3590	}
3591
3592	/* CPL header */
3593	cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3594	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3595	cpl->pack = 0;
3596	cpl->len = htobe16(pktlen);
3597	cpl->ctrl1 = htobe64(ctrl1);
3598
3599	/* Software descriptor */
3600	txsd = &txq->sdesc[eq->pidx];
3601	txsd->desc_used = ndesc;
3602
3603	eq->pending += ndesc;
3604	eq->avail -= ndesc;
3605	eq->pidx += ndesc;
3606	if (eq->pidx >= eq->cap)
3607		eq->pidx -= eq->cap;
3608
3609	/* SGL */
3610	dst = (void *)(cpl + 1);
3611	if (sgl->nsegs > 0) {
3612		txsd->credits = 1;
3613		txq->sgl_wrs++;
3614		write_sgl_to_txd(eq, sgl, &dst);
3615	} else {
3616		txsd->credits = 0;
3617		txq->imm_wrs++;
3618		for (; m; m = m->m_next) {
3619			copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
3620#ifdef INVARIANTS
3621			pktlen -= m->m_len;
3622#endif
3623		}
3624#ifdef INVARIANTS
3625		KASSERT(pktlen == 0, ("%s: %d bytes left.", __func__, pktlen));
3626#endif
3627
3628	}
3629
3630	txq->txpkt_wrs++;
3631	return (0);
3632}
3633
3634/*
3635 * Returns 0 to indicate that m has been accepted into a coalesced tx work
3636 * request.  It has either been folded into txpkts or txpkts was flushed and m
3637 * has started a new coalesced work request (as the first frame in a fresh
3638 * txpkts).
3639 *
3640 * Returns non-zero to indicate a failure - caller is responsible for
3641 * transmitting m, if there was anything in txpkts it has been flushed.
3642 */
3643static int
3644add_to_txpkts(struct port_info *pi, struct sge_txq *txq, struct txpkts *txpkts,
3645    struct mbuf *m, struct sgl *sgl)
3646{
3647	struct sge_eq *eq = &txq->eq;
3648	int can_coalesce;
3649	struct tx_sdesc *txsd;
3650	int flits;
3651
3652	TXQ_LOCK_ASSERT_OWNED(txq);
3653
3654	KASSERT(sgl->nsegs, ("%s: can't coalesce imm data", __func__));
3655
3656	if (txpkts->npkt > 0) {
3657		flits = TXPKTS_PKT_HDR + sgl->nflits;
3658		can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
3659		    txpkts->nflits + flits <= TX_WR_FLITS &&
3660		    txpkts->nflits + flits <= eq->avail * 8 &&
3661		    txpkts->plen + m->m_pkthdr.len < 65536;
3662
3663		if (can_coalesce) {
3664			txpkts->npkt++;
3665			txpkts->nflits += flits;
3666			txpkts->plen += m->m_pkthdr.len;
3667
3668			txsd = &txq->sdesc[eq->pidx];
3669			txsd->credits++;
3670
3671			return (0);
3672		}
3673
3674		/*
3675		 * Couldn't coalesce m into txpkts.  The first order of business
3676		 * is to send txpkts on its way.  Then we'll revisit m.
3677		 */
3678		write_txpkts_wr(txq, txpkts);
3679	}
3680
3681	/*
3682	 * Check if we can start a new coalesced tx work request with m as
3683	 * the first packet in it.
3684	 */
3685
3686	KASSERT(txpkts->npkt == 0, ("%s: txpkts not empty", __func__));
3687
3688	flits = TXPKTS_WR_HDR + sgl->nflits;
3689	can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
3690	    flits <= eq->avail * 8 && flits <= TX_WR_FLITS;
3691
3692	if (can_coalesce == 0)
3693		return (EINVAL);
3694
3695	/*
3696	 * Start a fresh coalesced tx WR with m as the first frame in it.
3697	 */
3698	txpkts->npkt = 1;
3699	txpkts->nflits = flits;
3700	txpkts->flitp = &eq->desc[eq->pidx].flit[2];
3701	txpkts->plen = m->m_pkthdr.len;
3702
3703	txsd = &txq->sdesc[eq->pidx];
3704	txsd->credits = 1;
3705
3706	return (0);
3707}
3708
3709/*
3710 * Note that write_txpkts_wr can never run out of hardware descriptors (but
3711 * write_txpkt_wr can).  add_to_txpkts ensures that a frame is accepted for
3712 * coalescing only if sufficient hardware descriptors are available.
3713 */
3714static void
3715write_txpkts_wr(struct sge_txq *txq, struct txpkts *txpkts)
3716{
3717	struct sge_eq *eq = &txq->eq;
3718	struct fw_eth_tx_pkts_wr *wr;
3719	struct tx_sdesc *txsd;
3720	uint32_t ctrl;
3721	int ndesc;
3722
3723	TXQ_LOCK_ASSERT_OWNED(txq);
3724
3725	ndesc = howmany(txpkts->nflits, 8);
3726
3727	wr = (void *)&eq->desc[eq->pidx];
3728	wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
3729	ctrl = V_FW_WR_LEN16(howmany(txpkts->nflits, 2));
3730	if (eq->avail == ndesc) {
3731		if (!(eq->flags & EQ_CRFLUSHED)) {
3732			ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
3733			eq->flags |= EQ_CRFLUSHED;
3734		}
3735		eq->flags |= EQ_STALLED;
3736	}
3737	wr->equiq_to_len16 = htobe32(ctrl);
3738	wr->plen = htobe16(txpkts->plen);
3739	wr->npkt = txpkts->npkt;
3740	wr->r3 = wr->type = 0;
3741
3742	/* Everything else already written */
3743
3744	txsd = &txq->sdesc[eq->pidx];
3745	txsd->desc_used = ndesc;
3746
3747	KASSERT(eq->avail >= ndesc, ("%s: out of descriptors", __func__));
3748
3749	eq->pending += ndesc;
3750	eq->avail -= ndesc;
3751	eq->pidx += ndesc;
3752	if (eq->pidx >= eq->cap)
3753		eq->pidx -= eq->cap;
3754
3755	txq->txpkts_pkts += txpkts->npkt;
3756	txq->txpkts_wrs++;
3757	txpkts->npkt = 0;	/* emptied */
3758}
3759
3760static inline void
3761write_ulp_cpl_sgl(struct port_info *pi, struct sge_txq *txq,
3762    struct txpkts *txpkts, struct mbuf *m, struct sgl *sgl)
3763{
3764	struct ulp_txpkt *ulpmc;
3765	struct ulptx_idata *ulpsc;
3766	struct cpl_tx_pkt_core *cpl;
3767	struct sge_eq *eq = &txq->eq;
3768	uintptr_t flitp, start, end;
3769	uint64_t ctrl;
3770	caddr_t dst;
3771
3772	KASSERT(txpkts->npkt > 0, ("%s: txpkts is empty", __func__));
3773
3774	start = (uintptr_t)eq->desc;
3775	end = (uintptr_t)eq->spg;
3776
3777	/* Checksum offload */
3778	ctrl = 0;
3779	if (!(m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO)))
3780		ctrl |= F_TXPKT_IPCSUM_DIS;
3781	if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
3782	    CSUM_TCP_IPV6 | CSUM_TSO)))
3783		ctrl |= F_TXPKT_L4CSUM_DIS;
3784	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3785	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3786		txq->txcsum++;	/* some hardware assistance provided */
3787
3788	/* VLAN tag insertion */
3789	if (m->m_flags & M_VLANTAG) {
3790		ctrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3791		txq->vlan_insertion++;
3792	}
3793
3794	/*
3795	 * The previous packet's SGL must have ended at a 16 byte boundary (this
3796	 * is required by the firmware/hardware).  It follows that flitp cannot
3797	 * wrap around between the ULPTX master command and ULPTX subcommand (8
3798	 * bytes each), and that it can not wrap around in the middle of the
3799	 * cpl_tx_pkt_core either.
3800	 */
3801	flitp = (uintptr_t)txpkts->flitp;
3802	KASSERT((flitp & 0xf) == 0,
3803	    ("%s: last SGL did not end at 16 byte boundary: %p",
3804	    __func__, txpkts->flitp));
3805
3806	/* ULP master command */
3807	ulpmc = (void *)flitp;
3808	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0) |
3809	    V_ULP_TXPKT_FID(eq->iqid));
3810	ulpmc->len = htonl(howmany(sizeof(*ulpmc) + sizeof(*ulpsc) +
3811	    sizeof(*cpl) + 8 * sgl->nflits, 16));
3812
3813	/* ULP subcommand */
3814	ulpsc = (void *)(ulpmc + 1);
3815	ulpsc->cmd_more = htobe32(V_ULPTX_CMD((u32)ULP_TX_SC_IMM) |
3816	    F_ULP_TX_SC_MORE);
3817	ulpsc->len = htobe32(sizeof(struct cpl_tx_pkt_core));
3818
3819	flitp += sizeof(*ulpmc) + sizeof(*ulpsc);
3820	if (flitp == end)
3821		flitp = start;
3822
3823	/* CPL_TX_PKT */
3824	cpl = (void *)flitp;
3825	cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3826	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3827	cpl->pack = 0;
3828	cpl->len = htobe16(m->m_pkthdr.len);
3829	cpl->ctrl1 = htobe64(ctrl);
3830
3831	flitp += sizeof(*cpl);
3832	if (flitp == end)
3833		flitp = start;
3834
3835	/* SGL for this frame */
3836	dst = (caddr_t)flitp;
3837	txpkts->nflits += write_sgl_to_txd(eq, sgl, &dst);
3838	txpkts->flitp = (void *)dst;
3839
3840	KASSERT(((uintptr_t)dst & 0xf) == 0,
3841	    ("%s: SGL ends at %p (not a 16 byte boundary)", __func__, dst));
3842}
3843
3844/*
3845 * If the SGL ends on an address that is not 16 byte aligned, this function will
3846 * add a 0 filled flit at the end.  It returns 1 in that case.
3847 */
3848static int
3849write_sgl_to_txd(struct sge_eq *eq, struct sgl *sgl, caddr_t *to)
3850{
3851	__be64 *flitp, *end;
3852	struct ulptx_sgl *usgl;
3853	bus_dma_segment_t *seg;
3854	int i, padded;
3855
3856	KASSERT(sgl->nsegs > 0 && sgl->nflits > 0,
3857	    ("%s: bad SGL - nsegs=%d, nflits=%d",
3858	    __func__, sgl->nsegs, sgl->nflits));
3859
3860	KASSERT(((uintptr_t)(*to) & 0xf) == 0,
3861	    ("%s: SGL must start at a 16 byte boundary: %p", __func__, *to));
3862
3863	flitp = (__be64 *)(*to);
3864	end = flitp + sgl->nflits;
3865	seg = &sgl->seg[0];
3866	usgl = (void *)flitp;
3867
3868	/*
3869	 * We start at a 16 byte boundary somewhere inside the tx descriptor
3870	 * ring, so we're at least 16 bytes away from the status page.  There is
3871	 * no chance of a wrap around in the middle of usgl (which is 16 bytes).
3872	 */
3873
3874	usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
3875	    V_ULPTX_NSGE(sgl->nsegs));
3876	usgl->len0 = htobe32(seg->ds_len);
3877	usgl->addr0 = htobe64(seg->ds_addr);
3878	seg++;
3879
3880	if ((uintptr_t)end <= (uintptr_t)eq->spg) {
3881
3882		/* Won't wrap around at all */
3883
3884		for (i = 0; i < sgl->nsegs - 1; i++, seg++) {
3885			usgl->sge[i / 2].len[i & 1] = htobe32(seg->ds_len);
3886			usgl->sge[i / 2].addr[i & 1] = htobe64(seg->ds_addr);
3887		}
3888		if (i & 1)
3889			usgl->sge[i / 2].len[1] = htobe32(0);
3890	} else {
3891
3892		/* Will wrap somewhere in the rest of the SGL */
3893
3894		/* 2 flits already written, write the rest flit by flit */
3895		flitp = (void *)(usgl + 1);
3896		for (i = 0; i < sgl->nflits - 2; i++) {
3897			if ((uintptr_t)flitp == (uintptr_t)eq->spg)
3898				flitp = (void *)eq->desc;
3899			*flitp++ = get_flit(seg, sgl->nsegs - 1, i);
3900		}
3901		end = flitp;
3902	}
3903
3904	if ((uintptr_t)end & 0xf) {
3905		*(uint64_t *)end = 0;
3906		end++;
3907		padded = 1;
3908	} else
3909		padded = 0;
3910
3911	if ((uintptr_t)end == (uintptr_t)eq->spg)
3912		*to = (void *)eq->desc;
3913	else
3914		*to = (void *)end;
3915
3916	return (padded);
3917}
3918
3919static inline void
3920copy_to_txd(struct sge_eq *eq, caddr_t from, caddr_t *to, int len)
3921{
3922	if (__predict_true((uintptr_t)(*to) + len <= (uintptr_t)eq->spg)) {
3923		bcopy(from, *to, len);
3924		(*to) += len;
3925	} else {
3926		int portion = (uintptr_t)eq->spg - (uintptr_t)(*to);
3927
3928		bcopy(from, *to, portion);
3929		from += portion;
3930		portion = len - portion;	/* remaining */
3931		bcopy(from, (void *)eq->desc, portion);
3932		(*to) = (caddr_t)eq->desc + portion;
3933	}
3934}
3935
3936static inline void
3937ring_eq_db(struct adapter *sc, struct sge_eq *eq)
3938{
3939	u_int db, pending;
3940
3941	db = eq->doorbells;
3942	pending = eq->pending;
3943	if (pending > 1)
3944		clrbit(&db, DOORBELL_WCWR);
3945	eq->pending = 0;
3946	wmb();
3947
3948	switch (ffs(db) - 1) {
3949	case DOORBELL_UDB:
3950		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(pending));
3951		return;
3952
3953	case DOORBELL_WCWR: {
3954		volatile uint64_t *dst, *src;
3955		int i;
3956
3957		/*
3958		 * Queues whose 128B doorbell segment fits in the page do not
3959		 * use relative qid (udb_qid is always 0).  Only queues with
3960		 * doorbell segments can do WCWR.
3961		 */
3962		KASSERT(eq->udb_qid == 0 && pending == 1,
3963		    ("%s: inappropriate doorbell (0x%x, %d, %d) for eq %p",
3964		    __func__, eq->doorbells, pending, eq->pidx, eq));
3965
3966		dst = (volatile void *)((uintptr_t)eq->udb + UDBS_WR_OFFSET -
3967		    UDBS_DB_OFFSET);
3968		i = eq->pidx ? eq->pidx - 1 : eq->cap - 1;
3969		src = (void *)&eq->desc[i];
3970		while (src != (void *)&eq->desc[i + 1])
3971			*dst++ = *src++;
3972		wmb();
3973		return;
3974	}
3975
3976	case DOORBELL_UDBWC:
3977		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(pending));
3978		wmb();
3979		return;
3980
3981	case DOORBELL_KDB:
3982		t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL),
3983		    V_QID(eq->cntxt_id) | V_PIDX(pending));
3984		return;
3985	}
3986}
3987
3988static inline int
3989reclaimable(struct sge_eq *eq)
3990{
3991	unsigned int cidx;
3992
3993	cidx = eq->spg->cidx;	/* stable snapshot */
3994	cidx = be16toh(cidx);
3995
3996	if (cidx >= eq->cidx)
3997		return (cidx - eq->cidx);
3998	else
3999		return (cidx + eq->cap - eq->cidx);
4000}
4001
4002/*
4003 * There are "can_reclaim" tx descriptors ready to be reclaimed.  Reclaim as
4004 * many as possible but stop when there are around "n" mbufs to free.
4005 *
4006 * The actual number reclaimed is provided as the return value.
4007 */
4008static int
4009reclaim_tx_descs(struct sge_txq *txq, int can_reclaim, int n)
4010{
4011	struct tx_sdesc *txsd;
4012	struct tx_maps *txmaps;
4013	struct tx_map *txm;
4014	unsigned int reclaimed, maps;
4015	struct sge_eq *eq = &txq->eq;
4016
4017	TXQ_LOCK_ASSERT_OWNED(txq);
4018
4019	if (can_reclaim == 0)
4020		can_reclaim = reclaimable(eq);
4021
4022	maps = reclaimed = 0;
4023	while (can_reclaim && maps < n) {
4024		int ndesc;
4025
4026		txsd = &txq->sdesc[eq->cidx];
4027		ndesc = txsd->desc_used;
4028
4029		/* Firmware doesn't return "partial" credits. */
4030		KASSERT(can_reclaim >= ndesc,
4031		    ("%s: unexpected number of credits: %d, %d",
4032		    __func__, can_reclaim, ndesc));
4033
4034		maps += txsd->credits;
4035
4036		reclaimed += ndesc;
4037		can_reclaim -= ndesc;
4038
4039		eq->cidx += ndesc;
4040		if (__predict_false(eq->cidx >= eq->cap))
4041			eq->cidx -= eq->cap;
4042	}
4043
4044	txmaps = &txq->txmaps;
4045	txm = &txmaps->maps[txmaps->map_cidx];
4046	if (maps)
4047		prefetch(txm->m);
4048
4049	eq->avail += reclaimed;
4050	KASSERT(eq->avail < eq->cap,	/* avail tops out at (cap - 1) */
4051	    ("%s: too many descriptors available", __func__));
4052
4053	txmaps->map_avail += maps;
4054	KASSERT(txmaps->map_avail <= txmaps->map_total,
4055	    ("%s: too many maps available", __func__));
4056
4057	while (maps--) {
4058		struct tx_map *next;
4059
4060		next = txm + 1;
4061		if (__predict_false(txmaps->map_cidx + 1 == txmaps->map_total))
4062			next = txmaps->maps;
4063		prefetch(next->m);
4064
4065		bus_dmamap_unload(txq->tx_tag, txm->map);
4066		m_freem(txm->m);
4067		txm->m = NULL;
4068
4069		txm = next;
4070		if (__predict_false(++txmaps->map_cidx == txmaps->map_total))
4071			txmaps->map_cidx = 0;
4072	}
4073
4074	return (reclaimed);
4075}
4076
4077static void
4078write_eqflush_wr(struct sge_eq *eq)
4079{
4080	struct fw_eq_flush_wr *wr;
4081
4082	EQ_LOCK_ASSERT_OWNED(eq);
4083	KASSERT(eq->avail > 0, ("%s: no descriptors left.", __func__));
4084	KASSERT(!(eq->flags & EQ_CRFLUSHED), ("%s: flushed already", __func__));
4085
4086	wr = (void *)&eq->desc[eq->pidx];
4087	bzero(wr, sizeof(*wr));
4088	wr->opcode = FW_EQ_FLUSH_WR;
4089	wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(sizeof(*wr) / 16) |
4090	    F_FW_WR_EQUEQ | F_FW_WR_EQUIQ);
4091
4092	eq->flags |= (EQ_CRFLUSHED | EQ_STALLED);
4093	eq->pending++;
4094	eq->avail--;
4095	if (++eq->pidx == eq->cap)
4096		eq->pidx = 0;
4097}
4098
4099static __be64
4100get_flit(bus_dma_segment_t *sgl, int nsegs, int idx)
4101{
4102	int i = (idx / 3) * 2;
4103
4104	switch (idx % 3) {
4105	case 0: {
4106		__be64 rc;
4107
4108		rc = htobe32(sgl[i].ds_len);
4109		if (i + 1 < nsegs)
4110			rc |= (uint64_t)htobe32(sgl[i + 1].ds_len) << 32;
4111
4112		return (rc);
4113	}
4114	case 1:
4115		return htobe64(sgl[i].ds_addr);
4116	case 2:
4117		return htobe64(sgl[i + 1].ds_addr);
4118	}
4119
4120	return (0);
4121}
4122
4123/*
4124 * Find an SGE FL buffer size to use for the given bufsize.  Look for the the
4125 * smallest size that is large enough to hold bufsize or pick the largest size
4126 * if all sizes are less than bufsize.
4127 */
4128static void
4129set_fl_tag_idx(struct adapter *sc, struct sge_fl *fl, int bufsize)
4130{
4131	int i, largest, best, delta, start;
4132
4133	if (fl->flags & FL_BUF_PACKING) {
4134		fl->tag_idx = 0;	/* first tag is the one for packing */
4135		return;
4136	}
4137
4138	start = sc->flags & BUF_PACKING_OK ? 1 : 0;
4139	delta = FL_BUF_SIZE(sc, start) - bufsize;
4140	if (delta == 0) {
4141		fl->tag_idx = start;	/* ideal fit, look no further */
4142		return;
4143	}
4144	best = start;
4145	largest = start;
4146
4147	for (i = start + 1; i < FL_BUF_SIZES(sc); i++) {
4148		int d, fl_buf_size;
4149
4150		fl_buf_size = FL_BUF_SIZE(sc, i);
4151		d = fl_buf_size - bufsize;
4152
4153		if (d == 0) {
4154			fl->tag_idx = i;	/* ideal fit, look no further */
4155			return;
4156		}
4157		if (fl_buf_size > FL_BUF_SIZE(sc, largest))
4158			largest = i;
4159		if (d > 0 && (delta < 0 || delta > d)) {
4160			delta = d;
4161			best = i;
4162		}
4163	}
4164
4165	if (delta > 0)
4166		fl->tag_idx = best;	/* Found a buf bigger than bufsize */
4167	else
4168		fl->tag_idx = largest;	/* No buf large enough for bufsize */
4169}
4170
4171static void
4172add_fl_to_sfl(struct adapter *sc, struct sge_fl *fl)
4173{
4174	mtx_lock(&sc->sfl_lock);
4175	FL_LOCK(fl);
4176	if ((fl->flags & FL_DOOMED) == 0) {
4177		fl->flags |= FL_STARVING;
4178		TAILQ_INSERT_TAIL(&sc->sfl, fl, link);
4179		callout_reset(&sc->sfl_callout, hz / 5, refill_sfl, sc);
4180	}
4181	FL_UNLOCK(fl);
4182	mtx_unlock(&sc->sfl_lock);
4183}
4184
4185static int
4186handle_sge_egr_update(struct sge_iq *iq, const struct rss_header *rss,
4187    struct mbuf *m)
4188{
4189	const struct cpl_sge_egr_update *cpl = (const void *)(rss + 1);
4190	unsigned int qid = G_EGR_QID(ntohl(cpl->opcode_qid));
4191	struct adapter *sc = iq->adapter;
4192	struct sge *s = &sc->sge;
4193	struct sge_eq *eq;
4194
4195	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
4196	    rss->opcode));
4197
4198	eq = s->eqmap[qid - s->eq_start];
4199	EQ_LOCK(eq);
4200	KASSERT(eq->flags & EQ_CRFLUSHED,
4201	    ("%s: unsolicited egress update", __func__));
4202	eq->flags &= ~EQ_CRFLUSHED;
4203	eq->egr_update++;
4204
4205	if (__predict_false(eq->flags & EQ_DOOMED))
4206		wakeup_one(eq);
4207	else if (eq->flags & EQ_STALLED && can_resume_tx(eq))
4208		taskqueue_enqueue(sc->tq[eq->tx_chan], &eq->tx_task);
4209	EQ_UNLOCK(eq);
4210
4211	return (0);
4212}
4213
4214/* handle_fw_msg works for both fw4_msg and fw6_msg because this is valid */
4215CTASSERT(offsetof(struct cpl_fw4_msg, data) == \
4216    offsetof(struct cpl_fw6_msg, data));
4217
4218static int
4219handle_fw_msg(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
4220{
4221	struct adapter *sc = iq->adapter;
4222	const struct cpl_fw6_msg *cpl = (const void *)(rss + 1);
4223
4224	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
4225	    rss->opcode));
4226
4227	if (cpl->type == FW_TYPE_RSSCPL || cpl->type == FW6_TYPE_RSSCPL) {
4228		const struct rss_header *rss2;
4229
4230		rss2 = (const struct rss_header *)&cpl->data[0];
4231		return (sc->cpl_handler[rss2->opcode](iq, rss2, m));
4232	}
4233
4234	return (sc->fw_msg_handler[cpl->type](sc, &cpl->data[0]));
4235}
4236
4237static int
4238sysctl_uint16(SYSCTL_HANDLER_ARGS)
4239{
4240	uint16_t *id = arg1;
4241	int i = *id;
4242
4243	return sysctl_handle_int(oidp, &i, 0, req);
4244}
4245