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