xref: /freebsd/sys/dev/cxgbe/t4_sge.c (revision cc759c1995237364b02829feb9e5fdd1e6ed2c5b)
1 /*-
2  * Copyright (c) 2011 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 
34 #include <sys/types.h>
35 #include <sys/mbuf.h>
36 #include <sys/socket.h>
37 #include <sys/kernel.h>
38 #include <sys/kdb.h>
39 #include <sys/malloc.h>
40 #include <sys/queue.h>
41 #include <sys/taskqueue.h>
42 #include <sys/sysctl.h>
43 #include <sys/smp.h>
44 #include <net/bpf.h>
45 #include <net/ethernet.h>
46 #include <net/if.h>
47 #include <net/if_vlan_var.h>
48 #include <netinet/in.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip6.h>
51 #include <netinet/tcp.h>
52 
53 #include "common/common.h"
54 #include "common/t4_regs.h"
55 #include "common/t4_regs_values.h"
56 #include "common/t4_msg.h"
57 
58 struct fl_buf_info {
59 	int size;
60 	int type;
61 	uma_zone_t zone;
62 };
63 
64 /* Filled up by t4_sge_modload */
65 static struct fl_buf_info fl_buf_info[FL_BUF_SIZES];
66 
67 #define FL_BUF_SIZE(x)	(fl_buf_info[x].size)
68 #define FL_BUF_TYPE(x)	(fl_buf_info[x].type)
69 #define FL_BUF_ZONE(x)	(fl_buf_info[x].zone)
70 
71 #ifdef T4_PKT_TIMESTAMP
72 #define RX_COPY_THRESHOLD (MINCLSIZE - 8)
73 #else
74 #define RX_COPY_THRESHOLD MINCLSIZE
75 #endif
76 
77 /*
78  * Ethernet frames are DMA'd at this byte offset into the freelist buffer.
79  * 0-7 are valid values.
80  */
81 static int fl_pktshift = 2;
82 TUNABLE_INT("hw.cxgbe.fl_pktshift", &fl_pktshift);
83 
84 /*
85  * Pad ethernet payload up to this boundary.
86  * -1: driver should figure out a good value.
87  *  Any power of 2, from 32 to 4096 (both inclusive) is a valid value.
88  */
89 static int fl_pad = -1;
90 TUNABLE_INT("hw.cxgbe.fl_pad", &fl_pad);
91 
92 /*
93  * Status page length.
94  * -1: driver should figure out a good value.
95  *  64 or 128 are the only other valid values.
96  */
97 static int spg_len = -1;
98 TUNABLE_INT("hw.cxgbe.spg_len", &spg_len);
99 
100 /*
101  * Congestion drops.
102  * -1: no congestion feedback (not recommended).
103  *  0: backpressure the channel instead of dropping packets right away.
104  *  1: no backpressure, drop packets for the congested queue immediately.
105  */
106 static int cong_drop = 0;
107 TUNABLE_INT("hw.cxgbe.cong_drop", &cong_drop);
108 
109 /* Used to track coalesced tx work request */
110 struct txpkts {
111 	uint64_t *flitp;	/* ptr to flit where next pkt should start */
112 	uint8_t npkt;		/* # of packets in this work request */
113 	uint8_t nflits;		/* # of flits used by this work request */
114 	uint16_t plen;		/* total payload (sum of all packets) */
115 };
116 
117 /* A packet's SGL.  This + m_pkthdr has all info needed for tx */
118 struct sgl {
119 	int nsegs;		/* # of segments in the SGL, 0 means imm. tx */
120 	int nflits;		/* # of flits needed for the SGL */
121 	bus_dma_segment_t seg[TX_SGL_SEGS];
122 };
123 
124 static int service_iq(struct sge_iq *, int);
125 static struct mbuf *get_fl_payload(struct adapter *, struct sge_fl *, uint32_t,
126     int *);
127 static int t4_eth_rx(struct sge_iq *, const struct rss_header *, struct mbuf *);
128 static inline void init_iq(struct sge_iq *, struct adapter *, int, int, int,
129     int);
130 static inline void init_fl(struct sge_fl *, int, int, char *);
131 static inline void init_eq(struct sge_eq *, int, int, uint8_t, uint16_t,
132     char *);
133 static int alloc_ring(struct adapter *, size_t, bus_dma_tag_t *, bus_dmamap_t *,
134     bus_addr_t *, void **);
135 static int free_ring(struct adapter *, bus_dma_tag_t, bus_dmamap_t, bus_addr_t,
136     void *);
137 static int alloc_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *,
138     int, int);
139 static int free_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *);
140 static int alloc_fwq(struct adapter *);
141 static int free_fwq(struct adapter *);
142 static int alloc_mgmtq(struct adapter *);
143 static int free_mgmtq(struct adapter *);
144 static int alloc_rxq(struct port_info *, struct sge_rxq *, int, int,
145     struct sysctl_oid *);
146 static int free_rxq(struct port_info *, struct sge_rxq *);
147 #ifdef TCP_OFFLOAD
148 static int alloc_ofld_rxq(struct port_info *, struct sge_ofld_rxq *, int, int,
149     struct sysctl_oid *);
150 static int free_ofld_rxq(struct port_info *, struct sge_ofld_rxq *);
151 #endif
152 static int ctrl_eq_alloc(struct adapter *, struct sge_eq *);
153 static int eth_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
154 #ifdef TCP_OFFLOAD
155 static int ofld_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
156 #endif
157 static int alloc_eq(struct adapter *, struct port_info *, struct sge_eq *);
158 static int free_eq(struct adapter *, struct sge_eq *);
159 static int alloc_wrq(struct adapter *, struct port_info *, struct sge_wrq *,
160     struct sysctl_oid *);
161 static int free_wrq(struct adapter *, struct sge_wrq *);
162 static int alloc_txq(struct port_info *, struct sge_txq *, int,
163     struct sysctl_oid *);
164 static int free_txq(struct port_info *, struct sge_txq *);
165 static void oneseg_dma_callback(void *, bus_dma_segment_t *, int, int);
166 static inline bool is_new_response(const struct sge_iq *, struct rsp_ctrl **);
167 static inline void iq_next(struct sge_iq *);
168 static inline void ring_fl_db(struct adapter *, struct sge_fl *);
169 static int refill_fl(struct adapter *, struct sge_fl *, int);
170 static void refill_sfl(void *);
171 static int alloc_fl_sdesc(struct sge_fl *);
172 static void free_fl_sdesc(struct sge_fl *);
173 static void set_fl_tag_idx(struct sge_fl *, int);
174 static void add_fl_to_sfl(struct adapter *, struct sge_fl *);
175 
176 static int get_pkt_sgl(struct sge_txq *, struct mbuf **, struct sgl *, int);
177 static int free_pkt_sgl(struct sge_txq *, struct sgl *);
178 static int write_txpkt_wr(struct port_info *, struct sge_txq *, struct mbuf *,
179     struct sgl *);
180 static int add_to_txpkts(struct port_info *, struct sge_txq *, struct txpkts *,
181     struct mbuf *, struct sgl *);
182 static void write_txpkts_wr(struct sge_txq *, struct txpkts *);
183 static inline void write_ulp_cpl_sgl(struct port_info *, struct sge_txq *,
184     struct txpkts *, struct mbuf *, struct sgl *);
185 static int write_sgl_to_txd(struct sge_eq *, struct sgl *, caddr_t *);
186 static inline void copy_to_txd(struct sge_eq *, caddr_t, caddr_t *, int);
187 static inline void ring_eq_db(struct adapter *, struct sge_eq *);
188 static inline int reclaimable(struct sge_eq *);
189 static int reclaim_tx_descs(struct sge_txq *, int, int);
190 static void write_eqflush_wr(struct sge_eq *);
191 static __be64 get_flit(bus_dma_segment_t *, int, int);
192 static int handle_sge_egr_update(struct sge_iq *, const struct rss_header *,
193     struct mbuf *);
194 static int handle_fw_msg(struct sge_iq *, const struct rss_header *,
195     struct mbuf *);
196 
197 static int sysctl_uint16(SYSCTL_HANDLER_ARGS);
198 
199 #if defined(__i386__) || defined(__amd64__)
200 extern u_int cpu_clflush_line_size;
201 #endif
202 
203 /*
204  * Called on MOD_LOAD.  Fills up fl_buf_info[] and validates/calculates the SGE
205  * tunables.
206  */
207 void
208 t4_sge_modload(void)
209 {
210 	int i;
211 	int bufsize[FL_BUF_SIZES] = {
212 		MCLBYTES,
213 #if MJUMPAGESIZE != MCLBYTES
214 		MJUMPAGESIZE,
215 #endif
216 		MJUM9BYTES,
217 		MJUM16BYTES
218 	};
219 
220 	for (i = 0; i < FL_BUF_SIZES; i++) {
221 		FL_BUF_SIZE(i) = bufsize[i];
222 		FL_BUF_TYPE(i) = m_gettype(bufsize[i]);
223 		FL_BUF_ZONE(i) = m_getzone(bufsize[i]);
224 	}
225 
226 	if (fl_pktshift < 0 || fl_pktshift > 7) {
227 		printf("Invalid hw.cxgbe.fl_pktshift value (%d),"
228 		    " using 2 instead.\n", fl_pktshift);
229 		fl_pktshift = 2;
230 	}
231 
232 	if (fl_pad < 32 || fl_pad > 4096 || !powerof2(fl_pad)) {
233 		int pad;
234 
235 #if defined(__i386__) || defined(__amd64__)
236 		pad = max(cpu_clflush_line_size, 32);
237 #else
238 		pad = max(CACHE_LINE_SIZE, 32);
239 #endif
240 		pad = min(pad, 4096);
241 
242 		if (fl_pad != -1) {
243 			printf("Invalid hw.cxgbe.fl_pad value (%d),"
244 			    " using %d instead.\n", fl_pad, pad);
245 		}
246 		fl_pad = pad;
247 	}
248 
249 	if (spg_len != 64 && spg_len != 128) {
250 		int len;
251 
252 #if defined(__i386__) || defined(__amd64__)
253 		len = cpu_clflush_line_size > 64 ? 128 : 64;
254 #else
255 		len = 64;
256 #endif
257 		if (spg_len != -1) {
258 			printf("Invalid hw.cxgbe.spg_len value (%d),"
259 			    " using %d instead.\n", spg_len, len);
260 		}
261 		spg_len = len;
262 	}
263 
264 	if (cong_drop < -1 || cong_drop > 1) {
265 		printf("Invalid hw.cxgbe.cong_drop value (%d),"
266 		    " using 0 instead.\n", cong_drop);
267 		cong_drop = 0;
268 	}
269 }
270 
271 void
272 t4_init_sge_cpl_handlers(struct adapter *sc)
273 {
274 
275 	t4_register_cpl_handler(sc, CPL_FW4_MSG, handle_fw_msg);
276 	t4_register_cpl_handler(sc, CPL_FW6_MSG, handle_fw_msg);
277 	t4_register_cpl_handler(sc, CPL_SGE_EGR_UPDATE, handle_sge_egr_update);
278 	t4_register_cpl_handler(sc, CPL_RX_PKT, t4_eth_rx);
279 
280 	t4_register_fw_msg_handler(sc, FW6_TYPE_CMD_RPL, t4_handle_fw_rpl);
281 }
282 
283 /*
284  * adap->params.vpd.cclk must be set up before this is called.
285  */
286 void
287 t4_tweak_chip_settings(struct adapter *sc)
288 {
289 	int i;
290 	uint32_t v, m;
291 	int intr_timer[SGE_NTIMERS] = {1, 5, 10, 50, 100, 200};
292 	int timer_max = M_TIMERVALUE0 * 1000 / sc->params.vpd.cclk;
293 	int intr_pktcount[SGE_NCOUNTERS] = {1, 8, 16, 32}; /* 63 max */
294 	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
295 
296 	KASSERT(sc->flags & MASTER_PF,
297 	    ("%s: trying to change chip settings when not master.", __func__));
298 
299 	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE |
300 	    V_INGPADBOUNDARY(M_INGPADBOUNDARY) | F_EGRSTATUSPAGESIZE;
301 	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
302 	    V_INGPADBOUNDARY(ilog2(fl_pad) - 5) |
303 	    V_EGRSTATUSPAGESIZE(spg_len == 128);
304 	t4_set_reg_field(sc, A_SGE_CONTROL, m, v);
305 
306 	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
307 	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
308 	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
309 	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
310 	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
311 	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
312 	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
313 	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
314 	t4_write_reg(sc, A_SGE_HOST_PAGE_SIZE, v);
315 
316 	for (i = 0; i < FL_BUF_SIZES; i++) {
317 		t4_write_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i),
318 		    FL_BUF_SIZE(i));
319 	}
320 
321 	v = V_THRESHOLD_0(intr_pktcount[0]) | V_THRESHOLD_1(intr_pktcount[1]) |
322 	    V_THRESHOLD_2(intr_pktcount[2]) | V_THRESHOLD_3(intr_pktcount[3]);
323 	t4_write_reg(sc, A_SGE_INGRESS_RX_THRESHOLD, v);
324 
325 	KASSERT(intr_timer[0] <= timer_max,
326 	    ("%s: not a single usable timer (%d, %d)", __func__, intr_timer[0],
327 	    timer_max));
328 	for (i = 1; i < nitems(intr_timer); i++) {
329 		KASSERT(intr_timer[i] >= intr_timer[i - 1],
330 		    ("%s: timers not listed in increasing order (%d)",
331 		    __func__, i));
332 
333 		while (intr_timer[i] > timer_max) {
334 			if (i == nitems(intr_timer) - 1) {
335 				intr_timer[i] = timer_max;
336 				break;
337 			}
338 			intr_timer[i] += intr_timer[i - 1];
339 			intr_timer[i] /= 2;
340 		}
341 	}
342 
343 	v = V_TIMERVALUE0(us_to_core_ticks(sc, intr_timer[0])) |
344 	    V_TIMERVALUE1(us_to_core_ticks(sc, intr_timer[1]));
345 	t4_write_reg(sc, A_SGE_TIMER_VALUE_0_AND_1, v);
346 	v = V_TIMERVALUE2(us_to_core_ticks(sc, intr_timer[2])) |
347 	    V_TIMERVALUE3(us_to_core_ticks(sc, intr_timer[3]));
348 	t4_write_reg(sc, A_SGE_TIMER_VALUE_2_AND_3, v);
349 	v = V_TIMERVALUE4(us_to_core_ticks(sc, intr_timer[4])) |
350 	    V_TIMERVALUE5(us_to_core_ticks(sc, intr_timer[5]));
351 	t4_write_reg(sc, A_SGE_TIMER_VALUE_4_AND_5, v);
352 
353 	if (cong_drop == 0) {
354 		m = F_TUNNELCNGDROP0 | F_TUNNELCNGDROP1 | F_TUNNELCNGDROP2 |
355 		    F_TUNNELCNGDROP3;
356 		t4_set_reg_field(sc, A_TP_PARA_REG3, m, 0);
357 	}
358 
359 	/* 4K, 16K, 64K, 256K DDP "page sizes" */
360 	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
361 	t4_write_reg(sc, A_ULP_RX_TDDP_PSZ, v);
362 
363 	m = v = F_TDDPTAGTCB;
364 	t4_set_reg_field(sc, A_ULP_RX_CTL, m, v);
365 
366 	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
367 	    F_RESETDDPOFFSET;
368 	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
369 	t4_set_reg_field(sc, A_TP_PARA_REG5, m, v);
370 }
371 
372 /*
373  * XXX: driver really should be able to deal with unexpected settings.
374  */
375 int
376 t4_read_chip_settings(struct adapter *sc)
377 {
378 	struct sge *s = &sc->sge;
379 	int i, rc = 0;
380 	uint32_t m, v, r;
381 	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
382 
383 	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE |
384 	    V_INGPADBOUNDARY(M_INGPADBOUNDARY) | F_EGRSTATUSPAGESIZE;
385 	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
386 	    V_INGPADBOUNDARY(ilog2(fl_pad) - 5) |
387 	    V_EGRSTATUSPAGESIZE(spg_len == 128);
388 	r = t4_read_reg(sc, A_SGE_CONTROL);
389 	if ((r & m) != v) {
390 		device_printf(sc->dev, "invalid SGE_CONTROL(0x%x)\n", r);
391 		rc = EINVAL;
392 	}
393 
394 	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
395 	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
396 	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
397 	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
398 	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
399 	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
400 	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
401 	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
402 	r = t4_read_reg(sc, A_SGE_HOST_PAGE_SIZE);
403 	if (r != v) {
404 		device_printf(sc->dev, "invalid SGE_HOST_PAGE_SIZE(0x%x)\n", r);
405 		rc = EINVAL;
406 	}
407 
408 	for (i = 0; i < FL_BUF_SIZES; i++) {
409 		v = t4_read_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i));
410 		if (v != FL_BUF_SIZE(i)) {
411 			device_printf(sc->dev,
412 			    "invalid SGE_FL_BUFFER_SIZE[%d](0x%x)\n", i, v);
413 			rc = EINVAL;
414 		}
415 	}
416 
417 	r = t4_read_reg(sc, A_SGE_INGRESS_RX_THRESHOLD);
418 	s->counter_val[0] = G_THRESHOLD_0(r);
419 	s->counter_val[1] = G_THRESHOLD_1(r);
420 	s->counter_val[2] = G_THRESHOLD_2(r);
421 	s->counter_val[3] = G_THRESHOLD_3(r);
422 
423 	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_0_AND_1);
424 	s->timer_val[0] = G_TIMERVALUE0(r) / core_ticks_per_usec(sc);
425 	s->timer_val[1] = G_TIMERVALUE1(r) / core_ticks_per_usec(sc);
426 	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_2_AND_3);
427 	s->timer_val[2] = G_TIMERVALUE2(r) / core_ticks_per_usec(sc);
428 	s->timer_val[3] = G_TIMERVALUE3(r) / core_ticks_per_usec(sc);
429 	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_4_AND_5);
430 	s->timer_val[4] = G_TIMERVALUE4(r) / core_ticks_per_usec(sc);
431 	s->timer_val[5] = G_TIMERVALUE5(r) / core_ticks_per_usec(sc);
432 
433 	if (cong_drop == 0) {
434 		m = F_TUNNELCNGDROP0 | F_TUNNELCNGDROP1 | F_TUNNELCNGDROP2 |
435 		    F_TUNNELCNGDROP3;
436 		r = t4_read_reg(sc, A_TP_PARA_REG3);
437 		if (r & m) {
438 			device_printf(sc->dev,
439 			    "invalid TP_PARA_REG3(0x%x)\n", r);
440 			rc = EINVAL;
441 		}
442 	}
443 
444 	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
445 	r = t4_read_reg(sc, A_ULP_RX_TDDP_PSZ);
446 	if (r != v) {
447 		device_printf(sc->dev, "invalid ULP_RX_TDDP_PSZ(0x%x)\n", r);
448 		rc = EINVAL;
449 	}
450 
451 	m = v = F_TDDPTAGTCB;
452 	r = t4_read_reg(sc, A_ULP_RX_CTL);
453 	if ((r & m) != v) {
454 		device_printf(sc->dev, "invalid ULP_RX_CTL(0x%x)\n", r);
455 		rc = EINVAL;
456 	}
457 
458 	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
459 	    F_RESETDDPOFFSET;
460 	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
461 	r = t4_read_reg(sc, A_TP_PARA_REG5);
462 	if ((r & m) != v) {
463 		device_printf(sc->dev, "invalid TP_PARA_REG5(0x%x)\n", r);
464 		rc = EINVAL;
465 	}
466 
467 	r = t4_read_reg(sc, A_SGE_CONM_CTRL);
468 	s->fl_starve_threshold = G_EGRTHRESHOLD(r) * 2 + 1;
469 
470 	if (is_t5(sc)) {
471 		r = t4_read_reg(sc, A_SGE_EGRESS_QUEUES_PER_PAGE_PF);
472 		r >>= S_QUEUESPERPAGEPF0 +
473 		    (S_QUEUESPERPAGEPF1 - S_QUEUESPERPAGEPF0) * sc->pf;
474 		s->s_qpp = r & M_QUEUESPERPAGEPF0;
475 	}
476 
477 	t4_init_tp_params(sc);
478 
479 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
480 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
481 
482 	return (rc);
483 }
484 
485 int
486 t4_create_dma_tag(struct adapter *sc)
487 {
488 	int rc;
489 
490 	rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), 1, 0,
491 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE,
492 	    BUS_SPACE_UNRESTRICTED, BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL,
493 	    NULL, &sc->dmat);
494 	if (rc != 0) {
495 		device_printf(sc->dev,
496 		    "failed to create main DMA tag: %d\n", rc);
497 	}
498 
499 	return (rc);
500 }
501 
502 int
503 t4_destroy_dma_tag(struct adapter *sc)
504 {
505 	if (sc->dmat)
506 		bus_dma_tag_destroy(sc->dmat);
507 
508 	return (0);
509 }
510 
511 /*
512  * Allocate and initialize the firmware event queue and the management queue.
513  *
514  * Returns errno on failure.  Resources allocated up to that point may still be
515  * allocated.  Caller is responsible for cleanup in case this function fails.
516  */
517 int
518 t4_setup_adapter_queues(struct adapter *sc)
519 {
520 	int rc;
521 
522 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
523 
524 	sysctl_ctx_init(&sc->ctx);
525 	sc->flags |= ADAP_SYSCTL_CTX;
526 
527 	/*
528 	 * Firmware event queue
529 	 */
530 	rc = alloc_fwq(sc);
531 	if (rc != 0)
532 		return (rc);
533 
534 	/*
535 	 * Management queue.  This is just a control queue that uses the fwq as
536 	 * its associated iq.
537 	 */
538 	rc = alloc_mgmtq(sc);
539 
540 	return (rc);
541 }
542 
543 /*
544  * Idempotent
545  */
546 int
547 t4_teardown_adapter_queues(struct adapter *sc)
548 {
549 
550 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
551 
552 	/* Do this before freeing the queue */
553 	if (sc->flags & ADAP_SYSCTL_CTX) {
554 		sysctl_ctx_free(&sc->ctx);
555 		sc->flags &= ~ADAP_SYSCTL_CTX;
556 	}
557 
558 	free_mgmtq(sc);
559 	free_fwq(sc);
560 
561 	return (0);
562 }
563 
564 static inline int
565 first_vector(struct port_info *pi)
566 {
567 	struct adapter *sc = pi->adapter;
568 	int rc = T4_EXTRA_INTR, i;
569 
570 	if (sc->intr_count == 1)
571 		return (0);
572 
573 	for_each_port(sc, i) {
574 		struct port_info *p = sc->port[i];
575 
576 		if (i == pi->port_id)
577 			break;
578 
579 #ifdef TCP_OFFLOAD
580 		if (sc->flags & INTR_DIRECT)
581 			rc += p->nrxq + p->nofldrxq;
582 		else
583 			rc += max(p->nrxq, p->nofldrxq);
584 #else
585 		/*
586 		 * Not compiled with offload support and intr_count > 1.  Only
587 		 * NIC queues exist and they'd better be taking direct
588 		 * interrupts.
589 		 */
590 		KASSERT(sc->flags & INTR_DIRECT,
591 		    ("%s: intr_count %d, !INTR_DIRECT", __func__,
592 		    sc->intr_count));
593 
594 		rc += p->nrxq;
595 #endif
596 	}
597 
598 	return (rc);
599 }
600 
601 /*
602  * Given an arbitrary "index," come up with an iq that can be used by other
603  * queues (of this port) for interrupt forwarding, SGE egress updates, etc.
604  * The iq returned is guaranteed to be something that takes direct interrupts.
605  */
606 static struct sge_iq *
607 port_intr_iq(struct port_info *pi, int idx)
608 {
609 	struct adapter *sc = pi->adapter;
610 	struct sge *s = &sc->sge;
611 	struct sge_iq *iq = NULL;
612 
613 	if (sc->intr_count == 1)
614 		return (&sc->sge.fwq);
615 
616 #ifdef TCP_OFFLOAD
617 	if (sc->flags & INTR_DIRECT) {
618 		idx %= pi->nrxq + pi->nofldrxq;
619 
620 		if (idx >= pi->nrxq) {
621 			idx -= pi->nrxq;
622 			iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
623 		} else
624 			iq = &s->rxq[pi->first_rxq + idx].iq;
625 
626 	} else {
627 		idx %= max(pi->nrxq, pi->nofldrxq);
628 
629 		if (pi->nrxq >= pi->nofldrxq)
630 			iq = &s->rxq[pi->first_rxq + idx].iq;
631 		else
632 			iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
633 	}
634 #else
635 	/*
636 	 * Not compiled with offload support and intr_count > 1.  Only NIC
637 	 * queues exist and they'd better be taking direct interrupts.
638 	 */
639 	KASSERT(sc->flags & INTR_DIRECT,
640 	    ("%s: intr_count %d, !INTR_DIRECT", __func__, sc->intr_count));
641 
642 	idx %= pi->nrxq;
643 	iq = &s->rxq[pi->first_rxq + idx].iq;
644 #endif
645 
646 	KASSERT(iq->flags & IQ_INTR, ("%s: EDOOFUS", __func__));
647 	return (iq);
648 }
649 
650 static inline int
651 mtu_to_bufsize(int mtu)
652 {
653 	int bufsize;
654 
655 	/* large enough for a frame even when VLAN extraction is disabled */
656 	bufsize = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN + mtu;
657 	bufsize = roundup2(bufsize + fl_pktshift, fl_pad);
658 
659 	return (bufsize);
660 }
661 
662 #ifdef TCP_OFFLOAD
663 static inline int
664 mtu_to_bufsize_toe(struct adapter *sc, int mtu)
665 {
666 
667 	if (sc->tt.rx_coalesce)
668 		return (G_RXCOALESCESIZE(t4_read_reg(sc, A_TP_PARA_REG2)));
669 
670 	return (mtu);
671 }
672 #endif
673 
674 int
675 t4_setup_port_queues(struct port_info *pi)
676 {
677 	int rc = 0, i, j, intr_idx, iqid;
678 	struct sge_rxq *rxq;
679 	struct sge_txq *txq;
680 	struct sge_wrq *ctrlq;
681 #ifdef TCP_OFFLOAD
682 	struct sge_ofld_rxq *ofld_rxq;
683 	struct sge_wrq *ofld_txq;
684 	struct sysctl_oid *oid2 = NULL;
685 #endif
686 	char name[16];
687 	struct adapter *sc = pi->adapter;
688 	struct ifnet *ifp = pi->ifp;
689 	struct sysctl_oid *oid = device_get_sysctl_tree(pi->dev);
690 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
691 	int bufsize;
692 
693 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "rxq", CTLFLAG_RD,
694 	    NULL, "rx queues");
695 
696 #ifdef TCP_OFFLOAD
697 	if (is_offload(sc)) {
698 		oid2 = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_rxq",
699 		    CTLFLAG_RD, NULL,
700 		    "rx queues for offloaded TCP connections");
701 	}
702 #endif
703 
704 	/* Interrupt vector to start from (when using multiple vectors) */
705 	intr_idx = first_vector(pi);
706 
707 	/*
708 	 * First pass over all rx queues (NIC and TOE):
709 	 * a) initialize iq and fl
710 	 * b) allocate queue iff it will take direct interrupts.
711 	 */
712 	bufsize = mtu_to_bufsize(ifp->if_mtu);
713 	for_each_rxq(pi, i, rxq) {
714 
715 		init_iq(&rxq->iq, sc, pi->tmr_idx, pi->pktc_idx, pi->qsize_rxq,
716 		    RX_IQ_ESIZE);
717 
718 		snprintf(name, sizeof(name), "%s rxq%d-fl",
719 		    device_get_nameunit(pi->dev), i);
720 		init_fl(&rxq->fl, pi->qsize_rxq / 8, bufsize, name);
721 
722 		if (sc->flags & INTR_DIRECT
723 #ifdef TCP_OFFLOAD
724 		    || (sc->intr_count > 1 && pi->nrxq >= pi->nofldrxq)
725 #endif
726 		   ) {
727 			rxq->iq.flags |= IQ_INTR;
728 			rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
729 			if (rc != 0)
730 				goto done;
731 			intr_idx++;
732 		}
733 	}
734 
735 #ifdef TCP_OFFLOAD
736 	bufsize = mtu_to_bufsize_toe(sc, ifp->if_mtu);
737 	for_each_ofld_rxq(pi, i, ofld_rxq) {
738 
739 		init_iq(&ofld_rxq->iq, sc, pi->tmr_idx, pi->pktc_idx,
740 		    pi->qsize_rxq, RX_IQ_ESIZE);
741 
742 		snprintf(name, sizeof(name), "%s ofld_rxq%d-fl",
743 		    device_get_nameunit(pi->dev), i);
744 		init_fl(&ofld_rxq->fl, pi->qsize_rxq / 8, bufsize, name);
745 
746 		if (sc->flags & INTR_DIRECT ||
747 		    (sc->intr_count > 1 && pi->nofldrxq > pi->nrxq)) {
748 			ofld_rxq->iq.flags |= IQ_INTR;
749 			rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
750 			if (rc != 0)
751 				goto done;
752 			intr_idx++;
753 		}
754 	}
755 #endif
756 
757 	/*
758 	 * Second pass over all rx queues (NIC and TOE).  The queues forwarding
759 	 * their interrupts are allocated now.
760 	 */
761 	j = 0;
762 	for_each_rxq(pi, i, rxq) {
763 		if (rxq->iq.flags & IQ_INTR)
764 			continue;
765 
766 		intr_idx = port_intr_iq(pi, j)->abs_id;
767 
768 		rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
769 		if (rc != 0)
770 			goto done;
771 		j++;
772 	}
773 
774 #ifdef TCP_OFFLOAD
775 	for_each_ofld_rxq(pi, i, ofld_rxq) {
776 		if (ofld_rxq->iq.flags & IQ_INTR)
777 			continue;
778 
779 		intr_idx = port_intr_iq(pi, j)->abs_id;
780 
781 		rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
782 		if (rc != 0)
783 			goto done;
784 		j++;
785 	}
786 #endif
787 
788 	/*
789 	 * Now the tx queues.  Only one pass needed.
790 	 */
791 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "txq", CTLFLAG_RD,
792 	    NULL, "tx queues");
793 	j = 0;
794 	for_each_txq(pi, i, txq) {
795 		uint16_t iqid;
796 
797 		iqid = port_intr_iq(pi, j)->cntxt_id;
798 
799 		snprintf(name, sizeof(name), "%s txq%d",
800 		    device_get_nameunit(pi->dev), i);
801 		init_eq(&txq->eq, EQ_ETH, pi->qsize_txq, pi->tx_chan, iqid,
802 		    name);
803 
804 		rc = alloc_txq(pi, txq, i, oid);
805 		if (rc != 0)
806 			goto done;
807 		j++;
808 	}
809 
810 #ifdef TCP_OFFLOAD
811 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_txq",
812 	    CTLFLAG_RD, NULL, "tx queues for offloaded TCP connections");
813 	for_each_ofld_txq(pi, i, ofld_txq) {
814 		uint16_t iqid;
815 
816 		iqid = port_intr_iq(pi, j)->cntxt_id;
817 
818 		snprintf(name, sizeof(name), "%s ofld_txq%d",
819 		    device_get_nameunit(pi->dev), i);
820 		init_eq(&ofld_txq->eq, EQ_OFLD, pi->qsize_txq, pi->tx_chan,
821 		    iqid, name);
822 
823 		snprintf(name, sizeof(name), "%d", i);
824 		oid2 = SYSCTL_ADD_NODE(&pi->ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
825 		    name, CTLFLAG_RD, NULL, "offload tx queue");
826 
827 		rc = alloc_wrq(sc, pi, ofld_txq, oid2);
828 		if (rc != 0)
829 			goto done;
830 		j++;
831 	}
832 #endif
833 
834 	/*
835 	 * Finally, the control queue.
836 	 */
837 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ctrlq", CTLFLAG_RD,
838 	    NULL, "ctrl queue");
839 	ctrlq = &sc->sge.ctrlq[pi->port_id];
840 	iqid = port_intr_iq(pi, 0)->cntxt_id;
841 	snprintf(name, sizeof(name), "%s ctrlq", device_get_nameunit(pi->dev));
842 	init_eq(&ctrlq->eq, EQ_CTRL, CTRL_EQ_QSIZE, pi->tx_chan, iqid, name);
843 	rc = alloc_wrq(sc, pi, ctrlq, oid);
844 
845 done:
846 	if (rc)
847 		t4_teardown_port_queues(pi);
848 
849 	return (rc);
850 }
851 
852 /*
853  * Idempotent
854  */
855 int
856 t4_teardown_port_queues(struct port_info *pi)
857 {
858 	int i;
859 	struct adapter *sc = pi->adapter;
860 	struct sge_rxq *rxq;
861 	struct sge_txq *txq;
862 #ifdef TCP_OFFLOAD
863 	struct sge_ofld_rxq *ofld_rxq;
864 	struct sge_wrq *ofld_txq;
865 #endif
866 
867 	/* Do this before freeing the queues */
868 	if (pi->flags & PORT_SYSCTL_CTX) {
869 		sysctl_ctx_free(&pi->ctx);
870 		pi->flags &= ~PORT_SYSCTL_CTX;
871 	}
872 
873 	/*
874 	 * Take down all the tx queues first, as they reference the rx queues
875 	 * (for egress updates, etc.).
876 	 */
877 
878 	free_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
879 
880 	for_each_txq(pi, i, txq) {
881 		free_txq(pi, txq);
882 	}
883 
884 #ifdef TCP_OFFLOAD
885 	for_each_ofld_txq(pi, i, ofld_txq) {
886 		free_wrq(sc, ofld_txq);
887 	}
888 #endif
889 
890 	/*
891 	 * Then take down the rx queues that forward their interrupts, as they
892 	 * reference other rx queues.
893 	 */
894 
895 	for_each_rxq(pi, i, rxq) {
896 		if ((rxq->iq.flags & IQ_INTR) == 0)
897 			free_rxq(pi, rxq);
898 	}
899 
900 #ifdef TCP_OFFLOAD
901 	for_each_ofld_rxq(pi, i, ofld_rxq) {
902 		if ((ofld_rxq->iq.flags & IQ_INTR) == 0)
903 			free_ofld_rxq(pi, ofld_rxq);
904 	}
905 #endif
906 
907 	/*
908 	 * Then take down the rx queues that take direct interrupts.
909 	 */
910 
911 	for_each_rxq(pi, i, rxq) {
912 		if (rxq->iq.flags & IQ_INTR)
913 			free_rxq(pi, rxq);
914 	}
915 
916 #ifdef TCP_OFFLOAD
917 	for_each_ofld_rxq(pi, i, ofld_rxq) {
918 		if (ofld_rxq->iq.flags & IQ_INTR)
919 			free_ofld_rxq(pi, ofld_rxq);
920 	}
921 #endif
922 
923 	return (0);
924 }
925 
926 /*
927  * Deals with errors and the firmware event queue.  All data rx queues forward
928  * their interrupt to the firmware event queue.
929  */
930 void
931 t4_intr_all(void *arg)
932 {
933 	struct adapter *sc = arg;
934 	struct sge_iq *fwq = &sc->sge.fwq;
935 
936 	t4_intr_err(arg);
937 	if (atomic_cmpset_int(&fwq->state, IQS_IDLE, IQS_BUSY)) {
938 		service_iq(fwq, 0);
939 		atomic_cmpset_int(&fwq->state, IQS_BUSY, IQS_IDLE);
940 	}
941 }
942 
943 /* Deals with error interrupts */
944 void
945 t4_intr_err(void *arg)
946 {
947 	struct adapter *sc = arg;
948 
949 	t4_write_reg(sc, MYPF_REG(A_PCIE_PF_CLI), 0);
950 	t4_slow_intr_handler(sc);
951 }
952 
953 void
954 t4_intr_evt(void *arg)
955 {
956 	struct sge_iq *iq = arg;
957 
958 	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
959 		service_iq(iq, 0);
960 		atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
961 	}
962 }
963 
964 void
965 t4_intr(void *arg)
966 {
967 	struct sge_iq *iq = arg;
968 
969 	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
970 		service_iq(iq, 0);
971 		atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
972 	}
973 }
974 
975 /*
976  * Deals with anything and everything on the given ingress queue.
977  */
978 static int
979 service_iq(struct sge_iq *iq, int budget)
980 {
981 	struct sge_iq *q;
982 	struct sge_rxq *rxq = iq_to_rxq(iq);	/* Use iff iq is part of rxq */
983 	struct sge_fl *fl = &rxq->fl;		/* Use iff IQ_HAS_FL */
984 	struct adapter *sc = iq->adapter;
985 	struct rsp_ctrl *ctrl;
986 	const struct rss_header *rss;
987 	int ndescs = 0, limit, fl_bufs_used = 0;
988 	int rsp_type;
989 	uint32_t lq;
990 	struct mbuf *m0;
991 	STAILQ_HEAD(, sge_iq) iql = STAILQ_HEAD_INITIALIZER(iql);
992 
993 	limit = budget ? budget : iq->qsize / 8;
994 
995 	KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
996 
997 	/*
998 	 * We always come back and check the descriptor ring for new indirect
999 	 * interrupts and other responses after running a single handler.
1000 	 */
1001 	for (;;) {
1002 		while (is_new_response(iq, &ctrl)) {
1003 
1004 			rmb();
1005 
1006 			m0 = NULL;
1007 			rsp_type = G_RSPD_TYPE(ctrl->u.type_gen);
1008 			lq = be32toh(ctrl->pldbuflen_qid);
1009 			rss = (const void *)iq->cdesc;
1010 
1011 			switch (rsp_type) {
1012 			case X_RSPD_TYPE_FLBUF:
1013 
1014 				KASSERT(iq->flags & IQ_HAS_FL,
1015 				    ("%s: data for an iq (%p) with no freelist",
1016 				    __func__, iq));
1017 
1018 				m0 = get_fl_payload(sc, fl, lq, &fl_bufs_used);
1019 #ifdef T4_PKT_TIMESTAMP
1020 				/*
1021 				 * 60 bit timestamp for the payload is
1022 				 * *(uint64_t *)m0->m_pktdat.  Note that it is
1023 				 * in the leading free-space in the mbuf.  The
1024 				 * kernel can clobber it during a pullup,
1025 				 * m_copymdata, etc.  You need to make sure that
1026 				 * the mbuf reaches you unmolested if you care
1027 				 * about the timestamp.
1028 				 */
1029 				*(uint64_t *)m0->m_pktdat =
1030 				    be64toh(ctrl->u.last_flit) &
1031 				    0xfffffffffffffff;
1032 #endif
1033 
1034 				/* fall through */
1035 
1036 			case X_RSPD_TYPE_CPL:
1037 				KASSERT(rss->opcode < NUM_CPL_CMDS,
1038 				    ("%s: bad opcode %02x.", __func__,
1039 				    rss->opcode));
1040 				sc->cpl_handler[rss->opcode](iq, rss, m0);
1041 				break;
1042 
1043 			case X_RSPD_TYPE_INTR:
1044 
1045 				/*
1046 				 * Interrupts should be forwarded only to queues
1047 				 * that are not forwarding their interrupts.
1048 				 * This means service_iq can recurse but only 1
1049 				 * level deep.
1050 				 */
1051 				KASSERT(budget == 0,
1052 				    ("%s: budget %u, rsp_type %u", __func__,
1053 				    budget, rsp_type));
1054 
1055 				q = sc->sge.iqmap[lq - sc->sge.iq_start];
1056 				if (atomic_cmpset_int(&q->state, IQS_IDLE,
1057 				    IQS_BUSY)) {
1058 					if (service_iq(q, q->qsize / 8) == 0) {
1059 						atomic_cmpset_int(&q->state,
1060 						    IQS_BUSY, IQS_IDLE);
1061 					} else {
1062 						STAILQ_INSERT_TAIL(&iql, q,
1063 						    link);
1064 					}
1065 				}
1066 				break;
1067 
1068 			default:
1069 				sc->an_handler(iq, ctrl);
1070 				break;
1071 			}
1072 
1073 			iq_next(iq);
1074 			if (++ndescs == limit) {
1075 				t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS),
1076 				    V_CIDXINC(ndescs) |
1077 				    V_INGRESSQID(iq->cntxt_id) |
1078 				    V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));
1079 				ndescs = 0;
1080 
1081 				if (fl_bufs_used > 0) {
1082 					FL_LOCK(fl);
1083 					fl->needed += fl_bufs_used;
1084 					refill_fl(sc, fl, fl->cap / 8);
1085 					FL_UNLOCK(fl);
1086 					fl_bufs_used = 0;
1087 				}
1088 
1089 				if (budget)
1090 					return (EINPROGRESS);
1091 			}
1092 		}
1093 
1094 		if (STAILQ_EMPTY(&iql))
1095 			break;
1096 
1097 		/*
1098 		 * Process the head only, and send it to the back of the list if
1099 		 * it's still not done.
1100 		 */
1101 		q = STAILQ_FIRST(&iql);
1102 		STAILQ_REMOVE_HEAD(&iql, link);
1103 		if (service_iq(q, q->qsize / 8) == 0)
1104 			atomic_cmpset_int(&q->state, IQS_BUSY, IQS_IDLE);
1105 		else
1106 			STAILQ_INSERT_TAIL(&iql, q, link);
1107 	}
1108 
1109 #if defined(INET) || defined(INET6)
1110 	if (iq->flags & IQ_LRO_ENABLED) {
1111 		struct lro_ctrl *lro = &rxq->lro;
1112 		struct lro_entry *l;
1113 
1114 		while (!SLIST_EMPTY(&lro->lro_active)) {
1115 			l = SLIST_FIRST(&lro->lro_active);
1116 			SLIST_REMOVE_HEAD(&lro->lro_active, next);
1117 			tcp_lro_flush(lro, l);
1118 		}
1119 	}
1120 #endif
1121 
1122 	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_CIDXINC(ndescs) |
1123 	    V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));
1124 
1125 	if (iq->flags & IQ_HAS_FL) {
1126 		int starved;
1127 
1128 		FL_LOCK(fl);
1129 		fl->needed += fl_bufs_used;
1130 		starved = refill_fl(sc, fl, fl->cap / 4);
1131 		FL_UNLOCK(fl);
1132 		if (__predict_false(starved != 0))
1133 			add_fl_to_sfl(sc, fl);
1134 	}
1135 
1136 	return (0);
1137 }
1138 
1139 static struct mbuf *
1140 get_fl_payload(struct adapter *sc, struct sge_fl *fl, uint32_t len_newbuf,
1141     int *fl_bufs_used)
1142 {
1143 	struct mbuf *m0, *m;
1144 	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
1145 	unsigned int nbuf, len;
1146 
1147 	/*
1148 	 * No assertion for the fl lock because we don't need it.  This routine
1149 	 * is called only from the rx interrupt handler and it only updates
1150 	 * fl->cidx.  (Contrast that with fl->pidx/fl->needed which could be
1151 	 * updated in the rx interrupt handler or the starvation helper routine.
1152 	 * That's why code that manipulates fl->pidx/fl->needed needs the fl
1153 	 * lock but this routine does not).
1154 	 */
1155 
1156 	if (__predict_false((len_newbuf & F_RSPD_NEWBUF) == 0))
1157 		panic("%s: cannot handle packed frames", __func__);
1158 	len = G_RSPD_LEN(len_newbuf);
1159 
1160 	m0 = sd->m;
1161 	sd->m = NULL;	/* consumed */
1162 
1163 	bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map, BUS_DMASYNC_POSTREAD);
1164 	m_init(m0, NULL, 0, M_NOWAIT, MT_DATA, M_PKTHDR);
1165 #ifdef T4_PKT_TIMESTAMP
1166 	/* Leave room for a timestamp */
1167 	m0->m_data += 8;
1168 #endif
1169 
1170 	if (len < RX_COPY_THRESHOLD) {
1171 		/* copy data to mbuf, buffer will be recycled */
1172 		bcopy(sd->cl, mtod(m0, caddr_t), len);
1173 		m0->m_len = len;
1174 	} else {
1175 		bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
1176 		m_cljset(m0, sd->cl, FL_BUF_TYPE(sd->tag_idx));
1177 		sd->cl = NULL;	/* consumed */
1178 		m0->m_len = min(len, FL_BUF_SIZE(sd->tag_idx));
1179 	}
1180 	m0->m_pkthdr.len = len;
1181 
1182 	sd++;
1183 	if (__predict_false(++fl->cidx == fl->cap)) {
1184 		sd = fl->sdesc;
1185 		fl->cidx = 0;
1186 	}
1187 
1188 	m = m0;
1189 	len -= m->m_len;
1190 	nbuf = 1;	/* # of fl buffers used */
1191 
1192 	while (len > 0) {
1193 		m->m_next = sd->m;
1194 		sd->m = NULL;	/* consumed */
1195 		m = m->m_next;
1196 
1197 		bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map,
1198 		    BUS_DMASYNC_POSTREAD);
1199 
1200 		m_init(m, NULL, 0, M_NOWAIT, MT_DATA, 0);
1201 		if (len <= MLEN) {
1202 			bcopy(sd->cl, mtod(m, caddr_t), len);
1203 			m->m_len = len;
1204 		} else {
1205 			bus_dmamap_unload(fl->tag[sd->tag_idx],
1206 			    sd->map);
1207 			m_cljset(m, sd->cl, FL_BUF_TYPE(sd->tag_idx));
1208 			sd->cl = NULL;	/* consumed */
1209 			m->m_len = min(len, FL_BUF_SIZE(sd->tag_idx));
1210 		}
1211 
1212 		sd++;
1213 		if (__predict_false(++fl->cidx == fl->cap)) {
1214 			sd = fl->sdesc;
1215 			fl->cidx = 0;
1216 		}
1217 
1218 		len -= m->m_len;
1219 		nbuf++;
1220 	}
1221 
1222 	(*fl_bufs_used) += nbuf;
1223 
1224 	return (m0);
1225 }
1226 
1227 static int
1228 t4_eth_rx(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m0)
1229 {
1230 	struct sge_rxq *rxq = iq_to_rxq(iq);
1231 	struct ifnet *ifp = rxq->ifp;
1232 	const struct cpl_rx_pkt *cpl = (const void *)(rss + 1);
1233 #if defined(INET) || defined(INET6)
1234 	struct lro_ctrl *lro = &rxq->lro;
1235 #endif
1236 
1237 	KASSERT(m0 != NULL, ("%s: no payload with opcode %02x", __func__,
1238 	    rss->opcode));
1239 
1240 	m0->m_pkthdr.len -= fl_pktshift;
1241 	m0->m_len -= fl_pktshift;
1242 	m0->m_data += fl_pktshift;
1243 
1244 	m0->m_pkthdr.rcvif = ifp;
1245 	m0->m_flags |= M_FLOWID;
1246 	m0->m_pkthdr.flowid = rss->hash_val;
1247 
1248 	if (cpl->csum_calc && !cpl->err_vec) {
1249 		if (ifp->if_capenable & IFCAP_RXCSUM &&
1250 		    cpl->l2info & htobe32(F_RXF_IP)) {
1251 			m0->m_pkthdr.csum_flags = (CSUM_IP_CHECKED |
1252 			    CSUM_IP_VALID | CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1253 			rxq->rxcsum++;
1254 		} else if (ifp->if_capenable & IFCAP_RXCSUM_IPV6 &&
1255 		    cpl->l2info & htobe32(F_RXF_IP6)) {
1256 			m0->m_pkthdr.csum_flags = (CSUM_DATA_VALID_IPV6 |
1257 			    CSUM_PSEUDO_HDR);
1258 			rxq->rxcsum++;
1259 		}
1260 
1261 		if (__predict_false(cpl->ip_frag))
1262 			m0->m_pkthdr.csum_data = be16toh(cpl->csum);
1263 		else
1264 			m0->m_pkthdr.csum_data = 0xffff;
1265 	}
1266 
1267 	if (cpl->vlan_ex) {
1268 		m0->m_pkthdr.ether_vtag = be16toh(cpl->vlan);
1269 		m0->m_flags |= M_VLANTAG;
1270 		rxq->vlan_extraction++;
1271 	}
1272 
1273 #if defined(INET) || defined(INET6)
1274 	if (cpl->l2info & htobe32(F_RXF_LRO) &&
1275 	    iq->flags & IQ_LRO_ENABLED &&
1276 	    tcp_lro_rx(lro, m0, 0) == 0) {
1277 		/* queued for LRO */
1278 	} else
1279 #endif
1280 	ifp->if_input(ifp, m0);
1281 
1282 	return (0);
1283 }
1284 
1285 /*
1286  * Doesn't fail.  Holds on to work requests it can't send right away.
1287  */
1288 void
1289 t4_wrq_tx_locked(struct adapter *sc, struct sge_wrq *wrq, struct wrqe *wr)
1290 {
1291 	struct sge_eq *eq = &wrq->eq;
1292 	int can_reclaim;
1293 	caddr_t dst;
1294 
1295 	TXQ_LOCK_ASSERT_OWNED(wrq);
1296 #ifdef TCP_OFFLOAD
1297 	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_OFLD ||
1298 	    (eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1299 	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1300 #else
1301 	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1302 	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1303 #endif
1304 
1305 	if (__predict_true(wr != NULL))
1306 		STAILQ_INSERT_TAIL(&wrq->wr_list, wr, link);
1307 
1308 	can_reclaim = reclaimable(eq);
1309 	if (__predict_false(eq->flags & EQ_STALLED)) {
1310 		if (can_reclaim < tx_resume_threshold(eq))
1311 			return;
1312 		eq->flags &= ~EQ_STALLED;
1313 		eq->unstalled++;
1314 	}
1315 	eq->cidx += can_reclaim;
1316 	eq->avail += can_reclaim;
1317 	if (__predict_false(eq->cidx >= eq->cap))
1318 		eq->cidx -= eq->cap;
1319 
1320 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
1321 		int ndesc;
1322 
1323 		if (__predict_false(wr->wr_len < 0 ||
1324 		    wr->wr_len > SGE_MAX_WR_LEN || (wr->wr_len & 0x7))) {
1325 
1326 #ifdef INVARIANTS
1327 			panic("%s: work request with length %d", __func__,
1328 			    wr->wr_len);
1329 #endif
1330 #ifdef KDB
1331 			kdb_backtrace();
1332 #endif
1333 			log(LOG_ERR, "%s: %s work request with length %d",
1334 			    device_get_nameunit(sc->dev), __func__, wr->wr_len);
1335 			STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1336 			free_wrqe(wr);
1337 			continue;
1338 		}
1339 
1340 		ndesc = howmany(wr->wr_len, EQ_ESIZE);
1341 		if (eq->avail < ndesc) {
1342 			wrq->no_desc++;
1343 			break;
1344 		}
1345 
1346 		dst = (void *)&eq->desc[eq->pidx];
1347 		copy_to_txd(eq, wrtod(wr), &dst, wr->wr_len);
1348 
1349 		eq->pidx += ndesc;
1350 		eq->avail -= ndesc;
1351 		if (__predict_false(eq->pidx >= eq->cap))
1352 			eq->pidx -= eq->cap;
1353 
1354 		eq->pending += ndesc;
1355 		if (eq->pending >= 8)
1356 			ring_eq_db(sc, eq);
1357 
1358 		wrq->tx_wrs++;
1359 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1360 		free_wrqe(wr);
1361 
1362 		if (eq->avail < 8) {
1363 			can_reclaim = reclaimable(eq);
1364 			eq->cidx += can_reclaim;
1365 			eq->avail += can_reclaim;
1366 			if (__predict_false(eq->cidx >= eq->cap))
1367 				eq->cidx -= eq->cap;
1368 		}
1369 	}
1370 
1371 	if (eq->pending)
1372 		ring_eq_db(sc, eq);
1373 
1374 	if (wr != NULL) {
1375 		eq->flags |= EQ_STALLED;
1376 		if (callout_pending(&eq->tx_callout) == 0)
1377 			callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1378 	}
1379 }
1380 
1381 /* Per-packet header in a coalesced tx WR, before the SGL starts (in flits) */
1382 #define TXPKTS_PKT_HDR ((\
1383     sizeof(struct ulp_txpkt) + \
1384     sizeof(struct ulptx_idata) + \
1385     sizeof(struct cpl_tx_pkt_core) \
1386     ) / 8)
1387 
1388 /* Header of a coalesced tx WR, before SGL of first packet (in flits) */
1389 #define TXPKTS_WR_HDR (\
1390     sizeof(struct fw_eth_tx_pkts_wr) / 8 + \
1391     TXPKTS_PKT_HDR)
1392 
1393 /* Header of a tx WR, before SGL of first packet (in flits) */
1394 #define TXPKT_WR_HDR ((\
1395     sizeof(struct fw_eth_tx_pkt_wr) + \
1396     sizeof(struct cpl_tx_pkt_core) \
1397     ) / 8 )
1398 
1399 /* Header of a tx LSO WR, before SGL of first packet (in flits) */
1400 #define TXPKT_LSO_WR_HDR ((\
1401     sizeof(struct fw_eth_tx_pkt_wr) + \
1402     sizeof(struct cpl_tx_pkt_lso_core) + \
1403     sizeof(struct cpl_tx_pkt_core) \
1404     ) / 8 )
1405 
1406 int
1407 t4_eth_tx(struct ifnet *ifp, struct sge_txq *txq, struct mbuf *m)
1408 {
1409 	struct port_info *pi = (void *)ifp->if_softc;
1410 	struct adapter *sc = pi->adapter;
1411 	struct sge_eq *eq = &txq->eq;
1412 	struct buf_ring *br = txq->br;
1413 	struct mbuf *next;
1414 	int rc, coalescing, can_reclaim;
1415 	struct txpkts txpkts;
1416 	struct sgl sgl;
1417 
1418 	TXQ_LOCK_ASSERT_OWNED(txq);
1419 	KASSERT(m, ("%s: called with nothing to do.", __func__));
1420 	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_ETH,
1421 	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1422 
1423 	prefetch(&eq->desc[eq->pidx]);
1424 	prefetch(&txq->sdesc[eq->pidx]);
1425 
1426 	txpkts.npkt = 0;/* indicates there's nothing in txpkts */
1427 	coalescing = 0;
1428 
1429 	can_reclaim = reclaimable(eq);
1430 	if (__predict_false(eq->flags & EQ_STALLED)) {
1431 		if (can_reclaim < tx_resume_threshold(eq)) {
1432 			txq->m = m;
1433 			return (0);
1434 		}
1435 		eq->flags &= ~EQ_STALLED;
1436 		eq->unstalled++;
1437 	}
1438 
1439 	if (__predict_false(eq->flags & EQ_DOOMED)) {
1440 		m_freem(m);
1441 		while ((m = buf_ring_dequeue_sc(txq->br)) != NULL)
1442 			m_freem(m);
1443 		return (ENETDOWN);
1444 	}
1445 
1446 	if (eq->avail < 8 && can_reclaim)
1447 		reclaim_tx_descs(txq, can_reclaim, 32);
1448 
1449 	for (; m; m = next ? next : drbr_dequeue(ifp, br)) {
1450 
1451 		if (eq->avail < 8)
1452 			break;
1453 
1454 		next = m->m_nextpkt;
1455 		m->m_nextpkt = NULL;
1456 
1457 		if (next || buf_ring_peek(br))
1458 			coalescing = 1;
1459 
1460 		rc = get_pkt_sgl(txq, &m, &sgl, coalescing);
1461 		if (rc != 0) {
1462 			if (rc == ENOMEM) {
1463 
1464 				/* Short of resources, suspend tx */
1465 
1466 				m->m_nextpkt = next;
1467 				break;
1468 			}
1469 
1470 			/*
1471 			 * Unrecoverable error for this packet, throw it away
1472 			 * and move on to the next.  get_pkt_sgl may already
1473 			 * have freed m (it will be NULL in that case and the
1474 			 * m_freem here is still safe).
1475 			 */
1476 
1477 			m_freem(m);
1478 			continue;
1479 		}
1480 
1481 		if (coalescing &&
1482 		    add_to_txpkts(pi, txq, &txpkts, m, &sgl) == 0) {
1483 
1484 			/* Successfully absorbed into txpkts */
1485 
1486 			write_ulp_cpl_sgl(pi, txq, &txpkts, m, &sgl);
1487 			goto doorbell;
1488 		}
1489 
1490 		/*
1491 		 * We weren't coalescing to begin with, or current frame could
1492 		 * not be coalesced (add_to_txpkts flushes txpkts if a frame
1493 		 * given to it can't be coalesced).  Either way there should be
1494 		 * nothing in txpkts.
1495 		 */
1496 		KASSERT(txpkts.npkt == 0,
1497 		    ("%s: txpkts not empty: %d", __func__, txpkts.npkt));
1498 
1499 		/* We're sending out individual packets now */
1500 		coalescing = 0;
1501 
1502 		if (eq->avail < 8)
1503 			reclaim_tx_descs(txq, 0, 8);
1504 		rc = write_txpkt_wr(pi, txq, m, &sgl);
1505 		if (rc != 0) {
1506 
1507 			/* Short of hardware descriptors, suspend tx */
1508 
1509 			/*
1510 			 * This is an unlikely but expensive failure.  We've
1511 			 * done all the hard work (DMA mappings etc.) and now we
1512 			 * can't send out the packet.  What's worse, we have to
1513 			 * spend even more time freeing up everything in sgl.
1514 			 */
1515 			txq->no_desc++;
1516 			free_pkt_sgl(txq, &sgl);
1517 
1518 			m->m_nextpkt = next;
1519 			break;
1520 		}
1521 
1522 		ETHER_BPF_MTAP(ifp, m);
1523 		if (sgl.nsegs == 0)
1524 			m_freem(m);
1525 doorbell:
1526 		if (eq->pending >= 8)
1527 			ring_eq_db(sc, eq);
1528 
1529 		can_reclaim = reclaimable(eq);
1530 		if (can_reclaim >= 32)
1531 			reclaim_tx_descs(txq, can_reclaim, 64);
1532 	}
1533 
1534 	if (txpkts.npkt > 0)
1535 		write_txpkts_wr(txq, &txpkts);
1536 
1537 	/*
1538 	 * m not NULL means there was an error but we haven't thrown it away.
1539 	 * This can happen when we're short of tx descriptors (no_desc) or maybe
1540 	 * even DMA maps (no_dmamap).  Either way, a credit flush and reclaim
1541 	 * will get things going again.
1542 	 */
1543 	if (m && !(eq->flags & EQ_CRFLUSHED)) {
1544 		struct tx_sdesc *txsd = &txq->sdesc[eq->pidx];
1545 
1546 		/*
1547 		 * If EQ_CRFLUSHED is not set then we know we have at least one
1548 		 * available descriptor because any WR that reduces eq->avail to
1549 		 * 0 also sets EQ_CRFLUSHED.
1550 		 */
1551 		KASSERT(eq->avail > 0, ("%s: no space for eqflush.", __func__));
1552 
1553 		txsd->desc_used = 1;
1554 		txsd->credits = 0;
1555 		write_eqflush_wr(eq);
1556 	}
1557 	txq->m = m;
1558 
1559 	if (eq->pending)
1560 		ring_eq_db(sc, eq);
1561 
1562 	reclaim_tx_descs(txq, 0, 128);
1563 
1564 	if (eq->flags & EQ_STALLED && callout_pending(&eq->tx_callout) == 0)
1565 		callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1566 
1567 	return (0);
1568 }
1569 
1570 void
1571 t4_update_fl_bufsize(struct ifnet *ifp)
1572 {
1573 	struct port_info *pi = ifp->if_softc;
1574 	struct sge_rxq *rxq;
1575 #ifdef TCP_OFFLOAD
1576 	struct sge_ofld_rxq *ofld_rxq;
1577 #endif
1578 	struct sge_fl *fl;
1579 	int i, bufsize;
1580 
1581 	bufsize = mtu_to_bufsize(ifp->if_mtu);
1582 	for_each_rxq(pi, i, rxq) {
1583 		fl = &rxq->fl;
1584 
1585 		FL_LOCK(fl);
1586 		set_fl_tag_idx(fl, bufsize);
1587 		FL_UNLOCK(fl);
1588 	}
1589 #ifdef TCP_OFFLOAD
1590 	bufsize = mtu_to_bufsize_toe(pi->adapter, ifp->if_mtu);
1591 	for_each_ofld_rxq(pi, i, ofld_rxq) {
1592 		fl = &ofld_rxq->fl;
1593 
1594 		FL_LOCK(fl);
1595 		set_fl_tag_idx(fl, bufsize);
1596 		FL_UNLOCK(fl);
1597 	}
1598 #endif
1599 }
1600 
1601 int
1602 can_resume_tx(struct sge_eq *eq)
1603 {
1604 	return (reclaimable(eq) >= tx_resume_threshold(eq));
1605 }
1606 
1607 static inline void
1608 init_iq(struct sge_iq *iq, struct adapter *sc, int tmr_idx, int pktc_idx,
1609     int qsize, int esize)
1610 {
1611 	KASSERT(tmr_idx >= 0 && tmr_idx < SGE_NTIMERS,
1612 	    ("%s: bad tmr_idx %d", __func__, tmr_idx));
1613 	KASSERT(pktc_idx < SGE_NCOUNTERS,	/* -ve is ok, means don't use */
1614 	    ("%s: bad pktc_idx %d", __func__, pktc_idx));
1615 
1616 	iq->flags = 0;
1617 	iq->adapter = sc;
1618 	iq->intr_params = V_QINTR_TIMER_IDX(tmr_idx);
1619 	iq->intr_pktc_idx = SGE_NCOUNTERS - 1;
1620 	if (pktc_idx >= 0) {
1621 		iq->intr_params |= F_QINTR_CNT_EN;
1622 		iq->intr_pktc_idx = pktc_idx;
1623 	}
1624 	iq->qsize = roundup2(qsize, 16);	/* See FW_IQ_CMD/iqsize */
1625 	iq->esize = max(esize, 16);		/* See FW_IQ_CMD/iqesize */
1626 }
1627 
1628 static inline void
1629 init_fl(struct sge_fl *fl, int qsize, int bufsize, char *name)
1630 {
1631 	fl->qsize = qsize;
1632 	strlcpy(fl->lockname, name, sizeof(fl->lockname));
1633 	set_fl_tag_idx(fl, bufsize);
1634 }
1635 
1636 static inline void
1637 init_eq(struct sge_eq *eq, int eqtype, int qsize, uint8_t tx_chan,
1638     uint16_t iqid, char *name)
1639 {
1640 	KASSERT(tx_chan < NCHAN, ("%s: bad tx channel %d", __func__, tx_chan));
1641 	KASSERT(eqtype <= EQ_TYPEMASK, ("%s: bad qtype %d", __func__, eqtype));
1642 
1643 	eq->flags = eqtype & EQ_TYPEMASK;
1644 	eq->tx_chan = tx_chan;
1645 	eq->iqid = iqid;
1646 	eq->qsize = qsize;
1647 	strlcpy(eq->lockname, name, sizeof(eq->lockname));
1648 
1649 	TASK_INIT(&eq->tx_task, 0, t4_tx_task, eq);
1650 	callout_init(&eq->tx_callout, CALLOUT_MPSAFE);
1651 }
1652 
1653 static int
1654 alloc_ring(struct adapter *sc, size_t len, bus_dma_tag_t *tag,
1655     bus_dmamap_t *map, bus_addr_t *pa, void **va)
1656 {
1657 	int rc;
1658 
1659 	rc = bus_dma_tag_create(sc->dmat, 512, 0, BUS_SPACE_MAXADDR,
1660 	    BUS_SPACE_MAXADDR, NULL, NULL, len, 1, len, 0, NULL, NULL, tag);
1661 	if (rc != 0) {
1662 		device_printf(sc->dev, "cannot allocate DMA tag: %d\n", rc);
1663 		goto done;
1664 	}
1665 
1666 	rc = bus_dmamem_alloc(*tag, va,
1667 	    BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, map);
1668 	if (rc != 0) {
1669 		device_printf(sc->dev, "cannot allocate DMA memory: %d\n", rc);
1670 		goto done;
1671 	}
1672 
1673 	rc = bus_dmamap_load(*tag, *map, *va, len, oneseg_dma_callback, pa, 0);
1674 	if (rc != 0) {
1675 		device_printf(sc->dev, "cannot load DMA map: %d\n", rc);
1676 		goto done;
1677 	}
1678 done:
1679 	if (rc)
1680 		free_ring(sc, *tag, *map, *pa, *va);
1681 
1682 	return (rc);
1683 }
1684 
1685 static int
1686 free_ring(struct adapter *sc, bus_dma_tag_t tag, bus_dmamap_t map,
1687     bus_addr_t pa, void *va)
1688 {
1689 	if (pa)
1690 		bus_dmamap_unload(tag, map);
1691 	if (va)
1692 		bus_dmamem_free(tag, va, map);
1693 	if (tag)
1694 		bus_dma_tag_destroy(tag);
1695 
1696 	return (0);
1697 }
1698 
1699 /*
1700  * Allocates the ring for an ingress queue and an optional freelist.  If the
1701  * freelist is specified it will be allocated and then associated with the
1702  * ingress queue.
1703  *
1704  * Returns errno on failure.  Resources allocated up to that point may still be
1705  * allocated.  Caller is responsible for cleanup in case this function fails.
1706  *
1707  * If the ingress queue will take interrupts directly (iq->flags & IQ_INTR) then
1708  * the intr_idx specifies the vector, starting from 0.  Otherwise it specifies
1709  * the abs_id of the ingress queue to which its interrupts should be forwarded.
1710  */
1711 static int
1712 alloc_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl,
1713     int intr_idx, int cong)
1714 {
1715 	int rc, i, cntxt_id;
1716 	size_t len;
1717 	struct fw_iq_cmd c;
1718 	struct adapter *sc = iq->adapter;
1719 	__be32 v = 0;
1720 
1721 	len = iq->qsize * iq->esize;
1722 	rc = alloc_ring(sc, len, &iq->desc_tag, &iq->desc_map, &iq->ba,
1723 	    (void **)&iq->desc);
1724 	if (rc != 0)
1725 		return (rc);
1726 
1727 	bzero(&c, sizeof(c));
1728 	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
1729 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_IQ_CMD_PFN(sc->pf) |
1730 	    V_FW_IQ_CMD_VFN(0));
1731 
1732 	c.alloc_to_len16 = htobe32(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
1733 	    FW_LEN16(c));
1734 
1735 	/* Special handling for firmware event queue */
1736 	if (iq == &sc->sge.fwq)
1737 		v |= F_FW_IQ_CMD_IQASYNCH;
1738 
1739 	if (iq->flags & IQ_INTR) {
1740 		KASSERT(intr_idx < sc->intr_count,
1741 		    ("%s: invalid direct intr_idx %d", __func__, intr_idx));
1742 	} else
1743 		v |= F_FW_IQ_CMD_IQANDST;
1744 	v |= V_FW_IQ_CMD_IQANDSTINDEX(intr_idx);
1745 
1746 	c.type_to_iqandstindex = htobe32(v |
1747 	    V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
1748 	    V_FW_IQ_CMD_VIID(pi->viid) |
1749 	    V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT));
1750 	c.iqdroprss_to_iqesize = htobe16(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
1751 	    F_FW_IQ_CMD_IQGTSMODE |
1752 	    V_FW_IQ_CMD_IQINTCNTTHRESH(iq->intr_pktc_idx) |
1753 	    V_FW_IQ_CMD_IQESIZE(ilog2(iq->esize) - 4));
1754 	c.iqsize = htobe16(iq->qsize);
1755 	c.iqaddr = htobe64(iq->ba);
1756 	if (cong >= 0)
1757 		c.iqns_to_fl0congen = htobe32(F_FW_IQ_CMD_IQFLINTCONGEN);
1758 
1759 	if (fl) {
1760 		mtx_init(&fl->fl_lock, fl->lockname, NULL, MTX_DEF);
1761 
1762 		for (i = 0; i < FL_BUF_SIZES; i++) {
1763 
1764 			/*
1765 			 * A freelist buffer must be 16 byte aligned as the SGE
1766 			 * uses the low 4 bits of the bus addr to figure out the
1767 			 * buffer size.
1768 			 */
1769 			rc = bus_dma_tag_create(sc->dmat, 16, 0,
1770 			    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1771 			    FL_BUF_SIZE(i), 1, FL_BUF_SIZE(i), BUS_DMA_ALLOCNOW,
1772 			    NULL, NULL, &fl->tag[i]);
1773 			if (rc != 0) {
1774 				device_printf(sc->dev,
1775 				    "failed to create fl DMA tag[%d]: %d\n",
1776 				    i, rc);
1777 				return (rc);
1778 			}
1779 		}
1780 		len = fl->qsize * RX_FL_ESIZE;
1781 		rc = alloc_ring(sc, len, &fl->desc_tag, &fl->desc_map,
1782 		    &fl->ba, (void **)&fl->desc);
1783 		if (rc)
1784 			return (rc);
1785 
1786 		/* Allocate space for one software descriptor per buffer. */
1787 		fl->cap = (fl->qsize - spg_len / RX_FL_ESIZE) * 8;
1788 		FL_LOCK(fl);
1789 		rc = alloc_fl_sdesc(fl);
1790 		FL_UNLOCK(fl);
1791 		if (rc != 0) {
1792 			device_printf(sc->dev,
1793 			    "failed to setup fl software descriptors: %d\n",
1794 			    rc);
1795 			return (rc);
1796 		}
1797 		fl->needed = fl->cap;
1798 		fl->lowat = roundup2(sc->sge.fl_starve_threshold, 8);
1799 
1800 		c.iqns_to_fl0congen |=
1801 		    htobe32(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
1802 			F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
1803 			F_FW_IQ_CMD_FL0PADEN);
1804 		if (cong >= 0) {
1805 			c.iqns_to_fl0congen |=
1806 				htobe32(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
1807 				    F_FW_IQ_CMD_FL0CONGCIF |
1808 				    F_FW_IQ_CMD_FL0CONGEN);
1809 		}
1810 		c.fl0dcaen_to_fl0cidxfthresh =
1811 		    htobe16(V_FW_IQ_CMD_FL0FBMIN(X_FETCHBURSTMIN_64B) |
1812 			V_FW_IQ_CMD_FL0FBMAX(X_FETCHBURSTMAX_512B));
1813 		c.fl0size = htobe16(fl->qsize);
1814 		c.fl0addr = htobe64(fl->ba);
1815 	}
1816 
1817 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
1818 	if (rc != 0) {
1819 		device_printf(sc->dev,
1820 		    "failed to create ingress queue: %d\n", rc);
1821 		return (rc);
1822 	}
1823 
1824 	iq->cdesc = iq->desc;
1825 	iq->cidx = 0;
1826 	iq->gen = 1;
1827 	iq->intr_next = iq->intr_params;
1828 	iq->cntxt_id = be16toh(c.iqid);
1829 	iq->abs_id = be16toh(c.physiqid);
1830 	iq->flags |= IQ_ALLOCATED;
1831 
1832 	cntxt_id = iq->cntxt_id - sc->sge.iq_start;
1833 	if (cntxt_id >= sc->sge.niq) {
1834 		panic ("%s: iq->cntxt_id (%d) more than the max (%d)", __func__,
1835 		    cntxt_id, sc->sge.niq - 1);
1836 	}
1837 	sc->sge.iqmap[cntxt_id] = iq;
1838 
1839 	if (fl) {
1840 		fl->cntxt_id = be16toh(c.fl0id);
1841 		fl->pidx = fl->cidx = 0;
1842 
1843 		cntxt_id = fl->cntxt_id - sc->sge.eq_start;
1844 		if (cntxt_id >= sc->sge.neq) {
1845 			panic("%s: fl->cntxt_id (%d) more than the max (%d)",
1846 			    __func__, cntxt_id, sc->sge.neq - 1);
1847 		}
1848 		sc->sge.eqmap[cntxt_id] = (void *)fl;
1849 
1850 		FL_LOCK(fl);
1851 		/* Enough to make sure the SGE doesn't think it's starved */
1852 		refill_fl(sc, fl, fl->lowat);
1853 		FL_UNLOCK(fl);
1854 
1855 		iq->flags |= IQ_HAS_FL;
1856 	}
1857 
1858 	/* Enable IQ interrupts */
1859 	atomic_store_rel_int(&iq->state, IQS_IDLE);
1860 	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_SEINTARM(iq->intr_params) |
1861 	    V_INGRESSQID(iq->cntxt_id));
1862 
1863 	return (0);
1864 }
1865 
1866 static int
1867 free_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl)
1868 {
1869 	int i, rc;
1870 	struct adapter *sc = iq->adapter;
1871 	device_t dev;
1872 
1873 	if (sc == NULL)
1874 		return (0);	/* nothing to do */
1875 
1876 	dev = pi ? pi->dev : sc->dev;
1877 
1878 	if (iq->flags & IQ_ALLOCATED) {
1879 		rc = -t4_iq_free(sc, sc->mbox, sc->pf, 0,
1880 		    FW_IQ_TYPE_FL_INT_CAP, iq->cntxt_id,
1881 		    fl ? fl->cntxt_id : 0xffff, 0xffff);
1882 		if (rc != 0) {
1883 			device_printf(dev,
1884 			    "failed to free queue %p: %d\n", iq, rc);
1885 			return (rc);
1886 		}
1887 		iq->flags &= ~IQ_ALLOCATED;
1888 	}
1889 
1890 	free_ring(sc, iq->desc_tag, iq->desc_map, iq->ba, iq->desc);
1891 
1892 	bzero(iq, sizeof(*iq));
1893 
1894 	if (fl) {
1895 		free_ring(sc, fl->desc_tag, fl->desc_map, fl->ba,
1896 		    fl->desc);
1897 
1898 		if (fl->sdesc) {
1899 			FL_LOCK(fl);
1900 			free_fl_sdesc(fl);
1901 			FL_UNLOCK(fl);
1902 		}
1903 
1904 		if (mtx_initialized(&fl->fl_lock))
1905 			mtx_destroy(&fl->fl_lock);
1906 
1907 		for (i = 0; i < FL_BUF_SIZES; i++) {
1908 			if (fl->tag[i])
1909 				bus_dma_tag_destroy(fl->tag[i]);
1910 		}
1911 
1912 		bzero(fl, sizeof(*fl));
1913 	}
1914 
1915 	return (0);
1916 }
1917 
1918 static int
1919 alloc_fwq(struct adapter *sc)
1920 {
1921 	int rc, intr_idx;
1922 	struct sge_iq *fwq = &sc->sge.fwq;
1923 	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
1924 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
1925 
1926 	init_iq(fwq, sc, 0, 0, FW_IQ_QSIZE, FW_IQ_ESIZE);
1927 	fwq->flags |= IQ_INTR;	/* always */
1928 	intr_idx = sc->intr_count > 1 ? 1 : 0;
1929 	rc = alloc_iq_fl(sc->port[0], fwq, NULL, intr_idx, -1);
1930 	if (rc != 0) {
1931 		device_printf(sc->dev,
1932 		    "failed to create firmware event queue: %d\n", rc);
1933 		return (rc);
1934 	}
1935 
1936 	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "fwq", CTLFLAG_RD,
1937 	    NULL, "firmware event queue");
1938 	children = SYSCTL_CHILDREN(oid);
1939 
1940 	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "abs_id",
1941 	    CTLTYPE_INT | CTLFLAG_RD, &fwq->abs_id, 0, sysctl_uint16, "I",
1942 	    "absolute id of the queue");
1943 	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cntxt_id",
1944 	    CTLTYPE_INT | CTLFLAG_RD, &fwq->cntxt_id, 0, sysctl_uint16, "I",
1945 	    "SGE context id of the queue");
1946 	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cidx",
1947 	    CTLTYPE_INT | CTLFLAG_RD, &fwq->cidx, 0, sysctl_uint16, "I",
1948 	    "consumer index");
1949 
1950 	return (0);
1951 }
1952 
1953 static int
1954 free_fwq(struct adapter *sc)
1955 {
1956 	return free_iq_fl(NULL, &sc->sge.fwq, NULL);
1957 }
1958 
1959 static int
1960 alloc_mgmtq(struct adapter *sc)
1961 {
1962 	int rc;
1963 	struct sge_wrq *mgmtq = &sc->sge.mgmtq;
1964 	char name[16];
1965 	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
1966 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
1967 
1968 	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "mgmtq", CTLFLAG_RD,
1969 	    NULL, "management queue");
1970 
1971 	snprintf(name, sizeof(name), "%s mgmtq", device_get_nameunit(sc->dev));
1972 	init_eq(&mgmtq->eq, EQ_CTRL, CTRL_EQ_QSIZE, sc->port[0]->tx_chan,
1973 	    sc->sge.fwq.cntxt_id, name);
1974 	rc = alloc_wrq(sc, NULL, mgmtq, oid);
1975 	if (rc != 0) {
1976 		device_printf(sc->dev,
1977 		    "failed to create management queue: %d\n", rc);
1978 		return (rc);
1979 	}
1980 
1981 	return (0);
1982 }
1983 
1984 static int
1985 free_mgmtq(struct adapter *sc)
1986 {
1987 
1988 	return free_wrq(sc, &sc->sge.mgmtq);
1989 }
1990 
1991 static inline int
1992 tnl_cong(struct port_info *pi)
1993 {
1994 
1995 	if (cong_drop == -1)
1996 		return (-1);
1997 	else if (cong_drop == 1)
1998 		return (0);
1999 	else
2000 		return (1 << pi->tx_chan);
2001 }
2002 
2003 static int
2004 alloc_rxq(struct port_info *pi, struct sge_rxq *rxq, int intr_idx, int idx,
2005     struct sysctl_oid *oid)
2006 {
2007 	int rc;
2008 	struct sysctl_oid_list *children;
2009 	char name[16];
2010 
2011 	rc = alloc_iq_fl(pi, &rxq->iq, &rxq->fl, intr_idx, tnl_cong(pi));
2012 	if (rc != 0)
2013 		return (rc);
2014 
2015 	FL_LOCK(&rxq->fl);
2016 	refill_fl(pi->adapter, &rxq->fl, rxq->fl.needed / 8);
2017 	FL_UNLOCK(&rxq->fl);
2018 
2019 #if defined(INET) || defined(INET6)
2020 	rc = tcp_lro_init(&rxq->lro);
2021 	if (rc != 0)
2022 		return (rc);
2023 	rxq->lro.ifp = pi->ifp; /* also indicates LRO init'ed */
2024 
2025 	if (pi->ifp->if_capenable & IFCAP_LRO)
2026 		rxq->iq.flags |= IQ_LRO_ENABLED;
2027 #endif
2028 	rxq->ifp = pi->ifp;
2029 
2030 	children = SYSCTL_CHILDREN(oid);
2031 
2032 	snprintf(name, sizeof(name), "%d", idx);
2033 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2034 	    NULL, "rx queue");
2035 	children = SYSCTL_CHILDREN(oid);
2036 
2037 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
2038 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.abs_id, 0, sysctl_uint16, "I",
2039 	    "absolute id of the queue");
2040 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2041 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cntxt_id, 0, sysctl_uint16, "I",
2042 	    "SGE context id of the queue");
2043 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2044 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cidx, 0, sysctl_uint16, "I",
2045 	    "consumer index");
2046 #if defined(INET) || defined(INET6)
2047 	SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_queued", CTLFLAG_RD,
2048 	    &rxq->lro.lro_queued, 0, NULL);
2049 	SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_flushed", CTLFLAG_RD,
2050 	    &rxq->lro.lro_flushed, 0, NULL);
2051 #endif
2052 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "rxcsum", CTLFLAG_RD,
2053 	    &rxq->rxcsum, "# of times hardware assisted with checksum");
2054 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_extraction",
2055 	    CTLFLAG_RD, &rxq->vlan_extraction,
2056 	    "# of times hardware extracted 802.1Q tag");
2057 
2058 	children = SYSCTL_CHILDREN(oid);
2059 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
2060 	    NULL, "freelist");
2061 	children = SYSCTL_CHILDREN(oid);
2062 
2063 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2064 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->fl.cntxt_id, 0, sysctl_uint16, "I",
2065 	    "SGE context id of the queue");
2066 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
2067 	    &rxq->fl.cidx, 0, "consumer index");
2068 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
2069 	    &rxq->fl.pidx, 0, "producer index");
2070 
2071 	return (rc);
2072 }
2073 
2074 static int
2075 free_rxq(struct port_info *pi, struct sge_rxq *rxq)
2076 {
2077 	int rc;
2078 
2079 #if defined(INET) || defined(INET6)
2080 	if (rxq->lro.ifp) {
2081 		tcp_lro_free(&rxq->lro);
2082 		rxq->lro.ifp = NULL;
2083 	}
2084 #endif
2085 
2086 	rc = free_iq_fl(pi, &rxq->iq, &rxq->fl);
2087 	if (rc == 0)
2088 		bzero(rxq, sizeof(*rxq));
2089 
2090 	return (rc);
2091 }
2092 
2093 #ifdef TCP_OFFLOAD
2094 static int
2095 alloc_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq,
2096     int intr_idx, int idx, struct sysctl_oid *oid)
2097 {
2098 	int rc;
2099 	struct sysctl_oid_list *children;
2100 	char name[16];
2101 
2102 	rc = alloc_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl, intr_idx,
2103 	    1 << pi->tx_chan);
2104 	if (rc != 0)
2105 		return (rc);
2106 
2107 	children = SYSCTL_CHILDREN(oid);
2108 
2109 	snprintf(name, sizeof(name), "%d", idx);
2110 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2111 	    NULL, "rx queue");
2112 	children = SYSCTL_CHILDREN(oid);
2113 
2114 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
2115 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.abs_id, 0, sysctl_uint16,
2116 	    "I", "absolute id of the queue");
2117 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2118 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cntxt_id, 0, sysctl_uint16,
2119 	    "I", "SGE context id of the queue");
2120 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2121 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cidx, 0, sysctl_uint16, "I",
2122 	    "consumer index");
2123 
2124 	children = SYSCTL_CHILDREN(oid);
2125 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
2126 	    NULL, "freelist");
2127 	children = SYSCTL_CHILDREN(oid);
2128 
2129 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2130 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->fl.cntxt_id, 0, sysctl_uint16,
2131 	    "I", "SGE context id of the queue");
2132 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
2133 	    &ofld_rxq->fl.cidx, 0, "consumer index");
2134 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
2135 	    &ofld_rxq->fl.pidx, 0, "producer index");
2136 
2137 	return (rc);
2138 }
2139 
2140 static int
2141 free_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq)
2142 {
2143 	int rc;
2144 
2145 	rc = free_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl);
2146 	if (rc == 0)
2147 		bzero(ofld_rxq, sizeof(*ofld_rxq));
2148 
2149 	return (rc);
2150 }
2151 #endif
2152 
2153 static int
2154 ctrl_eq_alloc(struct adapter *sc, struct sge_eq *eq)
2155 {
2156 	int rc, cntxt_id;
2157 	struct fw_eq_ctrl_cmd c;
2158 
2159 	bzero(&c, sizeof(c));
2160 
2161 	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
2162 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_CTRL_CMD_PFN(sc->pf) |
2163 	    V_FW_EQ_CTRL_CMD_VFN(0));
2164 	c.alloc_to_len16 = htobe32(F_FW_EQ_CTRL_CMD_ALLOC |
2165 	    F_FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
2166 	c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(eq->iqid)); /* XXX */
2167 	c.physeqid_pkd = htobe32(0);
2168 	c.fetchszm_to_iqid =
2169 	    htobe32(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2170 		V_FW_EQ_CTRL_CMD_PCIECHN(eq->tx_chan) |
2171 		F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(eq->iqid));
2172 	c.dcaen_to_eqsize =
2173 	    htobe32(V_FW_EQ_CTRL_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2174 		V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2175 		V_FW_EQ_CTRL_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2176 		V_FW_EQ_CTRL_CMD_EQSIZE(eq->qsize));
2177 	c.eqaddr = htobe64(eq->ba);
2178 
2179 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2180 	if (rc != 0) {
2181 		device_printf(sc->dev,
2182 		    "failed to create control queue %d: %d\n", eq->tx_chan, rc);
2183 		return (rc);
2184 	}
2185 	eq->flags |= EQ_ALLOCATED;
2186 
2187 	eq->cntxt_id = G_FW_EQ_CTRL_CMD_EQID(be32toh(c.cmpliqid_eqid));
2188 	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2189 	if (cntxt_id >= sc->sge.neq)
2190 	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2191 		cntxt_id, sc->sge.neq - 1);
2192 	sc->sge.eqmap[cntxt_id] = eq;
2193 
2194 	return (rc);
2195 }
2196 
2197 static int
2198 eth_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2199 {
2200 	int rc, cntxt_id;
2201 	struct fw_eq_eth_cmd c;
2202 
2203 	bzero(&c, sizeof(c));
2204 
2205 	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
2206 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
2207 	    V_FW_EQ_ETH_CMD_VFN(0));
2208 	c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
2209 	    F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
2210 	c.viid_pkd = htobe32(V_FW_EQ_ETH_CMD_VIID(pi->viid));
2211 	c.fetchszm_to_iqid =
2212 	    htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2213 		V_FW_EQ_ETH_CMD_PCIECHN(eq->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
2214 		V_FW_EQ_ETH_CMD_IQID(eq->iqid));
2215 	c.dcaen_to_eqsize = htobe32(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2216 		      V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2217 		      V_FW_EQ_ETH_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2218 		      V_FW_EQ_ETH_CMD_EQSIZE(eq->qsize));
2219 	c.eqaddr = htobe64(eq->ba);
2220 
2221 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2222 	if (rc != 0) {
2223 		device_printf(pi->dev,
2224 		    "failed to create Ethernet egress queue: %d\n", rc);
2225 		return (rc);
2226 	}
2227 	eq->flags |= EQ_ALLOCATED;
2228 
2229 	eq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
2230 	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2231 	if (cntxt_id >= sc->sge.neq)
2232 	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2233 		cntxt_id, sc->sge.neq - 1);
2234 	sc->sge.eqmap[cntxt_id] = eq;
2235 
2236 	return (rc);
2237 }
2238 
2239 #ifdef TCP_OFFLOAD
2240 static int
2241 ofld_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2242 {
2243 	int rc, cntxt_id;
2244 	struct fw_eq_ofld_cmd c;
2245 
2246 	bzero(&c, sizeof(c));
2247 
2248 	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_OFLD_CMD) | F_FW_CMD_REQUEST |
2249 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_OFLD_CMD_PFN(sc->pf) |
2250 	    V_FW_EQ_OFLD_CMD_VFN(0));
2251 	c.alloc_to_len16 = htonl(F_FW_EQ_OFLD_CMD_ALLOC |
2252 	    F_FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
2253 	c.fetchszm_to_iqid =
2254 		htonl(V_FW_EQ_OFLD_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2255 		    V_FW_EQ_OFLD_CMD_PCIECHN(eq->tx_chan) |
2256 		    F_FW_EQ_OFLD_CMD_FETCHRO | V_FW_EQ_OFLD_CMD_IQID(eq->iqid));
2257 	c.dcaen_to_eqsize =
2258 	    htobe32(V_FW_EQ_OFLD_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2259 		V_FW_EQ_OFLD_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2260 		V_FW_EQ_OFLD_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2261 		V_FW_EQ_OFLD_CMD_EQSIZE(eq->qsize));
2262 	c.eqaddr = htobe64(eq->ba);
2263 
2264 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2265 	if (rc != 0) {
2266 		device_printf(pi->dev,
2267 		    "failed to create egress queue for TCP offload: %d\n", rc);
2268 		return (rc);
2269 	}
2270 	eq->flags |= EQ_ALLOCATED;
2271 
2272 	eq->cntxt_id = G_FW_EQ_OFLD_CMD_EQID(be32toh(c.eqid_pkd));
2273 	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2274 	if (cntxt_id >= sc->sge.neq)
2275 	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2276 		cntxt_id, sc->sge.neq - 1);
2277 	sc->sge.eqmap[cntxt_id] = eq;
2278 
2279 	return (rc);
2280 }
2281 #endif
2282 
2283 static int
2284 alloc_eq(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2285 {
2286 	int rc;
2287 	size_t len;
2288 
2289 	mtx_init(&eq->eq_lock, eq->lockname, NULL, MTX_DEF);
2290 
2291 	len = eq->qsize * EQ_ESIZE;
2292 	rc = alloc_ring(sc, len, &eq->desc_tag, &eq->desc_map,
2293 	    &eq->ba, (void **)&eq->desc);
2294 	if (rc)
2295 		return (rc);
2296 
2297 	eq->cap = eq->qsize - spg_len / EQ_ESIZE;
2298 	eq->spg = (void *)&eq->desc[eq->cap];
2299 	eq->avail = eq->cap - 1;	/* one less to avoid cidx = pidx */
2300 	eq->pidx = eq->cidx = 0;
2301 	eq->doorbells = sc->doorbells;
2302 
2303 	switch (eq->flags & EQ_TYPEMASK) {
2304 	case EQ_CTRL:
2305 		rc = ctrl_eq_alloc(sc, eq);
2306 		break;
2307 
2308 	case EQ_ETH:
2309 		rc = eth_eq_alloc(sc, pi, eq);
2310 		break;
2311 
2312 #ifdef TCP_OFFLOAD
2313 	case EQ_OFLD:
2314 		rc = ofld_eq_alloc(sc, pi, eq);
2315 		break;
2316 #endif
2317 
2318 	default:
2319 		panic("%s: invalid eq type %d.", __func__,
2320 		    eq->flags & EQ_TYPEMASK);
2321 	}
2322 	if (rc != 0) {
2323 		device_printf(sc->dev,
2324 		    "failed to allocate egress queue(%d): %d",
2325 		    eq->flags & EQ_TYPEMASK, rc);
2326 	}
2327 
2328 	eq->tx_callout.c_cpu = eq->cntxt_id % mp_ncpus;
2329 
2330 	if (isset(&eq->doorbells, DOORBELL_UDB) ||
2331 	    isset(&eq->doorbells, DOORBELL_UDBWC) ||
2332 	    isset(&eq->doorbells, DOORBELL_WCWR)) {
2333 		uint32_t s_qpp = sc->sge.s_qpp;
2334 		uint32_t mask = (1 << s_qpp) - 1;
2335 		volatile uint8_t *udb;
2336 
2337 		udb = sc->udbs_base + UDBS_DB_OFFSET;
2338 		udb += (eq->cntxt_id >> s_qpp) << PAGE_SHIFT;	/* pg offset */
2339 		eq->udb_qid = eq->cntxt_id & mask;		/* id in page */
2340 		if (eq->udb_qid > PAGE_SIZE / UDBS_SEG_SIZE)
2341 	    		clrbit(&eq->doorbells, DOORBELL_WCWR);
2342 		else {
2343 			udb += eq->udb_qid << UDBS_SEG_SHIFT;	/* seg offset */
2344 			eq->udb_qid = 0;
2345 		}
2346 		eq->udb = (volatile void *)udb;
2347 	}
2348 
2349 	return (rc);
2350 }
2351 
2352 static int
2353 free_eq(struct adapter *sc, struct sge_eq *eq)
2354 {
2355 	int rc;
2356 
2357 	if (eq->flags & EQ_ALLOCATED) {
2358 		switch (eq->flags & EQ_TYPEMASK) {
2359 		case EQ_CTRL:
2360 			rc = -t4_ctrl_eq_free(sc, sc->mbox, sc->pf, 0,
2361 			    eq->cntxt_id);
2362 			break;
2363 
2364 		case EQ_ETH:
2365 			rc = -t4_eth_eq_free(sc, sc->mbox, sc->pf, 0,
2366 			    eq->cntxt_id);
2367 			break;
2368 
2369 #ifdef TCP_OFFLOAD
2370 		case EQ_OFLD:
2371 			rc = -t4_ofld_eq_free(sc, sc->mbox, sc->pf, 0,
2372 			    eq->cntxt_id);
2373 			break;
2374 #endif
2375 
2376 		default:
2377 			panic("%s: invalid eq type %d.", __func__,
2378 			    eq->flags & EQ_TYPEMASK);
2379 		}
2380 		if (rc != 0) {
2381 			device_printf(sc->dev,
2382 			    "failed to free egress queue (%d): %d\n",
2383 			    eq->flags & EQ_TYPEMASK, rc);
2384 			return (rc);
2385 		}
2386 		eq->flags &= ~EQ_ALLOCATED;
2387 	}
2388 
2389 	free_ring(sc, eq->desc_tag, eq->desc_map, eq->ba, eq->desc);
2390 
2391 	if (mtx_initialized(&eq->eq_lock))
2392 		mtx_destroy(&eq->eq_lock);
2393 
2394 	bzero(eq, sizeof(*eq));
2395 	return (0);
2396 }
2397 
2398 static int
2399 alloc_wrq(struct adapter *sc, struct port_info *pi, struct sge_wrq *wrq,
2400     struct sysctl_oid *oid)
2401 {
2402 	int rc;
2403 	struct sysctl_ctx_list *ctx = pi ? &pi->ctx : &sc->ctx;
2404 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2405 
2406 	rc = alloc_eq(sc, pi, &wrq->eq);
2407 	if (rc)
2408 		return (rc);
2409 
2410 	wrq->adapter = sc;
2411 	STAILQ_INIT(&wrq->wr_list);
2412 
2413 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2414 	    &wrq->eq.cntxt_id, 0, "SGE context id of the queue");
2415 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
2416 	    CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.cidx, 0, sysctl_uint16, "I",
2417 	    "consumer index");
2418 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pidx",
2419 	    CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.pidx, 0, sysctl_uint16, "I",
2420 	    "producer index");
2421 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs", CTLFLAG_RD,
2422 	    &wrq->tx_wrs, "# of work requests");
2423 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2424 	    &wrq->no_desc, 0,
2425 	    "# of times queue ran out of hardware descriptors");
2426 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2427 	    &wrq->eq.unstalled, 0, "# of times queue recovered after stall");
2428 
2429 
2430 	return (rc);
2431 }
2432 
2433 static int
2434 free_wrq(struct adapter *sc, struct sge_wrq *wrq)
2435 {
2436 	int rc;
2437 
2438 	rc = free_eq(sc, &wrq->eq);
2439 	if (rc)
2440 		return (rc);
2441 
2442 	bzero(wrq, sizeof(*wrq));
2443 	return (0);
2444 }
2445 
2446 static int
2447 alloc_txq(struct port_info *pi, struct sge_txq *txq, int idx,
2448     struct sysctl_oid *oid)
2449 {
2450 	int rc;
2451 	struct adapter *sc = pi->adapter;
2452 	struct sge_eq *eq = &txq->eq;
2453 	char name[16];
2454 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2455 
2456 	rc = alloc_eq(sc, pi, eq);
2457 	if (rc)
2458 		return (rc);
2459 
2460 	txq->ifp = pi->ifp;
2461 
2462 	txq->sdesc = malloc(eq->cap * sizeof(struct tx_sdesc), M_CXGBE,
2463 	    M_ZERO | M_WAITOK);
2464 	txq->br = buf_ring_alloc(eq->qsize, M_CXGBE, M_WAITOK, &eq->eq_lock);
2465 
2466 	rc = bus_dma_tag_create(sc->dmat, 1, 0, BUS_SPACE_MAXADDR,
2467 	    BUS_SPACE_MAXADDR, NULL, NULL, 64 * 1024, TX_SGL_SEGS,
2468 	    BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL, NULL, &txq->tx_tag);
2469 	if (rc != 0) {
2470 		device_printf(sc->dev,
2471 		    "failed to create tx DMA tag: %d\n", rc);
2472 		return (rc);
2473 	}
2474 
2475 	/*
2476 	 * We can stuff ~10 frames in an 8-descriptor txpkts WR (8 is the SGE
2477 	 * limit for any WR).  txq->no_dmamap events shouldn't occur if maps is
2478 	 * sized for the worst case.
2479 	 */
2480 	rc = t4_alloc_tx_maps(&txq->txmaps, txq->tx_tag, eq->qsize * 10 / 8,
2481 	    M_WAITOK);
2482 	if (rc != 0) {
2483 		device_printf(sc->dev, "failed to setup tx DMA maps: %d\n", rc);
2484 		return (rc);
2485 	}
2486 
2487 	snprintf(name, sizeof(name), "%d", idx);
2488 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2489 	    NULL, "tx queue");
2490 	children = SYSCTL_CHILDREN(oid);
2491 
2492 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2493 	    &eq->cntxt_id, 0, "SGE context id of the queue");
2494 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2495 	    CTLTYPE_INT | CTLFLAG_RD, &eq->cidx, 0, sysctl_uint16, "I",
2496 	    "consumer index");
2497 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "pidx",
2498 	    CTLTYPE_INT | CTLFLAG_RD, &eq->pidx, 0, sysctl_uint16, "I",
2499 	    "producer index");
2500 
2501 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txcsum", CTLFLAG_RD,
2502 	    &txq->txcsum, "# of times hardware assisted with checksum");
2503 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_insertion",
2504 	    CTLFLAG_RD, &txq->vlan_insertion,
2505 	    "# of times hardware inserted 802.1Q tag");
2506 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "tso_wrs", CTLFLAG_RD,
2507 	    &txq->tso_wrs, "# of TSO work requests");
2508 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "imm_wrs", CTLFLAG_RD,
2509 	    &txq->imm_wrs, "# of work requests with immediate data");
2510 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "sgl_wrs", CTLFLAG_RD,
2511 	    &txq->sgl_wrs, "# of work requests with direct SGL");
2512 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkt_wrs", CTLFLAG_RD,
2513 	    &txq->txpkt_wrs, "# of txpkt work requests (one pkt/WR)");
2514 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_wrs", CTLFLAG_RD,
2515 	    &txq->txpkts_wrs, "# of txpkts work requests (multiple pkts/WR)");
2516 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_pkts", CTLFLAG_RD,
2517 	    &txq->txpkts_pkts, "# of frames tx'd using txpkts work requests");
2518 
2519 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "br_drops", CTLFLAG_RD,
2520 	    &txq->br->br_drops, "# of drops in the buf_ring for this queue");
2521 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_dmamap", CTLFLAG_RD,
2522 	    &txq->no_dmamap, 0, "# of times txq ran out of DMA maps");
2523 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2524 	    &txq->no_desc, 0, "# of times txq ran out of hardware descriptors");
2525 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "egr_update", CTLFLAG_RD,
2526 	    &eq->egr_update, 0, "egress update notifications from the SGE");
2527 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2528 	    &eq->unstalled, 0, "# of times txq recovered after stall");
2529 
2530 	return (rc);
2531 }
2532 
2533 static int
2534 free_txq(struct port_info *pi, struct sge_txq *txq)
2535 {
2536 	int rc;
2537 	struct adapter *sc = pi->adapter;
2538 	struct sge_eq *eq = &txq->eq;
2539 
2540 	rc = free_eq(sc, eq);
2541 	if (rc)
2542 		return (rc);
2543 
2544 	free(txq->sdesc, M_CXGBE);
2545 
2546 	if (txq->txmaps.maps)
2547 		t4_free_tx_maps(&txq->txmaps, txq->tx_tag);
2548 
2549 	buf_ring_free(txq->br, M_CXGBE);
2550 
2551 	if (txq->tx_tag)
2552 		bus_dma_tag_destroy(txq->tx_tag);
2553 
2554 	bzero(txq, sizeof(*txq));
2555 	return (0);
2556 }
2557 
2558 static void
2559 oneseg_dma_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2560 {
2561 	bus_addr_t *ba = arg;
2562 
2563 	KASSERT(nseg == 1,
2564 	    ("%s meant for single segment mappings only.", __func__));
2565 
2566 	*ba = error ? 0 : segs->ds_addr;
2567 }
2568 
2569 static inline bool
2570 is_new_response(const struct sge_iq *iq, struct rsp_ctrl **ctrl)
2571 {
2572 	*ctrl = (void *)((uintptr_t)iq->cdesc +
2573 	    (iq->esize - sizeof(struct rsp_ctrl)));
2574 
2575 	return (((*ctrl)->u.type_gen >> S_RSPD_GEN) == iq->gen);
2576 }
2577 
2578 static inline void
2579 iq_next(struct sge_iq *iq)
2580 {
2581 	iq->cdesc = (void *) ((uintptr_t)iq->cdesc + iq->esize);
2582 	if (__predict_false(++iq->cidx == iq->qsize - 1)) {
2583 		iq->cidx = 0;
2584 		iq->gen ^= 1;
2585 		iq->cdesc = iq->desc;
2586 	}
2587 }
2588 
2589 #define FL_HW_IDX(x) ((x) >> 3)
2590 static inline void
2591 ring_fl_db(struct adapter *sc, struct sge_fl *fl)
2592 {
2593 	int ndesc = fl->pending / 8;
2594 	uint32_t v;
2595 
2596 	if (FL_HW_IDX(fl->pidx) == FL_HW_IDX(fl->cidx))
2597 		ndesc--;	/* hold back one credit */
2598 
2599 	if (ndesc <= 0)
2600 		return;		/* nothing to do */
2601 
2602 	v = F_DBPRIO | V_QID(fl->cntxt_id) | V_PIDX(ndesc);
2603 	if (is_t5(sc))
2604 		v |= F_DBTYPE;
2605 
2606 	wmb();
2607 
2608 	t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL), v);
2609 	fl->pending -= ndesc * 8;
2610 }
2611 
2612 /*
2613  * Fill up the freelist by upto nbufs and maybe ring its doorbell.
2614  *
2615  * Returns non-zero to indicate that it should be added to the list of starving
2616  * freelists.
2617  */
2618 static int
2619 refill_fl(struct adapter *sc, struct sge_fl *fl, int nbufs)
2620 {
2621 	__be64 *d = &fl->desc[fl->pidx];
2622 	struct fl_sdesc *sd = &fl->sdesc[fl->pidx];
2623 	bus_dma_tag_t tag;
2624 	bus_addr_t pa;
2625 	caddr_t cl;
2626 	int rc;
2627 
2628 	FL_LOCK_ASSERT_OWNED(fl);
2629 
2630 	if (nbufs > fl->needed)
2631 		nbufs = fl->needed;
2632 
2633 	while (nbufs--) {
2634 
2635 		if (sd->cl != NULL) {
2636 
2637 			/*
2638 			 * This happens when a frame small enough to fit
2639 			 * entirely in an mbuf was received in cl last time.
2640 			 * We'd held on to cl and can reuse it now.  Note that
2641 			 * we reuse a cluster of the old size if fl->tag_idx is
2642 			 * no longer the same as sd->tag_idx.
2643 			 */
2644 
2645 			KASSERT(*d == sd->ba_tag,
2646 			    ("%s: recyling problem at pidx %d",
2647 			    __func__, fl->pidx));
2648 
2649 			d++;
2650 			goto recycled;
2651 		}
2652 
2653 
2654 		if (fl->tag_idx != sd->tag_idx) {
2655 			bus_dmamap_t map;
2656 			bus_dma_tag_t newtag = fl->tag[fl->tag_idx];
2657 			bus_dma_tag_t oldtag = fl->tag[sd->tag_idx];
2658 
2659 			/*
2660 			 * An MTU change can get us here.  Discard the old map
2661 			 * which was created with the old tag, but only if
2662 			 * we're able to get a new one.
2663 			 */
2664 			rc = bus_dmamap_create(newtag, 0, &map);
2665 			if (rc == 0) {
2666 				bus_dmamap_destroy(oldtag, sd->map);
2667 				sd->map = map;
2668 				sd->tag_idx = fl->tag_idx;
2669 			}
2670 		}
2671 
2672 		tag = fl->tag[sd->tag_idx];
2673 
2674 		cl = m_cljget(NULL, M_NOWAIT, FL_BUF_SIZE(sd->tag_idx));
2675 		if (cl == NULL)
2676 			break;
2677 
2678 		rc = bus_dmamap_load(tag, sd->map, cl, FL_BUF_SIZE(sd->tag_idx),
2679 		    oneseg_dma_callback, &pa, 0);
2680 		if (rc != 0 || pa == 0) {
2681 			fl->dmamap_failed++;
2682 			uma_zfree(FL_BUF_ZONE(sd->tag_idx), cl);
2683 			break;
2684 		}
2685 
2686 		sd->cl = cl;
2687 		*d++ = htobe64(pa | sd->tag_idx);
2688 
2689 #ifdef INVARIANTS
2690 		sd->ba_tag = htobe64(pa | sd->tag_idx);
2691 #endif
2692 
2693 recycled:
2694 		/* sd->m is never recycled, should always be NULL */
2695 		KASSERT(sd->m == NULL, ("%s: stray mbuf", __func__));
2696 
2697 		sd->m = m_gethdr(M_NOWAIT, MT_NOINIT);
2698 		if (sd->m == NULL)
2699 			break;
2700 
2701 		fl->pending++;
2702 		fl->needed--;
2703 		sd++;
2704 		if (++fl->pidx == fl->cap) {
2705 			fl->pidx = 0;
2706 			sd = fl->sdesc;
2707 			d = fl->desc;
2708 		}
2709 	}
2710 
2711 	if (fl->pending >= 8)
2712 		ring_fl_db(sc, fl);
2713 
2714 	return (FL_RUNNING_LOW(fl) && !(fl->flags & FL_STARVING));
2715 }
2716 
2717 /*
2718  * Attempt to refill all starving freelists.
2719  */
2720 static void
2721 refill_sfl(void *arg)
2722 {
2723 	struct adapter *sc = arg;
2724 	struct sge_fl *fl, *fl_temp;
2725 
2726 	mtx_lock(&sc->sfl_lock);
2727 	TAILQ_FOREACH_SAFE(fl, &sc->sfl, link, fl_temp) {
2728 		FL_LOCK(fl);
2729 		refill_fl(sc, fl, 64);
2730 		if (FL_NOT_RUNNING_LOW(fl) || fl->flags & FL_DOOMED) {
2731 			TAILQ_REMOVE(&sc->sfl, fl, link);
2732 			fl->flags &= ~FL_STARVING;
2733 		}
2734 		FL_UNLOCK(fl);
2735 	}
2736 
2737 	if (!TAILQ_EMPTY(&sc->sfl))
2738 		callout_schedule(&sc->sfl_callout, hz / 5);
2739 	mtx_unlock(&sc->sfl_lock);
2740 }
2741 
2742 static int
2743 alloc_fl_sdesc(struct sge_fl *fl)
2744 {
2745 	struct fl_sdesc *sd;
2746 	bus_dma_tag_t tag;
2747 	int i, rc;
2748 
2749 	FL_LOCK_ASSERT_OWNED(fl);
2750 
2751 	fl->sdesc = malloc(fl->cap * sizeof(struct fl_sdesc), M_CXGBE,
2752 	    M_ZERO | M_WAITOK);
2753 
2754 	tag = fl->tag[fl->tag_idx];
2755 	sd = fl->sdesc;
2756 	for (i = 0; i < fl->cap; i++, sd++) {
2757 
2758 		sd->tag_idx = fl->tag_idx;
2759 		rc = bus_dmamap_create(tag, 0, &sd->map);
2760 		if (rc != 0)
2761 			goto failed;
2762 	}
2763 
2764 	return (0);
2765 failed:
2766 	while (--i >= 0) {
2767 		sd--;
2768 		bus_dmamap_destroy(tag, sd->map);
2769 		if (sd->m) {
2770 			m_init(sd->m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2771 			m_free(sd->m);
2772 			sd->m = NULL;
2773 		}
2774 	}
2775 	KASSERT(sd == fl->sdesc, ("%s: EDOOFUS", __func__));
2776 
2777 	free(fl->sdesc, M_CXGBE);
2778 	fl->sdesc = NULL;
2779 
2780 	return (rc);
2781 }
2782 
2783 static void
2784 free_fl_sdesc(struct sge_fl *fl)
2785 {
2786 	struct fl_sdesc *sd;
2787 	int i;
2788 
2789 	FL_LOCK_ASSERT_OWNED(fl);
2790 
2791 	sd = fl->sdesc;
2792 	for (i = 0; i < fl->cap; i++, sd++) {
2793 
2794 		if (sd->m) {
2795 			m_init(sd->m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2796 			m_free(sd->m);
2797 			sd->m = NULL;
2798 		}
2799 
2800 		if (sd->cl) {
2801 			bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
2802 			uma_zfree(FL_BUF_ZONE(sd->tag_idx), sd->cl);
2803 			sd->cl = NULL;
2804 		}
2805 
2806 		bus_dmamap_destroy(fl->tag[sd->tag_idx], sd->map);
2807 	}
2808 
2809 	free(fl->sdesc, M_CXGBE);
2810 	fl->sdesc = NULL;
2811 }
2812 
2813 int
2814 t4_alloc_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag, int count,
2815     int flags)
2816 {
2817 	struct tx_map *txm;
2818 	int i, rc;
2819 
2820 	txmaps->map_total = txmaps->map_avail = count;
2821 	txmaps->map_cidx = txmaps->map_pidx = 0;
2822 
2823 	txmaps->maps = malloc(count * sizeof(struct tx_map), M_CXGBE,
2824 	    M_ZERO | flags);
2825 
2826 	txm = txmaps->maps;
2827 	for (i = 0; i < count; i++, txm++) {
2828 		rc = bus_dmamap_create(tx_tag, 0, &txm->map);
2829 		if (rc != 0)
2830 			goto failed;
2831 	}
2832 
2833 	return (0);
2834 failed:
2835 	while (--i >= 0) {
2836 		txm--;
2837 		bus_dmamap_destroy(tx_tag, txm->map);
2838 	}
2839 	KASSERT(txm == txmaps->maps, ("%s: EDOOFUS", __func__));
2840 
2841 	free(txmaps->maps, M_CXGBE);
2842 	txmaps->maps = NULL;
2843 
2844 	return (rc);
2845 }
2846 
2847 void
2848 t4_free_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag)
2849 {
2850 	struct tx_map *txm;
2851 	int i;
2852 
2853 	txm = txmaps->maps;
2854 	for (i = 0; i < txmaps->map_total; i++, txm++) {
2855 
2856 		if (txm->m) {
2857 			bus_dmamap_unload(tx_tag, txm->map);
2858 			m_freem(txm->m);
2859 			txm->m = NULL;
2860 		}
2861 
2862 		bus_dmamap_destroy(tx_tag, txm->map);
2863 	}
2864 
2865 	free(txmaps->maps, M_CXGBE);
2866 	txmaps->maps = NULL;
2867 }
2868 
2869 /*
2870  * We'll do immediate data tx for non-TSO, but only when not coalescing.  We're
2871  * willing to use upto 2 hardware descriptors which means a maximum of 96 bytes
2872  * of immediate data.
2873  */
2874 #define IMM_LEN ( \
2875       2 * EQ_ESIZE \
2876     - sizeof(struct fw_eth_tx_pkt_wr) \
2877     - sizeof(struct cpl_tx_pkt_core))
2878 
2879 /*
2880  * Returns non-zero on failure, no need to cleanup anything in that case.
2881  *
2882  * Note 1: We always try to defrag the mbuf if required and return EFBIG only
2883  * if the resulting chain still won't fit in a tx descriptor.
2884  *
2885  * Note 2: We'll pullup the mbuf chain if TSO is requested and the first mbuf
2886  * does not have the TCP header in it.
2887  */
2888 static int
2889 get_pkt_sgl(struct sge_txq *txq, struct mbuf **fp, struct sgl *sgl,
2890     int sgl_only)
2891 {
2892 	struct mbuf *m = *fp;
2893 	struct tx_maps *txmaps;
2894 	struct tx_map *txm;
2895 	int rc, defragged = 0, n;
2896 
2897 	TXQ_LOCK_ASSERT_OWNED(txq);
2898 
2899 	if (m->m_pkthdr.tso_segsz)
2900 		sgl_only = 1;	/* Do not allow immediate data with LSO */
2901 
2902 start:	sgl->nsegs = 0;
2903 
2904 	if (m->m_pkthdr.len <= IMM_LEN && !sgl_only)
2905 		return (0);	/* nsegs = 0 tells caller to use imm. tx */
2906 
2907 	txmaps = &txq->txmaps;
2908 	if (txmaps->map_avail == 0) {
2909 		txq->no_dmamap++;
2910 		return (ENOMEM);
2911 	}
2912 	txm = &txmaps->maps[txmaps->map_pidx];
2913 
2914 	if (m->m_pkthdr.tso_segsz && m->m_len < 50) {
2915 		*fp = m_pullup(m, 50);
2916 		m = *fp;
2917 		if (m == NULL)
2918 			return (ENOBUFS);
2919 	}
2920 
2921 	rc = bus_dmamap_load_mbuf_sg(txq->tx_tag, txm->map, m, sgl->seg,
2922 	    &sgl->nsegs, BUS_DMA_NOWAIT);
2923 	if (rc == EFBIG && defragged == 0) {
2924 		m = m_defrag(m, M_NOWAIT);
2925 		if (m == NULL)
2926 			return (EFBIG);
2927 
2928 		defragged = 1;
2929 		*fp = m;
2930 		goto start;
2931 	}
2932 	if (rc != 0)
2933 		return (rc);
2934 
2935 	txm->m = m;
2936 	txmaps->map_avail--;
2937 	if (++txmaps->map_pidx == txmaps->map_total)
2938 		txmaps->map_pidx = 0;
2939 
2940 	KASSERT(sgl->nsegs > 0 && sgl->nsegs <= TX_SGL_SEGS,
2941 	    ("%s: bad DMA mapping (%d segments)", __func__, sgl->nsegs));
2942 
2943 	/*
2944 	 * Store the # of flits required to hold this frame's SGL in nflits.  An
2945 	 * SGL has a (ULPTX header + len0, addr0) tuple optionally followed by
2946 	 * multiple (len0 + len1, addr0, addr1) tuples.  If addr1 is not used
2947 	 * then len1 must be set to 0.
2948 	 */
2949 	n = sgl->nsegs - 1;
2950 	sgl->nflits = (3 * n) / 2 + (n & 1) + 2;
2951 
2952 	return (0);
2953 }
2954 
2955 
2956 /*
2957  * Releases all the txq resources used up in the specified sgl.
2958  */
2959 static int
2960 free_pkt_sgl(struct sge_txq *txq, struct sgl *sgl)
2961 {
2962 	struct tx_maps *txmaps;
2963 	struct tx_map *txm;
2964 
2965 	TXQ_LOCK_ASSERT_OWNED(txq);
2966 
2967 	if (sgl->nsegs == 0)
2968 		return (0);	/* didn't use any map */
2969 
2970 	txmaps = &txq->txmaps;
2971 
2972 	/* 1 pkt uses exactly 1 map, back it out */
2973 
2974 	txmaps->map_avail++;
2975 	if (txmaps->map_pidx > 0)
2976 		txmaps->map_pidx--;
2977 	else
2978 		txmaps->map_pidx = txmaps->map_total - 1;
2979 
2980 	txm = &txmaps->maps[txmaps->map_pidx];
2981 	bus_dmamap_unload(txq->tx_tag, txm->map);
2982 	txm->m = NULL;
2983 
2984 	return (0);
2985 }
2986 
2987 static int
2988 write_txpkt_wr(struct port_info *pi, struct sge_txq *txq, struct mbuf *m,
2989     struct sgl *sgl)
2990 {
2991 	struct sge_eq *eq = &txq->eq;
2992 	struct fw_eth_tx_pkt_wr *wr;
2993 	struct cpl_tx_pkt_core *cpl;
2994 	uint32_t ctrl;	/* used in many unrelated places */
2995 	uint64_t ctrl1;
2996 	int nflits, ndesc, pktlen;
2997 	struct tx_sdesc *txsd;
2998 	caddr_t dst;
2999 
3000 	TXQ_LOCK_ASSERT_OWNED(txq);
3001 
3002 	pktlen = m->m_pkthdr.len;
3003 
3004 	/*
3005 	 * Do we have enough flits to send this frame out?
3006 	 */
3007 	ctrl = sizeof(struct cpl_tx_pkt_core);
3008 	if (m->m_pkthdr.tso_segsz) {
3009 		nflits = TXPKT_LSO_WR_HDR;
3010 		ctrl += sizeof(struct cpl_tx_pkt_lso_core);
3011 	} else
3012 		nflits = TXPKT_WR_HDR;
3013 	if (sgl->nsegs > 0)
3014 		nflits += sgl->nflits;
3015 	else {
3016 		nflits += howmany(pktlen, 8);
3017 		ctrl += pktlen;
3018 	}
3019 	ndesc = howmany(nflits, 8);
3020 	if (ndesc > eq->avail)
3021 		return (ENOMEM);
3022 
3023 	/* Firmware work request header */
3024 	wr = (void *)&eq->desc[eq->pidx];
3025 	wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
3026 	    V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));
3027 	ctrl = V_FW_WR_LEN16(howmany(nflits, 2));
3028 	if (eq->avail == ndesc) {
3029 		if (!(eq->flags & EQ_CRFLUSHED)) {
3030 			ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
3031 			eq->flags |= EQ_CRFLUSHED;
3032 		}
3033 		eq->flags |= EQ_STALLED;
3034 	}
3035 
3036 	wr->equiq_to_len16 = htobe32(ctrl);
3037 	wr->r3 = 0;
3038 
3039 	if (m->m_pkthdr.tso_segsz) {
3040 		struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
3041 		struct ether_header *eh;
3042 		void *l3hdr;
3043 #if defined(INET) || defined(INET6)
3044 		struct tcphdr *tcp;
3045 #endif
3046 		uint16_t eh_type;
3047 
3048 		ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) | F_LSO_FIRST_SLICE |
3049 		    F_LSO_LAST_SLICE;
3050 
3051 		eh = mtod(m, struct ether_header *);
3052 		eh_type = ntohs(eh->ether_type);
3053 		if (eh_type == ETHERTYPE_VLAN) {
3054 			struct ether_vlan_header *evh = (void *)eh;
3055 
3056 			ctrl |= V_LSO_ETHHDR_LEN(1);
3057 			l3hdr = evh + 1;
3058 			eh_type = ntohs(evh->evl_proto);
3059 		} else
3060 			l3hdr = eh + 1;
3061 
3062 		switch (eh_type) {
3063 #ifdef INET6
3064 		case ETHERTYPE_IPV6:
3065 		{
3066 			struct ip6_hdr *ip6 = l3hdr;
3067 
3068 			/*
3069 			 * XXX-BZ For now we do not pretend to support
3070 			 * IPv6 extension headers.
3071 			 */
3072 			KASSERT(ip6->ip6_nxt == IPPROTO_TCP, ("%s: CSUM_TSO "
3073 			    "with ip6_nxt != TCP: %u", __func__, ip6->ip6_nxt));
3074 			tcp = (struct tcphdr *)(ip6 + 1);
3075 			ctrl |= F_LSO_IPV6;
3076 			ctrl |= V_LSO_IPHDR_LEN(sizeof(*ip6) >> 2) |
3077 			    V_LSO_TCPHDR_LEN(tcp->th_off);
3078 			break;
3079 		}
3080 #endif
3081 #ifdef INET
3082 		case ETHERTYPE_IP:
3083 		{
3084 			struct ip *ip = l3hdr;
3085 
3086 			tcp = (void *)((uintptr_t)ip + ip->ip_hl * 4);
3087 			ctrl |= V_LSO_IPHDR_LEN(ip->ip_hl) |
3088 			    V_LSO_TCPHDR_LEN(tcp->th_off);
3089 			break;
3090 		}
3091 #endif
3092 		default:
3093 			panic("%s: CSUM_TSO but no supported IP version "
3094 			    "(0x%04x)", __func__, eh_type);
3095 		}
3096 
3097 		lso->lso_ctrl = htobe32(ctrl);
3098 		lso->ipid_ofst = htobe16(0);
3099 		lso->mss = htobe16(m->m_pkthdr.tso_segsz);
3100 		lso->seqno_offset = htobe32(0);
3101 		lso->len = htobe32(pktlen);
3102 
3103 		cpl = (void *)(lso + 1);
3104 
3105 		txq->tso_wrs++;
3106 	} else
3107 		cpl = (void *)(wr + 1);
3108 
3109 	/* Checksum offload */
3110 	ctrl1 = 0;
3111 	if (!(m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO)))
3112 		ctrl1 |= F_TXPKT_IPCSUM_DIS;
3113 	if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
3114 	    CSUM_TCP_IPV6 | CSUM_TSO)))
3115 		ctrl1 |= F_TXPKT_L4CSUM_DIS;
3116 	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3117 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3118 		txq->txcsum++;	/* some hardware assistance provided */
3119 
3120 	/* VLAN tag insertion */
3121 	if (m->m_flags & M_VLANTAG) {
3122 		ctrl1 |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3123 		txq->vlan_insertion++;
3124 	}
3125 
3126 	/* CPL header */
3127 	cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3128 	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3129 	cpl->pack = 0;
3130 	cpl->len = htobe16(pktlen);
3131 	cpl->ctrl1 = htobe64(ctrl1);
3132 
3133 	/* Software descriptor */
3134 	txsd = &txq->sdesc[eq->pidx];
3135 	txsd->desc_used = ndesc;
3136 
3137 	eq->pending += ndesc;
3138 	eq->avail -= ndesc;
3139 	eq->pidx += ndesc;
3140 	if (eq->pidx >= eq->cap)
3141 		eq->pidx -= eq->cap;
3142 
3143 	/* SGL */
3144 	dst = (void *)(cpl + 1);
3145 	if (sgl->nsegs > 0) {
3146 		txsd->credits = 1;
3147 		txq->sgl_wrs++;
3148 		write_sgl_to_txd(eq, sgl, &dst);
3149 	} else {
3150 		txsd->credits = 0;
3151 		txq->imm_wrs++;
3152 		for (; m; m = m->m_next) {
3153 			copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
3154 #ifdef INVARIANTS
3155 			pktlen -= m->m_len;
3156 #endif
3157 		}
3158 #ifdef INVARIANTS
3159 		KASSERT(pktlen == 0, ("%s: %d bytes left.", __func__, pktlen));
3160 #endif
3161 
3162 	}
3163 
3164 	txq->txpkt_wrs++;
3165 	return (0);
3166 }
3167 
3168 /*
3169  * Returns 0 to indicate that m has been accepted into a coalesced tx work
3170  * request.  It has either been folded into txpkts or txpkts was flushed and m
3171  * has started a new coalesced work request (as the first frame in a fresh
3172  * txpkts).
3173  *
3174  * Returns non-zero to indicate a failure - caller is responsible for
3175  * transmitting m, if there was anything in txpkts it has been flushed.
3176  */
3177 static int
3178 add_to_txpkts(struct port_info *pi, struct sge_txq *txq, struct txpkts *txpkts,
3179     struct mbuf *m, struct sgl *sgl)
3180 {
3181 	struct sge_eq *eq = &txq->eq;
3182 	int can_coalesce;
3183 	struct tx_sdesc *txsd;
3184 	int flits;
3185 
3186 	TXQ_LOCK_ASSERT_OWNED(txq);
3187 
3188 	KASSERT(sgl->nsegs, ("%s: can't coalesce imm data", __func__));
3189 
3190 	if (txpkts->npkt > 0) {
3191 		flits = TXPKTS_PKT_HDR + sgl->nflits;
3192 		can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
3193 		    txpkts->nflits + flits <= TX_WR_FLITS &&
3194 		    txpkts->nflits + flits <= eq->avail * 8 &&
3195 		    txpkts->plen + m->m_pkthdr.len < 65536;
3196 
3197 		if (can_coalesce) {
3198 			txpkts->npkt++;
3199 			txpkts->nflits += flits;
3200 			txpkts->plen += m->m_pkthdr.len;
3201 
3202 			txsd = &txq->sdesc[eq->pidx];
3203 			txsd->credits++;
3204 
3205 			return (0);
3206 		}
3207 
3208 		/*
3209 		 * Couldn't coalesce m into txpkts.  The first order of business
3210 		 * is to send txpkts on its way.  Then we'll revisit m.
3211 		 */
3212 		write_txpkts_wr(txq, txpkts);
3213 	}
3214 
3215 	/*
3216 	 * Check if we can start a new coalesced tx work request with m as
3217 	 * the first packet in it.
3218 	 */
3219 
3220 	KASSERT(txpkts->npkt == 0, ("%s: txpkts not empty", __func__));
3221 
3222 	flits = TXPKTS_WR_HDR + sgl->nflits;
3223 	can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
3224 	    flits <= eq->avail * 8 && flits <= TX_WR_FLITS;
3225 
3226 	if (can_coalesce == 0)
3227 		return (EINVAL);
3228 
3229 	/*
3230 	 * Start a fresh coalesced tx WR with m as the first frame in it.
3231 	 */
3232 	txpkts->npkt = 1;
3233 	txpkts->nflits = flits;
3234 	txpkts->flitp = &eq->desc[eq->pidx].flit[2];
3235 	txpkts->plen = m->m_pkthdr.len;
3236 
3237 	txsd = &txq->sdesc[eq->pidx];
3238 	txsd->credits = 1;
3239 
3240 	return (0);
3241 }
3242 
3243 /*
3244  * Note that write_txpkts_wr can never run out of hardware descriptors (but
3245  * write_txpkt_wr can).  add_to_txpkts ensures that a frame is accepted for
3246  * coalescing only if sufficient hardware descriptors are available.
3247  */
3248 static void
3249 write_txpkts_wr(struct sge_txq *txq, struct txpkts *txpkts)
3250 {
3251 	struct sge_eq *eq = &txq->eq;
3252 	struct fw_eth_tx_pkts_wr *wr;
3253 	struct tx_sdesc *txsd;
3254 	uint32_t ctrl;
3255 	int ndesc;
3256 
3257 	TXQ_LOCK_ASSERT_OWNED(txq);
3258 
3259 	ndesc = howmany(txpkts->nflits, 8);
3260 
3261 	wr = (void *)&eq->desc[eq->pidx];
3262 	wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
3263 	ctrl = V_FW_WR_LEN16(howmany(txpkts->nflits, 2));
3264 	if (eq->avail == ndesc) {
3265 		if (!(eq->flags & EQ_CRFLUSHED)) {
3266 			ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
3267 			eq->flags |= EQ_CRFLUSHED;
3268 		}
3269 		eq->flags |= EQ_STALLED;
3270 	}
3271 	wr->equiq_to_len16 = htobe32(ctrl);
3272 	wr->plen = htobe16(txpkts->plen);
3273 	wr->npkt = txpkts->npkt;
3274 	wr->r3 = wr->type = 0;
3275 
3276 	/* Everything else already written */
3277 
3278 	txsd = &txq->sdesc[eq->pidx];
3279 	txsd->desc_used = ndesc;
3280 
3281 	KASSERT(eq->avail >= ndesc, ("%s: out of descriptors", __func__));
3282 
3283 	eq->pending += ndesc;
3284 	eq->avail -= ndesc;
3285 	eq->pidx += ndesc;
3286 	if (eq->pidx >= eq->cap)
3287 		eq->pidx -= eq->cap;
3288 
3289 	txq->txpkts_pkts += txpkts->npkt;
3290 	txq->txpkts_wrs++;
3291 	txpkts->npkt = 0;	/* emptied */
3292 }
3293 
3294 static inline void
3295 write_ulp_cpl_sgl(struct port_info *pi, struct sge_txq *txq,
3296     struct txpkts *txpkts, struct mbuf *m, struct sgl *sgl)
3297 {
3298 	struct ulp_txpkt *ulpmc;
3299 	struct ulptx_idata *ulpsc;
3300 	struct cpl_tx_pkt_core *cpl;
3301 	struct sge_eq *eq = &txq->eq;
3302 	uintptr_t flitp, start, end;
3303 	uint64_t ctrl;
3304 	caddr_t dst;
3305 
3306 	KASSERT(txpkts->npkt > 0, ("%s: txpkts is empty", __func__));
3307 
3308 	start = (uintptr_t)eq->desc;
3309 	end = (uintptr_t)eq->spg;
3310 
3311 	/* Checksum offload */
3312 	ctrl = 0;
3313 	if (!(m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO)))
3314 		ctrl |= F_TXPKT_IPCSUM_DIS;
3315 	if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
3316 	    CSUM_TCP_IPV6 | CSUM_TSO)))
3317 		ctrl |= F_TXPKT_L4CSUM_DIS;
3318 	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3319 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3320 		txq->txcsum++;	/* some hardware assistance provided */
3321 
3322 	/* VLAN tag insertion */
3323 	if (m->m_flags & M_VLANTAG) {
3324 		ctrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3325 		txq->vlan_insertion++;
3326 	}
3327 
3328 	/*
3329 	 * The previous packet's SGL must have ended at a 16 byte boundary (this
3330 	 * is required by the firmware/hardware).  It follows that flitp cannot
3331 	 * wrap around between the ULPTX master command and ULPTX subcommand (8
3332 	 * bytes each), and that it can not wrap around in the middle of the
3333 	 * cpl_tx_pkt_core either.
3334 	 */
3335 	flitp = (uintptr_t)txpkts->flitp;
3336 	KASSERT((flitp & 0xf) == 0,
3337 	    ("%s: last SGL did not end at 16 byte boundary: %p",
3338 	    __func__, txpkts->flitp));
3339 
3340 	/* ULP master command */
3341 	ulpmc = (void *)flitp;
3342 	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0) |
3343 	    V_ULP_TXPKT_FID(eq->iqid));
3344 	ulpmc->len = htonl(howmany(sizeof(*ulpmc) + sizeof(*ulpsc) +
3345 	    sizeof(*cpl) + 8 * sgl->nflits, 16));
3346 
3347 	/* ULP subcommand */
3348 	ulpsc = (void *)(ulpmc + 1);
3349 	ulpsc->cmd_more = htobe32(V_ULPTX_CMD((u32)ULP_TX_SC_IMM) |
3350 	    F_ULP_TX_SC_MORE);
3351 	ulpsc->len = htobe32(sizeof(struct cpl_tx_pkt_core));
3352 
3353 	flitp += sizeof(*ulpmc) + sizeof(*ulpsc);
3354 	if (flitp == end)
3355 		flitp = start;
3356 
3357 	/* CPL_TX_PKT */
3358 	cpl = (void *)flitp;
3359 	cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3360 	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3361 	cpl->pack = 0;
3362 	cpl->len = htobe16(m->m_pkthdr.len);
3363 	cpl->ctrl1 = htobe64(ctrl);
3364 
3365 	flitp += sizeof(*cpl);
3366 	if (flitp == end)
3367 		flitp = start;
3368 
3369 	/* SGL for this frame */
3370 	dst = (caddr_t)flitp;
3371 	txpkts->nflits += write_sgl_to_txd(eq, sgl, &dst);
3372 	txpkts->flitp = (void *)dst;
3373 
3374 	KASSERT(((uintptr_t)dst & 0xf) == 0,
3375 	    ("%s: SGL ends at %p (not a 16 byte boundary)", __func__, dst));
3376 }
3377 
3378 /*
3379  * If the SGL ends on an address that is not 16 byte aligned, this function will
3380  * add a 0 filled flit at the end.  It returns 1 in that case.
3381  */
3382 static int
3383 write_sgl_to_txd(struct sge_eq *eq, struct sgl *sgl, caddr_t *to)
3384 {
3385 	__be64 *flitp, *end;
3386 	struct ulptx_sgl *usgl;
3387 	bus_dma_segment_t *seg;
3388 	int i, padded;
3389 
3390 	KASSERT(sgl->nsegs > 0 && sgl->nflits > 0,
3391 	    ("%s: bad SGL - nsegs=%d, nflits=%d",
3392 	    __func__, sgl->nsegs, sgl->nflits));
3393 
3394 	KASSERT(((uintptr_t)(*to) & 0xf) == 0,
3395 	    ("%s: SGL must start at a 16 byte boundary: %p", __func__, *to));
3396 
3397 	flitp = (__be64 *)(*to);
3398 	end = flitp + sgl->nflits;
3399 	seg = &sgl->seg[0];
3400 	usgl = (void *)flitp;
3401 
3402 	/*
3403 	 * We start at a 16 byte boundary somewhere inside the tx descriptor
3404 	 * ring, so we're at least 16 bytes away from the status page.  There is
3405 	 * no chance of a wrap around in the middle of usgl (which is 16 bytes).
3406 	 */
3407 
3408 	usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
3409 	    V_ULPTX_NSGE(sgl->nsegs));
3410 	usgl->len0 = htobe32(seg->ds_len);
3411 	usgl->addr0 = htobe64(seg->ds_addr);
3412 	seg++;
3413 
3414 	if ((uintptr_t)end <= (uintptr_t)eq->spg) {
3415 
3416 		/* Won't wrap around at all */
3417 
3418 		for (i = 0; i < sgl->nsegs - 1; i++, seg++) {
3419 			usgl->sge[i / 2].len[i & 1] = htobe32(seg->ds_len);
3420 			usgl->sge[i / 2].addr[i & 1] = htobe64(seg->ds_addr);
3421 		}
3422 		if (i & 1)
3423 			usgl->sge[i / 2].len[1] = htobe32(0);
3424 	} else {
3425 
3426 		/* Will wrap somewhere in the rest of the SGL */
3427 
3428 		/* 2 flits already written, write the rest flit by flit */
3429 		flitp = (void *)(usgl + 1);
3430 		for (i = 0; i < sgl->nflits - 2; i++) {
3431 			if ((uintptr_t)flitp == (uintptr_t)eq->spg)
3432 				flitp = (void *)eq->desc;
3433 			*flitp++ = get_flit(seg, sgl->nsegs - 1, i);
3434 		}
3435 		end = flitp;
3436 	}
3437 
3438 	if ((uintptr_t)end & 0xf) {
3439 		*(uint64_t *)end = 0;
3440 		end++;
3441 		padded = 1;
3442 	} else
3443 		padded = 0;
3444 
3445 	if ((uintptr_t)end == (uintptr_t)eq->spg)
3446 		*to = (void *)eq->desc;
3447 	else
3448 		*to = (void *)end;
3449 
3450 	return (padded);
3451 }
3452 
3453 static inline void
3454 copy_to_txd(struct sge_eq *eq, caddr_t from, caddr_t *to, int len)
3455 {
3456 	if (__predict_true((uintptr_t)(*to) + len <= (uintptr_t)eq->spg)) {
3457 		bcopy(from, *to, len);
3458 		(*to) += len;
3459 	} else {
3460 		int portion = (uintptr_t)eq->spg - (uintptr_t)(*to);
3461 
3462 		bcopy(from, *to, portion);
3463 		from += portion;
3464 		portion = len - portion;	/* remaining */
3465 		bcopy(from, (void *)eq->desc, portion);
3466 		(*to) = (caddr_t)eq->desc + portion;
3467 	}
3468 }
3469 
3470 static inline void
3471 ring_eq_db(struct adapter *sc, struct sge_eq *eq)
3472 {
3473 	u_int db, pending;
3474 
3475 	db = eq->doorbells;
3476 	pending = eq->pending;
3477 	if (pending > 1)
3478 		clrbit(&db, DOORBELL_WCWR);
3479 	eq->pending = 0;
3480 	wmb();
3481 
3482 	switch (ffs(db) - 1) {
3483 	case DOORBELL_UDB:
3484 		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(pending));
3485 		return;
3486 
3487 	case DOORBELL_WCWR: {
3488 		volatile uint64_t *dst, *src;
3489 		int i;
3490 
3491 		/*
3492 		 * Queues whose 128B doorbell segment fits in the page do not
3493 		 * use relative qid (udb_qid is always 0).  Only queues with
3494 		 * doorbell segments can do WCWR.
3495 		 */
3496 		KASSERT(eq->udb_qid == 0 && pending == 1,
3497 		    ("%s: inappropriate doorbell (0x%x, %d, %d) for eq %p",
3498 		    __func__, eq->doorbells, pending, eq->pidx, eq));
3499 
3500 		dst = (volatile void *)((uintptr_t)eq->udb + UDBS_WR_OFFSET -
3501 		    UDBS_DB_OFFSET);
3502 		i = eq->pidx ? eq->pidx - 1 : eq->cap - 1;
3503 		src = (void *)&eq->desc[i];
3504 		while (src != (void *)&eq->desc[i + 1])
3505 			*dst++ = *src++;
3506 		wmb();
3507 		return;
3508 	}
3509 
3510 	case DOORBELL_UDBWC:
3511 		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(pending));
3512 		wmb();
3513 		return;
3514 
3515 	case DOORBELL_KDB:
3516 		t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL),
3517 		    V_QID(eq->cntxt_id) | V_PIDX(pending));
3518 		return;
3519 	}
3520 }
3521 
3522 static inline int
3523 reclaimable(struct sge_eq *eq)
3524 {
3525 	unsigned int cidx;
3526 
3527 	cidx = eq->spg->cidx;	/* stable snapshot */
3528 	cidx = be16toh(cidx);
3529 
3530 	if (cidx >= eq->cidx)
3531 		return (cidx - eq->cidx);
3532 	else
3533 		return (cidx + eq->cap - eq->cidx);
3534 }
3535 
3536 /*
3537  * There are "can_reclaim" tx descriptors ready to be reclaimed.  Reclaim as
3538  * many as possible but stop when there are around "n" mbufs to free.
3539  *
3540  * The actual number reclaimed is provided as the return value.
3541  */
3542 static int
3543 reclaim_tx_descs(struct sge_txq *txq, int can_reclaim, int n)
3544 {
3545 	struct tx_sdesc *txsd;
3546 	struct tx_maps *txmaps;
3547 	struct tx_map *txm;
3548 	unsigned int reclaimed, maps;
3549 	struct sge_eq *eq = &txq->eq;
3550 
3551 	TXQ_LOCK_ASSERT_OWNED(txq);
3552 
3553 	if (can_reclaim == 0)
3554 		can_reclaim = reclaimable(eq);
3555 
3556 	maps = reclaimed = 0;
3557 	while (can_reclaim && maps < n) {
3558 		int ndesc;
3559 
3560 		txsd = &txq->sdesc[eq->cidx];
3561 		ndesc = txsd->desc_used;
3562 
3563 		/* Firmware doesn't return "partial" credits. */
3564 		KASSERT(can_reclaim >= ndesc,
3565 		    ("%s: unexpected number of credits: %d, %d",
3566 		    __func__, can_reclaim, ndesc));
3567 
3568 		maps += txsd->credits;
3569 
3570 		reclaimed += ndesc;
3571 		can_reclaim -= ndesc;
3572 
3573 		eq->cidx += ndesc;
3574 		if (__predict_false(eq->cidx >= eq->cap))
3575 			eq->cidx -= eq->cap;
3576 	}
3577 
3578 	txmaps = &txq->txmaps;
3579 	txm = &txmaps->maps[txmaps->map_cidx];
3580 	if (maps)
3581 		prefetch(txm->m);
3582 
3583 	eq->avail += reclaimed;
3584 	KASSERT(eq->avail < eq->cap,	/* avail tops out at (cap - 1) */
3585 	    ("%s: too many descriptors available", __func__));
3586 
3587 	txmaps->map_avail += maps;
3588 	KASSERT(txmaps->map_avail <= txmaps->map_total,
3589 	    ("%s: too many maps available", __func__));
3590 
3591 	while (maps--) {
3592 		struct tx_map *next;
3593 
3594 		next = txm + 1;
3595 		if (__predict_false(txmaps->map_cidx + 1 == txmaps->map_total))
3596 			next = txmaps->maps;
3597 		prefetch(next->m);
3598 
3599 		bus_dmamap_unload(txq->tx_tag, txm->map);
3600 		m_freem(txm->m);
3601 		txm->m = NULL;
3602 
3603 		txm = next;
3604 		if (__predict_false(++txmaps->map_cidx == txmaps->map_total))
3605 			txmaps->map_cidx = 0;
3606 	}
3607 
3608 	return (reclaimed);
3609 }
3610 
3611 static void
3612 write_eqflush_wr(struct sge_eq *eq)
3613 {
3614 	struct fw_eq_flush_wr *wr;
3615 
3616 	EQ_LOCK_ASSERT_OWNED(eq);
3617 	KASSERT(eq->avail > 0, ("%s: no descriptors left.", __func__));
3618 	KASSERT(!(eq->flags & EQ_CRFLUSHED), ("%s: flushed already", __func__));
3619 
3620 	wr = (void *)&eq->desc[eq->pidx];
3621 	bzero(wr, sizeof(*wr));
3622 	wr->opcode = FW_EQ_FLUSH_WR;
3623 	wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(sizeof(*wr) / 16) |
3624 	    F_FW_WR_EQUEQ | F_FW_WR_EQUIQ);
3625 
3626 	eq->flags |= (EQ_CRFLUSHED | EQ_STALLED);
3627 	eq->pending++;
3628 	eq->avail--;
3629 	if (++eq->pidx == eq->cap)
3630 		eq->pidx = 0;
3631 }
3632 
3633 static __be64
3634 get_flit(bus_dma_segment_t *sgl, int nsegs, int idx)
3635 {
3636 	int i = (idx / 3) * 2;
3637 
3638 	switch (idx % 3) {
3639 	case 0: {
3640 		__be64 rc;
3641 
3642 		rc = htobe32(sgl[i].ds_len);
3643 		if (i + 1 < nsegs)
3644 			rc |= (uint64_t)htobe32(sgl[i + 1].ds_len) << 32;
3645 
3646 		return (rc);
3647 	}
3648 	case 1:
3649 		return htobe64(sgl[i].ds_addr);
3650 	case 2:
3651 		return htobe64(sgl[i + 1].ds_addr);
3652 	}
3653 
3654 	return (0);
3655 }
3656 
3657 static void
3658 set_fl_tag_idx(struct sge_fl *fl, int bufsize)
3659 {
3660 	int i;
3661 
3662 	for (i = 0; i < FL_BUF_SIZES - 1; i++) {
3663 		if (FL_BUF_SIZE(i) >= bufsize)
3664 			break;
3665 	}
3666 
3667 	fl->tag_idx = i;
3668 }
3669 
3670 static void
3671 add_fl_to_sfl(struct adapter *sc, struct sge_fl *fl)
3672 {
3673 	mtx_lock(&sc->sfl_lock);
3674 	FL_LOCK(fl);
3675 	if ((fl->flags & FL_DOOMED) == 0) {
3676 		fl->flags |= FL_STARVING;
3677 		TAILQ_INSERT_TAIL(&sc->sfl, fl, link);
3678 		callout_reset(&sc->sfl_callout, hz / 5, refill_sfl, sc);
3679 	}
3680 	FL_UNLOCK(fl);
3681 	mtx_unlock(&sc->sfl_lock);
3682 }
3683 
3684 static int
3685 handle_sge_egr_update(struct sge_iq *iq, const struct rss_header *rss,
3686     struct mbuf *m)
3687 {
3688 	const struct cpl_sge_egr_update *cpl = (const void *)(rss + 1);
3689 	unsigned int qid = G_EGR_QID(ntohl(cpl->opcode_qid));
3690 	struct adapter *sc = iq->adapter;
3691 	struct sge *s = &sc->sge;
3692 	struct sge_eq *eq;
3693 
3694 	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
3695 	    rss->opcode));
3696 
3697 	eq = s->eqmap[qid - s->eq_start];
3698 	EQ_LOCK(eq);
3699 	KASSERT(eq->flags & EQ_CRFLUSHED,
3700 	    ("%s: unsolicited egress update", __func__));
3701 	eq->flags &= ~EQ_CRFLUSHED;
3702 	eq->egr_update++;
3703 
3704 	if (__predict_false(eq->flags & EQ_DOOMED))
3705 		wakeup_one(eq);
3706 	else if (eq->flags & EQ_STALLED && can_resume_tx(eq))
3707 		taskqueue_enqueue(sc->tq[eq->tx_chan], &eq->tx_task);
3708 	EQ_UNLOCK(eq);
3709 
3710 	return (0);
3711 }
3712 
3713 /* handle_fw_msg works for both fw4_msg and fw6_msg because this is valid */
3714 CTASSERT(offsetof(struct cpl_fw4_msg, data) == \
3715     offsetof(struct cpl_fw6_msg, data));
3716 
3717 static int
3718 handle_fw_msg(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
3719 {
3720 	struct adapter *sc = iq->adapter;
3721 	const struct cpl_fw6_msg *cpl = (const void *)(rss + 1);
3722 
3723 	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
3724 	    rss->opcode));
3725 
3726 	if (cpl->type == FW_TYPE_RSSCPL || cpl->type == FW6_TYPE_RSSCPL) {
3727 		const struct rss_header *rss2;
3728 
3729 		rss2 = (const struct rss_header *)&cpl->data[0];
3730 		return (sc->cpl_handler[rss2->opcode](iq, rss2, m));
3731 	}
3732 
3733 	return (sc->fw_msg_handler[cpl->type](sc, &cpl->data[0]));
3734 }
3735 
3736 static int
3737 sysctl_uint16(SYSCTL_HANDLER_ARGS)
3738 {
3739 	uint16_t *id = arg1;
3740 	int i = *id;
3741 
3742 	return sysctl_handle_int(oidp, &i, 0, req);
3743 }
3744