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