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