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