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