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