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