]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/cxgbe/t4_sge.c
MFC 291665,291685,291856,297467,302110,302263: Add support for VIs.
[FreeBSD/stable/10.git] / sys / dev / cxgbe / t4_sge.c
1 /*-
2  * Copyright (c) 2011 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33
34 #include <sys/types.h>
35 #include <sys/mbuf.h>
36 #include <sys/socket.h>
37 #include <sys/kernel.h>
38 #include <sys/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 vi_info *, struct sge_iq *, struct sge_fl *,
175     int, int);
176 static int free_iq_fl(struct vi_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 vi_info *, struct sge_rxq *, int, int,
184     struct sysctl_oid *);
185 static int free_rxq(struct vi_info *, struct sge_rxq *);
186 #ifdef TCP_OFFLOAD
187 static int alloc_ofld_rxq(struct vi_info *, struct sge_ofld_rxq *, int, int,
188     struct sysctl_oid *);
189 static int free_ofld_rxq(struct vi_info *, struct sge_ofld_rxq *);
190 #endif
191 #ifdef DEV_NETMAP
192 static int alloc_nm_rxq(struct vi_info *, struct sge_nm_rxq *, int, int,
193     struct sysctl_oid *);
194 static int free_nm_rxq(struct vi_info *, struct sge_nm_rxq *);
195 static int alloc_nm_txq(struct vi_info *, struct sge_nm_txq *, int, int,
196     struct sysctl_oid *);
197 static int free_nm_txq(struct vi_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 vi_info *, struct sge_eq *);
201 #ifdef TCP_OFFLOAD
202 static int ofld_eq_alloc(struct adapter *, struct vi_info *, struct sge_eq *);
203 #endif
204 static int alloc_eq(struct adapter *, struct vi_info *, struct sge_eq *);
205 static int free_eq(struct adapter *, struct sge_eq *);
206 static int alloc_wrq(struct adapter *, struct vi_info *, struct sge_wrq *,
207     struct sysctl_oid *);
208 static int free_wrq(struct adapter *, struct sge_wrq *);
209 static int alloc_txq(struct vi_info *, struct sge_txq *, int,
210     struct sysctl_oid *);
211 static int free_txq(struct vi_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 first_vector(struct vi_info *vi)
837 {
838         struct adapter *sc = vi->pi->adapter;
839
840         if (sc->intr_count == 1)
841                 return (0);
842
843         return (vi->first_intr);
844 }
845
846 /*
847  * Given an arbitrary "index," come up with an iq that can be used by other
848  * queues (of this VI) for interrupt forwarding, SGE egress updates, etc.
849  * The iq returned is guaranteed to be something that takes direct interrupts.
850  */
851 static struct sge_iq *
852 vi_intr_iq(struct vi_info *vi, int idx)
853 {
854         struct adapter *sc = vi->pi->adapter;
855         struct sge *s = &sc->sge;
856         struct sge_iq *iq = NULL;
857         int nintr, i;
858
859         if (sc->intr_count == 1)
860                 return (&sc->sge.fwq);
861
862         nintr = vi->nintr;
863         KASSERT(nintr != 0,
864             ("%s: vi %p has no exclusive interrupts, total interrupts = %d",
865             __func__, vi, sc->intr_count));
866         i = idx % nintr;
867
868         if (vi->flags & INTR_RXQ) {
869                 if (i < vi->nrxq) {
870                         iq = &s->rxq[vi->first_rxq + i].iq;
871                         goto done;
872                 }
873                 i -= vi->nrxq;
874         }
875 #ifdef TCP_OFFLOAD
876         if (vi->flags & INTR_OFLD_RXQ) {
877                 if (i < vi->nofldrxq) {
878                         iq = &s->ofld_rxq[vi->first_ofld_rxq + i].iq;
879                         goto done;
880                 }
881                 i -= vi->nofldrxq;
882         }
883 #endif
884         panic("%s: vi %p, intr_flags 0x%lx, idx %d, total intr %d\n", __func__,
885             vi, vi->flags & INTR_ALL, idx, nintr);
886 done:
887         MPASS(iq != NULL);
888         KASSERT(iq->flags & IQ_INTR,
889             ("%s: iq %p (vi %p, intr_flags 0x%lx, idx %d)", __func__, iq, vi,
890             vi->flags & INTR_ALL, idx));
891         return (iq);
892 }
893
894 /* Maximum payload that can be delivered with a single iq descriptor */
895 static inline int
896 mtu_to_max_payload(struct adapter *sc, int mtu, const int toe)
897 {
898         int payload;
899
900 #ifdef TCP_OFFLOAD
901         if (toe) {
902                 payload = sc->tt.rx_coalesce ?
903                     G_RXCOALESCESIZE(t4_read_reg(sc, A_TP_PARA_REG2)) : mtu;
904         } else {
905 #endif
906                 /* large enough even when hw VLAN extraction is disabled */
907                 payload = fl_pktshift + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN +
908                     mtu;
909 #ifdef TCP_OFFLOAD
910         }
911 #endif
912
913         return (payload);
914 }
915
916 int
917 t4_setup_vi_queues(struct vi_info *vi)
918 {
919         int rc = 0, i, j, intr_idx, iqid;
920         struct sge_rxq *rxq;
921         struct sge_txq *txq;
922         struct sge_wrq *ctrlq;
923 #ifdef TCP_OFFLOAD
924         struct sge_ofld_rxq *ofld_rxq;
925         struct sge_wrq *ofld_txq;
926 #endif
927 #ifdef DEV_NETMAP
928         int saved_idx;
929         struct sge_nm_rxq *nm_rxq;
930         struct sge_nm_txq *nm_txq;
931 #endif
932         char name[16];
933         struct port_info *pi = vi->pi;
934         struct adapter *sc = pi->adapter;
935         struct ifnet *ifp = vi->ifp;
936         struct sysctl_oid *oid = device_get_sysctl_tree(vi->dev);
937         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
938         int maxp, mtu = ifp->if_mtu;
939
940         /* Interrupt vector to start from (when using multiple vectors) */
941         intr_idx = first_vector(vi);
942
943 #ifdef DEV_NETMAP
944         saved_idx = intr_idx;
945         if (ifp->if_capabilities & IFCAP_NETMAP) {
946
947                 /* netmap is supported with direct interrupts only. */
948                 MPASS(vi->flags & INTR_RXQ);
949
950                 /*
951                  * We don't have buffers to back the netmap rx queues
952                  * right now so we create the queues in a way that
953                  * doesn't set off any congestion signal in the chip.
954                  */
955                 oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "nm_rxq",
956                     CTLFLAG_RD, NULL, "rx queues");
957                 for_each_nm_rxq(vi, i, nm_rxq) {
958                         rc = alloc_nm_rxq(vi, nm_rxq, intr_idx, i, oid);
959                         if (rc != 0)
960                                 goto done;
961                         intr_idx++;
962                 }
963
964                 oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "nm_txq",
965                     CTLFLAG_RD, NULL, "tx queues");
966                 for_each_nm_txq(vi, i, nm_txq) {
967                         iqid = vi->first_nm_rxq + (i % vi->nnmrxq);
968                         rc = alloc_nm_txq(vi, nm_txq, iqid, i, oid);
969                         if (rc != 0)
970                                 goto done;
971                 }
972         }
973
974         /* Normal rx queues and netmap rx queues share the same interrupts. */
975         intr_idx = saved_idx;
976 #endif
977
978         /*
979          * First pass over all NIC and TOE rx queues:
980          * a) initialize iq and fl
981          * b) allocate queue iff it will take direct interrupts.
982          */
983         maxp = mtu_to_max_payload(sc, mtu, 0);
984         if (vi->flags & INTR_RXQ) {
985                 oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "rxq",
986                     CTLFLAG_RD, NULL, "rx queues");
987         }
988         for_each_rxq(vi, i, rxq) {
989
990                 init_iq(&rxq->iq, sc, vi->tmr_idx, vi->pktc_idx, vi->qsize_rxq);
991
992                 snprintf(name, sizeof(name), "%s rxq%d-fl",
993                     device_get_nameunit(vi->dev), i);
994                 init_fl(sc, &rxq->fl, vi->qsize_rxq / 8, maxp, name);
995
996                 if (vi->flags & INTR_RXQ) {
997                         rxq->iq.flags |= IQ_INTR;
998                         rc = alloc_rxq(vi, rxq, intr_idx, i, oid);
999                         if (rc != 0)
1000                                 goto done;
1001                         intr_idx++;
1002                 }
1003         }
1004 #ifdef DEV_NETMAP
1005         if (ifp->if_capabilities & IFCAP_NETMAP)
1006                 intr_idx = saved_idx + max(vi->nrxq, vi->nnmrxq);
1007 #endif
1008 #ifdef TCP_OFFLOAD
1009         maxp = mtu_to_max_payload(sc, mtu, 1);
1010         if (vi->flags & INTR_OFLD_RXQ) {
1011                 oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "ofld_rxq",
1012                     CTLFLAG_RD, NULL,
1013                     "rx queues for offloaded TCP connections");
1014         }
1015         for_each_ofld_rxq(vi, i, ofld_rxq) {
1016
1017                 init_iq(&ofld_rxq->iq, sc, vi->tmr_idx, vi->pktc_idx,
1018                     vi->qsize_rxq);
1019
1020                 snprintf(name, sizeof(name), "%s ofld_rxq%d-fl",
1021                     device_get_nameunit(vi->dev), i);
1022                 init_fl(sc, &ofld_rxq->fl, vi->qsize_rxq / 8, maxp, name);
1023
1024                 if (vi->flags & INTR_OFLD_RXQ) {
1025                         ofld_rxq->iq.flags |= IQ_INTR;
1026                         rc = alloc_ofld_rxq(vi, ofld_rxq, intr_idx, i, oid);
1027                         if (rc != 0)
1028                                 goto done;
1029                         intr_idx++;
1030                 }
1031         }
1032 #endif
1033
1034         /*
1035          * Second pass over all NIC and TOE rx queues.  The queues forwarding
1036          * their interrupts are allocated now.
1037          */
1038         j = 0;
1039         if (!(vi->flags & INTR_RXQ)) {
1040                 oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "rxq",
1041                     CTLFLAG_RD, NULL, "rx queues");
1042                 for_each_rxq(vi, i, rxq) {
1043                         MPASS(!(rxq->iq.flags & IQ_INTR));
1044
1045                         intr_idx = vi_intr_iq(vi, j)->abs_id;
1046
1047                         rc = alloc_rxq(vi, rxq, intr_idx, i, oid);
1048                         if (rc != 0)
1049                                 goto done;
1050                         j++;
1051                 }
1052         }
1053 #ifdef TCP_OFFLOAD
1054         if (vi->nofldrxq != 0 && !(vi->flags & INTR_OFLD_RXQ)) {
1055                 oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "ofld_rxq",
1056                     CTLFLAG_RD, NULL,
1057                     "rx queues for offloaded TCP connections");
1058                 for_each_ofld_rxq(vi, i, ofld_rxq) {
1059                         MPASS(!(ofld_rxq->iq.flags & IQ_INTR));
1060
1061                         intr_idx = vi_intr_iq(vi, j)->abs_id;
1062
1063                         rc = alloc_ofld_rxq(vi, ofld_rxq, intr_idx, i, oid);
1064                         if (rc != 0)
1065                                 goto done;
1066                         j++;
1067                 }
1068         }
1069 #endif
1070
1071         /*
1072          * Now the tx queues.  Only one pass needed.
1073          */
1074         oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "txq", CTLFLAG_RD,
1075             NULL, "tx queues");
1076         j = 0;
1077         for_each_txq(vi, i, txq) {
1078                 iqid = vi_intr_iq(vi, j)->cntxt_id;
1079                 snprintf(name, sizeof(name), "%s txq%d",
1080                     device_get_nameunit(vi->dev), i);
1081                 init_eq(&txq->eq, EQ_ETH, vi->qsize_txq, pi->tx_chan, iqid,
1082                     name);
1083
1084                 rc = alloc_txq(vi, txq, i, oid);
1085                 if (rc != 0)
1086                         goto done;
1087                 j++;
1088         }
1089 #ifdef TCP_OFFLOAD
1090         oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "ofld_txq",
1091             CTLFLAG_RD, NULL, "tx queues for offloaded TCP connections");
1092         for_each_ofld_txq(vi, i, ofld_txq) {
1093                 struct sysctl_oid *oid2;
1094
1095                 iqid = vi_intr_iq(vi, j)->cntxt_id;
1096                 snprintf(name, sizeof(name), "%s ofld_txq%d",
1097                     device_get_nameunit(vi->dev), i);
1098                 init_eq(&ofld_txq->eq, EQ_OFLD, vi->qsize_txq, pi->tx_chan,
1099                     iqid, name);
1100
1101                 snprintf(name, sizeof(name), "%d", i);
1102                 oid2 = SYSCTL_ADD_NODE(&vi->ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
1103                     name, CTLFLAG_RD, NULL, "offload tx queue");
1104
1105                 rc = alloc_wrq(sc, vi, ofld_txq, oid2);
1106                 if (rc != 0)
1107                         goto done;
1108                 j++;
1109         }
1110 #endif
1111
1112         /*
1113          * Finally, the control queue.
1114          */
1115         if (!IS_MAIN_VI(vi))
1116                 goto done;
1117         oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "ctrlq", CTLFLAG_RD,
1118             NULL, "ctrl queue");
1119         ctrlq = &sc->sge.ctrlq[pi->port_id];
1120         iqid = vi_intr_iq(vi, 0)->cntxt_id;
1121         snprintf(name, sizeof(name), "%s ctrlq", device_get_nameunit(vi->dev));
1122         init_eq(&ctrlq->eq, EQ_CTRL, CTRL_EQ_QSIZE, pi->tx_chan, iqid, name);
1123         rc = alloc_wrq(sc, vi, ctrlq, oid);
1124
1125 done:
1126         if (rc)
1127                 t4_teardown_vi_queues(vi);
1128
1129         return (rc);
1130 }
1131
1132 /*
1133  * Idempotent
1134  */
1135 int
1136 t4_teardown_vi_queues(struct vi_info *vi)
1137 {
1138         int i;
1139         struct port_info *pi = vi->pi;
1140         struct adapter *sc = pi->adapter;
1141         struct sge_rxq *rxq;
1142         struct sge_txq *txq;
1143 #ifdef TCP_OFFLOAD
1144         struct sge_ofld_rxq *ofld_rxq;
1145         struct sge_wrq *ofld_txq;
1146 #endif
1147 #ifdef DEV_NETMAP
1148         struct sge_nm_rxq *nm_rxq;
1149         struct sge_nm_txq *nm_txq;
1150 #endif
1151
1152         /* Do this before freeing the queues */
1153         if (vi->flags & VI_SYSCTL_CTX) {
1154                 sysctl_ctx_free(&vi->ctx);
1155                 vi->flags &= ~VI_SYSCTL_CTX;
1156         }
1157
1158 #ifdef DEV_NETMAP
1159         if (vi->ifp->if_capabilities & IFCAP_NETMAP) {
1160                 for_each_nm_txq(vi, i, nm_txq) {
1161                         free_nm_txq(vi, nm_txq);
1162                 }
1163
1164                 for_each_nm_rxq(vi, i, nm_rxq) {
1165                         free_nm_rxq(vi, nm_rxq);
1166                 }
1167         }
1168 #endif
1169
1170         /*
1171          * Take down all the tx queues first, as they reference the rx queues
1172          * (for egress updates, etc.).
1173          */
1174
1175         if (IS_MAIN_VI(vi))
1176                 free_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
1177
1178         for_each_txq(vi, i, txq) {
1179                 free_txq(vi, txq);
1180         }
1181 #ifdef TCP_OFFLOAD
1182         for_each_ofld_txq(vi, i, ofld_txq) {
1183                 free_wrq(sc, ofld_txq);
1184         }
1185 #endif
1186
1187         /*
1188          * Then take down the rx queues that forward their interrupts, as they
1189          * reference other rx queues.
1190          */
1191
1192         for_each_rxq(vi, i, rxq) {
1193                 if ((rxq->iq.flags & IQ_INTR) == 0)
1194                         free_rxq(vi, rxq);
1195         }
1196 #ifdef TCP_OFFLOAD
1197         for_each_ofld_rxq(vi, i, ofld_rxq) {
1198                 if ((ofld_rxq->iq.flags & IQ_INTR) == 0)
1199                         free_ofld_rxq(vi, ofld_rxq);
1200         }
1201 #endif
1202
1203         /*
1204          * Then take down the rx queues that take direct interrupts.
1205          */
1206
1207         for_each_rxq(vi, i, rxq) {
1208                 if (rxq->iq.flags & IQ_INTR)
1209                         free_rxq(vi, rxq);
1210         }
1211 #ifdef TCP_OFFLOAD
1212         for_each_ofld_rxq(vi, i, ofld_rxq) {
1213                 if (ofld_rxq->iq.flags & IQ_INTR)
1214                         free_ofld_rxq(vi, ofld_rxq);
1215         }
1216 #endif
1217
1218         return (0);
1219 }
1220
1221 /*
1222  * Deals with errors and the firmware event queue.  All data rx queues forward
1223  * their interrupt to the firmware event queue.
1224  */
1225 void
1226 t4_intr_all(void *arg)
1227 {
1228         struct adapter *sc = arg;
1229         struct sge_iq *fwq = &sc->sge.fwq;
1230
1231         t4_intr_err(arg);
1232         if (atomic_cmpset_int(&fwq->state, IQS_IDLE, IQS_BUSY)) {
1233                 service_iq(fwq, 0);
1234                 atomic_cmpset_int(&fwq->state, IQS_BUSY, IQS_IDLE);
1235         }
1236 }
1237
1238 /* Deals with error interrupts */
1239 void
1240 t4_intr_err(void *arg)
1241 {
1242         struct adapter *sc = arg;
1243
1244         t4_write_reg(sc, MYPF_REG(A_PCIE_PF_CLI), 0);
1245         t4_slow_intr_handler(sc);
1246 }
1247
1248 void
1249 t4_intr_evt(void *arg)
1250 {
1251         struct sge_iq *iq = arg;
1252
1253         if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
1254                 service_iq(iq, 0);
1255                 atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
1256         }
1257 }
1258
1259 void
1260 t4_intr(void *arg)
1261 {
1262         struct sge_iq *iq = arg;
1263
1264         if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
1265                 service_iq(iq, 0);
1266                 atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
1267         }
1268 }
1269
1270 void
1271 t4_vi_intr(void *arg)
1272 {
1273         struct irq *irq = arg;
1274
1275 #ifdef DEV_NETMAP
1276         if (atomic_cmpset_int(&irq->nm_state, NM_ON, NM_BUSY)) {
1277                 t4_nm_intr(irq->nm_rxq);
1278                 atomic_cmpset_int(&irq->nm_state, NM_BUSY, NM_ON);
1279         }
1280 #endif
1281         if (irq->rxq != NULL)
1282                 t4_intr(irq->rxq);
1283 }
1284
1285 /*
1286  * Deals with anything and everything on the given ingress queue.
1287  */
1288 static int
1289 service_iq(struct sge_iq *iq, int budget)
1290 {
1291         struct sge_iq *q;
1292         struct sge_rxq *rxq = iq_to_rxq(iq);    /* Use iff iq is part of rxq */
1293         struct sge_fl *fl;                      /* Use iff IQ_HAS_FL */
1294         struct adapter *sc = iq->adapter;
1295         struct iq_desc *d = &iq->desc[iq->cidx];
1296         int ndescs = 0, limit;
1297         int rsp_type, refill;
1298         uint32_t lq;
1299         uint16_t fl_hw_cidx;
1300         struct mbuf *m0;
1301         STAILQ_HEAD(, sge_iq) iql = STAILQ_HEAD_INITIALIZER(iql);
1302 #if defined(INET) || defined(INET6)
1303         const struct timeval lro_timeout = {0, sc->lro_timeout};
1304 #endif
1305
1306         KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
1307
1308         limit = budget ? budget : iq->qsize / 16;
1309
1310         if (iq->flags & IQ_HAS_FL) {
1311                 fl = &rxq->fl;
1312                 fl_hw_cidx = fl->hw_cidx;       /* stable snapshot */
1313         } else {
1314                 fl = NULL;
1315                 fl_hw_cidx = 0;                 /* to silence gcc warning */
1316         }
1317
1318         /*
1319          * We always come back and check the descriptor ring for new indirect
1320          * interrupts and other responses after running a single handler.
1321          */
1322         for (;;) {
1323                 while ((d->rsp.u.type_gen & F_RSPD_GEN) == iq->gen) {
1324
1325                         rmb();
1326
1327                         refill = 0;
1328                         m0 = NULL;
1329                         rsp_type = G_RSPD_TYPE(d->rsp.u.type_gen);
1330                         lq = be32toh(d->rsp.pldbuflen_qid);
1331
1332                         switch (rsp_type) {
1333                         case X_RSPD_TYPE_FLBUF:
1334
1335                                 KASSERT(iq->flags & IQ_HAS_FL,
1336                                     ("%s: data for an iq (%p) with no freelist",
1337                                     __func__, iq));
1338
1339                                 m0 = get_fl_payload(sc, fl, lq);
1340                                 if (__predict_false(m0 == NULL))
1341                                         goto process_iql;
1342                                 refill = IDXDIFF(fl->hw_cidx, fl_hw_cidx, fl->sidx) > 2;
1343 #ifdef T4_PKT_TIMESTAMP
1344                                 /*
1345                                  * 60 bit timestamp for the payload is
1346                                  * *(uint64_t *)m0->m_pktdat.  Note that it is
1347                                  * in the leading free-space in the mbuf.  The
1348                                  * kernel can clobber it during a pullup,
1349                                  * m_copymdata, etc.  You need to make sure that
1350                                  * the mbuf reaches you unmolested if you care
1351                                  * about the timestamp.
1352                                  */
1353                                 *(uint64_t *)m0->m_pktdat =
1354                                     be64toh(ctrl->u.last_flit) &
1355                                     0xfffffffffffffff;
1356 #endif
1357
1358                                 /* fall through */
1359
1360                         case X_RSPD_TYPE_CPL:
1361                                 KASSERT(d->rss.opcode < NUM_CPL_CMDS,
1362                                     ("%s: bad opcode %02x.", __func__,
1363                                     d->rss.opcode));
1364                                 sc->cpl_handler[d->rss.opcode](iq, &d->rss, m0);
1365                                 break;
1366
1367                         case X_RSPD_TYPE_INTR:
1368
1369                                 /*
1370                                  * Interrupts should be forwarded only to queues
1371                                  * that are not forwarding their interrupts.
1372                                  * This means service_iq can recurse but only 1
1373                                  * level deep.
1374                                  */
1375                                 KASSERT(budget == 0,
1376                                     ("%s: budget %u, rsp_type %u", __func__,
1377                                     budget, rsp_type));
1378
1379                                 /*
1380                                  * There are 1K interrupt-capable queues (qids 0
1381                                  * through 1023).  A response type indicating a
1382                                  * forwarded interrupt with a qid >= 1K is an
1383                                  * iWARP async notification.
1384                                  */
1385                                 if (lq >= 1024) {
1386                                         sc->an_handler(iq, &d->rsp);
1387                                         break;
1388                                 }
1389
1390                                 q = sc->sge.iqmap[lq - sc->sge.iq_start];
1391                                 if (atomic_cmpset_int(&q->state, IQS_IDLE,
1392                                     IQS_BUSY)) {
1393                                         if (service_iq(q, q->qsize / 16) == 0) {
1394                                                 atomic_cmpset_int(&q->state,
1395                                                     IQS_BUSY, IQS_IDLE);
1396                                         } else {
1397                                                 STAILQ_INSERT_TAIL(&iql, q,
1398                                                     link);
1399                                         }
1400                                 }
1401                                 break;
1402
1403                         default:
1404                                 KASSERT(0,
1405                                     ("%s: illegal response type %d on iq %p",
1406                                     __func__, rsp_type, iq));
1407                                 log(LOG_ERR,
1408                                     "%s: illegal response type %d on iq %p",
1409                                     device_get_nameunit(sc->dev), rsp_type, iq);
1410                                 break;
1411                         }
1412
1413                         d++;
1414                         if (__predict_false(++iq->cidx == iq->sidx)) {
1415                                 iq->cidx = 0;
1416                                 iq->gen ^= F_RSPD_GEN;
1417                                 d = &iq->desc[0];
1418                         }
1419                         if (__predict_false(++ndescs == limit)) {
1420                                 t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS),
1421                                     V_CIDXINC(ndescs) |
1422                                     V_INGRESSQID(iq->cntxt_id) |
1423                                     V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));
1424                                 ndescs = 0;
1425
1426 #if defined(INET) || defined(INET6)
1427                                 if (iq->flags & IQ_LRO_ENABLED &&
1428                                     sc->lro_timeout != 0) {
1429                                         tcp_lro_flush_inactive(&rxq->lro,
1430                                             &lro_timeout);
1431                                 }
1432 #endif
1433
1434                                 if (budget) {
1435                                         if (iq->flags & IQ_HAS_FL) {
1436                                                 FL_LOCK(fl);
1437                                                 refill_fl(sc, fl, 32);
1438                                                 FL_UNLOCK(fl);
1439                                         }
1440                                         return (EINPROGRESS);
1441                                 }
1442                         }
1443                         if (refill) {
1444                                 FL_LOCK(fl);
1445                                 refill_fl(sc, fl, 32);
1446                                 FL_UNLOCK(fl);
1447                                 fl_hw_cidx = fl->hw_cidx;
1448                         }
1449                 }
1450
1451 process_iql:
1452                 if (STAILQ_EMPTY(&iql))
1453                         break;
1454
1455                 /*
1456                  * Process the head only, and send it to the back of the list if
1457                  * it's still not done.
1458                  */
1459                 q = STAILQ_FIRST(&iql);
1460                 STAILQ_REMOVE_HEAD(&iql, link);
1461                 if (service_iq(q, q->qsize / 8) == 0)
1462                         atomic_cmpset_int(&q->state, IQS_BUSY, IQS_IDLE);
1463                 else
1464                         STAILQ_INSERT_TAIL(&iql, q, link);
1465         }
1466
1467 #if defined(INET) || defined(INET6)
1468         if (iq->flags & IQ_LRO_ENABLED) {
1469                 struct lro_ctrl *lro = &rxq->lro;
1470                 struct lro_entry *l;
1471
1472                 while (!SLIST_EMPTY(&lro->lro_active)) {
1473                         l = SLIST_FIRST(&lro->lro_active);
1474                         SLIST_REMOVE_HEAD(&lro->lro_active, next);
1475                         tcp_lro_flush(lro, l);
1476                 }
1477         }
1478 #endif
1479
1480         t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_CIDXINC(ndescs) |
1481             V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));
1482
1483         if (iq->flags & IQ_HAS_FL) {
1484                 int starved;
1485
1486                 FL_LOCK(fl);
1487                 starved = refill_fl(sc, fl, 64);
1488                 FL_UNLOCK(fl);
1489                 if (__predict_false(starved != 0))
1490                         add_fl_to_sfl(sc, fl);
1491         }
1492
1493         return (0);
1494 }
1495
1496 static inline int
1497 cl_has_metadata(struct sge_fl *fl, struct cluster_layout *cll)
1498 {
1499         int rc = fl->flags & FL_BUF_PACKING || cll->region1 > 0;
1500
1501         if (rc)
1502                 MPASS(cll->region3 >= CL_METADATA_SIZE);
1503
1504         return (rc);
1505 }
1506
1507 static inline struct cluster_metadata *
1508 cl_metadata(struct adapter *sc, struct sge_fl *fl, struct cluster_layout *cll,
1509     caddr_t cl)
1510 {
1511
1512         if (cl_has_metadata(fl, cll)) {
1513                 struct sw_zone_info *swz = &sc->sge.sw_zone_info[cll->zidx];
1514
1515                 return ((struct cluster_metadata *)(cl + swz->size) - 1);
1516         }
1517         return (NULL);
1518 }
1519
1520 static int
1521 rxb_free(struct mbuf *m, void *arg1, void *arg2)
1522 {
1523         uma_zone_t zone = arg1;
1524         caddr_t cl = arg2;
1525
1526         uma_zfree(zone, cl);
1527         counter_u64_add(extfree_rels, 1);
1528
1529         return (EXT_FREE_OK);
1530 }
1531
1532 /*
1533  * The mbuf returned by this function could be allocated from zone_mbuf or
1534  * constructed in spare room in the cluster.
1535  *
1536  * The mbuf carries the payload in one of these ways
1537  * a) frame inside the mbuf (mbuf from zone_mbuf)
1538  * b) m_cljset (for clusters without metadata) zone_mbuf
1539  * c) m_extaddref (cluster with metadata) inline mbuf
1540  * d) m_extaddref (cluster with metadata) zone_mbuf
1541  */
1542 static struct mbuf *
1543 get_scatter_segment(struct adapter *sc, struct sge_fl *fl, int fr_offset,
1544     int remaining)
1545 {
1546         struct mbuf *m;
1547         struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
1548         struct cluster_layout *cll = &sd->cll;
1549         struct sw_zone_info *swz = &sc->sge.sw_zone_info[cll->zidx];
1550         struct hw_buf_info *hwb = &sc->sge.hw_buf_info[cll->hwidx];
1551         struct cluster_metadata *clm = cl_metadata(sc, fl, cll, sd->cl);
1552         int len, blen;
1553         caddr_t payload;
1554
1555         blen = hwb->size - fl->rx_offset;       /* max possible in this buf */
1556         len = min(remaining, blen);
1557         payload = sd->cl + cll->region1 + fl->rx_offset;
1558         if (fl->flags & FL_BUF_PACKING) {
1559                 const u_int l = fr_offset + len;
1560                 const u_int pad = roundup2(l, fl->buf_boundary) - l;
1561
1562                 if (fl->rx_offset + len + pad < hwb->size)
1563                         blen = len + pad;
1564                 MPASS(fl->rx_offset + blen <= hwb->size);
1565         } else {
1566                 MPASS(fl->rx_offset == 0);      /* not packing */
1567         }
1568
1569
1570         if (sc->sc_do_rxcopy && len < RX_COPY_THRESHOLD) {
1571
1572                 /*
1573                  * Copy payload into a freshly allocated mbuf.
1574                  */
1575
1576                 m = fr_offset == 0 ?
1577                     m_gethdr(M_NOWAIT, MT_DATA) : m_get(M_NOWAIT, MT_DATA);
1578                 if (m == NULL)
1579                         return (NULL);
1580                 fl->mbuf_allocated++;
1581 #ifdef T4_PKT_TIMESTAMP
1582                 /* Leave room for a timestamp */
1583                 m->m_data += 8;
1584 #endif
1585                 /* copy data to mbuf */
1586                 bcopy(payload, mtod(m, caddr_t), len);
1587
1588         } else if (sd->nmbuf * MSIZE < cll->region1) {
1589
1590                 /*
1591                  * There's spare room in the cluster for an mbuf.  Create one
1592                  * and associate it with the payload that's in the cluster.
1593                  */
1594
1595                 MPASS(clm != NULL);
1596                 m = (struct mbuf *)(sd->cl + sd->nmbuf * MSIZE);
1597                 /* No bzero required */
1598                 if (m_init(m, NULL, 0, M_NOWAIT, MT_DATA,
1599                     fr_offset == 0 ? M_PKTHDR | M_NOFREE : M_NOFREE))
1600                         return (NULL);
1601                 fl->mbuf_inlined++;
1602                 m_extaddref(m, payload, blen, &clm->refcount, rxb_free,
1603                     swz->zone, sd->cl);
1604                 if (sd->nmbuf++ == 0)
1605                         counter_u64_add(extfree_refs, 1);
1606
1607         } else {
1608
1609                 /*
1610                  * Grab an mbuf from zone_mbuf and associate it with the
1611                  * payload in the cluster.
1612                  */
1613
1614                 m = fr_offset == 0 ?
1615                     m_gethdr(M_NOWAIT, MT_DATA) : m_get(M_NOWAIT, MT_DATA);
1616                 if (m == NULL)
1617                         return (NULL);
1618                 fl->mbuf_allocated++;
1619                 if (clm != NULL) {
1620                         m_extaddref(m, payload, blen, &clm->refcount,
1621                             rxb_free, swz->zone, sd->cl);
1622                         if (sd->nmbuf++ == 0)
1623                                 counter_u64_add(extfree_refs, 1);
1624                 } else {
1625                         m_cljset(m, sd->cl, swz->type);
1626                         sd->cl = NULL;  /* consumed, not a recycle candidate */
1627                 }
1628         }
1629         if (fr_offset == 0)
1630                 m->m_pkthdr.len = remaining;
1631         m->m_len = len;
1632
1633         if (fl->flags & FL_BUF_PACKING) {
1634                 fl->rx_offset += blen;
1635                 MPASS(fl->rx_offset <= hwb->size);
1636                 if (fl->rx_offset < hwb->size)
1637                         return (m);     /* without advancing the cidx */
1638         }
1639
1640         if (__predict_false(++fl->cidx % 8 == 0)) {
1641                 uint16_t cidx = fl->cidx / 8;
1642
1643                 if (__predict_false(cidx == fl->sidx))
1644                         fl->cidx = cidx = 0;
1645                 fl->hw_cidx = cidx;
1646         }
1647         fl->rx_offset = 0;
1648
1649         return (m);
1650 }
1651
1652 static struct mbuf *
1653 get_fl_payload(struct adapter *sc, struct sge_fl *fl, uint32_t len_newbuf)
1654 {
1655         struct mbuf *m0, *m, **pnext;
1656         u_int remaining;
1657         const u_int total = G_RSPD_LEN(len_newbuf);
1658
1659         if (__predict_false(fl->flags & FL_BUF_RESUME)) {
1660                 M_ASSERTPKTHDR(fl->m0);
1661                 MPASS(fl->m0->m_pkthdr.len == total);
1662                 MPASS(fl->remaining < total);
1663
1664                 m0 = fl->m0;
1665                 pnext = fl->pnext;
1666                 remaining = fl->remaining;
1667                 fl->flags &= ~FL_BUF_RESUME;
1668                 goto get_segment;
1669         }
1670
1671         if (fl->rx_offset > 0 && len_newbuf & F_RSPD_NEWBUF) {
1672                 fl->rx_offset = 0;
1673                 if (__predict_false(++fl->cidx % 8 == 0)) {
1674                         uint16_t cidx = fl->cidx / 8;
1675
1676                         if (__predict_false(cidx == fl->sidx))
1677                                 fl->cidx = cidx = 0;
1678                         fl->hw_cidx = cidx;
1679                 }
1680         }
1681
1682         /*
1683          * Payload starts at rx_offset in the current hw buffer.  Its length is
1684          * 'len' and it may span multiple hw buffers.
1685          */
1686
1687         m0 = get_scatter_segment(sc, fl, 0, total);
1688         if (m0 == NULL)
1689                 return (NULL);
1690         remaining = total - m0->m_len;
1691         pnext = &m0->m_next;
1692         while (remaining > 0) {
1693 get_segment:
1694                 MPASS(fl->rx_offset == 0);
1695                 m = get_scatter_segment(sc, fl, total - remaining, remaining);
1696                 if (__predict_false(m == NULL)) {
1697                         fl->m0 = m0;
1698                         fl->pnext = pnext;
1699                         fl->remaining = remaining;
1700                         fl->flags |= FL_BUF_RESUME;
1701                         return (NULL);
1702                 }
1703                 *pnext = m;
1704                 pnext = &m->m_next;
1705                 remaining -= m->m_len;
1706         }
1707         *pnext = NULL;
1708
1709         M_ASSERTPKTHDR(m0);
1710         return (m0);
1711 }
1712
1713 static int
1714 t4_eth_rx(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m0)
1715 {
1716         struct sge_rxq *rxq = iq_to_rxq(iq);
1717         struct ifnet *ifp = rxq->ifp;
1718         const struct cpl_rx_pkt *cpl = (const void *)(rss + 1);
1719 #if defined(INET) || defined(INET6)
1720         struct lro_ctrl *lro = &rxq->lro;
1721 #endif
1722
1723         KASSERT(m0 != NULL, ("%s: no payload with opcode %02x", __func__,
1724             rss->opcode));
1725
1726         m0->m_pkthdr.len -= fl_pktshift;
1727         m0->m_len -= fl_pktshift;
1728         m0->m_data += fl_pktshift;
1729
1730         m0->m_pkthdr.rcvif = ifp;
1731         M_HASHTYPE_SET(m0, M_HASHTYPE_OPAQUE);
1732         m0->m_pkthdr.flowid = be32toh(rss->hash_val);
1733
1734         if (cpl->csum_calc && !cpl->err_vec) {
1735                 if (ifp->if_capenable & IFCAP_RXCSUM &&
1736                     cpl->l2info & htobe32(F_RXF_IP)) {
1737                         m0->m_pkthdr.csum_flags = (CSUM_IP_CHECKED |
1738                             CSUM_IP_VALID | CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1739                         rxq->rxcsum++;
1740                 } else if (ifp->if_capenable & IFCAP_RXCSUM_IPV6 &&
1741                     cpl->l2info & htobe32(F_RXF_IP6)) {
1742                         m0->m_pkthdr.csum_flags = (CSUM_DATA_VALID_IPV6 |
1743                             CSUM_PSEUDO_HDR);
1744                         rxq->rxcsum++;
1745                 }
1746
1747                 if (__predict_false(cpl->ip_frag))
1748                         m0->m_pkthdr.csum_data = be16toh(cpl->csum);
1749                 else
1750                         m0->m_pkthdr.csum_data = 0xffff;
1751         }
1752
1753         if (cpl->vlan_ex) {
1754                 m0->m_pkthdr.ether_vtag = be16toh(cpl->vlan);
1755                 m0->m_flags |= M_VLANTAG;
1756                 rxq->vlan_extraction++;
1757         }
1758
1759 #if defined(INET) || defined(INET6)
1760         if (cpl->l2info & htobe32(F_RXF_LRO) &&
1761             iq->flags & IQ_LRO_ENABLED &&
1762             tcp_lro_rx(lro, m0, 0) == 0) {
1763                 /* queued for LRO */
1764         } else
1765 #endif
1766         ifp->if_input(ifp, m0);
1767
1768         return (0);
1769 }
1770
1771 /*
1772  * Must drain the wrq or make sure that someone else will.
1773  */
1774 static void
1775 wrq_tx_drain(void *arg, int n)
1776 {
1777         struct sge_wrq *wrq = arg;
1778         struct sge_eq *eq = &wrq->eq;
1779
1780         EQ_LOCK(eq);
1781         if (TAILQ_EMPTY(&wrq->incomplete_wrs) && !STAILQ_EMPTY(&wrq->wr_list))
1782                 drain_wrq_wr_list(wrq->adapter, wrq);
1783         EQ_UNLOCK(eq);
1784 }
1785
1786 static void
1787 drain_wrq_wr_list(struct adapter *sc, struct sge_wrq *wrq)
1788 {
1789         struct sge_eq *eq = &wrq->eq;
1790         u_int available, dbdiff;        /* # of hardware descriptors */
1791         u_int n;
1792         struct wrqe *wr;
1793         struct fw_eth_tx_pkt_wr *dst;   /* any fw WR struct will do */
1794
1795         EQ_LOCK_ASSERT_OWNED(eq);
1796         MPASS(TAILQ_EMPTY(&wrq->incomplete_wrs));
1797         wr = STAILQ_FIRST(&wrq->wr_list);
1798         MPASS(wr != NULL);      /* Must be called with something useful to do */
1799         dbdiff = IDXDIFF(eq->pidx, eq->dbidx, eq->sidx);
1800
1801         do {
1802                 eq->cidx = read_hw_cidx(eq);
1803                 if (eq->pidx == eq->cidx)
1804                         available = eq->sidx - 1;
1805                 else
1806                         available = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;
1807
1808                 MPASS(wr->wrq == wrq);
1809                 n = howmany(wr->wr_len, EQ_ESIZE);
1810                 if (available < n)
1811                         return;
1812
1813                 dst = (void *)&eq->desc[eq->pidx];
1814                 if (__predict_true(eq->sidx - eq->pidx > n)) {
1815                         /* Won't wrap, won't end exactly at the status page. */
1816                         bcopy(&wr->wr[0], dst, wr->wr_len);
1817                         eq->pidx += n;
1818                 } else {
1819                         int first_portion = (eq->sidx - eq->pidx) * EQ_ESIZE;
1820
1821                         bcopy(&wr->wr[0], dst, first_portion);
1822                         if (wr->wr_len > first_portion) {
1823                                 bcopy(&wr->wr[first_portion], &eq->desc[0],
1824                                     wr->wr_len - first_portion);
1825                         }
1826                         eq->pidx = n - (eq->sidx - eq->pidx);
1827                 }
1828
1829                 if (available < eq->sidx / 4 &&
1830                     atomic_cmpset_int(&eq->equiq, 0, 1)) {
1831                         dst->equiq_to_len16 |= htobe32(F_FW_WR_EQUIQ |
1832                             F_FW_WR_EQUEQ);
1833                         eq->equeqidx = eq->pidx;
1834                 } else if (IDXDIFF(eq->pidx, eq->equeqidx, eq->sidx) >= 32) {
1835                         dst->equiq_to_len16 |= htobe32(F_FW_WR_EQUEQ);
1836                         eq->equeqidx = eq->pidx;
1837                 }
1838
1839                 dbdiff += n;
1840                 if (dbdiff >= 16) {
1841                         ring_eq_db(sc, eq, dbdiff);
1842                         dbdiff = 0;
1843                 }
1844
1845                 STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1846                 free_wrqe(wr);
1847                 MPASS(wrq->nwr_pending > 0);
1848                 wrq->nwr_pending--;
1849                 MPASS(wrq->ndesc_needed >= n);
1850                 wrq->ndesc_needed -= n;
1851         } while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL);
1852
1853         if (dbdiff)
1854                 ring_eq_db(sc, eq, dbdiff);
1855 }
1856
1857 /*
1858  * Doesn't fail.  Holds on to work requests it can't send right away.
1859  */
1860 void
1861 t4_wrq_tx_locked(struct adapter *sc, struct sge_wrq *wrq, struct wrqe *wr)
1862 {
1863 #ifdef INVARIANTS
1864         struct sge_eq *eq = &wrq->eq;
1865 #endif
1866
1867         EQ_LOCK_ASSERT_OWNED(eq);
1868         MPASS(wr != NULL);
1869         MPASS(wr->wr_len > 0 && wr->wr_len <= SGE_MAX_WR_LEN);
1870         MPASS((wr->wr_len & 0x7) == 0);
1871
1872         STAILQ_INSERT_TAIL(&wrq->wr_list, wr, link);
1873         wrq->nwr_pending++;
1874         wrq->ndesc_needed += howmany(wr->wr_len, EQ_ESIZE);
1875
1876         if (!TAILQ_EMPTY(&wrq->incomplete_wrs))
1877                 return; /* commit_wrq_wr will drain wr_list as well. */
1878
1879         drain_wrq_wr_list(sc, wrq);
1880
1881         /* Doorbell must have caught up to the pidx. */
1882         MPASS(eq->pidx == eq->dbidx);
1883 }
1884
1885 void
1886 t4_update_fl_bufsize(struct ifnet *ifp)
1887 {
1888         struct vi_info *vi = ifp->if_softc;
1889         struct adapter *sc = vi->pi->adapter;
1890         struct sge_rxq *rxq;
1891 #ifdef TCP_OFFLOAD
1892         struct sge_ofld_rxq *ofld_rxq;
1893 #endif
1894         struct sge_fl *fl;
1895         int i, maxp, mtu = ifp->if_mtu;
1896
1897         maxp = mtu_to_max_payload(sc, mtu, 0);
1898         for_each_rxq(vi, i, rxq) {
1899                 fl = &rxq->fl;
1900
1901                 FL_LOCK(fl);
1902                 find_best_refill_source(sc, fl, maxp);
1903                 FL_UNLOCK(fl);
1904         }
1905 #ifdef TCP_OFFLOAD
1906         maxp = mtu_to_max_payload(sc, mtu, 1);
1907         for_each_ofld_rxq(vi, i, ofld_rxq) {
1908                 fl = &ofld_rxq->fl;
1909
1910                 FL_LOCK(fl);
1911                 find_best_refill_source(sc, fl, maxp);
1912                 FL_UNLOCK(fl);
1913         }
1914 #endif
1915 }
1916
1917 static inline int
1918 mbuf_nsegs(struct mbuf *m)
1919 {
1920
1921         M_ASSERTPKTHDR(m);
1922         KASSERT(m->m_pkthdr.l5hlen > 0,
1923             ("%s: mbuf %p missing information on # of segments.", __func__, m));
1924
1925         return (m->m_pkthdr.l5hlen);
1926 }
1927
1928 static inline void
1929 set_mbuf_nsegs(struct mbuf *m, uint8_t nsegs)
1930 {
1931
1932         M_ASSERTPKTHDR(m);
1933         m->m_pkthdr.l5hlen = nsegs;
1934 }
1935
1936 static inline int
1937 mbuf_len16(struct mbuf *m)
1938 {
1939         int n;
1940
1941         M_ASSERTPKTHDR(m);
1942         n = m->m_pkthdr.PH_loc.eigth[0];
1943         MPASS(n > 0 && n <= SGE_MAX_WR_LEN / 16);
1944
1945         return (n);
1946 }
1947
1948 static inline void
1949 set_mbuf_len16(struct mbuf *m, uint8_t len16)
1950 {
1951
1952         M_ASSERTPKTHDR(m);
1953         m->m_pkthdr.PH_loc.eigth[0] = len16;
1954 }
1955
1956 static inline int
1957 needs_tso(struct mbuf *m)
1958 {
1959
1960         M_ASSERTPKTHDR(m);
1961
1962         if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1963                 KASSERT(m->m_pkthdr.tso_segsz > 0,
1964                     ("%s: TSO requested in mbuf %p but MSS not provided",
1965                     __func__, m));
1966                 return (1);
1967         }
1968
1969         return (0);
1970 }
1971
1972 static inline int
1973 needs_l3_csum(struct mbuf *m)
1974 {
1975
1976         M_ASSERTPKTHDR(m);
1977
1978         if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO))
1979                 return (1);
1980         return (0);
1981 }
1982
1983 static inline int
1984 needs_l4_csum(struct mbuf *m)
1985 {
1986
1987         M_ASSERTPKTHDR(m);
1988
1989         if (m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
1990             CSUM_TCP_IPV6 | CSUM_TSO))
1991                 return (1);
1992         return (0);
1993 }
1994
1995 static inline int
1996 needs_vlan_insertion(struct mbuf *m)
1997 {
1998
1999         M_ASSERTPKTHDR(m);
2000
2001         if (m->m_flags & M_VLANTAG) {
2002                 KASSERT(m->m_pkthdr.ether_vtag != 0,
2003                     ("%s: HWVLAN requested in mbuf %p but tag not provided",
2004                     __func__, m));
2005                 return (1);
2006         }
2007         return (0);
2008 }
2009
2010 static void *
2011 m_advance(struct mbuf **pm, int *poffset, int len)
2012 {
2013         struct mbuf *m = *pm;
2014         int offset = *poffset;
2015         uintptr_t p = 0;
2016
2017         MPASS(len > 0);
2018
2019         while (len) {
2020                 if (offset + len < m->m_len) {
2021                         offset += len;
2022                         p = mtod(m, uintptr_t) + offset;
2023                         break;
2024                 }
2025                 len -= m->m_len - offset;
2026                 m = m->m_next;
2027                 offset = 0;
2028                 MPASS(m != NULL);
2029         }
2030         *poffset = offset;
2031         *pm = m;
2032         return ((void *)p);
2033 }
2034
2035 static inline int
2036 same_paddr(char *a, char *b)
2037 {
2038
2039         if (a == b)
2040                 return (1);
2041         else if (a != NULL && b != NULL) {
2042                 vm_offset_t x = (vm_offset_t)a;
2043                 vm_offset_t y = (vm_offset_t)b;
2044
2045                 if ((x & PAGE_MASK) == (y & PAGE_MASK) &&
2046                     pmap_kextract(x) == pmap_kextract(y))
2047                         return (1);
2048         }
2049
2050         return (0);
2051 }
2052
2053 /*
2054  * Can deal with empty mbufs in the chain that have m_len = 0, but the chain
2055  * must have at least one mbuf that's not empty.
2056  */
2057 static inline int
2058 count_mbuf_nsegs(struct mbuf *m)
2059 {
2060         char *prev_end, *start;
2061         int len, nsegs;
2062
2063         MPASS(m != NULL);
2064
2065         nsegs = 0;
2066         prev_end = NULL;
2067         for (; m; m = m->m_next) {
2068
2069                 len = m->m_len;
2070                 if (__predict_false(len == 0))
2071                         continue;
2072                 start = mtod(m, char *);
2073
2074                 nsegs += sglist_count(start, len);
2075                 if (same_paddr(prev_end, start))
2076                         nsegs--;
2077                 prev_end = start + len;
2078         }
2079
2080         MPASS(nsegs > 0);
2081         return (nsegs);
2082 }
2083
2084 /*
2085  * Analyze the mbuf to determine its tx needs.  The mbuf passed in may change:
2086  * a) caller can assume it's been freed if this function returns with an error.
2087  * b) it may get defragged up if the gather list is too long for the hardware.
2088  */
2089 int
2090 parse_pkt(struct mbuf **mp)
2091 {
2092         struct mbuf *m0 = *mp, *m;
2093         int rc, nsegs, defragged = 0, offset;
2094         struct ether_header *eh;
2095         void *l3hdr;
2096 #if defined(INET) || defined(INET6)
2097         struct tcphdr *tcp;
2098 #endif
2099         uint16_t eh_type;
2100
2101         M_ASSERTPKTHDR(m0);
2102         if (__predict_false(m0->m_pkthdr.len < ETHER_HDR_LEN)) {
2103                 rc = EINVAL;
2104 fail:
2105                 m_freem(m0);
2106                 *mp = NULL;
2107                 return (rc);
2108         }
2109 restart:
2110         /*
2111          * First count the number of gather list segments in the payload.
2112          * Defrag the mbuf if nsegs exceeds the hardware limit.
2113          */
2114         M_ASSERTPKTHDR(m0);
2115         MPASS(m0->m_pkthdr.len > 0);
2116         nsegs = count_mbuf_nsegs(m0);
2117         if (nsegs > (needs_tso(m0) ? TX_SGL_SEGS_TSO : TX_SGL_SEGS)) {
2118                 if (defragged++ > 0 || (m = m_defrag(m0, M_NOWAIT)) == NULL) {
2119                         rc = EFBIG;
2120                         goto fail;
2121                 }
2122                 *mp = m0 = m;   /* update caller's copy after defrag */
2123                 goto restart;
2124         }
2125
2126         if (__predict_false(nsegs > 2 && m0->m_pkthdr.len <= MHLEN)) {
2127                 m0 = m_pullup(m0, m0->m_pkthdr.len);
2128                 if (m0 == NULL) {
2129                         /* Should have left well enough alone. */
2130                         rc = EFBIG;
2131                         goto fail;
2132                 }
2133                 *mp = m0;       /* update caller's copy after pullup */
2134                 goto restart;
2135         }
2136         set_mbuf_nsegs(m0, nsegs);
2137         set_mbuf_len16(m0, txpkt_len16(nsegs, needs_tso(m0)));
2138
2139         if (!needs_tso(m0))
2140                 return (0);
2141
2142         m = m0;
2143         eh = mtod(m, struct ether_header *);
2144         eh_type = ntohs(eh->ether_type);
2145         if (eh_type == ETHERTYPE_VLAN) {
2146                 struct ether_vlan_header *evh = (void *)eh;
2147
2148                 eh_type = ntohs(evh->evl_proto);
2149                 m0->m_pkthdr.l2hlen = sizeof(*evh);
2150         } else
2151                 m0->m_pkthdr.l2hlen = sizeof(*eh);
2152
2153         offset = 0;
2154         l3hdr = m_advance(&m, &offset, m0->m_pkthdr.l2hlen);
2155
2156         switch (eh_type) {
2157 #ifdef INET6
2158         case ETHERTYPE_IPV6:
2159         {
2160                 struct ip6_hdr *ip6 = l3hdr;
2161
2162                 MPASS(ip6->ip6_nxt == IPPROTO_TCP);
2163
2164                 m0->m_pkthdr.l3hlen = sizeof(*ip6);
2165                 break;
2166         }
2167 #endif
2168 #ifdef INET
2169         case ETHERTYPE_IP:
2170         {
2171                 struct ip *ip = l3hdr;
2172
2173                 m0->m_pkthdr.l3hlen = ip->ip_hl * 4;
2174                 break;
2175         }
2176 #endif
2177         default:
2178                 panic("%s: ethertype 0x%04x unknown.  if_cxgbe must be compiled"
2179                     " with the same INET/INET6 options as the kernel.",
2180                     __func__, eh_type);
2181         }
2182
2183 #if defined(INET) || defined(INET6)
2184         tcp = m_advance(&m, &offset, m0->m_pkthdr.l3hlen);
2185         m0->m_pkthdr.l4hlen = tcp->th_off * 4;
2186 #endif
2187         MPASS(m0 == *mp);
2188         return (0);
2189 }
2190
2191 void *
2192 start_wrq_wr(struct sge_wrq *wrq, int len16, struct wrq_cookie *cookie)
2193 {
2194         struct sge_eq *eq = &wrq->eq;
2195         struct adapter *sc = wrq->adapter;
2196         int ndesc, available;
2197         struct wrqe *wr;
2198         void *w;
2199
2200         MPASS(len16 > 0);
2201         ndesc = howmany(len16, EQ_ESIZE / 16);
2202         MPASS(ndesc > 0 && ndesc <= SGE_MAX_WR_NDESC);
2203
2204         EQ_LOCK(eq);
2205
2206         if (!STAILQ_EMPTY(&wrq->wr_list))
2207                 drain_wrq_wr_list(sc, wrq);
2208
2209         if (!STAILQ_EMPTY(&wrq->wr_list)) {
2210 slowpath:
2211                 EQ_UNLOCK(eq);
2212                 wr = alloc_wrqe(len16 * 16, wrq);
2213                 if (__predict_false(wr == NULL))
2214                         return (NULL);
2215                 cookie->pidx = -1;
2216                 cookie->ndesc = ndesc;
2217                 return (&wr->wr);
2218         }
2219
2220         eq->cidx = read_hw_cidx(eq);
2221         if (eq->pidx == eq->cidx)
2222                 available = eq->sidx - 1;
2223         else
2224                 available = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;
2225         if (available < ndesc)
2226                 goto slowpath;
2227
2228         cookie->pidx = eq->pidx;
2229         cookie->ndesc = ndesc;
2230         TAILQ_INSERT_TAIL(&wrq->incomplete_wrs, cookie, link);
2231
2232         w = &eq->desc[eq->pidx];
2233         IDXINCR(eq->pidx, ndesc, eq->sidx);
2234         if (__predict_false(eq->pidx < ndesc - 1)) {
2235                 w = &wrq->ss[0];
2236                 wrq->ss_pidx = cookie->pidx;
2237                 wrq->ss_len = len16 * 16;
2238         }
2239
2240         EQ_UNLOCK(eq);
2241
2242         return (w);
2243 }
2244
2245 void
2246 commit_wrq_wr(struct sge_wrq *wrq, void *w, struct wrq_cookie *cookie)
2247 {
2248         struct sge_eq *eq = &wrq->eq;
2249         struct adapter *sc = wrq->adapter;
2250         int ndesc, pidx;
2251         struct wrq_cookie *prev, *next;
2252
2253         if (cookie->pidx == -1) {
2254                 struct wrqe *wr = __containerof(w, struct wrqe, wr);
2255
2256                 t4_wrq_tx(sc, wr);
2257                 return;
2258         }
2259
2260         ndesc = cookie->ndesc;  /* Can be more than SGE_MAX_WR_NDESC here. */
2261         pidx = cookie->pidx;
2262         MPASS(pidx >= 0 && pidx < eq->sidx);
2263         if (__predict_false(w == &wrq->ss[0])) {
2264                 int n = (eq->sidx - wrq->ss_pidx) * EQ_ESIZE;
2265
2266                 MPASS(wrq->ss_len > n); /* WR had better wrap around. */
2267                 bcopy(&wrq->ss[0], &eq->desc[wrq->ss_pidx], n);
2268                 bcopy(&wrq->ss[n], &eq->desc[0], wrq->ss_len - n);
2269                 wrq->tx_wrs_ss++;
2270         } else
2271                 wrq->tx_wrs_direct++;
2272
2273         EQ_LOCK(eq);
2274         prev = TAILQ_PREV(cookie, wrq_incomplete_wrs, link);
2275         next = TAILQ_NEXT(cookie, link);
2276         if (prev == NULL) {
2277                 MPASS(pidx == eq->dbidx);
2278                 if (next == NULL || ndesc >= 16)
2279                         ring_eq_db(wrq->adapter, eq, ndesc);
2280                 else {
2281                         MPASS(IDXDIFF(next->pidx, pidx, eq->sidx) == ndesc);
2282                         next->pidx = pidx;
2283                         next->ndesc += ndesc;
2284                 }
2285         } else {
2286                 MPASS(IDXDIFF(pidx, prev->pidx, eq->sidx) == prev->ndesc);
2287                 prev->ndesc += ndesc;
2288         }
2289         TAILQ_REMOVE(&wrq->incomplete_wrs, cookie, link);
2290
2291         if (TAILQ_EMPTY(&wrq->incomplete_wrs) && !STAILQ_EMPTY(&wrq->wr_list))
2292                 drain_wrq_wr_list(sc, wrq);
2293
2294 #ifdef INVARIANTS
2295         if (TAILQ_EMPTY(&wrq->incomplete_wrs)) {
2296                 /* Doorbell must have caught up to the pidx. */
2297                 MPASS(wrq->eq.pidx == wrq->eq.dbidx);
2298         }
2299 #endif
2300         EQ_UNLOCK(eq);
2301 }
2302
2303 static u_int
2304 can_resume_eth_tx(struct mp_ring *r)
2305 {
2306         struct sge_eq *eq = r->cookie;
2307
2308         return (total_available_tx_desc(eq) > eq->sidx / 8);
2309 }
2310
2311 static inline int
2312 cannot_use_txpkts(struct mbuf *m)
2313 {
2314         /* maybe put a GL limit too, to avoid silliness? */
2315
2316         return (needs_tso(m));
2317 }
2318
2319 /*
2320  * r->items[cidx] to r->items[pidx], with a wraparound at r->size, are ready to
2321  * be consumed.  Return the actual number consumed.  0 indicates a stall.
2322  */
2323 static u_int
2324 eth_tx(struct mp_ring *r, u_int cidx, u_int pidx)
2325 {
2326         struct sge_txq *txq = r->cookie;
2327         struct sge_eq *eq = &txq->eq;
2328         struct ifnet *ifp = txq->ifp;
2329         struct vi_info *vi = ifp->if_softc;
2330         struct port_info *pi = vi->pi;
2331         struct adapter *sc = pi->adapter;
2332         u_int total, remaining;         /* # of packets */
2333         u_int available, dbdiff;        /* # of hardware descriptors */
2334         u_int n, next_cidx;
2335         struct mbuf *m0, *tail;
2336         struct txpkts txp;
2337         struct fw_eth_tx_pkts_wr *wr;   /* any fw WR struct will do */
2338
2339         remaining = IDXDIFF(pidx, cidx, r->size);
2340         MPASS(remaining > 0);   /* Must not be called without work to do. */
2341         total = 0;
2342
2343         TXQ_LOCK(txq);
2344         if (__predict_false((eq->flags & EQ_ENABLED) == 0)) {
2345                 while (cidx != pidx) {
2346                         m0 = r->items[cidx];
2347                         m_freem(m0);
2348                         if (++cidx == r->size)
2349                                 cidx = 0;
2350                 }
2351                 reclaim_tx_descs(txq, 2048);
2352                 total = remaining;
2353                 goto done;
2354         }
2355
2356         /* How many hardware descriptors do we have readily available. */
2357         if (eq->pidx == eq->cidx)
2358                 available = eq->sidx - 1;
2359         else
2360                 available = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;
2361         dbdiff = IDXDIFF(eq->pidx, eq->dbidx, eq->sidx);
2362
2363         while (remaining > 0) {
2364
2365                 m0 = r->items[cidx];
2366                 M_ASSERTPKTHDR(m0);
2367                 MPASS(m0->m_nextpkt == NULL);
2368
2369                 if (available < SGE_MAX_WR_NDESC) {
2370                         available += reclaim_tx_descs(txq, 64);
2371                         if (available < howmany(mbuf_len16(m0), EQ_ESIZE / 16))
2372                                 break;  /* out of descriptors */
2373                 }
2374
2375                 next_cidx = cidx + 1;
2376                 if (__predict_false(next_cidx == r->size))
2377                         next_cidx = 0;
2378
2379                 wr = (void *)&eq->desc[eq->pidx];
2380                 if (remaining > 1 &&
2381                     try_txpkts(m0, r->items[next_cidx], &txp, available) == 0) {
2382
2383                         /* pkts at cidx, next_cidx should both be in txp. */
2384                         MPASS(txp.npkt == 2);
2385                         tail = r->items[next_cidx];
2386                         MPASS(tail->m_nextpkt == NULL);
2387                         ETHER_BPF_MTAP(ifp, m0);
2388                         ETHER_BPF_MTAP(ifp, tail);
2389                         m0->m_nextpkt = tail;
2390
2391                         if (__predict_false(++next_cidx == r->size))
2392                                 next_cidx = 0;
2393
2394                         while (next_cidx != pidx) {
2395                                 if (add_to_txpkts(r->items[next_cidx], &txp,
2396                                     available) != 0)
2397                                         break;
2398                                 tail->m_nextpkt = r->items[next_cidx];
2399                                 tail = tail->m_nextpkt;
2400                                 ETHER_BPF_MTAP(ifp, tail);
2401                                 if (__predict_false(++next_cidx == r->size))
2402                                         next_cidx = 0;
2403                         }
2404
2405                         n = write_txpkts_wr(txq, wr, m0, &txp, available);
2406                         total += txp.npkt;
2407                         remaining -= txp.npkt;
2408                 } else {
2409                         total++;
2410                         remaining--;
2411                         n = write_txpkt_wr(txq, (void *)wr, m0, available);
2412                         ETHER_BPF_MTAP(ifp, m0);
2413                 }
2414                 MPASS(n >= 1 && n <= available && n <= SGE_MAX_WR_NDESC);
2415
2416                 available -= n;
2417                 dbdiff += n;
2418                 IDXINCR(eq->pidx, n, eq->sidx);
2419
2420                 if (total_available_tx_desc(eq) < eq->sidx / 4 &&
2421                     atomic_cmpset_int(&eq->equiq, 0, 1)) {
2422                         wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUIQ |
2423                             F_FW_WR_EQUEQ);
2424                         eq->equeqidx = eq->pidx;
2425                 } else if (IDXDIFF(eq->pidx, eq->equeqidx, eq->sidx) >= 32) {
2426                         wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUEQ);
2427                         eq->equeqidx = eq->pidx;
2428                 }
2429
2430                 if (dbdiff >= 16 && remaining >= 4) {
2431                         ring_eq_db(sc, eq, dbdiff);
2432                         available += reclaim_tx_descs(txq, 4 * dbdiff);
2433                         dbdiff = 0;
2434                 }
2435
2436                 cidx = next_cidx;
2437         }
2438         if (dbdiff != 0) {
2439                 ring_eq_db(sc, eq, dbdiff);
2440                 reclaim_tx_descs(txq, 32);
2441         }
2442 done:
2443         TXQ_UNLOCK(txq);
2444
2445         return (total);
2446 }
2447
2448 static inline void
2449 init_iq(struct sge_iq *iq, struct adapter *sc, int tmr_idx, int pktc_idx,
2450     int qsize)
2451 {
2452
2453         KASSERT(tmr_idx >= 0 && tmr_idx < SGE_NTIMERS,
2454             ("%s: bad tmr_idx %d", __func__, tmr_idx));
2455         KASSERT(pktc_idx < SGE_NCOUNTERS,       /* -ve is ok, means don't use */
2456             ("%s: bad pktc_idx %d", __func__, pktc_idx));
2457
2458         iq->flags = 0;
2459         iq->adapter = sc;
2460         iq->intr_params = V_QINTR_TIMER_IDX(tmr_idx);
2461         iq->intr_pktc_idx = SGE_NCOUNTERS - 1;
2462         if (pktc_idx >= 0) {
2463                 iq->intr_params |= F_QINTR_CNT_EN;
2464                 iq->intr_pktc_idx = pktc_idx;
2465         }
2466         iq->qsize = roundup2(qsize, 16);        /* See FW_IQ_CMD/iqsize */
2467         iq->sidx = iq->qsize - spg_len / IQ_ESIZE;
2468 }
2469
2470 static inline void
2471 init_fl(struct adapter *sc, struct sge_fl *fl, int qsize, int maxp, char *name)
2472 {
2473
2474         fl->qsize = qsize;
2475         fl->sidx = qsize - spg_len / EQ_ESIZE;
2476         strlcpy(fl->lockname, name, sizeof(fl->lockname));
2477         if (sc->flags & BUF_PACKING_OK &&
2478             ((!is_t4(sc) && buffer_packing) ||  /* T5+: enabled unless 0 */
2479             (is_t4(sc) && buffer_packing == 1)))/* T4: disabled unless 1 */
2480                 fl->flags |= FL_BUF_PACKING;
2481         find_best_refill_source(sc, fl, maxp);
2482         find_safe_refill_source(sc, fl);
2483 }
2484
2485 static inline void
2486 init_eq(struct sge_eq *eq, int eqtype, int qsize, uint8_t tx_chan,
2487     uint16_t iqid, char *name)
2488 {
2489         KASSERT(tx_chan < NCHAN, ("%s: bad tx channel %d", __func__, tx_chan));
2490         KASSERT(eqtype <= EQ_TYPEMASK, ("%s: bad qtype %d", __func__, eqtype));
2491
2492         eq->flags = eqtype & EQ_TYPEMASK;
2493         eq->tx_chan = tx_chan;
2494         eq->iqid = iqid;
2495         eq->sidx = qsize - spg_len / EQ_ESIZE;
2496         strlcpy(eq->lockname, name, sizeof(eq->lockname));
2497 }
2498
2499 static int
2500 alloc_ring(struct adapter *sc, size_t len, bus_dma_tag_t *tag,
2501     bus_dmamap_t *map, bus_addr_t *pa, void **va)
2502 {
2503         int rc;
2504
2505         rc = bus_dma_tag_create(sc->dmat, 512, 0, BUS_SPACE_MAXADDR,
2506             BUS_SPACE_MAXADDR, NULL, NULL, len, 1, len, 0, NULL, NULL, tag);
2507         if (rc != 0) {
2508                 device_printf(sc->dev, "cannot allocate DMA tag: %d\n", rc);
2509                 goto done;
2510         }
2511
2512         rc = bus_dmamem_alloc(*tag, va,
2513             BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, map);
2514         if (rc != 0) {
2515                 device_printf(sc->dev, "cannot allocate DMA memory: %d\n", rc);
2516                 goto done;
2517         }
2518
2519         rc = bus_dmamap_load(*tag, *map, *va, len, oneseg_dma_callback, pa, 0);
2520         if (rc != 0) {
2521                 device_printf(sc->dev, "cannot load DMA map: %d\n", rc);
2522                 goto done;
2523         }
2524 done:
2525         if (rc)
2526                 free_ring(sc, *tag, *map, *pa, *va);
2527
2528         return (rc);
2529 }
2530
2531 static int
2532 free_ring(struct adapter *sc, bus_dma_tag_t tag, bus_dmamap_t map,
2533     bus_addr_t pa, void *va)
2534 {
2535         if (pa)
2536                 bus_dmamap_unload(tag, map);
2537         if (va)
2538                 bus_dmamem_free(tag, va, map);
2539         if (tag)
2540                 bus_dma_tag_destroy(tag);
2541
2542         return (0);
2543 }
2544
2545 /*
2546  * Allocates the ring for an ingress queue and an optional freelist.  If the
2547  * freelist is specified it will be allocated and then associated with the
2548  * ingress queue.
2549  *
2550  * Returns errno on failure.  Resources allocated up to that point may still be
2551  * allocated.  Caller is responsible for cleanup in case this function fails.
2552  *
2553  * If the ingress queue will take interrupts directly (iq->flags & IQ_INTR) then
2554  * the intr_idx specifies the vector, starting from 0.  Otherwise it specifies
2555  * the abs_id of the ingress queue to which its interrupts should be forwarded.
2556  */
2557 static int
2558 alloc_iq_fl(struct vi_info *vi, struct sge_iq *iq, struct sge_fl *fl,
2559     int intr_idx, int cong)
2560 {
2561         int rc, i, cntxt_id;
2562         size_t len;
2563         struct fw_iq_cmd c;
2564         struct port_info *pi = vi->pi;
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(vi->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 vi_info *vi, 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 = vi ? vi->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]->vi[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 vi_info *vi, 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(vi, &rxq->iq, &rxq->fl, intr_idx,
2921             tnl_cong(vi->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(vi->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 = vi->ifp; /* also indicates LRO init'ed */
2938
2939         if (vi->ifp->if_capenable & IFCAP_LRO)
2940                 rxq->iq.flags |= IQ_LRO_ENABLED;
2941 #endif
2942         rxq->ifp = vi->ifp;
2943
2944         children = SYSCTL_CHILDREN(oid);
2945
2946         snprintf(name, sizeof(name), "%d", idx);
2947         oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2948             NULL, "rx queue");
2949         children = SYSCTL_CHILDREN(oid);
2950
2951         SYSCTL_ADD_PROC(&vi->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(&vi->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(&vi->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(&vi->ctx, children, OID_AUTO, "lro_queued", CTLFLAG_RD,
2962             &rxq->lro.lro_queued, 0, NULL);
2963         SYSCTL_ADD_INT(&vi->ctx, children, OID_AUTO, "lro_flushed", CTLFLAG_RD,
2964             &rxq->lro.lro_flushed, 0, NULL);
2965 #endif
2966         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "rxcsum", CTLFLAG_RD,
2967             &rxq->rxcsum, "# of times hardware assisted with checksum");
2968         SYSCTL_ADD_UQUAD(&vi->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(&vi->ctx, oid, &rxq->fl);
2973
2974         return (rc);
2975 }
2976
2977 static int
2978 free_rxq(struct vi_info *vi, 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(vi, &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 vi_info *vi, 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(vi, &ofld_rxq->iq, &ofld_rxq->fl, intr_idx,
3006             vi->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(&vi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
3014             NULL, "rx queue");
3015         children = SYSCTL_CHILDREN(oid);
3016
3017         SYSCTL_ADD_PROC(&vi->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(&vi->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(&vi->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(&vi->ctx, oid, &ofld_rxq->fl);
3028
3029         return (rc);
3030 }
3031
3032 static int
3033 free_ofld_rxq(struct vi_info *vi, struct sge_ofld_rxq *ofld_rxq)
3034 {
3035         int rc;
3036
3037         rc = free_iq_fl(vi, &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 vi_info *vi, 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 = vi->pi->adapter;
3056         struct netmap_adapter *na = NA(vi->ifp);
3057
3058         MPASS(na != NULL);
3059
3060         len = vi->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->vi = vi;
3073         nm_rxq->nid = idx;
3074         nm_rxq->iq_cidx = 0;
3075         nm_rxq->iq_sidx = vi->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 = &vi->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 vi_info *vi, struct sge_nm_rxq *nm_rxq)
3118 {
3119         struct adapter *sc = vi->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 vi_info *vi, 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 port_info *pi = vi->pi;
3136         struct adapter *sc = pi->adapter;
3137         struct netmap_adapter *na = NA(vi->ifp);
3138         char name[16];
3139         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
3140
3141         len = na->num_tx_desc * EQ_ESIZE + spg_len;
3142         rc = alloc_ring(sc, len, &nm_txq->desc_tag, &nm_txq->desc_map,
3143             &nm_txq->ba, (void **)&nm_txq->desc);
3144         if (rc)
3145                 return (rc);
3146
3147         nm_txq->pidx = nm_txq->cidx = 0;
3148         nm_txq->sidx = na->num_tx_desc;
3149         nm_txq->nid = idx;
3150         nm_txq->iqidx = iqidx;
3151         nm_txq->cpl_ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3152             V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_VF_VLD(1) |
3153             V_TXPKT_VF(vi->viid));
3154
3155         snprintf(name, sizeof(name), "%d", idx);
3156         oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
3157             NULL, "netmap tx queue");
3158         children = SYSCTL_CHILDREN(oid);
3159
3160         SYSCTL_ADD_UINT(&vi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
3161             &nm_txq->cntxt_id, 0, "SGE context id of the queue");
3162         SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "cidx",
3163             CTLTYPE_INT | CTLFLAG_RD, &nm_txq->cidx, 0, sysctl_uint16, "I",
3164             "consumer index");
3165         SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "pidx",
3166             CTLTYPE_INT | CTLFLAG_RD, &nm_txq->pidx, 0, sysctl_uint16, "I",
3167             "producer index");
3168
3169         return (rc);
3170 }
3171
3172 static int
3173 free_nm_txq(struct vi_info *vi, struct sge_nm_txq *nm_txq)
3174 {
3175         struct adapter *sc = vi->pi->adapter;
3176
3177         free_ring(sc, nm_txq->desc_tag, nm_txq->desc_map, nm_txq->ba,
3178             nm_txq->desc);
3179
3180         return (0);
3181 }
3182 #endif
3183
3184 static int
3185 ctrl_eq_alloc(struct adapter *sc, struct sge_eq *eq)
3186 {
3187         int rc, cntxt_id;
3188         struct fw_eq_ctrl_cmd c;
3189         int qsize = eq->sidx + spg_len / EQ_ESIZE;
3190
3191         bzero(&c, sizeof(c));
3192
3193         c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
3194             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_CTRL_CMD_PFN(sc->pf) |
3195             V_FW_EQ_CTRL_CMD_VFN(0));
3196         c.alloc_to_len16 = htobe32(F_FW_EQ_CTRL_CMD_ALLOC |
3197             F_FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
3198         c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(eq->iqid));
3199         c.physeqid_pkd = htobe32(0);
3200         c.fetchszm_to_iqid =
3201             htobe32(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
3202                 V_FW_EQ_CTRL_CMD_PCIECHN(eq->tx_chan) |
3203                 F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(eq->iqid));
3204         c.dcaen_to_eqsize =
3205             htobe32(V_FW_EQ_CTRL_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
3206                 V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
3207                 V_FW_EQ_CTRL_CMD_EQSIZE(qsize));
3208         c.eqaddr = htobe64(eq->ba);
3209
3210         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
3211         if (rc != 0) {
3212                 device_printf(sc->dev,
3213                     "failed to create control queue %d: %d\n", eq->tx_chan, rc);
3214                 return (rc);
3215         }
3216         eq->flags |= EQ_ALLOCATED;
3217
3218         eq->cntxt_id = G_FW_EQ_CTRL_CMD_EQID(be32toh(c.cmpliqid_eqid));
3219         cntxt_id = eq->cntxt_id - sc->sge.eq_start;
3220         if (cntxt_id >= sc->sge.neq)
3221             panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
3222                 cntxt_id, sc->sge.neq - 1);
3223         sc->sge.eqmap[cntxt_id] = eq;
3224
3225         return (rc);
3226 }
3227
3228 static int
3229 eth_eq_alloc(struct adapter *sc, struct vi_info *vi, struct sge_eq *eq)
3230 {
3231         int rc, cntxt_id;
3232         struct fw_eq_eth_cmd c;
3233         int qsize = eq->sidx + spg_len / EQ_ESIZE;
3234
3235         bzero(&c, sizeof(c));
3236
3237         c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
3238             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
3239             V_FW_EQ_ETH_CMD_VFN(0));
3240         c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
3241             F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
3242         c.autoequiqe_to_viid = htobe32(F_FW_EQ_ETH_CMD_AUTOEQUIQE |
3243             F_FW_EQ_ETH_CMD_AUTOEQUEQE | V_FW_EQ_ETH_CMD_VIID(vi->viid));
3244         c.fetchszm_to_iqid =
3245             htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
3246                 V_FW_EQ_ETH_CMD_PCIECHN(eq->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
3247                 V_FW_EQ_ETH_CMD_IQID(eq->iqid));
3248         c.dcaen_to_eqsize = htobe32(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
3249             V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
3250             V_FW_EQ_ETH_CMD_EQSIZE(qsize));
3251         c.eqaddr = htobe64(eq->ba);
3252
3253         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
3254         if (rc != 0) {
3255                 device_printf(vi->dev,
3256                     "failed to create Ethernet egress queue: %d\n", rc);
3257                 return (rc);
3258         }
3259         eq->flags |= EQ_ALLOCATED;
3260
3261         eq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
3262         cntxt_id = eq->cntxt_id - sc->sge.eq_start;
3263         if (cntxt_id >= sc->sge.neq)
3264             panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
3265                 cntxt_id, sc->sge.neq - 1);
3266         sc->sge.eqmap[cntxt_id] = eq;
3267
3268         return (rc);
3269 }
3270
3271 #ifdef TCP_OFFLOAD
3272 static int
3273 ofld_eq_alloc(struct adapter *sc, struct vi_info *vi, struct sge_eq *eq)
3274 {
3275         int rc, cntxt_id;
3276         struct fw_eq_ofld_cmd c;
3277         int qsize = eq->sidx + spg_len / EQ_ESIZE;
3278
3279         bzero(&c, sizeof(c));
3280
3281         c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_OFLD_CMD) | F_FW_CMD_REQUEST |
3282             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_OFLD_CMD_PFN(sc->pf) |
3283             V_FW_EQ_OFLD_CMD_VFN(0));
3284         c.alloc_to_len16 = htonl(F_FW_EQ_OFLD_CMD_ALLOC |
3285             F_FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
3286         c.fetchszm_to_iqid =
3287                 htonl(V_FW_EQ_OFLD_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
3288                     V_FW_EQ_OFLD_CMD_PCIECHN(eq->tx_chan) |
3289                     F_FW_EQ_OFLD_CMD_FETCHRO | V_FW_EQ_OFLD_CMD_IQID(eq->iqid));
3290         c.dcaen_to_eqsize =
3291             htobe32(V_FW_EQ_OFLD_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
3292                 V_FW_EQ_OFLD_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
3293                 V_FW_EQ_OFLD_CMD_EQSIZE(qsize));
3294         c.eqaddr = htobe64(eq->ba);
3295
3296         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
3297         if (rc != 0) {
3298                 device_printf(vi->dev,
3299                     "failed to create egress queue for TCP offload: %d\n", rc);
3300                 return (rc);
3301         }
3302         eq->flags |= EQ_ALLOCATED;
3303
3304         eq->cntxt_id = G_FW_EQ_OFLD_CMD_EQID(be32toh(c.eqid_pkd));
3305         cntxt_id = eq->cntxt_id - sc->sge.eq_start;
3306         if (cntxt_id >= sc->sge.neq)
3307             panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
3308                 cntxt_id, sc->sge.neq - 1);
3309         sc->sge.eqmap[cntxt_id] = eq;
3310
3311         return (rc);
3312 }
3313 #endif
3314
3315 static int
3316 alloc_eq(struct adapter *sc, struct vi_info *vi, struct sge_eq *eq)
3317 {
3318         int rc, qsize;
3319         size_t len;
3320
3321         mtx_init(&eq->eq_lock, eq->lockname, NULL, MTX_DEF);
3322
3323         qsize = eq->sidx + spg_len / EQ_ESIZE;
3324         len = qsize * EQ_ESIZE;
3325         rc = alloc_ring(sc, len, &eq->desc_tag, &eq->desc_map,
3326             &eq->ba, (void **)&eq->desc);
3327         if (rc)
3328                 return (rc);
3329
3330         eq->pidx = eq->cidx = 0;
3331         eq->equeqidx = eq->dbidx = 0;
3332         eq->doorbells = sc->doorbells;
3333
3334         switch (eq->flags & EQ_TYPEMASK) {
3335         case EQ_CTRL:
3336                 rc = ctrl_eq_alloc(sc, eq);
3337                 break;
3338
3339         case EQ_ETH:
3340                 rc = eth_eq_alloc(sc, vi, eq);
3341                 break;
3342
3343 #ifdef TCP_OFFLOAD
3344         case EQ_OFLD:
3345                 rc = ofld_eq_alloc(sc, vi, eq);
3346                 break;
3347 #endif
3348
3349         default:
3350                 panic("%s: invalid eq type %d.", __func__,
3351                     eq->flags & EQ_TYPEMASK);
3352         }
3353         if (rc != 0) {
3354                 device_printf(sc->dev,
3355                     "failed to allocate egress queue(%d): %d\n",
3356                     eq->flags & EQ_TYPEMASK, rc);
3357         }
3358
3359         if (isset(&eq->doorbells, DOORBELL_UDB) ||
3360             isset(&eq->doorbells, DOORBELL_UDBWC) ||
3361             isset(&eq->doorbells, DOORBELL_WCWR)) {
3362                 uint32_t s_qpp = sc->sge.eq_s_qpp;
3363                 uint32_t mask = (1 << s_qpp) - 1;
3364                 volatile uint8_t *udb;
3365
3366                 udb = sc->udbs_base + UDBS_DB_OFFSET;
3367                 udb += (eq->cntxt_id >> s_qpp) << PAGE_SHIFT;   /* pg offset */
3368                 eq->udb_qid = eq->cntxt_id & mask;              /* id in page */
3369                 if (eq->udb_qid >= PAGE_SIZE / UDBS_SEG_SIZE)
3370                         clrbit(&eq->doorbells, DOORBELL_WCWR);
3371                 else {
3372                         udb += eq->udb_qid << UDBS_SEG_SHIFT;   /* seg offset */
3373                         eq->udb_qid = 0;
3374                 }
3375                 eq->udb = (volatile void *)udb;
3376         }
3377
3378         return (rc);
3379 }
3380
3381 static int
3382 free_eq(struct adapter *sc, struct sge_eq *eq)
3383 {
3384         int rc;
3385
3386         if (eq->flags & EQ_ALLOCATED) {
3387                 switch (eq->flags & EQ_TYPEMASK) {
3388                 case EQ_CTRL:
3389                         rc = -t4_ctrl_eq_free(sc, sc->mbox, sc->pf, 0,
3390                             eq->cntxt_id);
3391                         break;
3392
3393                 case EQ_ETH:
3394                         rc = -t4_eth_eq_free(sc, sc->mbox, sc->pf, 0,
3395                             eq->cntxt_id);
3396                         break;
3397
3398 #ifdef TCP_OFFLOAD
3399                 case EQ_OFLD:
3400                         rc = -t4_ofld_eq_free(sc, sc->mbox, sc->pf, 0,
3401                             eq->cntxt_id);
3402                         break;
3403 #endif
3404
3405                 default:
3406                         panic("%s: invalid eq type %d.", __func__,
3407                             eq->flags & EQ_TYPEMASK);
3408                 }
3409                 if (rc != 0) {
3410                         device_printf(sc->dev,
3411                             "failed to free egress queue (%d): %d\n",
3412                             eq->flags & EQ_TYPEMASK, rc);
3413                         return (rc);
3414                 }
3415                 eq->flags &= ~EQ_ALLOCATED;
3416         }
3417
3418         free_ring(sc, eq->desc_tag, eq->desc_map, eq->ba, eq->desc);
3419
3420         if (mtx_initialized(&eq->eq_lock))
3421                 mtx_destroy(&eq->eq_lock);
3422
3423         bzero(eq, sizeof(*eq));
3424         return (0);
3425 }
3426
3427 static int
3428 alloc_wrq(struct adapter *sc, struct vi_info *vi, struct sge_wrq *wrq,
3429     struct sysctl_oid *oid)
3430 {
3431         int rc;
3432         struct sysctl_ctx_list *ctx = vi ? &vi->ctx : &sc->ctx;
3433         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
3434
3435         rc = alloc_eq(sc, vi, &wrq->eq);
3436         if (rc)
3437                 return (rc);
3438
3439         wrq->adapter = sc;
3440         TASK_INIT(&wrq->wrq_tx_task, 0, wrq_tx_drain, wrq);
3441         TAILQ_INIT(&wrq->incomplete_wrs);
3442         STAILQ_INIT(&wrq->wr_list);
3443         wrq->nwr_pending = 0;
3444         wrq->ndesc_needed = 0;
3445
3446         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
3447             &wrq->eq.cntxt_id, 0, "SGE context id of the queue");
3448         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
3449             CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.cidx, 0, sysctl_uint16, "I",
3450             "consumer index");
3451         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pidx",
3452             CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.pidx, 0, sysctl_uint16, "I",
3453             "producer index");
3454         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs_direct", CTLFLAG_RD,
3455             &wrq->tx_wrs_direct, "# of work requests (direct)");
3456         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs_copied", CTLFLAG_RD,
3457             &wrq->tx_wrs_copied, "# of work requests (copied)");
3458
3459         return (rc);
3460 }
3461
3462 static int
3463 free_wrq(struct adapter *sc, struct sge_wrq *wrq)
3464 {
3465         int rc;
3466
3467         rc = free_eq(sc, &wrq->eq);
3468         if (rc)
3469                 return (rc);
3470
3471         bzero(wrq, sizeof(*wrq));
3472         return (0);
3473 }
3474
3475 static int
3476 alloc_txq(struct vi_info *vi, struct sge_txq *txq, int idx,
3477     struct sysctl_oid *oid)
3478 {
3479         int rc;
3480         struct port_info *pi = vi->pi;
3481         struct adapter *sc = pi->adapter;
3482         struct sge_eq *eq = &txq->eq;
3483         char name[16];
3484         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
3485
3486         rc = mp_ring_alloc(&txq->r, eq->sidx, txq, eth_tx, can_resume_eth_tx,
3487             M_CXGBE, M_WAITOK);
3488         if (rc != 0) {
3489                 device_printf(sc->dev, "failed to allocate mp_ring: %d\n", rc);
3490                 return (rc);
3491         }
3492
3493         rc = alloc_eq(sc, vi, eq);
3494         if (rc != 0) {
3495                 mp_ring_free(txq->r);
3496                 txq->r = NULL;
3497                 return (rc);
3498         }
3499
3500         /* Can't fail after this point. */
3501
3502         TASK_INIT(&txq->tx_reclaim_task, 0, tx_reclaim, eq);
3503         txq->ifp = vi->ifp;
3504         txq->gl = sglist_alloc(TX_SGL_SEGS, M_WAITOK);
3505         txq->cpl_ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3506             V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_VF_VLD(1) |
3507             V_TXPKT_VF(vi->viid));
3508         txq->sdesc = malloc(eq->sidx * sizeof(struct tx_sdesc), M_CXGBE,
3509             M_ZERO | M_WAITOK);
3510
3511         snprintf(name, sizeof(name), "%d", idx);
3512         oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
3513             NULL, "tx queue");
3514         children = SYSCTL_CHILDREN(oid);
3515
3516         SYSCTL_ADD_UINT(&vi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
3517             &eq->cntxt_id, 0, "SGE context id of the queue");
3518         SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "cidx",
3519             CTLTYPE_INT | CTLFLAG_RD, &eq->cidx, 0, sysctl_uint16, "I",
3520             "consumer index");
3521         SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "pidx",
3522             CTLTYPE_INT | CTLFLAG_RD, &eq->pidx, 0, sysctl_uint16, "I",
3523             "producer index");
3524
3525         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txcsum", CTLFLAG_RD,
3526             &txq->txcsum, "# of times hardware assisted with checksum");
3527         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "vlan_insertion",
3528             CTLFLAG_RD, &txq->vlan_insertion,
3529             "# of times hardware inserted 802.1Q tag");
3530         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "tso_wrs", CTLFLAG_RD,
3531             &txq->tso_wrs, "# of TSO work requests");
3532         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "imm_wrs", CTLFLAG_RD,
3533             &txq->imm_wrs, "# of work requests with immediate data");
3534         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "sgl_wrs", CTLFLAG_RD,
3535             &txq->sgl_wrs, "# of work requests with direct SGL");
3536         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkt_wrs", CTLFLAG_RD,
3537             &txq->txpkt_wrs, "# of txpkt work requests (one pkt/WR)");
3538         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts0_wrs",
3539             CTLFLAG_RD, &txq->txpkts0_wrs,
3540             "# of txpkts (type 0) work requests");
3541         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts1_wrs",
3542             CTLFLAG_RD, &txq->txpkts1_wrs,
3543             "# of txpkts (type 1) work requests");
3544         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts0_pkts",
3545             CTLFLAG_RD, &txq->txpkts0_pkts,
3546             "# of frames tx'd using type0 txpkts work requests");
3547         SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts1_pkts",
3548             CTLFLAG_RD, &txq->txpkts1_pkts,
3549             "# of frames tx'd using type1 txpkts work requests");
3550
3551         SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_enqueues",
3552             CTLFLAG_RD, &txq->r->enqueues,
3553             "# of enqueues to the mp_ring for this queue");
3554         SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_drops",
3555             CTLFLAG_RD, &txq->r->drops,
3556             "# of drops in the mp_ring for this queue");
3557         SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_starts",
3558             CTLFLAG_RD, &txq->r->starts,
3559             "# of normal consumer starts in the mp_ring for this queue");
3560         SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_stalls",
3561             CTLFLAG_RD, &txq->r->stalls,
3562             "# of consumer stalls in the mp_ring for this queue");
3563         SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_restarts",
3564             CTLFLAG_RD, &txq->r->restarts,
3565             "# of consumer restarts in the mp_ring for this queue");
3566         SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_abdications",
3567             CTLFLAG_RD, &txq->r->abdications,
3568             "# of consumer abdications in the mp_ring for this queue");
3569
3570         return (0);
3571 }
3572
3573 static int
3574 free_txq(struct vi_info *vi, struct sge_txq *txq)
3575 {
3576         int rc;
3577         struct adapter *sc = vi->pi->adapter;
3578         struct sge_eq *eq = &txq->eq;
3579
3580         rc = free_eq(sc, eq);
3581         if (rc)
3582                 return (rc);
3583
3584         sglist_free(txq->gl);
3585         free(txq->sdesc, M_CXGBE);
3586         mp_ring_free(txq->r);
3587
3588         bzero(txq, sizeof(*txq));
3589         return (0);
3590 }
3591
3592 static void
3593 oneseg_dma_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
3594 {
3595         bus_addr_t *ba = arg;
3596
3597         KASSERT(nseg == 1,
3598             ("%s meant for single segment mappings only.", __func__));
3599
3600         *ba = error ? 0 : segs->ds_addr;
3601 }
3602
3603 static inline void
3604 ring_fl_db(struct adapter *sc, struct sge_fl *fl)
3605 {
3606         uint32_t n, v;
3607
3608         n = IDXDIFF(fl->pidx / 8, fl->dbidx, fl->sidx);
3609         MPASS(n > 0);
3610
3611         wmb();
3612         v = fl->dbval | V_PIDX(n);
3613         if (fl->udb)
3614                 *fl->udb = htole32(v);
3615         else
3616                 t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL), v);
3617         IDXINCR(fl->dbidx, n, fl->sidx);
3618 }
3619
3620 /*
3621  * Fills up the freelist by allocating upto 'n' buffers.  Buffers that are
3622  * recycled do not count towards this allocation budget.
3623  *
3624  * Returns non-zero to indicate that this freelist should be added to the list
3625  * of starving freelists.
3626  */
3627 static int
3628 refill_fl(struct adapter *sc, struct sge_fl *fl, int n)
3629 {
3630         __be64 *d;
3631         struct fl_sdesc *sd;
3632         uintptr_t pa;
3633         caddr_t cl;
3634         struct cluster_layout *cll;
3635         struct sw_zone_info *swz;
3636         struct cluster_metadata *clm;
3637         uint16_t max_pidx;
3638         uint16_t hw_cidx = fl->hw_cidx;         /* stable snapshot */
3639
3640         FL_LOCK_ASSERT_OWNED(fl);
3641
3642         /*
3643          * We always stop at the begining of the hardware descriptor that's just
3644          * before the one with the hw cidx.  This is to avoid hw pidx = hw cidx,
3645          * which would mean an empty freelist to the chip.
3646          */
3647         max_pidx = __predict_false(hw_cidx == 0) ? fl->sidx - 1 : hw_cidx - 1;
3648         if (fl->pidx == max_pidx * 8)
3649                 return (0);
3650
3651         d = &fl->desc[fl->pidx];
3652         sd = &fl->sdesc[fl->pidx];
3653         cll = &fl->cll_def;     /* default layout */
3654         swz = &sc->sge.sw_zone_info[cll->zidx];
3655
3656         while (n > 0) {
3657
3658                 if (sd->cl != NULL) {
3659
3660                         if (sd->nmbuf == 0) {
3661                                 /*
3662                                  * Fast recycle without involving any atomics on
3663                                  * the cluster's metadata (if the cluster has
3664                                  * metadata).  This happens when all frames
3665                                  * received in the cluster were small enough to
3666                                  * fit within a single mbuf each.
3667                                  */
3668                                 fl->cl_fast_recycled++;
3669 #ifdef INVARIANTS
3670                                 clm = cl_metadata(sc, fl, &sd->cll, sd->cl);
3671                                 if (clm != NULL)
3672                                         MPASS(clm->refcount == 1);
3673 #endif
3674                                 goto recycled_fast;
3675                         }
3676
3677                         /*
3678                          * Cluster is guaranteed to have metadata.  Clusters
3679                          * without metadata always take the fast recycle path
3680                          * when they're recycled.
3681                          */
3682                         clm = cl_metadata(sc, fl, &sd->cll, sd->cl);
3683                         MPASS(clm != NULL);
3684
3685                         if (atomic_fetchadd_int(&clm->refcount, -1) == 1) {
3686                                 fl->cl_recycled++;
3687                                 counter_u64_add(extfree_rels, 1);
3688                                 goto recycled;
3689                         }
3690                         sd->cl = NULL;  /* gave up my reference */
3691                 }
3692                 MPASS(sd->cl == NULL);
3693 alloc:
3694                 cl = uma_zalloc(swz->zone, M_NOWAIT);
3695                 if (__predict_false(cl == NULL)) {
3696                         if (cll == &fl->cll_alt || fl->cll_alt.zidx == -1 ||
3697                             fl->cll_def.zidx == fl->cll_alt.zidx)
3698                                 break;
3699
3700                         /* fall back to the safe zone */
3701                         cll = &fl->cll_alt;
3702                         swz = &sc->sge.sw_zone_info[cll->zidx];
3703                         goto alloc;
3704                 }
3705                 fl->cl_allocated++;
3706                 n--;
3707
3708                 pa = pmap_kextract((vm_offset_t)cl);
3709                 pa += cll->region1;
3710                 sd->cl = cl;
3711                 sd->cll = *cll;
3712                 *d = htobe64(pa | cll->hwidx);
3713                 clm = cl_metadata(sc, fl, cll, cl);
3714                 if (clm != NULL) {
3715 recycled:
3716 #ifdef INVARIANTS
3717                         clm->sd = sd;
3718 #endif
3719                         clm->refcount = 1;
3720                 }
3721                 sd->nmbuf = 0;
3722 recycled_fast:
3723                 d++;
3724                 sd++;
3725                 if (__predict_false(++fl->pidx % 8 == 0)) {
3726                         uint16_t pidx = fl->pidx / 8;
3727
3728                         if (__predict_false(pidx == fl->sidx)) {
3729                                 fl->pidx = 0;
3730                                 pidx = 0;
3731                                 sd = fl->sdesc;
3732                                 d = fl->desc;
3733                         }
3734                         if (pidx == max_pidx)
3735                                 break;
3736
3737                         if (IDXDIFF(pidx, fl->dbidx, fl->sidx) >= 4)
3738                                 ring_fl_db(sc, fl);
3739                 }
3740         }
3741
3742         if (fl->pidx / 8 != fl->dbidx)
3743                 ring_fl_db(sc, fl);
3744
3745         return (FL_RUNNING_LOW(fl) && !(fl->flags & FL_STARVING));
3746 }
3747
3748 /*
3749  * Attempt to refill all starving freelists.
3750  */
3751 static void
3752 refill_sfl(void *arg)
3753 {
3754         struct adapter *sc = arg;
3755         struct sge_fl *fl, *fl_temp;
3756
3757         mtx_assert(&sc->sfl_lock, MA_OWNED);
3758         TAILQ_FOREACH_SAFE(fl, &sc->sfl, link, fl_temp) {
3759                 FL_LOCK(fl);
3760                 refill_fl(sc, fl, 64);
3761                 if (FL_NOT_RUNNING_LOW(fl) || fl->flags & FL_DOOMED) {
3762                         TAILQ_REMOVE(&sc->sfl, fl, link);
3763                         fl->flags &= ~FL_STARVING;
3764                 }
3765                 FL_UNLOCK(fl);
3766         }
3767
3768         if (!TAILQ_EMPTY(&sc->sfl))
3769                 callout_schedule(&sc->sfl_callout, hz / 5);
3770 }
3771
3772 static int
3773 alloc_fl_sdesc(struct sge_fl *fl)
3774 {
3775
3776         fl->sdesc = malloc(fl->sidx * 8 * sizeof(struct fl_sdesc), M_CXGBE,
3777             M_ZERO | M_WAITOK);
3778
3779         return (0);
3780 }
3781
3782 static void
3783 free_fl_sdesc(struct adapter *sc, struct sge_fl *fl)
3784 {
3785         struct fl_sdesc *sd;
3786         struct cluster_metadata *clm;
3787         struct cluster_layout *cll;
3788         int i;
3789
3790         sd = fl->sdesc;
3791         for (i = 0; i < fl->sidx * 8; i++, sd++) {
3792                 if (sd->cl == NULL)
3793                         continue;
3794
3795                 cll = &sd->cll;
3796                 clm = cl_metadata(sc, fl, cll, sd->cl);
3797                 if (sd->nmbuf == 0)
3798                         uma_zfree(sc->sge.sw_zone_info[cll->zidx].zone, sd->cl);
3799                 else if (clm && atomic_fetchadd_int(&clm->refcount, -1) == 1) {
3800                         uma_zfree(sc->sge.sw_zone_info[cll->zidx].zone, sd->cl);
3801                         counter_u64_add(extfree_rels, 1);
3802                 }
3803                 sd->cl = NULL;
3804         }
3805
3806         free(fl->sdesc, M_CXGBE);
3807         fl->sdesc = NULL;
3808 }
3809
3810 static inline void
3811 get_pkt_gl(struct mbuf *m, struct sglist *gl)
3812 {
3813         int rc;
3814
3815         M_ASSERTPKTHDR(m);
3816
3817         sglist_reset(gl);
3818         rc = sglist_append_mbuf(gl, m);
3819         if (__predict_false(rc != 0)) {
3820                 panic("%s: mbuf %p (%d segs) was vetted earlier but now fails "
3821                     "with %d.", __func__, m, mbuf_nsegs(m), rc);
3822         }
3823
3824         KASSERT(gl->sg_nseg == mbuf_nsegs(m),
3825             ("%s: nsegs changed for mbuf %p from %d to %d", __func__, m,
3826             mbuf_nsegs(m), gl->sg_nseg));
3827         KASSERT(gl->sg_nseg > 0 &&
3828             gl->sg_nseg <= (needs_tso(m) ? TX_SGL_SEGS_TSO : TX_SGL_SEGS),
3829             ("%s: %d segments, should have been 1 <= nsegs <= %d", __func__,
3830                 gl->sg_nseg, needs_tso(m) ? TX_SGL_SEGS_TSO : TX_SGL_SEGS));
3831 }
3832
3833 /*
3834  * len16 for a txpkt WR with a GL.  Includes the firmware work request header.
3835  */
3836 static inline u_int
3837 txpkt_len16(u_int nsegs, u_int tso)
3838 {
3839         u_int n;
3840
3841         MPASS(nsegs > 0);
3842
3843         nsegs--; /* first segment is part of ulptx_sgl */
3844         n = sizeof(struct fw_eth_tx_pkt_wr) + sizeof(struct cpl_tx_pkt_core) +
3845             sizeof(struct ulptx_sgl) + 8 * ((3 * nsegs) / 2 + (nsegs & 1));
3846         if (tso)
3847                 n += sizeof(struct cpl_tx_pkt_lso_core);
3848
3849         return (howmany(n, 16));
3850 }
3851
3852 /*
3853  * len16 for a txpkts type 0 WR with a GL.  Does not include the firmware work
3854  * request header.
3855  */
3856 static inline u_int
3857 txpkts0_len16(u_int nsegs)
3858 {
3859         u_int n;
3860
3861         MPASS(nsegs > 0);
3862
3863         nsegs--; /* first segment is part of ulptx_sgl */
3864         n = sizeof(struct ulp_txpkt) + sizeof(struct ulptx_idata) +
3865             sizeof(struct cpl_tx_pkt_core) + sizeof(struct ulptx_sgl) +
3866             8 * ((3 * nsegs) / 2 + (nsegs & 1));
3867
3868         return (howmany(n, 16));
3869 }
3870
3871 /*
3872  * len16 for a txpkts type 1 WR with a GL.  Does not include the firmware work
3873  * request header.
3874  */
3875 static inline u_int
3876 txpkts1_len16(void)
3877 {
3878         u_int n;
3879
3880         n = sizeof(struct cpl_tx_pkt_core) + sizeof(struct ulptx_sgl);
3881
3882         return (howmany(n, 16));
3883 }
3884
3885 static inline u_int
3886 imm_payload(u_int ndesc)
3887 {
3888         u_int n;
3889
3890         n = ndesc * EQ_ESIZE - sizeof(struct fw_eth_tx_pkt_wr) -
3891             sizeof(struct cpl_tx_pkt_core);
3892
3893         return (n);
3894 }
3895
3896 /*
3897  * Write a txpkt WR for this packet to the hardware descriptors, update the
3898  * software descriptor, and advance the pidx.  It is guaranteed that enough
3899  * descriptors are available.
3900  *
3901  * The return value is the # of hardware descriptors used.
3902  */
3903 static u_int
3904 write_txpkt_wr(struct sge_txq *txq, struct fw_eth_tx_pkt_wr *wr,
3905     struct mbuf *m0, u_int available)
3906 {
3907         struct sge_eq *eq = &txq->eq;
3908         struct tx_sdesc *txsd;
3909         struct cpl_tx_pkt_core *cpl;
3910         uint32_t ctrl;  /* used in many unrelated places */
3911         uint64_t ctrl1;
3912         int len16, ndesc, pktlen, nsegs;
3913         caddr_t dst;
3914
3915         TXQ_LOCK_ASSERT_OWNED(txq);
3916         M_ASSERTPKTHDR(m0);
3917         MPASS(available > 0 && available < eq->sidx);
3918
3919         len16 = mbuf_len16(m0);
3920         nsegs = mbuf_nsegs(m0);
3921         pktlen = m0->m_pkthdr.len;
3922         ctrl = sizeof(struct cpl_tx_pkt_core);
3923         if (needs_tso(m0))
3924                 ctrl += sizeof(struct cpl_tx_pkt_lso_core);
3925         else if (pktlen <= imm_payload(2) && available >= 2) {
3926                 /* Immediate data.  Recalculate len16 and set nsegs to 0. */
3927                 ctrl += pktlen;
3928                 len16 = howmany(sizeof(struct fw_eth_tx_pkt_wr) +
3929                     sizeof(struct cpl_tx_pkt_core) + pktlen, 16);
3930                 nsegs = 0;
3931         }
3932         ndesc = howmany(len16, EQ_ESIZE / 16);
3933         MPASS(ndesc <= available);
3934
3935         /* Firmware work request header */
3936         MPASS(wr == (void *)&eq->desc[eq->pidx]);
3937         wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
3938             V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));
3939
3940         ctrl = V_FW_WR_LEN16(len16);
3941         wr->equiq_to_len16 = htobe32(ctrl);
3942         wr->r3 = 0;
3943
3944         if (needs_tso(m0)) {
3945                 struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
3946
3947                 KASSERT(m0->m_pkthdr.l2hlen > 0 && m0->m_pkthdr.l3hlen > 0 &&
3948                     m0->m_pkthdr.l4hlen > 0,
3949                     ("%s: mbuf %p needs TSO but missing header lengths",
3950                         __func__, m0));
3951
3952                 ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) | F_LSO_FIRST_SLICE |
3953                     F_LSO_LAST_SLICE | V_LSO_IPHDR_LEN(m0->m_pkthdr.l3hlen >> 2)
3954                     | V_LSO_TCPHDR_LEN(m0->m_pkthdr.l4hlen >> 2);
3955                 if (m0->m_pkthdr.l2hlen == sizeof(struct ether_vlan_header))
3956                         ctrl |= V_LSO_ETHHDR_LEN(1);
3957                 if (m0->m_pkthdr.l3hlen == sizeof(struct ip6_hdr))
3958                         ctrl |= F_LSO_IPV6;
3959
3960                 lso->lso_ctrl = htobe32(ctrl);
3961                 lso->ipid_ofst = htobe16(0);
3962                 lso->mss = htobe16(m0->m_pkthdr.tso_segsz);
3963                 lso->seqno_offset = htobe32(0);
3964                 lso->len = htobe32(pktlen);
3965
3966                 cpl = (void *)(lso + 1);
3967
3968                 txq->tso_wrs++;
3969         } else
3970                 cpl = (void *)(wr + 1);
3971
3972         /* Checksum offload */
3973         ctrl1 = 0;
3974         if (needs_l3_csum(m0) == 0)
3975                 ctrl1 |= F_TXPKT_IPCSUM_DIS;
3976         if (needs_l4_csum(m0) == 0)
3977                 ctrl1 |= F_TXPKT_L4CSUM_DIS;
3978         if (m0->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3979             CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3980                 txq->txcsum++;  /* some hardware assistance provided */
3981
3982         /* VLAN tag insertion */
3983         if (needs_vlan_insertion(m0)) {
3984                 ctrl1 |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m0->m_pkthdr.ether_vtag);
3985                 txq->vlan_insertion++;
3986         }
3987
3988         /* CPL header */
3989         cpl->ctrl0 = txq->cpl_ctrl0;
3990         cpl->pack = 0;
3991         cpl->len = htobe16(pktlen);
3992         cpl->ctrl1 = htobe64(ctrl1);
3993
3994         /* SGL */
3995         dst = (void *)(cpl + 1);
3996         if (nsegs > 0) {
3997
3998                 write_gl_to_txd(txq, m0, &dst, eq->sidx - ndesc < eq->pidx);
3999                 txq->sgl_wrs++;
4000         } else {
4001                 struct mbuf *m;
4002
4003                 for (m = m0; m != NULL; m = m->m_next) {
4004                         copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
4005 #ifdef INVARIANTS
4006                         pktlen -= m->m_len;
4007 #endif
4008                 }
4009 #ifdef INVARIANTS
4010                 KASSERT(pktlen == 0, ("%s: %d bytes left.", __func__, pktlen));
4011 #endif
4012                 txq->imm_wrs++;
4013         }
4014
4015         txq->txpkt_wrs++;
4016
4017         txsd = &txq->sdesc[eq->pidx];
4018         txsd->m = m0;
4019         txsd->desc_used = ndesc;
4020
4021         return (ndesc);
4022 }
4023
4024 static int
4025 try_txpkts(struct mbuf *m, struct mbuf *n, struct txpkts *txp, u_int available)
4026 {
4027         u_int needed, nsegs1, nsegs2, l1, l2;
4028
4029         if (cannot_use_txpkts(m) || cannot_use_txpkts(n))
4030                 return (1);
4031
4032         nsegs1 = mbuf_nsegs(m);
4033         nsegs2 = mbuf_nsegs(n);
4034         if (nsegs1 + nsegs2 == 2) {
4035                 txp->wr_type = 1;
4036                 l1 = l2 = txpkts1_len16();
4037         } else {
4038                 txp->wr_type = 0;
4039                 l1 = txpkts0_len16(nsegs1);
4040                 l2 = txpkts0_len16(nsegs2);
4041         }
4042         txp->len16 = howmany(sizeof(struct fw_eth_tx_pkts_wr), 16) + l1 + l2;
4043         needed = howmany(txp->len16, EQ_ESIZE / 16);
4044         if (needed > SGE_MAX_WR_NDESC || needed > available)
4045                 return (1);
4046
4047         txp->plen = m->m_pkthdr.len + n->m_pkthdr.len;
4048         if (txp->plen > 65535)
4049                 return (1);
4050
4051         txp->npkt = 2;
4052         set_mbuf_len16(m, l1);
4053         set_mbuf_len16(n, l2);
4054
4055         return (0);
4056 }
4057
4058 static int
4059 add_to_txpkts(struct mbuf *m, struct txpkts *txp, u_int available)
4060 {
4061         u_int plen, len16, needed, nsegs;
4062
4063         MPASS(txp->wr_type == 0 || txp->wr_type == 1);
4064
4065         nsegs = mbuf_nsegs(m);
4066         if (needs_tso(m) || (txp->wr_type == 1 && nsegs != 1))
4067                 return (1);
4068
4069         plen = txp->plen + m->m_pkthdr.len;
4070         if (plen > 65535)
4071                 return (1);
4072
4073         if (txp->wr_type == 0)
4074                 len16 = txpkts0_len16(nsegs);
4075         else
4076                 len16 = txpkts1_len16();
4077         needed = howmany(txp->len16 + len16, EQ_ESIZE / 16);
4078         if (needed > SGE_MAX_WR_NDESC || needed > available)
4079                 return (1);
4080
4081         txp->npkt++;
4082         txp->plen = plen;
4083         txp->len16 += len16;
4084         set_mbuf_len16(m, len16);
4085
4086         return (0);
4087 }
4088
4089 /*
4090  * Write a txpkts WR for the packets in txp to the hardware descriptors, update
4091  * the software descriptor, and advance the pidx.  It is guaranteed that enough
4092  * descriptors are available.
4093  *
4094  * The return value is the # of hardware descriptors used.
4095  */
4096 static u_int
4097 write_txpkts_wr(struct sge_txq *txq, struct fw_eth_tx_pkts_wr *wr,
4098     struct mbuf *m0, const struct txpkts *txp, u_int available)
4099 {
4100         struct sge_eq *eq = &txq->eq;
4101         struct tx_sdesc *txsd;
4102         struct cpl_tx_pkt_core *cpl;
4103         uint32_t ctrl;
4104         uint64_t ctrl1;
4105         int ndesc, checkwrap;
4106         struct mbuf *m;
4107         void *flitp;
4108
4109         TXQ_LOCK_ASSERT_OWNED(txq);
4110         MPASS(txp->npkt > 0);
4111         MPASS(txp->plen < 65536);
4112         MPASS(m0 != NULL);
4113         MPASS(m0->m_nextpkt != NULL);
4114         MPASS(txp->len16 <= howmany(SGE_MAX_WR_LEN, 16));
4115         MPASS(available > 0 && available < eq->sidx);
4116
4117         ndesc = howmany(txp->len16, EQ_ESIZE / 16);
4118         MPASS(ndesc <= available);
4119
4120         MPASS(wr == (void *)&eq->desc[eq->pidx]);
4121         wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
4122         ctrl = V_FW_WR_LEN16(txp->len16);
4123         wr->equiq_to_len16 = htobe32(ctrl);
4124         wr->plen = htobe16(txp->plen);
4125         wr->npkt = txp->npkt;
4126         wr->r3 = 0;
4127         wr->type = txp->wr_type;
4128         flitp = wr + 1;
4129
4130         /*
4131          * At this point we are 16B into a hardware descriptor.  If checkwrap is
4132          * set then we know the WR is going to wrap around somewhere.  We'll
4133          * check for that at appropriate points.
4134          */
4135         checkwrap = eq->sidx - ndesc < eq->pidx;
4136         for (m = m0; m != NULL; m = m->m_nextpkt) {
4137                 if (txp->wr_type == 0) {
4138                         struct ulp_txpkt *ulpmc;
4139                         struct ulptx_idata *ulpsc;
4140
4141                         /* ULP master command */
4142                         ulpmc = flitp;
4143                         ulpmc->cmd_dest = htobe32(V_ULPTX_CMD(ULP_TX_PKT) |
4144                             V_ULP_TXPKT_DEST(0) | V_ULP_TXPKT_FID(eq->iqid));
4145                         ulpmc->len = htobe32(mbuf_len16(m));
4146
4147                         /* ULP subcommand */
4148                         ulpsc = (void *)(ulpmc + 1);
4149                         ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM) |
4150                             F_ULP_TX_SC_MORE);
4151                         ulpsc->len = htobe32(sizeof(struct cpl_tx_pkt_core));
4152
4153                         cpl = (void *)(ulpsc + 1);
4154                         if (checkwrap &&
4155                             (uintptr_t)cpl == (uintptr_t)&eq->desc[eq->sidx])
4156                                 cpl = (void *)&eq->desc[0];
4157                         txq->txpkts0_pkts += txp->npkt;
4158                         txq->txpkts0_wrs++;
4159                 } else {
4160                         cpl = flitp;
4161                         txq->txpkts1_pkts += txp->npkt;
4162                         txq->txpkts1_wrs++;
4163                 }
4164
4165                 /* Checksum offload */
4166                 ctrl1 = 0;
4167                 if (needs_l3_csum(m) == 0)
4168                         ctrl1 |= F_TXPKT_IPCSUM_DIS;
4169                 if (needs_l4_csum(m) == 0)
4170                         ctrl1 |= F_TXPKT_L4CSUM_DIS;
4171                 if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
4172                     CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
4173                         txq->txcsum++;  /* some hardware assistance provided */
4174
4175                 /* VLAN tag insertion */
4176                 if (needs_vlan_insertion(m)) {
4177                         ctrl1 |= F_TXPKT_VLAN_VLD |
4178                             V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
4179                         txq->vlan_insertion++;
4180                 }
4181
4182                 /* CPL header */
4183                 cpl->ctrl0 = txq->cpl_ctrl0;
4184                 cpl->pack = 0;
4185                 cpl->len = htobe16(m->m_pkthdr.len);
4186                 cpl->ctrl1 = htobe64(ctrl1);
4187
4188                 flitp = cpl + 1;
4189                 if (checkwrap &&
4190                     (uintptr_t)flitp == (uintptr_t)&eq->desc[eq->sidx])
4191                         flitp = (void *)&eq->desc[0];
4192
4193                 write_gl_to_txd(txq, m, (caddr_t *)(&flitp), checkwrap);
4194
4195         }
4196
4197         txsd = &txq->sdesc[eq->pidx];
4198         txsd->m = m0;
4199         txsd->desc_used = ndesc;
4200
4201         return (ndesc);
4202 }
4203
4204 /*
4205  * If the SGL ends on an address that is not 16 byte aligned, this function will
4206  * add a 0 filled flit at the end.
4207  */
4208 static void
4209 write_gl_to_txd(struct sge_txq *txq, struct mbuf *m, caddr_t *to, int checkwrap)
4210 {
4211         struct sge_eq *eq = &txq->eq;
4212         struct sglist *gl = txq->gl;
4213         struct sglist_seg *seg;
4214         __be64 *flitp, *wrap;
4215         struct ulptx_sgl *usgl;
4216         int i, nflits, nsegs;
4217
4218         KASSERT(((uintptr_t)(*to) & 0xf) == 0,
4219             ("%s: SGL must start at a 16 byte boundary: %p", __func__, *to));
4220         MPASS((uintptr_t)(*to) >= (uintptr_t)&eq->desc[0]);
4221         MPASS((uintptr_t)(*to) < (uintptr_t)&eq->desc[eq->sidx]);
4222
4223         get_pkt_gl(m, gl);
4224         nsegs = gl->sg_nseg;
4225         MPASS(nsegs > 0);
4226
4227         nflits = (3 * (nsegs - 1)) / 2 + ((nsegs - 1) & 1) + 2;
4228         flitp = (__be64 *)(*to);
4229         wrap = (__be64 *)(&eq->desc[eq->sidx]);
4230         seg = &gl->sg_segs[0];
4231         usgl = (void *)flitp;
4232
4233         /*
4234          * We start at a 16 byte boundary somewhere inside the tx descriptor
4235          * ring, so we're at least 16 bytes away from the status page.  There is
4236          * no chance of a wrap around in the middle of usgl (which is 16 bytes).
4237          */
4238
4239         usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
4240             V_ULPTX_NSGE(nsegs));
4241         usgl->len0 = htobe32(seg->ss_len);
4242         usgl->addr0 = htobe64(seg->ss_paddr);
4243         seg++;
4244
4245         if (checkwrap == 0 || (uintptr_t)(flitp + nflits) <= (uintptr_t)wrap) {
4246
4247                 /* Won't wrap around at all */
4248
4249                 for (i = 0; i < nsegs - 1; i++, seg++) {
4250                         usgl->sge[i / 2].len[i & 1] = htobe32(seg->ss_len);
4251                         usgl->sge[i / 2].addr[i & 1] = htobe64(seg->ss_paddr);
4252                 }
4253                 if (i & 1)
4254                         usgl->sge[i / 2].len[1] = htobe32(0);
4255                 flitp += nflits;
4256         } else {
4257
4258                 /* Will wrap somewhere in the rest of the SGL */
4259
4260                 /* 2 flits already written, write the rest flit by flit */
4261                 flitp = (void *)(usgl + 1);
4262                 for (i = 0; i < nflits - 2; i++) {
4263                         if (flitp == wrap)
4264                                 flitp = (void *)eq->desc;
4265                         *flitp++ = get_flit(seg, nsegs - 1, i);
4266                 }
4267         }
4268
4269         if (nflits & 1) {
4270                 MPASS(((uintptr_t)flitp) & 0xf);
4271                 *flitp++ = 0;
4272         }
4273
4274         MPASS((((uintptr_t)flitp) & 0xf) == 0);
4275         if (__predict_false(flitp == wrap))
4276                 *to = (void *)eq->desc;
4277         else
4278                 *to = (void *)flitp;
4279 }
4280
4281 static inline void
4282 copy_to_txd(struct sge_eq *eq, caddr_t from, caddr_t *to, int len)
4283 {
4284
4285         MPASS((uintptr_t)(*to) >= (uintptr_t)&eq->desc[0]);
4286         MPASS((uintptr_t)(*to) < (uintptr_t)&eq->desc[eq->sidx]);
4287
4288         if (__predict_true((uintptr_t)(*to) + len <=
4289             (uintptr_t)&eq->desc[eq->sidx])) {
4290                 bcopy(from, *to, len);
4291                 (*to) += len;
4292         } else {
4293                 int portion = (uintptr_t)&eq->desc[eq->sidx] - (uintptr_t)(*to);
4294
4295                 bcopy(from, *to, portion);
4296                 from += portion;
4297                 portion = len - portion;        /* remaining */
4298                 bcopy(from, (void *)eq->desc, portion);
4299                 (*to) = (caddr_t)eq->desc + portion;
4300         }
4301 }
4302
4303 static inline void
4304 ring_eq_db(struct adapter *sc, struct sge_eq *eq, u_int n)
4305 {
4306         u_int db;
4307
4308         MPASS(n > 0);
4309
4310         db = eq->doorbells;
4311         if (n > 1)
4312                 clrbit(&db, DOORBELL_WCWR);
4313         wmb();
4314
4315         switch (ffs(db) - 1) {
4316         case DOORBELL_UDB:
4317                 *eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(n));
4318                 break;
4319
4320         case DOORBELL_WCWR: {
4321                 volatile uint64_t *dst, *src;
4322                 int i;
4323
4324                 /*
4325                  * Queues whose 128B doorbell segment fits in the page do not
4326                  * use relative qid (udb_qid is always 0).  Only queues with
4327                  * doorbell segments can do WCWR.
4328                  */
4329                 KASSERT(eq->udb_qid == 0 && n == 1,
4330                     ("%s: inappropriate doorbell (0x%x, %d, %d) for eq %p",
4331                     __func__, eq->doorbells, n, eq->dbidx, eq));
4332
4333                 dst = (volatile void *)((uintptr_t)eq->udb + UDBS_WR_OFFSET -
4334                     UDBS_DB_OFFSET);
4335                 i = eq->dbidx;
4336                 src = (void *)&eq->desc[i];
4337                 while (src != (void *)&eq->desc[i + 1])
4338                         *dst++ = *src++;
4339                 wmb();
4340                 break;
4341         }
4342
4343         case DOORBELL_UDBWC:
4344                 *eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(n));
4345                 wmb();
4346                 break;
4347
4348         case DOORBELL_KDB:
4349                 t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL),
4350                     V_QID(eq->cntxt_id) | V_PIDX(n));
4351                 break;
4352         }
4353
4354         IDXINCR(eq->dbidx, n, eq->sidx);
4355 }
4356
4357 static inline u_int
4358 reclaimable_tx_desc(struct sge_eq *eq)
4359 {
4360         uint16_t hw_cidx;
4361
4362         hw_cidx = read_hw_cidx(eq);
4363         return (IDXDIFF(hw_cidx, eq->cidx, eq->sidx));
4364 }
4365
4366 static inline u_int
4367 total_available_tx_desc(struct sge_eq *eq)
4368 {
4369         uint16_t hw_cidx, pidx;
4370
4371         hw_cidx = read_hw_cidx(eq);
4372         pidx = eq->pidx;
4373
4374         if (pidx == hw_cidx)
4375                 return (eq->sidx - 1);
4376         else
4377                 return (IDXDIFF(hw_cidx, pidx, eq->sidx) - 1);
4378 }
4379
4380 static inline uint16_t
4381 read_hw_cidx(struct sge_eq *eq)
4382 {
4383         struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
4384         uint16_t cidx = spg->cidx;      /* stable snapshot */
4385
4386         return (be16toh(cidx));
4387 }
4388
4389 /*
4390  * Reclaim 'n' descriptors approximately.
4391  */
4392 static u_int
4393 reclaim_tx_descs(struct sge_txq *txq, u_int n)
4394 {
4395         struct tx_sdesc *txsd;
4396         struct sge_eq *eq = &txq->eq;
4397         u_int can_reclaim, reclaimed;
4398
4399         TXQ_LOCK_ASSERT_OWNED(txq);
4400         MPASS(n > 0);
4401
4402         reclaimed = 0;
4403         can_reclaim = reclaimable_tx_desc(eq);
4404         while (can_reclaim && reclaimed < n) {
4405                 int ndesc;
4406                 struct mbuf *m, *nextpkt;
4407
4408                 txsd = &txq->sdesc[eq->cidx];
4409                 ndesc = txsd->desc_used;
4410
4411                 /* Firmware doesn't return "partial" credits. */
4412                 KASSERT(can_reclaim >= ndesc,
4413                     ("%s: unexpected number of credits: %d, %d",
4414                     __func__, can_reclaim, ndesc));
4415
4416                 for (m = txsd->m; m != NULL; m = nextpkt) {
4417                         nextpkt = m->m_nextpkt;
4418                         m->m_nextpkt = NULL;
4419                         m_freem(m);
4420                 }
4421                 reclaimed += ndesc;
4422                 can_reclaim -= ndesc;
4423                 IDXINCR(eq->cidx, ndesc, eq->sidx);
4424         }
4425
4426         return (reclaimed);
4427 }
4428
4429 static void
4430 tx_reclaim(void *arg, int n)
4431 {
4432         struct sge_txq *txq = arg;
4433         struct sge_eq *eq = &txq->eq;
4434
4435         do {
4436                 if (TXQ_TRYLOCK(txq) == 0)
4437                         break;
4438                 n = reclaim_tx_descs(txq, 32);
4439                 if (eq->cidx == eq->pidx)
4440                         eq->equeqidx = eq->pidx;
4441                 TXQ_UNLOCK(txq);
4442         } while (n > 0);
4443 }
4444
4445 static __be64
4446 get_flit(struct sglist_seg *segs, int nsegs, int idx)
4447 {
4448         int i = (idx / 3) * 2;
4449
4450         switch (idx % 3) {
4451         case 0: {
4452                 __be64 rc;
4453
4454                 rc = htobe32(segs[i].ss_len);
4455                 if (i + 1 < nsegs)
4456                         rc |= (uint64_t)htobe32(segs[i + 1].ss_len) << 32;
4457
4458                 return (rc);
4459         }
4460         case 1:
4461                 return (htobe64(segs[i].ss_paddr));
4462         case 2:
4463                 return (htobe64(segs[i + 1].ss_paddr));
4464         }
4465
4466         return (0);
4467 }
4468
4469 static void
4470 find_best_refill_source(struct adapter *sc, struct sge_fl *fl, int maxp)
4471 {
4472         int8_t zidx, hwidx, idx;
4473         uint16_t region1, region3;
4474         int spare, spare_needed, n;
4475         struct sw_zone_info *swz;
4476         struct hw_buf_info *hwb, *hwb_list = &sc->sge.hw_buf_info[0];
4477
4478         /*
4479          * Buffer Packing: Look for PAGE_SIZE or larger zone which has a bufsize
4480          * large enough for the max payload and cluster metadata.  Otherwise
4481          * settle for the largest bufsize that leaves enough room in the cluster
4482          * for metadata.
4483          *
4484          * Without buffer packing: Look for the smallest zone which has a
4485          * bufsize large enough for the max payload.  Settle for the largest
4486          * bufsize available if there's nothing big enough for max payload.
4487          */
4488         spare_needed = fl->flags & FL_BUF_PACKING ? CL_METADATA_SIZE : 0;
4489         swz = &sc->sge.sw_zone_info[0];
4490         hwidx = -1;
4491         for (zidx = 0; zidx < SW_ZONE_SIZES; zidx++, swz++) {
4492                 if (swz->size > largest_rx_cluster) {
4493                         if (__predict_true(hwidx != -1))
4494                                 break;
4495
4496                         /*
4497                          * This is a misconfiguration.  largest_rx_cluster is
4498                          * preventing us from finding a refill source.  See
4499                          * dev.t5nex.<n>.buffer_sizes to figure out why.
4500                          */
4501                         device_printf(sc->dev, "largest_rx_cluster=%u leaves no"
4502                             " refill source for fl %p (dma %u).  Ignored.\n",
4503                             largest_rx_cluster, fl, maxp);
4504                 }
4505                 for (idx = swz->head_hwidx; idx != -1; idx = hwb->next) {
4506                         hwb = &hwb_list[idx];
4507                         spare = swz->size - hwb->size;
4508                         if (spare < spare_needed)
4509                                 continue;
4510
4511                         hwidx = idx;            /* best option so far */
4512                         if (hwb->size >= maxp) {
4513
4514                                 if ((fl->flags & FL_BUF_PACKING) == 0)
4515                                         goto done; /* stop looking (not packing) */
4516
4517                                 if (swz->size >= safest_rx_cluster)
4518                                         goto done; /* stop looking (packing) */
4519                         }
4520                         break;          /* keep looking, next zone */
4521                 }
4522         }
4523 done:
4524         /* A usable hwidx has been located. */
4525         MPASS(hwidx != -1);
4526         hwb = &hwb_list[hwidx];
4527         zidx = hwb->zidx;
4528         swz = &sc->sge.sw_zone_info[zidx];
4529         region1 = 0;
4530         region3 = swz->size - hwb->size;
4531
4532         /*
4533          * Stay within this zone and see if there is a better match when mbuf
4534          * inlining is allowed.  Remember that the hwidx's are sorted in
4535          * decreasing order of size (so in increasing order of spare area).
4536          */
4537         for (idx = hwidx; idx != -1; idx = hwb->next) {
4538                 hwb = &hwb_list[idx];
4539                 spare = swz->size - hwb->size;
4540
4541                 if (allow_mbufs_in_cluster == 0 || hwb->size < maxp)
4542                         break;
4543
4544                 /*
4545                  * Do not inline mbufs if doing so would violate the pad/pack
4546                  * boundary alignment requirement.
4547                  */
4548                 if (fl_pad && (MSIZE % sc->sge.pad_boundary) != 0)
4549                         continue;
4550                 if (fl->flags & FL_BUF_PACKING &&
4551                     (MSIZE % sc->sge.pack_boundary) != 0)
4552                         continue;
4553
4554                 if (spare < CL_METADATA_SIZE + MSIZE)
4555                         continue;
4556                 n = (spare - CL_METADATA_SIZE) / MSIZE;
4557                 if (n > howmany(hwb->size, maxp))
4558                         break;
4559
4560                 hwidx = idx;
4561                 if (fl->flags & FL_BUF_PACKING) {
4562                         region1 = n * MSIZE;
4563                         region3 = spare - region1;
4564                 } else {
4565                         region1 = MSIZE;
4566                         region3 = spare - region1;
4567                         break;
4568                 }
4569         }
4570
4571         KASSERT(zidx >= 0 && zidx < SW_ZONE_SIZES,
4572             ("%s: bad zone %d for fl %p, maxp %d", __func__, zidx, fl, maxp));
4573         KASSERT(hwidx >= 0 && hwidx <= SGE_FLBUF_SIZES,
4574             ("%s: bad hwidx %d for fl %p, maxp %d", __func__, hwidx, fl, maxp));
4575         KASSERT(region1 + sc->sge.hw_buf_info[hwidx].size + region3 ==
4576             sc->sge.sw_zone_info[zidx].size,
4577             ("%s: bad buffer layout for fl %p, maxp %d. "
4578                 "cl %d; r1 %d, payload %d, r3 %d", __func__, fl, maxp,
4579                 sc->sge.sw_zone_info[zidx].size, region1,
4580                 sc->sge.hw_buf_info[hwidx].size, region3));
4581         if (fl->flags & FL_BUF_PACKING || region1 > 0) {
4582                 KASSERT(region3 >= CL_METADATA_SIZE,
4583                     ("%s: no room for metadata.  fl %p, maxp %d; "
4584                     "cl %d; r1 %d, payload %d, r3 %d", __func__, fl, maxp,
4585                     sc->sge.sw_zone_info[zidx].size, region1,
4586                     sc->sge.hw_buf_info[hwidx].size, region3));
4587                 KASSERT(region1 % MSIZE == 0,
4588                     ("%s: bad mbuf region for fl %p, maxp %d. "
4589                     "cl %d; r1 %d, payload %d, r3 %d", __func__, fl, maxp,
4590                     sc->sge.sw_zone_info[zidx].size, region1,
4591                     sc->sge.hw_buf_info[hwidx].size, region3));
4592         }
4593
4594         fl->cll_def.zidx = zidx;
4595         fl->cll_def.hwidx = hwidx;
4596         fl->cll_def.region1 = region1;
4597         fl->cll_def.region3 = region3;
4598 }
4599
4600 static void
4601 find_safe_refill_source(struct adapter *sc, struct sge_fl *fl)
4602 {
4603         struct sge *s = &sc->sge;
4604         struct hw_buf_info *hwb;
4605         struct sw_zone_info *swz;
4606         int spare;
4607         int8_t hwidx;
4608
4609         if (fl->flags & FL_BUF_PACKING)
4610                 hwidx = s->safe_hwidx2; /* with room for metadata */
4611         else if (allow_mbufs_in_cluster && s->safe_hwidx2 != -1) {
4612                 hwidx = s->safe_hwidx2;
4613                 hwb = &s->hw_buf_info[hwidx];
4614                 swz = &s->sw_zone_info[hwb->zidx];
4615                 spare = swz->size - hwb->size;
4616
4617                 /* no good if there isn't room for an mbuf as well */
4618                 if (spare < CL_METADATA_SIZE + MSIZE)
4619                         hwidx = s->safe_hwidx1;
4620         } else
4621                 hwidx = s->safe_hwidx1;
4622
4623         if (hwidx == -1) {
4624                 /* No fallback source */
4625                 fl->cll_alt.hwidx = -1;
4626                 fl->cll_alt.zidx = -1;
4627
4628                 return;
4629         }
4630
4631         hwb = &s->hw_buf_info[hwidx];
4632         swz = &s->sw_zone_info[hwb->zidx];
4633         spare = swz->size - hwb->size;
4634         fl->cll_alt.hwidx = hwidx;
4635         fl->cll_alt.zidx = hwb->zidx;
4636         if (allow_mbufs_in_cluster &&
4637             (fl_pad == 0 || (MSIZE % sc->sge.pad_boundary) == 0))
4638                 fl->cll_alt.region1 = ((spare - CL_METADATA_SIZE) / MSIZE) * MSIZE;
4639         else
4640                 fl->cll_alt.region1 = 0;
4641         fl->cll_alt.region3 = spare - fl->cll_alt.region1;
4642 }
4643
4644 static void
4645 add_fl_to_sfl(struct adapter *sc, struct sge_fl *fl)
4646 {
4647         mtx_lock(&sc->sfl_lock);
4648         FL_LOCK(fl);
4649         if ((fl->flags & FL_DOOMED) == 0) {
4650                 fl->flags |= FL_STARVING;
4651                 TAILQ_INSERT_TAIL(&sc->sfl, fl, link);
4652                 callout_reset(&sc->sfl_callout, hz / 5, refill_sfl, sc);
4653         }
4654         FL_UNLOCK(fl);
4655         mtx_unlock(&sc->sfl_lock);
4656 }
4657
4658 static void
4659 handle_wrq_egr_update(struct adapter *sc, struct sge_eq *eq)
4660 {
4661         struct sge_wrq *wrq = (void *)eq;
4662
4663         atomic_readandclear_int(&eq->equiq);
4664         taskqueue_enqueue(sc->tq[eq->tx_chan], &wrq->wrq_tx_task);
4665 }
4666
4667 static void
4668 handle_eth_egr_update(struct adapter *sc, struct sge_eq *eq)
4669 {
4670         struct sge_txq *txq = (void *)eq;
4671
4672         MPASS((eq->flags & EQ_TYPEMASK) == EQ_ETH);
4673
4674         atomic_readandclear_int(&eq->equiq);
4675         mp_ring_check_drainage(txq->r, 0);
4676         taskqueue_enqueue(sc->tq[eq->tx_chan], &txq->tx_reclaim_task);
4677 }
4678
4679 static int
4680 handle_sge_egr_update(struct sge_iq *iq, const struct rss_header *rss,
4681     struct mbuf *m)
4682 {
4683         const struct cpl_sge_egr_update *cpl = (const void *)(rss + 1);
4684         unsigned int qid = G_EGR_QID(ntohl(cpl->opcode_qid));
4685         struct adapter *sc = iq->adapter;
4686         struct sge *s = &sc->sge;
4687         struct sge_eq *eq;
4688         static void (*h[])(struct adapter *, struct sge_eq *) = {NULL,
4689                 &handle_wrq_egr_update, &handle_eth_egr_update,
4690                 &handle_wrq_egr_update};
4691
4692         KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
4693             rss->opcode));
4694
4695         eq = s->eqmap[qid - s->eq_start];
4696         (*h[eq->flags & EQ_TYPEMASK])(sc, eq);
4697
4698         return (0);
4699 }
4700
4701 /* handle_fw_msg works for both fw4_msg and fw6_msg because this is valid */
4702 CTASSERT(offsetof(struct cpl_fw4_msg, data) == \
4703     offsetof(struct cpl_fw6_msg, data));
4704
4705 static int
4706 handle_fw_msg(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
4707 {
4708         struct adapter *sc = iq->adapter;
4709         const struct cpl_fw6_msg *cpl = (const void *)(rss + 1);
4710
4711         KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
4712             rss->opcode));
4713
4714         if (cpl->type == FW_TYPE_RSSCPL || cpl->type == FW6_TYPE_RSSCPL) {
4715                 const struct rss_header *rss2;
4716
4717                 rss2 = (const struct rss_header *)&cpl->data[0];
4718                 return (sc->cpl_handler[rss2->opcode](iq, rss2, m));
4719         }
4720
4721         return (sc->fw_msg_handler[cpl->type](sc, &cpl->data[0]));
4722 }
4723
4724 static int
4725 sysctl_uint16(SYSCTL_HANDLER_ARGS)
4726 {
4727         uint16_t *id = arg1;
4728         int i = *id;
4729
4730         return sysctl_handle_int(oidp, &i, 0, req);
4731 }
4732
4733 static int
4734 sysctl_bufsizes(SYSCTL_HANDLER_ARGS)
4735 {
4736         struct sge *s = arg1;
4737         struct hw_buf_info *hwb = &s->hw_buf_info[0];
4738         struct sw_zone_info *swz = &s->sw_zone_info[0];
4739         int i, rc;
4740         struct sbuf sb;
4741         char c;
4742
4743         sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
4744         for (i = 0; i < SGE_FLBUF_SIZES; i++, hwb++) {
4745                 if (hwb->zidx >= 0 && swz[hwb->zidx].size <= largest_rx_cluster)
4746                         c = '*';
4747                 else
4748                         c = '\0';
4749
4750                 sbuf_printf(&sb, "%u%c ", hwb->size, c);
4751         }
4752         sbuf_trim(&sb);
4753         sbuf_finish(&sb);
4754         rc = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
4755         sbuf_delete(&sb);
4756         return (rc);
4757 }