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