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