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