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