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