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