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