]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/t4_sge.c
- Updated TOE support in the kernel.
[FreeBSD/FreeBSD.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
33 #include <sys/types.h>
34 #include <sys/mbuf.h>
35 #include <sys/socket.h>
36 #include <sys/kernel.h>
37 #include <sys/kdb.h>
38 #include <sys/malloc.h>
39 #include <sys/queue.h>
40 #include <sys/taskqueue.h>
41 #include <sys/sysctl.h>
42 #include <sys/smp.h>
43 #include <net/bpf.h>
44 #include <net/ethernet.h>
45 #include <net/if.h>
46 #include <net/if_vlan_var.h>
47 #include <netinet/in.h>
48 #include <netinet/ip.h>
49 #include <netinet/tcp.h>
50
51 #include "common/common.h"
52 #include "common/t4_regs.h"
53 #include "common/t4_regs_values.h"
54 #include "common/t4_msg.h"
55
56 struct fl_buf_info {
57         int size;
58         int type;
59         uma_zone_t zone;
60 };
61
62 /* Filled up by t4_sge_modload */
63 static struct fl_buf_info fl_buf_info[FL_BUF_SIZES];
64
65 #define FL_BUF_SIZE(x)  (fl_buf_info[x].size)
66 #define FL_BUF_TYPE(x)  (fl_buf_info[x].type)
67 #define FL_BUF_ZONE(x)  (fl_buf_info[x].zone)
68
69 enum {
70         FL_PKTSHIFT = 2
71 };
72
73 #define FL_ALIGN        min(CACHE_LINE_SIZE, 32)
74 #if CACHE_LINE_SIZE > 64
75 #define SPG_LEN         128
76 #else
77 #define SPG_LEN         64
78 #endif
79
80 /* Used to track coalesced tx work request */
81 struct txpkts {
82         uint64_t *flitp;        /* ptr to flit where next pkt should start */
83         uint8_t npkt;           /* # of packets in this work request */
84         uint8_t nflits;         /* # of flits used by this work request */
85         uint16_t plen;          /* total payload (sum of all packets) */
86 };
87
88 /* A packet's SGL.  This + m_pkthdr has all info needed for tx */
89 struct sgl {
90         int nsegs;              /* # of segments in the SGL, 0 means imm. tx */
91         int nflits;             /* # of flits needed for the SGL */
92         bus_dma_segment_t seg[TX_SGL_SEGS];
93 };
94
95 static int service_iq(struct sge_iq *, int);
96 static struct mbuf *get_fl_payload(struct adapter *, struct sge_fl *, uint32_t,
97     int *);
98 static int t4_eth_rx(struct sge_iq *, const struct rss_header *, struct mbuf *);
99 static inline void init_iq(struct sge_iq *, struct adapter *, int, int, int,
100     int, char *);
101 static inline void init_fl(struct sge_fl *, int, int, char *);
102 static inline void init_eq(struct sge_eq *, int, int, uint8_t, uint16_t,
103     char *);
104 static int alloc_ring(struct adapter *, size_t, bus_dma_tag_t *, bus_dmamap_t *,
105     bus_addr_t *, void **);
106 static int free_ring(struct adapter *, bus_dma_tag_t, bus_dmamap_t, bus_addr_t,
107     void *);
108 static int alloc_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *,
109     int, int);
110 static int free_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *);
111 static int alloc_fwq(struct adapter *);
112 static int free_fwq(struct adapter *);
113 static int alloc_mgmtq(struct adapter *);
114 static int free_mgmtq(struct adapter *);
115 static int alloc_rxq(struct port_info *, struct sge_rxq *, int, int,
116     struct sysctl_oid *);
117 static int free_rxq(struct port_info *, struct sge_rxq *);
118 #ifdef TCP_OFFLOAD
119 static int alloc_ofld_rxq(struct port_info *, struct sge_ofld_rxq *, int, int,
120     struct sysctl_oid *);
121 static int free_ofld_rxq(struct port_info *, struct sge_ofld_rxq *);
122 #endif
123 static int ctrl_eq_alloc(struct adapter *, struct sge_eq *);
124 static int eth_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
125 #ifdef TCP_OFFLOAD
126 static int ofld_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
127 #endif
128 static int alloc_eq(struct adapter *, struct port_info *, struct sge_eq *);
129 static int free_eq(struct adapter *, struct sge_eq *);
130 static int alloc_wrq(struct adapter *, struct port_info *, struct sge_wrq *,
131     struct sysctl_oid *);
132 static int free_wrq(struct adapter *, struct sge_wrq *);
133 static int alloc_txq(struct port_info *, struct sge_txq *, int,
134     struct sysctl_oid *);
135 static int free_txq(struct port_info *, struct sge_txq *);
136 static void oneseg_dma_callback(void *, bus_dma_segment_t *, int, int);
137 static inline bool is_new_response(const struct sge_iq *, struct rsp_ctrl **);
138 static inline void iq_next(struct sge_iq *);
139 static inline void ring_fl_db(struct adapter *, struct sge_fl *);
140 static int refill_fl(struct adapter *, struct sge_fl *, int);
141 static void refill_sfl(void *);
142 static int alloc_fl_sdesc(struct sge_fl *);
143 static void free_fl_sdesc(struct sge_fl *);
144 static void set_fl_tag_idx(struct sge_fl *, int);
145 static void add_fl_to_sfl(struct adapter *, struct sge_fl *);
146
147 static int get_pkt_sgl(struct sge_txq *, struct mbuf **, struct sgl *, int);
148 static int free_pkt_sgl(struct sge_txq *, struct sgl *);
149 static int write_txpkt_wr(struct port_info *, struct sge_txq *, struct mbuf *,
150     struct sgl *);
151 static int add_to_txpkts(struct port_info *, struct sge_txq *, struct txpkts *,
152     struct mbuf *, struct sgl *);
153 static void write_txpkts_wr(struct sge_txq *, struct txpkts *);
154 static inline void write_ulp_cpl_sgl(struct port_info *, struct sge_txq *,
155     struct txpkts *, struct mbuf *, struct sgl *);
156 static int write_sgl_to_txd(struct sge_eq *, struct sgl *, caddr_t *);
157 static inline void copy_to_txd(struct sge_eq *, caddr_t, caddr_t *, int);
158 static inline void ring_eq_db(struct adapter *, struct sge_eq *);
159 static inline int reclaimable(struct sge_eq *);
160 static int reclaim_tx_descs(struct sge_txq *, int, int);
161 static void write_eqflush_wr(struct sge_eq *);
162 static __be64 get_flit(bus_dma_segment_t *, int, int);
163 static int handle_sge_egr_update(struct sge_iq *, const struct rss_header *,
164     struct mbuf *);
165 static int handle_fw_rpl(struct sge_iq *, const struct rss_header *,
166     struct mbuf *);
167
168 static int sysctl_uint16(SYSCTL_HANDLER_ARGS);
169
170 /*
171  * Called on MOD_LOAD and fills up fl_buf_info[].
172  */
173 void
174 t4_sge_modload(void)
175 {
176         int i;
177         int bufsize[FL_BUF_SIZES] = {
178                 MCLBYTES,
179 #if MJUMPAGESIZE != MCLBYTES
180                 MJUMPAGESIZE,
181 #endif
182                 MJUM9BYTES,
183                 MJUM16BYTES
184         };
185
186         for (i = 0; i < FL_BUF_SIZES; i++) {
187                 FL_BUF_SIZE(i) = bufsize[i];
188                 FL_BUF_TYPE(i) = m_gettype(bufsize[i]);
189                 FL_BUF_ZONE(i) = m_getzone(bufsize[i]);
190         }
191 }
192
193 /**
194  *      t4_sge_init - initialize SGE
195  *      @sc: the adapter
196  *
197  *      Performs SGE initialization needed every time after a chip reset.
198  *      We do not initialize any of the queues here, instead the driver
199  *      top-level must request them individually.
200  */
201 int
202 t4_sge_init(struct adapter *sc)
203 {
204         struct sge *s = &sc->sge;
205         int i, rc = 0;
206         uint32_t ctrl_mask, ctrl_val, hpsize, v;
207
208         ctrl_mask = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE |
209             V_INGPADBOUNDARY(M_INGPADBOUNDARY) |
210             F_EGRSTATUSPAGESIZE;
211         ctrl_val = V_PKTSHIFT(FL_PKTSHIFT) | F_RXPKTCPLMODE |
212             V_INGPADBOUNDARY(ilog2(FL_ALIGN) - 5) |
213             V_EGRSTATUSPAGESIZE(SPG_LEN == 128);
214
215         hpsize = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
216             V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
217             V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
218             V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
219             V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
220             V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
221             V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
222             V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
223
224         if (sc->flags & MASTER_PF) {
225                 int intr_timer[SGE_NTIMERS] = {1, 5, 10, 50, 100, 200};
226                 int intr_pktcount[SGE_NCOUNTERS] = {1, 8, 16, 32}; /* 63 max */
227
228                 t4_set_reg_field(sc, A_SGE_CONTROL, ctrl_mask, ctrl_val);
229                 t4_write_reg(sc, A_SGE_HOST_PAGE_SIZE, hpsize);
230                 for (i = 0; i < FL_BUF_SIZES; i++) {
231                         t4_write_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i),
232                             FL_BUF_SIZE(i));
233                 }
234
235                 t4_write_reg(sc, A_SGE_INGRESS_RX_THRESHOLD,
236                     V_THRESHOLD_0(intr_pktcount[0]) |
237                     V_THRESHOLD_1(intr_pktcount[1]) |
238                     V_THRESHOLD_2(intr_pktcount[2]) |
239                     V_THRESHOLD_3(intr_pktcount[3]));
240
241                 t4_write_reg(sc, A_SGE_TIMER_VALUE_0_AND_1,
242                     V_TIMERVALUE0(us_to_core_ticks(sc, intr_timer[0])) |
243                     V_TIMERVALUE1(us_to_core_ticks(sc, intr_timer[1])));
244                 t4_write_reg(sc, A_SGE_TIMER_VALUE_2_AND_3,
245                     V_TIMERVALUE2(us_to_core_ticks(sc, intr_timer[2])) |
246                     V_TIMERVALUE3(us_to_core_ticks(sc, intr_timer[3])));
247                 t4_write_reg(sc, A_SGE_TIMER_VALUE_4_AND_5,
248                     V_TIMERVALUE4(us_to_core_ticks(sc, intr_timer[4])) |
249                     V_TIMERVALUE5(us_to_core_ticks(sc, intr_timer[5])));
250         }
251
252         v = t4_read_reg(sc, A_SGE_CONTROL);
253         if ((v & ctrl_mask) != ctrl_val) {
254                 device_printf(sc->dev, "invalid SGE_CONTROL(0x%x)\n", v);
255                 rc = EINVAL;
256         }
257
258         v = t4_read_reg(sc, A_SGE_HOST_PAGE_SIZE);
259         if (v != hpsize) {
260                 device_printf(sc->dev, "invalid SGE_HOST_PAGE_SIZE(0x%x)\n", v);
261                 rc = EINVAL;
262         }
263
264         for (i = 0; i < FL_BUF_SIZES; i++) {
265                 v = t4_read_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i));
266                 if (v != FL_BUF_SIZE(i)) {
267                         device_printf(sc->dev,
268                             "invalid SGE_FL_BUFFER_SIZE[%d](0x%x)\n", i, v);
269                         rc = EINVAL;
270                 }
271         }
272
273         v = t4_read_reg(sc, A_SGE_CONM_CTRL);
274         s->fl_starve_threshold = G_EGRTHRESHOLD(v) * 2 + 1;
275
276         v = t4_read_reg(sc, A_SGE_INGRESS_RX_THRESHOLD);
277         sc->sge.counter_val[0] = G_THRESHOLD_0(v);
278         sc->sge.counter_val[1] = G_THRESHOLD_1(v);
279         sc->sge.counter_val[2] = G_THRESHOLD_2(v);
280         sc->sge.counter_val[3] = G_THRESHOLD_3(v);
281
282         v = t4_read_reg(sc, A_SGE_TIMER_VALUE_0_AND_1);
283         sc->sge.timer_val[0] = G_TIMERVALUE0(v) / core_ticks_per_usec(sc);
284         sc->sge.timer_val[1] = G_TIMERVALUE1(v) / core_ticks_per_usec(sc);
285         v = t4_read_reg(sc, A_SGE_TIMER_VALUE_2_AND_3);
286         sc->sge.timer_val[2] = G_TIMERVALUE2(v) / core_ticks_per_usec(sc);
287         sc->sge.timer_val[3] = G_TIMERVALUE3(v) / core_ticks_per_usec(sc);
288         v = t4_read_reg(sc, A_SGE_TIMER_VALUE_4_AND_5);
289         sc->sge.timer_val[4] = G_TIMERVALUE4(v) / core_ticks_per_usec(sc);
290         sc->sge.timer_val[5] = G_TIMERVALUE5(v) / core_ticks_per_usec(sc);
291
292         t4_register_cpl_handler(sc, CPL_FW4_MSG, handle_fw_rpl);
293         t4_register_cpl_handler(sc, CPL_FW6_MSG, handle_fw_rpl);
294         t4_register_cpl_handler(sc, CPL_SGE_EGR_UPDATE, handle_sge_egr_update);
295         t4_register_cpl_handler(sc, CPL_RX_PKT, t4_eth_rx);
296
297         return (rc);
298 }
299
300 int
301 t4_create_dma_tag(struct adapter *sc)
302 {
303         int rc;
304
305         rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), 1, 0,
306             BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE,
307             BUS_SPACE_UNRESTRICTED, BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL,
308             NULL, &sc->dmat);
309         if (rc != 0) {
310                 device_printf(sc->dev,
311                     "failed to create main DMA tag: %d\n", rc);
312         }
313
314         return (rc);
315 }
316
317 int
318 t4_destroy_dma_tag(struct adapter *sc)
319 {
320         if (sc->dmat)
321                 bus_dma_tag_destroy(sc->dmat);
322
323         return (0);
324 }
325
326 /*
327  * Allocate and initialize the firmware event queue and the management queue.
328  *
329  * Returns errno on failure.  Resources allocated up to that point may still be
330  * allocated.  Caller is responsible for cleanup in case this function fails.
331  */
332 int
333 t4_setup_adapter_queues(struct adapter *sc)
334 {
335         int rc;
336
337         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
338
339         sysctl_ctx_init(&sc->ctx);
340         sc->flags |= ADAP_SYSCTL_CTX;
341
342         /*
343          * Firmware event queue
344          */
345         rc = alloc_fwq(sc);
346         if (rc != 0) {
347                 device_printf(sc->dev,
348                     "failed to create firmware event queue: %d\n", rc);
349                 return (rc);
350         }
351
352         /*
353          * Management queue.  This is just a control queue that uses the fwq as
354          * its associated iq.
355          */
356         rc = alloc_mgmtq(sc);
357         if (rc != 0) {
358                 device_printf(sc->dev,
359                     "failed to create management queue: %d\n", rc);
360                 return (rc);
361         }
362
363         return (rc);
364 }
365
366 /*
367  * Idempotent
368  */
369 int
370 t4_teardown_adapter_queues(struct adapter *sc)
371 {
372
373         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
374
375         /* Do this before freeing the queue */
376         if (sc->flags & ADAP_SYSCTL_CTX) {
377                 sysctl_ctx_free(&sc->ctx);
378                 sc->flags &= ~ADAP_SYSCTL_CTX;
379         }
380
381         free_mgmtq(sc);
382         free_fwq(sc);
383
384         return (0);
385 }
386
387 static inline int
388 first_vector(struct port_info *pi)
389 {
390         struct adapter *sc = pi->adapter;
391         int rc = T4_EXTRA_INTR, i;
392
393         if (sc->intr_count == 1)
394                 return (0);
395
396         for_each_port(sc, i) {
397                 if (i == pi->port_id)
398                         break;
399
400 #ifdef TCP_OFFLOAD
401                 if (sc->flags & INTR_DIRECT)
402                         rc += pi->nrxq + pi->nofldrxq;
403                 else
404                         rc += max(pi->nrxq, pi->nofldrxq);
405 #else
406                 /*
407                  * Not compiled with offload support and intr_count > 1.  Only
408                  * NIC queues exist and they'd better be taking direct
409                  * interrupts.
410                  */
411                 KASSERT(sc->flags & INTR_DIRECT,
412                     ("%s: intr_count %d, !INTR_DIRECT", __func__,
413                     sc->intr_count));
414
415                 rc += pi->nrxq;
416 #endif
417         }
418
419         return (rc);
420 }
421
422 /*
423  * Given an arbitrary "index," come up with an iq that can be used by other
424  * queues (of this port) for interrupt forwarding, SGE egress updates, etc.
425  * The iq returned is guaranteed to be something that takes direct interrupts.
426  */
427 static struct sge_iq *
428 port_intr_iq(struct port_info *pi, int idx)
429 {
430         struct adapter *sc = pi->adapter;
431         struct sge *s = &sc->sge;
432         struct sge_iq *iq = NULL;
433
434         if (sc->intr_count == 1)
435                 return (&sc->sge.fwq);
436
437 #ifdef TCP_OFFLOAD
438         if (sc->flags & INTR_DIRECT) {
439                 idx %= pi->nrxq + pi->nofldrxq;
440                 
441                 if (idx >= pi->nrxq) {
442                         idx -= pi->nrxq;
443                         iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
444                 } else
445                         iq = &s->rxq[pi->first_rxq + idx].iq;
446
447         } else {
448                 idx %= max(pi->nrxq, pi->nofldrxq);
449
450                 if (pi->nrxq >= pi->nofldrxq)
451                         iq = &s->rxq[pi->first_rxq + idx].iq;
452                 else
453                         iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
454         }
455 #else
456         /*
457          * Not compiled with offload support and intr_count > 1.  Only NIC
458          * queues exist and they'd better be taking direct interrupts.
459          */
460         KASSERT(sc->flags & INTR_DIRECT,
461             ("%s: intr_count %d, !INTR_DIRECT", __func__, sc->intr_count));
462
463         idx %= pi->nrxq;
464         iq = &s->rxq[pi->first_rxq + idx].iq;
465 #endif
466
467         KASSERT(iq->flags & IQ_INTR, ("%s: EDOOFUS", __func__));
468         return (iq);
469 }
470
471 int
472 t4_setup_port_queues(struct port_info *pi)
473 {
474         int rc = 0, i, j, intr_idx, iqid;
475         struct sge_rxq *rxq;
476         struct sge_txq *txq;
477         struct sge_wrq *ctrlq;
478 #ifdef TCP_OFFLOAD
479         struct sge_ofld_rxq *ofld_rxq;
480         struct sge_wrq *ofld_txq;
481         struct sysctl_oid *oid2 = NULL;
482 #endif
483         char name[16];
484         struct adapter *sc = pi->adapter;
485         struct sysctl_oid *oid = device_get_sysctl_tree(pi->dev);
486         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
487
488         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "rxq", CTLFLAG_RD,
489             NULL, "rx queues");
490
491 #ifdef TCP_OFFLOAD
492         if (is_offload(sc)) {
493                 oid2 = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_rxq",
494                     CTLFLAG_RD, NULL,
495                     "rx queues for offloaded TCP connections");
496         }
497 #endif
498
499         /* Interrupt vector to start from (when using multiple vectors) */
500         intr_idx = first_vector(pi);
501
502         /*
503          * First pass over all rx queues (NIC and TOE):
504          * a) initialize iq and fl
505          * b) allocate queue iff it will take direct interrupts.
506          */
507         for_each_rxq(pi, i, rxq) {
508
509                 snprintf(name, sizeof(name), "%s rxq%d-iq",
510                     device_get_nameunit(pi->dev), i);
511                 init_iq(&rxq->iq, sc, pi->tmr_idx, pi->pktc_idx, pi->qsize_rxq,
512                     RX_IQ_ESIZE, name);
513
514                 snprintf(name, sizeof(name), "%s rxq%d-fl",
515                     device_get_nameunit(pi->dev), i);
516                 init_fl(&rxq->fl, pi->qsize_rxq / 8, pi->ifp->if_mtu, name);
517
518                 if (sc->flags & INTR_DIRECT
519 #ifdef TCP_OFFLOAD
520                     || (sc->intr_count > 1 && pi->nrxq >= pi->nofldrxq)
521 #endif
522                    ) {
523                         rxq->iq.flags |= IQ_INTR;
524                         rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
525                         if (rc != 0)
526                                 goto done;
527                         intr_idx++;
528                 }
529         }
530
531 #ifdef TCP_OFFLOAD
532         for_each_ofld_rxq(pi, i, ofld_rxq) {
533
534                 snprintf(name, sizeof(name), "%s ofld_rxq%d-iq",
535                     device_get_nameunit(pi->dev), i);
536                 init_iq(&ofld_rxq->iq, sc, pi->tmr_idx, pi->pktc_idx,
537                     pi->qsize_rxq, RX_IQ_ESIZE, name);
538
539                 snprintf(name, sizeof(name), "%s ofld_rxq%d-fl",
540                     device_get_nameunit(pi->dev), i);
541                 init_fl(&ofld_rxq->fl, pi->qsize_rxq / 8, MJUM16BYTES, name);
542
543                 if (sc->flags & INTR_DIRECT ||
544                     (sc->intr_count > 1 && pi->nofldrxq > pi->nrxq)) {
545                         ofld_rxq->iq.flags |= IQ_INTR;
546                         rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
547                         if (rc != 0)
548                                 goto done;
549                         intr_idx++;
550                 }
551         }
552 #endif
553
554         /*
555          * Second pass over all rx queues (NIC and TOE).  The queues forwarding
556          * their interrupts are allocated now.
557          */
558         j = 0;
559         for_each_rxq(pi, i, rxq) {
560                 if (rxq->iq.flags & IQ_INTR)
561                         continue;
562
563                 intr_idx = port_intr_iq(pi, j)->abs_id;
564
565                 rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
566                 if (rc != 0)
567                         goto done;
568                 j++;
569         }
570
571 #ifdef TCP_OFFLOAD
572         for_each_ofld_rxq(pi, i, ofld_rxq) {
573                 if (ofld_rxq->iq.flags & IQ_INTR)
574                         continue;
575
576                 intr_idx = port_intr_iq(pi, j)->abs_id;
577
578                 rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
579                 if (rc != 0)
580                         goto done;
581                 j++;
582         }
583 #endif
584
585         /*
586          * Now the tx queues.  Only one pass needed.
587          */
588         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "txq", CTLFLAG_RD,
589             NULL, "tx queues");
590         j = 0;
591         for_each_txq(pi, i, txq) {
592                 uint16_t iqid;
593
594                 iqid = port_intr_iq(pi, j)->cntxt_id;
595
596                 snprintf(name, sizeof(name), "%s txq%d",
597                     device_get_nameunit(pi->dev), i);
598                 init_eq(&txq->eq, EQ_ETH, pi->qsize_txq, pi->tx_chan, iqid,
599                     name);
600
601                 rc = alloc_txq(pi, txq, i, oid);
602                 if (rc != 0)
603                         goto done;
604                 j++;
605         }
606
607 #ifdef TCP_OFFLOAD
608         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_txq",
609             CTLFLAG_RD, NULL, "tx queues for offloaded TCP connections");
610         for_each_ofld_txq(pi, i, ofld_txq) {
611                 uint16_t iqid;
612
613                 iqid = port_intr_iq(pi, j)->cntxt_id;
614
615                 snprintf(name, sizeof(name), "%s ofld_txq%d",
616                     device_get_nameunit(pi->dev), i);
617                 init_eq(&ofld_txq->eq, EQ_OFLD, pi->qsize_txq, pi->tx_chan,
618                     iqid, name);
619
620                 snprintf(name, sizeof(name), "%d", i);
621                 oid2 = SYSCTL_ADD_NODE(&pi->ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
622                     name, CTLFLAG_RD, NULL, "offload tx queue");
623
624                 rc = alloc_wrq(sc, pi, ofld_txq, oid2);
625                 if (rc != 0)
626                         goto done;
627                 j++;
628         }
629 #endif
630
631         /*
632          * Finally, the control queue.
633          */
634         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ctrlq", CTLFLAG_RD,
635             NULL, "ctrl queue");
636         ctrlq = &sc->sge.ctrlq[pi->port_id];
637         iqid = port_intr_iq(pi, 0)->cntxt_id;
638         snprintf(name, sizeof(name), "%s ctrlq", device_get_nameunit(pi->dev));
639         init_eq(&ctrlq->eq, EQ_CTRL, CTRL_EQ_QSIZE, pi->tx_chan, iqid, name);
640         rc = alloc_wrq(sc, pi, ctrlq, oid);
641
642 done:
643         if (rc)
644                 t4_teardown_port_queues(pi);
645
646         return (rc);
647 }
648
649 /*
650  * Idempotent
651  */
652 int
653 t4_teardown_port_queues(struct port_info *pi)
654 {
655         int i;
656         struct adapter *sc = pi->adapter;
657         struct sge_rxq *rxq;
658         struct sge_txq *txq;
659 #ifdef TCP_OFFLOAD
660         struct sge_ofld_rxq *ofld_rxq;
661         struct sge_wrq *ofld_txq;
662 #endif
663
664         /* Do this before freeing the queues */
665         if (pi->flags & PORT_SYSCTL_CTX) {
666                 sysctl_ctx_free(&pi->ctx);
667                 pi->flags &= ~PORT_SYSCTL_CTX;
668         }
669
670         /*
671          * Take down all the tx queues first, as they reference the rx queues
672          * (for egress updates, etc.).
673          */
674
675         free_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
676
677         for_each_txq(pi, i, txq) {
678                 free_txq(pi, txq);
679         }
680
681 #ifdef TCP_OFFLOAD
682         for_each_ofld_txq(pi, i, ofld_txq) {
683                 free_wrq(sc, ofld_txq);
684         }
685 #endif
686
687         /*
688          * Then take down the rx queues that forward their interrupts, as they
689          * reference other rx queues.
690          */
691
692         for_each_rxq(pi, i, rxq) {
693                 if ((rxq->iq.flags & IQ_INTR) == 0)
694                         free_rxq(pi, rxq);
695         }
696
697 #ifdef TCP_OFFLOAD
698         for_each_ofld_rxq(pi, i, ofld_rxq) {
699                 if ((ofld_rxq->iq.flags & IQ_INTR) == 0)
700                         free_ofld_rxq(pi, ofld_rxq);
701         }
702 #endif
703
704         /*
705          * Then take down the rx queues that take direct interrupts.
706          */
707
708         for_each_rxq(pi, i, rxq) {
709                 if (rxq->iq.flags & IQ_INTR)
710                         free_rxq(pi, rxq);
711         }
712
713 #ifdef TCP_OFFLOAD
714         for_each_ofld_rxq(pi, i, ofld_rxq) {
715                 if (ofld_rxq->iq.flags & IQ_INTR)
716                         free_ofld_rxq(pi, ofld_rxq);
717         }
718 #endif
719
720         return (0);
721 }
722
723 /*
724  * Deals with errors and the firmware event queue.  All data rx queues forward
725  * their interrupt to the firmware event queue.
726  */
727 void
728 t4_intr_all(void *arg)
729 {
730         struct adapter *sc = arg;
731         struct sge_iq *fwq = &sc->sge.fwq;
732
733         t4_intr_err(arg);
734         if (atomic_cmpset_int(&fwq->state, IQS_IDLE, IQS_BUSY)) {
735                 service_iq(fwq, 0);
736                 atomic_cmpset_int(&fwq->state, IQS_BUSY, IQS_IDLE);
737         }
738 }
739
740 /* Deals with error interrupts */
741 void
742 t4_intr_err(void *arg)
743 {
744         struct adapter *sc = arg;
745
746         t4_write_reg(sc, MYPF_REG(A_PCIE_PF_CLI), 0);
747         t4_slow_intr_handler(sc);
748 }
749
750 void
751 t4_intr_evt(void *arg)
752 {
753         struct sge_iq *iq = arg;
754
755         if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
756                 service_iq(iq, 0);
757                 atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
758         }
759 }
760
761 void
762 t4_intr(void *arg)
763 {
764         struct sge_iq *iq = arg;
765
766         if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
767                 service_iq(iq, 0);
768                 atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
769         }
770 }
771
772 /*
773  * Deals with anything and everything on the given ingress queue.
774  */
775 static int
776 service_iq(struct sge_iq *iq, int budget)
777 {
778         struct sge_iq *q;
779         struct sge_rxq *rxq = iq_to_rxq(iq);    /* Use iff iq is part of rxq */
780         struct sge_fl *fl = &rxq->fl;           /* Use iff IQ_HAS_FL */
781         struct adapter *sc = iq->adapter;
782         struct rsp_ctrl *ctrl;
783         const struct rss_header *rss;
784         int ndescs = 0, limit, fl_bufs_used = 0;
785         int rsp_type;
786         uint32_t lq;
787         struct mbuf *m0;
788         STAILQ_HEAD(, sge_iq) iql = STAILQ_HEAD_INITIALIZER(iql);
789
790         limit = budget ? budget : iq->qsize / 8;
791
792         KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
793
794         /*
795          * We always come back and check the descriptor ring for new indirect
796          * interrupts and other responses after running a single handler.
797          */
798         for (;;) {
799                 while (is_new_response(iq, &ctrl)) {
800
801                         rmb();
802
803                         m0 = NULL;
804                         rsp_type = G_RSPD_TYPE(ctrl->u.type_gen);
805                         lq = be32toh(ctrl->pldbuflen_qid);
806                         rss = (const void *)iq->cdesc;
807
808                         switch (rsp_type) {
809                         case X_RSPD_TYPE_FLBUF:
810
811                                 KASSERT(iq->flags & IQ_HAS_FL,
812                                     ("%s: data for an iq (%p) with no freelist",
813                                     __func__, iq));
814
815                                 m0 = get_fl_payload(sc, fl, lq, &fl_bufs_used);
816 #ifdef T4_PKT_TIMESTAMP
817                                 /*
818                                  * 60 bit timestamp for the payload is
819                                  * *(uint64_t *)m0->m_pktdat.  Note that it is
820                                  * in the leading free-space in the mbuf.  The
821                                  * kernel can clobber it during a pullup,
822                                  * m_copymdata, etc.  You need to make sure that
823                                  * the mbuf reaches you unmolested if you care
824                                  * about the timestamp.
825                                  */
826                                 *(uint64_t *)m0->m_pktdat =
827                                     be64toh(ctrl->u.last_flit) &
828                                     0xfffffffffffffff;
829 #endif
830
831                                 /* fall through */
832
833                         case X_RSPD_TYPE_CPL:
834                                 KASSERT(rss->opcode < NUM_CPL_CMDS,
835                                     ("%s: bad opcode %02x.", __func__,
836                                     rss->opcode));
837                                 sc->cpl_handler[rss->opcode](iq, rss, m0);
838                                 break;
839
840                         case X_RSPD_TYPE_INTR:
841
842                                 /*
843                                  * Interrupts should be forwarded only to queues
844                                  * that are not forwarding their interrupts.
845                                  * This means service_iq can recurse but only 1
846                                  * level deep.
847                                  */
848                                 KASSERT(budget == 0,
849                                     ("%s: budget %u, rsp_type %u", __func__,
850                                     budget, rsp_type));
851
852                                 q = sc->sge.iqmap[lq - sc->sge.iq_start];
853                                 if (atomic_cmpset_int(&q->state, IQS_IDLE,
854                                     IQS_BUSY)) {
855                                         if (service_iq(q, q->qsize / 8) == 0) {
856                                                 atomic_cmpset_int(&q->state,
857                                                     IQS_BUSY, IQS_IDLE);
858                                         } else {
859                                                 STAILQ_INSERT_TAIL(&iql, q,
860                                                     link);
861                                         }
862                                 }
863                                 break;
864
865                         default:
866                                 sc->an_handler(iq, ctrl);
867                                 break;
868                         }
869
870                         iq_next(iq);
871                         if (++ndescs == limit) {
872                                 t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS),
873                                     V_CIDXINC(ndescs) |
874                                     V_INGRESSQID(iq->cntxt_id) |
875                                     V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));
876                                 ndescs = 0;
877
878                                 if (fl_bufs_used > 0) {
879                                         FL_LOCK(fl);
880                                         fl->needed += fl_bufs_used;
881                                         refill_fl(sc, fl, fl->cap / 8);
882                                         FL_UNLOCK(fl);
883                                         fl_bufs_used = 0;
884                                 }
885
886                                 if (budget)
887                                         return (EINPROGRESS);
888                         }
889                 }
890
891                 if (STAILQ_EMPTY(&iql))
892                         break;
893
894                 /*
895                  * Process the head only, and send it to the back of the list if
896                  * it's still not done.
897                  */
898                 q = STAILQ_FIRST(&iql);
899                 STAILQ_REMOVE_HEAD(&iql, link);
900                 if (service_iq(q, q->qsize / 8) == 0)
901                         atomic_cmpset_int(&q->state, IQS_BUSY, IQS_IDLE);
902                 else
903                         STAILQ_INSERT_TAIL(&iql, q, link);
904         }
905
906 #ifdef INET
907         if (iq->flags & IQ_LRO_ENABLED) {
908                 struct lro_ctrl *lro = &rxq->lro;
909                 struct lro_entry *l;
910
911                 while (!SLIST_EMPTY(&lro->lro_active)) {
912                         l = SLIST_FIRST(&lro->lro_active);
913                         SLIST_REMOVE_HEAD(&lro->lro_active, next);
914                         tcp_lro_flush(lro, l);
915                 }
916         }
917 #endif
918
919         t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_CIDXINC(ndescs) |
920             V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));
921
922         if (iq->flags & IQ_HAS_FL) {
923                 int starved;
924
925                 FL_LOCK(fl);
926                 fl->needed += fl_bufs_used;
927                 starved = refill_fl(sc, fl, fl->cap / 4);
928                 FL_UNLOCK(fl);
929                 if (__predict_false(starved != 0))
930                         add_fl_to_sfl(sc, fl);
931         }
932
933         return (0);
934 }
935
936
937 #ifdef T4_PKT_TIMESTAMP
938 #define RX_COPY_THRESHOLD (MINCLSIZE - 8)
939 #else
940 #define RX_COPY_THRESHOLD MINCLSIZE
941 #endif
942
943 static struct mbuf *
944 get_fl_payload(struct adapter *sc, struct sge_fl *fl, uint32_t len_newbuf,
945     int *fl_bufs_used)
946 {
947         struct mbuf *m0, *m;
948         struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
949         unsigned int nbuf, len;
950
951         /*
952          * No assertion for the fl lock because we don't need it.  This routine
953          * is called only from the rx interrupt handler and it only updates
954          * fl->cidx.  (Contrast that with fl->pidx/fl->needed which could be
955          * updated in the rx interrupt handler or the starvation helper routine.
956          * That's why code that manipulates fl->pidx/fl->needed needs the fl
957          * lock but this routine does not).
958          */
959
960         if (__predict_false((len_newbuf & F_RSPD_NEWBUF) == 0))
961                 panic("%s: cannot handle packed frames", __func__);
962         len = G_RSPD_LEN(len_newbuf);
963
964         m0 = sd->m;
965         sd->m = NULL;   /* consumed */
966
967         bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map, BUS_DMASYNC_POSTREAD);
968         m_init(m0, NULL, 0, M_NOWAIT, MT_DATA, M_PKTHDR);
969 #ifdef T4_PKT_TIMESTAMP
970         /* Leave room for a timestamp */
971         m0->m_data += 8;
972 #endif
973
974         if (len < RX_COPY_THRESHOLD) {
975                 /* copy data to mbuf, buffer will be recycled */
976                 bcopy(sd->cl, mtod(m0, caddr_t), len);
977                 m0->m_len = len;
978         } else {
979                 bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
980                 m_cljset(m0, sd->cl, FL_BUF_TYPE(sd->tag_idx));
981                 sd->cl = NULL;  /* consumed */
982                 m0->m_len = min(len, FL_BUF_SIZE(sd->tag_idx));
983         }
984         m0->m_pkthdr.len = len;
985
986         sd++;
987         if (__predict_false(++fl->cidx == fl->cap)) {
988                 sd = fl->sdesc;
989                 fl->cidx = 0;
990         }
991
992         m = m0;
993         len -= m->m_len;
994         nbuf = 1;       /* # of fl buffers used */
995
996         while (len > 0) {
997                 m->m_next = sd->m;
998                 sd->m = NULL;   /* consumed */
999                 m = m->m_next;
1000
1001                 bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map,
1002                     BUS_DMASYNC_POSTREAD);
1003
1004                 m_init(m, NULL, 0, M_NOWAIT, MT_DATA, 0);
1005                 if (len <= MLEN) {
1006                         bcopy(sd->cl, mtod(m, caddr_t), len);
1007                         m->m_len = len;
1008                 } else {
1009                         bus_dmamap_unload(fl->tag[sd->tag_idx],
1010                             sd->map);
1011                         m_cljset(m, sd->cl, FL_BUF_TYPE(sd->tag_idx));
1012                         sd->cl = NULL;  /* consumed */
1013                         m->m_len = min(len, FL_BUF_SIZE(sd->tag_idx));
1014                 }
1015
1016                 sd++;
1017                 if (__predict_false(++fl->cidx == fl->cap)) {
1018                         sd = fl->sdesc;
1019                         fl->cidx = 0;
1020                 }
1021
1022                 len -= m->m_len;
1023                 nbuf++;
1024         }
1025
1026         (*fl_bufs_used) += nbuf;
1027
1028         return (m0);
1029 }
1030
1031 static int
1032 t4_eth_rx(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m0)
1033 {
1034         struct sge_rxq *rxq = (void *)iq;
1035         struct ifnet *ifp = rxq->ifp;
1036         const struct cpl_rx_pkt *cpl = (const void *)(rss + 1);
1037 #ifdef INET
1038         struct lro_ctrl *lro = &rxq->lro;
1039 #endif
1040
1041         KASSERT(m0 != NULL, ("%s: no payload with opcode %02x", __func__,
1042             rss->opcode));
1043
1044         m0->m_pkthdr.len -= FL_PKTSHIFT;
1045         m0->m_len -= FL_PKTSHIFT;
1046         m0->m_data += FL_PKTSHIFT;
1047
1048         m0->m_pkthdr.rcvif = ifp;
1049         m0->m_flags |= M_FLOWID;
1050         m0->m_pkthdr.flowid = rss->hash_val;
1051
1052         if (cpl->csum_calc && !cpl->err_vec &&
1053             ifp->if_capenable & IFCAP_RXCSUM) {
1054                 m0->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
1055                     CSUM_IP_VALID | CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1056                 if (cpl->ip_frag)
1057                         m0->m_pkthdr.csum_data = be16toh(cpl->csum);
1058                 else
1059                         m0->m_pkthdr.csum_data = 0xffff;
1060                 rxq->rxcsum++;
1061         }
1062
1063         if (cpl->vlan_ex) {
1064                 m0->m_pkthdr.ether_vtag = be16toh(cpl->vlan);
1065                 m0->m_flags |= M_VLANTAG;
1066                 rxq->vlan_extraction++;
1067         }
1068
1069 #ifdef INET
1070         if (cpl->l2info & htobe32(F_RXF_LRO) &&
1071             iq->flags & IQ_LRO_ENABLED &&
1072             tcp_lro_rx(lro, m0, 0) == 0) {
1073                 /* queued for LRO */
1074         } else
1075 #endif
1076         ifp->if_input(ifp, m0);
1077
1078         return (0);
1079 }
1080
1081 /*
1082  * Doesn't fail.  Holds on to work requests it can't send right away.
1083  */
1084 void
1085 t4_wrq_tx_locked(struct adapter *sc, struct sge_wrq *wrq, struct wrqe *wr)
1086 {
1087         struct sge_eq *eq = &wrq->eq;
1088         int can_reclaim;
1089         caddr_t dst;
1090
1091         TXQ_LOCK_ASSERT_OWNED(wrq);
1092 #ifdef TCP_OFFLOAD
1093         KASSERT((eq->flags & EQ_TYPEMASK) == EQ_OFLD ||
1094             (eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1095             ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1096 #else
1097         KASSERT((eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1098             ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1099 #endif
1100
1101         if (__predict_true(wr != NULL))
1102                 STAILQ_INSERT_TAIL(&wrq->wr_list, wr, link);
1103
1104         can_reclaim = reclaimable(eq);
1105         if (__predict_false(eq->flags & EQ_STALLED)) {
1106                 if (can_reclaim < tx_resume_threshold(eq))
1107                         return;
1108                 eq->flags &= ~EQ_STALLED;
1109                 eq->unstalled++;
1110         }
1111         eq->cidx += can_reclaim;
1112         eq->avail += can_reclaim;
1113         if (__predict_false(eq->cidx >= eq->cap))
1114                 eq->cidx -= eq->cap;
1115
1116         while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
1117                 int ndesc;
1118
1119                 if (__predict_false(wr->wr_len < 0 ||
1120                     wr->wr_len > SGE_MAX_WR_LEN || (wr->wr_len & 0x7))) {
1121
1122 #ifdef INVARIANTS
1123                         panic("%s: work request with length %d", __func__,
1124                             wr->wr_len);
1125 #endif
1126 #ifdef KDB
1127                         kdb_backtrace();
1128 #endif
1129                         log(LOG_ERR, "%s: %s work request with length %d",
1130                             device_get_nameunit(sc->dev), __func__, wr->wr_len);
1131                         STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1132                         free_wrqe(wr);
1133                         continue;
1134                 }
1135
1136                 ndesc = howmany(wr->wr_len, EQ_ESIZE);
1137                 if (eq->avail < ndesc) {
1138                         wrq->no_desc++;
1139                         break;
1140                 }
1141
1142                 dst = (void *)&eq->desc[eq->pidx];
1143                 copy_to_txd(eq, wrtod(wr), &dst, wr->wr_len);
1144
1145                 eq->pidx += ndesc;
1146                 eq->avail -= ndesc;
1147                 if (__predict_false(eq->pidx >= eq->cap))
1148                         eq->pidx -= eq->cap;
1149
1150                 eq->pending += ndesc;
1151                 if (eq->pending > 16)
1152                         ring_eq_db(sc, eq);
1153
1154                 wrq->tx_wrs++;
1155                 STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1156                 free_wrqe(wr);
1157
1158                 if (eq->avail < 8) {
1159                         can_reclaim = reclaimable(eq);
1160                         eq->cidx += can_reclaim;
1161                         eq->avail += can_reclaim;
1162                         if (__predict_false(eq->cidx >= eq->cap))
1163                                 eq->cidx -= eq->cap;
1164                 }
1165         }
1166
1167         if (eq->pending)
1168                 ring_eq_db(sc, eq);
1169
1170         if (wr != NULL) {
1171                 eq->flags |= EQ_STALLED;
1172                 if (callout_pending(&eq->tx_callout) == 0)
1173                         callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1174         }
1175 }
1176
1177 /* Per-packet header in a coalesced tx WR, before the SGL starts (in flits) */
1178 #define TXPKTS_PKT_HDR ((\
1179     sizeof(struct ulp_txpkt) + \
1180     sizeof(struct ulptx_idata) + \
1181     sizeof(struct cpl_tx_pkt_core) \
1182     ) / 8)
1183
1184 /* Header of a coalesced tx WR, before SGL of first packet (in flits) */
1185 #define TXPKTS_WR_HDR (\
1186     sizeof(struct fw_eth_tx_pkts_wr) / 8 + \
1187     TXPKTS_PKT_HDR)
1188
1189 /* Header of a tx WR, before SGL of first packet (in flits) */
1190 #define TXPKT_WR_HDR ((\
1191     sizeof(struct fw_eth_tx_pkt_wr) + \
1192     sizeof(struct cpl_tx_pkt_core) \
1193     ) / 8 )
1194
1195 /* Header of a tx LSO WR, before SGL of first packet (in flits) */
1196 #define TXPKT_LSO_WR_HDR ((\
1197     sizeof(struct fw_eth_tx_pkt_wr) + \
1198     sizeof(struct cpl_tx_pkt_lso) + \
1199     sizeof(struct cpl_tx_pkt_core) \
1200     ) / 8 )
1201
1202 int
1203 t4_eth_tx(struct ifnet *ifp, struct sge_txq *txq, struct mbuf *m)
1204 {
1205         struct port_info *pi = (void *)ifp->if_softc;
1206         struct adapter *sc = pi->adapter;
1207         struct sge_eq *eq = &txq->eq;
1208         struct buf_ring *br = txq->br;
1209         struct mbuf *next;
1210         int rc, coalescing, can_reclaim;
1211         struct txpkts txpkts;
1212         struct sgl sgl;
1213
1214         TXQ_LOCK_ASSERT_OWNED(txq);
1215         KASSERT(m, ("%s: called with nothing to do.", __func__));
1216         KASSERT((eq->flags & EQ_TYPEMASK) == EQ_ETH,
1217             ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1218
1219         prefetch(&eq->desc[eq->pidx]);
1220         prefetch(&txq->sdesc[eq->pidx]);
1221
1222         txpkts.npkt = 0;/* indicates there's nothing in txpkts */
1223         coalescing = 0;
1224
1225         can_reclaim = reclaimable(eq);
1226         if (__predict_false(eq->flags & EQ_STALLED)) {
1227                 if (can_reclaim < tx_resume_threshold(eq)) {
1228                         txq->m = m;
1229                         return (0);
1230                 }
1231                 eq->flags &= ~EQ_STALLED;
1232                 eq->unstalled++;
1233         }
1234
1235         if (__predict_false(eq->flags & EQ_DOOMED)) {
1236                 m_freem(m);
1237                 while ((m = buf_ring_dequeue_sc(txq->br)) != NULL)
1238                         m_freem(m);
1239                 return (ENETDOWN);
1240         }
1241
1242         if (eq->avail < 8 && can_reclaim)
1243                 reclaim_tx_descs(txq, can_reclaim, 32);
1244
1245         for (; m; m = next ? next : drbr_dequeue(ifp, br)) {
1246
1247                 if (eq->avail < 8)
1248                         break;
1249
1250                 next = m->m_nextpkt;
1251                 m->m_nextpkt = NULL;
1252
1253                 if (next || buf_ring_peek(br))
1254                         coalescing = 1;
1255
1256                 rc = get_pkt_sgl(txq, &m, &sgl, coalescing);
1257                 if (rc != 0) {
1258                         if (rc == ENOMEM) {
1259
1260                                 /* Short of resources, suspend tx */
1261
1262                                 m->m_nextpkt = next;
1263                                 break;
1264                         }
1265
1266                         /*
1267                          * Unrecoverable error for this packet, throw it away
1268                          * and move on to the next.  get_pkt_sgl may already
1269                          * have freed m (it will be NULL in that case and the
1270                          * m_freem here is still safe).
1271                          */
1272
1273                         m_freem(m);
1274                         continue;
1275                 }
1276
1277                 if (coalescing &&
1278                     add_to_txpkts(pi, txq, &txpkts, m, &sgl) == 0) {
1279
1280                         /* Successfully absorbed into txpkts */
1281
1282                         write_ulp_cpl_sgl(pi, txq, &txpkts, m, &sgl);
1283                         goto doorbell;
1284                 }
1285
1286                 /*
1287                  * We weren't coalescing to begin with, or current frame could
1288                  * not be coalesced (add_to_txpkts flushes txpkts if a frame
1289                  * given to it can't be coalesced).  Either way there should be
1290                  * nothing in txpkts.
1291                  */
1292                 KASSERT(txpkts.npkt == 0,
1293                     ("%s: txpkts not empty: %d", __func__, txpkts.npkt));
1294
1295                 /* We're sending out individual packets now */
1296                 coalescing = 0;
1297
1298                 if (eq->avail < 8)
1299                         reclaim_tx_descs(txq, 0, 8);
1300                 rc = write_txpkt_wr(pi, txq, m, &sgl);
1301                 if (rc != 0) {
1302
1303                         /* Short of hardware descriptors, suspend tx */
1304
1305                         /*
1306                          * This is an unlikely but expensive failure.  We've
1307                          * done all the hard work (DMA mappings etc.) and now we
1308                          * can't send out the packet.  What's worse, we have to
1309                          * spend even more time freeing up everything in sgl.
1310                          */
1311                         txq->no_desc++;
1312                         free_pkt_sgl(txq, &sgl);
1313
1314                         m->m_nextpkt = next;
1315                         break;
1316                 }
1317
1318                 ETHER_BPF_MTAP(ifp, m);
1319                 if (sgl.nsegs == 0)
1320                         m_freem(m);
1321 doorbell:
1322                 if (eq->pending >= 64)
1323                     ring_eq_db(sc, eq);
1324
1325                 can_reclaim = reclaimable(eq);
1326                 if (can_reclaim >= 32)
1327                         reclaim_tx_descs(txq, can_reclaim, 64);
1328         }
1329
1330         if (txpkts.npkt > 0)
1331                 write_txpkts_wr(txq, &txpkts);
1332
1333         /*
1334          * m not NULL means there was an error but we haven't thrown it away.
1335          * This can happen when we're short of tx descriptors (no_desc) or maybe
1336          * even DMA maps (no_dmamap).  Either way, a credit flush and reclaim
1337          * will get things going again.
1338          */
1339         if (m && !(eq->flags & EQ_CRFLUSHED)) {
1340                 struct tx_sdesc *txsd = &txq->sdesc[eq->pidx];
1341
1342                 /*
1343                  * If EQ_CRFLUSHED is not set then we know we have at least one
1344                  * available descriptor because any WR that reduces eq->avail to
1345                  * 0 also sets EQ_CRFLUSHED.
1346                  */
1347                 KASSERT(eq->avail > 0, ("%s: no space for eqflush.", __func__));
1348
1349                 txsd->desc_used = 1;
1350                 txsd->credits = 0;
1351                 write_eqflush_wr(eq);
1352         }
1353         txq->m = m;
1354
1355         if (eq->pending)
1356                 ring_eq_db(sc, eq);
1357
1358         reclaim_tx_descs(txq, 0, 128);
1359
1360         if (eq->flags & EQ_STALLED && callout_pending(&eq->tx_callout) == 0)
1361                 callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1362
1363         return (0);
1364 }
1365
1366 void
1367 t4_update_fl_bufsize(struct ifnet *ifp)
1368 {
1369         struct port_info *pi = ifp->if_softc;
1370         struct sge_rxq *rxq;
1371         struct sge_fl *fl;
1372         int i, bufsize;
1373
1374         /* large enough for a frame even when VLAN extraction is disabled */
1375         bufsize = FL_PKTSHIFT + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN +
1376             ifp->if_mtu;
1377         for_each_rxq(pi, i, rxq) {
1378                 fl = &rxq->fl;
1379
1380                 FL_LOCK(fl);
1381                 set_fl_tag_idx(fl, bufsize);
1382                 FL_UNLOCK(fl);
1383         }
1384 }
1385
1386 int
1387 can_resume_tx(struct sge_eq *eq)
1388 {
1389         return (reclaimable(eq) >= tx_resume_threshold(eq));
1390 }
1391
1392 static inline void
1393 init_iq(struct sge_iq *iq, struct adapter *sc, int tmr_idx, int pktc_idx,
1394     int qsize, int esize, char *name)
1395 {
1396         KASSERT(tmr_idx >= 0 && tmr_idx < SGE_NTIMERS,
1397             ("%s: bad tmr_idx %d", __func__, tmr_idx));
1398         KASSERT(pktc_idx < SGE_NCOUNTERS,       /* -ve is ok, means don't use */
1399             ("%s: bad pktc_idx %d", __func__, pktc_idx));
1400
1401         iq->flags = 0;
1402         iq->adapter = sc;
1403         iq->intr_params = V_QINTR_TIMER_IDX(tmr_idx);
1404         iq->intr_pktc_idx = SGE_NCOUNTERS - 1;
1405         if (pktc_idx >= 0) {
1406                 iq->intr_params |= F_QINTR_CNT_EN;
1407                 iq->intr_pktc_idx = pktc_idx;
1408         }
1409         iq->qsize = roundup(qsize, 16);         /* See FW_IQ_CMD/iqsize */
1410         iq->esize = max(esize, 16);             /* See FW_IQ_CMD/iqesize */
1411         strlcpy(iq->lockname, name, sizeof(iq->lockname));
1412 }
1413
1414 static inline void
1415 init_fl(struct sge_fl *fl, int qsize, int bufsize, char *name)
1416 {
1417         fl->qsize = qsize;
1418         strlcpy(fl->lockname, name, sizeof(fl->lockname));
1419         set_fl_tag_idx(fl, bufsize);
1420 }
1421
1422 static inline void
1423 init_eq(struct sge_eq *eq, int eqtype, int qsize, uint8_t tx_chan,
1424     uint16_t iqid, char *name)
1425 {
1426         KASSERT(tx_chan < NCHAN, ("%s: bad tx channel %d", __func__, tx_chan));
1427         KASSERT(eqtype <= EQ_TYPEMASK, ("%s: bad qtype %d", __func__, eqtype));
1428
1429         eq->flags = eqtype & EQ_TYPEMASK;
1430         eq->tx_chan = tx_chan;
1431         eq->iqid = iqid;
1432         eq->qsize = qsize;
1433         strlcpy(eq->lockname, name, sizeof(eq->lockname));
1434
1435         TASK_INIT(&eq->tx_task, 0, t4_tx_task, eq);
1436         callout_init(&eq->tx_callout, CALLOUT_MPSAFE);
1437 }
1438
1439 static int
1440 alloc_ring(struct adapter *sc, size_t len, bus_dma_tag_t *tag,
1441     bus_dmamap_t *map, bus_addr_t *pa, void **va)
1442 {
1443         int rc;
1444
1445         rc = bus_dma_tag_create(sc->dmat, 512, 0, BUS_SPACE_MAXADDR,
1446             BUS_SPACE_MAXADDR, NULL, NULL, len, 1, len, 0, NULL, NULL, tag);
1447         if (rc != 0) {
1448                 device_printf(sc->dev, "cannot allocate DMA tag: %d\n", rc);
1449                 goto done;
1450         }
1451
1452         rc = bus_dmamem_alloc(*tag, va,
1453             BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, map);
1454         if (rc != 0) {
1455                 device_printf(sc->dev, "cannot allocate DMA memory: %d\n", rc);
1456                 goto done;
1457         }
1458
1459         rc = bus_dmamap_load(*tag, *map, *va, len, oneseg_dma_callback, pa, 0);
1460         if (rc != 0) {
1461                 device_printf(sc->dev, "cannot load DMA map: %d\n", rc);
1462                 goto done;
1463         }
1464 done:
1465         if (rc)
1466                 free_ring(sc, *tag, *map, *pa, *va);
1467
1468         return (rc);
1469 }
1470
1471 static int
1472 free_ring(struct adapter *sc, bus_dma_tag_t tag, bus_dmamap_t map,
1473     bus_addr_t pa, void *va)
1474 {
1475         if (pa)
1476                 bus_dmamap_unload(tag, map);
1477         if (va)
1478                 bus_dmamem_free(tag, va, map);
1479         if (tag)
1480                 bus_dma_tag_destroy(tag);
1481
1482         return (0);
1483 }
1484
1485 /*
1486  * Allocates the ring for an ingress queue and an optional freelist.  If the
1487  * freelist is specified it will be allocated and then associated with the
1488  * ingress queue.
1489  *
1490  * Returns errno on failure.  Resources allocated up to that point may still be
1491  * allocated.  Caller is responsible for cleanup in case this function fails.
1492  *
1493  * If the ingress queue will take interrupts directly (iq->flags & IQ_INTR) then
1494  * the intr_idx specifies the vector, starting from 0.  Otherwise it specifies
1495  * the abs_id of the ingress queue to which its interrupts should be forwarded.
1496  */
1497 static int
1498 alloc_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl,
1499     int intr_idx, int cong)
1500 {
1501         int rc, i, cntxt_id;
1502         size_t len;
1503         struct fw_iq_cmd c;
1504         struct adapter *sc = iq->adapter;
1505         __be32 v = 0;
1506
1507         len = iq->qsize * iq->esize;
1508         rc = alloc_ring(sc, len, &iq->desc_tag, &iq->desc_map, &iq->ba,
1509             (void **)&iq->desc);
1510         if (rc != 0)
1511                 return (rc);
1512
1513         bzero(&c, sizeof(c));
1514         c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
1515             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_IQ_CMD_PFN(sc->pf) |
1516             V_FW_IQ_CMD_VFN(0));
1517
1518         c.alloc_to_len16 = htobe32(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
1519             FW_LEN16(c));
1520
1521         /* Special handling for firmware event queue */
1522         if (iq == &sc->sge.fwq)
1523                 v |= F_FW_IQ_CMD_IQASYNCH;
1524
1525         if (iq->flags & IQ_INTR) {
1526                 KASSERT(intr_idx < sc->intr_count,
1527                     ("%s: invalid direct intr_idx %d", __func__, intr_idx));
1528         } else
1529                 v |= F_FW_IQ_CMD_IQANDST;
1530         v |= V_FW_IQ_CMD_IQANDSTINDEX(intr_idx);
1531
1532         c.type_to_iqandstindex = htobe32(v |
1533             V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
1534             V_FW_IQ_CMD_VIID(pi->viid) |
1535             V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT));
1536         c.iqdroprss_to_iqesize = htobe16(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
1537             F_FW_IQ_CMD_IQGTSMODE |
1538             V_FW_IQ_CMD_IQINTCNTTHRESH(iq->intr_pktc_idx) |
1539             V_FW_IQ_CMD_IQESIZE(ilog2(iq->esize) - 4));
1540         c.iqsize = htobe16(iq->qsize);
1541         c.iqaddr = htobe64(iq->ba);
1542         if (cong >= 0)
1543                 c.iqns_to_fl0congen = htobe32(F_FW_IQ_CMD_IQFLINTCONGEN);
1544
1545         if (fl) {
1546                 mtx_init(&fl->fl_lock, fl->lockname, NULL, MTX_DEF);
1547
1548                 for (i = 0; i < FL_BUF_SIZES; i++) {
1549
1550                         /*
1551                          * A freelist buffer must be 16 byte aligned as the SGE
1552                          * uses the low 4 bits of the bus addr to figure out the
1553                          * buffer size.
1554                          */
1555                         rc = bus_dma_tag_create(sc->dmat, 16, 0,
1556                             BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1557                             FL_BUF_SIZE(i), 1, FL_BUF_SIZE(i), BUS_DMA_ALLOCNOW,
1558                             NULL, NULL, &fl->tag[i]);
1559                         if (rc != 0) {
1560                                 device_printf(sc->dev,
1561                                     "failed to create fl DMA tag[%d]: %d\n",
1562                                     i, rc);
1563                                 return (rc);
1564                         }
1565                 }
1566                 len = fl->qsize * RX_FL_ESIZE;
1567                 rc = alloc_ring(sc, len, &fl->desc_tag, &fl->desc_map,
1568                     &fl->ba, (void **)&fl->desc);
1569                 if (rc)
1570                         return (rc);
1571
1572                 /* Allocate space for one software descriptor per buffer. */
1573                 fl->cap = (fl->qsize - SPG_LEN / RX_FL_ESIZE) * 8;
1574                 FL_LOCK(fl);
1575                 rc = alloc_fl_sdesc(fl);
1576                 FL_UNLOCK(fl);
1577                 if (rc != 0) {
1578                         device_printf(sc->dev,
1579                             "failed to setup fl software descriptors: %d\n",
1580                             rc);
1581                         return (rc);
1582                 }
1583                 fl->needed = fl->cap;
1584                 fl->lowat = roundup(sc->sge.fl_starve_threshold, 8);
1585
1586                 c.iqns_to_fl0congen |=
1587                     htobe32(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
1588                         F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
1589                         F_FW_IQ_CMD_FL0PADEN);
1590                 if (cong >= 0) {
1591                         c.iqns_to_fl0congen |=
1592                                 htobe32(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
1593                                     F_FW_IQ_CMD_FL0CONGCIF |
1594                                     F_FW_IQ_CMD_FL0CONGEN);
1595                 }
1596                 c.fl0dcaen_to_fl0cidxfthresh =
1597                     htobe16(V_FW_IQ_CMD_FL0FBMIN(X_FETCHBURSTMIN_64B) |
1598                         V_FW_IQ_CMD_FL0FBMAX(X_FETCHBURSTMAX_512B));
1599                 c.fl0size = htobe16(fl->qsize);
1600                 c.fl0addr = htobe64(fl->ba);
1601         }
1602
1603         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
1604         if (rc != 0) {
1605                 device_printf(sc->dev,
1606                     "failed to create ingress queue: %d\n", rc);
1607                 return (rc);
1608         }
1609
1610         iq->cdesc = iq->desc;
1611         iq->cidx = 0;
1612         iq->gen = 1;
1613         iq->intr_next = iq->intr_params;
1614         iq->cntxt_id = be16toh(c.iqid);
1615         iq->abs_id = be16toh(c.physiqid);
1616         iq->flags |= IQ_ALLOCATED;
1617
1618         cntxt_id = iq->cntxt_id - sc->sge.iq_start;
1619         if (cntxt_id >= sc->sge.niq) {
1620                 panic ("%s: iq->cntxt_id (%d) more than the max (%d)", __func__,
1621                     cntxt_id, sc->sge.niq - 1);
1622         }
1623         sc->sge.iqmap[cntxt_id] = iq;
1624
1625         if (fl) {
1626                 fl->cntxt_id = be16toh(c.fl0id);
1627                 fl->pidx = fl->cidx = 0;
1628
1629                 cntxt_id = fl->cntxt_id - sc->sge.eq_start;
1630                 if (cntxt_id >= sc->sge.neq) {
1631                         panic("%s: fl->cntxt_id (%d) more than the max (%d)",
1632                             __func__, cntxt_id, sc->sge.neq - 1);
1633                 }
1634                 sc->sge.eqmap[cntxt_id] = (void *)fl;
1635
1636                 FL_LOCK(fl);
1637                 /* Enough to make sure the SGE doesn't think it's starved */
1638                 refill_fl(sc, fl, fl->lowat);
1639                 FL_UNLOCK(fl);
1640
1641                 iq->flags |= IQ_HAS_FL;
1642         }
1643
1644         /* Enable IQ interrupts */
1645         atomic_store_rel_int(&iq->state, IQS_IDLE);
1646         t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_SEINTARM(iq->intr_params) |
1647             V_INGRESSQID(iq->cntxt_id));
1648
1649         return (0);
1650 }
1651
1652 static int
1653 free_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl)
1654 {
1655         int i, rc;
1656         struct adapter *sc = iq->adapter;
1657         device_t dev;
1658
1659         if (sc == NULL)
1660                 return (0);     /* nothing to do */
1661
1662         dev = pi ? pi->dev : sc->dev;
1663
1664         if (iq->flags & IQ_ALLOCATED) {
1665                 rc = -t4_iq_free(sc, sc->mbox, sc->pf, 0,
1666                     FW_IQ_TYPE_FL_INT_CAP, iq->cntxt_id,
1667                     fl ? fl->cntxt_id : 0xffff, 0xffff);
1668                 if (rc != 0) {
1669                         device_printf(dev,
1670                             "failed to free queue %p: %d\n", iq, rc);
1671                         return (rc);
1672                 }
1673                 iq->flags &= ~IQ_ALLOCATED;
1674         }
1675
1676         free_ring(sc, iq->desc_tag, iq->desc_map, iq->ba, iq->desc);
1677
1678         bzero(iq, sizeof(*iq));
1679
1680         if (fl) {
1681                 free_ring(sc, fl->desc_tag, fl->desc_map, fl->ba,
1682                     fl->desc);
1683
1684                 if (fl->sdesc) {
1685                         FL_LOCK(fl);
1686                         free_fl_sdesc(fl);
1687                         FL_UNLOCK(fl);
1688                 }
1689
1690                 if (mtx_initialized(&fl->fl_lock))
1691                         mtx_destroy(&fl->fl_lock);
1692
1693                 for (i = 0; i < FL_BUF_SIZES; i++) {
1694                         if (fl->tag[i])
1695                                 bus_dma_tag_destroy(fl->tag[i]);
1696                 }
1697
1698                 bzero(fl, sizeof(*fl));
1699         }
1700
1701         return (0);
1702 }
1703
1704 static int
1705 alloc_fwq(struct adapter *sc)
1706 {
1707         int rc, intr_idx;
1708         struct sge_iq *fwq = &sc->sge.fwq;
1709         char name[16];
1710         struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
1711         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
1712
1713         snprintf(name, sizeof(name), "%s fwq", device_get_nameunit(sc->dev));
1714         init_iq(fwq, sc, 0, 0, FW_IQ_QSIZE, FW_IQ_ESIZE, name);
1715         fwq->flags |= IQ_INTR;  /* always */
1716         intr_idx = sc->intr_count > 1 ? 1 : 0;
1717         rc = alloc_iq_fl(sc->port[0], fwq, NULL, intr_idx, -1);
1718         if (rc != 0) {
1719                 device_printf(sc->dev,
1720                     "failed to create firmware event queue: %d\n", rc);
1721                 return (rc);
1722         }
1723
1724         oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "fwq", CTLFLAG_RD,
1725             NULL, "firmware event queue");
1726         children = SYSCTL_CHILDREN(oid);
1727
1728         SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "abs_id",
1729             CTLTYPE_INT | CTLFLAG_RD, &fwq->abs_id, 0, sysctl_uint16, "I",
1730             "absolute id of the queue");
1731         SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cntxt_id",
1732             CTLTYPE_INT | CTLFLAG_RD, &fwq->cntxt_id, 0, sysctl_uint16, "I",
1733             "SGE context id of the queue");
1734         SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cidx",
1735             CTLTYPE_INT | CTLFLAG_RD, &fwq->cidx, 0, sysctl_uint16, "I",
1736             "consumer index");
1737
1738         return (0);
1739 }
1740
1741 static int
1742 free_fwq(struct adapter *sc)
1743 {
1744         return free_iq_fl(NULL, &sc->sge.fwq, NULL);
1745 }
1746
1747 static int
1748 alloc_mgmtq(struct adapter *sc)
1749 {
1750         int rc;
1751         struct sge_wrq *mgmtq = &sc->sge.mgmtq;
1752         char name[16];
1753         struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
1754         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
1755
1756         oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "mgmtq", CTLFLAG_RD,
1757             NULL, "management queue");
1758
1759         snprintf(name, sizeof(name), "%s mgmtq", device_get_nameunit(sc->dev));
1760         init_eq(&mgmtq->eq, EQ_CTRL, CTRL_EQ_QSIZE, sc->port[0]->tx_chan,
1761             sc->sge.fwq.cntxt_id, name);
1762         rc = alloc_wrq(sc, NULL, mgmtq, oid);
1763         if (rc != 0) {
1764                 device_printf(sc->dev,
1765                     "failed to create management queue: %d\n", rc);
1766                 return (rc);
1767         }
1768
1769         return (0);
1770 }
1771
1772 static int
1773 free_mgmtq(struct adapter *sc)
1774 {
1775
1776         return free_wrq(sc, &sc->sge.mgmtq);
1777 }
1778
1779 static int
1780 alloc_rxq(struct port_info *pi, struct sge_rxq *rxq, int intr_idx, int idx,
1781     struct sysctl_oid *oid)
1782 {
1783         int rc;
1784         struct sysctl_oid_list *children;
1785         char name[16];
1786
1787         rc = alloc_iq_fl(pi, &rxq->iq, &rxq->fl, intr_idx, 1 << pi->tx_chan);
1788         if (rc != 0)
1789                 return (rc);
1790
1791         FL_LOCK(&rxq->fl);
1792         refill_fl(pi->adapter, &rxq->fl, rxq->fl.needed / 8);
1793         FL_UNLOCK(&rxq->fl);
1794
1795 #ifdef INET
1796         rc = tcp_lro_init(&rxq->lro);
1797         if (rc != 0)
1798                 return (rc);
1799         rxq->lro.ifp = pi->ifp; /* also indicates LRO init'ed */
1800
1801         if (pi->ifp->if_capenable & IFCAP_LRO)
1802                 rxq->iq.flags |= IQ_LRO_ENABLED;
1803 #endif
1804         rxq->ifp = pi->ifp;
1805
1806         children = SYSCTL_CHILDREN(oid);
1807
1808         snprintf(name, sizeof(name), "%d", idx);
1809         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
1810             NULL, "rx queue");
1811         children = SYSCTL_CHILDREN(oid);
1812
1813         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
1814             CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.abs_id, 0, sysctl_uint16, "I",
1815             "absolute id of the queue");
1816         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
1817             CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cntxt_id, 0, sysctl_uint16, "I",
1818             "SGE context id of the queue");
1819         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
1820             CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cidx, 0, sysctl_uint16, "I",
1821             "consumer index");
1822 #ifdef INET
1823         SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_queued", CTLFLAG_RD,
1824             &rxq->lro.lro_queued, 0, NULL);
1825         SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_flushed", CTLFLAG_RD,
1826             &rxq->lro.lro_flushed, 0, NULL);
1827 #endif
1828         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "rxcsum", CTLFLAG_RD,
1829             &rxq->rxcsum, "# of times hardware assisted with checksum");
1830         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_extraction",
1831             CTLFLAG_RD, &rxq->vlan_extraction,
1832             "# of times hardware extracted 802.1Q tag");
1833
1834         children = SYSCTL_CHILDREN(oid);
1835         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
1836             NULL, "freelist");
1837         children = SYSCTL_CHILDREN(oid);
1838
1839         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
1840             CTLTYPE_INT | CTLFLAG_RD, &rxq->fl.cntxt_id, 0, sysctl_uint16, "I",
1841             "SGE context id of the queue");
1842         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
1843             &rxq->fl.cidx, 0, "consumer index");
1844         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
1845             &rxq->fl.pidx, 0, "producer index");
1846
1847         return (rc);
1848 }
1849
1850 static int
1851 free_rxq(struct port_info *pi, struct sge_rxq *rxq)
1852 {
1853         int rc;
1854
1855 #ifdef INET
1856         if (rxq->lro.ifp) {
1857                 tcp_lro_free(&rxq->lro);
1858                 rxq->lro.ifp = NULL;
1859         }
1860 #endif
1861
1862         rc = free_iq_fl(pi, &rxq->iq, &rxq->fl);
1863         if (rc == 0)
1864                 bzero(rxq, sizeof(*rxq));
1865
1866         return (rc);
1867 }
1868
1869 #ifdef TCP_OFFLOAD
1870 static int
1871 alloc_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq,
1872     int intr_idx, int idx, struct sysctl_oid *oid)
1873 {
1874         int rc;
1875         struct sysctl_oid_list *children;
1876         char name[16];
1877
1878         rc = alloc_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl, intr_idx,
1879             1 << pi->tx_chan);
1880         if (rc != 0)
1881                 return (rc);
1882
1883         children = SYSCTL_CHILDREN(oid);
1884
1885         snprintf(name, sizeof(name), "%d", idx);
1886         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
1887             NULL, "rx queue");
1888         children = SYSCTL_CHILDREN(oid);
1889
1890         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
1891             CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.abs_id, 0, sysctl_uint16,
1892             "I", "absolute id of the queue");
1893         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
1894             CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cntxt_id, 0, sysctl_uint16,
1895             "I", "SGE context id of the queue");
1896         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
1897             CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cidx, 0, sysctl_uint16, "I",
1898             "consumer index");
1899
1900         children = SYSCTL_CHILDREN(oid);
1901         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
1902             NULL, "freelist");
1903         children = SYSCTL_CHILDREN(oid);
1904
1905         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
1906             CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->fl.cntxt_id, 0, sysctl_uint16,
1907             "I", "SGE context id of the queue");
1908         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
1909             &ofld_rxq->fl.cidx, 0, "consumer index");
1910         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
1911             &ofld_rxq->fl.pidx, 0, "producer index");
1912
1913         return (rc);
1914 }
1915
1916 static int
1917 free_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq)
1918 {
1919         int rc;
1920
1921         rc = free_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl);
1922         if (rc == 0)
1923                 bzero(ofld_rxq, sizeof(*ofld_rxq));
1924
1925         return (rc);
1926 }
1927 #endif
1928
1929 static int
1930 ctrl_eq_alloc(struct adapter *sc, struct sge_eq *eq)
1931 {
1932         int rc, cntxt_id;
1933         struct fw_eq_ctrl_cmd c;
1934
1935         bzero(&c, sizeof(c));
1936
1937         c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
1938             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_CTRL_CMD_PFN(sc->pf) |
1939             V_FW_EQ_CTRL_CMD_VFN(0));
1940         c.alloc_to_len16 = htobe32(F_FW_EQ_CTRL_CMD_ALLOC |
1941             F_FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
1942         c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(eq->iqid)); /* XXX */
1943         c.physeqid_pkd = htobe32(0);
1944         c.fetchszm_to_iqid =
1945             htobe32(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
1946                 V_FW_EQ_CTRL_CMD_PCIECHN(eq->tx_chan) |
1947                 F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(eq->iqid));
1948         c.dcaen_to_eqsize =
1949             htobe32(V_FW_EQ_CTRL_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
1950                 V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
1951                 V_FW_EQ_CTRL_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
1952                 V_FW_EQ_CTRL_CMD_EQSIZE(eq->qsize));
1953         c.eqaddr = htobe64(eq->ba);
1954
1955         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
1956         if (rc != 0) {
1957                 device_printf(sc->dev,
1958                     "failed to create control queue %d: %d\n", eq->tx_chan, rc);
1959                 return (rc);
1960         }
1961         eq->flags |= EQ_ALLOCATED;
1962
1963         eq->cntxt_id = G_FW_EQ_CTRL_CMD_EQID(be32toh(c.cmpliqid_eqid));
1964         cntxt_id = eq->cntxt_id - sc->sge.eq_start;
1965         if (cntxt_id >= sc->sge.neq)
1966             panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
1967                 cntxt_id, sc->sge.neq - 1);
1968         sc->sge.eqmap[cntxt_id] = eq;
1969
1970         return (rc);
1971 }
1972
1973 static int
1974 eth_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
1975 {
1976         int rc, cntxt_id;
1977         struct fw_eq_eth_cmd c;
1978
1979         bzero(&c, sizeof(c));
1980
1981         c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
1982             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
1983             V_FW_EQ_ETH_CMD_VFN(0));
1984         c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
1985             F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
1986         c.viid_pkd = htobe32(V_FW_EQ_ETH_CMD_VIID(pi->viid));
1987         c.fetchszm_to_iqid =
1988             htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
1989                 V_FW_EQ_ETH_CMD_PCIECHN(eq->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
1990                 V_FW_EQ_ETH_CMD_IQID(eq->iqid));
1991         c.dcaen_to_eqsize = htobe32(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
1992                       V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
1993                       V_FW_EQ_ETH_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
1994                       V_FW_EQ_ETH_CMD_EQSIZE(eq->qsize));
1995         c.eqaddr = htobe64(eq->ba);
1996
1997         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
1998         if (rc != 0) {
1999                 device_printf(pi->dev,
2000                     "failed to create Ethernet egress queue: %d\n", rc);
2001                 return (rc);
2002         }
2003         eq->flags |= EQ_ALLOCATED;
2004
2005         eq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
2006         cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2007         if (cntxt_id >= sc->sge.neq)
2008             panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2009                 cntxt_id, sc->sge.neq - 1);
2010         sc->sge.eqmap[cntxt_id] = eq;
2011
2012         return (rc);
2013 }
2014
2015 #ifdef TCP_OFFLOAD
2016 static int
2017 ofld_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2018 {
2019         int rc, cntxt_id;
2020         struct fw_eq_ofld_cmd c;
2021
2022         bzero(&c, sizeof(c));
2023
2024         c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_OFLD_CMD) | F_FW_CMD_REQUEST |
2025             F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_OFLD_CMD_PFN(sc->pf) |
2026             V_FW_EQ_OFLD_CMD_VFN(0));
2027         c.alloc_to_len16 = htonl(F_FW_EQ_OFLD_CMD_ALLOC |
2028             F_FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
2029         c.fetchszm_to_iqid =
2030                 htonl(V_FW_EQ_OFLD_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2031                     V_FW_EQ_OFLD_CMD_PCIECHN(eq->tx_chan) |
2032                     F_FW_EQ_OFLD_CMD_FETCHRO | V_FW_EQ_OFLD_CMD_IQID(eq->iqid));
2033         c.dcaen_to_eqsize =
2034             htobe32(V_FW_EQ_OFLD_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2035                 V_FW_EQ_OFLD_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2036                 V_FW_EQ_OFLD_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2037                 V_FW_EQ_OFLD_CMD_EQSIZE(eq->qsize));
2038         c.eqaddr = htobe64(eq->ba);
2039
2040         rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2041         if (rc != 0) {
2042                 device_printf(pi->dev,
2043                     "failed to create egress queue for TCP offload: %d\n", rc);
2044                 return (rc);
2045         }
2046         eq->flags |= EQ_ALLOCATED;
2047
2048         eq->cntxt_id = G_FW_EQ_OFLD_CMD_EQID(be32toh(c.eqid_pkd));
2049         cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2050         if (cntxt_id >= sc->sge.neq)
2051             panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2052                 cntxt_id, sc->sge.neq - 1);
2053         sc->sge.eqmap[cntxt_id] = eq;
2054
2055         return (rc);
2056 }
2057 #endif
2058
2059 static int
2060 alloc_eq(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2061 {
2062         int rc;
2063         size_t len;
2064
2065         mtx_init(&eq->eq_lock, eq->lockname, NULL, MTX_DEF);
2066
2067         len = eq->qsize * EQ_ESIZE;
2068         rc = alloc_ring(sc, len, &eq->desc_tag, &eq->desc_map,
2069             &eq->ba, (void **)&eq->desc);
2070         if (rc)
2071                 return (rc);
2072
2073         eq->cap = eq->qsize - SPG_LEN / EQ_ESIZE;
2074         eq->spg = (void *)&eq->desc[eq->cap];
2075         eq->avail = eq->cap - 1;        /* one less to avoid cidx = pidx */
2076         eq->pidx = eq->cidx = 0;
2077
2078         switch (eq->flags & EQ_TYPEMASK) {
2079         case EQ_CTRL:
2080                 rc = ctrl_eq_alloc(sc, eq);
2081                 break;
2082
2083         case EQ_ETH:
2084                 rc = eth_eq_alloc(sc, pi, eq);
2085                 break;
2086
2087 #ifdef TCP_OFFLOAD
2088         case EQ_OFLD:
2089                 rc = ofld_eq_alloc(sc, pi, eq);
2090                 break;
2091 #endif
2092
2093         default:
2094                 panic("%s: invalid eq type %d.", __func__,
2095                     eq->flags & EQ_TYPEMASK);
2096         }
2097         if (rc != 0) {
2098                 device_printf(sc->dev,
2099                     "failed to allocate egress queue(%d): %d",
2100                     eq->flags & EQ_TYPEMASK, rc);
2101         }
2102
2103         eq->tx_callout.c_cpu = eq->cntxt_id % mp_ncpus;
2104
2105         return (rc);
2106 }
2107
2108 static int
2109 free_eq(struct adapter *sc, struct sge_eq *eq)
2110 {
2111         int rc;
2112
2113         if (eq->flags & EQ_ALLOCATED) {
2114                 switch (eq->flags & EQ_TYPEMASK) {
2115                 case EQ_CTRL:
2116                         rc = -t4_ctrl_eq_free(sc, sc->mbox, sc->pf, 0,
2117                             eq->cntxt_id);
2118                         break;
2119
2120                 case EQ_ETH:
2121                         rc = -t4_eth_eq_free(sc, sc->mbox, sc->pf, 0,
2122                             eq->cntxt_id);
2123                         break;
2124
2125 #ifdef TCP_OFFLOAD
2126                 case EQ_OFLD:
2127                         rc = -t4_ofld_eq_free(sc, sc->mbox, sc->pf, 0,
2128                             eq->cntxt_id);
2129                         break;
2130 #endif
2131
2132                 default:
2133                         panic("%s: invalid eq type %d.", __func__,
2134                             eq->flags & EQ_TYPEMASK);
2135                 }
2136                 if (rc != 0) {
2137                         device_printf(sc->dev,
2138                             "failed to free egress queue (%d): %d\n",
2139                             eq->flags & EQ_TYPEMASK, rc);
2140                         return (rc);
2141                 }
2142                 eq->flags &= ~EQ_ALLOCATED;
2143         }
2144
2145         free_ring(sc, eq->desc_tag, eq->desc_map, eq->ba, eq->desc);
2146
2147         if (mtx_initialized(&eq->eq_lock))
2148                 mtx_destroy(&eq->eq_lock);
2149
2150         bzero(eq, sizeof(*eq));
2151         return (0);
2152 }
2153
2154 static int
2155 alloc_wrq(struct adapter *sc, struct port_info *pi, struct sge_wrq *wrq,
2156     struct sysctl_oid *oid)
2157 {
2158         int rc;
2159         struct sysctl_ctx_list *ctx = pi ? &pi->ctx : &sc->ctx;
2160         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2161
2162         rc = alloc_eq(sc, pi, &wrq->eq);
2163         if (rc)
2164                 return (rc);
2165
2166         wrq->adapter = sc;
2167         STAILQ_INIT(&wrq->wr_list);
2168
2169         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2170             &wrq->eq.cntxt_id, 0, "SGE context id of the queue");
2171         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
2172             CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.cidx, 0, sysctl_uint16, "I",
2173             "consumer index");
2174         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pidx",
2175             CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.pidx, 0, sysctl_uint16, "I",
2176             "producer index");
2177         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs", CTLFLAG_RD,
2178             &wrq->tx_wrs, "# of work requests");
2179         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2180             &wrq->no_desc, 0,
2181             "# of times queue ran out of hardware descriptors");
2182         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2183             &wrq->eq.unstalled, 0, "# of times queue recovered after stall");
2184
2185
2186         return (rc);
2187 }
2188
2189 static int
2190 free_wrq(struct adapter *sc, struct sge_wrq *wrq)
2191 {
2192         int rc;
2193
2194         rc = free_eq(sc, &wrq->eq);
2195         if (rc)
2196                 return (rc);
2197
2198         bzero(wrq, sizeof(*wrq));
2199         return (0);
2200 }
2201
2202 static int
2203 alloc_txq(struct port_info *pi, struct sge_txq *txq, int idx,
2204     struct sysctl_oid *oid)
2205 {
2206         int rc;
2207         struct adapter *sc = pi->adapter;
2208         struct sge_eq *eq = &txq->eq;
2209         char name[16];
2210         struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2211
2212         rc = alloc_eq(sc, pi, eq);
2213         if (rc)
2214                 return (rc);
2215
2216         txq->ifp = pi->ifp;
2217
2218         txq->sdesc = malloc(eq->cap * sizeof(struct tx_sdesc), M_CXGBE,
2219             M_ZERO | M_WAITOK);
2220         txq->br = buf_ring_alloc(eq->qsize, M_CXGBE, M_WAITOK, &eq->eq_lock);
2221
2222         rc = bus_dma_tag_create(sc->dmat, 1, 0, BUS_SPACE_MAXADDR,
2223             BUS_SPACE_MAXADDR, NULL, NULL, 64 * 1024, TX_SGL_SEGS,
2224             BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL, NULL, &txq->tx_tag);
2225         if (rc != 0) {
2226                 device_printf(sc->dev,
2227                     "failed to create tx DMA tag: %d\n", rc);
2228                 return (rc);
2229         }
2230
2231         /*
2232          * We can stuff ~10 frames in an 8-descriptor txpkts WR (8 is the SGE
2233          * limit for any WR).  txq->no_dmamap events shouldn't occur if maps is
2234          * sized for the worst case.
2235          */
2236         rc = t4_alloc_tx_maps(&txq->txmaps, txq->tx_tag, eq->qsize * 10 / 8,
2237             M_WAITOK);
2238         if (rc != 0) {
2239                 device_printf(sc->dev, "failed to setup tx DMA maps: %d\n", rc);
2240                 return (rc);
2241         }
2242
2243         snprintf(name, sizeof(name), "%d", idx);
2244         oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2245             NULL, "tx queue");
2246         children = SYSCTL_CHILDREN(oid);
2247
2248         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2249             &eq->cntxt_id, 0, "SGE context id of the queue");
2250         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2251             CTLTYPE_INT | CTLFLAG_RD, &eq->cidx, 0, sysctl_uint16, "I",
2252             "consumer index");
2253         SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "pidx",
2254             CTLTYPE_INT | CTLFLAG_RD, &eq->pidx, 0, sysctl_uint16, "I",
2255             "producer index");
2256
2257         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txcsum", CTLFLAG_RD,
2258             &txq->txcsum, "# of times hardware assisted with checksum");
2259         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_insertion",
2260             CTLFLAG_RD, &txq->vlan_insertion,
2261             "# of times hardware inserted 802.1Q tag");
2262         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "tso_wrs", CTLFLAG_RD,
2263             &txq->tso_wrs, "# of IPv4 TSO work requests");
2264         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "imm_wrs", CTLFLAG_RD,
2265             &txq->imm_wrs, "# of work requests with immediate data");
2266         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "sgl_wrs", CTLFLAG_RD,
2267             &txq->sgl_wrs, "# of work requests with direct SGL");
2268         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkt_wrs", CTLFLAG_RD,
2269             &txq->txpkt_wrs, "# of txpkt work requests (one pkt/WR)");
2270         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_wrs", CTLFLAG_RD,
2271             &txq->txpkts_wrs, "# of txpkts work requests (multiple pkts/WR)");
2272         SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_pkts", CTLFLAG_RD,
2273             &txq->txpkts_pkts, "# of frames tx'd using txpkts work requests");
2274
2275         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_dmamap", CTLFLAG_RD,
2276             &txq->no_dmamap, 0, "# of times txq ran out of DMA maps");
2277         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2278             &txq->no_desc, 0, "# of times txq ran out of hardware descriptors");
2279         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "egr_update", CTLFLAG_RD,
2280             &eq->egr_update, 0, "egress update notifications from the SGE");
2281         SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2282             &eq->unstalled, 0, "# of times txq recovered after stall");
2283
2284         return (rc);
2285 }
2286
2287 static int
2288 free_txq(struct port_info *pi, struct sge_txq *txq)
2289 {
2290         int rc;
2291         struct adapter *sc = pi->adapter;
2292         struct sge_eq *eq = &txq->eq;
2293
2294         rc = free_eq(sc, eq);
2295         if (rc)
2296                 return (rc);
2297
2298         free(txq->sdesc, M_CXGBE);
2299
2300         if (txq->txmaps.maps)
2301                 t4_free_tx_maps(&txq->txmaps, txq->tx_tag);
2302
2303         buf_ring_free(txq->br, M_CXGBE);
2304
2305         if (txq->tx_tag)
2306                 bus_dma_tag_destroy(txq->tx_tag);
2307
2308         bzero(txq, sizeof(*txq));
2309         return (0);
2310 }
2311
2312 static void
2313 oneseg_dma_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2314 {
2315         bus_addr_t *ba = arg;
2316
2317         KASSERT(nseg == 1,
2318             ("%s meant for single segment mappings only.", __func__));
2319
2320         *ba = error ? 0 : segs->ds_addr;
2321 }
2322
2323 static inline bool
2324 is_new_response(const struct sge_iq *iq, struct rsp_ctrl **ctrl)
2325 {
2326         *ctrl = (void *)((uintptr_t)iq->cdesc +
2327             (iq->esize - sizeof(struct rsp_ctrl)));
2328
2329         return (((*ctrl)->u.type_gen >> S_RSPD_GEN) == iq->gen);
2330 }
2331
2332 static inline void
2333 iq_next(struct sge_iq *iq)
2334 {
2335         iq->cdesc = (void *) ((uintptr_t)iq->cdesc + iq->esize);
2336         if (__predict_false(++iq->cidx == iq->qsize - 1)) {
2337                 iq->cidx = 0;
2338                 iq->gen ^= 1;
2339                 iq->cdesc = iq->desc;
2340         }
2341 }
2342
2343 #define FL_HW_IDX(x) ((x) >> 3)
2344 static inline void
2345 ring_fl_db(struct adapter *sc, struct sge_fl *fl)
2346 {
2347         int ndesc = fl->pending / 8;
2348
2349         if (FL_HW_IDX(fl->pidx) == FL_HW_IDX(fl->cidx))
2350                 ndesc--;        /* hold back one credit */
2351
2352         if (ndesc <= 0)
2353                 return;         /* nothing to do */
2354
2355         wmb();
2356
2357         t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL), F_DBPRIO |
2358             V_QID(fl->cntxt_id) | V_PIDX(ndesc));
2359         fl->pending -= ndesc * 8;
2360 }
2361
2362 /*
2363  * Fill up the freelist by upto nbufs and maybe ring its doorbell.
2364  *
2365  * Returns non-zero to indicate that it should be added to the list of starving
2366  * freelists.
2367  */
2368 static int
2369 refill_fl(struct adapter *sc, struct sge_fl *fl, int nbufs)
2370 {
2371         __be64 *d = &fl->desc[fl->pidx];
2372         struct fl_sdesc *sd = &fl->sdesc[fl->pidx];
2373         bus_dma_tag_t tag;
2374         bus_addr_t pa;
2375         caddr_t cl;
2376         int rc;
2377
2378         FL_LOCK_ASSERT_OWNED(fl);
2379
2380         if (nbufs > fl->needed)
2381                 nbufs = fl->needed;
2382
2383         while (nbufs--) {
2384
2385                 if (sd->cl != NULL) {
2386
2387                         /*
2388                          * This happens when a frame small enough to fit
2389                          * entirely in an mbuf was received in cl last time.
2390                          * We'd held on to cl and can reuse it now.  Note that
2391                          * we reuse a cluster of the old size if fl->tag_idx is
2392                          * no longer the same as sd->tag_idx.
2393                          */
2394
2395                         KASSERT(*d == sd->ba_tag,
2396                             ("%s: recyling problem at pidx %d",
2397                             __func__, fl->pidx));
2398
2399                         d++;
2400                         goto recycled;
2401                 }
2402
2403
2404                 if (fl->tag_idx != sd->tag_idx) {
2405                         bus_dmamap_t map;
2406                         bus_dma_tag_t newtag = fl->tag[fl->tag_idx];
2407                         bus_dma_tag_t oldtag = fl->tag[sd->tag_idx];
2408
2409                         /*
2410                          * An MTU change can get us here.  Discard the old map
2411                          * which was created with the old tag, but only if
2412                          * we're able to get a new one.
2413                          */
2414                         rc = bus_dmamap_create(newtag, 0, &map);
2415                         if (rc == 0) {
2416                                 bus_dmamap_destroy(oldtag, sd->map);
2417                                 sd->map = map;
2418                                 sd->tag_idx = fl->tag_idx;
2419                         }
2420                 }
2421
2422                 tag = fl->tag[sd->tag_idx];
2423
2424                 cl = m_cljget(NULL, M_NOWAIT, FL_BUF_SIZE(sd->tag_idx));
2425                 if (cl == NULL)
2426                         break;
2427
2428                 rc = bus_dmamap_load(tag, sd->map, cl, FL_BUF_SIZE(sd->tag_idx),
2429                     oneseg_dma_callback, &pa, 0);
2430                 if (rc != 0 || pa == 0) {
2431                         fl->dmamap_failed++;
2432                         uma_zfree(FL_BUF_ZONE(sd->tag_idx), cl);
2433                         break;
2434                 }
2435
2436                 sd->cl = cl;
2437                 *d++ = htobe64(pa | sd->tag_idx);
2438
2439 #ifdef INVARIANTS
2440                 sd->ba_tag = htobe64(pa | sd->tag_idx);
2441 #endif
2442
2443 recycled:
2444                 /* sd->m is never recycled, should always be NULL */
2445                 KASSERT(sd->m == NULL, ("%s: stray mbuf", __func__));
2446
2447                 sd->m = m_gethdr(M_NOWAIT, MT_NOINIT);
2448                 if (sd->m == NULL)
2449                         break;
2450
2451                 fl->pending++;
2452                 fl->needed--;
2453                 sd++;
2454                 if (++fl->pidx == fl->cap) {
2455                         fl->pidx = 0;
2456                         sd = fl->sdesc;
2457                         d = fl->desc;
2458                 }
2459         }
2460
2461         if (fl->pending >= 8)
2462                 ring_fl_db(sc, fl);
2463
2464         return (FL_RUNNING_LOW(fl) && !(fl->flags & FL_STARVING));
2465 }
2466
2467 /*
2468  * Attempt to refill all starving freelists.
2469  */
2470 static void
2471 refill_sfl(void *arg)
2472 {
2473         struct adapter *sc = arg;
2474         struct sge_fl *fl, *fl_temp;
2475
2476         mtx_lock(&sc->sfl_lock);
2477         TAILQ_FOREACH_SAFE(fl, &sc->sfl, link, fl_temp) {
2478                 FL_LOCK(fl);
2479                 refill_fl(sc, fl, 64);
2480                 if (FL_NOT_RUNNING_LOW(fl) || fl->flags & FL_DOOMED) {
2481                         TAILQ_REMOVE(&sc->sfl, fl, link);
2482                         fl->flags &= ~FL_STARVING;
2483                 }
2484                 FL_UNLOCK(fl);
2485         }
2486
2487         if (!TAILQ_EMPTY(&sc->sfl))
2488                 callout_schedule(&sc->sfl_callout, hz / 5);
2489         mtx_unlock(&sc->sfl_lock);
2490 }
2491
2492 static int
2493 alloc_fl_sdesc(struct sge_fl *fl)
2494 {
2495         struct fl_sdesc *sd;
2496         bus_dma_tag_t tag;
2497         int i, rc;
2498
2499         FL_LOCK_ASSERT_OWNED(fl);
2500
2501         fl->sdesc = malloc(fl->cap * sizeof(struct fl_sdesc), M_CXGBE,
2502             M_ZERO | M_WAITOK);
2503
2504         tag = fl->tag[fl->tag_idx];
2505         sd = fl->sdesc;
2506         for (i = 0; i < fl->cap; i++, sd++) {
2507
2508                 sd->tag_idx = fl->tag_idx;
2509                 rc = bus_dmamap_create(tag, 0, &sd->map);
2510                 if (rc != 0)
2511                         goto failed;
2512         }
2513
2514         return (0);
2515 failed:
2516         while (--i >= 0) {
2517                 sd--;
2518                 bus_dmamap_destroy(tag, sd->map);
2519                 if (sd->m) {
2520                         m_init(sd->m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2521                         m_free(sd->m);
2522                         sd->m = NULL;
2523                 }
2524         }
2525         KASSERT(sd == fl->sdesc, ("%s: EDOOFUS", __func__));
2526
2527         free(fl->sdesc, M_CXGBE);
2528         fl->sdesc = NULL;
2529
2530         return (rc);
2531 }
2532
2533 static void
2534 free_fl_sdesc(struct sge_fl *fl)
2535 {
2536         struct fl_sdesc *sd;
2537         int i;
2538
2539         FL_LOCK_ASSERT_OWNED(fl);
2540
2541         sd = fl->sdesc;
2542         for (i = 0; i < fl->cap; i++, sd++) {
2543
2544                 if (sd->m) {
2545                         m_init(sd->m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2546                         m_free(sd->m);
2547                         sd->m = NULL;
2548                 }
2549
2550                 if (sd->cl) {
2551                         bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
2552                         uma_zfree(FL_BUF_ZONE(sd->tag_idx), sd->cl);
2553                         sd->cl = NULL;
2554                 }
2555
2556                 bus_dmamap_destroy(fl->tag[sd->tag_idx], sd->map);
2557         }
2558
2559         free(fl->sdesc, M_CXGBE);
2560         fl->sdesc = NULL;
2561 }
2562
2563 int
2564 t4_alloc_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag, int count,
2565     int flags)
2566 {
2567         struct tx_map *txm;
2568         int i, rc;
2569
2570         txmaps->map_total = txmaps->map_avail = count;
2571         txmaps->map_cidx = txmaps->map_pidx = 0;
2572
2573         txmaps->maps = malloc(count * sizeof(struct tx_map), M_CXGBE,
2574             M_ZERO | flags);
2575
2576         txm = txmaps->maps;
2577         for (i = 0; i < count; i++, txm++) {
2578                 rc = bus_dmamap_create(tx_tag, 0, &txm->map);
2579                 if (rc != 0)
2580                         goto failed;
2581         }
2582
2583         return (0);
2584 failed:
2585         while (--i >= 0) {
2586                 txm--;
2587                 bus_dmamap_destroy(tx_tag, txm->map);
2588         }
2589         KASSERT(txm == txmaps->maps, ("%s: EDOOFUS", __func__));
2590
2591         free(txmaps->maps, M_CXGBE);
2592         txmaps->maps = NULL;
2593
2594         return (rc);
2595 }
2596
2597 void
2598 t4_free_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag)
2599 {
2600         struct tx_map *txm;
2601         int i;
2602
2603         txm = txmaps->maps;
2604         for (i = 0; i < txmaps->map_total; i++, txm++) {
2605
2606                 if (txm->m) {
2607                         bus_dmamap_unload(tx_tag, txm->map);
2608                         m_freem(txm->m);
2609                         txm->m = NULL;
2610                 }
2611
2612                 bus_dmamap_destroy(tx_tag, txm->map);
2613         }
2614
2615         free(txmaps->maps, M_CXGBE);
2616         txmaps->maps = NULL;
2617 }
2618
2619 /*
2620  * We'll do immediate data tx for non-TSO, but only when not coalescing.  We're
2621  * willing to use upto 2 hardware descriptors which means a maximum of 96 bytes
2622  * of immediate data.
2623  */
2624 #define IMM_LEN ( \
2625       2 * EQ_ESIZE \
2626     - sizeof(struct fw_eth_tx_pkt_wr) \
2627     - sizeof(struct cpl_tx_pkt_core))
2628
2629 /*
2630  * Returns non-zero on failure, no need to cleanup anything in that case.
2631  *
2632  * Note 1: We always try to defrag the mbuf if required and return EFBIG only
2633  * if the resulting chain still won't fit in a tx descriptor.
2634  *
2635  * Note 2: We'll pullup the mbuf chain if TSO is requested and the first mbuf
2636  * does not have the TCP header in it.
2637  */
2638 static int
2639 get_pkt_sgl(struct sge_txq *txq, struct mbuf **fp, struct sgl *sgl,
2640     int sgl_only)
2641 {
2642         struct mbuf *m = *fp;
2643         struct tx_maps *txmaps;
2644         struct tx_map *txm;
2645         int rc, defragged = 0, n;
2646
2647         TXQ_LOCK_ASSERT_OWNED(txq);
2648
2649         if (m->m_pkthdr.tso_segsz)
2650                 sgl_only = 1;   /* Do not allow immediate data with LSO */
2651
2652 start:  sgl->nsegs = 0;
2653
2654         if (m->m_pkthdr.len <= IMM_LEN && !sgl_only)
2655                 return (0);     /* nsegs = 0 tells caller to use imm. tx */
2656
2657         txmaps = &txq->txmaps;
2658         if (txmaps->map_avail == 0) {
2659                 txq->no_dmamap++;
2660                 return (ENOMEM);
2661         }
2662         txm = &txmaps->maps[txmaps->map_pidx];
2663
2664         if (m->m_pkthdr.tso_segsz && m->m_len < 50) {
2665                 *fp = m_pullup(m, 50);
2666                 m = *fp;
2667                 if (m == NULL)
2668                         return (ENOBUFS);
2669         }
2670
2671         rc = bus_dmamap_load_mbuf_sg(txq->tx_tag, txm->map, m, sgl->seg,
2672             &sgl->nsegs, BUS_DMA_NOWAIT);
2673         if (rc == EFBIG && defragged == 0) {
2674                 m = m_defrag(m, M_DONTWAIT);
2675                 if (m == NULL)
2676                         return (EFBIG);
2677
2678                 defragged = 1;
2679                 *fp = m;
2680                 goto start;
2681         }
2682         if (rc != 0)
2683                 return (rc);
2684
2685         txm->m = m;
2686         txmaps->map_avail--;
2687         if (++txmaps->map_pidx == txmaps->map_total)
2688                 txmaps->map_pidx = 0;
2689
2690         KASSERT(sgl->nsegs > 0 && sgl->nsegs <= TX_SGL_SEGS,
2691             ("%s: bad DMA mapping (%d segments)", __func__, sgl->nsegs));
2692
2693         /*
2694          * Store the # of flits required to hold this frame's SGL in nflits.  An
2695          * SGL has a (ULPTX header + len0, addr0) tuple optionally followed by
2696          * multiple (len0 + len1, addr0, addr1) tuples.  If addr1 is not used
2697          * then len1 must be set to 0.
2698          */
2699         n = sgl->nsegs - 1;
2700         sgl->nflits = (3 * n) / 2 + (n & 1) + 2;
2701
2702         return (0);
2703 }
2704
2705
2706 /*
2707  * Releases all the txq resources used up in the specified sgl.
2708  */
2709 static int
2710 free_pkt_sgl(struct sge_txq *txq, struct sgl *sgl)
2711 {
2712         struct tx_maps *txmaps;
2713         struct tx_map *txm;
2714
2715         TXQ_LOCK_ASSERT_OWNED(txq);
2716
2717         if (sgl->nsegs == 0)
2718                 return (0);     /* didn't use any map */
2719
2720         txmaps = &txq->txmaps;
2721
2722         /* 1 pkt uses exactly 1 map, back it out */
2723
2724         txmaps->map_avail++;
2725         if (txmaps->map_pidx > 0)
2726                 txmaps->map_pidx--;
2727         else
2728                 txmaps->map_pidx = txmaps->map_total - 1;
2729
2730         txm = &txmaps->maps[txmaps->map_pidx];
2731         bus_dmamap_unload(txq->tx_tag, txm->map);
2732         txm->m = NULL;
2733
2734         return (0);
2735 }
2736
2737 static int
2738 write_txpkt_wr(struct port_info *pi, struct sge_txq *txq, struct mbuf *m,
2739     struct sgl *sgl)
2740 {
2741         struct sge_eq *eq = &txq->eq;
2742         struct fw_eth_tx_pkt_wr *wr;
2743         struct cpl_tx_pkt_core *cpl;
2744         uint32_t ctrl;  /* used in many unrelated places */
2745         uint64_t ctrl1;
2746         int nflits, ndesc, pktlen;
2747         struct tx_sdesc *txsd;
2748         caddr_t dst;
2749
2750         TXQ_LOCK_ASSERT_OWNED(txq);
2751
2752         pktlen = m->m_pkthdr.len;
2753
2754         /*
2755          * Do we have enough flits to send this frame out?
2756          */
2757         ctrl = sizeof(struct cpl_tx_pkt_core);
2758         if (m->m_pkthdr.tso_segsz) {
2759                 nflits = TXPKT_LSO_WR_HDR;
2760                 ctrl += sizeof(struct cpl_tx_pkt_lso);
2761         } else
2762                 nflits = TXPKT_WR_HDR;
2763         if (sgl->nsegs > 0)
2764                 nflits += sgl->nflits;
2765         else {
2766                 nflits += howmany(pktlen, 8);
2767                 ctrl += pktlen;
2768         }
2769         ndesc = howmany(nflits, 8);
2770         if (ndesc > eq->avail)
2771                 return (ENOMEM);
2772
2773         /* Firmware work request header */
2774         wr = (void *)&eq->desc[eq->pidx];
2775         wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
2776             V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));
2777         ctrl = V_FW_WR_LEN16(howmany(nflits, 2));
2778         if (eq->avail == ndesc) {
2779                 if (!(eq->flags & EQ_CRFLUSHED)) {
2780                         ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
2781                         eq->flags |= EQ_CRFLUSHED;
2782                 }
2783                 eq->flags |= EQ_STALLED;
2784         }
2785
2786         wr->equiq_to_len16 = htobe32(ctrl);
2787         wr->r3 = 0;
2788
2789         if (m->m_pkthdr.tso_segsz) {
2790                 struct cpl_tx_pkt_lso *lso = (void *)(wr + 1);
2791                 struct ether_header *eh;
2792                 struct ip *ip;
2793                 struct tcphdr *tcp;
2794
2795                 ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) | F_LSO_FIRST_SLICE |
2796                     F_LSO_LAST_SLICE;
2797
2798                 eh = mtod(m, struct ether_header *);
2799                 if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
2800                         ctrl |= V_LSO_ETHHDR_LEN(1);
2801                         ip = (void *)((struct ether_vlan_header *)eh + 1);
2802                 } else
2803                         ip = (void *)(eh + 1);
2804
2805                 tcp = (void *)((uintptr_t)ip + ip->ip_hl * 4);
2806                 ctrl |= V_LSO_IPHDR_LEN(ip->ip_hl) |
2807                     V_LSO_TCPHDR_LEN(tcp->th_off);
2808
2809                 lso->lso_ctrl = htobe32(ctrl);
2810                 lso->ipid_ofst = htobe16(0);
2811                 lso->mss = htobe16(m->m_pkthdr.tso_segsz);
2812                 lso->seqno_offset = htobe32(0);
2813                 lso->len = htobe32(pktlen);
2814
2815                 cpl = (void *)(lso + 1);
2816
2817                 txq->tso_wrs++;
2818         } else
2819                 cpl = (void *)(wr + 1);
2820
2821         /* Checksum offload */
2822         ctrl1 = 0;
2823         if (!(m->m_pkthdr.csum_flags & CSUM_IP))
2824                 ctrl1 |= F_TXPKT_IPCSUM_DIS;
2825         if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP)))
2826                 ctrl1 |= F_TXPKT_L4CSUM_DIS;
2827         if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP))
2828                 txq->txcsum++;  /* some hardware assistance provided */
2829
2830         /* VLAN tag insertion */
2831         if (m->m_flags & M_VLANTAG) {
2832                 ctrl1 |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
2833                 txq->vlan_insertion++;
2834         }
2835
2836         /* CPL header */
2837         cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
2838             V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
2839         cpl->pack = 0;
2840         cpl->len = htobe16(pktlen);
2841         cpl->ctrl1 = htobe64(ctrl1);
2842
2843         /* Software descriptor */
2844         txsd = &txq->sdesc[eq->pidx];
2845         txsd->desc_used = ndesc;
2846
2847         eq->pending += ndesc;
2848         eq->avail -= ndesc;
2849         eq->pidx += ndesc;
2850         if (eq->pidx >= eq->cap)
2851                 eq->pidx -= eq->cap;
2852
2853         /* SGL */
2854         dst = (void *)(cpl + 1);
2855         if (sgl->nsegs > 0) {
2856                 txsd->credits = 1;
2857                 txq->sgl_wrs++;
2858                 write_sgl_to_txd(eq, sgl, &dst);
2859         } else {
2860                 txsd->credits = 0;
2861                 txq->imm_wrs++;
2862                 for (; m; m = m->m_next) {
2863                         copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
2864 #ifdef INVARIANTS
2865                         pktlen -= m->m_len;
2866 #endif
2867                 }
2868 #ifdef INVARIANTS
2869                 KASSERT(pktlen == 0, ("%s: %d bytes left.", __func__, pktlen));
2870 #endif
2871
2872         }
2873
2874         txq->txpkt_wrs++;
2875         return (0);
2876 }
2877
2878 /*
2879  * Returns 0 to indicate that m has been accepted into a coalesced tx work
2880  * request.  It has either been folded into txpkts or txpkts was flushed and m
2881  * has started a new coalesced work request (as the first frame in a fresh
2882  * txpkts).
2883  *
2884  * Returns non-zero to indicate a failure - caller is responsible for
2885  * transmitting m, if there was anything in txpkts it has been flushed.
2886  */
2887 static int
2888 add_to_txpkts(struct port_info *pi, struct sge_txq *txq, struct txpkts *txpkts,
2889     struct mbuf *m, struct sgl *sgl)
2890 {
2891         struct sge_eq *eq = &txq->eq;
2892         int can_coalesce;
2893         struct tx_sdesc *txsd;
2894         int flits;
2895
2896         TXQ_LOCK_ASSERT_OWNED(txq);
2897
2898         KASSERT(sgl->nsegs, ("%s: can't coalesce imm data", __func__));
2899
2900         if (txpkts->npkt > 0) {
2901                 flits = TXPKTS_PKT_HDR + sgl->nflits;
2902                 can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
2903                     txpkts->nflits + flits <= TX_WR_FLITS &&
2904                     txpkts->nflits + flits <= eq->avail * 8 &&
2905                     txpkts->plen + m->m_pkthdr.len < 65536;
2906
2907                 if (can_coalesce) {
2908                         txpkts->npkt++;
2909                         txpkts->nflits += flits;
2910                         txpkts->plen += m->m_pkthdr.len;
2911
2912                         txsd = &txq->sdesc[eq->pidx];
2913                         txsd->credits++;
2914
2915                         return (0);
2916                 }
2917
2918                 /*
2919                  * Couldn't coalesce m into txpkts.  The first order of business
2920                  * is to send txpkts on its way.  Then we'll revisit m.
2921                  */
2922                 write_txpkts_wr(txq, txpkts);
2923         }
2924
2925         /*
2926          * Check if we can start a new coalesced tx work request with m as
2927          * the first packet in it.
2928          */
2929
2930         KASSERT(txpkts->npkt == 0, ("%s: txpkts not empty", __func__));
2931
2932         flits = TXPKTS_WR_HDR + sgl->nflits;
2933         can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
2934             flits <= eq->avail * 8 && flits <= TX_WR_FLITS;
2935
2936         if (can_coalesce == 0)
2937                 return (EINVAL);
2938
2939         /*
2940          * Start a fresh coalesced tx WR with m as the first frame in it.
2941          */
2942         txpkts->npkt = 1;
2943         txpkts->nflits = flits;
2944         txpkts->flitp = &eq->desc[eq->pidx].flit[2];
2945         txpkts->plen = m->m_pkthdr.len;
2946
2947         txsd = &txq->sdesc[eq->pidx];
2948         txsd->credits = 1;
2949
2950         return (0);
2951 }
2952
2953 /*
2954  * Note that write_txpkts_wr can never run out of hardware descriptors (but
2955  * write_txpkt_wr can).  add_to_txpkts ensures that a frame is accepted for
2956  * coalescing only if sufficient hardware descriptors are available.
2957  */
2958 static void
2959 write_txpkts_wr(struct sge_txq *txq, struct txpkts *txpkts)
2960 {
2961         struct sge_eq *eq = &txq->eq;
2962         struct fw_eth_tx_pkts_wr *wr;
2963         struct tx_sdesc *txsd;
2964         uint32_t ctrl;
2965         int ndesc;
2966
2967         TXQ_LOCK_ASSERT_OWNED(txq);
2968
2969         ndesc = howmany(txpkts->nflits, 8);
2970
2971         wr = (void *)&eq->desc[eq->pidx];
2972         wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
2973         ctrl = V_FW_WR_LEN16(howmany(txpkts->nflits, 2));
2974         if (eq->avail == ndesc) {
2975                 if (!(eq->flags & EQ_CRFLUSHED)) {
2976                         ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
2977                         eq->flags |= EQ_CRFLUSHED;
2978                 }
2979                 eq->flags |= EQ_STALLED;
2980         }
2981         wr->equiq_to_len16 = htobe32(ctrl);
2982         wr->plen = htobe16(txpkts->plen);
2983         wr->npkt = txpkts->npkt;
2984         wr->r3 = wr->type = 0;
2985
2986         /* Everything else already written */
2987
2988         txsd = &txq->sdesc[eq->pidx];
2989         txsd->desc_used = ndesc;
2990
2991         KASSERT(eq->avail >= ndesc, ("%s: out of descriptors", __func__));
2992
2993         eq->pending += ndesc;
2994         eq->avail -= ndesc;
2995         eq->pidx += ndesc;
2996         if (eq->pidx >= eq->cap)
2997                 eq->pidx -= eq->cap;
2998
2999         txq->txpkts_pkts += txpkts->npkt;
3000         txq->txpkts_wrs++;
3001         txpkts->npkt = 0;       /* emptied */
3002 }
3003
3004 static inline void
3005 write_ulp_cpl_sgl(struct port_info *pi, struct sge_txq *txq,
3006     struct txpkts *txpkts, struct mbuf *m, struct sgl *sgl)
3007 {
3008         struct ulp_txpkt *ulpmc;
3009         struct ulptx_idata *ulpsc;
3010         struct cpl_tx_pkt_core *cpl;
3011         struct sge_eq *eq = &txq->eq;
3012         uintptr_t flitp, start, end;
3013         uint64_t ctrl;
3014         caddr_t dst;
3015
3016         KASSERT(txpkts->npkt > 0, ("%s: txpkts is empty", __func__));
3017
3018         start = (uintptr_t)eq->desc;
3019         end = (uintptr_t)eq->spg;
3020
3021         /* Checksum offload */
3022         ctrl = 0;
3023         if (!(m->m_pkthdr.csum_flags & CSUM_IP))
3024                 ctrl |= F_TXPKT_IPCSUM_DIS;
3025         if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP)))
3026                 ctrl |= F_TXPKT_L4CSUM_DIS;
3027         if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP))
3028                 txq->txcsum++;  /* some hardware assistance provided */
3029
3030         /* VLAN tag insertion */
3031         if (m->m_flags & M_VLANTAG) {
3032                 ctrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3033                 txq->vlan_insertion++;
3034         }
3035
3036         /*
3037          * The previous packet's SGL must have ended at a 16 byte boundary (this
3038          * is required by the firmware/hardware).  It follows that flitp cannot
3039          * wrap around between the ULPTX master command and ULPTX subcommand (8
3040          * bytes each), and that it can not wrap around in the middle of the
3041          * cpl_tx_pkt_core either.
3042          */
3043         flitp = (uintptr_t)txpkts->flitp;
3044         KASSERT((flitp & 0xf) == 0,
3045             ("%s: last SGL did not end at 16 byte boundary: %p",
3046             __func__, txpkts->flitp));
3047
3048         /* ULP master command */
3049         ulpmc = (void *)flitp;
3050         ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0) |
3051             V_ULP_TXPKT_FID(eq->iqid));
3052         ulpmc->len = htonl(howmany(sizeof(*ulpmc) + sizeof(*ulpsc) +
3053             sizeof(*cpl) + 8 * sgl->nflits, 16));
3054
3055         /* ULP subcommand */
3056         ulpsc = (void *)(ulpmc + 1);
3057         ulpsc->cmd_more = htobe32(V_ULPTX_CMD((u32)ULP_TX_SC_IMM) |
3058             F_ULP_TX_SC_MORE);
3059         ulpsc->len = htobe32(sizeof(struct cpl_tx_pkt_core));
3060
3061         flitp += sizeof(*ulpmc) + sizeof(*ulpsc);
3062         if (flitp == end)
3063                 flitp = start;
3064
3065         /* CPL_TX_PKT */
3066         cpl = (void *)flitp;
3067         cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3068             V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3069         cpl->pack = 0;
3070         cpl->len = htobe16(m->m_pkthdr.len);
3071         cpl->ctrl1 = htobe64(ctrl);
3072
3073         flitp += sizeof(*cpl);
3074         if (flitp == end)
3075                 flitp = start;
3076
3077         /* SGL for this frame */
3078         dst = (caddr_t)flitp;
3079         txpkts->nflits += write_sgl_to_txd(eq, sgl, &dst);
3080         txpkts->flitp = (void *)dst;
3081
3082         KASSERT(((uintptr_t)dst & 0xf) == 0,
3083             ("%s: SGL ends at %p (not a 16 byte boundary)", __func__, dst));
3084 }
3085
3086 /*
3087  * If the SGL ends on an address that is not 16 byte aligned, this function will
3088  * add a 0 filled flit at the end.  It returns 1 in that case.
3089  */
3090 static int
3091 write_sgl_to_txd(struct sge_eq *eq, struct sgl *sgl, caddr_t *to)
3092 {
3093         __be64 *flitp, *end;
3094         struct ulptx_sgl *usgl;
3095         bus_dma_segment_t *seg;
3096         int i, padded;
3097
3098         KASSERT(sgl->nsegs > 0 && sgl->nflits > 0,
3099             ("%s: bad SGL - nsegs=%d, nflits=%d",
3100             __func__, sgl->nsegs, sgl->nflits));
3101
3102         KASSERT(((uintptr_t)(*to) & 0xf) == 0,
3103             ("%s: SGL must start at a 16 byte boundary: %p", __func__, *to));
3104
3105         flitp = (__be64 *)(*to);
3106         end = flitp + sgl->nflits;
3107         seg = &sgl->seg[0];
3108         usgl = (void *)flitp;
3109
3110         /*
3111          * We start at a 16 byte boundary somewhere inside the tx descriptor
3112          * ring, so we're at least 16 bytes away from the status page.  There is
3113          * no chance of a wrap around in the middle of usgl (which is 16 bytes).
3114          */
3115
3116         usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
3117             V_ULPTX_NSGE(sgl->nsegs));
3118         usgl->len0 = htobe32(seg->ds_len);
3119         usgl->addr0 = htobe64(seg->ds_addr);
3120         seg++;
3121
3122         if ((uintptr_t)end <= (uintptr_t)eq->spg) {
3123
3124                 /* Won't wrap around at all */
3125
3126                 for (i = 0; i < sgl->nsegs - 1; i++, seg++) {
3127                         usgl->sge[i / 2].len[i & 1] = htobe32(seg->ds_len);
3128                         usgl->sge[i / 2].addr[i & 1] = htobe64(seg->ds_addr);
3129                 }
3130                 if (i & 1)
3131                         usgl->sge[i / 2].len[1] = htobe32(0);
3132         } else {
3133
3134                 /* Will wrap somewhere in the rest of the SGL */
3135
3136                 /* 2 flits already written, write the rest flit by flit */
3137                 flitp = (void *)(usgl + 1);
3138                 for (i = 0; i < sgl->nflits - 2; i++) {
3139                         if ((uintptr_t)flitp == (uintptr_t)eq->spg)
3140                                 flitp = (void *)eq->desc;
3141                         *flitp++ = get_flit(seg, sgl->nsegs - 1, i);
3142                 }
3143                 end = flitp;
3144         }
3145
3146         if ((uintptr_t)end & 0xf) {
3147                 *(uint64_t *)end = 0;
3148                 end++;
3149                 padded = 1;
3150         } else
3151                 padded = 0;
3152
3153         if ((uintptr_t)end == (uintptr_t)eq->spg)
3154                 *to = (void *)eq->desc;
3155         else
3156                 *to = (void *)end;
3157
3158         return (padded);
3159 }
3160
3161 static inline void
3162 copy_to_txd(struct sge_eq *eq, caddr_t from, caddr_t *to, int len)
3163 {
3164         if (__predict_true((uintptr_t)(*to) + len <= (uintptr_t)eq->spg)) {
3165                 bcopy(from, *to, len);
3166                 (*to) += len;
3167         } else {
3168                 int portion = (uintptr_t)eq->spg - (uintptr_t)(*to);
3169
3170                 bcopy(from, *to, portion);
3171                 from += portion;
3172                 portion = len - portion;        /* remaining */
3173                 bcopy(from, (void *)eq->desc, portion);
3174                 (*to) = (caddr_t)eq->desc + portion;
3175         }
3176 }
3177
3178 static inline void
3179 ring_eq_db(struct adapter *sc, struct sge_eq *eq)
3180 {
3181         wmb();
3182         t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL),
3183             V_QID(eq->cntxt_id) | V_PIDX(eq->pending));
3184         eq->pending = 0;
3185 }
3186
3187 static inline int
3188 reclaimable(struct sge_eq *eq)
3189 {
3190         unsigned int cidx;
3191
3192         cidx = eq->spg->cidx;   /* stable snapshot */
3193         cidx = be16toh(cidx);
3194
3195         if (cidx >= eq->cidx)
3196                 return (cidx - eq->cidx);
3197         else
3198                 return (cidx + eq->cap - eq->cidx);
3199 }
3200
3201 /*
3202  * There are "can_reclaim" tx descriptors ready to be reclaimed.  Reclaim as
3203  * many as possible but stop when there are around "n" mbufs to free.
3204  *
3205  * The actual number reclaimed is provided as the return value.
3206  */
3207 static int
3208 reclaim_tx_descs(struct sge_txq *txq, int can_reclaim, int n)
3209 {
3210         struct tx_sdesc *txsd;
3211         struct tx_maps *txmaps;
3212         struct tx_map *txm;
3213         unsigned int reclaimed, maps;
3214         struct sge_eq *eq = &txq->eq;
3215
3216         TXQ_LOCK_ASSERT_OWNED(txq);
3217
3218         if (can_reclaim == 0)
3219                 can_reclaim = reclaimable(eq);
3220
3221         maps = reclaimed = 0;
3222         while (can_reclaim && maps < n) {
3223                 int ndesc;
3224
3225                 txsd = &txq->sdesc[eq->cidx];
3226                 ndesc = txsd->desc_used;
3227
3228                 /* Firmware doesn't return "partial" credits. */
3229                 KASSERT(can_reclaim >= ndesc,
3230                     ("%s: unexpected number of credits: %d, %d",
3231                     __func__, can_reclaim, ndesc));
3232
3233                 maps += txsd->credits;
3234
3235                 reclaimed += ndesc;
3236                 can_reclaim -= ndesc;
3237
3238                 eq->cidx += ndesc;
3239                 if (__predict_false(eq->cidx >= eq->cap))
3240                         eq->cidx -= eq->cap;
3241         }
3242
3243         txmaps = &txq->txmaps;
3244         txm = &txmaps->maps[txmaps->map_cidx];
3245         if (maps)
3246                 prefetch(txm->m);
3247
3248         eq->avail += reclaimed;
3249         KASSERT(eq->avail < eq->cap,    /* avail tops out at (cap - 1) */
3250             ("%s: too many descriptors available", __func__));
3251
3252         txmaps->map_avail += maps;
3253         KASSERT(txmaps->map_avail <= txmaps->map_total,
3254             ("%s: too many maps available", __func__));
3255
3256         while (maps--) {
3257                 struct tx_map *next;
3258
3259                 next = txm + 1;
3260                 if (__predict_false(txmaps->map_cidx + 1 == txmaps->map_total))
3261                         next = txmaps->maps;
3262                 prefetch(next->m);
3263
3264                 bus_dmamap_unload(txq->tx_tag, txm->map);
3265                 m_freem(txm->m);
3266                 txm->m = NULL;
3267
3268                 txm = next;
3269                 if (__predict_false(++txmaps->map_cidx == txmaps->map_total))
3270                         txmaps->map_cidx = 0;
3271         }
3272
3273         return (reclaimed);
3274 }
3275
3276 static void
3277 write_eqflush_wr(struct sge_eq *eq)
3278 {
3279         struct fw_eq_flush_wr *wr;
3280
3281         EQ_LOCK_ASSERT_OWNED(eq);
3282         KASSERT(eq->avail > 0, ("%s: no descriptors left.", __func__));
3283         KASSERT(!(eq->flags & EQ_CRFLUSHED), ("%s: flushed already", __func__));
3284
3285         wr = (void *)&eq->desc[eq->pidx];
3286         bzero(wr, sizeof(*wr));
3287         wr->opcode = FW_EQ_FLUSH_WR;
3288         wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(sizeof(*wr) / 16) |
3289             F_FW_WR_EQUEQ | F_FW_WR_EQUIQ);
3290
3291         eq->flags |= (EQ_CRFLUSHED | EQ_STALLED);
3292         eq->pending++;
3293         eq->avail--;
3294         if (++eq->pidx == eq->cap)
3295                 eq->pidx = 0; 
3296 }
3297
3298 static __be64
3299 get_flit(bus_dma_segment_t *sgl, int nsegs, int idx)
3300 {
3301         int i = (idx / 3) * 2;
3302
3303         switch (idx % 3) {
3304         case 0: {
3305                 __be64 rc;
3306
3307                 rc = htobe32(sgl[i].ds_len);
3308                 if (i + 1 < nsegs)
3309                         rc |= (uint64_t)htobe32(sgl[i + 1].ds_len) << 32;
3310
3311                 return (rc);
3312         }
3313         case 1:
3314                 return htobe64(sgl[i].ds_addr);
3315         case 2:
3316                 return htobe64(sgl[i + 1].ds_addr);
3317         }
3318
3319         return (0);
3320 }
3321
3322 static void
3323 set_fl_tag_idx(struct sge_fl *fl, int bufsize)
3324 {
3325         int i;
3326
3327         for (i = 0; i < FL_BUF_SIZES - 1; i++) {
3328                 if (FL_BUF_SIZE(i) >= bufsize)
3329                         break;
3330         }
3331
3332         fl->tag_idx = i;
3333 }
3334
3335 static void
3336 add_fl_to_sfl(struct adapter *sc, struct sge_fl *fl)
3337 {
3338         mtx_lock(&sc->sfl_lock);
3339         FL_LOCK(fl);
3340         if ((fl->flags & FL_DOOMED) == 0) {
3341                 fl->flags |= FL_STARVING;
3342                 TAILQ_INSERT_TAIL(&sc->sfl, fl, link);
3343                 callout_reset(&sc->sfl_callout, hz / 5, refill_sfl, sc);
3344         }
3345         FL_UNLOCK(fl);
3346         mtx_unlock(&sc->sfl_lock);
3347 }
3348
3349 static int
3350 handle_sge_egr_update(struct sge_iq *iq, const struct rss_header *rss,
3351     struct mbuf *m)
3352 {
3353         const struct cpl_sge_egr_update *cpl = (const void *)(rss + 1);
3354         unsigned int qid = G_EGR_QID(ntohl(cpl->opcode_qid));
3355         struct adapter *sc = iq->adapter;
3356         struct sge *s = &sc->sge;
3357         struct sge_eq *eq;
3358
3359         KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
3360             rss->opcode));
3361
3362         eq = s->eqmap[qid - s->eq_start];
3363         EQ_LOCK(eq);
3364         KASSERT(eq->flags & EQ_CRFLUSHED,
3365             ("%s: unsolicited egress update", __func__));
3366         eq->flags &= ~EQ_CRFLUSHED;
3367         eq->egr_update++;
3368
3369         if (__predict_false(eq->flags & EQ_DOOMED))
3370                 wakeup_one(eq);
3371         else if (eq->flags & EQ_STALLED && can_resume_tx(eq))
3372                 taskqueue_enqueue(sc->tq[eq->tx_chan], &eq->tx_task);
3373         EQ_UNLOCK(eq);
3374
3375         return (0);
3376 }
3377
3378 static int
3379 handle_fw_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
3380 {
3381         const struct cpl_fw6_msg *cpl = (const void *)(rss + 1);
3382
3383         KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
3384             rss->opcode));
3385
3386         if (cpl->type == FW6_TYPE_CMD_RPL)
3387                 t4_handle_fw_rpl(iq->adapter, cpl->data);
3388
3389         return (0);
3390 }
3391
3392 static int
3393 sysctl_uint16(SYSCTL_HANDLER_ARGS)
3394 {
3395         uint16_t *id = arg1;
3396         int i = *id;
3397
3398         return sysctl_handle_int(oidp, &i, 0, req);
3399 }