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