3c62d03e17b665c263a212af2f4431fb59b50885
[dpdk.git] / drivers / net / cxgbe / sge.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2014-2015 Chelsio Communications.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Chelsio Communications nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <sys/queue.h>
35 #include <stdio.h>
36 #include <errno.h>
37 #include <stdint.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <stdarg.h>
41 #include <inttypes.h>
42 #include <netinet/in.h>
43
44 #include <rte_byteorder.h>
45 #include <rte_common.h>
46 #include <rte_cycles.h>
47 #include <rte_interrupts.h>
48 #include <rte_log.h>
49 #include <rte_debug.h>
50 #include <rte_pci.h>
51 #include <rte_atomic.h>
52 #include <rte_branch_prediction.h>
53 #include <rte_memory.h>
54 #include <rte_memzone.h>
55 #include <rte_tailq.h>
56 #include <rte_eal.h>
57 #include <rte_alarm.h>
58 #include <rte_ether.h>
59 #include <rte_ethdev.h>
60 #include <rte_atomic.h>
61 #include <rte_malloc.h>
62 #include <rte_random.h>
63 #include <rte_dev.h>
64
65 #include "common.h"
66 #include "t4_regs.h"
67 #include "t4_msg.h"
68 #include "cxgbe.h"
69
70 static inline void ship_tx_pkt_coalesce_wr(struct adapter *adap,
71                                            struct sge_eth_txq *txq);
72
73 /*
74  * Max number of Rx buffers we replenish at a time.
75  */
76 #define MAX_RX_REFILL 64U
77
78 #define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
79
80 /*
81  * Max Tx descriptor space we allow for an Ethernet packet to be inlined
82  * into a WR.
83  */
84 #define MAX_IMM_TX_PKT_LEN 256
85
86 /*
87  * Rx buffer sizes for "usembufs" Free List buffers (one ingress packet
88  * per mbuf buffer).  We currently only support two sizes for 1500- and
89  * 9000-byte MTUs. We could easily support more but there doesn't seem to be
90  * much need for that ...
91  */
92 #define FL_MTU_SMALL 1500
93 #define FL_MTU_LARGE 9000
94
95 static inline unsigned int fl_mtu_bufsize(struct adapter *adapter,
96                                           unsigned int mtu)
97 {
98         struct sge *s = &adapter->sge;
99
100         return CXGBE_ALIGN(s->pktshift + ETHER_HDR_LEN + VLAN_HLEN + mtu,
101                            s->fl_align);
102 }
103
104 #define FL_MTU_SMALL_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_SMALL)
105 #define FL_MTU_LARGE_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_LARGE)
106
107 /*
108  * Bits 0..3 of rx_sw_desc.dma_addr have special meaning.  The hardware uses
109  * these to specify the buffer size as an index into the SGE Free List Buffer
110  * Size register array.  We also use bit 4, when the buffer has been unmapped
111  * for DMA, but this is of course never sent to the hardware and is only used
112  * to prevent double unmappings.  All of the above requires that the Free List
113  * Buffers which we allocate have the bottom 5 bits free (0) -- i.e. are
114  * 32-byte or or a power of 2 greater in alignment.  Since the SGE's minimal
115  * Free List Buffer alignment is 32 bytes, this works out for us ...
116  */
117 enum {
118         RX_BUF_FLAGS     = 0x1f,   /* bottom five bits are special */
119         RX_BUF_SIZE      = 0x0f,   /* bottom three bits are for buf sizes */
120         RX_UNMAPPED_BUF  = 0x10,   /* buffer is not mapped */
121
122         /*
123          * XXX We shouldn't depend on being able to use these indices.
124          * XXX Especially when some other Master PF has initialized the
125          * XXX adapter or we use the Firmware Configuration File.  We
126          * XXX should really search through the Host Buffer Size register
127          * XXX array for the appropriately sized buffer indices.
128          */
129         RX_SMALL_PG_BUF  = 0x0,   /* small (PAGE_SIZE) page buffer */
130         RX_LARGE_PG_BUF  = 0x1,   /* buffer large page buffer */
131
132         RX_SMALL_MTU_BUF = 0x2,   /* small MTU buffer */
133         RX_LARGE_MTU_BUF = 0x3,   /* large MTU buffer */
134 };
135
136 /**
137  * txq_avail - return the number of available slots in a Tx queue
138  * @q: the Tx queue
139  *
140  * Returns the number of descriptors in a Tx queue available to write new
141  * packets.
142  */
143 static inline unsigned int txq_avail(const struct sge_txq *q)
144 {
145         return q->size - 1 - q->in_use;
146 }
147
148 static int map_mbuf(struct rte_mbuf *mbuf, dma_addr_t *addr)
149 {
150         struct rte_mbuf *m = mbuf;
151
152         for (; m; m = m->next, addr++) {
153                 *addr = m->buf_physaddr + rte_pktmbuf_headroom(m);
154                 if (*addr == 0)
155                         goto out_err;
156         }
157         return 0;
158
159 out_err:
160         return -ENOMEM;
161 }
162
163 /**
164  * free_tx_desc - reclaims Tx descriptors and their buffers
165  * @q: the Tx queue to reclaim descriptors from
166  * @n: the number of descriptors to reclaim
167  *
168  * Reclaims Tx descriptors from an SGE Tx queue and frees the associated
169  * Tx buffers.  Called with the Tx queue lock held.
170  */
171 static void free_tx_desc(struct sge_txq *q, unsigned int n)
172 {
173         struct tx_sw_desc *d;
174         unsigned int cidx = 0;
175
176         d = &q->sdesc[cidx];
177         while (n--) {
178                 if (d->mbuf) {                       /* an SGL is present */
179                         rte_pktmbuf_free(d->mbuf);
180                         d->mbuf = NULL;
181                 }
182                 if (d->coalesce.idx) {
183                         int i;
184
185                         for (i = 0; i < d->coalesce.idx; i++) {
186                                 rte_pktmbuf_free(d->coalesce.mbuf[i]);
187                                 d->coalesce.mbuf[i] = NULL;
188                         }
189                         d->coalesce.idx = 0;
190                 }
191                 ++d;
192                 if (++cidx == q->size) {
193                         cidx = 0;
194                         d = q->sdesc;
195                 }
196                 RTE_MBUF_PREFETCH_TO_FREE(&q->sdesc->mbuf->pool);
197         }
198 }
199
200 static void reclaim_tx_desc(struct sge_txq *q, unsigned int n)
201 {
202         struct tx_sw_desc *d;
203         unsigned int cidx = q->cidx;
204
205         d = &q->sdesc[cidx];
206         while (n--) {
207                 if (d->mbuf) {                       /* an SGL is present */
208                         rte_pktmbuf_free(d->mbuf);
209                         d->mbuf = NULL;
210                 }
211                 ++d;
212                 if (++cidx == q->size) {
213                         cidx = 0;
214                         d = q->sdesc;
215                 }
216         }
217         q->cidx = cidx;
218 }
219
220 /**
221  * fl_cap - return the capacity of a free-buffer list
222  * @fl: the FL
223  *
224  * Returns the capacity of a free-buffer list.  The capacity is less than
225  * the size because one descriptor needs to be left unpopulated, otherwise
226  * HW will think the FL is empty.
227  */
228 static inline unsigned int fl_cap(const struct sge_fl *fl)
229 {
230         return fl->size - 8;   /* 1 descriptor = 8 buffers */
231 }
232
233 /**
234  * fl_starving - return whether a Free List is starving.
235  * @adapter: pointer to the adapter
236  * @fl: the Free List
237  *
238  * Tests specified Free List to see whether the number of buffers
239  * available to the hardware has falled below our "starvation"
240  * threshold.
241  */
242 static inline bool fl_starving(const struct adapter *adapter,
243                                const struct sge_fl *fl)
244 {
245         const struct sge *s = &adapter->sge;
246
247         return fl->avail - fl->pend_cred <= s->fl_starve_thres;
248 }
249
250 static inline unsigned int get_buf_size(struct adapter *adapter,
251                                         const struct rx_sw_desc *d)
252 {
253         unsigned int rx_buf_size_idx = d->dma_addr & RX_BUF_SIZE;
254         unsigned int buf_size = 0;
255
256         switch (rx_buf_size_idx) {
257         case RX_SMALL_MTU_BUF:
258                 buf_size = FL_MTU_SMALL_BUFSIZE(adapter);
259                 break;
260
261         case RX_LARGE_MTU_BUF:
262                 buf_size = FL_MTU_LARGE_BUFSIZE(adapter);
263                 break;
264
265         default:
266                 BUG_ON(1);
267                 /* NOT REACHED */
268         }
269
270         return buf_size;
271 }
272
273 /**
274  * free_rx_bufs - free the Rx buffers on an SGE free list
275  * @q: the SGE free list to free buffers from
276  * @n: how many buffers to free
277  *
278  * Release the next @n buffers on an SGE free-buffer Rx queue.   The
279  * buffers must be made inaccessible to HW before calling this function.
280  */
281 static void free_rx_bufs(struct sge_fl *q, int n)
282 {
283         unsigned int cidx = q->cidx;
284         struct rx_sw_desc *d;
285
286         d = &q->sdesc[cidx];
287         while (n--) {
288                 if (d->buf) {
289                         rte_pktmbuf_free(d->buf);
290                         d->buf = NULL;
291                 }
292                 ++d;
293                 if (++cidx == q->size) {
294                         cidx = 0;
295                         d = q->sdesc;
296                 }
297                 q->avail--;
298         }
299         q->cidx = cidx;
300 }
301
302 /**
303  * unmap_rx_buf - unmap the current Rx buffer on an SGE free list
304  * @q: the SGE free list
305  *
306  * Unmap the current buffer on an SGE free-buffer Rx queue.   The
307  * buffer must be made inaccessible to HW before calling this function.
308  *
309  * This is similar to @free_rx_bufs above but does not free the buffer.
310  * Do note that the FL still loses any further access to the buffer.
311  */
312 static void unmap_rx_buf(struct sge_fl *q)
313 {
314         if (++q->cidx == q->size)
315                 q->cidx = 0;
316         q->avail--;
317 }
318
319 static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
320 {
321         if (q->pend_cred >= 64) {
322                 u32 val = adap->params.arch.sge_fl_db;
323
324                 if (is_t4(adap->params.chip))
325                         val |= V_PIDX(q->pend_cred / 8);
326                 else
327                         val |= V_PIDX_T5(q->pend_cred / 8);
328
329                 /*
330                  * Make sure all memory writes to the Free List queue are
331                  * committed before we tell the hardware about them.
332                  */
333                 wmb();
334
335                 /*
336                  * If we don't have access to the new User Doorbell (T5+), use
337                  * the old doorbell mechanism; otherwise use the new BAR2
338                  * mechanism.
339                  */
340                 if (unlikely(!q->bar2_addr)) {
341                         t4_write_reg(adap, MYPF_REG(A_SGE_PF_KDOORBELL),
342                                      val | V_QID(q->cntxt_id));
343                 } else {
344                         writel(val | V_QID(q->bar2_qid),
345                                (void *)((uintptr_t)q->bar2_addr +
346                                SGE_UDB_KDOORBELL));
347
348                         /*
349                          * This Write memory Barrier will force the write to
350                          * the User Doorbell area to be flushed.
351                          */
352                         wmb();
353                 }
354                 q->pend_cred &= 7;
355         }
356 }
357
358 static inline void set_rx_sw_desc(struct rx_sw_desc *sd, void *buf,
359                                   dma_addr_t mapping)
360 {
361         sd->buf = buf;
362         sd->dma_addr = mapping;      /* includes size low bits */
363 }
364
365 /**
366  * refill_fl_usembufs - refill an SGE Rx buffer ring with mbufs
367  * @adap: the adapter
368  * @q: the ring to refill
369  * @n: the number of new buffers to allocate
370  *
371  * (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
372  * allocated with the supplied gfp flags.  The caller must assure that
373  * @n does not exceed the queue's capacity.  If afterwards the queue is
374  * found critically low mark it as starving in the bitmap of starving FLs.
375  *
376  * Returns the number of buffers allocated.
377  */
378 static unsigned int refill_fl_usembufs(struct adapter *adap, struct sge_fl *q,
379                                        int n)
380 {
381         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, fl);
382         unsigned int cred = q->avail;
383         __be64 *d = &q->desc[q->pidx];
384         struct rx_sw_desc *sd = &q->sdesc[q->pidx];
385         unsigned int buf_size_idx = RX_SMALL_MTU_BUF;
386         struct rte_mbuf *buf_bulk[n];
387         int ret, i;
388         struct rte_pktmbuf_pool_private *mbp_priv;
389         u8 jumbo_en = rxq->rspq.eth_dev->data->dev_conf.rxmode.jumbo_frame;
390
391         /* Use jumbo mtu buffers iff mbuf data room size can fit jumbo data. */
392         mbp_priv = rte_mempool_get_priv(rxq->rspq.mb_pool);
393         if (jumbo_en &&
394             ((mbp_priv->mbuf_data_room_size - RTE_PKTMBUF_HEADROOM) >= 9000))
395                 buf_size_idx = RX_LARGE_MTU_BUF;
396
397         ret = rte_mempool_get_bulk(rxq->rspq.mb_pool, (void *)buf_bulk, n);
398         if (unlikely(ret != 0)) {
399                 dev_debug(adap, "%s: failed to allocated fl entries in bulk ..\n",
400                           __func__);
401                 q->alloc_failed++;
402                 rxq->rspq.eth_dev->data->rx_mbuf_alloc_failed++;
403                 goto out;
404         }
405
406         for (i = 0; i < n; i++) {
407                 struct rte_mbuf *mbuf = buf_bulk[i];
408                 dma_addr_t mapping;
409
410                 if (!mbuf) {
411                         dev_debug(adap, "%s: mbuf alloc failed\n", __func__);
412                         q->alloc_failed++;
413                         rxq->rspq.eth_dev->data->rx_mbuf_alloc_failed++;
414                         goto out;
415                 }
416
417                 rte_mbuf_refcnt_set(mbuf, 1);
418                 mbuf->data_off = RTE_PKTMBUF_HEADROOM;
419                 mbuf->next = NULL;
420                 mbuf->nb_segs = 1;
421                 mbuf->port = rxq->rspq.port_id;
422
423                 mapping = (dma_addr_t)(mbuf->buf_physaddr + mbuf->data_off);
424                 mapping |= buf_size_idx;
425                 *d++ = cpu_to_be64(mapping);
426                 set_rx_sw_desc(sd, mbuf, mapping);
427                 sd++;
428
429                 q->avail++;
430                 if (++q->pidx == q->size) {
431                         q->pidx = 0;
432                         sd = q->sdesc;
433                         d = q->desc;
434                 }
435         }
436
437 out:    cred = q->avail - cred;
438         q->pend_cred += cred;
439         ring_fl_db(adap, q);
440
441         if (unlikely(fl_starving(adap, q))) {
442                 /*
443                  * Make sure data has been written to free list
444                  */
445                 wmb();
446                 q->low++;
447         }
448
449         return cred;
450 }
451
452 /**
453  * refill_fl - refill an SGE Rx buffer ring with mbufs
454  * @adap: the adapter
455  * @q: the ring to refill
456  * @n: the number of new buffers to allocate
457  *
458  * (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
459  * allocated with the supplied gfp flags.  The caller must assure that
460  * @n does not exceed the queue's capacity.  Returns the number of buffers
461  * allocated.
462  */
463 static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n)
464 {
465         return refill_fl_usembufs(adap, q, n);
466 }
467
468 static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
469 {
470         refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail));
471 }
472
473 /*
474  * Return the number of reclaimable descriptors in a Tx queue.
475  */
476 static inline int reclaimable(const struct sge_txq *q)
477 {
478         int hw_cidx = ntohs(q->stat->cidx);
479
480         hw_cidx -= q->cidx;
481         if (hw_cidx < 0)
482                 return hw_cidx + q->size;
483         return hw_cidx;
484 }
485
486 /**
487  * reclaim_completed_tx - reclaims completed Tx descriptors
488  * @q: the Tx queue to reclaim completed descriptors from
489  *
490  * Reclaims Tx descriptors that the SGE has indicated it has processed.
491  */
492 void reclaim_completed_tx(struct sge_txq *q)
493 {
494         unsigned int avail = reclaimable(q);
495
496         do {
497                 /* reclaim as much as possible */
498                 reclaim_tx_desc(q, avail);
499                 q->in_use -= avail;
500                 avail = reclaimable(q);
501         } while (avail);
502 }
503
504 /**
505  * sgl_len - calculates the size of an SGL of the given capacity
506  * @n: the number of SGL entries
507  *
508  * Calculates the number of flits needed for a scatter/gather list that
509  * can hold the given number of entries.
510  */
511 static inline unsigned int sgl_len(unsigned int n)
512 {
513         /*
514          * A Direct Scatter Gather List uses 32-bit lengths and 64-bit PCI DMA
515          * addresses.  The DSGL Work Request starts off with a 32-bit DSGL
516          * ULPTX header, then Length0, then Address0, then, for 1 <= i <= N,
517          * repeated sequences of { Length[i], Length[i+1], Address[i],
518          * Address[i+1] } (this ensures that all addresses are on 64-bit
519          * boundaries).  If N is even, then Length[N+1] should be set to 0 and
520          * Address[N+1] is omitted.
521          *
522          * The following calculation incorporates all of the above.  It's
523          * somewhat hard to follow but, briefly: the "+2" accounts for the
524          * first two flits which include the DSGL header, Length0 and
525          * Address0; the "(3*(n-1))/2" covers the main body of list entries (3
526          * flits for every pair of the remaining N) +1 if (n-1) is odd; and
527          * finally the "+((n-1)&1)" adds the one remaining flit needed if
528          * (n-1) is odd ...
529          */
530         n--;
531         return (3 * n) / 2 + (n & 1) + 2;
532 }
533
534 /**
535  * flits_to_desc - returns the num of Tx descriptors for the given flits
536  * @n: the number of flits
537  *
538  * Returns the number of Tx descriptors needed for the supplied number
539  * of flits.
540  */
541 static inline unsigned int flits_to_desc(unsigned int n)
542 {
543         return DIV_ROUND_UP(n, 8);
544 }
545
546 /**
547  * is_eth_imm - can an Ethernet packet be sent as immediate data?
548  * @m: the packet
549  *
550  * Returns whether an Ethernet packet is small enough to fit as
551  * immediate data. Return value corresponds to the headroom required.
552  */
553 static inline int is_eth_imm(const struct rte_mbuf *m)
554 {
555         unsigned int hdrlen = (m->ol_flags & PKT_TX_TCP_SEG) ?
556                               sizeof(struct cpl_tx_pkt_lso_core) : 0;
557
558         hdrlen += sizeof(struct cpl_tx_pkt);
559         if (m->pkt_len <= MAX_IMM_TX_PKT_LEN - hdrlen)
560                 return hdrlen;
561
562         return 0;
563 }
564
565 /**
566  * calc_tx_flits - calculate the number of flits for a packet Tx WR
567  * @m: the packet
568  *
569  * Returns the number of flits needed for a Tx WR for the given Ethernet
570  * packet, including the needed WR and CPL headers.
571  */
572 static inline unsigned int calc_tx_flits(const struct rte_mbuf *m)
573 {
574         unsigned int flits;
575         int hdrlen;
576
577         /*
578          * If the mbuf is small enough, we can pump it out as a work request
579          * with only immediate data.  In that case we just have to have the
580          * TX Packet header plus the mbuf data in the Work Request.
581          */
582
583         hdrlen = is_eth_imm(m);
584         if (hdrlen)
585                 return DIV_ROUND_UP(m->pkt_len + hdrlen, sizeof(__be64));
586
587         /*
588          * Otherwise, we're going to have to construct a Scatter gather list
589          * of the mbuf body and fragments.  We also include the flits necessary
590          * for the TX Packet Work Request and CPL.  We always have a firmware
591          * Write Header (incorporated as part of the cpl_tx_pkt_lso and
592          * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
593          * message or, if we're doing a Large Send Offload, an LSO CPL message
594          * with an embeded TX Packet Write CPL message.
595          */
596         flits = sgl_len(m->nb_segs);
597         if (m->tso_segsz)
598                 flits += (sizeof(struct fw_eth_tx_pkt_wr) +
599                           sizeof(struct cpl_tx_pkt_lso_core) +
600                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
601         else
602                 flits += (sizeof(struct fw_eth_tx_pkt_wr) +
603                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
604         return flits;
605 }
606
607 /**
608  * write_sgl - populate a scatter/gather list for a packet
609  * @mbuf: the packet
610  * @q: the Tx queue we are writing into
611  * @sgl: starting location for writing the SGL
612  * @end: points right after the end of the SGL
613  * @start: start offset into mbuf main-body data to include in the SGL
614  * @addr: address of mapped region
615  *
616  * Generates a scatter/gather list for the buffers that make up a packet.
617  * The caller must provide adequate space for the SGL that will be written.
618  * The SGL includes all of the packet's page fragments and the data in its
619  * main body except for the first @start bytes.  @sgl must be 16-byte
620  * aligned and within a Tx descriptor with available space.  @end points
621  * write after the end of the SGL but does not account for any potential
622  * wrap around, i.e., @end > @sgl.
623  */
624 static void write_sgl(struct rte_mbuf *mbuf, struct sge_txq *q,
625                       struct ulptx_sgl *sgl, u64 *end, unsigned int start,
626                       const dma_addr_t *addr)
627 {
628         unsigned int i, len;
629         struct ulptx_sge_pair *to;
630         struct rte_mbuf *m = mbuf;
631         unsigned int nfrags = m->nb_segs;
632         struct ulptx_sge_pair buf[nfrags / 2];
633
634         len = m->data_len - start;
635         sgl->len0 = htonl(len);
636         sgl->addr0 = rte_cpu_to_be_64(addr[0]);
637
638         sgl->cmd_nsge = htonl(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
639                               V_ULPTX_NSGE(nfrags));
640         if (likely(--nfrags == 0))
641                 return;
642         /*
643          * Most of the complexity below deals with the possibility we hit the
644          * end of the queue in the middle of writing the SGL.  For this case
645          * only we create the SGL in a temporary buffer and then copy it.
646          */
647         to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
648
649         for (i = 0; nfrags >= 2; nfrags -= 2, to++) {
650                 m = m->next;
651                 to->len[0] = rte_cpu_to_be_32(m->data_len);
652                 to->addr[0] = rte_cpu_to_be_64(addr[++i]);
653                 m = m->next;
654                 to->len[1] = rte_cpu_to_be_32(m->data_len);
655                 to->addr[1] = rte_cpu_to_be_64(addr[++i]);
656         }
657         if (nfrags) {
658                 m = m->next;
659                 to->len[0] = rte_cpu_to_be_32(m->data_len);
660                 to->len[1] = rte_cpu_to_be_32(0);
661                 to->addr[0] = rte_cpu_to_be_64(addr[i + 1]);
662         }
663         if (unlikely((u8 *)end > (u8 *)q->stat)) {
664                 unsigned int part0 = RTE_PTR_DIFF((u8 *)q->stat,
665                                                   (u8 *)sgl->sge);
666                 unsigned int part1;
667
668                 if (likely(part0))
669                         memcpy(sgl->sge, buf, part0);
670                 part1 = RTE_PTR_DIFF((u8 *)end, (u8 *)q->stat);
671                 rte_memcpy(q->desc, RTE_PTR_ADD((u8 *)buf, part0), part1);
672                 end = RTE_PTR_ADD((void *)q->desc, part1);
673         }
674         if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
675                 *(u64 *)end = 0;
676 }
677
678 #define IDXDIFF(head, tail, wrap) \
679         ((head) >= (tail) ? (head) - (tail) : (wrap) - (tail) + (head))
680
681 #define Q_IDXDIFF(q, idx) IDXDIFF((q)->pidx, (q)->idx, (q)->size)
682 #define R_IDXDIFF(q, idx) IDXDIFF((q)->cidx, (q)->idx, (q)->size)
683
684 /**
685  * ring_tx_db - ring a Tx queue's doorbell
686  * @adap: the adapter
687  * @q: the Tx queue
688  * @n: number of new descriptors to give to HW
689  *
690  * Ring the doorbel for a Tx queue.
691  */
692 static inline void ring_tx_db(struct adapter *adap, struct sge_txq *q)
693 {
694         int n = Q_IDXDIFF(q, dbidx);
695
696         /*
697          * Make sure that all writes to the TX Descriptors are committed
698          * before we tell the hardware about them.
699          */
700         rte_wmb();
701
702         /*
703          * If we don't have access to the new User Doorbell (T5+), use the old
704          * doorbell mechanism; otherwise use the new BAR2 mechanism.
705          */
706         if (unlikely(!q->bar2_addr)) {
707                 u32 val = V_PIDX(n);
708
709                 /*
710                  * For T4 we need to participate in the Doorbell Recovery
711                  * mechanism.
712                  */
713                 if (!q->db_disabled)
714                         t4_write_reg(adap, MYPF_REG(A_SGE_PF_KDOORBELL),
715                                      V_QID(q->cntxt_id) | val);
716                 else
717                         q->db_pidx_inc += n;
718                 q->db_pidx = q->pidx;
719         } else {
720                 u32 val = V_PIDX_T5(n);
721
722                 /*
723                  * T4 and later chips share the same PIDX field offset within
724                  * the doorbell, but T5 and later shrank the field in order to
725                  * gain a bit for Doorbell Priority.  The field was absurdly
726                  * large in the first place (14 bits) so we just use the T5
727                  * and later limits and warn if a Queue ID is too large.
728                  */
729                 WARN_ON(val & F_DBPRIO);
730
731                 writel(val | V_QID(q->bar2_qid),
732                        (void *)((uintptr_t)q->bar2_addr + SGE_UDB_KDOORBELL));
733
734                 /*
735                  * This Write Memory Barrier will force the write to the User
736                  * Doorbell area to be flushed.  This is needed to prevent
737                  * writes on different CPUs for the same queue from hitting
738                  * the adapter out of order.  This is required when some Work
739                  * Requests take the Write Combine Gather Buffer path (user
740                  * doorbell area offset [SGE_UDB_WCDOORBELL..+63]) and some
741                  * take the traditional path where we simply increment the
742                  * PIDX (User Doorbell area SGE_UDB_KDOORBELL) and have the
743                  * hardware DMA read the actual Work Request.
744                  */
745                 rte_wmb();
746         }
747         q->dbidx = q->pidx;
748 }
749
750 /*
751  * Figure out what HW csum a packet wants and return the appropriate control
752  * bits.
753  */
754 static u64 hwcsum(enum chip_type chip, const struct rte_mbuf *m)
755 {
756         int csum_type;
757
758         if (m->ol_flags & PKT_TX_IP_CKSUM) {
759                 switch (m->ol_flags & PKT_TX_L4_MASK) {
760                 case PKT_TX_TCP_CKSUM:
761                         csum_type = TX_CSUM_TCPIP;
762                         break;
763                 case PKT_TX_UDP_CKSUM:
764                         csum_type = TX_CSUM_UDPIP;
765                         break;
766                 default:
767                         goto nocsum;
768                 }
769         } else {
770                 goto nocsum;
771         }
772
773         if (likely(csum_type >= TX_CSUM_TCPIP)) {
774                 int hdr_len = V_TXPKT_IPHDR_LEN(m->l3_len);
775                 int eth_hdr_len = m->l2_len;
776
777                 if (CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5)
778                         hdr_len |= V_TXPKT_ETHHDR_LEN(eth_hdr_len);
779                 else
780                         hdr_len |= V_T6_TXPKT_ETHHDR_LEN(eth_hdr_len);
781                 return V_TXPKT_CSUM_TYPE(csum_type) | hdr_len;
782         }
783 nocsum:
784         /*
785          * unknown protocol, disable HW csum
786          * and hope a bad packet is detected
787          */
788         return F_TXPKT_L4CSUM_DIS;
789 }
790
791 static inline void txq_advance(struct sge_txq *q, unsigned int n)
792 {
793         q->in_use += n;
794         q->pidx += n;
795         if (q->pidx >= q->size)
796                 q->pidx -= q->size;
797 }
798
799 #define MAX_COALESCE_LEN 64000
800
801 static inline int wraps_around(struct sge_txq *q, int ndesc)
802 {
803         return (q->pidx + ndesc) > q->size ? 1 : 0;
804 }
805
806 static void tx_timer_cb(void *data)
807 {
808         struct adapter *adap = (struct adapter *)data;
809         struct sge_eth_txq *txq = &adap->sge.ethtxq[0];
810         int i;
811         unsigned int coal_idx;
812
813         /* monitor any pending tx */
814         for (i = 0; i < adap->sge.max_ethqsets; i++, txq++) {
815                 if (t4_os_trylock(&txq->txq_lock)) {
816                         coal_idx = txq->q.coalesce.idx;
817                         if (coal_idx) {
818                                 if (coal_idx == txq->q.last_coal_idx &&
819                                     txq->q.pidx == txq->q.last_pidx) {
820                                         ship_tx_pkt_coalesce_wr(adap, txq);
821                                 } else {
822                                         txq->q.last_coal_idx = coal_idx;
823                                         txq->q.last_pidx = txq->q.pidx;
824                                 }
825                         }
826                         t4_os_unlock(&txq->txq_lock);
827                 }
828         }
829         rte_eal_alarm_set(50, tx_timer_cb, (void *)adap);
830 }
831
832 /**
833  * ship_tx_pkt_coalesce_wr - finalizes and ships a coalesce WR
834  * @ adap: adapter structure
835  * @txq: tx queue
836  *
837  * writes the different fields of the pkts WR and sends it.
838  */
839 static inline void ship_tx_pkt_coalesce_wr(struct adapter *adap,
840                                            struct sge_eth_txq *txq)
841 {
842         u32 wr_mid;
843         struct sge_txq *q = &txq->q;
844         struct fw_eth_tx_pkts_wr *wr;
845         unsigned int ndesc;
846
847         /* fill the pkts WR header */
848         wr = (void *)&q->desc[q->pidx];
849         wr->op_pkd = htonl(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
850
851         wr_mid = V_FW_WR_LEN16(DIV_ROUND_UP(q->coalesce.flits, 2));
852         ndesc = flits_to_desc(q->coalesce.flits);
853         wr->equiq_to_len16 = htonl(wr_mid);
854         wr->plen = cpu_to_be16(q->coalesce.len);
855         wr->npkt = q->coalesce.idx;
856         wr->r3 = 0;
857         wr->type = q->coalesce.type;
858
859         /* zero out coalesce structure members */
860         q->coalesce.idx = 0;
861         q->coalesce.flits = 0;
862         q->coalesce.len = 0;
863
864         txq_advance(q, ndesc);
865         txq->stats.coal_wr++;
866         txq->stats.coal_pkts += wr->npkt;
867
868         if (Q_IDXDIFF(q, equeidx) >= q->size / 2) {
869                 q->equeidx = q->pidx;
870                 wr_mid |= F_FW_WR_EQUEQ;
871                 wr->equiq_to_len16 = htonl(wr_mid);
872         }
873         ring_tx_db(adap, q);
874 }
875
876 /**
877  * should_tx_packet_coalesce - decides wether to coalesce an mbuf or not
878  * @txq: tx queue where the mbuf is sent
879  * @mbuf: mbuf to be sent
880  * @nflits: return value for number of flits needed
881  * @adap: adapter structure
882  *
883  * This function decides if a packet should be coalesced or not.
884  */
885 static inline int should_tx_packet_coalesce(struct sge_eth_txq *txq,
886                                             struct rte_mbuf *mbuf,
887                                             unsigned int *nflits,
888                                             struct adapter *adap)
889 {
890         struct sge_txq *q = &txq->q;
891         unsigned int flits, ndesc;
892         unsigned char type = 0;
893         int credits, hw_cidx = ntohs(q->stat->cidx);
894         int in_use = q->pidx - hw_cidx + flits_to_desc(q->coalesce.flits);
895
896         /* use coal WR type 1 when no frags are present */
897         type = (mbuf->nb_segs == 1) ? 1 : 0;
898
899         if (in_use < 0)
900                 in_use += q->size;
901
902         if (unlikely(type != q->coalesce.type && q->coalesce.idx))
903                 ship_tx_pkt_coalesce_wr(adap, txq);
904
905         /* calculate the number of flits required for coalescing this packet
906          * without the 2 flits of the WR header. These are added further down
907          * if we are just starting in new PKTS WR. sgl_len doesn't account for
908          * the possible 16 bytes alignment ULP TX commands so we do it here.
909          */
910         flits = (sgl_len(mbuf->nb_segs) + 1) & ~1U;
911         if (type == 0)
912                 flits += (sizeof(struct ulp_txpkt) +
913                           sizeof(struct ulptx_idata)) / sizeof(__be64);
914         flits += sizeof(struct cpl_tx_pkt_core) / sizeof(__be64);
915         *nflits = flits;
916
917         /* If coalescing is on, the mbuf is added to a pkts WR */
918         if (q->coalesce.idx) {
919                 ndesc = DIV_ROUND_UP(q->coalesce.flits + flits, 8);
920                 credits = txq_avail(q) - ndesc;
921
922                 /* If we are wrapping or this is last mbuf then, send the
923                  * already coalesced mbufs and let the non-coalesce pass
924                  * handle the mbuf.
925                  */
926                 if (unlikely(credits < 0 || wraps_around(q, ndesc))) {
927                         ship_tx_pkt_coalesce_wr(adap, txq);
928                         return 0;
929                 }
930
931                 /* If the max coalesce len or the max WR len is reached
932                  * ship the WR and keep coalescing on.
933                  */
934                 if (unlikely((q->coalesce.len + mbuf->pkt_len >
935                                                 MAX_COALESCE_LEN) ||
936                              (q->coalesce.flits + flits >
937                               q->coalesce.max))) {
938                         ship_tx_pkt_coalesce_wr(adap, txq);
939                         goto new;
940                 }
941                 return 1;
942         }
943
944 new:
945         /* start a new pkts WR, the WR header is not filled below */
946         flits += sizeof(struct fw_eth_tx_pkts_wr) / sizeof(__be64);
947         ndesc = flits_to_desc(q->coalesce.flits + flits);
948         credits = txq_avail(q) - ndesc;
949
950         if (unlikely(credits < 0 || wraps_around(q, ndesc)))
951                 return 0;
952         q->coalesce.flits += 2;
953         q->coalesce.type = type;
954         q->coalesce.ptr = (unsigned char *)&q->desc[q->pidx] +
955                            2 * sizeof(__be64);
956         return 1;
957 }
958
959 /**
960  * tx_do_packet_coalesce - add an mbuf to a coalesce WR
961  * @txq: sge_eth_txq used send the mbuf
962  * @mbuf: mbuf to be sent
963  * @flits: flits needed for this mbuf
964  * @adap: adapter structure
965  * @pi: port_info structure
966  * @addr: mapped address of the mbuf
967  *
968  * Adds an mbuf to be sent as part of a coalesce WR by filling a
969  * ulp_tx_pkt command, ulp_tx_sc_imm command, cpl message and
970  * ulp_tx_sc_dsgl command.
971  */
972 static inline int tx_do_packet_coalesce(struct sge_eth_txq *txq,
973                                         struct rte_mbuf *mbuf,
974                                         int flits, struct adapter *adap,
975                                         const struct port_info *pi,
976                                         dma_addr_t *addr)
977 {
978         u64 cntrl, *end;
979         struct sge_txq *q = &txq->q;
980         struct ulp_txpkt *mc;
981         struct ulptx_idata *sc_imm;
982         struct cpl_tx_pkt_core *cpl;
983         struct tx_sw_desc *sd;
984         unsigned int idx = q->coalesce.idx, len = mbuf->pkt_len;
985
986         if (q->coalesce.type == 0) {
987                 mc = (struct ulp_txpkt *)q->coalesce.ptr;
988                 mc->cmd_dest = htonl(V_ULPTX_CMD(4) | V_ULP_TXPKT_DEST(0) |
989                                      V_ULP_TXPKT_FID(adap->sge.fw_evtq.cntxt_id) |
990                                      F_ULP_TXPKT_RO);
991                 mc->len = htonl(DIV_ROUND_UP(flits, 2));
992                 sc_imm = (struct ulptx_idata *)(mc + 1);
993                 sc_imm->cmd_more = htonl(V_ULPTX_CMD(ULP_TX_SC_IMM) |
994                                          F_ULP_TX_SC_MORE);
995                 sc_imm->len = htonl(sizeof(*cpl));
996                 end = (u64 *)mc + flits;
997                 cpl = (struct cpl_tx_pkt_core *)(sc_imm + 1);
998         } else {
999                 end = (u64 *)q->coalesce.ptr + flits;
1000                 cpl = (struct cpl_tx_pkt_core *)q->coalesce.ptr;
1001         }
1002
1003         /* update coalesce structure for this txq */
1004         q->coalesce.flits += flits;
1005         q->coalesce.ptr += flits * sizeof(__be64);
1006         q->coalesce.len += mbuf->pkt_len;
1007
1008         /* fill the cpl message, same as in t4_eth_xmit, this should be kept
1009          * similar to t4_eth_xmit
1010          */
1011         if (mbuf->ol_flags & PKT_TX_IP_CKSUM) {
1012                 cntrl = hwcsum(adap->params.chip, mbuf) |
1013                                F_TXPKT_IPCSUM_DIS;
1014                 txq->stats.tx_cso++;
1015         } else {
1016                 cntrl = F_TXPKT_L4CSUM_DIS | F_TXPKT_IPCSUM_DIS;
1017         }
1018
1019         if (mbuf->ol_flags & PKT_TX_VLAN_PKT) {
1020                 txq->stats.vlan_ins++;
1021                 cntrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(mbuf->vlan_tci);
1022         }
1023
1024         cpl->ctrl0 = htonl(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
1025                            V_TXPKT_INTF(pi->tx_chan) |
1026                            V_TXPKT_PF(adap->pf));
1027         cpl->pack = htons(0);
1028         cpl->len = htons(len);
1029         cpl->ctrl1 = cpu_to_be64(cntrl);
1030         write_sgl(mbuf, q, (struct ulptx_sgl *)(cpl + 1), end, 0,  addr);
1031         txq->stats.pkts++;
1032         txq->stats.tx_bytes += len;
1033
1034         sd = &q->sdesc[q->pidx + (idx >> 1)];
1035         if (!(idx & 1)) {
1036                 if (sd->coalesce.idx) {
1037                         int i;
1038
1039                         for (i = 0; i < sd->coalesce.idx; i++) {
1040                                 rte_pktmbuf_free(sd->coalesce.mbuf[i]);
1041                                 sd->coalesce.mbuf[i] = NULL;
1042                         }
1043                 }
1044         }
1045
1046         /* store pointers to the mbuf and the sgl used in free_tx_desc.
1047          * each tx desc can hold two pointers corresponding to the value
1048          * of ETH_COALESCE_PKT_PER_DESC
1049          */
1050         sd->coalesce.mbuf[idx & 1] = mbuf;
1051         sd->coalesce.sgl[idx & 1] = (struct ulptx_sgl *)(cpl + 1);
1052         sd->coalesce.idx = (idx & 1) + 1;
1053
1054         /* send the coaelsced work request if max reached */
1055         if (++q->coalesce.idx == ETH_COALESCE_PKT_NUM)
1056                 ship_tx_pkt_coalesce_wr(adap, txq);
1057         return 0;
1058 }
1059
1060 /**
1061  * t4_eth_xmit - add a packet to an Ethernet Tx queue
1062  * @txq: the egress queue
1063  * @mbuf: the packet
1064  *
1065  * Add a packet to an SGE Ethernet Tx queue.  Runs with softirqs disabled.
1066  */
1067 int t4_eth_xmit(struct sge_eth_txq *txq, struct rte_mbuf *mbuf)
1068 {
1069         const struct port_info *pi;
1070         struct cpl_tx_pkt_lso_core *lso;
1071         struct adapter *adap;
1072         struct rte_mbuf *m = mbuf;
1073         struct fw_eth_tx_pkt_wr *wr;
1074         struct cpl_tx_pkt_core *cpl;
1075         struct tx_sw_desc *d;
1076         dma_addr_t addr[m->nb_segs];
1077         unsigned int flits, ndesc, cflits;
1078         int l3hdr_len, l4hdr_len, eth_xtra_len;
1079         int len, last_desc;
1080         int credits;
1081         u32 wr_mid;
1082         u64 cntrl, *end;
1083         bool v6;
1084         u32 max_pkt_len = txq->eth_dev->data->dev_conf.rxmode.max_rx_pkt_len;
1085
1086         /* Reject xmit if queue is stopped */
1087         if (unlikely(txq->flags & EQ_STOPPED))
1088                 return -(EBUSY);
1089
1090         /*
1091          * The chip min packet length is 10 octets but play safe and reject
1092          * anything shorter than an Ethernet header.
1093          */
1094         if (unlikely(m->pkt_len < ETHER_HDR_LEN)) {
1095 out_free:
1096                 rte_pktmbuf_free(m);
1097                 return 0;
1098         }
1099
1100         if ((!(m->ol_flags & PKT_TX_TCP_SEG)) &&
1101             (unlikely(m->pkt_len > max_pkt_len)))
1102                 goto out_free;
1103
1104         pi = (struct port_info *)txq->eth_dev->data->dev_private;
1105         adap = pi->adapter;
1106
1107         cntrl = F_TXPKT_L4CSUM_DIS | F_TXPKT_IPCSUM_DIS;
1108         /* align the end of coalesce WR to a 512 byte boundary */
1109         txq->q.coalesce.max = (8 - (txq->q.pidx & 7)) * 8;
1110
1111         if (!((m->ol_flags & PKT_TX_TCP_SEG) || (m->pkt_len > ETHER_MAX_LEN))) {
1112                 if (should_tx_packet_coalesce(txq, mbuf, &cflits, adap)) {
1113                         if (unlikely(map_mbuf(mbuf, addr) < 0)) {
1114                                 dev_warn(adap, "%s: mapping err for coalesce\n",
1115                                          __func__);
1116                                 txq->stats.mapping_err++;
1117                                 goto out_free;
1118                         }
1119                         rte_prefetch0((volatile void *)addr);
1120                         return tx_do_packet_coalesce(txq, mbuf, cflits, adap,
1121                                                      pi, addr);
1122                 } else {
1123                         return -EBUSY;
1124                 }
1125         }
1126
1127         if (txq->q.coalesce.idx)
1128                 ship_tx_pkt_coalesce_wr(adap, txq);
1129
1130         flits = calc_tx_flits(m);
1131         ndesc = flits_to_desc(flits);
1132         credits = txq_avail(&txq->q) - ndesc;
1133
1134         if (unlikely(credits < 0)) {
1135                 dev_debug(adap, "%s: Tx ring %u full; credits = %d\n",
1136                           __func__, txq->q.cntxt_id, credits);
1137                 return -EBUSY;
1138         }
1139
1140         if (unlikely(map_mbuf(m, addr) < 0)) {
1141                 txq->stats.mapping_err++;
1142                 goto out_free;
1143         }
1144
1145         wr_mid = V_FW_WR_LEN16(DIV_ROUND_UP(flits, 2));
1146         if (Q_IDXDIFF(&txq->q, equeidx)  >= 64) {
1147                 txq->q.equeidx = txq->q.pidx;
1148                 wr_mid |= F_FW_WR_EQUEQ;
1149         }
1150
1151         wr = (void *)&txq->q.desc[txq->q.pidx];
1152         wr->equiq_to_len16 = htonl(wr_mid);
1153         wr->r3 = rte_cpu_to_be_64(0);
1154         end = (u64 *)wr + flits;
1155
1156         len = 0;
1157         len += sizeof(*cpl);
1158
1159         /* Coalescing skipped and we send through normal path */
1160         if (!(m->ol_flags & PKT_TX_TCP_SEG)) {
1161                 wr->op_immdlen = htonl(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
1162                                        V_FW_WR_IMMDLEN(len));
1163                 cpl = (void *)(wr + 1);
1164                 if (m->ol_flags & PKT_TX_IP_CKSUM) {
1165                         cntrl = hwcsum(adap->params.chip, m) |
1166                                 F_TXPKT_IPCSUM_DIS;
1167                         txq->stats.tx_cso++;
1168                 }
1169         } else {
1170                 lso = (void *)(wr + 1);
1171                 v6 = (m->ol_flags & PKT_TX_IPV6) != 0;
1172                 l3hdr_len = m->l3_len;
1173                 l4hdr_len = m->l4_len;
1174                 eth_xtra_len = m->l2_len - ETHER_HDR_LEN;
1175                 len += sizeof(*lso);
1176                 wr->op_immdlen = htonl(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
1177                                        V_FW_WR_IMMDLEN(len));
1178                 lso->lso_ctrl = htonl(V_LSO_OPCODE(CPL_TX_PKT_LSO) |
1179                                       F_LSO_FIRST_SLICE | F_LSO_LAST_SLICE |
1180                                       V_LSO_IPV6(v6) |
1181                                       V_LSO_ETHHDR_LEN(eth_xtra_len / 4) |
1182                                       V_LSO_IPHDR_LEN(l3hdr_len / 4) |
1183                                       V_LSO_TCPHDR_LEN(l4hdr_len / 4));
1184                 lso->ipid_ofst = htons(0);
1185                 lso->mss = htons(m->tso_segsz);
1186                 lso->seqno_offset = htonl(0);
1187                 if (is_t4(adap->params.chip))
1188                         lso->len = htonl(m->pkt_len);
1189                 else
1190                         lso->len = htonl(V_LSO_T5_XFER_SIZE(m->pkt_len));
1191                 cpl = (void *)(lso + 1);
1192                 cntrl = V_TXPKT_CSUM_TYPE(v6 ? TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
1193                         V_TXPKT_IPHDR_LEN(l3hdr_len) |
1194                         V_TXPKT_ETHHDR_LEN(eth_xtra_len);
1195                 txq->stats.tso++;
1196                 txq->stats.tx_cso += m->tso_segsz;
1197         }
1198
1199         if (m->ol_flags & PKT_TX_VLAN_PKT) {
1200                 txq->stats.vlan_ins++;
1201                 cntrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->vlan_tci);
1202         }
1203
1204         cpl->ctrl0 = htonl(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
1205                            V_TXPKT_INTF(pi->tx_chan) |
1206                            V_TXPKT_PF(adap->pf));
1207         cpl->pack = htons(0);
1208         cpl->len = htons(m->pkt_len);
1209         cpl->ctrl1 = cpu_to_be64(cntrl);
1210
1211         txq->stats.pkts++;
1212         txq->stats.tx_bytes += m->pkt_len;
1213         last_desc = txq->q.pidx + ndesc - 1;
1214         if (last_desc >= (int)txq->q.size)
1215                 last_desc -= txq->q.size;
1216
1217         d = &txq->q.sdesc[last_desc];
1218         if (d->coalesce.idx) {
1219                 int i;
1220
1221                 for (i = 0; i < d->coalesce.idx; i++) {
1222                         rte_pktmbuf_free(d->coalesce.mbuf[i]);
1223                         d->coalesce.mbuf[i] = NULL;
1224                 }
1225                 d->coalesce.idx = 0;
1226         }
1227         write_sgl(m, &txq->q, (struct ulptx_sgl *)(cpl + 1), end, 0,
1228                   addr);
1229         txq->q.sdesc[last_desc].mbuf = m;
1230         txq->q.sdesc[last_desc].sgl = (struct ulptx_sgl *)(cpl + 1);
1231         txq_advance(&txq->q, ndesc);
1232         ring_tx_db(adap, &txq->q);
1233         return 0;
1234 }
1235
1236 /**
1237  * alloc_ring - allocate resources for an SGE descriptor ring
1238  * @dev: the PCI device's core device
1239  * @nelem: the number of descriptors
1240  * @elem_size: the size of each descriptor
1241  * @sw_size: the size of the SW state associated with each ring element
1242  * @phys: the physical address of the allocated ring
1243  * @metadata: address of the array holding the SW state for the ring
1244  * @stat_size: extra space in HW ring for status information
1245  * @node: preferred node for memory allocations
1246  *
1247  * Allocates resources for an SGE descriptor ring, such as Tx queues,
1248  * free buffer lists, or response queues.  Each SGE ring requires
1249  * space for its HW descriptors plus, optionally, space for the SW state
1250  * associated with each HW entry (the metadata).  The function returns
1251  * three values: the virtual address for the HW ring (the return value
1252  * of the function), the bus address of the HW ring, and the address
1253  * of the SW ring.
1254  */
1255 static void *alloc_ring(size_t nelem, size_t elem_size,
1256                         size_t sw_size, dma_addr_t *phys, void *metadata,
1257                         size_t stat_size, __rte_unused uint16_t queue_id,
1258                         int socket_id, const char *z_name,
1259                         const char *z_name_sw)
1260 {
1261         size_t len = CXGBE_MAX_RING_DESC_SIZE * elem_size + stat_size;
1262         const struct rte_memzone *tz;
1263         void *s = NULL;
1264
1265         dev_debug(adapter, "%s: nelem = %zu; elem_size = %zu; sw_size = %zu; "
1266                   "stat_size = %zu; queue_id = %u; socket_id = %d; z_name = %s;"
1267                   " z_name_sw = %s\n", __func__, nelem, elem_size, sw_size,
1268                   stat_size, queue_id, socket_id, z_name, z_name_sw);
1269
1270         tz = rte_memzone_lookup(z_name);
1271         if (tz) {
1272                 dev_debug(adapter, "%s: tz exists...returning existing..\n",
1273                           __func__);
1274                 goto alloc_sw_ring;
1275         }
1276
1277         /*
1278          * Allocate TX/RX ring hardware descriptors. A memzone large enough to
1279          * handle the maximum ring size is allocated in order to allow for
1280          * resizing in later calls to the queue setup function.
1281          */
1282         tz = rte_memzone_reserve_aligned(z_name, len, socket_id, 0, 4096);
1283         if (!tz)
1284                 return NULL;
1285
1286 alloc_sw_ring:
1287         memset(tz->addr, 0, len);
1288         if (sw_size) {
1289                 s = rte_zmalloc_socket(z_name_sw, nelem * sw_size,
1290                                        RTE_CACHE_LINE_SIZE, socket_id);
1291
1292                 if (!s) {
1293                         dev_err(adapter, "%s: failed to get sw_ring memory\n",
1294                                 __func__);
1295                         return NULL;
1296                 }
1297         }
1298         if (metadata)
1299                 *(void **)metadata = s;
1300
1301         *phys = (uint64_t)tz->phys_addr;
1302         return tz->addr;
1303 }
1304
1305 /**
1306  * t4_pktgl_to_mbuf_usembufs - build an mbuf from a packet gather list
1307  * @gl: the gather list
1308  *
1309  * Builds an mbuf from the given packet gather list.  Returns the mbuf or
1310  * %NULL if mbuf allocation failed.
1311  */
1312 static struct rte_mbuf *t4_pktgl_to_mbuf_usembufs(const struct pkt_gl *gl)
1313 {
1314         /*
1315          * If there's only one mbuf fragment, just return that.
1316          */
1317         if (likely(gl->nfrags == 1))
1318                 return gl->mbufs[0];
1319
1320         return NULL;
1321 }
1322
1323 /**
1324  * t4_pktgl_to_mbuf - build an mbuf from a packet gather list
1325  * @gl: the gather list
1326  *
1327  * Builds an mbuf from the given packet gather list.  Returns the mbuf or
1328  * %NULL if mbuf allocation failed.
1329  */
1330 static struct rte_mbuf *t4_pktgl_to_mbuf(const struct pkt_gl *gl)
1331 {
1332         return t4_pktgl_to_mbuf_usembufs(gl);
1333 }
1334
1335 #define RTE_MBUF_DATA_DMA_ADDR_DEFAULT(mb) \
1336         ((dma_addr_t) ((mb)->buf_physaddr + (mb)->data_off))
1337
1338 /**
1339  * t4_ethrx_handler - process an ingress ethernet packet
1340  * @q: the response queue that received the packet
1341  * @rsp: the response queue descriptor holding the RX_PKT message
1342  * @si: the gather list of packet fragments
1343  *
1344  * Process an ingress ethernet packet and deliver it to the stack.
1345  */
1346 int t4_ethrx_handler(struct sge_rspq *q, const __be64 *rsp,
1347                      const struct pkt_gl *si)
1348 {
1349         struct rte_mbuf *mbuf;
1350         const struct cpl_rx_pkt *pkt;
1351         const struct rss_header *rss_hdr;
1352         bool csum_ok;
1353         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
1354
1355         rss_hdr = (const void *)rsp;
1356         pkt = (const void *)&rsp[1];
1357         csum_ok = pkt->csum_calc && !pkt->err_vec;
1358
1359         mbuf = t4_pktgl_to_mbuf(si);
1360         if (unlikely(!mbuf)) {
1361                 rxq->stats.rx_drops++;
1362                 return 0;
1363         }
1364
1365         mbuf->port = pkt->iff;
1366         if (pkt->l2info & htonl(F_RXF_IP)) {
1367                 mbuf->packet_type = RTE_PTYPE_L3_IPV4;
1368                 if (unlikely(!csum_ok))
1369                         mbuf->ol_flags |= PKT_RX_IP_CKSUM_BAD;
1370
1371                 if ((pkt->l2info & htonl(F_RXF_UDP | F_RXF_TCP)) && !csum_ok)
1372                         mbuf->ol_flags |= PKT_RX_L4_CKSUM_BAD;
1373         } else if (pkt->l2info & htonl(F_RXF_IP6)) {
1374                 mbuf->packet_type = RTE_PTYPE_L3_IPV6;
1375         }
1376
1377         mbuf->port = pkt->iff;
1378
1379         if (!rss_hdr->filter_tid && rss_hdr->hash_type) {
1380                 mbuf->ol_flags |= PKT_RX_RSS_HASH;
1381                 mbuf->hash.rss = ntohl(rss_hdr->hash_val);
1382         }
1383
1384         if (pkt->vlan_ex) {
1385                 mbuf->ol_flags |= PKT_RX_VLAN_PKT;
1386                 mbuf->vlan_tci = ntohs(pkt->vlan);
1387         }
1388         rxq->stats.pkts++;
1389         rxq->stats.rx_bytes += mbuf->pkt_len;
1390
1391         return 0;
1392 }
1393
1394 /**
1395  * is_new_response - check if a response is newly written
1396  * @r: the response descriptor
1397  * @q: the response queue
1398  *
1399  * Returns true if a response descriptor contains a yet unprocessed
1400  * response.
1401  */
1402 static inline bool is_new_response(const struct rsp_ctrl *r,
1403                                    const struct sge_rspq *q)
1404 {
1405         return (r->u.type_gen >> S_RSPD_GEN) == q->gen;
1406 }
1407
1408 #define CXGB4_MSG_AN ((void *)1)
1409
1410 /**
1411  * rspq_next - advance to the next entry in a response queue
1412  * @q: the queue
1413  *
1414  * Updates the state of a response queue to advance it to the next entry.
1415  */
1416 static inline void rspq_next(struct sge_rspq *q)
1417 {
1418         q->cur_desc = (const __be64 *)((const char *)q->cur_desc + q->iqe_len);
1419         if (unlikely(++q->cidx == q->size)) {
1420                 q->cidx = 0;
1421                 q->gen ^= 1;
1422                 q->cur_desc = q->desc;
1423         }
1424 }
1425
1426 /**
1427  * process_responses - process responses from an SGE response queue
1428  * @q: the ingress queue to process
1429  * @budget: how many responses can be processed in this round
1430  * @rx_pkts: mbuf to put the pkts
1431  *
1432  * Process responses from an SGE response queue up to the supplied budget.
1433  * Responses include received packets as well as control messages from FW
1434  * or HW.
1435  *
1436  * Additionally choose the interrupt holdoff time for the next interrupt
1437  * on this queue.  If the system is under memory shortage use a fairly
1438  * long delay to help recovery.
1439  */
1440 static int process_responses(struct sge_rspq *q, int budget,
1441                              struct rte_mbuf **rx_pkts)
1442 {
1443         int ret = 0, rsp_type;
1444         int budget_left = budget;
1445         const struct rsp_ctrl *rc;
1446         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
1447
1448         while (likely(budget_left)) {
1449                 rc = (const struct rsp_ctrl *)
1450                      ((const char *)q->cur_desc + (q->iqe_len - sizeof(*rc)));
1451
1452                 if (!is_new_response(rc, q))
1453                         break;
1454
1455                 /*
1456                  * Ensure response has been read
1457                  */
1458                 rmb();
1459                 rsp_type = G_RSPD_TYPE(rc->u.type_gen);
1460
1461                 if (likely(rsp_type == X_RSPD_TYPE_FLBUF)) {
1462                         const struct rx_sw_desc *rsd =
1463                                                 &rxq->fl.sdesc[rxq->fl.cidx];
1464                         const struct rss_header *rss_hdr =
1465                                                 (const void *)q->cur_desc;
1466                         const struct cpl_rx_pkt *cpl =
1467                                                 (const void *)&q->cur_desc[1];
1468                         bool csum_ok = cpl->csum_calc && !cpl->err_vec;
1469                         struct rte_mbuf *pkt, *npkt;
1470                         u32 len, bufsz;
1471
1472                         len = ntohl(rc->pldbuflen_qid);
1473                         BUG_ON(!(len & F_RSPD_NEWBUF));
1474                         pkt = rsd->buf;
1475                         npkt = pkt;
1476                         len = G_RSPD_LEN(len);
1477                         pkt->pkt_len = len;
1478
1479                         /* Chain mbufs into len if necessary */
1480                         while (len) {
1481                                 struct rte_mbuf *new_pkt = rsd->buf;
1482
1483                                 bufsz = min(get_buf_size(q->adapter, rsd), len);
1484                                 new_pkt->data_len = bufsz;
1485                                 unmap_rx_buf(&rxq->fl);
1486                                 len -= bufsz;
1487                                 npkt->next = new_pkt;
1488                                 npkt = new_pkt;
1489                                 pkt->nb_segs++;
1490                                 rsd = &rxq->fl.sdesc[rxq->fl.cidx];
1491                         }
1492                         npkt->next = NULL;
1493                         pkt->nb_segs--;
1494
1495                         if (cpl->l2info & htonl(F_RXF_IP)) {
1496                                 pkt->packet_type = RTE_PTYPE_L3_IPV4;
1497                                 if (unlikely(!csum_ok))
1498                                         pkt->ol_flags |= PKT_RX_IP_CKSUM_BAD;
1499
1500                                 if ((cpl->l2info &
1501                                      htonl(F_RXF_UDP | F_RXF_TCP)) && !csum_ok)
1502                                         pkt->ol_flags |= PKT_RX_L4_CKSUM_BAD;
1503                         } else if (cpl->l2info & htonl(F_RXF_IP6)) {
1504                                 pkt->packet_type = RTE_PTYPE_L3_IPV6;
1505                         }
1506
1507                         if (!rss_hdr->filter_tid && rss_hdr->hash_type) {
1508                                 pkt->ol_flags |= PKT_RX_RSS_HASH;
1509                                 pkt->hash.rss = ntohl(rss_hdr->hash_val);
1510                         }
1511
1512                         if (cpl->vlan_ex) {
1513                                 pkt->ol_flags |= PKT_RX_VLAN_PKT;
1514                                 pkt->vlan_tci = ntohs(cpl->vlan);
1515                         }
1516                         rxq->stats.pkts++;
1517                         rxq->stats.rx_bytes += pkt->pkt_len;
1518                         rx_pkts[budget - budget_left] = pkt;
1519                 } else if (likely(rsp_type == X_RSPD_TYPE_CPL)) {
1520                         ret = q->handler(q, q->cur_desc, NULL);
1521                 } else {
1522                         ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
1523                 }
1524
1525                 if (unlikely(ret)) {
1526                         /* couldn't process descriptor, back off for recovery */
1527                         q->next_intr_params = V_QINTR_TIMER_IDX(NOMEM_TMR_IDX);
1528                         break;
1529                 }
1530
1531                 rspq_next(q);
1532                 budget_left--;
1533
1534                 if (R_IDXDIFF(q, gts_idx) >= 64) {
1535                         unsigned int cidx_inc = R_IDXDIFF(q, gts_idx);
1536                         unsigned int params;
1537                         u32 val;
1538
1539                         if (fl_cap(&rxq->fl) - rxq->fl.avail >= 64)
1540                                 __refill_fl(q->adapter, &rxq->fl);
1541                         params = V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX);
1542                         q->next_intr_params = params;
1543                         val = V_CIDXINC(cidx_inc) | V_SEINTARM(params);
1544
1545                         if (unlikely(!q->bar2_addr))
1546                                 t4_write_reg(q->adapter, MYPF_REG(A_SGE_PF_GTS),
1547                                              val |
1548                                              V_INGRESSQID((u32)q->cntxt_id));
1549                         else {
1550                                 writel(val | V_INGRESSQID(q->bar2_qid),
1551                                        (void *)((uintptr_t)q->bar2_addr +
1552                                        SGE_UDB_GTS));
1553                                 /*
1554                                  * This Write memory Barrier will force the
1555                                  * write to the User Doorbell area to be
1556                                  * flushed.
1557                                  */
1558                                 wmb();
1559                         }
1560                         q->gts_idx = q->cidx;
1561                 }
1562         }
1563
1564         /*
1565          * If this is a Response Queue with an associated Free List and
1566          * there's room for another chunk of new Free List buffer pointers,
1567          * refill the Free List.
1568          */
1569
1570         if (q->offset >= 0 && fl_cap(&rxq->fl) - rxq->fl.avail >= 64)
1571                 __refill_fl(q->adapter, &rxq->fl);
1572
1573         return budget - budget_left;
1574 }
1575
1576 int cxgbe_poll(struct sge_rspq *q, struct rte_mbuf **rx_pkts,
1577                unsigned int budget, unsigned int *work_done)
1578 {
1579         int err = 0;
1580
1581         *work_done = process_responses(q, budget, rx_pkts);
1582         return err;
1583 }
1584
1585 /**
1586  * bar2_address - return the BAR2 address for an SGE Queue's Registers
1587  * @adapter: the adapter
1588  * @qid: the SGE Queue ID
1589  * @qtype: the SGE Queue Type (Egress or Ingress)
1590  * @pbar2_qid: BAR2 Queue ID or 0 for Queue ID inferred SGE Queues
1591  *
1592  * Returns the BAR2 address for the SGE Queue Registers associated with
1593  * @qid.  If BAR2 SGE Registers aren't available, returns NULL.  Also
1594  * returns the BAR2 Queue ID to be used with writes to the BAR2 SGE
1595  * Queue Registers.  If the BAR2 Queue ID is 0, then "Inferred Queue ID"
1596  * Registers are supported (e.g. the Write Combining Doorbell Buffer).
1597  */
1598 static void __iomem *bar2_address(struct adapter *adapter, unsigned int qid,
1599                                   enum t4_bar2_qtype qtype,
1600                                   unsigned int *pbar2_qid)
1601 {
1602         u64 bar2_qoffset;
1603         int ret;
1604
1605         ret = t4_bar2_sge_qregs(adapter, qid, qtype, &bar2_qoffset, pbar2_qid);
1606         if (ret)
1607                 return NULL;
1608
1609         return adapter->bar2 + bar2_qoffset;
1610 }
1611
1612 int t4_sge_eth_rxq_start(struct adapter *adap, struct sge_rspq *rq)
1613 {
1614         struct sge_eth_rxq *rxq = container_of(rq, struct sge_eth_rxq, rspq);
1615         unsigned int fl_id = rxq->fl.size ? rxq->fl.cntxt_id : 0xffff;
1616
1617         return t4_iq_start_stop(adap, adap->mbox, true, adap->pf, 0,
1618                                 rq->cntxt_id, fl_id, 0xffff);
1619 }
1620
1621 int t4_sge_eth_rxq_stop(struct adapter *adap, struct sge_rspq *rq)
1622 {
1623         struct sge_eth_rxq *rxq = container_of(rq, struct sge_eth_rxq, rspq);
1624         unsigned int fl_id = rxq->fl.size ? rxq->fl.cntxt_id : 0xffff;
1625
1626         return t4_iq_start_stop(adap, adap->mbox, false, adap->pf, 0,
1627                                 rq->cntxt_id, fl_id, 0xffff);
1628 }
1629
1630 /*
1631  * @intr_idx: MSI/MSI-X vector if >=0, -(absolute qid + 1) if < 0
1632  * @cong: < 0 -> no congestion feedback, >= 0 -> congestion channel map
1633  */
1634 int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
1635                      struct rte_eth_dev *eth_dev, int intr_idx,
1636                      struct sge_fl *fl, rspq_handler_t hnd, int cong,
1637                      struct rte_mempool *mp, int queue_id, int socket_id)
1638 {
1639         int ret, flsz = 0;
1640         struct fw_iq_cmd c;
1641         struct sge *s = &adap->sge;
1642         struct port_info *pi = (struct port_info *)(eth_dev->data->dev_private);
1643         char z_name[RTE_MEMZONE_NAMESIZE];
1644         char z_name_sw[RTE_MEMZONE_NAMESIZE];
1645         unsigned int nb_refill;
1646
1647         /* Size needs to be multiple of 16, including status entry. */
1648         iq->size = cxgbe_roundup(iq->size, 16);
1649
1650         snprintf(z_name, sizeof(z_name), "%s_%s_%d_%d",
1651                  eth_dev->driver->pci_drv.name, fwevtq ? "fwq_ring" : "rx_ring",
1652                  eth_dev->data->port_id, queue_id);
1653         snprintf(z_name_sw, sizeof(z_name_sw), "%s_sw_ring", z_name);
1654
1655         iq->desc = alloc_ring(iq->size, iq->iqe_len, 0, &iq->phys_addr, NULL, 0,
1656                               queue_id, socket_id, z_name, z_name_sw);
1657         if (!iq->desc)
1658                 return -ENOMEM;
1659
1660         memset(&c, 0, sizeof(c));
1661         c.op_to_vfn = htonl(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
1662                             F_FW_CMD_WRITE | F_FW_CMD_EXEC |
1663                             V_FW_IQ_CMD_PFN(adap->pf) | V_FW_IQ_CMD_VFN(0));
1664         c.alloc_to_len16 = htonl(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
1665                                  (sizeof(c) / 16));
1666         c.type_to_iqandstindex =
1667                 htonl(V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
1668                       V_FW_IQ_CMD_IQASYNCH(fwevtq) |
1669                       V_FW_IQ_CMD_VIID(pi->viid) |
1670                       V_FW_IQ_CMD_IQANDST(intr_idx < 0) |
1671                       V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT) |
1672                       V_FW_IQ_CMD_IQANDSTINDEX(intr_idx >= 0 ? intr_idx :
1673                                                                -intr_idx - 1));
1674         c.iqdroprss_to_iqesize =
1675                 htons(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
1676                       F_FW_IQ_CMD_IQGTSMODE |
1677                       V_FW_IQ_CMD_IQINTCNTTHRESH(iq->pktcnt_idx) |
1678                       V_FW_IQ_CMD_IQESIZE(ilog2(iq->iqe_len) - 4));
1679         c.iqsize = htons(iq->size);
1680         c.iqaddr = cpu_to_be64(iq->phys_addr);
1681         if (cong >= 0)
1682                 c.iqns_to_fl0congen = htonl(F_FW_IQ_CMD_IQFLINTCONGEN);
1683
1684         if (fl) {
1685                 struct sge_eth_rxq *rxq = container_of(fl, struct sge_eth_rxq,
1686                                                        fl);
1687                 enum chip_type chip = (enum chip_type)CHELSIO_CHIP_VERSION(
1688                                 adap->params.chip);
1689
1690                 /*
1691                  * Allocate the ring for the hardware free list (with space
1692                  * for its status page) along with the associated software
1693                  * descriptor ring.  The free list size needs to be a multiple
1694                  * of the Egress Queue Unit and at least 2 Egress Units larger
1695                  * than the SGE's Egress Congrestion Threshold
1696                  * (fl_starve_thres - 1).
1697                  */
1698                 if (fl->size < s->fl_starve_thres - 1 + 2 * 8)
1699                         fl->size = s->fl_starve_thres - 1 + 2 * 8;
1700                 fl->size = cxgbe_roundup(fl->size, 8);
1701
1702                 snprintf(z_name, sizeof(z_name), "%s_%s_%d_%d",
1703                          eth_dev->driver->pci_drv.name,
1704                          fwevtq ? "fwq_ring" : "fl_ring",
1705                          eth_dev->data->port_id, queue_id);
1706                 snprintf(z_name_sw, sizeof(z_name_sw), "%s_sw_ring", z_name);
1707
1708                 fl->desc = alloc_ring(fl->size, sizeof(__be64),
1709                                       sizeof(struct rx_sw_desc),
1710                                       &fl->addr, &fl->sdesc, s->stat_len,
1711                                       queue_id, socket_id, z_name, z_name_sw);
1712
1713                 if (!fl->desc)
1714                         goto fl_nomem;
1715
1716                 flsz = fl->size / 8 + s->stat_len / sizeof(struct tx_desc);
1717                 c.iqns_to_fl0congen |=
1718                         htonl(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
1719                               (unlikely(rxq->usembufs) ?
1720                                0 : F_FW_IQ_CMD_FL0PACKEN) |
1721                               F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
1722                               F_FW_IQ_CMD_FL0PADEN);
1723                 if (cong >= 0)
1724                         c.iqns_to_fl0congen |=
1725                                 htonl(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
1726                                       F_FW_IQ_CMD_FL0CONGCIF |
1727                                       F_FW_IQ_CMD_FL0CONGEN);
1728
1729                 /* In T6, for egress queue type FL there is internal overhead
1730                  * of 16B for header going into FLM module.
1731                  * Hence maximum allowed burst size will be 448 bytes.
1732                  */
1733                 c.fl0dcaen_to_fl0cidxfthresh =
1734                         htons(V_FW_IQ_CMD_FL0FBMIN(X_FETCHBURSTMIN_128B) |
1735                               V_FW_IQ_CMD_FL0FBMAX((chip <= CHELSIO_T5) ?
1736                               X_FETCHBURSTMAX_512B : X_FETCHBURSTMAX_256B));
1737                 c.fl0size = htons(flsz);
1738                 c.fl0addr = cpu_to_be64(fl->addr);
1739         }
1740
1741         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
1742         if (ret)
1743                 goto err;
1744
1745         iq->cur_desc = iq->desc;
1746         iq->cidx = 0;
1747         iq->gts_idx = 0;
1748         iq->gen = 1;
1749         iq->next_intr_params = iq->intr_params;
1750         iq->cntxt_id = ntohs(c.iqid);
1751         iq->abs_id = ntohs(c.physiqid);
1752         iq->bar2_addr = bar2_address(adap, iq->cntxt_id, T4_BAR2_QTYPE_INGRESS,
1753                                      &iq->bar2_qid);
1754         iq->size--;                           /* subtract status entry */
1755         iq->eth_dev = eth_dev;
1756         iq->handler = hnd;
1757         iq->port_id = pi->port_id;
1758         iq->mb_pool = mp;
1759
1760         /* set offset to -1 to distinguish ingress queues without FL */
1761         iq->offset = fl ? 0 : -1;
1762
1763         if (fl) {
1764                 fl->cntxt_id = ntohs(c.fl0id);
1765                 fl->avail = 0;
1766                 fl->pend_cred = 0;
1767                 fl->pidx = 0;
1768                 fl->cidx = 0;
1769                 fl->alloc_failed = 0;
1770
1771                 /*
1772                  * Note, we must initialize the BAR2 Free List User Doorbell
1773                  * information before refilling the Free List!
1774                  */
1775                 fl->bar2_addr = bar2_address(adap, fl->cntxt_id,
1776                                              T4_BAR2_QTYPE_EGRESS,
1777                                              &fl->bar2_qid);
1778
1779                 nb_refill = refill_fl(adap, fl, fl_cap(fl));
1780                 if (nb_refill != fl_cap(fl)) {
1781                         ret = -ENOMEM;
1782                         dev_err(adap, "%s: mbuf alloc failed with error: %d\n",
1783                                 __func__, ret);
1784                         goto refill_fl_err;
1785                 }
1786         }
1787
1788         /*
1789          * For T5 and later we attempt to set up the Congestion Manager values
1790          * of the new RX Ethernet Queue.  This should really be handled by
1791          * firmware because it's more complex than any host driver wants to
1792          * get involved with and it's different per chip and this is almost
1793          * certainly wrong.  Formware would be wrong as well, but it would be
1794          * a lot easier to fix in one place ...  For now we do something very
1795          * simple (and hopefully less wrong).
1796          */
1797         if (!is_t4(adap->params.chip) && cong >= 0) {
1798                 u32 param, val;
1799                 int i;
1800
1801                 param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
1802                          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
1803                          V_FW_PARAMS_PARAM_YZ(iq->cntxt_id));
1804                 if (cong == 0) {
1805                         val = V_CONMCTXT_CNGTPMODE(X_CONMCTXT_CNGTPMODE_QUEUE);
1806                 } else {
1807                         val = V_CONMCTXT_CNGTPMODE(
1808                                         X_CONMCTXT_CNGTPMODE_CHANNEL);
1809                         for (i = 0; i < 4; i++) {
1810                                 if (cong & (1 << i))
1811                                         val |= V_CONMCTXT_CNGCHMAP(1 <<
1812                                                                    (i << 2));
1813                         }
1814                 }
1815                 ret = t4_set_params(adap, adap->mbox, adap->pf, 0, 1,
1816                                     &param, &val);
1817                 if (ret)
1818                         dev_warn(adap->pdev_dev, "Failed to set Congestion Manager Context for Ingress Queue %d: %d\n",
1819                                  iq->cntxt_id, -ret);
1820         }
1821
1822         return 0;
1823
1824 refill_fl_err:
1825         t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
1826                    iq->cntxt_id, fl->cntxt_id, 0xffff);
1827 fl_nomem:
1828         ret = -ENOMEM;
1829 err:
1830         iq->cntxt_id = 0;
1831         iq->abs_id = 0;
1832         if (iq->desc)
1833                 iq->desc = NULL;
1834
1835         if (fl && fl->desc) {
1836                 rte_free(fl->sdesc);
1837                 fl->cntxt_id = 0;
1838                 fl->sdesc = NULL;
1839                 fl->desc = NULL;
1840         }
1841         return ret;
1842 }
1843
1844 static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id)
1845 {
1846         q->cntxt_id = id;
1847         q->bar2_addr = bar2_address(adap, q->cntxt_id, T4_BAR2_QTYPE_EGRESS,
1848                                     &q->bar2_qid);
1849         q->cidx = 0;
1850         q->pidx = 0;
1851         q->dbidx = 0;
1852         q->in_use = 0;
1853         q->equeidx = 0;
1854         q->coalesce.idx = 0;
1855         q->coalesce.len = 0;
1856         q->coalesce.flits = 0;
1857         q->last_coal_idx = 0;
1858         q->last_pidx = 0;
1859         q->stat = (void *)&q->desc[q->size];
1860 }
1861
1862 int t4_sge_eth_txq_start(struct sge_eth_txq *txq)
1863 {
1864         /*
1865          *  TODO: For flow-control, queue may be stopped waiting to reclaim
1866          *  credits.
1867          *  Ensure queue is in EQ_STOPPED state before starting it.
1868          */
1869         if (!(txq->flags & EQ_STOPPED))
1870                 return -(EBUSY);
1871
1872         txq->flags &= ~EQ_STOPPED;
1873
1874         return 0;
1875 }
1876
1877 int t4_sge_eth_txq_stop(struct sge_eth_txq *txq)
1878 {
1879         txq->flags |= EQ_STOPPED;
1880
1881         return 0;
1882 }
1883
1884 int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
1885                          struct rte_eth_dev *eth_dev, uint16_t queue_id,
1886                          unsigned int iqid, int socket_id)
1887 {
1888         int ret, nentries;
1889         struct fw_eq_eth_cmd c;
1890         struct sge *s = &adap->sge;
1891         struct port_info *pi = (struct port_info *)(eth_dev->data->dev_private);
1892         char z_name[RTE_MEMZONE_NAMESIZE];
1893         char z_name_sw[RTE_MEMZONE_NAMESIZE];
1894
1895         /* Add status entries */
1896         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
1897
1898         snprintf(z_name, sizeof(z_name), "%s_%s_%d_%d",
1899                  eth_dev->driver->pci_drv.name, "tx_ring",
1900                  eth_dev->data->port_id, queue_id);
1901         snprintf(z_name_sw, sizeof(z_name_sw), "%s_sw_ring", z_name);
1902
1903         txq->q.desc = alloc_ring(txq->q.size, sizeof(struct tx_desc),
1904                                  sizeof(struct tx_sw_desc), &txq->q.phys_addr,
1905                                  &txq->q.sdesc, s->stat_len, queue_id,
1906                                  socket_id, z_name, z_name_sw);
1907         if (!txq->q.desc)
1908                 return -ENOMEM;
1909
1910         memset(&c, 0, sizeof(c));
1911         c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
1912                             F_FW_CMD_WRITE | F_FW_CMD_EXEC |
1913                             V_FW_EQ_ETH_CMD_PFN(adap->pf) |
1914                             V_FW_EQ_ETH_CMD_VFN(0));
1915         c.alloc_to_len16 = htonl(F_FW_EQ_ETH_CMD_ALLOC |
1916                                  F_FW_EQ_ETH_CMD_EQSTART | (sizeof(c) / 16));
1917         c.autoequiqe_to_viid = htonl(F_FW_EQ_ETH_CMD_AUTOEQUEQE |
1918                                      V_FW_EQ_ETH_CMD_VIID(pi->viid));
1919         c.fetchszm_to_iqid =
1920                 htonl(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
1921                       V_FW_EQ_ETH_CMD_PCIECHN(pi->tx_chan) |
1922                       F_FW_EQ_ETH_CMD_FETCHRO | V_FW_EQ_ETH_CMD_IQID(iqid));
1923         c.dcaen_to_eqsize =
1924                 htonl(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
1925                       V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
1926                       V_FW_EQ_ETH_CMD_EQSIZE(nentries));
1927         c.eqaddr = rte_cpu_to_be_64(txq->q.phys_addr);
1928
1929         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
1930         if (ret) {
1931                 rte_free(txq->q.sdesc);
1932                 txq->q.sdesc = NULL;
1933                 txq->q.desc = NULL;
1934                 return ret;
1935         }
1936
1937         init_txq(adap, &txq->q, G_FW_EQ_ETH_CMD_EQID(ntohl(c.eqid_pkd)));
1938         txq->stats.tso = 0;
1939         txq->stats.pkts = 0;
1940         txq->stats.tx_cso = 0;
1941         txq->stats.coal_wr = 0;
1942         txq->stats.vlan_ins = 0;
1943         txq->stats.tx_bytes = 0;
1944         txq->stats.coal_pkts = 0;
1945         txq->stats.mapping_err = 0;
1946         txq->flags |= EQ_STOPPED;
1947         txq->eth_dev = eth_dev;
1948         t4_os_lock_init(&txq->txq_lock);
1949         return 0;
1950 }
1951
1952 static void free_txq(struct sge_txq *q)
1953 {
1954         q->cntxt_id = 0;
1955         q->sdesc = NULL;
1956         q->desc = NULL;
1957 }
1958
1959 static void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
1960                          struct sge_fl *fl)
1961 {
1962         unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
1963
1964         t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
1965                    rq->cntxt_id, fl_id, 0xffff);
1966         rq->cntxt_id = 0;
1967         rq->abs_id = 0;
1968         rq->desc = NULL;
1969
1970         if (fl) {
1971                 free_rx_bufs(fl, fl->avail);
1972                 rte_free(fl->sdesc);
1973                 fl->sdesc = NULL;
1974                 fl->cntxt_id = 0;
1975                 fl->desc = NULL;
1976         }
1977 }
1978
1979 /*
1980  * Clear all queues of the port
1981  *
1982  * Note:  This function must only be called after rx and tx path
1983  * of the port have been disabled.
1984  */
1985 void t4_sge_eth_clear_queues(struct port_info *pi)
1986 {
1987         int i;
1988         struct adapter *adap = pi->adapter;
1989         struct sge_eth_rxq *rxq = &adap->sge.ethrxq[pi->first_qset];
1990         struct sge_eth_txq *txq = &adap->sge.ethtxq[pi->first_qset];
1991
1992         for (i = 0; i < pi->n_rx_qsets; i++, rxq++) {
1993                 if (rxq->rspq.desc)
1994                         t4_sge_eth_rxq_stop(adap, &rxq->rspq);
1995         }
1996         for (i = 0; i < pi->n_tx_qsets; i++, txq++) {
1997                 if (txq->q.desc) {
1998                         struct sge_txq *q = &txq->q;
1999
2000                         t4_sge_eth_txq_stop(txq);
2001                         reclaim_completed_tx(q);
2002                         free_tx_desc(q, q->size);
2003                         q->equeidx = q->pidx;
2004                 }
2005         }
2006 }
2007
2008 void t4_sge_eth_rxq_release(struct adapter *adap, struct sge_eth_rxq *rxq)
2009 {
2010         if (rxq->rspq.desc) {
2011                 t4_sge_eth_rxq_stop(adap, &rxq->rspq);
2012                 free_rspq_fl(adap, &rxq->rspq, rxq->fl.size ? &rxq->fl : NULL);
2013         }
2014 }
2015
2016 void t4_sge_eth_txq_release(struct adapter *adap, struct sge_eth_txq *txq)
2017 {
2018         if (txq->q.desc) {
2019                 t4_sge_eth_txq_stop(txq);
2020                 reclaim_completed_tx(&txq->q);
2021                 t4_eth_eq_free(adap, adap->mbox, adap->pf, 0, txq->q.cntxt_id);
2022                 free_tx_desc(&txq->q, txq->q.size);
2023                 rte_free(txq->q.sdesc);
2024                 free_txq(&txq->q);
2025         }
2026 }
2027
2028 void t4_sge_tx_monitor_start(struct adapter *adap)
2029 {
2030         rte_eal_alarm_set(50, tx_timer_cb, (void *)adap);
2031 }
2032
2033 void t4_sge_tx_monitor_stop(struct adapter *adap)
2034 {
2035         rte_eal_alarm_cancel(tx_timer_cb, (void *)adap);
2036 }
2037
2038 /**
2039  * t4_free_sge_resources - free SGE resources
2040  * @adap: the adapter
2041  *
2042  * Frees resources used by the SGE queue sets.
2043  */
2044 void t4_free_sge_resources(struct adapter *adap)
2045 {
2046         int i;
2047         struct sge_eth_rxq *rxq = &adap->sge.ethrxq[0];
2048         struct sge_eth_txq *txq = &adap->sge.ethtxq[0];
2049
2050         /* clean up Ethernet Tx/Rx queues */
2051         for (i = 0; i < adap->sge.max_ethqsets; i++, rxq++, txq++) {
2052                 /* Free only the queues allocated */
2053                 if (rxq->rspq.desc) {
2054                         t4_sge_eth_rxq_release(adap, rxq);
2055                         rxq->rspq.eth_dev = NULL;
2056                 }
2057                 if (txq->q.desc) {
2058                         t4_sge_eth_txq_release(adap, txq);
2059                         txq->eth_dev = NULL;
2060                 }
2061         }
2062
2063         if (adap->sge.fw_evtq.desc)
2064                 free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
2065 }
2066
2067 /**
2068  * t4_sge_init - initialize SGE
2069  * @adap: the adapter
2070  *
2071  * Performs SGE initialization needed every time after a chip reset.
2072  * We do not initialize any of the queues here, instead the driver
2073  * top-level must request those individually.
2074  *
2075  * Called in two different modes:
2076  *
2077  *  1. Perform actual hardware initialization and record hard-coded
2078  *     parameters which were used.  This gets used when we're the
2079  *     Master PF and the Firmware Configuration File support didn't
2080  *     work for some reason.
2081  *
2082  *  2. We're not the Master PF or initialization was performed with
2083  *     a Firmware Configuration File.  In this case we need to grab
2084  *     any of the SGE operating parameters that we need to have in
2085  *     order to do our job and make sure we can live with them ...
2086  */
2087 static int t4_sge_init_soft(struct adapter *adap)
2088 {
2089         struct sge *s = &adap->sge;
2090         u32 fl_small_pg, fl_large_pg, fl_small_mtu, fl_large_mtu;
2091         u32 timer_value_0_and_1, timer_value_2_and_3, timer_value_4_and_5;
2092         u32 ingress_rx_threshold;
2093
2094         /*
2095          * Verify that CPL messages are going to the Ingress Queue for
2096          * process_responses() and that only packet data is going to the
2097          * Free Lists.
2098          */
2099         if ((t4_read_reg(adap, A_SGE_CONTROL) & F_RXPKTCPLMODE) !=
2100             V_RXPKTCPLMODE(X_RXPKTCPLMODE_SPLIT)) {
2101                 dev_err(adap, "bad SGE CPL MODE\n");
2102                 return -EINVAL;
2103         }
2104
2105         /*
2106          * Validate the Host Buffer Register Array indices that we want to
2107          * use ...
2108          *
2109          * XXX Note that we should really read through the Host Buffer Size
2110          * XXX register array and find the indices of the Buffer Sizes which
2111          * XXX meet our needs!
2112          */
2113 #define READ_FL_BUF(x) \
2114         t4_read_reg(adap, A_SGE_FL_BUFFER_SIZE0 + (x) * sizeof(u32))
2115
2116         fl_small_pg = READ_FL_BUF(RX_SMALL_PG_BUF);
2117         fl_large_pg = READ_FL_BUF(RX_LARGE_PG_BUF);
2118         fl_small_mtu = READ_FL_BUF(RX_SMALL_MTU_BUF);
2119         fl_large_mtu = READ_FL_BUF(RX_LARGE_MTU_BUF);
2120
2121         /*
2122          * We only bother using the Large Page logic if the Large Page Buffer
2123          * is larger than our Page Size Buffer.
2124          */
2125         if (fl_large_pg <= fl_small_pg)
2126                 fl_large_pg = 0;
2127
2128 #undef READ_FL_BUF
2129
2130         /*
2131          * The Page Size Buffer must be exactly equal to our Page Size and the
2132          * Large Page Size Buffer should be 0 (per above) or a power of 2.
2133          */
2134         if (fl_small_pg != CXGBE_PAGE_SIZE ||
2135             (fl_large_pg & (fl_large_pg - 1)) != 0) {
2136                 dev_err(adap, "bad SGE FL page buffer sizes [%d, %d]\n",
2137                         fl_small_pg, fl_large_pg);
2138                 return -EINVAL;
2139         }
2140         if (fl_large_pg)
2141                 s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
2142
2143         if (adap->use_unpacked_mode) {
2144                 int err = 0;
2145
2146                 if (fl_small_mtu < FL_MTU_SMALL_BUFSIZE(adap)) {
2147                         dev_err(adap, "bad SGE FL small MTU %d\n",
2148                                 fl_small_mtu);
2149                         err = -EINVAL;
2150                 }
2151                 if (fl_large_mtu < FL_MTU_LARGE_BUFSIZE(adap)) {
2152                         dev_err(adap, "bad SGE FL large MTU %d\n",
2153                                 fl_large_mtu);
2154                         err = -EINVAL;
2155                 }
2156                 if (err)
2157                         return err;
2158         }
2159
2160         /*
2161          * Retrieve our RX interrupt holdoff timer values and counter
2162          * threshold values from the SGE parameters.
2163          */
2164         timer_value_0_and_1 = t4_read_reg(adap, A_SGE_TIMER_VALUE_0_AND_1);
2165         timer_value_2_and_3 = t4_read_reg(adap, A_SGE_TIMER_VALUE_2_AND_3);
2166         timer_value_4_and_5 = t4_read_reg(adap, A_SGE_TIMER_VALUE_4_AND_5);
2167         s->timer_val[0] = core_ticks_to_us(adap,
2168                                            G_TIMERVALUE0(timer_value_0_and_1));
2169         s->timer_val[1] = core_ticks_to_us(adap,
2170                                            G_TIMERVALUE1(timer_value_0_and_1));
2171         s->timer_val[2] = core_ticks_to_us(adap,
2172                                            G_TIMERVALUE2(timer_value_2_and_3));
2173         s->timer_val[3] = core_ticks_to_us(adap,
2174                                            G_TIMERVALUE3(timer_value_2_and_3));
2175         s->timer_val[4] = core_ticks_to_us(adap,
2176                                            G_TIMERVALUE4(timer_value_4_and_5));
2177         s->timer_val[5] = core_ticks_to_us(adap,
2178                                            G_TIMERVALUE5(timer_value_4_and_5));
2179
2180         ingress_rx_threshold = t4_read_reg(adap, A_SGE_INGRESS_RX_THRESHOLD);
2181         s->counter_val[0] = G_THRESHOLD_0(ingress_rx_threshold);
2182         s->counter_val[1] = G_THRESHOLD_1(ingress_rx_threshold);
2183         s->counter_val[2] = G_THRESHOLD_2(ingress_rx_threshold);
2184         s->counter_val[3] = G_THRESHOLD_3(ingress_rx_threshold);
2185
2186         return 0;
2187 }
2188
2189 int t4_sge_init(struct adapter *adap)
2190 {
2191         struct sge *s = &adap->sge;
2192         u32 sge_control, sge_control2, sge_conm_ctrl;
2193         unsigned int ingpadboundary, ingpackboundary;
2194         int ret, egress_threshold;
2195
2196         /*
2197          * Ingress Padding Boundary and Egress Status Page Size are set up by
2198          * t4_fixup_host_params().
2199          */
2200         sge_control = t4_read_reg(adap, A_SGE_CONTROL);
2201         s->pktshift = G_PKTSHIFT(sge_control);
2202         s->stat_len = (sge_control & F_EGRSTATUSPAGESIZE) ? 128 : 64;
2203
2204         /*
2205          * T4 uses a single control field to specify both the PCIe Padding and
2206          * Packing Boundary.  T5 introduced the ability to specify these
2207          * separately.  The actual Ingress Packet Data alignment boundary
2208          * within Packed Buffer Mode is the maximum of these two
2209          * specifications.
2210          */
2211         ingpadboundary = 1 << (G_INGPADBOUNDARY(sge_control) +
2212                          X_INGPADBOUNDARY_SHIFT);
2213         s->fl_align = ingpadboundary;
2214
2215         if (!is_t4(adap->params.chip) && !adap->use_unpacked_mode) {
2216                 /*
2217                  * T5 has a weird interpretation of one of the PCIe Packing
2218                  * Boundary values.  No idea why ...
2219                  */
2220                 sge_control2 = t4_read_reg(adap, A_SGE_CONTROL2);
2221                 ingpackboundary = G_INGPACKBOUNDARY(sge_control2);
2222                 if (ingpackboundary == X_INGPACKBOUNDARY_16B)
2223                         ingpackboundary = 16;
2224                 else
2225                         ingpackboundary = 1 << (ingpackboundary +
2226                                           X_INGPACKBOUNDARY_SHIFT);
2227
2228                 s->fl_align = max(ingpadboundary, ingpackboundary);
2229         }
2230
2231         ret = t4_sge_init_soft(adap);
2232         if (ret < 0) {
2233                 dev_err(adap, "%s: t4_sge_init_soft failed, error %d\n",
2234                         __func__, -ret);
2235                 return ret;
2236         }
2237
2238         /*
2239          * A FL with <= fl_starve_thres buffers is starving and a periodic
2240          * timer will attempt to refill it.  This needs to be larger than the
2241          * SGE's Egress Congestion Threshold.  If it isn't, then we can get
2242          * stuck waiting for new packets while the SGE is waiting for us to
2243          * give it more Free List entries.  (Note that the SGE's Egress
2244          * Congestion Threshold is in units of 2 Free List pointers.)  For T4,
2245          * there was only a single field to control this.  For T5 there's the
2246          * original field which now only applies to Unpacked Mode Free List
2247          * buffers and a new field which only applies to Packed Mode Free List
2248          * buffers.
2249          */
2250         sge_conm_ctrl = t4_read_reg(adap, A_SGE_CONM_CTRL);
2251         if (is_t4(adap->params.chip) || adap->use_unpacked_mode)
2252                 egress_threshold = G_EGRTHRESHOLD(sge_conm_ctrl);
2253         else
2254                 egress_threshold = G_EGRTHRESHOLDPACKING(sge_conm_ctrl);
2255         s->fl_starve_thres = 2 * egress_threshold + 1;
2256
2257         return 0;
2258 }