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