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