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