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