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