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