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