Merge branch 'linus' of git://git.kernel.org/pub/scm/linux/kernel/git/herbert/crypto-2.6
[sfrench/cifs-2.6.git] / drivers / net / ethernet / chelsio / cxgb4 / sge.c
1 /*
2  * This file is part of the Chelsio T4 Ethernet driver for Linux.
3  *
4  * Copyright (c) 2003-2014 Chelsio Communications, Inc. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34
35 #include <linux/skbuff.h>
36 #include <linux/netdevice.h>
37 #include <linux/etherdevice.h>
38 #include <linux/if_vlan.h>
39 #include <linux/ip.h>
40 #include <linux/dma-mapping.h>
41 #include <linux/jiffies.h>
42 #include <linux/prefetch.h>
43 #include <linux/export.h>
44 #include <net/ipv6.h>
45 #include <net/tcp.h>
46 #include <net/busy_poll.h>
47 #ifdef CONFIG_CHELSIO_T4_FCOE
48 #include <scsi/fc/fc_fcoe.h>
49 #endif /* CONFIG_CHELSIO_T4_FCOE */
50 #include "cxgb4.h"
51 #include "t4_regs.h"
52 #include "t4_values.h"
53 #include "t4_msg.h"
54 #include "t4fw_api.h"
55 #include "cxgb4_ptp.h"
56
57 /*
58  * Rx buffer size.  We use largish buffers if possible but settle for single
59  * pages under memory shortage.
60  */
61 #if PAGE_SHIFT >= 16
62 # define FL_PG_ORDER 0
63 #else
64 # define FL_PG_ORDER (16 - PAGE_SHIFT)
65 #endif
66
67 /* RX_PULL_LEN should be <= RX_COPY_THRES */
68 #define RX_COPY_THRES    256
69 #define RX_PULL_LEN      128
70
71 /*
72  * Main body length for sk_buffs used for Rx Ethernet packets with fragments.
73  * Should be >= RX_PULL_LEN but possibly bigger to give pskb_may_pull some room.
74  */
75 #define RX_PKT_SKB_LEN   512
76
77 /*
78  * Max number of Tx descriptors we clean up at a time.  Should be modest as
79  * freeing skbs isn't cheap and it happens while holding locks.  We just need
80  * to free packets faster than they arrive, we eventually catch up and keep
81  * the amortized cost reasonable.  Must be >= 2 * TXQ_STOP_THRES.
82  */
83 #define MAX_TX_RECLAIM 16
84
85 /*
86  * Max number of Rx buffers we replenish at a time.  Again keep this modest,
87  * allocating buffers isn't cheap either.
88  */
89 #define MAX_RX_REFILL 16U
90
91 /*
92  * Period of the Rx queue check timer.  This timer is infrequent as it has
93  * something to do only when the system experiences severe memory shortage.
94  */
95 #define RX_QCHECK_PERIOD (HZ / 2)
96
97 /*
98  * Period of the Tx queue check timer.
99  */
100 #define TX_QCHECK_PERIOD (HZ / 2)
101
102 /*
103  * Max number of Tx descriptors to be reclaimed by the Tx timer.
104  */
105 #define MAX_TIMER_TX_RECLAIM 100
106
107 /*
108  * Timer index used when backing off due to memory shortage.
109  */
110 #define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
111
112 /*
113  * Suspend an Ethernet Tx queue with fewer available descriptors than this.
114  * This is the same as calc_tx_descs() for a TSO packet with
115  * nr_frags == MAX_SKB_FRAGS.
116  */
117 #define ETHTXQ_STOP_THRES \
118         (1 + DIV_ROUND_UP((3 * MAX_SKB_FRAGS) / 2 + (MAX_SKB_FRAGS & 1), 8))
119
120 /*
121  * Suspension threshold for non-Ethernet Tx queues.  We require enough room
122  * for a full sized WR.
123  */
124 #define TXQ_STOP_THRES (SGE_MAX_WR_LEN / sizeof(struct tx_desc))
125
126 /*
127  * Max Tx descriptor space we allow for an Ethernet packet to be inlined
128  * into a WR.
129  */
130 #define MAX_IMM_TX_PKT_LEN 256
131
132 /*
133  * Max size of a WR sent through a control Tx queue.
134  */
135 #define MAX_CTRL_WR_LEN SGE_MAX_WR_LEN
136
137 struct tx_sw_desc {                /* SW state per Tx descriptor */
138         struct sk_buff *skb;
139         struct ulptx_sgl *sgl;
140 };
141
142 struct rx_sw_desc {                /* SW state per Rx descriptor */
143         struct page *page;
144         dma_addr_t dma_addr;
145 };
146
147 /*
148  * Rx buffer sizes for "useskbs" Free List buffers (one ingress packet pe skb
149  * buffer).  We currently only support two sizes for 1500- and 9000-byte MTUs.
150  * We could easily support more but there doesn't seem to be much need for
151  * that ...
152  */
153 #define FL_MTU_SMALL 1500
154 #define FL_MTU_LARGE 9000
155
156 static inline unsigned int fl_mtu_bufsize(struct adapter *adapter,
157                                           unsigned int mtu)
158 {
159         struct sge *s = &adapter->sge;
160
161         return ALIGN(s->pktshift + ETH_HLEN + VLAN_HLEN + mtu, s->fl_align);
162 }
163
164 #define FL_MTU_SMALL_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_SMALL)
165 #define FL_MTU_LARGE_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_LARGE)
166
167 /*
168  * Bits 0..3 of rx_sw_desc.dma_addr have special meaning.  The hardware uses
169  * these to specify the buffer size as an index into the SGE Free List Buffer
170  * Size register array.  We also use bit 4, when the buffer has been unmapped
171  * for DMA, but this is of course never sent to the hardware and is only used
172  * to prevent double unmappings.  All of the above requires that the Free List
173  * Buffers which we allocate have the bottom 5 bits free (0) -- i.e. are
174  * 32-byte or or a power of 2 greater in alignment.  Since the SGE's minimal
175  * Free List Buffer alignment is 32 bytes, this works out for us ...
176  */
177 enum {
178         RX_BUF_FLAGS     = 0x1f,   /* bottom five bits are special */
179         RX_BUF_SIZE      = 0x0f,   /* bottom three bits are for buf sizes */
180         RX_UNMAPPED_BUF  = 0x10,   /* buffer is not mapped */
181
182         /*
183          * XXX We shouldn't depend on being able to use these indices.
184          * XXX Especially when some other Master PF has initialized the
185          * XXX adapter or we use the Firmware Configuration File.  We
186          * XXX should really search through the Host Buffer Size register
187          * XXX array for the appropriately sized buffer indices.
188          */
189         RX_SMALL_PG_BUF  = 0x0,   /* small (PAGE_SIZE) page buffer */
190         RX_LARGE_PG_BUF  = 0x1,   /* buffer large (FL_PG_ORDER) page buffer */
191
192         RX_SMALL_MTU_BUF = 0x2,   /* small MTU buffer */
193         RX_LARGE_MTU_BUF = 0x3,   /* large MTU buffer */
194 };
195
196 static int timer_pkt_quota[] = {1, 1, 2, 3, 4, 5};
197 #define MIN_NAPI_WORK  1
198
199 static inline dma_addr_t get_buf_addr(const struct rx_sw_desc *d)
200 {
201         return d->dma_addr & ~(dma_addr_t)RX_BUF_FLAGS;
202 }
203
204 static inline bool is_buf_mapped(const struct rx_sw_desc *d)
205 {
206         return !(d->dma_addr & RX_UNMAPPED_BUF);
207 }
208
209 /**
210  *      txq_avail - return the number of available slots in a Tx queue
211  *      @q: the Tx queue
212  *
213  *      Returns the number of descriptors in a Tx queue available to write new
214  *      packets.
215  */
216 static inline unsigned int txq_avail(const struct sge_txq *q)
217 {
218         return q->size - 1 - q->in_use;
219 }
220
221 /**
222  *      fl_cap - return the capacity of a free-buffer list
223  *      @fl: the FL
224  *
225  *      Returns the capacity of a free-buffer list.  The capacity is less than
226  *      the size because one descriptor needs to be left unpopulated, otherwise
227  *      HW will think the FL is empty.
228  */
229 static inline unsigned int fl_cap(const struct sge_fl *fl)
230 {
231         return fl->size - 8;   /* 1 descriptor = 8 buffers */
232 }
233
234 /**
235  *      fl_starving - return whether a Free List is starving.
236  *      @adapter: pointer to the adapter
237  *      @fl: the Free List
238  *
239  *      Tests specified Free List to see whether the number of buffers
240  *      available to the hardware has falled below our "starvation"
241  *      threshold.
242  */
243 static inline bool fl_starving(const struct adapter *adapter,
244                                const struct sge_fl *fl)
245 {
246         const struct sge *s = &adapter->sge;
247
248         return fl->avail - fl->pend_cred <= s->fl_starve_thres;
249 }
250
251 static int map_skb(struct device *dev, const struct sk_buff *skb,
252                    dma_addr_t *addr)
253 {
254         const skb_frag_t *fp, *end;
255         const struct skb_shared_info *si;
256
257         *addr = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
258         if (dma_mapping_error(dev, *addr))
259                 goto out_err;
260
261         si = skb_shinfo(skb);
262         end = &si->frags[si->nr_frags];
263
264         for (fp = si->frags; fp < end; fp++) {
265                 *++addr = skb_frag_dma_map(dev, fp, 0, skb_frag_size(fp),
266                                            DMA_TO_DEVICE);
267                 if (dma_mapping_error(dev, *addr))
268                         goto unwind;
269         }
270         return 0;
271
272 unwind:
273         while (fp-- > si->frags)
274                 dma_unmap_page(dev, *--addr, skb_frag_size(fp), DMA_TO_DEVICE);
275
276         dma_unmap_single(dev, addr[-1], skb_headlen(skb), DMA_TO_DEVICE);
277 out_err:
278         return -ENOMEM;
279 }
280
281 #ifdef CONFIG_NEED_DMA_MAP_STATE
282 static void unmap_skb(struct device *dev, const struct sk_buff *skb,
283                       const dma_addr_t *addr)
284 {
285         const skb_frag_t *fp, *end;
286         const struct skb_shared_info *si;
287
288         dma_unmap_single(dev, *addr++, skb_headlen(skb), DMA_TO_DEVICE);
289
290         si = skb_shinfo(skb);
291         end = &si->frags[si->nr_frags];
292         for (fp = si->frags; fp < end; fp++)
293                 dma_unmap_page(dev, *addr++, skb_frag_size(fp), DMA_TO_DEVICE);
294 }
295
296 /**
297  *      deferred_unmap_destructor - unmap a packet when it is freed
298  *      @skb: the packet
299  *
300  *      This is the packet destructor used for Tx packets that need to remain
301  *      mapped until they are freed rather than until their Tx descriptors are
302  *      freed.
303  */
304 static void deferred_unmap_destructor(struct sk_buff *skb)
305 {
306         unmap_skb(skb->dev->dev.parent, skb, (dma_addr_t *)skb->head);
307 }
308 #endif
309
310 static void unmap_sgl(struct device *dev, const struct sk_buff *skb,
311                       const struct ulptx_sgl *sgl, const struct sge_txq *q)
312 {
313         const struct ulptx_sge_pair *p;
314         unsigned int nfrags = skb_shinfo(skb)->nr_frags;
315
316         if (likely(skb_headlen(skb)))
317                 dma_unmap_single(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
318                                  DMA_TO_DEVICE);
319         else {
320                 dma_unmap_page(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
321                                DMA_TO_DEVICE);
322                 nfrags--;
323         }
324
325         /*
326          * the complexity below is because of the possibility of a wrap-around
327          * in the middle of an SGL
328          */
329         for (p = sgl->sge; nfrags >= 2; nfrags -= 2) {
330                 if (likely((u8 *)(p + 1) <= (u8 *)q->stat)) {
331 unmap:                  dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
332                                        ntohl(p->len[0]), DMA_TO_DEVICE);
333                         dma_unmap_page(dev, be64_to_cpu(p->addr[1]),
334                                        ntohl(p->len[1]), DMA_TO_DEVICE);
335                         p++;
336                 } else if ((u8 *)p == (u8 *)q->stat) {
337                         p = (const struct ulptx_sge_pair *)q->desc;
338                         goto unmap;
339                 } else if ((u8 *)p + 8 == (u8 *)q->stat) {
340                         const __be64 *addr = (const __be64 *)q->desc;
341
342                         dma_unmap_page(dev, be64_to_cpu(addr[0]),
343                                        ntohl(p->len[0]), DMA_TO_DEVICE);
344                         dma_unmap_page(dev, be64_to_cpu(addr[1]),
345                                        ntohl(p->len[1]), DMA_TO_DEVICE);
346                         p = (const struct ulptx_sge_pair *)&addr[2];
347                 } else {
348                         const __be64 *addr = (const __be64 *)q->desc;
349
350                         dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
351                                        ntohl(p->len[0]), DMA_TO_DEVICE);
352                         dma_unmap_page(dev, be64_to_cpu(addr[0]),
353                                        ntohl(p->len[1]), DMA_TO_DEVICE);
354                         p = (const struct ulptx_sge_pair *)&addr[1];
355                 }
356         }
357         if (nfrags) {
358                 __be64 addr;
359
360                 if ((u8 *)p == (u8 *)q->stat)
361                         p = (const struct ulptx_sge_pair *)q->desc;
362                 addr = (u8 *)p + 16 <= (u8 *)q->stat ? p->addr[0] :
363                                                        *(const __be64 *)q->desc;
364                 dma_unmap_page(dev, be64_to_cpu(addr), ntohl(p->len[0]),
365                                DMA_TO_DEVICE);
366         }
367 }
368
369 /**
370  *      free_tx_desc - reclaims Tx descriptors and their buffers
371  *      @adapter: the adapter
372  *      @q: the Tx queue to reclaim descriptors from
373  *      @n: the number of descriptors to reclaim
374  *      @unmap: whether the buffers should be unmapped for DMA
375  *
376  *      Reclaims Tx descriptors from an SGE Tx queue and frees the associated
377  *      Tx buffers.  Called with the Tx queue lock held.
378  */
379 void free_tx_desc(struct adapter *adap, struct sge_txq *q,
380                   unsigned int n, bool unmap)
381 {
382         struct tx_sw_desc *d;
383         unsigned int cidx = q->cidx;
384         struct device *dev = adap->pdev_dev;
385
386         d = &q->sdesc[cidx];
387         while (n--) {
388                 if (d->skb) {                       /* an SGL is present */
389                         if (unmap)
390                                 unmap_sgl(dev, d->skb, d->sgl, q);
391                         dev_consume_skb_any(d->skb);
392                         d->skb = NULL;
393                 }
394                 ++d;
395                 if (++cidx == q->size) {
396                         cidx = 0;
397                         d = q->sdesc;
398                 }
399         }
400         q->cidx = cidx;
401 }
402
403 /*
404  * Return the number of reclaimable descriptors in a Tx queue.
405  */
406 static inline int reclaimable(const struct sge_txq *q)
407 {
408         int hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
409         hw_cidx -= q->cidx;
410         return hw_cidx < 0 ? hw_cidx + q->size : hw_cidx;
411 }
412
413 /**
414  *      reclaim_completed_tx - reclaims completed Tx descriptors
415  *      @adap: the adapter
416  *      @q: the Tx queue to reclaim completed descriptors from
417  *      @unmap: whether the buffers should be unmapped for DMA
418  *
419  *      Reclaims Tx descriptors that the SGE has indicated it has processed,
420  *      and frees the associated buffers if possible.  Called with the Tx
421  *      queue locked.
422  */
423 static inline void reclaim_completed_tx(struct adapter *adap, struct sge_txq *q,
424                                         bool unmap)
425 {
426         int avail = reclaimable(q);
427
428         if (avail) {
429                 /*
430                  * Limit the amount of clean up work we do at a time to keep
431                  * the Tx lock hold time O(1).
432                  */
433                 if (avail > MAX_TX_RECLAIM)
434                         avail = MAX_TX_RECLAIM;
435
436                 free_tx_desc(adap, q, avail, unmap);
437                 q->in_use -= avail;
438         }
439 }
440
441 static inline int get_buf_size(struct adapter *adapter,
442                                const struct rx_sw_desc *d)
443 {
444         struct sge *s = &adapter->sge;
445         unsigned int rx_buf_size_idx = d->dma_addr & RX_BUF_SIZE;
446         int buf_size;
447
448         switch (rx_buf_size_idx) {
449         case RX_SMALL_PG_BUF:
450                 buf_size = PAGE_SIZE;
451                 break;
452
453         case RX_LARGE_PG_BUF:
454                 buf_size = PAGE_SIZE << s->fl_pg_order;
455                 break;
456
457         case RX_SMALL_MTU_BUF:
458                 buf_size = FL_MTU_SMALL_BUFSIZE(adapter);
459                 break;
460
461         case RX_LARGE_MTU_BUF:
462                 buf_size = FL_MTU_LARGE_BUFSIZE(adapter);
463                 break;
464
465         default:
466                 BUG_ON(1);
467         }
468
469         return buf_size;
470 }
471
472 /**
473  *      free_rx_bufs - free the Rx buffers on an SGE free list
474  *      @adap: the adapter
475  *      @q: the SGE free list to free buffers from
476  *      @n: how many buffers to free
477  *
478  *      Release the next @n buffers on an SGE free-buffer Rx queue.   The
479  *      buffers must be made inaccessible to HW before calling this function.
480  */
481 static void free_rx_bufs(struct adapter *adap, struct sge_fl *q, int n)
482 {
483         while (n--) {
484                 struct rx_sw_desc *d = &q->sdesc[q->cidx];
485
486                 if (is_buf_mapped(d))
487                         dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
488                                        get_buf_size(adap, d),
489                                        PCI_DMA_FROMDEVICE);
490                 put_page(d->page);
491                 d->page = NULL;
492                 if (++q->cidx == q->size)
493                         q->cidx = 0;
494                 q->avail--;
495         }
496 }
497
498 /**
499  *      unmap_rx_buf - unmap the current Rx buffer on an SGE free list
500  *      @adap: the adapter
501  *      @q: the SGE free list
502  *
503  *      Unmap the current buffer on an SGE free-buffer Rx queue.   The
504  *      buffer must be made inaccessible to HW before calling this function.
505  *
506  *      This is similar to @free_rx_bufs above but does not free the buffer.
507  *      Do note that the FL still loses any further access to the buffer.
508  */
509 static void unmap_rx_buf(struct adapter *adap, struct sge_fl *q)
510 {
511         struct rx_sw_desc *d = &q->sdesc[q->cidx];
512
513         if (is_buf_mapped(d))
514                 dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
515                                get_buf_size(adap, d), PCI_DMA_FROMDEVICE);
516         d->page = NULL;
517         if (++q->cidx == q->size)
518                 q->cidx = 0;
519         q->avail--;
520 }
521
522 static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
523 {
524         if (q->pend_cred >= 8) {
525                 u32 val = adap->params.arch.sge_fl_db;
526
527                 if (is_t4(adap->params.chip))
528                         val |= PIDX_V(q->pend_cred / 8);
529                 else
530                         val |= PIDX_T5_V(q->pend_cred / 8);
531
532                 /* Make sure all memory writes to the Free List queue are
533                  * committed before we tell the hardware about them.
534                  */
535                 wmb();
536
537                 /* If we don't have access to the new User Doorbell (T5+), use
538                  * the old doorbell mechanism; otherwise use the new BAR2
539                  * mechanism.
540                  */
541                 if (unlikely(q->bar2_addr == NULL)) {
542                         t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
543                                      val | QID_V(q->cntxt_id));
544                 } else {
545                         writel(val | QID_V(q->bar2_qid),
546                                q->bar2_addr + SGE_UDB_KDOORBELL);
547
548                         /* This Write memory Barrier will force the write to
549                          * the User Doorbell area to be flushed.
550                          */
551                         wmb();
552                 }
553                 q->pend_cred &= 7;
554         }
555 }
556
557 static inline void set_rx_sw_desc(struct rx_sw_desc *sd, struct page *pg,
558                                   dma_addr_t mapping)
559 {
560         sd->page = pg;
561         sd->dma_addr = mapping;      /* includes size low bits */
562 }
563
564 /**
565  *      refill_fl - refill an SGE Rx buffer ring
566  *      @adap: the adapter
567  *      @q: the ring to refill
568  *      @n: the number of new buffers to allocate
569  *      @gfp: the gfp flags for the allocations
570  *
571  *      (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
572  *      allocated with the supplied gfp flags.  The caller must assure that
573  *      @n does not exceed the queue's capacity.  If afterwards the queue is
574  *      found critically low mark it as starving in the bitmap of starving FLs.
575  *
576  *      Returns the number of buffers allocated.
577  */
578 static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n,
579                               gfp_t gfp)
580 {
581         struct sge *s = &adap->sge;
582         struct page *pg;
583         dma_addr_t mapping;
584         unsigned int cred = q->avail;
585         __be64 *d = &q->desc[q->pidx];
586         struct rx_sw_desc *sd = &q->sdesc[q->pidx];
587         int node;
588
589 #ifdef CONFIG_DEBUG_FS
590         if (test_bit(q->cntxt_id - adap->sge.egr_start, adap->sge.blocked_fl))
591                 goto out;
592 #endif
593
594         gfp |= __GFP_NOWARN;
595         node = dev_to_node(adap->pdev_dev);
596
597         if (s->fl_pg_order == 0)
598                 goto alloc_small_pages;
599
600         /*
601          * Prefer large buffers
602          */
603         while (n) {
604                 pg = alloc_pages_node(node, gfp | __GFP_COMP, s->fl_pg_order);
605                 if (unlikely(!pg)) {
606                         q->large_alloc_failed++;
607                         break;       /* fall back to single pages */
608                 }
609
610                 mapping = dma_map_page(adap->pdev_dev, pg, 0,
611                                        PAGE_SIZE << s->fl_pg_order,
612                                        PCI_DMA_FROMDEVICE);
613                 if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
614                         __free_pages(pg, s->fl_pg_order);
615                         q->mapping_err++;
616                         goto out;   /* do not try small pages for this error */
617                 }
618                 mapping |= RX_LARGE_PG_BUF;
619                 *d++ = cpu_to_be64(mapping);
620
621                 set_rx_sw_desc(sd, pg, mapping);
622                 sd++;
623
624                 q->avail++;
625                 if (++q->pidx == q->size) {
626                         q->pidx = 0;
627                         sd = q->sdesc;
628                         d = q->desc;
629                 }
630                 n--;
631         }
632
633 alloc_small_pages:
634         while (n--) {
635                 pg = alloc_pages_node(node, gfp, 0);
636                 if (unlikely(!pg)) {
637                         q->alloc_failed++;
638                         break;
639                 }
640
641                 mapping = dma_map_page(adap->pdev_dev, pg, 0, PAGE_SIZE,
642                                        PCI_DMA_FROMDEVICE);
643                 if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
644                         put_page(pg);
645                         q->mapping_err++;
646                         goto out;
647                 }
648                 *d++ = cpu_to_be64(mapping);
649
650                 set_rx_sw_desc(sd, pg, mapping);
651                 sd++;
652
653                 q->avail++;
654                 if (++q->pidx == q->size) {
655                         q->pidx = 0;
656                         sd = q->sdesc;
657                         d = q->desc;
658                 }
659         }
660
661 out:    cred = q->avail - cred;
662         q->pend_cred += cred;
663         ring_fl_db(adap, q);
664
665         if (unlikely(fl_starving(adap, q))) {
666                 smp_wmb();
667                 q->low++;
668                 set_bit(q->cntxt_id - adap->sge.egr_start,
669                         adap->sge.starving_fl);
670         }
671
672         return cred;
673 }
674
675 static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
676 {
677         refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail),
678                   GFP_ATOMIC);
679 }
680
681 /**
682  *      alloc_ring - allocate resources for an SGE descriptor ring
683  *      @dev: the PCI device's core device
684  *      @nelem: the number of descriptors
685  *      @elem_size: the size of each descriptor
686  *      @sw_size: the size of the SW state associated with each ring element
687  *      @phys: the physical address of the allocated ring
688  *      @metadata: address of the array holding the SW state for the ring
689  *      @stat_size: extra space in HW ring for status information
690  *      @node: preferred node for memory allocations
691  *
692  *      Allocates resources for an SGE descriptor ring, such as Tx queues,
693  *      free buffer lists, or response queues.  Each SGE ring requires
694  *      space for its HW descriptors plus, optionally, space for the SW state
695  *      associated with each HW entry (the metadata).  The function returns
696  *      three values: the virtual address for the HW ring (the return value
697  *      of the function), the bus address of the HW ring, and the address
698  *      of the SW ring.
699  */
700 static void *alloc_ring(struct device *dev, size_t nelem, size_t elem_size,
701                         size_t sw_size, dma_addr_t *phys, void *metadata,
702                         size_t stat_size, int node)
703 {
704         size_t len = nelem * elem_size + stat_size;
705         void *s = NULL;
706         void *p = dma_alloc_coherent(dev, len, phys, GFP_KERNEL);
707
708         if (!p)
709                 return NULL;
710         if (sw_size) {
711                 s = kzalloc_node(nelem * sw_size, GFP_KERNEL, node);
712
713                 if (!s) {
714                         dma_free_coherent(dev, len, p, *phys);
715                         return NULL;
716                 }
717         }
718         if (metadata)
719                 *(void **)metadata = s;
720         memset(p, 0, len);
721         return p;
722 }
723
724 /**
725  *      sgl_len - calculates the size of an SGL of the given capacity
726  *      @n: the number of SGL entries
727  *
728  *      Calculates the number of flits needed for a scatter/gather list that
729  *      can hold the given number of entries.
730  */
731 static inline unsigned int sgl_len(unsigned int n)
732 {
733         /* A Direct Scatter Gather List uses 32-bit lengths and 64-bit PCI DMA
734          * addresses.  The DSGL Work Request starts off with a 32-bit DSGL
735          * ULPTX header, then Length0, then Address0, then, for 1 <= i <= N,
736          * repeated sequences of { Length[i], Length[i+1], Address[i],
737          * Address[i+1] } (this ensures that all addresses are on 64-bit
738          * boundaries).  If N is even, then Length[N+1] should be set to 0 and
739          * Address[N+1] is omitted.
740          *
741          * The following calculation incorporates all of the above.  It's
742          * somewhat hard to follow but, briefly: the "+2" accounts for the
743          * first two flits which include the DSGL header, Length0 and
744          * Address0; the "(3*(n-1))/2" covers the main body of list entries (3
745          * flits for every pair of the remaining N) +1 if (n-1) is odd; and
746          * finally the "+((n-1)&1)" adds the one remaining flit needed if
747          * (n-1) is odd ...
748          */
749         n--;
750         return (3 * n) / 2 + (n & 1) + 2;
751 }
752
753 /**
754  *      flits_to_desc - returns the num of Tx descriptors for the given flits
755  *      @n: the number of flits
756  *
757  *      Returns the number of Tx descriptors needed for the supplied number
758  *      of flits.
759  */
760 static inline unsigned int flits_to_desc(unsigned int n)
761 {
762         BUG_ON(n > SGE_MAX_WR_LEN / 8);
763         return DIV_ROUND_UP(n, 8);
764 }
765
766 /**
767  *      is_eth_imm - can an Ethernet packet be sent as immediate data?
768  *      @skb: the packet
769  *
770  *      Returns whether an Ethernet packet is small enough to fit as
771  *      immediate data. Return value corresponds to headroom required.
772  */
773 static inline int is_eth_imm(const struct sk_buff *skb)
774 {
775         int hdrlen = skb_shinfo(skb)->gso_size ?
776                         sizeof(struct cpl_tx_pkt_lso_core) : 0;
777
778         hdrlen += sizeof(struct cpl_tx_pkt);
779         if (skb->len <= MAX_IMM_TX_PKT_LEN - hdrlen)
780                 return hdrlen;
781         return 0;
782 }
783
784 /**
785  *      calc_tx_flits - calculate the number of flits for a packet Tx WR
786  *      @skb: the packet
787  *
788  *      Returns the number of flits needed for a Tx WR for the given Ethernet
789  *      packet, including the needed WR and CPL headers.
790  */
791 static inline unsigned int calc_tx_flits(const struct sk_buff *skb)
792 {
793         unsigned int flits;
794         int hdrlen = is_eth_imm(skb);
795
796         /* If the skb is small enough, we can pump it out as a work request
797          * with only immediate data.  In that case we just have to have the
798          * TX Packet header plus the skb data in the Work Request.
799          */
800
801         if (hdrlen)
802                 return DIV_ROUND_UP(skb->len + hdrlen, sizeof(__be64));
803
804         /* Otherwise, we're going to have to construct a Scatter gather list
805          * of the skb body and fragments.  We also include the flits necessary
806          * for the TX Packet Work Request and CPL.  We always have a firmware
807          * Write Header (incorporated as part of the cpl_tx_pkt_lso and
808          * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
809          * message or, if we're doing a Large Send Offload, an LSO CPL message
810          * with an embedded TX Packet Write CPL message.
811          */
812         flits = sgl_len(skb_shinfo(skb)->nr_frags + 1);
813         if (skb_shinfo(skb)->gso_size)
814                 flits += (sizeof(struct fw_eth_tx_pkt_wr) +
815                           sizeof(struct cpl_tx_pkt_lso_core) +
816                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
817         else
818                 flits += (sizeof(struct fw_eth_tx_pkt_wr) +
819                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
820         return flits;
821 }
822
823 /**
824  *      calc_tx_descs - calculate the number of Tx descriptors for a packet
825  *      @skb: the packet
826  *
827  *      Returns the number of Tx descriptors needed for the given Ethernet
828  *      packet, including the needed WR and CPL headers.
829  */
830 static inline unsigned int calc_tx_descs(const struct sk_buff *skb)
831 {
832         return flits_to_desc(calc_tx_flits(skb));
833 }
834
835 /**
836  *      write_sgl - populate a scatter/gather list for a packet
837  *      @skb: the packet
838  *      @q: the Tx queue we are writing into
839  *      @sgl: starting location for writing the SGL
840  *      @end: points right after the end of the SGL
841  *      @start: start offset into skb main-body data to include in the SGL
842  *      @addr: the list of bus addresses for the SGL elements
843  *
844  *      Generates a gather list for the buffers that make up a packet.
845  *      The caller must provide adequate space for the SGL that will be written.
846  *      The SGL includes all of the packet's page fragments and the data in its
847  *      main body except for the first @start bytes.  @sgl must be 16-byte
848  *      aligned and within a Tx descriptor with available space.  @end points
849  *      right after the end of the SGL but does not account for any potential
850  *      wrap around, i.e., @end > @sgl.
851  */
852 static void write_sgl(const struct sk_buff *skb, struct sge_txq *q,
853                       struct ulptx_sgl *sgl, u64 *end, unsigned int start,
854                       const dma_addr_t *addr)
855 {
856         unsigned int i, len;
857         struct ulptx_sge_pair *to;
858         const struct skb_shared_info *si = skb_shinfo(skb);
859         unsigned int nfrags = si->nr_frags;
860         struct ulptx_sge_pair buf[MAX_SKB_FRAGS / 2 + 1];
861
862         len = skb_headlen(skb) - start;
863         if (likely(len)) {
864                 sgl->len0 = htonl(len);
865                 sgl->addr0 = cpu_to_be64(addr[0] + start);
866                 nfrags++;
867         } else {
868                 sgl->len0 = htonl(skb_frag_size(&si->frags[0]));
869                 sgl->addr0 = cpu_to_be64(addr[1]);
870         }
871
872         sgl->cmd_nsge = htonl(ULPTX_CMD_V(ULP_TX_SC_DSGL) |
873                               ULPTX_NSGE_V(nfrags));
874         if (likely(--nfrags == 0))
875                 return;
876         /*
877          * Most of the complexity below deals with the possibility we hit the
878          * end of the queue in the middle of writing the SGL.  For this case
879          * only we create the SGL in a temporary buffer and then copy it.
880          */
881         to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
882
883         for (i = (nfrags != si->nr_frags); nfrags >= 2; nfrags -= 2, to++) {
884                 to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
885                 to->len[1] = cpu_to_be32(skb_frag_size(&si->frags[++i]));
886                 to->addr[0] = cpu_to_be64(addr[i]);
887                 to->addr[1] = cpu_to_be64(addr[++i]);
888         }
889         if (nfrags) {
890                 to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
891                 to->len[1] = cpu_to_be32(0);
892                 to->addr[0] = cpu_to_be64(addr[i + 1]);
893         }
894         if (unlikely((u8 *)end > (u8 *)q->stat)) {
895                 unsigned int part0 = (u8 *)q->stat - (u8 *)sgl->sge, part1;
896
897                 if (likely(part0))
898                         memcpy(sgl->sge, buf, part0);
899                 part1 = (u8 *)end - (u8 *)q->stat;
900                 memcpy(q->desc, (u8 *)buf + part0, part1);
901                 end = (void *)q->desc + part1;
902         }
903         if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
904                 *end = 0;
905 }
906
907 /* This function copies 64 byte coalesced work request to
908  * memory mapped BAR2 space. For coalesced WR SGE fetches
909  * data from the FIFO instead of from Host.
910  */
911 static void cxgb_pio_copy(u64 __iomem *dst, u64 *src)
912 {
913         int count = 8;
914
915         while (count) {
916                 writeq(*src, dst);
917                 src++;
918                 dst++;
919                 count--;
920         }
921 }
922
923 /**
924  *      ring_tx_db - check and potentially ring a Tx queue's doorbell
925  *      @adap: the adapter
926  *      @q: the Tx queue
927  *      @n: number of new descriptors to give to HW
928  *
929  *      Ring the doorbel for a Tx queue.
930  */
931 static inline void ring_tx_db(struct adapter *adap, struct sge_txq *q, int n)
932 {
933         /* Make sure that all writes to the TX Descriptors are committed
934          * before we tell the hardware about them.
935          */
936         wmb();
937
938         /* If we don't have access to the new User Doorbell (T5+), use the old
939          * doorbell mechanism; otherwise use the new BAR2 mechanism.
940          */
941         if (unlikely(q->bar2_addr == NULL)) {
942                 u32 val = PIDX_V(n);
943                 unsigned long flags;
944
945                 /* For T4 we need to participate in the Doorbell Recovery
946                  * mechanism.
947                  */
948                 spin_lock_irqsave(&q->db_lock, flags);
949                 if (!q->db_disabled)
950                         t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
951                                      QID_V(q->cntxt_id) | val);
952                 else
953                         q->db_pidx_inc += n;
954                 q->db_pidx = q->pidx;
955                 spin_unlock_irqrestore(&q->db_lock, flags);
956         } else {
957                 u32 val = PIDX_T5_V(n);
958
959                 /* T4 and later chips share the same PIDX field offset within
960                  * the doorbell, but T5 and later shrank the field in order to
961                  * gain a bit for Doorbell Priority.  The field was absurdly
962                  * large in the first place (14 bits) so we just use the T5
963                  * and later limits and warn if a Queue ID is too large.
964                  */
965                 WARN_ON(val & DBPRIO_F);
966
967                 /* If we're only writing a single TX Descriptor and we can use
968                  * Inferred QID registers, we can use the Write Combining
969                  * Gather Buffer; otherwise we use the simple doorbell.
970                  */
971                 if (n == 1 && q->bar2_qid == 0) {
972                         int index = (q->pidx
973                                      ? (q->pidx - 1)
974                                      : (q->size - 1));
975                         u64 *wr = (u64 *)&q->desc[index];
976
977                         cxgb_pio_copy((u64 __iomem *)
978                                       (q->bar2_addr + SGE_UDB_WCDOORBELL),
979                                       wr);
980                 } else {
981                         writel(val | QID_V(q->bar2_qid),
982                                q->bar2_addr + SGE_UDB_KDOORBELL);
983                 }
984
985                 /* This Write Memory Barrier will force the write to the User
986                  * Doorbell area to be flushed.  This is needed to prevent
987                  * writes on different CPUs for the same queue from hitting
988                  * the adapter out of order.  This is required when some Work
989                  * Requests take the Write Combine Gather Buffer path (user
990                  * doorbell area offset [SGE_UDB_WCDOORBELL..+63]) and some
991                  * take the traditional path where we simply increment the
992                  * PIDX (User Doorbell area SGE_UDB_KDOORBELL) and have the
993                  * hardware DMA read the actual Work Request.
994                  */
995                 wmb();
996         }
997 }
998
999 /**
1000  *      inline_tx_skb - inline a packet's data into Tx descriptors
1001  *      @skb: the packet
1002  *      @q: the Tx queue where the packet will be inlined
1003  *      @pos: starting position in the Tx queue where to inline the packet
1004  *
1005  *      Inline a packet's contents directly into Tx descriptors, starting at
1006  *      the given position within the Tx DMA ring.
1007  *      Most of the complexity of this operation is dealing with wrap arounds
1008  *      in the middle of the packet we want to inline.
1009  */
1010 static void inline_tx_skb(const struct sk_buff *skb, const struct sge_txq *q,
1011                           void *pos)
1012 {
1013         u64 *p;
1014         int left = (void *)q->stat - pos;
1015
1016         if (likely(skb->len <= left)) {
1017                 if (likely(!skb->data_len))
1018                         skb_copy_from_linear_data(skb, pos, skb->len);
1019                 else
1020                         skb_copy_bits(skb, 0, pos, skb->len);
1021                 pos += skb->len;
1022         } else {
1023                 skb_copy_bits(skb, 0, pos, left);
1024                 skb_copy_bits(skb, left, q->desc, skb->len - left);
1025                 pos = (void *)q->desc + (skb->len - left);
1026         }
1027
1028         /* 0-pad to multiple of 16 */
1029         p = PTR_ALIGN(pos, 8);
1030         if ((uintptr_t)p & 8)
1031                 *p = 0;
1032 }
1033
1034 static void *inline_tx_skb_header(const struct sk_buff *skb,
1035                                   const struct sge_txq *q,  void *pos,
1036                                   int length)
1037 {
1038         u64 *p;
1039         int left = (void *)q->stat - pos;
1040
1041         if (likely(length <= left)) {
1042                 memcpy(pos, skb->data, length);
1043                 pos += length;
1044         } else {
1045                 memcpy(pos, skb->data, left);
1046                 memcpy(q->desc, skb->data + left, length - left);
1047                 pos = (void *)q->desc + (length - left);
1048         }
1049         /* 0-pad to multiple of 16 */
1050         p = PTR_ALIGN(pos, 8);
1051         if ((uintptr_t)p & 8) {
1052                 *p = 0;
1053                 return p + 1;
1054         }
1055         return p;
1056 }
1057
1058 /*
1059  * Figure out what HW csum a packet wants and return the appropriate control
1060  * bits.
1061  */
1062 static u64 hwcsum(enum chip_type chip, const struct sk_buff *skb)
1063 {
1064         int csum_type;
1065         const struct iphdr *iph = ip_hdr(skb);
1066
1067         if (iph->version == 4) {
1068                 if (iph->protocol == IPPROTO_TCP)
1069                         csum_type = TX_CSUM_TCPIP;
1070                 else if (iph->protocol == IPPROTO_UDP)
1071                         csum_type = TX_CSUM_UDPIP;
1072                 else {
1073 nocsum:                 /*
1074                          * unknown protocol, disable HW csum
1075                          * and hope a bad packet is detected
1076                          */
1077                         return TXPKT_L4CSUM_DIS_F;
1078                 }
1079         } else {
1080                 /*
1081                  * this doesn't work with extension headers
1082                  */
1083                 const struct ipv6hdr *ip6h = (const struct ipv6hdr *)iph;
1084
1085                 if (ip6h->nexthdr == IPPROTO_TCP)
1086                         csum_type = TX_CSUM_TCPIP6;
1087                 else if (ip6h->nexthdr == IPPROTO_UDP)
1088                         csum_type = TX_CSUM_UDPIP6;
1089                 else
1090                         goto nocsum;
1091         }
1092
1093         if (likely(csum_type >= TX_CSUM_TCPIP)) {
1094                 u64 hdr_len = TXPKT_IPHDR_LEN_V(skb_network_header_len(skb));
1095                 int eth_hdr_len = skb_network_offset(skb) - ETH_HLEN;
1096
1097                 if (CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5)
1098                         hdr_len |= TXPKT_ETHHDR_LEN_V(eth_hdr_len);
1099                 else
1100                         hdr_len |= T6_TXPKT_ETHHDR_LEN_V(eth_hdr_len);
1101                 return TXPKT_CSUM_TYPE_V(csum_type) | hdr_len;
1102         } else {
1103                 int start = skb_transport_offset(skb);
1104
1105                 return TXPKT_CSUM_TYPE_V(csum_type) |
1106                         TXPKT_CSUM_START_V(start) |
1107                         TXPKT_CSUM_LOC_V(start + skb->csum_offset);
1108         }
1109 }
1110
1111 static void eth_txq_stop(struct sge_eth_txq *q)
1112 {
1113         netif_tx_stop_queue(q->txq);
1114         q->q.stops++;
1115 }
1116
1117 static inline void txq_advance(struct sge_txq *q, unsigned int n)
1118 {
1119         q->in_use += n;
1120         q->pidx += n;
1121         if (q->pidx >= q->size)
1122                 q->pidx -= q->size;
1123 }
1124
1125 #ifdef CONFIG_CHELSIO_T4_FCOE
1126 static inline int
1127 cxgb_fcoe_offload(struct sk_buff *skb, struct adapter *adap,
1128                   const struct port_info *pi, u64 *cntrl)
1129 {
1130         const struct cxgb_fcoe *fcoe = &pi->fcoe;
1131
1132         if (!(fcoe->flags & CXGB_FCOE_ENABLED))
1133                 return 0;
1134
1135         if (skb->protocol != htons(ETH_P_FCOE))
1136                 return 0;
1137
1138         skb_reset_mac_header(skb);
1139         skb->mac_len = sizeof(struct ethhdr);
1140
1141         skb_set_network_header(skb, skb->mac_len);
1142         skb_set_transport_header(skb, skb->mac_len + sizeof(struct fcoe_hdr));
1143
1144         if (!cxgb_fcoe_sof_eof_supported(adap, skb))
1145                 return -ENOTSUPP;
1146
1147         /* FC CRC offload */
1148         *cntrl = TXPKT_CSUM_TYPE_V(TX_CSUM_FCOE) |
1149                      TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F |
1150                      TXPKT_CSUM_START_V(CXGB_FCOE_TXPKT_CSUM_START) |
1151                      TXPKT_CSUM_END_V(CXGB_FCOE_TXPKT_CSUM_END) |
1152                      TXPKT_CSUM_LOC_V(CXGB_FCOE_TXPKT_CSUM_END);
1153         return 0;
1154 }
1155 #endif /* CONFIG_CHELSIO_T4_FCOE */
1156
1157 /**
1158  *      t4_eth_xmit - add a packet to an Ethernet Tx queue
1159  *      @skb: the packet
1160  *      @dev: the egress net device
1161  *
1162  *      Add a packet to an SGE Ethernet Tx queue.  Runs with softirqs disabled.
1163  */
1164 netdev_tx_t t4_eth_xmit(struct sk_buff *skb, struct net_device *dev)
1165 {
1166         u32 wr_mid, ctrl0, op;
1167         u64 cntrl, *end;
1168         int qidx, credits;
1169         unsigned int flits, ndesc;
1170         struct adapter *adap;
1171         struct sge_eth_txq *q;
1172         const struct port_info *pi;
1173         struct fw_eth_tx_pkt_wr *wr;
1174         struct cpl_tx_pkt_core *cpl;
1175         const struct skb_shared_info *ssi;
1176         dma_addr_t addr[MAX_SKB_FRAGS + 1];
1177         bool immediate = false;
1178         int len, max_pkt_len;
1179         bool ptp_enabled = is_ptp_enabled(skb, dev);
1180 #ifdef CONFIG_CHELSIO_T4_FCOE
1181         int err;
1182 #endif /* CONFIG_CHELSIO_T4_FCOE */
1183
1184         /*
1185          * The chip min packet length is 10 octets but play safe and reject
1186          * anything shorter than an Ethernet header.
1187          */
1188         if (unlikely(skb->len < ETH_HLEN)) {
1189 out_free:       dev_kfree_skb_any(skb);
1190                 return NETDEV_TX_OK;
1191         }
1192
1193         /* Discard the packet if the length is greater than mtu */
1194         max_pkt_len = ETH_HLEN + dev->mtu;
1195         if (skb_vlan_tagged(skb))
1196                 max_pkt_len += VLAN_HLEN;
1197         if (!skb_shinfo(skb)->gso_size && (unlikely(skb->len > max_pkt_len)))
1198                 goto out_free;
1199
1200         pi = netdev_priv(dev);
1201         adap = pi->adapter;
1202         qidx = skb_get_queue_mapping(skb);
1203         if (ptp_enabled) {
1204                 spin_lock(&adap->ptp_lock);
1205                 if (!(adap->ptp_tx_skb)) {
1206                         skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
1207                         adap->ptp_tx_skb = skb_get(skb);
1208                 } else {
1209                         spin_unlock(&adap->ptp_lock);
1210                         goto out_free;
1211                 }
1212                 q = &adap->sge.ptptxq;
1213         } else {
1214                 q = &adap->sge.ethtxq[qidx + pi->first_qset];
1215         }
1216         skb_tx_timestamp(skb);
1217
1218         reclaim_completed_tx(adap, &q->q, true);
1219         cntrl = TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F;
1220
1221 #ifdef CONFIG_CHELSIO_T4_FCOE
1222         err = cxgb_fcoe_offload(skb, adap, pi, &cntrl);
1223         if (unlikely(err == -ENOTSUPP)) {
1224                 if (ptp_enabled)
1225                         spin_unlock(&adap->ptp_lock);
1226                 goto out_free;
1227         }
1228 #endif /* CONFIG_CHELSIO_T4_FCOE */
1229
1230         flits = calc_tx_flits(skb);
1231         ndesc = flits_to_desc(flits);
1232         credits = txq_avail(&q->q) - ndesc;
1233
1234         if (unlikely(credits < 0)) {
1235                 eth_txq_stop(q);
1236                 dev_err(adap->pdev_dev,
1237                         "%s: Tx ring %u full while queue awake!\n",
1238                         dev->name, qidx);
1239                 if (ptp_enabled)
1240                         spin_unlock(&adap->ptp_lock);
1241                 return NETDEV_TX_BUSY;
1242         }
1243
1244         if (is_eth_imm(skb))
1245                 immediate = true;
1246
1247         if (!immediate &&
1248             unlikely(map_skb(adap->pdev_dev, skb, addr) < 0)) {
1249                 q->mapping_err++;
1250                 if (ptp_enabled)
1251                         spin_unlock(&adap->ptp_lock);
1252                 goto out_free;
1253         }
1254
1255         wr_mid = FW_WR_LEN16_V(DIV_ROUND_UP(flits, 2));
1256         if (unlikely(credits < ETHTXQ_STOP_THRES)) {
1257                 eth_txq_stop(q);
1258                 wr_mid |= FW_WR_EQUEQ_F | FW_WR_EQUIQ_F;
1259         }
1260
1261         wr = (void *)&q->q.desc[q->q.pidx];
1262         wr->equiq_to_len16 = htonl(wr_mid);
1263         wr->r3 = cpu_to_be64(0);
1264         end = (u64 *)wr + flits;
1265
1266         len = immediate ? skb->len : 0;
1267         ssi = skb_shinfo(skb);
1268         if (ssi->gso_size) {
1269                 struct cpl_tx_pkt_lso *lso = (void *)wr;
1270                 bool v6 = (ssi->gso_type & SKB_GSO_TCPV6) != 0;
1271                 int l3hdr_len = skb_network_header_len(skb);
1272                 int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1273
1274                 len += sizeof(*lso);
1275                 wr->op_immdlen = htonl(FW_WR_OP_V(FW_ETH_TX_PKT_WR) |
1276                                        FW_WR_IMMDLEN_V(len));
1277                 lso->c.lso_ctrl = htonl(LSO_OPCODE_V(CPL_TX_PKT_LSO) |
1278                                         LSO_FIRST_SLICE_F | LSO_LAST_SLICE_F |
1279                                         LSO_IPV6_V(v6) |
1280                                         LSO_ETHHDR_LEN_V(eth_xtra_len / 4) |
1281                                         LSO_IPHDR_LEN_V(l3hdr_len / 4) |
1282                                         LSO_TCPHDR_LEN_V(tcp_hdr(skb)->doff));
1283                 lso->c.ipid_ofst = htons(0);
1284                 lso->c.mss = htons(ssi->gso_size);
1285                 lso->c.seqno_offset = htonl(0);
1286                 if (is_t4(adap->params.chip))
1287                         lso->c.len = htonl(skb->len);
1288                 else
1289                         lso->c.len = htonl(LSO_T5_XFER_SIZE_V(skb->len));
1290                 cpl = (void *)(lso + 1);
1291
1292                 if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
1293                         cntrl = TXPKT_ETHHDR_LEN_V(eth_xtra_len);
1294                 else
1295                         cntrl = T6_TXPKT_ETHHDR_LEN_V(eth_xtra_len);
1296
1297                 cntrl |= TXPKT_CSUM_TYPE_V(v6 ?
1298                                            TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
1299                          TXPKT_IPHDR_LEN_V(l3hdr_len);
1300                 q->tso++;
1301                 q->tx_cso += ssi->gso_segs;
1302         } else {
1303                 len += sizeof(*cpl);
1304                 if (ptp_enabled)
1305                         op = FW_PTP_TX_PKT_WR;
1306                 else
1307                         op = FW_ETH_TX_PKT_WR;
1308                 wr->op_immdlen = htonl(FW_WR_OP_V(op) |
1309                                        FW_WR_IMMDLEN_V(len));
1310                 cpl = (void *)(wr + 1);
1311                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1312                         cntrl = hwcsum(adap->params.chip, skb) |
1313                                 TXPKT_IPCSUM_DIS_F;
1314                         q->tx_cso++;
1315                 }
1316         }
1317
1318         if (skb_vlan_tag_present(skb)) {
1319                 q->vlan_ins++;
1320                 cntrl |= TXPKT_VLAN_VLD_F | TXPKT_VLAN_V(skb_vlan_tag_get(skb));
1321 #ifdef CONFIG_CHELSIO_T4_FCOE
1322                 if (skb->protocol == htons(ETH_P_FCOE))
1323                         cntrl |= TXPKT_VLAN_V(
1324                                  ((skb->priority & 0x7) << VLAN_PRIO_SHIFT));
1325 #endif /* CONFIG_CHELSIO_T4_FCOE */
1326         }
1327
1328         ctrl0 = TXPKT_OPCODE_V(CPL_TX_PKT_XT) | TXPKT_INTF_V(pi->tx_chan) |
1329                 TXPKT_PF_V(adap->pf);
1330         if (ptp_enabled)
1331                 ctrl0 |= TXPKT_TSTAMP_F;
1332 #ifdef CONFIG_CHELSIO_T4_DCB
1333         if (is_t4(adap->params.chip))
1334                 ctrl0 |= TXPKT_OVLAN_IDX_V(q->dcb_prio);
1335         else
1336                 ctrl0 |= TXPKT_T5_OVLAN_IDX_V(q->dcb_prio);
1337 #endif
1338         cpl->ctrl0 = htonl(ctrl0);
1339         cpl->pack = htons(0);
1340         cpl->len = htons(skb->len);
1341         cpl->ctrl1 = cpu_to_be64(cntrl);
1342
1343         if (immediate) {
1344                 inline_tx_skb(skb, &q->q, cpl + 1);
1345                 dev_consume_skb_any(skb);
1346         } else {
1347                 int last_desc;
1348
1349                 write_sgl(skb, &q->q, (struct ulptx_sgl *)(cpl + 1), end, 0,
1350                           addr);
1351                 skb_orphan(skb);
1352
1353                 last_desc = q->q.pidx + ndesc - 1;
1354                 if (last_desc >= q->q.size)
1355                         last_desc -= q->q.size;
1356                 q->q.sdesc[last_desc].skb = skb;
1357                 q->q.sdesc[last_desc].sgl = (struct ulptx_sgl *)(cpl + 1);
1358         }
1359
1360         txq_advance(&q->q, ndesc);
1361
1362         ring_tx_db(adap, &q->q, ndesc);
1363         if (ptp_enabled)
1364                 spin_unlock(&adap->ptp_lock);
1365         return NETDEV_TX_OK;
1366 }
1367
1368 /**
1369  *      reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
1370  *      @q: the SGE control Tx queue
1371  *
1372  *      This is a variant of reclaim_completed_tx() that is used for Tx queues
1373  *      that send only immediate data (presently just the control queues) and
1374  *      thus do not have any sk_buffs to release.
1375  */
1376 static inline void reclaim_completed_tx_imm(struct sge_txq *q)
1377 {
1378         int hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
1379         int reclaim = hw_cidx - q->cidx;
1380
1381         if (reclaim < 0)
1382                 reclaim += q->size;
1383
1384         q->in_use -= reclaim;
1385         q->cidx = hw_cidx;
1386 }
1387
1388 /**
1389  *      is_imm - check whether a packet can be sent as immediate data
1390  *      @skb: the packet
1391  *
1392  *      Returns true if a packet can be sent as a WR with immediate data.
1393  */
1394 static inline int is_imm(const struct sk_buff *skb)
1395 {
1396         return skb->len <= MAX_CTRL_WR_LEN;
1397 }
1398
1399 /**
1400  *      ctrlq_check_stop - check if a control queue is full and should stop
1401  *      @q: the queue
1402  *      @wr: most recent WR written to the queue
1403  *
1404  *      Check if a control queue has become full and should be stopped.
1405  *      We clean up control queue descriptors very lazily, only when we are out.
1406  *      If the queue is still full after reclaiming any completed descriptors
1407  *      we suspend it and have the last WR wake it up.
1408  */
1409 static void ctrlq_check_stop(struct sge_ctrl_txq *q, struct fw_wr_hdr *wr)
1410 {
1411         reclaim_completed_tx_imm(&q->q);
1412         if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
1413                 wr->lo |= htonl(FW_WR_EQUEQ_F | FW_WR_EQUIQ_F);
1414                 q->q.stops++;
1415                 q->full = 1;
1416         }
1417 }
1418
1419 /**
1420  *      ctrl_xmit - send a packet through an SGE control Tx queue
1421  *      @q: the control queue
1422  *      @skb: the packet
1423  *
1424  *      Send a packet through an SGE control Tx queue.  Packets sent through
1425  *      a control queue must fit entirely as immediate data.
1426  */
1427 static int ctrl_xmit(struct sge_ctrl_txq *q, struct sk_buff *skb)
1428 {
1429         unsigned int ndesc;
1430         struct fw_wr_hdr *wr;
1431
1432         if (unlikely(!is_imm(skb))) {
1433                 WARN_ON(1);
1434                 dev_kfree_skb(skb);
1435                 return NET_XMIT_DROP;
1436         }
1437
1438         ndesc = DIV_ROUND_UP(skb->len, sizeof(struct tx_desc));
1439         spin_lock(&q->sendq.lock);
1440
1441         if (unlikely(q->full)) {
1442                 skb->priority = ndesc;                  /* save for restart */
1443                 __skb_queue_tail(&q->sendq, skb);
1444                 spin_unlock(&q->sendq.lock);
1445                 return NET_XMIT_CN;
1446         }
1447
1448         wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1449         inline_tx_skb(skb, &q->q, wr);
1450
1451         txq_advance(&q->q, ndesc);
1452         if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES))
1453                 ctrlq_check_stop(q, wr);
1454
1455         ring_tx_db(q->adap, &q->q, ndesc);
1456         spin_unlock(&q->sendq.lock);
1457
1458         kfree_skb(skb);
1459         return NET_XMIT_SUCCESS;
1460 }
1461
1462 /**
1463  *      restart_ctrlq - restart a suspended control queue
1464  *      @data: the control queue to restart
1465  *
1466  *      Resumes transmission on a suspended Tx control queue.
1467  */
1468 static void restart_ctrlq(unsigned long data)
1469 {
1470         struct sk_buff *skb;
1471         unsigned int written = 0;
1472         struct sge_ctrl_txq *q = (struct sge_ctrl_txq *)data;
1473
1474         spin_lock(&q->sendq.lock);
1475         reclaim_completed_tx_imm(&q->q);
1476         BUG_ON(txq_avail(&q->q) < TXQ_STOP_THRES);  /* q should be empty */
1477
1478         while ((skb = __skb_dequeue(&q->sendq)) != NULL) {
1479                 struct fw_wr_hdr *wr;
1480                 unsigned int ndesc = skb->priority;     /* previously saved */
1481
1482                 written += ndesc;
1483                 /* Write descriptors and free skbs outside the lock to limit
1484                  * wait times.  q->full is still set so new skbs will be queued.
1485                  */
1486                 wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1487                 txq_advance(&q->q, ndesc);
1488                 spin_unlock(&q->sendq.lock);
1489
1490                 inline_tx_skb(skb, &q->q, wr);
1491                 kfree_skb(skb);
1492
1493                 if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
1494                         unsigned long old = q->q.stops;
1495
1496                         ctrlq_check_stop(q, wr);
1497                         if (q->q.stops != old) {          /* suspended anew */
1498                                 spin_lock(&q->sendq.lock);
1499                                 goto ringdb;
1500                         }
1501                 }
1502                 if (written > 16) {
1503                         ring_tx_db(q->adap, &q->q, written);
1504                         written = 0;
1505                 }
1506                 spin_lock(&q->sendq.lock);
1507         }
1508         q->full = 0;
1509 ringdb: if (written)
1510                 ring_tx_db(q->adap, &q->q, written);
1511         spin_unlock(&q->sendq.lock);
1512 }
1513
1514 /**
1515  *      t4_mgmt_tx - send a management message
1516  *      @adap: the adapter
1517  *      @skb: the packet containing the management message
1518  *
1519  *      Send a management message through control queue 0.
1520  */
1521 int t4_mgmt_tx(struct adapter *adap, struct sk_buff *skb)
1522 {
1523         int ret;
1524
1525         local_bh_disable();
1526         ret = ctrl_xmit(&adap->sge.ctrlq[0], skb);
1527         local_bh_enable();
1528         return ret;
1529 }
1530
1531 /**
1532  *      is_ofld_imm - check whether a packet can be sent as immediate data
1533  *      @skb: the packet
1534  *
1535  *      Returns true if a packet can be sent as an offload WR with immediate
1536  *      data.  We currently use the same limit as for Ethernet packets.
1537  */
1538 static inline int is_ofld_imm(const struct sk_buff *skb)
1539 {
1540         struct work_request_hdr *req = (struct work_request_hdr *)skb->data;
1541         unsigned long opcode = FW_WR_OP_G(ntohl(req->wr_hi));
1542
1543         if (opcode == FW_CRYPTO_LOOKASIDE_WR)
1544                 return skb->len <= SGE_MAX_WR_LEN;
1545         else
1546                 return skb->len <= MAX_IMM_TX_PKT_LEN;
1547 }
1548
1549 /**
1550  *      calc_tx_flits_ofld - calculate # of flits for an offload packet
1551  *      @skb: the packet
1552  *
1553  *      Returns the number of flits needed for the given offload packet.
1554  *      These packets are already fully constructed and no additional headers
1555  *      will be added.
1556  */
1557 static inline unsigned int calc_tx_flits_ofld(const struct sk_buff *skb)
1558 {
1559         unsigned int flits, cnt;
1560
1561         if (is_ofld_imm(skb))
1562                 return DIV_ROUND_UP(skb->len, 8);
1563
1564         flits = skb_transport_offset(skb) / 8U;   /* headers */
1565         cnt = skb_shinfo(skb)->nr_frags;
1566         if (skb_tail_pointer(skb) != skb_transport_header(skb))
1567                 cnt++;
1568         return flits + sgl_len(cnt);
1569 }
1570
1571 /**
1572  *      txq_stop_maperr - stop a Tx queue due to I/O MMU exhaustion
1573  *      @adap: the adapter
1574  *      @q: the queue to stop
1575  *
1576  *      Mark a Tx queue stopped due to I/O MMU exhaustion and resulting
1577  *      inability to map packets.  A periodic timer attempts to restart
1578  *      queues so marked.
1579  */
1580 static void txq_stop_maperr(struct sge_uld_txq *q)
1581 {
1582         q->mapping_err++;
1583         q->q.stops++;
1584         set_bit(q->q.cntxt_id - q->adap->sge.egr_start,
1585                 q->adap->sge.txq_maperr);
1586 }
1587
1588 /**
1589  *      ofldtxq_stop - stop an offload Tx queue that has become full
1590  *      @q: the queue to stop
1591  *      @skb: the packet causing the queue to become full
1592  *
1593  *      Stops an offload Tx queue that has become full and modifies the packet
1594  *      being written to request a wakeup.
1595  */
1596 static void ofldtxq_stop(struct sge_uld_txq *q, struct sk_buff *skb)
1597 {
1598         struct fw_wr_hdr *wr = (struct fw_wr_hdr *)skb->data;
1599
1600         wr->lo |= htonl(FW_WR_EQUEQ_F | FW_WR_EQUIQ_F);
1601         q->q.stops++;
1602         q->full = 1;
1603 }
1604
1605 /**
1606  *      service_ofldq - service/restart a suspended offload queue
1607  *      @q: the offload queue
1608  *
1609  *      Services an offload Tx queue by moving packets from its Pending Send
1610  *      Queue to the Hardware TX ring.  The function starts and ends with the
1611  *      Send Queue locked, but drops the lock while putting the skb at the
1612  *      head of the Send Queue onto the Hardware TX Ring.  Dropping the lock
1613  *      allows more skbs to be added to the Send Queue by other threads.
1614  *      The packet being processed at the head of the Pending Send Queue is
1615  *      left on the queue in case we experience DMA Mapping errors, etc.
1616  *      and need to give up and restart later.
1617  *
1618  *      service_ofldq() can be thought of as a task which opportunistically
1619  *      uses other threads execution contexts.  We use the Offload Queue
1620  *      boolean "service_ofldq_running" to make sure that only one instance
1621  *      is ever running at a time ...
1622  */
1623 static void service_ofldq(struct sge_uld_txq *q)
1624 {
1625         u64 *pos, *before, *end;
1626         int credits;
1627         struct sk_buff *skb;
1628         struct sge_txq *txq;
1629         unsigned int left;
1630         unsigned int written = 0;
1631         unsigned int flits, ndesc;
1632
1633         /* If another thread is currently in service_ofldq() processing the
1634          * Pending Send Queue then there's nothing to do. Otherwise, flag
1635          * that we're doing the work and continue.  Examining/modifying
1636          * the Offload Queue boolean "service_ofldq_running" must be done
1637          * while holding the Pending Send Queue Lock.
1638          */
1639         if (q->service_ofldq_running)
1640                 return;
1641         q->service_ofldq_running = true;
1642
1643         while ((skb = skb_peek(&q->sendq)) != NULL && !q->full) {
1644                 /* We drop the lock while we're working with the skb at the
1645                  * head of the Pending Send Queue.  This allows more skbs to
1646                  * be added to the Pending Send Queue while we're working on
1647                  * this one.  We don't need to lock to guard the TX Ring
1648                  * updates because only one thread of execution is ever
1649                  * allowed into service_ofldq() at a time.
1650                  */
1651                 spin_unlock(&q->sendq.lock);
1652
1653                 reclaim_completed_tx(q->adap, &q->q, false);
1654
1655                 flits = skb->priority;                /* previously saved */
1656                 ndesc = flits_to_desc(flits);
1657                 credits = txq_avail(&q->q) - ndesc;
1658                 BUG_ON(credits < 0);
1659                 if (unlikely(credits < TXQ_STOP_THRES))
1660                         ofldtxq_stop(q, skb);
1661
1662                 pos = (u64 *)&q->q.desc[q->q.pidx];
1663                 if (is_ofld_imm(skb))
1664                         inline_tx_skb(skb, &q->q, pos);
1665                 else if (map_skb(q->adap->pdev_dev, skb,
1666                                  (dma_addr_t *)skb->head)) {
1667                         txq_stop_maperr(q);
1668                         spin_lock(&q->sendq.lock);
1669                         break;
1670                 } else {
1671                         int last_desc, hdr_len = skb_transport_offset(skb);
1672
1673                         /* The WR headers  may not fit within one descriptor.
1674                          * So we need to deal with wrap-around here.
1675                          */
1676                         before = (u64 *)pos;
1677                         end = (u64 *)pos + flits;
1678                         txq = &q->q;
1679                         pos = (void *)inline_tx_skb_header(skb, &q->q,
1680                                                            (void *)pos,
1681                                                            hdr_len);
1682                         if (before > (u64 *)pos) {
1683                                 left = (u8 *)end - (u8 *)txq->stat;
1684                                 end = (void *)txq->desc + left;
1685                         }
1686
1687                         /* If current position is already at the end of the
1688                          * ofld queue, reset the current to point to
1689                          * start of the queue and update the end ptr as well.
1690                          */
1691                         if (pos == (u64 *)txq->stat) {
1692                                 left = (u8 *)end - (u8 *)txq->stat;
1693                                 end = (void *)txq->desc + left;
1694                                 pos = (void *)txq->desc;
1695                         }
1696
1697                         write_sgl(skb, &q->q, (void *)pos,
1698                                   end, hdr_len,
1699                                   (dma_addr_t *)skb->head);
1700 #ifdef CONFIG_NEED_DMA_MAP_STATE
1701                         skb->dev = q->adap->port[0];
1702                         skb->destructor = deferred_unmap_destructor;
1703 #endif
1704                         last_desc = q->q.pidx + ndesc - 1;
1705                         if (last_desc >= q->q.size)
1706                                 last_desc -= q->q.size;
1707                         q->q.sdesc[last_desc].skb = skb;
1708                 }
1709
1710                 txq_advance(&q->q, ndesc);
1711                 written += ndesc;
1712                 if (unlikely(written > 32)) {
1713                         ring_tx_db(q->adap, &q->q, written);
1714                         written = 0;
1715                 }
1716
1717                 /* Reacquire the Pending Send Queue Lock so we can unlink the
1718                  * skb we've just successfully transferred to the TX Ring and
1719                  * loop for the next skb which may be at the head of the
1720                  * Pending Send Queue.
1721                  */
1722                 spin_lock(&q->sendq.lock);
1723                 __skb_unlink(skb, &q->sendq);
1724                 if (is_ofld_imm(skb))
1725                         kfree_skb(skb);
1726         }
1727         if (likely(written))
1728                 ring_tx_db(q->adap, &q->q, written);
1729
1730         /*Indicate that no thread is processing the Pending Send Queue
1731          * currently.
1732          */
1733         q->service_ofldq_running = false;
1734 }
1735
1736 /**
1737  *      ofld_xmit - send a packet through an offload queue
1738  *      @q: the Tx offload queue
1739  *      @skb: the packet
1740  *
1741  *      Send an offload packet through an SGE offload queue.
1742  */
1743 static int ofld_xmit(struct sge_uld_txq *q, struct sk_buff *skb)
1744 {
1745         skb->priority = calc_tx_flits_ofld(skb);       /* save for restart */
1746         spin_lock(&q->sendq.lock);
1747
1748         /* Queue the new skb onto the Offload Queue's Pending Send Queue.  If
1749          * that results in this new skb being the only one on the queue, start
1750          * servicing it.  If there are other skbs already on the list, then
1751          * either the queue is currently being processed or it's been stopped
1752          * for some reason and it'll be restarted at a later time.  Restart
1753          * paths are triggered by events like experiencing a DMA Mapping Error
1754          * or filling the Hardware TX Ring.
1755          */
1756         __skb_queue_tail(&q->sendq, skb);
1757         if (q->sendq.qlen == 1)
1758                 service_ofldq(q);
1759
1760         spin_unlock(&q->sendq.lock);
1761         return NET_XMIT_SUCCESS;
1762 }
1763
1764 /**
1765  *      restart_ofldq - restart a suspended offload queue
1766  *      @data: the offload queue to restart
1767  *
1768  *      Resumes transmission on a suspended Tx offload queue.
1769  */
1770 static void restart_ofldq(unsigned long data)
1771 {
1772         struct sge_uld_txq *q = (struct sge_uld_txq *)data;
1773
1774         spin_lock(&q->sendq.lock);
1775         q->full = 0;            /* the queue actually is completely empty now */
1776         service_ofldq(q);
1777         spin_unlock(&q->sendq.lock);
1778 }
1779
1780 /**
1781  *      skb_txq - return the Tx queue an offload packet should use
1782  *      @skb: the packet
1783  *
1784  *      Returns the Tx queue an offload packet should use as indicated by bits
1785  *      1-15 in the packet's queue_mapping.
1786  */
1787 static inline unsigned int skb_txq(const struct sk_buff *skb)
1788 {
1789         return skb->queue_mapping >> 1;
1790 }
1791
1792 /**
1793  *      is_ctrl_pkt - return whether an offload packet is a control packet
1794  *      @skb: the packet
1795  *
1796  *      Returns whether an offload packet should use an OFLD or a CTRL
1797  *      Tx queue as indicated by bit 0 in the packet's queue_mapping.
1798  */
1799 static inline unsigned int is_ctrl_pkt(const struct sk_buff *skb)
1800 {
1801         return skb->queue_mapping & 1;
1802 }
1803
1804 static inline int uld_send(struct adapter *adap, struct sk_buff *skb,
1805                            unsigned int tx_uld_type)
1806 {
1807         struct sge_uld_txq_info *txq_info;
1808         struct sge_uld_txq *txq;
1809         unsigned int idx = skb_txq(skb);
1810
1811         if (unlikely(is_ctrl_pkt(skb))) {
1812                 /* Single ctrl queue is a requirement for LE workaround path */
1813                 if (adap->tids.nsftids)
1814                         idx = 0;
1815                 return ctrl_xmit(&adap->sge.ctrlq[idx], skb);
1816         }
1817
1818         txq_info = adap->sge.uld_txq_info[tx_uld_type];
1819         if (unlikely(!txq_info)) {
1820                 WARN_ON(true);
1821                 return NET_XMIT_DROP;
1822         }
1823
1824         txq = &txq_info->uldtxq[idx];
1825         return ofld_xmit(txq, skb);
1826 }
1827
1828 /**
1829  *      t4_ofld_send - send an offload packet
1830  *      @adap: the adapter
1831  *      @skb: the packet
1832  *
1833  *      Sends an offload packet.  We use the packet queue_mapping to select the
1834  *      appropriate Tx queue as follows: bit 0 indicates whether the packet
1835  *      should be sent as regular or control, bits 1-15 select the queue.
1836  */
1837 int t4_ofld_send(struct adapter *adap, struct sk_buff *skb)
1838 {
1839         int ret;
1840
1841         local_bh_disable();
1842         ret = uld_send(adap, skb, CXGB4_TX_OFLD);
1843         local_bh_enable();
1844         return ret;
1845 }
1846
1847 /**
1848  *      cxgb4_ofld_send - send an offload packet
1849  *      @dev: the net device
1850  *      @skb: the packet
1851  *
1852  *      Sends an offload packet.  This is an exported version of @t4_ofld_send,
1853  *      intended for ULDs.
1854  */
1855 int cxgb4_ofld_send(struct net_device *dev, struct sk_buff *skb)
1856 {
1857         return t4_ofld_send(netdev2adap(dev), skb);
1858 }
1859 EXPORT_SYMBOL(cxgb4_ofld_send);
1860
1861 /**
1862  *      t4_crypto_send - send crypto packet
1863  *      @adap: the adapter
1864  *      @skb: the packet
1865  *
1866  *      Sends crypto packet.  We use the packet queue_mapping to select the
1867  *      appropriate Tx queue as follows: bit 0 indicates whether the packet
1868  *      should be sent as regular or control, bits 1-15 select the queue.
1869  */
1870 static int t4_crypto_send(struct adapter *adap, struct sk_buff *skb)
1871 {
1872         int ret;
1873
1874         local_bh_disable();
1875         ret = uld_send(adap, skb, CXGB4_TX_CRYPTO);
1876         local_bh_enable();
1877         return ret;
1878 }
1879
1880 /**
1881  *      cxgb4_crypto_send - send crypto packet
1882  *      @dev: the net device
1883  *      @skb: the packet
1884  *
1885  *      Sends crypto packet.  This is an exported version of @t4_crypto_send,
1886  *      intended for ULDs.
1887  */
1888 int cxgb4_crypto_send(struct net_device *dev, struct sk_buff *skb)
1889 {
1890         return t4_crypto_send(netdev2adap(dev), skb);
1891 }
1892 EXPORT_SYMBOL(cxgb4_crypto_send);
1893
1894 static inline void copy_frags(struct sk_buff *skb,
1895                               const struct pkt_gl *gl, unsigned int offset)
1896 {
1897         int i;
1898
1899         /* usually there's just one frag */
1900         __skb_fill_page_desc(skb, 0, gl->frags[0].page,
1901                              gl->frags[0].offset + offset,
1902                              gl->frags[0].size - offset);
1903         skb_shinfo(skb)->nr_frags = gl->nfrags;
1904         for (i = 1; i < gl->nfrags; i++)
1905                 __skb_fill_page_desc(skb, i, gl->frags[i].page,
1906                                      gl->frags[i].offset,
1907                                      gl->frags[i].size);
1908
1909         /* get a reference to the last page, we don't own it */
1910         get_page(gl->frags[gl->nfrags - 1].page);
1911 }
1912
1913 /**
1914  *      cxgb4_pktgl_to_skb - build an sk_buff from a packet gather list
1915  *      @gl: the gather list
1916  *      @skb_len: size of sk_buff main body if it carries fragments
1917  *      @pull_len: amount of data to move to the sk_buff's main body
1918  *
1919  *      Builds an sk_buff from the given packet gather list.  Returns the
1920  *      sk_buff or %NULL if sk_buff allocation failed.
1921  */
1922 struct sk_buff *cxgb4_pktgl_to_skb(const struct pkt_gl *gl,
1923                                    unsigned int skb_len, unsigned int pull_len)
1924 {
1925         struct sk_buff *skb;
1926
1927         /*
1928          * Below we rely on RX_COPY_THRES being less than the smallest Rx buffer
1929          * size, which is expected since buffers are at least PAGE_SIZEd.
1930          * In this case packets up to RX_COPY_THRES have only one fragment.
1931          */
1932         if (gl->tot_len <= RX_COPY_THRES) {
1933                 skb = dev_alloc_skb(gl->tot_len);
1934                 if (unlikely(!skb))
1935                         goto out;
1936                 __skb_put(skb, gl->tot_len);
1937                 skb_copy_to_linear_data(skb, gl->va, gl->tot_len);
1938         } else {
1939                 skb = dev_alloc_skb(skb_len);
1940                 if (unlikely(!skb))
1941                         goto out;
1942                 __skb_put(skb, pull_len);
1943                 skb_copy_to_linear_data(skb, gl->va, pull_len);
1944
1945                 copy_frags(skb, gl, pull_len);
1946                 skb->len = gl->tot_len;
1947                 skb->data_len = skb->len - pull_len;
1948                 skb->truesize += skb->data_len;
1949         }
1950 out:    return skb;
1951 }
1952 EXPORT_SYMBOL(cxgb4_pktgl_to_skb);
1953
1954 /**
1955  *      t4_pktgl_free - free a packet gather list
1956  *      @gl: the gather list
1957  *
1958  *      Releases the pages of a packet gather list.  We do not own the last
1959  *      page on the list and do not free it.
1960  */
1961 static void t4_pktgl_free(const struct pkt_gl *gl)
1962 {
1963         int n;
1964         const struct page_frag *p;
1965
1966         for (p = gl->frags, n = gl->nfrags - 1; n--; p++)
1967                 put_page(p->page);
1968 }
1969
1970 /*
1971  * Process an MPS trace packet.  Give it an unused protocol number so it won't
1972  * be delivered to anyone and send it to the stack for capture.
1973  */
1974 static noinline int handle_trace_pkt(struct adapter *adap,
1975                                      const struct pkt_gl *gl)
1976 {
1977         struct sk_buff *skb;
1978
1979         skb = cxgb4_pktgl_to_skb(gl, RX_PULL_LEN, RX_PULL_LEN);
1980         if (unlikely(!skb)) {
1981                 t4_pktgl_free(gl);
1982                 return 0;
1983         }
1984
1985         if (is_t4(adap->params.chip))
1986                 __skb_pull(skb, sizeof(struct cpl_trace_pkt));
1987         else
1988                 __skb_pull(skb, sizeof(struct cpl_t5_trace_pkt));
1989
1990         skb_reset_mac_header(skb);
1991         skb->protocol = htons(0xffff);
1992         skb->dev = adap->port[0];
1993         netif_receive_skb(skb);
1994         return 0;
1995 }
1996
1997 /**
1998  * cxgb4_sgetim_to_hwtstamp - convert sge time stamp to hw time stamp
1999  * @adap: the adapter
2000  * @hwtstamps: time stamp structure to update
2001  * @sgetstamp: 60bit iqe timestamp
2002  *
2003  * Every ingress queue entry has the 60-bit timestamp, convert that timestamp
2004  * which is in Core Clock ticks into ktime_t and assign it
2005  **/
2006 static void cxgb4_sgetim_to_hwtstamp(struct adapter *adap,
2007                                      struct skb_shared_hwtstamps *hwtstamps,
2008                                      u64 sgetstamp)
2009 {
2010         u64 ns;
2011         u64 tmp = (sgetstamp * 1000 * 1000 + adap->params.vpd.cclk / 2);
2012
2013         ns = div_u64(tmp, adap->params.vpd.cclk);
2014
2015         memset(hwtstamps, 0, sizeof(*hwtstamps));
2016         hwtstamps->hwtstamp = ns_to_ktime(ns);
2017 }
2018
2019 static void do_gro(struct sge_eth_rxq *rxq, const struct pkt_gl *gl,
2020                    const struct cpl_rx_pkt *pkt)
2021 {
2022         struct adapter *adapter = rxq->rspq.adap;
2023         struct sge *s = &adapter->sge;
2024         struct port_info *pi;
2025         int ret;
2026         struct sk_buff *skb;
2027
2028         skb = napi_get_frags(&rxq->rspq.napi);
2029         if (unlikely(!skb)) {
2030                 t4_pktgl_free(gl);
2031                 rxq->stats.rx_drops++;
2032                 return;
2033         }
2034
2035         copy_frags(skb, gl, s->pktshift);
2036         skb->len = gl->tot_len - s->pktshift;
2037         skb->data_len = skb->len;
2038         skb->truesize += skb->data_len;
2039         skb->ip_summed = CHECKSUM_UNNECESSARY;
2040         skb_record_rx_queue(skb, rxq->rspq.idx);
2041         pi = netdev_priv(skb->dev);
2042         if (pi->rxtstamp)
2043                 cxgb4_sgetim_to_hwtstamp(adapter, skb_hwtstamps(skb),
2044                                          gl->sgetstamp);
2045         if (rxq->rspq.netdev->features & NETIF_F_RXHASH)
2046                 skb_set_hash(skb, (__force u32)pkt->rsshdr.hash_val,
2047                              PKT_HASH_TYPE_L3);
2048
2049         if (unlikely(pkt->vlan_ex)) {
2050                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(pkt->vlan));
2051                 rxq->stats.vlan_ex++;
2052         }
2053         ret = napi_gro_frags(&rxq->rspq.napi);
2054         if (ret == GRO_HELD)
2055                 rxq->stats.lro_pkts++;
2056         else if (ret == GRO_MERGED || ret == GRO_MERGED_FREE)
2057                 rxq->stats.lro_merged++;
2058         rxq->stats.pkts++;
2059         rxq->stats.rx_cso++;
2060 }
2061
2062 enum {
2063         RX_NON_PTP_PKT = 0,
2064         RX_PTP_PKT_SUC = 1,
2065         RX_PTP_PKT_ERR = 2
2066 };
2067
2068 /**
2069  *     t4_systim_to_hwstamp - read hardware time stamp
2070  *     @adap: the adapter
2071  *     @skb: the packet
2072  *
2073  *     Read Time Stamp from MPS packet and insert in skb which
2074  *     is forwarded to PTP application
2075  */
2076 static noinline int t4_systim_to_hwstamp(struct adapter *adapter,
2077                                          struct sk_buff *skb)
2078 {
2079         struct skb_shared_hwtstamps *hwtstamps;
2080         struct cpl_rx_mps_pkt *cpl = NULL;
2081         unsigned char *data;
2082         int offset;
2083
2084         cpl = (struct cpl_rx_mps_pkt *)skb->data;
2085         if (!(CPL_RX_MPS_PKT_TYPE_G(ntohl(cpl->op_to_r1_hi)) &
2086              X_CPL_RX_MPS_PKT_TYPE_PTP))
2087                 return RX_PTP_PKT_ERR;
2088
2089         data = skb->data + sizeof(*cpl);
2090         skb_pull(skb, 2 * sizeof(u64) + sizeof(struct cpl_rx_mps_pkt));
2091         offset = ETH_HLEN + IPV4_HLEN(skb->data) + UDP_HLEN;
2092         if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(short))
2093                 return RX_PTP_PKT_ERR;
2094
2095         hwtstamps = skb_hwtstamps(skb);
2096         memset(hwtstamps, 0, sizeof(*hwtstamps));
2097         hwtstamps->hwtstamp = ns_to_ktime(be64_to_cpu(*((u64 *)data)));
2098
2099         return RX_PTP_PKT_SUC;
2100 }
2101
2102 /**
2103  *     t4_rx_hststamp - Recv PTP Event Message
2104  *     @adap: the adapter
2105  *     @rsp: the response queue descriptor holding the RX_PKT message
2106  *     @skb: the packet
2107  *
2108  *     PTP enabled and MPS packet, read HW timestamp
2109  */
2110 static int t4_rx_hststamp(struct adapter *adapter, const __be64 *rsp,
2111                           struct sge_eth_rxq *rxq, struct sk_buff *skb)
2112 {
2113         int ret;
2114
2115         if (unlikely((*(u8 *)rsp == CPL_RX_MPS_PKT) &&
2116                      !is_t4(adapter->params.chip))) {
2117                 ret = t4_systim_to_hwstamp(adapter, skb);
2118                 if (ret == RX_PTP_PKT_ERR) {
2119                         kfree_skb(skb);
2120                         rxq->stats.rx_drops++;
2121                 }
2122                 return ret;
2123         }
2124         return RX_NON_PTP_PKT;
2125 }
2126
2127 /**
2128  *      t4_tx_hststamp - Loopback PTP Transmit Event Message
2129  *      @adap: the adapter
2130  *      @skb: the packet
2131  *      @dev: the ingress net device
2132  *
2133  *      Read hardware timestamp for the loopback PTP Tx event message
2134  */
2135 static int t4_tx_hststamp(struct adapter *adapter, struct sk_buff *skb,
2136                           struct net_device *dev)
2137 {
2138         struct port_info *pi = netdev_priv(dev);
2139
2140         if (!is_t4(adapter->params.chip) && adapter->ptp_tx_skb) {
2141                 cxgb4_ptp_read_hwstamp(adapter, pi);
2142                 kfree_skb(skb);
2143                 return 0;
2144         }
2145         return 1;
2146 }
2147
2148 /**
2149  *      t4_ethrx_handler - process an ingress ethernet packet
2150  *      @q: the response queue that received the packet
2151  *      @rsp: the response queue descriptor holding the RX_PKT message
2152  *      @si: the gather list of packet fragments
2153  *
2154  *      Process an ingress ethernet packet and deliver it to the stack.
2155  */
2156 int t4_ethrx_handler(struct sge_rspq *q, const __be64 *rsp,
2157                      const struct pkt_gl *si)
2158 {
2159         bool csum_ok;
2160         struct sk_buff *skb;
2161         const struct cpl_rx_pkt *pkt;
2162         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
2163         struct adapter *adapter = q->adap;
2164         struct sge *s = &q->adap->sge;
2165         int cpl_trace_pkt = is_t4(q->adap->params.chip) ?
2166                             CPL_TRACE_PKT : CPL_TRACE_PKT_T5;
2167         u16 err_vec;
2168         struct port_info *pi;
2169         int ret = 0;
2170
2171         if (unlikely(*(u8 *)rsp == cpl_trace_pkt))
2172                 return handle_trace_pkt(q->adap, si);
2173
2174         pkt = (const struct cpl_rx_pkt *)rsp;
2175         /* Compressed error vector is enabled for T6 only */
2176         if (q->adap->params.tp.rx_pkt_encap)
2177                 err_vec = T6_COMPR_RXERR_VEC_G(be16_to_cpu(pkt->err_vec));
2178         else
2179                 err_vec = be16_to_cpu(pkt->err_vec);
2180
2181         csum_ok = pkt->csum_calc && !err_vec &&
2182                   (q->netdev->features & NETIF_F_RXCSUM);
2183         if ((pkt->l2info & htonl(RXF_TCP_F)) &&
2184             (q->netdev->features & NETIF_F_GRO) && csum_ok && !pkt->ip_frag) {
2185                 do_gro(rxq, si, pkt);
2186                 return 0;
2187         }
2188
2189         skb = cxgb4_pktgl_to_skb(si, RX_PKT_SKB_LEN, RX_PULL_LEN);
2190         if (unlikely(!skb)) {
2191                 t4_pktgl_free(si);
2192                 rxq->stats.rx_drops++;
2193                 return 0;
2194         }
2195         pi = netdev_priv(q->netdev);
2196
2197         /* Handle PTP Event Rx packet */
2198         if (unlikely(pi->ptp_enable)) {
2199                 ret = t4_rx_hststamp(adapter, rsp, rxq, skb);
2200                 if (ret == RX_PTP_PKT_ERR)
2201                         return 0;
2202         }
2203         if (likely(!ret))
2204                 __skb_pull(skb, s->pktshift); /* remove ethernet header pad */
2205
2206         /* Handle the PTP Event Tx Loopback packet */
2207         if (unlikely(pi->ptp_enable && !ret &&
2208                      (pkt->l2info & htonl(RXF_UDP_F)) &&
2209                      cxgb4_ptp_is_ptp_rx(skb))) {
2210                 if (!t4_tx_hststamp(adapter, skb, q->netdev))
2211                         return 0;
2212         }
2213
2214         skb->protocol = eth_type_trans(skb, q->netdev);
2215         skb_record_rx_queue(skb, q->idx);
2216         if (skb->dev->features & NETIF_F_RXHASH)
2217                 skb_set_hash(skb, (__force u32)pkt->rsshdr.hash_val,
2218                              PKT_HASH_TYPE_L3);
2219
2220         rxq->stats.pkts++;
2221
2222         if (pi->rxtstamp)
2223                 cxgb4_sgetim_to_hwtstamp(q->adap, skb_hwtstamps(skb),
2224                                          si->sgetstamp);
2225         if (csum_ok && (pkt->l2info & htonl(RXF_UDP_F | RXF_TCP_F))) {
2226                 if (!pkt->ip_frag) {
2227                         skb->ip_summed = CHECKSUM_UNNECESSARY;
2228                         rxq->stats.rx_cso++;
2229                 } else if (pkt->l2info & htonl(RXF_IP_F)) {
2230                         __sum16 c = (__force __sum16)pkt->csum;
2231                         skb->csum = csum_unfold(c);
2232                         skb->ip_summed = CHECKSUM_COMPLETE;
2233                         rxq->stats.rx_cso++;
2234                 }
2235         } else {
2236                 skb_checksum_none_assert(skb);
2237 #ifdef CONFIG_CHELSIO_T4_FCOE
2238 #define CPL_RX_PKT_FLAGS (RXF_PSH_F | RXF_SYN_F | RXF_UDP_F | \
2239                           RXF_TCP_F | RXF_IP_F | RXF_IP6_F | RXF_LRO_F)
2240
2241                 if (!(pkt->l2info & cpu_to_be32(CPL_RX_PKT_FLAGS))) {
2242                         if ((pkt->l2info & cpu_to_be32(RXF_FCOE_F)) &&
2243                             (pi->fcoe.flags & CXGB_FCOE_ENABLED)) {
2244                                 if (q->adap->params.tp.rx_pkt_encap)
2245                                         csum_ok = err_vec &
2246                                                   T6_COMPR_RXERR_SUM_F;
2247                                 else
2248                                         csum_ok = err_vec & RXERR_CSUM_F;
2249                                 if (!csum_ok)
2250                                         skb->ip_summed = CHECKSUM_UNNECESSARY;
2251                         }
2252                 }
2253
2254 #undef CPL_RX_PKT_FLAGS
2255 #endif /* CONFIG_CHELSIO_T4_FCOE */
2256         }
2257
2258         if (unlikely(pkt->vlan_ex)) {
2259                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(pkt->vlan));
2260                 rxq->stats.vlan_ex++;
2261         }
2262         skb_mark_napi_id(skb, &q->napi);
2263         netif_receive_skb(skb);
2264         return 0;
2265 }
2266
2267 /**
2268  *      restore_rx_bufs - put back a packet's Rx buffers
2269  *      @si: the packet gather list
2270  *      @q: the SGE free list
2271  *      @frags: number of FL buffers to restore
2272  *
2273  *      Puts back on an FL the Rx buffers associated with @si.  The buffers
2274  *      have already been unmapped and are left unmapped, we mark them so to
2275  *      prevent further unmapping attempts.
2276  *
2277  *      This function undoes a series of @unmap_rx_buf calls when we find out
2278  *      that the current packet can't be processed right away afterall and we
2279  *      need to come back to it later.  This is a very rare event and there's
2280  *      no effort to make this particularly efficient.
2281  */
2282 static void restore_rx_bufs(const struct pkt_gl *si, struct sge_fl *q,
2283                             int frags)
2284 {
2285         struct rx_sw_desc *d;
2286
2287         while (frags--) {
2288                 if (q->cidx == 0)
2289                         q->cidx = q->size - 1;
2290                 else
2291                         q->cidx--;
2292                 d = &q->sdesc[q->cidx];
2293                 d->page = si->frags[frags].page;
2294                 d->dma_addr |= RX_UNMAPPED_BUF;
2295                 q->avail++;
2296         }
2297 }
2298
2299 /**
2300  *      is_new_response - check if a response is newly written
2301  *      @r: the response descriptor
2302  *      @q: the response queue
2303  *
2304  *      Returns true if a response descriptor contains a yet unprocessed
2305  *      response.
2306  */
2307 static inline bool is_new_response(const struct rsp_ctrl *r,
2308                                    const struct sge_rspq *q)
2309 {
2310         return (r->type_gen >> RSPD_GEN_S) == q->gen;
2311 }
2312
2313 /**
2314  *      rspq_next - advance to the next entry in a response queue
2315  *      @q: the queue
2316  *
2317  *      Updates the state of a response queue to advance it to the next entry.
2318  */
2319 static inline void rspq_next(struct sge_rspq *q)
2320 {
2321         q->cur_desc = (void *)q->cur_desc + q->iqe_len;
2322         if (unlikely(++q->cidx == q->size)) {
2323                 q->cidx = 0;
2324                 q->gen ^= 1;
2325                 q->cur_desc = q->desc;
2326         }
2327 }
2328
2329 /**
2330  *      process_responses - process responses from an SGE response queue
2331  *      @q: the ingress queue to process
2332  *      @budget: how many responses can be processed in this round
2333  *
2334  *      Process responses from an SGE response queue up to the supplied budget.
2335  *      Responses include received packets as well as control messages from FW
2336  *      or HW.
2337  *
2338  *      Additionally choose the interrupt holdoff time for the next interrupt
2339  *      on this queue.  If the system is under memory shortage use a fairly
2340  *      long delay to help recovery.
2341  */
2342 static int process_responses(struct sge_rspq *q, int budget)
2343 {
2344         int ret, rsp_type;
2345         int budget_left = budget;
2346         const struct rsp_ctrl *rc;
2347         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
2348         struct adapter *adapter = q->adap;
2349         struct sge *s = &adapter->sge;
2350
2351         while (likely(budget_left)) {
2352                 rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
2353                 if (!is_new_response(rc, q)) {
2354                         if (q->flush_handler)
2355                                 q->flush_handler(q);
2356                         break;
2357                 }
2358
2359                 dma_rmb();
2360                 rsp_type = RSPD_TYPE_G(rc->type_gen);
2361                 if (likely(rsp_type == RSPD_TYPE_FLBUF_X)) {
2362                         struct page_frag *fp;
2363                         struct pkt_gl si;
2364                         const struct rx_sw_desc *rsd;
2365                         u32 len = ntohl(rc->pldbuflen_qid), bufsz, frags;
2366
2367                         if (len & RSPD_NEWBUF_F) {
2368                                 if (likely(q->offset > 0)) {
2369                                         free_rx_bufs(q->adap, &rxq->fl, 1);
2370                                         q->offset = 0;
2371                                 }
2372                                 len = RSPD_LEN_G(len);
2373                         }
2374                         si.tot_len = len;
2375
2376                         /* gather packet fragments */
2377                         for (frags = 0, fp = si.frags; ; frags++, fp++) {
2378                                 rsd = &rxq->fl.sdesc[rxq->fl.cidx];
2379                                 bufsz = get_buf_size(adapter, rsd);
2380                                 fp->page = rsd->page;
2381                                 fp->offset = q->offset;
2382                                 fp->size = min(bufsz, len);
2383                                 len -= fp->size;
2384                                 if (!len)
2385                                         break;
2386                                 unmap_rx_buf(q->adap, &rxq->fl);
2387                         }
2388
2389                         si.sgetstamp = SGE_TIMESTAMP_G(
2390                                         be64_to_cpu(rc->last_flit));
2391                         /*
2392                          * Last buffer remains mapped so explicitly make it
2393                          * coherent for CPU access.
2394                          */
2395                         dma_sync_single_for_cpu(q->adap->pdev_dev,
2396                                                 get_buf_addr(rsd),
2397                                                 fp->size, DMA_FROM_DEVICE);
2398
2399                         si.va = page_address(si.frags[0].page) +
2400                                 si.frags[0].offset;
2401                         prefetch(si.va);
2402
2403                         si.nfrags = frags + 1;
2404                         ret = q->handler(q, q->cur_desc, &si);
2405                         if (likely(ret == 0))
2406                                 q->offset += ALIGN(fp->size, s->fl_align);
2407                         else
2408                                 restore_rx_bufs(&si, &rxq->fl, frags);
2409                 } else if (likely(rsp_type == RSPD_TYPE_CPL_X)) {
2410                         ret = q->handler(q, q->cur_desc, NULL);
2411                 } else {
2412                         ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
2413                 }
2414
2415                 if (unlikely(ret)) {
2416                         /* couldn't process descriptor, back off for recovery */
2417                         q->next_intr_params = QINTR_TIMER_IDX_V(NOMEM_TMR_IDX);
2418                         break;
2419                 }
2420
2421                 rspq_next(q);
2422                 budget_left--;
2423         }
2424
2425         if (q->offset >= 0 && fl_cap(&rxq->fl) - rxq->fl.avail >= 16)
2426                 __refill_fl(q->adap, &rxq->fl);
2427         return budget - budget_left;
2428 }
2429
2430 /**
2431  *      napi_rx_handler - the NAPI handler for Rx processing
2432  *      @napi: the napi instance
2433  *      @budget: how many packets we can process in this round
2434  *
2435  *      Handler for new data events when using NAPI.  This does not need any
2436  *      locking or protection from interrupts as data interrupts are off at
2437  *      this point and other adapter interrupts do not interfere (the latter
2438  *      in not a concern at all with MSI-X as non-data interrupts then have
2439  *      a separate handler).
2440  */
2441 static int napi_rx_handler(struct napi_struct *napi, int budget)
2442 {
2443         unsigned int params;
2444         struct sge_rspq *q = container_of(napi, struct sge_rspq, napi);
2445         int work_done;
2446         u32 val;
2447
2448         work_done = process_responses(q, budget);
2449         if (likely(work_done < budget)) {
2450                 int timer_index;
2451
2452                 napi_complete_done(napi, work_done);
2453                 timer_index = QINTR_TIMER_IDX_G(q->next_intr_params);
2454
2455                 if (q->adaptive_rx) {
2456                         if (work_done > max(timer_pkt_quota[timer_index],
2457                                             MIN_NAPI_WORK))
2458                                 timer_index = (timer_index + 1);
2459                         else
2460                                 timer_index = timer_index - 1;
2461
2462                         timer_index = clamp(timer_index, 0, SGE_TIMERREGS - 1);
2463                         q->next_intr_params =
2464                                         QINTR_TIMER_IDX_V(timer_index) |
2465                                         QINTR_CNT_EN_V(0);
2466                         params = q->next_intr_params;
2467                 } else {
2468                         params = q->next_intr_params;
2469                         q->next_intr_params = q->intr_params;
2470                 }
2471         } else
2472                 params = QINTR_TIMER_IDX_V(7);
2473
2474         val = CIDXINC_V(work_done) | SEINTARM_V(params);
2475
2476         /* If we don't have access to the new User GTS (T5+), use the old
2477          * doorbell mechanism; otherwise use the new BAR2 mechanism.
2478          */
2479         if (unlikely(q->bar2_addr == NULL)) {
2480                 t4_write_reg(q->adap, MYPF_REG(SGE_PF_GTS_A),
2481                              val | INGRESSQID_V((u32)q->cntxt_id));
2482         } else {
2483                 writel(val | INGRESSQID_V(q->bar2_qid),
2484                        q->bar2_addr + SGE_UDB_GTS);
2485                 wmb();
2486         }
2487         return work_done;
2488 }
2489
2490 /*
2491  * The MSI-X interrupt handler for an SGE response queue.
2492  */
2493 irqreturn_t t4_sge_intr_msix(int irq, void *cookie)
2494 {
2495         struct sge_rspq *q = cookie;
2496
2497         napi_schedule(&q->napi);
2498         return IRQ_HANDLED;
2499 }
2500
2501 /*
2502  * Process the indirect interrupt entries in the interrupt queue and kick off
2503  * NAPI for each queue that has generated an entry.
2504  */
2505 static unsigned int process_intrq(struct adapter *adap)
2506 {
2507         unsigned int credits;
2508         const struct rsp_ctrl *rc;
2509         struct sge_rspq *q = &adap->sge.intrq;
2510         u32 val;
2511
2512         spin_lock(&adap->sge.intrq_lock);
2513         for (credits = 0; ; credits++) {
2514                 rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
2515                 if (!is_new_response(rc, q))
2516                         break;
2517
2518                 dma_rmb();
2519                 if (RSPD_TYPE_G(rc->type_gen) == RSPD_TYPE_INTR_X) {
2520                         unsigned int qid = ntohl(rc->pldbuflen_qid);
2521
2522                         qid -= adap->sge.ingr_start;
2523                         napi_schedule(&adap->sge.ingr_map[qid]->napi);
2524                 }
2525
2526                 rspq_next(q);
2527         }
2528
2529         val =  CIDXINC_V(credits) | SEINTARM_V(q->intr_params);
2530
2531         /* If we don't have access to the new User GTS (T5+), use the old
2532          * doorbell mechanism; otherwise use the new BAR2 mechanism.
2533          */
2534         if (unlikely(q->bar2_addr == NULL)) {
2535                 t4_write_reg(adap, MYPF_REG(SGE_PF_GTS_A),
2536                              val | INGRESSQID_V(q->cntxt_id));
2537         } else {
2538                 writel(val | INGRESSQID_V(q->bar2_qid),
2539                        q->bar2_addr + SGE_UDB_GTS);
2540                 wmb();
2541         }
2542         spin_unlock(&adap->sge.intrq_lock);
2543         return credits;
2544 }
2545
2546 /*
2547  * The MSI interrupt handler, which handles data events from SGE response queues
2548  * as well as error and other async events as they all use the same MSI vector.
2549  */
2550 static irqreturn_t t4_intr_msi(int irq, void *cookie)
2551 {
2552         struct adapter *adap = cookie;
2553
2554         if (adap->flags & MASTER_PF)
2555                 t4_slow_intr_handler(adap);
2556         process_intrq(adap);
2557         return IRQ_HANDLED;
2558 }
2559
2560 /*
2561  * Interrupt handler for legacy INTx interrupts.
2562  * Handles data events from SGE response queues as well as error and other
2563  * async events as they all use the same interrupt line.
2564  */
2565 static irqreturn_t t4_intr_intx(int irq, void *cookie)
2566 {
2567         struct adapter *adap = cookie;
2568
2569         t4_write_reg(adap, MYPF_REG(PCIE_PF_CLI_A), 0);
2570         if (((adap->flags & MASTER_PF) && t4_slow_intr_handler(adap)) |
2571             process_intrq(adap))
2572                 return IRQ_HANDLED;
2573         return IRQ_NONE;             /* probably shared interrupt */
2574 }
2575
2576 /**
2577  *      t4_intr_handler - select the top-level interrupt handler
2578  *      @adap: the adapter
2579  *
2580  *      Selects the top-level interrupt handler based on the type of interrupts
2581  *      (MSI-X, MSI, or INTx).
2582  */
2583 irq_handler_t t4_intr_handler(struct adapter *adap)
2584 {
2585         if (adap->flags & USING_MSIX)
2586                 return t4_sge_intr_msix;
2587         if (adap->flags & USING_MSI)
2588                 return t4_intr_msi;
2589         return t4_intr_intx;
2590 }
2591
2592 static void sge_rx_timer_cb(unsigned long data)
2593 {
2594         unsigned long m;
2595         unsigned int i;
2596         struct adapter *adap = (struct adapter *)data;
2597         struct sge *s = &adap->sge;
2598
2599         for (i = 0; i < BITS_TO_LONGS(s->egr_sz); i++)
2600                 for (m = s->starving_fl[i]; m; m &= m - 1) {
2601                         struct sge_eth_rxq *rxq;
2602                         unsigned int id = __ffs(m) + i * BITS_PER_LONG;
2603                         struct sge_fl *fl = s->egr_map[id];
2604
2605                         clear_bit(id, s->starving_fl);
2606                         smp_mb__after_atomic();
2607
2608                         if (fl_starving(adap, fl)) {
2609                                 rxq = container_of(fl, struct sge_eth_rxq, fl);
2610                                 if (napi_reschedule(&rxq->rspq.napi))
2611                                         fl->starving++;
2612                                 else
2613                                         set_bit(id, s->starving_fl);
2614                         }
2615                 }
2616         /* The remainder of the SGE RX Timer Callback routine is dedicated to
2617          * global Master PF activities like checking for chip ingress stalls,
2618          * etc.
2619          */
2620         if (!(adap->flags & MASTER_PF))
2621                 goto done;
2622
2623         t4_idma_monitor(adap, &s->idma_monitor, HZ, RX_QCHECK_PERIOD);
2624
2625 done:
2626         mod_timer(&s->rx_timer, jiffies + RX_QCHECK_PERIOD);
2627 }
2628
2629 static void sge_tx_timer_cb(unsigned long data)
2630 {
2631         unsigned long m;
2632         unsigned int i, budget;
2633         struct adapter *adap = (struct adapter *)data;
2634         struct sge *s = &adap->sge;
2635
2636         for (i = 0; i < BITS_TO_LONGS(s->egr_sz); i++)
2637                 for (m = s->txq_maperr[i]; m; m &= m - 1) {
2638                         unsigned long id = __ffs(m) + i * BITS_PER_LONG;
2639                         struct sge_uld_txq *txq = s->egr_map[id];
2640
2641                         clear_bit(id, s->txq_maperr);
2642                         tasklet_schedule(&txq->qresume_tsk);
2643                 }
2644
2645         if (!is_t4(adap->params.chip)) {
2646                 struct sge_eth_txq *q = &s->ptptxq;
2647                 int avail;
2648
2649                 spin_lock(&adap->ptp_lock);
2650                 avail = reclaimable(&q->q);
2651
2652                 if (avail) {
2653                         free_tx_desc(adap, &q->q, avail, false);
2654                         q->q.in_use -= avail;
2655                 }
2656                 spin_unlock(&adap->ptp_lock);
2657         }
2658
2659         budget = MAX_TIMER_TX_RECLAIM;
2660         i = s->ethtxq_rover;
2661         do {
2662                 struct sge_eth_txq *q = &s->ethtxq[i];
2663
2664                 if (q->q.in_use &&
2665                     time_after_eq(jiffies, q->txq->trans_start + HZ / 100) &&
2666                     __netif_tx_trylock(q->txq)) {
2667                         int avail = reclaimable(&q->q);
2668
2669                         if (avail) {
2670                                 if (avail > budget)
2671                                         avail = budget;
2672
2673                                 free_tx_desc(adap, &q->q, avail, true);
2674                                 q->q.in_use -= avail;
2675                                 budget -= avail;
2676                         }
2677                         __netif_tx_unlock(q->txq);
2678                 }
2679
2680                 if (++i >= s->ethqsets)
2681                         i = 0;
2682         } while (budget && i != s->ethtxq_rover);
2683         s->ethtxq_rover = i;
2684         mod_timer(&s->tx_timer, jiffies + (budget ? TX_QCHECK_PERIOD : 2));
2685 }
2686
2687 /**
2688  *      bar2_address - return the BAR2 address for an SGE Queue's Registers
2689  *      @adapter: the adapter
2690  *      @qid: the SGE Queue ID
2691  *      @qtype: the SGE Queue Type (Egress or Ingress)
2692  *      @pbar2_qid: BAR2 Queue ID or 0 for Queue ID inferred SGE Queues
2693  *
2694  *      Returns the BAR2 address for the SGE Queue Registers associated with
2695  *      @qid.  If BAR2 SGE Registers aren't available, returns NULL.  Also
2696  *      returns the BAR2 Queue ID to be used with writes to the BAR2 SGE
2697  *      Queue Registers.  If the BAR2 Queue ID is 0, then "Inferred Queue ID"
2698  *      Registers are supported (e.g. the Write Combining Doorbell Buffer).
2699  */
2700 static void __iomem *bar2_address(struct adapter *adapter,
2701                                   unsigned int qid,
2702                                   enum t4_bar2_qtype qtype,
2703                                   unsigned int *pbar2_qid)
2704 {
2705         u64 bar2_qoffset;
2706         int ret;
2707
2708         ret = t4_bar2_sge_qregs(adapter, qid, qtype, 0,
2709                                 &bar2_qoffset, pbar2_qid);
2710         if (ret)
2711                 return NULL;
2712
2713         return adapter->bar2 + bar2_qoffset;
2714 }
2715
2716 /* @intr_idx: MSI/MSI-X vector if >=0, -(absolute qid + 1) if < 0
2717  * @cong: < 0 -> no congestion feedback, >= 0 -> congestion channel map
2718  */
2719 int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
2720                      struct net_device *dev, int intr_idx,
2721                      struct sge_fl *fl, rspq_handler_t hnd,
2722                      rspq_flush_handler_t flush_hnd, int cong)
2723 {
2724         int ret, flsz = 0;
2725         struct fw_iq_cmd c;
2726         struct sge *s = &adap->sge;
2727         struct port_info *pi = netdev_priv(dev);
2728         int relaxed = !(adap->flags & ROOT_NO_RELAXED_ORDERING);
2729
2730         /* Size needs to be multiple of 16, including status entry. */
2731         iq->size = roundup(iq->size, 16);
2732
2733         iq->desc = alloc_ring(adap->pdev_dev, iq->size, iq->iqe_len, 0,
2734                               &iq->phys_addr, NULL, 0,
2735                               dev_to_node(adap->pdev_dev));
2736         if (!iq->desc)
2737                 return -ENOMEM;
2738
2739         memset(&c, 0, sizeof(c));
2740         c.op_to_vfn = htonl(FW_CMD_OP_V(FW_IQ_CMD) | FW_CMD_REQUEST_F |
2741                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
2742                             FW_IQ_CMD_PFN_V(adap->pf) | FW_IQ_CMD_VFN_V(0));
2743         c.alloc_to_len16 = htonl(FW_IQ_CMD_ALLOC_F | FW_IQ_CMD_IQSTART_F |
2744                                  FW_LEN16(c));
2745         c.type_to_iqandstindex = htonl(FW_IQ_CMD_TYPE_V(FW_IQ_TYPE_FL_INT_CAP) |
2746                 FW_IQ_CMD_IQASYNCH_V(fwevtq) | FW_IQ_CMD_VIID_V(pi->viid) |
2747                 FW_IQ_CMD_IQANDST_V(intr_idx < 0) |
2748                 FW_IQ_CMD_IQANUD_V(UPDATEDELIVERY_INTERRUPT_X) |
2749                 FW_IQ_CMD_IQANDSTINDEX_V(intr_idx >= 0 ? intr_idx :
2750                                                         -intr_idx - 1));
2751         c.iqdroprss_to_iqesize = htons(FW_IQ_CMD_IQPCIECH_V(pi->tx_chan) |
2752                 FW_IQ_CMD_IQGTSMODE_F |
2753                 FW_IQ_CMD_IQINTCNTTHRESH_V(iq->pktcnt_idx) |
2754                 FW_IQ_CMD_IQESIZE_V(ilog2(iq->iqe_len) - 4));
2755         c.iqsize = htons(iq->size);
2756         c.iqaddr = cpu_to_be64(iq->phys_addr);
2757         if (cong >= 0)
2758                 c.iqns_to_fl0congen = htonl(FW_IQ_CMD_IQFLINTCONGEN_F);
2759
2760         if (fl) {
2761                 enum chip_type chip = CHELSIO_CHIP_VERSION(adap->params.chip);
2762
2763                 /* Allocate the ring for the hardware free list (with space
2764                  * for its status page) along with the associated software
2765                  * descriptor ring.  The free list size needs to be a multiple
2766                  * of the Egress Queue Unit and at least 2 Egress Units larger
2767                  * than the SGE's Egress Congrestion Threshold
2768                  * (fl_starve_thres - 1).
2769                  */
2770                 if (fl->size < s->fl_starve_thres - 1 + 2 * 8)
2771                         fl->size = s->fl_starve_thres - 1 + 2 * 8;
2772                 fl->size = roundup(fl->size, 8);
2773                 fl->desc = alloc_ring(adap->pdev_dev, fl->size, sizeof(__be64),
2774                                       sizeof(struct rx_sw_desc), &fl->addr,
2775                                       &fl->sdesc, s->stat_len,
2776                                       dev_to_node(adap->pdev_dev));
2777                 if (!fl->desc)
2778                         goto fl_nomem;
2779
2780                 flsz = fl->size / 8 + s->stat_len / sizeof(struct tx_desc);
2781                 c.iqns_to_fl0congen |= htonl(FW_IQ_CMD_FL0PACKEN_F |
2782                                              FW_IQ_CMD_FL0FETCHRO_V(relaxed) |
2783                                              FW_IQ_CMD_FL0DATARO_V(relaxed) |
2784                                              FW_IQ_CMD_FL0PADEN_F);
2785                 if (cong >= 0)
2786                         c.iqns_to_fl0congen |=
2787                                 htonl(FW_IQ_CMD_FL0CNGCHMAP_V(cong) |
2788                                       FW_IQ_CMD_FL0CONGCIF_F |
2789                                       FW_IQ_CMD_FL0CONGEN_F);
2790                 /* In T6, for egress queue type FL there is internal overhead
2791                  * of 16B for header going into FLM module.  Hence the maximum
2792                  * allowed burst size is 448 bytes.  For T4/T5, the hardware
2793                  * doesn't coalesce fetch requests if more than 64 bytes of
2794                  * Free List pointers are provided, so we use a 128-byte Fetch
2795                  * Burst Minimum there (T6 implements coalescing so we can use
2796                  * the smaller 64-byte value there).
2797                  */
2798                 c.fl0dcaen_to_fl0cidxfthresh =
2799                         htons(FW_IQ_CMD_FL0FBMIN_V(chip <= CHELSIO_T5 ?
2800                                                    FETCHBURSTMIN_128B_X :
2801                                                    FETCHBURSTMIN_64B_X) |
2802                               FW_IQ_CMD_FL0FBMAX_V((chip <= CHELSIO_T5) ?
2803                                                    FETCHBURSTMAX_512B_X :
2804                                                    FETCHBURSTMAX_256B_X));
2805                 c.fl0size = htons(flsz);
2806                 c.fl0addr = cpu_to_be64(fl->addr);
2807         }
2808
2809         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
2810         if (ret)
2811                 goto err;
2812
2813         netif_napi_add(dev, &iq->napi, napi_rx_handler, 64);
2814         iq->cur_desc = iq->desc;
2815         iq->cidx = 0;
2816         iq->gen = 1;
2817         iq->next_intr_params = iq->intr_params;
2818         iq->cntxt_id = ntohs(c.iqid);
2819         iq->abs_id = ntohs(c.physiqid);
2820         iq->bar2_addr = bar2_address(adap,
2821                                      iq->cntxt_id,
2822                                      T4_BAR2_QTYPE_INGRESS,
2823                                      &iq->bar2_qid);
2824         iq->size--;                           /* subtract status entry */
2825         iq->netdev = dev;
2826         iq->handler = hnd;
2827         iq->flush_handler = flush_hnd;
2828
2829         memset(&iq->lro_mgr, 0, sizeof(struct t4_lro_mgr));
2830         skb_queue_head_init(&iq->lro_mgr.lroq);
2831
2832         /* set offset to -1 to distinguish ingress queues without FL */
2833         iq->offset = fl ? 0 : -1;
2834
2835         adap->sge.ingr_map[iq->cntxt_id - adap->sge.ingr_start] = iq;
2836
2837         if (fl) {
2838                 fl->cntxt_id = ntohs(c.fl0id);
2839                 fl->avail = fl->pend_cred = 0;
2840                 fl->pidx = fl->cidx = 0;
2841                 fl->alloc_failed = fl->large_alloc_failed = fl->starving = 0;
2842                 adap->sge.egr_map[fl->cntxt_id - adap->sge.egr_start] = fl;
2843
2844                 /* Note, we must initialize the BAR2 Free List User Doorbell
2845                  * information before refilling the Free List!
2846                  */
2847                 fl->bar2_addr = bar2_address(adap,
2848                                              fl->cntxt_id,
2849                                              T4_BAR2_QTYPE_EGRESS,
2850                                              &fl->bar2_qid);
2851                 refill_fl(adap, fl, fl_cap(fl), GFP_KERNEL);
2852         }
2853
2854         /* For T5 and later we attempt to set up the Congestion Manager values
2855          * of the new RX Ethernet Queue.  This should really be handled by
2856          * firmware because it's more complex than any host driver wants to
2857          * get involved with and it's different per chip and this is almost
2858          * certainly wrong.  Firmware would be wrong as well, but it would be
2859          * a lot easier to fix in one place ...  For now we do something very
2860          * simple (and hopefully less wrong).
2861          */
2862         if (!is_t4(adap->params.chip) && cong >= 0) {
2863                 u32 param, val, ch_map = 0;
2864                 int i;
2865                 u16 cng_ch_bits_log = adap->params.arch.cng_ch_bits_log;
2866
2867                 param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
2868                          FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
2869                          FW_PARAMS_PARAM_YZ_V(iq->cntxt_id));
2870                 if (cong == 0) {
2871                         val = CONMCTXT_CNGTPMODE_V(CONMCTXT_CNGTPMODE_QUEUE_X);
2872                 } else {
2873                         val =
2874                             CONMCTXT_CNGTPMODE_V(CONMCTXT_CNGTPMODE_CHANNEL_X);
2875                         for (i = 0; i < 4; i++) {
2876                                 if (cong & (1 << i))
2877                                         ch_map |= 1 << (i << cng_ch_bits_log);
2878                         }
2879                         val |= CONMCTXT_CNGCHMAP_V(ch_map);
2880                 }
2881                 ret = t4_set_params(adap, adap->mbox, adap->pf, 0, 1,
2882                                     &param, &val);
2883                 if (ret)
2884                         dev_warn(adap->pdev_dev, "Failed to set Congestion"
2885                                  " Manager Context for Ingress Queue %d: %d\n",
2886                                  iq->cntxt_id, -ret);
2887         }
2888
2889         return 0;
2890
2891 fl_nomem:
2892         ret = -ENOMEM;
2893 err:
2894         if (iq->desc) {
2895                 dma_free_coherent(adap->pdev_dev, iq->size * iq->iqe_len,
2896                                   iq->desc, iq->phys_addr);
2897                 iq->desc = NULL;
2898         }
2899         if (fl && fl->desc) {
2900                 kfree(fl->sdesc);
2901                 fl->sdesc = NULL;
2902                 dma_free_coherent(adap->pdev_dev, flsz * sizeof(struct tx_desc),
2903                                   fl->desc, fl->addr);
2904                 fl->desc = NULL;
2905         }
2906         return ret;
2907 }
2908
2909 static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id)
2910 {
2911         q->cntxt_id = id;
2912         q->bar2_addr = bar2_address(adap,
2913                                     q->cntxt_id,
2914                                     T4_BAR2_QTYPE_EGRESS,
2915                                     &q->bar2_qid);
2916         q->in_use = 0;
2917         q->cidx = q->pidx = 0;
2918         q->stops = q->restarts = 0;
2919         q->stat = (void *)&q->desc[q->size];
2920         spin_lock_init(&q->db_lock);
2921         adap->sge.egr_map[id - adap->sge.egr_start] = q;
2922 }
2923
2924 int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
2925                          struct net_device *dev, struct netdev_queue *netdevq,
2926                          unsigned int iqid)
2927 {
2928         int ret, nentries;
2929         struct fw_eq_eth_cmd c;
2930         struct sge *s = &adap->sge;
2931         struct port_info *pi = netdev_priv(dev);
2932
2933         /* Add status entries */
2934         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2935
2936         txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
2937                         sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
2938                         &txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
2939                         netdev_queue_numa_node_read(netdevq));
2940         if (!txq->q.desc)
2941                 return -ENOMEM;
2942
2943         memset(&c, 0, sizeof(c));
2944         c.op_to_vfn = htonl(FW_CMD_OP_V(FW_EQ_ETH_CMD) | FW_CMD_REQUEST_F |
2945                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
2946                             FW_EQ_ETH_CMD_PFN_V(adap->pf) |
2947                             FW_EQ_ETH_CMD_VFN_V(0));
2948         c.alloc_to_len16 = htonl(FW_EQ_ETH_CMD_ALLOC_F |
2949                                  FW_EQ_ETH_CMD_EQSTART_F | FW_LEN16(c));
2950         c.viid_pkd = htonl(FW_EQ_ETH_CMD_AUTOEQUEQE_F |
2951                            FW_EQ_ETH_CMD_VIID_V(pi->viid));
2952         c.fetchszm_to_iqid =
2953                 htonl(FW_EQ_ETH_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
2954                       FW_EQ_ETH_CMD_PCIECHN_V(pi->tx_chan) |
2955                       FW_EQ_ETH_CMD_FETCHRO_F | FW_EQ_ETH_CMD_IQID_V(iqid));
2956         c.dcaen_to_eqsize =
2957                 htonl(FW_EQ_ETH_CMD_FBMIN_V(FETCHBURSTMIN_64B_X) |
2958                       FW_EQ_ETH_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
2959                       FW_EQ_ETH_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
2960                       FW_EQ_ETH_CMD_EQSIZE_V(nentries));
2961         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
2962
2963         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
2964         if (ret) {
2965                 kfree(txq->q.sdesc);
2966                 txq->q.sdesc = NULL;
2967                 dma_free_coherent(adap->pdev_dev,
2968                                   nentries * sizeof(struct tx_desc),
2969                                   txq->q.desc, txq->q.phys_addr);
2970                 txq->q.desc = NULL;
2971                 return ret;
2972         }
2973
2974         txq->q.q_type = CXGB4_TXQ_ETH;
2975         init_txq(adap, &txq->q, FW_EQ_ETH_CMD_EQID_G(ntohl(c.eqid_pkd)));
2976         txq->txq = netdevq;
2977         txq->tso = txq->tx_cso = txq->vlan_ins = 0;
2978         txq->mapping_err = 0;
2979         return 0;
2980 }
2981
2982 int t4_sge_alloc_ctrl_txq(struct adapter *adap, struct sge_ctrl_txq *txq,
2983                           struct net_device *dev, unsigned int iqid,
2984                           unsigned int cmplqid)
2985 {
2986         int ret, nentries;
2987         struct fw_eq_ctrl_cmd c;
2988         struct sge *s = &adap->sge;
2989         struct port_info *pi = netdev_priv(dev);
2990
2991         /* Add status entries */
2992         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2993
2994         txq->q.desc = alloc_ring(adap->pdev_dev, nentries,
2995                                  sizeof(struct tx_desc), 0, &txq->q.phys_addr,
2996                                  NULL, 0, dev_to_node(adap->pdev_dev));
2997         if (!txq->q.desc)
2998                 return -ENOMEM;
2999
3000         c.op_to_vfn = htonl(FW_CMD_OP_V(FW_EQ_CTRL_CMD) | FW_CMD_REQUEST_F |
3001                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
3002                             FW_EQ_CTRL_CMD_PFN_V(adap->pf) |
3003                             FW_EQ_CTRL_CMD_VFN_V(0));
3004         c.alloc_to_len16 = htonl(FW_EQ_CTRL_CMD_ALLOC_F |
3005                                  FW_EQ_CTRL_CMD_EQSTART_F | FW_LEN16(c));
3006         c.cmpliqid_eqid = htonl(FW_EQ_CTRL_CMD_CMPLIQID_V(cmplqid));
3007         c.physeqid_pkd = htonl(0);
3008         c.fetchszm_to_iqid =
3009                 htonl(FW_EQ_CTRL_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
3010                       FW_EQ_CTRL_CMD_PCIECHN_V(pi->tx_chan) |
3011                       FW_EQ_CTRL_CMD_FETCHRO_F | FW_EQ_CTRL_CMD_IQID_V(iqid));
3012         c.dcaen_to_eqsize =
3013                 htonl(FW_EQ_CTRL_CMD_FBMIN_V(FETCHBURSTMIN_64B_X) |
3014                       FW_EQ_CTRL_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
3015                       FW_EQ_CTRL_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
3016                       FW_EQ_CTRL_CMD_EQSIZE_V(nentries));
3017         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
3018
3019         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
3020         if (ret) {
3021                 dma_free_coherent(adap->pdev_dev,
3022                                   nentries * sizeof(struct tx_desc),
3023                                   txq->q.desc, txq->q.phys_addr);
3024                 txq->q.desc = NULL;
3025                 return ret;
3026         }
3027
3028         txq->q.q_type = CXGB4_TXQ_CTRL;
3029         init_txq(adap, &txq->q, FW_EQ_CTRL_CMD_EQID_G(ntohl(c.cmpliqid_eqid)));
3030         txq->adap = adap;
3031         skb_queue_head_init(&txq->sendq);
3032         tasklet_init(&txq->qresume_tsk, restart_ctrlq, (unsigned long)txq);
3033         txq->full = 0;
3034         return 0;
3035 }
3036
3037 int t4_sge_mod_ctrl_txq(struct adapter *adap, unsigned int eqid,
3038                         unsigned int cmplqid)
3039 {
3040         u32 param, val;
3041
3042         param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
3043                  FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DMAQ_EQ_CMPLIQID_CTRL) |
3044                  FW_PARAMS_PARAM_YZ_V(eqid));
3045         val = cmplqid;
3046         return t4_set_params(adap, adap->mbox, adap->pf, 0, 1, &param, &val);
3047 }
3048
3049 int t4_sge_alloc_uld_txq(struct adapter *adap, struct sge_uld_txq *txq,
3050                          struct net_device *dev, unsigned int iqid,
3051                          unsigned int uld_type)
3052 {
3053         int ret, nentries;
3054         struct fw_eq_ofld_cmd c;
3055         struct sge *s = &adap->sge;
3056         struct port_info *pi = netdev_priv(dev);
3057         int cmd = FW_EQ_OFLD_CMD;
3058
3059         /* Add status entries */
3060         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
3061
3062         txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
3063                         sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
3064                         &txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
3065                         NUMA_NO_NODE);
3066         if (!txq->q.desc)
3067                 return -ENOMEM;
3068
3069         memset(&c, 0, sizeof(c));
3070         if (unlikely(uld_type == CXGB4_TX_CRYPTO))
3071                 cmd = FW_EQ_CTRL_CMD;
3072         c.op_to_vfn = htonl(FW_CMD_OP_V(cmd) | FW_CMD_REQUEST_F |
3073                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
3074                             FW_EQ_OFLD_CMD_PFN_V(adap->pf) |
3075                             FW_EQ_OFLD_CMD_VFN_V(0));
3076         c.alloc_to_len16 = htonl(FW_EQ_OFLD_CMD_ALLOC_F |
3077                                  FW_EQ_OFLD_CMD_EQSTART_F | FW_LEN16(c));
3078         c.fetchszm_to_iqid =
3079                 htonl(FW_EQ_OFLD_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
3080                       FW_EQ_OFLD_CMD_PCIECHN_V(pi->tx_chan) |
3081                       FW_EQ_OFLD_CMD_FETCHRO_F | FW_EQ_OFLD_CMD_IQID_V(iqid));
3082         c.dcaen_to_eqsize =
3083                 htonl(FW_EQ_OFLD_CMD_FBMIN_V(FETCHBURSTMIN_64B_X) |
3084                       FW_EQ_OFLD_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
3085                       FW_EQ_OFLD_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
3086                       FW_EQ_OFLD_CMD_EQSIZE_V(nentries));
3087         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
3088
3089         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
3090         if (ret) {
3091                 kfree(txq->q.sdesc);
3092                 txq->q.sdesc = NULL;
3093                 dma_free_coherent(adap->pdev_dev,
3094                                   nentries * sizeof(struct tx_desc),
3095                                   txq->q.desc, txq->q.phys_addr);
3096                 txq->q.desc = NULL;
3097                 return ret;
3098         }
3099
3100         txq->q.q_type = CXGB4_TXQ_ULD;
3101         init_txq(adap, &txq->q, FW_EQ_OFLD_CMD_EQID_G(ntohl(c.eqid_pkd)));
3102         txq->adap = adap;
3103         skb_queue_head_init(&txq->sendq);
3104         tasklet_init(&txq->qresume_tsk, restart_ofldq, (unsigned long)txq);
3105         txq->full = 0;
3106         txq->mapping_err = 0;
3107         return 0;
3108 }
3109
3110 void free_txq(struct adapter *adap, struct sge_txq *q)
3111 {
3112         struct sge *s = &adap->sge;
3113
3114         dma_free_coherent(adap->pdev_dev,
3115                           q->size * sizeof(struct tx_desc) + s->stat_len,
3116                           q->desc, q->phys_addr);
3117         q->cntxt_id = 0;
3118         q->sdesc = NULL;
3119         q->desc = NULL;
3120 }
3121
3122 void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
3123                   struct sge_fl *fl)
3124 {
3125         struct sge *s = &adap->sge;
3126         unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
3127
3128         adap->sge.ingr_map[rq->cntxt_id - adap->sge.ingr_start] = NULL;
3129         t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
3130                    rq->cntxt_id, fl_id, 0xffff);
3131         dma_free_coherent(adap->pdev_dev, (rq->size + 1) * rq->iqe_len,
3132                           rq->desc, rq->phys_addr);
3133         netif_napi_del(&rq->napi);
3134         rq->netdev = NULL;
3135         rq->cntxt_id = rq->abs_id = 0;
3136         rq->desc = NULL;
3137
3138         if (fl) {
3139                 free_rx_bufs(adap, fl, fl->avail);
3140                 dma_free_coherent(adap->pdev_dev, fl->size * 8 + s->stat_len,
3141                                   fl->desc, fl->addr);
3142                 kfree(fl->sdesc);
3143                 fl->sdesc = NULL;
3144                 fl->cntxt_id = 0;
3145                 fl->desc = NULL;
3146         }
3147 }
3148
3149 /**
3150  *      t4_free_ofld_rxqs - free a block of consecutive Rx queues
3151  *      @adap: the adapter
3152  *      @n: number of queues
3153  *      @q: pointer to first queue
3154  *
3155  *      Release the resources of a consecutive block of offload Rx queues.
3156  */
3157 void t4_free_ofld_rxqs(struct adapter *adap, int n, struct sge_ofld_rxq *q)
3158 {
3159         for ( ; n; n--, q++)
3160                 if (q->rspq.desc)
3161                         free_rspq_fl(adap, &q->rspq,
3162                                      q->fl.size ? &q->fl : NULL);
3163 }
3164
3165 /**
3166  *      t4_free_sge_resources - free SGE resources
3167  *      @adap: the adapter
3168  *
3169  *      Frees resources used by the SGE queue sets.
3170  */
3171 void t4_free_sge_resources(struct adapter *adap)
3172 {
3173         int i;
3174         struct sge_eth_rxq *eq;
3175         struct sge_eth_txq *etq;
3176
3177         /* stop all Rx queues in order to start them draining */
3178         for (i = 0; i < adap->sge.ethqsets; i++) {
3179                 eq = &adap->sge.ethrxq[i];
3180                 if (eq->rspq.desc)
3181                         t4_iq_stop(adap, adap->mbox, adap->pf, 0,
3182                                    FW_IQ_TYPE_FL_INT_CAP,
3183                                    eq->rspq.cntxt_id,
3184                                    eq->fl.size ? eq->fl.cntxt_id : 0xffff,
3185                                    0xffff);
3186         }
3187
3188         /* clean up Ethernet Tx/Rx queues */
3189         for (i = 0; i < adap->sge.ethqsets; i++) {
3190                 eq = &adap->sge.ethrxq[i];
3191                 if (eq->rspq.desc)
3192                         free_rspq_fl(adap, &eq->rspq,
3193                                      eq->fl.size ? &eq->fl : NULL);
3194
3195                 etq = &adap->sge.ethtxq[i];
3196                 if (etq->q.desc) {
3197                         t4_eth_eq_free(adap, adap->mbox, adap->pf, 0,
3198                                        etq->q.cntxt_id);
3199                         __netif_tx_lock_bh(etq->txq);
3200                         free_tx_desc(adap, &etq->q, etq->q.in_use, true);
3201                         __netif_tx_unlock_bh(etq->txq);
3202                         kfree(etq->q.sdesc);
3203                         free_txq(adap, &etq->q);
3204                 }
3205         }
3206
3207         /* clean up control Tx queues */
3208         for (i = 0; i < ARRAY_SIZE(adap->sge.ctrlq); i++) {
3209                 struct sge_ctrl_txq *cq = &adap->sge.ctrlq[i];
3210
3211                 if (cq->q.desc) {
3212                         tasklet_kill(&cq->qresume_tsk);
3213                         t4_ctrl_eq_free(adap, adap->mbox, adap->pf, 0,
3214                                         cq->q.cntxt_id);
3215                         __skb_queue_purge(&cq->sendq);
3216                         free_txq(adap, &cq->q);
3217                 }
3218         }
3219
3220         if (adap->sge.fw_evtq.desc)
3221                 free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
3222
3223         if (adap->sge.intrq.desc)
3224                 free_rspq_fl(adap, &adap->sge.intrq, NULL);
3225
3226         if (!is_t4(adap->params.chip)) {
3227                 etq = &adap->sge.ptptxq;
3228                 if (etq->q.desc) {
3229                         t4_eth_eq_free(adap, adap->mbox, adap->pf, 0,
3230                                        etq->q.cntxt_id);
3231                         spin_lock_bh(&adap->ptp_lock);
3232                         free_tx_desc(adap, &etq->q, etq->q.in_use, true);
3233                         spin_unlock_bh(&adap->ptp_lock);
3234                         kfree(etq->q.sdesc);
3235                         free_txq(adap, &etq->q);
3236                 }
3237         }
3238
3239         /* clear the reverse egress queue map */
3240         memset(adap->sge.egr_map, 0,
3241                adap->sge.egr_sz * sizeof(*adap->sge.egr_map));
3242 }
3243
3244 void t4_sge_start(struct adapter *adap)
3245 {
3246         adap->sge.ethtxq_rover = 0;
3247         mod_timer(&adap->sge.rx_timer, jiffies + RX_QCHECK_PERIOD);
3248         mod_timer(&adap->sge.tx_timer, jiffies + TX_QCHECK_PERIOD);
3249 }
3250
3251 /**
3252  *      t4_sge_stop - disable SGE operation
3253  *      @adap: the adapter
3254  *
3255  *      Stop tasklets and timers associated with the DMA engine.  Note that
3256  *      this is effective only if measures have been taken to disable any HW
3257  *      events that may restart them.
3258  */
3259 void t4_sge_stop(struct adapter *adap)
3260 {
3261         int i;
3262         struct sge *s = &adap->sge;
3263
3264         if (in_interrupt())  /* actions below require waiting */
3265                 return;
3266
3267         if (s->rx_timer.function)
3268                 del_timer_sync(&s->rx_timer);
3269         if (s->tx_timer.function)
3270                 del_timer_sync(&s->tx_timer);
3271
3272         if (is_offload(adap)) {
3273                 struct sge_uld_txq_info *txq_info;
3274
3275                 txq_info = adap->sge.uld_txq_info[CXGB4_TX_OFLD];
3276                 if (txq_info) {
3277                         struct sge_uld_txq *txq = txq_info->uldtxq;
3278
3279                         for_each_ofldtxq(&adap->sge, i) {
3280                                 if (txq->q.desc)
3281                                         tasklet_kill(&txq->qresume_tsk);
3282                         }
3283                 }
3284         }
3285
3286         if (is_pci_uld(adap)) {
3287                 struct sge_uld_txq_info *txq_info;
3288
3289                 txq_info = adap->sge.uld_txq_info[CXGB4_TX_CRYPTO];
3290                 if (txq_info) {
3291                         struct sge_uld_txq *txq = txq_info->uldtxq;
3292
3293                         for_each_ofldtxq(&adap->sge, i) {
3294                                 if (txq->q.desc)
3295                                         tasklet_kill(&txq->qresume_tsk);
3296                         }
3297                 }
3298         }
3299
3300         for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++) {
3301                 struct sge_ctrl_txq *cq = &s->ctrlq[i];
3302
3303                 if (cq->q.desc)
3304                         tasklet_kill(&cq->qresume_tsk);
3305         }
3306 }
3307
3308 /**
3309  *      t4_sge_init_soft - grab core SGE values needed by SGE code
3310  *      @adap: the adapter
3311  *
3312  *      We need to grab the SGE operating parameters that we need to have
3313  *      in order to do our job and make sure we can live with them.
3314  */
3315
3316 static int t4_sge_init_soft(struct adapter *adap)
3317 {
3318         struct sge *s = &adap->sge;
3319         u32 fl_small_pg, fl_large_pg, fl_small_mtu, fl_large_mtu;
3320         u32 timer_value_0_and_1, timer_value_2_and_3, timer_value_4_and_5;
3321         u32 ingress_rx_threshold;
3322
3323         /*
3324          * Verify that CPL messages are going to the Ingress Queue for
3325          * process_responses() and that only packet data is going to the
3326          * Free Lists.
3327          */
3328         if ((t4_read_reg(adap, SGE_CONTROL_A) & RXPKTCPLMODE_F) !=
3329             RXPKTCPLMODE_V(RXPKTCPLMODE_SPLIT_X)) {
3330                 dev_err(adap->pdev_dev, "bad SGE CPL MODE\n");
3331                 return -EINVAL;
3332         }
3333
3334         /*
3335          * Validate the Host Buffer Register Array indices that we want to
3336          * use ...
3337          *
3338          * XXX Note that we should really read through the Host Buffer Size
3339          * XXX register array and find the indices of the Buffer Sizes which
3340          * XXX meet our needs!
3341          */
3342         #define READ_FL_BUF(x) \
3343                 t4_read_reg(adap, SGE_FL_BUFFER_SIZE0_A+(x)*sizeof(u32))
3344
3345         fl_small_pg = READ_FL_BUF(RX_SMALL_PG_BUF);
3346         fl_large_pg = READ_FL_BUF(RX_LARGE_PG_BUF);
3347         fl_small_mtu = READ_FL_BUF(RX_SMALL_MTU_BUF);
3348         fl_large_mtu = READ_FL_BUF(RX_LARGE_MTU_BUF);
3349
3350         /* We only bother using the Large Page logic if the Large Page Buffer
3351          * is larger than our Page Size Buffer.
3352          */
3353         if (fl_large_pg <= fl_small_pg)
3354                 fl_large_pg = 0;
3355
3356         #undef READ_FL_BUF
3357
3358         /* The Page Size Buffer must be exactly equal to our Page Size and the
3359          * Large Page Size Buffer should be 0 (per above) or a power of 2.
3360          */
3361         if (fl_small_pg != PAGE_SIZE ||
3362             (fl_large_pg & (fl_large_pg-1)) != 0) {
3363                 dev_err(adap->pdev_dev, "bad SGE FL page buffer sizes [%d, %d]\n",
3364                         fl_small_pg, fl_large_pg);
3365                 return -EINVAL;
3366         }
3367         if (fl_large_pg)
3368                 s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
3369
3370         if (fl_small_mtu < FL_MTU_SMALL_BUFSIZE(adap) ||
3371             fl_large_mtu < FL_MTU_LARGE_BUFSIZE(adap)) {
3372                 dev_err(adap->pdev_dev, "bad SGE FL MTU sizes [%d, %d]\n",
3373                         fl_small_mtu, fl_large_mtu);
3374                 return -EINVAL;
3375         }
3376
3377         /*
3378          * Retrieve our RX interrupt holdoff timer values and counter
3379          * threshold values from the SGE parameters.
3380          */
3381         timer_value_0_and_1 = t4_read_reg(adap, SGE_TIMER_VALUE_0_AND_1_A);
3382         timer_value_2_and_3 = t4_read_reg(adap, SGE_TIMER_VALUE_2_AND_3_A);
3383         timer_value_4_and_5 = t4_read_reg(adap, SGE_TIMER_VALUE_4_AND_5_A);
3384         s->timer_val[0] = core_ticks_to_us(adap,
3385                 TIMERVALUE0_G(timer_value_0_and_1));
3386         s->timer_val[1] = core_ticks_to_us(adap,
3387                 TIMERVALUE1_G(timer_value_0_and_1));
3388         s->timer_val[2] = core_ticks_to_us(adap,
3389                 TIMERVALUE2_G(timer_value_2_and_3));
3390         s->timer_val[3] = core_ticks_to_us(adap,
3391                 TIMERVALUE3_G(timer_value_2_and_3));
3392         s->timer_val[4] = core_ticks_to_us(adap,
3393                 TIMERVALUE4_G(timer_value_4_and_5));
3394         s->timer_val[5] = core_ticks_to_us(adap,
3395                 TIMERVALUE5_G(timer_value_4_and_5));
3396
3397         ingress_rx_threshold = t4_read_reg(adap, SGE_INGRESS_RX_THRESHOLD_A);
3398         s->counter_val[0] = THRESHOLD_0_G(ingress_rx_threshold);
3399         s->counter_val[1] = THRESHOLD_1_G(ingress_rx_threshold);
3400         s->counter_val[2] = THRESHOLD_2_G(ingress_rx_threshold);
3401         s->counter_val[3] = THRESHOLD_3_G(ingress_rx_threshold);
3402
3403         return 0;
3404 }
3405
3406 /**
3407  *     t4_sge_init - initialize SGE
3408  *     @adap: the adapter
3409  *
3410  *     Perform low-level SGE code initialization needed every time after a
3411  *     chip reset.
3412  */
3413 int t4_sge_init(struct adapter *adap)
3414 {
3415         struct sge *s = &adap->sge;
3416         u32 sge_control, sge_conm_ctrl;
3417         int ret, egress_threshold;
3418
3419         /*
3420          * Ingress Padding Boundary and Egress Status Page Size are set up by
3421          * t4_fixup_host_params().
3422          */
3423         sge_control = t4_read_reg(adap, SGE_CONTROL_A);
3424         s->pktshift = PKTSHIFT_G(sge_control);
3425         s->stat_len = (sge_control & EGRSTATUSPAGESIZE_F) ? 128 : 64;
3426
3427         s->fl_align = t4_fl_pkt_align(adap);
3428         ret = t4_sge_init_soft(adap);
3429         if (ret < 0)
3430                 return ret;
3431
3432         /*
3433          * A FL with <= fl_starve_thres buffers is starving and a periodic
3434          * timer will attempt to refill it.  This needs to be larger than the
3435          * SGE's Egress Congestion Threshold.  If it isn't, then we can get
3436          * stuck waiting for new packets while the SGE is waiting for us to
3437          * give it more Free List entries.  (Note that the SGE's Egress
3438          * Congestion Threshold is in units of 2 Free List pointers.) For T4,
3439          * there was only a single field to control this.  For T5 there's the
3440          * original field which now only applies to Unpacked Mode Free List
3441          * buffers and a new field which only applies to Packed Mode Free List
3442          * buffers.
3443          */
3444         sge_conm_ctrl = t4_read_reg(adap, SGE_CONM_CTRL_A);
3445         switch (CHELSIO_CHIP_VERSION(adap->params.chip)) {
3446         case CHELSIO_T4:
3447                 egress_threshold = EGRTHRESHOLD_G(sge_conm_ctrl);
3448                 break;
3449         case CHELSIO_T5:
3450                 egress_threshold = EGRTHRESHOLDPACKING_G(sge_conm_ctrl);
3451                 break;
3452         case CHELSIO_T6:
3453                 egress_threshold = T6_EGRTHRESHOLDPACKING_G(sge_conm_ctrl);
3454                 break;
3455         default:
3456                 dev_err(adap->pdev_dev, "Unsupported Chip version %d\n",
3457                         CHELSIO_CHIP_VERSION(adap->params.chip));
3458                 return -EINVAL;
3459         }
3460         s->fl_starve_thres = 2*egress_threshold + 1;
3461
3462         t4_idma_monitor_init(adap, &s->idma_monitor);
3463
3464         /* Set up timers used for recuring callbacks to process RX and TX
3465          * administrative tasks.
3466          */
3467         setup_timer(&s->rx_timer, sge_rx_timer_cb, (unsigned long)adap);
3468         setup_timer(&s->tx_timer, sge_tx_timer_cb, (unsigned long)adap);
3469
3470         spin_lock_init(&s->intrq_lock);
3471
3472         return 0;
3473 }