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