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