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