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