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