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