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