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