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