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