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