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