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