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