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