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