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