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