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