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