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