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