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