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