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