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