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