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