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