powerpc/perf/hv-24x7: Move cpumask file to top folder of hv-24x7 driver
[linux-2.6-microblaze.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/xfrm.h>
45 #include <net/ipv6.h>
46 #include <net/tcp.h>
47 #include <net/busy_poll.h>
48 #ifdef CONFIG_CHELSIO_T4_FCOE
49 #include <scsi/fc/fc_fcoe.h>
50 #endif /* CONFIG_CHELSIO_T4_FCOE */
51 #include "cxgb4.h"
52 #include "t4_regs.h"
53 #include "t4_values.h"
54 #include "t4_msg.h"
55 #include "t4fw_api.h"
56 #include "cxgb4_ptp.h"
57 #include "cxgb4_uld.h"
58 #include "cxgb4_tc_mqprio.h"
59 #include "sched.h"
60
61 /*
62  * Rx buffer size.  We use largish buffers if possible but settle for single
63  * pages under memory shortage.
64  */
65 #if PAGE_SHIFT >= 16
66 # define FL_PG_ORDER 0
67 #else
68 # define FL_PG_ORDER (16 - PAGE_SHIFT)
69 #endif
70
71 /* RX_PULL_LEN should be <= RX_COPY_THRES */
72 #define RX_COPY_THRES    256
73 #define RX_PULL_LEN      128
74
75 /*
76  * Main body length for sk_buffs used for Rx Ethernet packets with fragments.
77  * Should be >= RX_PULL_LEN but possibly bigger to give pskb_may_pull some room.
78  */
79 #define RX_PKT_SKB_LEN   512
80
81 /*
82  * Max number of Tx descriptors we clean up at a time.  Should be modest as
83  * freeing skbs isn't cheap and it happens while holding locks.  We just need
84  * to free packets faster than they arrive, we eventually catch up and keep
85  * the amortized cost reasonable.  Must be >= 2 * TXQ_STOP_THRES.  It should
86  * also match the CIDX Flush Threshold.
87  */
88 #define MAX_TX_RECLAIM 32
89
90 /*
91  * Max number of Rx buffers we replenish at a time.  Again keep this modest,
92  * allocating buffers isn't cheap either.
93  */
94 #define MAX_RX_REFILL 16U
95
96 /*
97  * Period of the Rx queue check timer.  This timer is infrequent as it has
98  * something to do only when the system experiences severe memory shortage.
99  */
100 #define RX_QCHECK_PERIOD (HZ / 2)
101
102 /*
103  * Period of the Tx queue check timer.
104  */
105 #define TX_QCHECK_PERIOD (HZ / 2)
106
107 /*
108  * Max number of Tx descriptors to be reclaimed by the Tx timer.
109  */
110 #define MAX_TIMER_TX_RECLAIM 100
111
112 /*
113  * Timer index used when backing off due to memory shortage.
114  */
115 #define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
116
117 /*
118  * Suspension threshold for non-Ethernet Tx queues.  We require enough room
119  * for a full sized WR.
120  */
121 #define TXQ_STOP_THRES (SGE_MAX_WR_LEN / sizeof(struct tx_desc))
122
123 /*
124  * Max Tx descriptor space we allow for an Ethernet packet to be inlined
125  * into a WR.
126  */
127 #define MAX_IMM_TX_PKT_LEN 256
128
129 /*
130  * Max size of a WR sent through a control Tx queue.
131  */
132 #define MAX_CTRL_WR_LEN SGE_MAX_WR_LEN
133
134 struct rx_sw_desc {                /* SW state per Rx descriptor */
135         struct page *page;
136         dma_addr_t dma_addr;
137 };
138
139 /*
140  * Rx buffer sizes for "useskbs" Free List buffers (one ingress packet pe skb
141  * buffer).  We currently only support two sizes for 1500- and 9000-byte MTUs.
142  * We could easily support more but there doesn't seem to be much need for
143  * that ...
144  */
145 #define FL_MTU_SMALL 1500
146 #define FL_MTU_LARGE 9000
147
148 static inline unsigned int fl_mtu_bufsize(struct adapter *adapter,
149                                           unsigned int mtu)
150 {
151         struct sge *s = &adapter->sge;
152
153         return ALIGN(s->pktshift + ETH_HLEN + VLAN_HLEN + mtu, s->fl_align);
154 }
155
156 #define FL_MTU_SMALL_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_SMALL)
157 #define FL_MTU_LARGE_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_LARGE)
158
159 /*
160  * Bits 0..3 of rx_sw_desc.dma_addr have special meaning.  The hardware uses
161  * these to specify the buffer size as an index into the SGE Free List Buffer
162  * Size register array.  We also use bit 4, when the buffer has been unmapped
163  * for DMA, but this is of course never sent to the hardware and is only used
164  * to prevent double unmappings.  All of the above requires that the Free List
165  * Buffers which we allocate have the bottom 5 bits free (0) -- i.e. are
166  * 32-byte or or a power of 2 greater in alignment.  Since the SGE's minimal
167  * Free List Buffer alignment is 32 bytes, this works out for us ...
168  */
169 enum {
170         RX_BUF_FLAGS     = 0x1f,   /* bottom five bits are special */
171         RX_BUF_SIZE      = 0x0f,   /* bottom three bits are for buf sizes */
172         RX_UNMAPPED_BUF  = 0x10,   /* buffer is not mapped */
173
174         /*
175          * XXX We shouldn't depend on being able to use these indices.
176          * XXX Especially when some other Master PF has initialized the
177          * XXX adapter or we use the Firmware Configuration File.  We
178          * XXX should really search through the Host Buffer Size register
179          * XXX array for the appropriately sized buffer indices.
180          */
181         RX_SMALL_PG_BUF  = 0x0,   /* small (PAGE_SIZE) page buffer */
182         RX_LARGE_PG_BUF  = 0x1,   /* buffer large (FL_PG_ORDER) page buffer */
183
184         RX_SMALL_MTU_BUF = 0x2,   /* small MTU buffer */
185         RX_LARGE_MTU_BUF = 0x3,   /* large MTU buffer */
186 };
187
188 static int timer_pkt_quota[] = {1, 1, 2, 3, 4, 5};
189 #define MIN_NAPI_WORK  1
190
191 static inline dma_addr_t get_buf_addr(const struct rx_sw_desc *d)
192 {
193         return d->dma_addr & ~(dma_addr_t)RX_BUF_FLAGS;
194 }
195
196 static inline bool is_buf_mapped(const struct rx_sw_desc *d)
197 {
198         return !(d->dma_addr & RX_UNMAPPED_BUF);
199 }
200
201 /**
202  *      txq_avail - return the number of available slots in a Tx queue
203  *      @q: the Tx queue
204  *
205  *      Returns the number of descriptors in a Tx queue available to write new
206  *      packets.
207  */
208 static inline unsigned int txq_avail(const struct sge_txq *q)
209 {
210         return q->size - 1 - q->in_use;
211 }
212
213 /**
214  *      fl_cap - return the capacity of a free-buffer list
215  *      @fl: the FL
216  *
217  *      Returns the capacity of a free-buffer list.  The capacity is less than
218  *      the size because one descriptor needs to be left unpopulated, otherwise
219  *      HW will think the FL is empty.
220  */
221 static inline unsigned int fl_cap(const struct sge_fl *fl)
222 {
223         return fl->size - 8;   /* 1 descriptor = 8 buffers */
224 }
225
226 /**
227  *      fl_starving - return whether a Free List is starving.
228  *      @adapter: pointer to the adapter
229  *      @fl: the Free List
230  *
231  *      Tests specified Free List to see whether the number of buffers
232  *      available to the hardware has falled below our "starvation"
233  *      threshold.
234  */
235 static inline bool fl_starving(const struct adapter *adapter,
236                                const struct sge_fl *fl)
237 {
238         const struct sge *s = &adapter->sge;
239
240         return fl->avail - fl->pend_cred <= s->fl_starve_thres;
241 }
242
243 int cxgb4_map_skb(struct device *dev, const struct sk_buff *skb,
244                   dma_addr_t *addr)
245 {
246         const skb_frag_t *fp, *end;
247         const struct skb_shared_info *si;
248
249         *addr = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
250         if (dma_mapping_error(dev, *addr))
251                 goto out_err;
252
253         si = skb_shinfo(skb);
254         end = &si->frags[si->nr_frags];
255
256         for (fp = si->frags; fp < end; fp++) {
257                 *++addr = skb_frag_dma_map(dev, fp, 0, skb_frag_size(fp),
258                                            DMA_TO_DEVICE);
259                 if (dma_mapping_error(dev, *addr))
260                         goto unwind;
261         }
262         return 0;
263
264 unwind:
265         while (fp-- > si->frags)
266                 dma_unmap_page(dev, *--addr, skb_frag_size(fp), DMA_TO_DEVICE);
267
268         dma_unmap_single(dev, addr[-1], skb_headlen(skb), DMA_TO_DEVICE);
269 out_err:
270         return -ENOMEM;
271 }
272 EXPORT_SYMBOL(cxgb4_map_skb);
273
274 static void unmap_skb(struct device *dev, const struct sk_buff *skb,
275                       const dma_addr_t *addr)
276 {
277         const skb_frag_t *fp, *end;
278         const struct skb_shared_info *si;
279
280         dma_unmap_single(dev, *addr++, skb_headlen(skb), DMA_TO_DEVICE);
281
282         si = skb_shinfo(skb);
283         end = &si->frags[si->nr_frags];
284         for (fp = si->frags; fp < end; fp++)
285                 dma_unmap_page(dev, *addr++, skb_frag_size(fp), DMA_TO_DEVICE);
286 }
287
288 #ifdef CONFIG_NEED_DMA_MAP_STATE
289 /**
290  *      deferred_unmap_destructor - unmap a packet when it is freed
291  *      @skb: the packet
292  *
293  *      This is the packet destructor used for Tx packets that need to remain
294  *      mapped until they are freed rather than until their Tx descriptors are
295  *      freed.
296  */
297 static void deferred_unmap_destructor(struct sk_buff *skb)
298 {
299         unmap_skb(skb->dev->dev.parent, skb, (dma_addr_t *)skb->head);
300 }
301 #endif
302
303 /**
304  *      free_tx_desc - reclaims Tx descriptors and their buffers
305  *      @adap: the adapter
306  *      @q: the Tx queue to reclaim descriptors from
307  *      @n: the number of descriptors to reclaim
308  *      @unmap: whether the buffers should be unmapped for DMA
309  *
310  *      Reclaims Tx descriptors from an SGE Tx queue and frees the associated
311  *      Tx buffers.  Called with the Tx queue lock held.
312  */
313 void free_tx_desc(struct adapter *adap, struct sge_txq *q,
314                   unsigned int n, bool unmap)
315 {
316         unsigned int cidx = q->cidx;
317         struct tx_sw_desc *d;
318
319         d = &q->sdesc[cidx];
320         while (n--) {
321                 if (d->skb) {                       /* an SGL is present */
322                         if (unmap && d->addr[0]) {
323                                 unmap_skb(adap->pdev_dev, d->skb, d->addr);
324                                 memset(d->addr, 0, sizeof(d->addr));
325                         }
326                         dev_consume_skb_any(d->skb);
327                         d->skb = NULL;
328                 }
329                 ++d;
330                 if (++cidx == q->size) {
331                         cidx = 0;
332                         d = q->sdesc;
333                 }
334         }
335         q->cidx = cidx;
336 }
337
338 /*
339  * Return the number of reclaimable descriptors in a Tx queue.
340  */
341 static inline int reclaimable(const struct sge_txq *q)
342 {
343         int hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
344         hw_cidx -= q->cidx;
345         return hw_cidx < 0 ? hw_cidx + q->size : hw_cidx;
346 }
347
348 /**
349  *      reclaim_completed_tx - reclaims completed TX Descriptors
350  *      @adap: the adapter
351  *      @q: the Tx queue to reclaim completed descriptors from
352  *      @maxreclaim: the maximum number of TX Descriptors to reclaim or -1
353  *      @unmap: whether the buffers should be unmapped for DMA
354  *
355  *      Reclaims Tx Descriptors that the SGE has indicated it has processed,
356  *      and frees the associated buffers if possible.  If @max == -1, then
357  *      we'll use a defaiult maximum.  Called with the TX Queue locked.
358  */
359 static inline int reclaim_completed_tx(struct adapter *adap, struct sge_txq *q,
360                                        int maxreclaim, bool unmap)
361 {
362         int reclaim = reclaimable(q);
363
364         if (reclaim) {
365                 /*
366                  * Limit the amount of clean up work we do at a time to keep
367                  * the Tx lock hold time O(1).
368                  */
369                 if (maxreclaim < 0)
370                         maxreclaim = MAX_TX_RECLAIM;
371                 if (reclaim > maxreclaim)
372                         reclaim = maxreclaim;
373
374                 free_tx_desc(adap, q, reclaim, unmap);
375                 q->in_use -= reclaim;
376         }
377
378         return reclaim;
379 }
380
381 /**
382  *      cxgb4_reclaim_completed_tx - reclaims completed Tx descriptors
383  *      @adap: the adapter
384  *      @q: the Tx queue to reclaim completed descriptors from
385  *      @unmap: whether the buffers should be unmapped for DMA
386  *
387  *      Reclaims Tx descriptors that the SGE has indicated it has processed,
388  *      and frees the associated buffers if possible.  Called with the Tx
389  *      queue locked.
390  */
391 void cxgb4_reclaim_completed_tx(struct adapter *adap, struct sge_txq *q,
392                                 bool unmap)
393 {
394         (void)reclaim_completed_tx(adap, q, -1, unmap);
395 }
396 EXPORT_SYMBOL(cxgb4_reclaim_completed_tx);
397
398 static inline int get_buf_size(struct adapter *adapter,
399                                const struct rx_sw_desc *d)
400 {
401         struct sge *s = &adapter->sge;
402         unsigned int rx_buf_size_idx = d->dma_addr & RX_BUF_SIZE;
403         int buf_size;
404
405         switch (rx_buf_size_idx) {
406         case RX_SMALL_PG_BUF:
407                 buf_size = PAGE_SIZE;
408                 break;
409
410         case RX_LARGE_PG_BUF:
411                 buf_size = PAGE_SIZE << s->fl_pg_order;
412                 break;
413
414         case RX_SMALL_MTU_BUF:
415                 buf_size = FL_MTU_SMALL_BUFSIZE(adapter);
416                 break;
417
418         case RX_LARGE_MTU_BUF:
419                 buf_size = FL_MTU_LARGE_BUFSIZE(adapter);
420                 break;
421
422         default:
423                 BUG();
424         }
425
426         return buf_size;
427 }
428
429 /**
430  *      free_rx_bufs - free the Rx buffers on an SGE free list
431  *      @adap: the adapter
432  *      @q: the SGE free list to free buffers from
433  *      @n: how many buffers to free
434  *
435  *      Release the next @n buffers on an SGE free-buffer Rx queue.   The
436  *      buffers must be made inaccessible to HW before calling this function.
437  */
438 static void free_rx_bufs(struct adapter *adap, struct sge_fl *q, int n)
439 {
440         while (n--) {
441                 struct rx_sw_desc *d = &q->sdesc[q->cidx];
442
443                 if (is_buf_mapped(d))
444                         dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
445                                        get_buf_size(adap, d),
446                                        PCI_DMA_FROMDEVICE);
447                 put_page(d->page);
448                 d->page = NULL;
449                 if (++q->cidx == q->size)
450                         q->cidx = 0;
451                 q->avail--;
452         }
453 }
454
455 /**
456  *      unmap_rx_buf - unmap the current Rx buffer on an SGE free list
457  *      @adap: the adapter
458  *      @q: the SGE free list
459  *
460  *      Unmap the current buffer on an SGE free-buffer Rx queue.   The
461  *      buffer must be made inaccessible to HW before calling this function.
462  *
463  *      This is similar to @free_rx_bufs above but does not free the buffer.
464  *      Do note that the FL still loses any further access to the buffer.
465  */
466 static void unmap_rx_buf(struct adapter *adap, struct sge_fl *q)
467 {
468         struct rx_sw_desc *d = &q->sdesc[q->cidx];
469
470         if (is_buf_mapped(d))
471                 dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
472                                get_buf_size(adap, d), PCI_DMA_FROMDEVICE);
473         d->page = NULL;
474         if (++q->cidx == q->size)
475                 q->cidx = 0;
476         q->avail--;
477 }
478
479 static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
480 {
481         if (q->pend_cred >= 8) {
482                 u32 val = adap->params.arch.sge_fl_db;
483
484                 if (is_t4(adap->params.chip))
485                         val |= PIDX_V(q->pend_cred / 8);
486                 else
487                         val |= PIDX_T5_V(q->pend_cred / 8);
488
489                 /* Make sure all memory writes to the Free List queue are
490                  * committed before we tell the hardware about them.
491                  */
492                 wmb();
493
494                 /* If we don't have access to the new User Doorbell (T5+), use
495                  * the old doorbell mechanism; otherwise use the new BAR2
496                  * mechanism.
497                  */
498                 if (unlikely(q->bar2_addr == NULL)) {
499                         t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
500                                      val | QID_V(q->cntxt_id));
501                 } else {
502                         writel(val | QID_V(q->bar2_qid),
503                                q->bar2_addr + SGE_UDB_KDOORBELL);
504
505                         /* This Write memory Barrier will force the write to
506                          * the User Doorbell area to be flushed.
507                          */
508                         wmb();
509                 }
510                 q->pend_cred &= 7;
511         }
512 }
513
514 static inline void set_rx_sw_desc(struct rx_sw_desc *sd, struct page *pg,
515                                   dma_addr_t mapping)
516 {
517         sd->page = pg;
518         sd->dma_addr = mapping;      /* includes size low bits */
519 }
520
521 /**
522  *      refill_fl - refill an SGE Rx buffer ring
523  *      @adap: the adapter
524  *      @q: the ring to refill
525  *      @n: the number of new buffers to allocate
526  *      @gfp: the gfp flags for the allocations
527  *
528  *      (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
529  *      allocated with the supplied gfp flags.  The caller must assure that
530  *      @n does not exceed the queue's capacity.  If afterwards the queue is
531  *      found critically low mark it as starving in the bitmap of starving FLs.
532  *
533  *      Returns the number of buffers allocated.
534  */
535 static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n,
536                               gfp_t gfp)
537 {
538         struct sge *s = &adap->sge;
539         struct page *pg;
540         dma_addr_t mapping;
541         unsigned int cred = q->avail;
542         __be64 *d = &q->desc[q->pidx];
543         struct rx_sw_desc *sd = &q->sdesc[q->pidx];
544         int node;
545
546 #ifdef CONFIG_DEBUG_FS
547         if (test_bit(q->cntxt_id - adap->sge.egr_start, adap->sge.blocked_fl))
548                 goto out;
549 #endif
550
551         gfp |= __GFP_NOWARN;
552         node = dev_to_node(adap->pdev_dev);
553
554         if (s->fl_pg_order == 0)
555                 goto alloc_small_pages;
556
557         /*
558          * Prefer large buffers
559          */
560         while (n) {
561                 pg = alloc_pages_node(node, gfp | __GFP_COMP, s->fl_pg_order);
562                 if (unlikely(!pg)) {
563                         q->large_alloc_failed++;
564                         break;       /* fall back to single pages */
565                 }
566
567                 mapping = dma_map_page(adap->pdev_dev, pg, 0,
568                                        PAGE_SIZE << s->fl_pg_order,
569                                        PCI_DMA_FROMDEVICE);
570                 if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
571                         __free_pages(pg, s->fl_pg_order);
572                         q->mapping_err++;
573                         goto out;   /* do not try small pages for this error */
574                 }
575                 mapping |= RX_LARGE_PG_BUF;
576                 *d++ = cpu_to_be64(mapping);
577
578                 set_rx_sw_desc(sd, pg, mapping);
579                 sd++;
580
581                 q->avail++;
582                 if (++q->pidx == q->size) {
583                         q->pidx = 0;
584                         sd = q->sdesc;
585                         d = q->desc;
586                 }
587                 n--;
588         }
589
590 alloc_small_pages:
591         while (n--) {
592                 pg = alloc_pages_node(node, gfp, 0);
593                 if (unlikely(!pg)) {
594                         q->alloc_failed++;
595                         break;
596                 }
597
598                 mapping = dma_map_page(adap->pdev_dev, pg, 0, PAGE_SIZE,
599                                        PCI_DMA_FROMDEVICE);
600                 if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
601                         put_page(pg);
602                         q->mapping_err++;
603                         goto out;
604                 }
605                 *d++ = cpu_to_be64(mapping);
606
607                 set_rx_sw_desc(sd, pg, mapping);
608                 sd++;
609
610                 q->avail++;
611                 if (++q->pidx == q->size) {
612                         q->pidx = 0;
613                         sd = q->sdesc;
614                         d = q->desc;
615                 }
616         }
617
618 out:    cred = q->avail - cred;
619         q->pend_cred += cred;
620         ring_fl_db(adap, q);
621
622         if (unlikely(fl_starving(adap, q))) {
623                 smp_wmb();
624                 q->low++;
625                 set_bit(q->cntxt_id - adap->sge.egr_start,
626                         adap->sge.starving_fl);
627         }
628
629         return cred;
630 }
631
632 static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
633 {
634         refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail),
635                   GFP_ATOMIC);
636 }
637
638 /**
639  *      alloc_ring - allocate resources for an SGE descriptor ring
640  *      @dev: the PCI device's core device
641  *      @nelem: the number of descriptors
642  *      @elem_size: the size of each descriptor
643  *      @sw_size: the size of the SW state associated with each ring element
644  *      @phys: the physical address of the allocated ring
645  *      @metadata: address of the array holding the SW state for the ring
646  *      @stat_size: extra space in HW ring for status information
647  *      @node: preferred node for memory allocations
648  *
649  *      Allocates resources for an SGE descriptor ring, such as Tx queues,
650  *      free buffer lists, or response queues.  Each SGE ring requires
651  *      space for its HW descriptors plus, optionally, space for the SW state
652  *      associated with each HW entry (the metadata).  The function returns
653  *      three values: the virtual address for the HW ring (the return value
654  *      of the function), the bus address of the HW ring, and the address
655  *      of the SW ring.
656  */
657 static void *alloc_ring(struct device *dev, size_t nelem, size_t elem_size,
658                         size_t sw_size, dma_addr_t *phys, void *metadata,
659                         size_t stat_size, int node)
660 {
661         size_t len = nelem * elem_size + stat_size;
662         void *s = NULL;
663         void *p = dma_alloc_coherent(dev, len, phys, GFP_KERNEL);
664
665         if (!p)
666                 return NULL;
667         if (sw_size) {
668                 s = kcalloc_node(sw_size, nelem, GFP_KERNEL, node);
669
670                 if (!s) {
671                         dma_free_coherent(dev, len, p, *phys);
672                         return NULL;
673                 }
674         }
675         if (metadata)
676                 *(void **)metadata = s;
677         return p;
678 }
679
680 /**
681  *      sgl_len - calculates the size of an SGL of the given capacity
682  *      @n: the number of SGL entries
683  *
684  *      Calculates the number of flits needed for a scatter/gather list that
685  *      can hold the given number of entries.
686  */
687 static inline unsigned int sgl_len(unsigned int n)
688 {
689         /* A Direct Scatter Gather List uses 32-bit lengths and 64-bit PCI DMA
690          * addresses.  The DSGL Work Request starts off with a 32-bit DSGL
691          * ULPTX header, then Length0, then Address0, then, for 1 <= i <= N,
692          * repeated sequences of { Length[i], Length[i+1], Address[i],
693          * Address[i+1] } (this ensures that all addresses are on 64-bit
694          * boundaries).  If N is even, then Length[N+1] should be set to 0 and
695          * Address[N+1] is omitted.
696          *
697          * The following calculation incorporates all of the above.  It's
698          * somewhat hard to follow but, briefly: the "+2" accounts for the
699          * first two flits which include the DSGL header, Length0 and
700          * Address0; the "(3*(n-1))/2" covers the main body of list entries (3
701          * flits for every pair of the remaining N) +1 if (n-1) is odd; and
702          * finally the "+((n-1)&1)" adds the one remaining flit needed if
703          * (n-1) is odd ...
704          */
705         n--;
706         return (3 * n) / 2 + (n & 1) + 2;
707 }
708
709 /**
710  *      flits_to_desc - returns the num of Tx descriptors for the given flits
711  *      @n: the number of flits
712  *
713  *      Returns the number of Tx descriptors needed for the supplied number
714  *      of flits.
715  */
716 static inline unsigned int flits_to_desc(unsigned int n)
717 {
718         BUG_ON(n > SGE_MAX_WR_LEN / 8);
719         return DIV_ROUND_UP(n, 8);
720 }
721
722 /**
723  *      is_eth_imm - can an Ethernet packet be sent as immediate data?
724  *      @skb: the packet
725  *      @chip_ver: chip version
726  *
727  *      Returns whether an Ethernet packet is small enough to fit as
728  *      immediate data. Return value corresponds to headroom required.
729  */
730 static inline int is_eth_imm(const struct sk_buff *skb, unsigned int chip_ver)
731 {
732         int hdrlen = 0;
733
734         if (skb->encapsulation && skb_shinfo(skb)->gso_size &&
735             chip_ver > CHELSIO_T5) {
736                 hdrlen = sizeof(struct cpl_tx_tnl_lso);
737                 hdrlen += sizeof(struct cpl_tx_pkt_core);
738         } else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) {
739                 return 0;
740         } else {
741                 hdrlen = skb_shinfo(skb)->gso_size ?
742                          sizeof(struct cpl_tx_pkt_lso_core) : 0;
743                 hdrlen += sizeof(struct cpl_tx_pkt);
744         }
745         if (skb->len <= MAX_IMM_TX_PKT_LEN - hdrlen)
746                 return hdrlen;
747         return 0;
748 }
749
750 /**
751  *      calc_tx_flits - calculate the number of flits for a packet Tx WR
752  *      @skb: the packet
753  *      @chip_ver: chip version
754  *
755  *      Returns the number of flits needed for a Tx WR for the given Ethernet
756  *      packet, including the needed WR and CPL headers.
757  */
758 static inline unsigned int calc_tx_flits(const struct sk_buff *skb,
759                                          unsigned int chip_ver)
760 {
761         unsigned int flits;
762         int hdrlen = is_eth_imm(skb, chip_ver);
763
764         /* If the skb is small enough, we can pump it out as a work request
765          * with only immediate data.  In that case we just have to have the
766          * TX Packet header plus the skb data in the Work Request.
767          */
768
769         if (hdrlen)
770                 return DIV_ROUND_UP(skb->len + hdrlen, sizeof(__be64));
771
772         /* Otherwise, we're going to have to construct a Scatter gather list
773          * of the skb body and fragments.  We also include the flits necessary
774          * for the TX Packet Work Request and CPL.  We always have a firmware
775          * Write Header (incorporated as part of the cpl_tx_pkt_lso and
776          * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
777          * message or, if we're doing a Large Send Offload, an LSO CPL message
778          * with an embedded TX Packet Write CPL message.
779          */
780         flits = sgl_len(skb_shinfo(skb)->nr_frags + 1);
781         if (skb_shinfo(skb)->gso_size) {
782                 if (skb->encapsulation && chip_ver > CHELSIO_T5) {
783                         hdrlen = sizeof(struct fw_eth_tx_pkt_wr) +
784                                  sizeof(struct cpl_tx_tnl_lso);
785                 } else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) {
786                         u32 pkt_hdrlen;
787
788                         pkt_hdrlen = eth_get_headlen(skb->dev, skb->data,
789                                                      skb_headlen(skb));
790                         hdrlen = sizeof(struct fw_eth_tx_eo_wr) +
791                                  round_up(pkt_hdrlen, 16);
792                 } else {
793                         hdrlen = sizeof(struct fw_eth_tx_pkt_wr) +
794                                  sizeof(struct cpl_tx_pkt_lso_core);
795                 }
796
797                 hdrlen += sizeof(struct cpl_tx_pkt_core);
798                 flits += (hdrlen / sizeof(__be64));
799         } else {
800                 flits += (sizeof(struct fw_eth_tx_pkt_wr) +
801                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
802         }
803         return flits;
804 }
805
806 /**
807  *      calc_tx_descs - calculate the number of Tx descriptors for a packet
808  *      @skb: the packet
809  *      @chip_ver: chip version
810  *
811  *      Returns the number of Tx descriptors needed for the given Ethernet
812  *      packet, including the needed WR and CPL headers.
813  */
814 static inline unsigned int calc_tx_descs(const struct sk_buff *skb,
815                                          unsigned int chip_ver)
816 {
817         return flits_to_desc(calc_tx_flits(skb, chip_ver));
818 }
819
820 /**
821  *      cxgb4_write_sgl - populate a scatter/gather list for a packet
822  *      @skb: the packet
823  *      @q: the Tx queue we are writing into
824  *      @sgl: starting location for writing the SGL
825  *      @end: points right after the end of the SGL
826  *      @start: start offset into skb main-body data to include in the SGL
827  *      @addr: the list of bus addresses for the SGL elements
828  *
829  *      Generates a gather list for the buffers that make up a packet.
830  *      The caller must provide adequate space for the SGL that will be written.
831  *      The SGL includes all of the packet's page fragments and the data in its
832  *      main body except for the first @start bytes.  @sgl must be 16-byte
833  *      aligned and within a Tx descriptor with available space.  @end points
834  *      right after the end of the SGL but does not account for any potential
835  *      wrap around, i.e., @end > @sgl.
836  */
837 void cxgb4_write_sgl(const struct sk_buff *skb, struct sge_txq *q,
838                      struct ulptx_sgl *sgl, u64 *end, unsigned int start,
839                      const dma_addr_t *addr)
840 {
841         unsigned int i, len;
842         struct ulptx_sge_pair *to;
843         const struct skb_shared_info *si = skb_shinfo(skb);
844         unsigned int nfrags = si->nr_frags;
845         struct ulptx_sge_pair buf[MAX_SKB_FRAGS / 2 + 1];
846
847         len = skb_headlen(skb) - start;
848         if (likely(len)) {
849                 sgl->len0 = htonl(len);
850                 sgl->addr0 = cpu_to_be64(addr[0] + start);
851                 nfrags++;
852         } else {
853                 sgl->len0 = htonl(skb_frag_size(&si->frags[0]));
854                 sgl->addr0 = cpu_to_be64(addr[1]);
855         }
856
857         sgl->cmd_nsge = htonl(ULPTX_CMD_V(ULP_TX_SC_DSGL) |
858                               ULPTX_NSGE_V(nfrags));
859         if (likely(--nfrags == 0))
860                 return;
861         /*
862          * Most of the complexity below deals with the possibility we hit the
863          * end of the queue in the middle of writing the SGL.  For this case
864          * only we create the SGL in a temporary buffer and then copy it.
865          */
866         to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
867
868         for (i = (nfrags != si->nr_frags); nfrags >= 2; nfrags -= 2, to++) {
869                 to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
870                 to->len[1] = cpu_to_be32(skb_frag_size(&si->frags[++i]));
871                 to->addr[0] = cpu_to_be64(addr[i]);
872                 to->addr[1] = cpu_to_be64(addr[++i]);
873         }
874         if (nfrags) {
875                 to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
876                 to->len[1] = cpu_to_be32(0);
877                 to->addr[0] = cpu_to_be64(addr[i + 1]);
878         }
879         if (unlikely((u8 *)end > (u8 *)q->stat)) {
880                 unsigned int part0 = (u8 *)q->stat - (u8 *)sgl->sge, part1;
881
882                 if (likely(part0))
883                         memcpy(sgl->sge, buf, part0);
884                 part1 = (u8 *)end - (u8 *)q->stat;
885                 memcpy(q->desc, (u8 *)buf + part0, part1);
886                 end = (void *)q->desc + part1;
887         }
888         if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
889                 *end = 0;
890 }
891 EXPORT_SYMBOL(cxgb4_write_sgl);
892
893 /* This function copies 64 byte coalesced work request to
894  * memory mapped BAR2 space. For coalesced WR SGE fetches
895  * data from the FIFO instead of from Host.
896  */
897 static void cxgb_pio_copy(u64 __iomem *dst, u64 *src)
898 {
899         int count = 8;
900
901         while (count) {
902                 writeq(*src, dst);
903                 src++;
904                 dst++;
905                 count--;
906         }
907 }
908
909 /**
910  *      cxgb4_ring_tx_db - check and potentially ring a Tx queue's doorbell
911  *      @adap: the adapter
912  *      @q: the Tx queue
913  *      @n: number of new descriptors to give to HW
914  *
915  *      Ring the doorbel for a Tx queue.
916  */
917 inline void cxgb4_ring_tx_db(struct adapter *adap, struct sge_txq *q, int n)
918 {
919         /* Make sure that all writes to the TX Descriptors are committed
920          * before we tell the hardware about them.
921          */
922         wmb();
923
924         /* If we don't have access to the new User Doorbell (T5+), use the old
925          * doorbell mechanism; otherwise use the new BAR2 mechanism.
926          */
927         if (unlikely(q->bar2_addr == NULL)) {
928                 u32 val = PIDX_V(n);
929                 unsigned long flags;
930
931                 /* For T4 we need to participate in the Doorbell Recovery
932                  * mechanism.
933                  */
934                 spin_lock_irqsave(&q->db_lock, flags);
935                 if (!q->db_disabled)
936                         t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
937                                      QID_V(q->cntxt_id) | val);
938                 else
939                         q->db_pidx_inc += n;
940                 q->db_pidx = q->pidx;
941                 spin_unlock_irqrestore(&q->db_lock, flags);
942         } else {
943                 u32 val = PIDX_T5_V(n);
944
945                 /* T4 and later chips share the same PIDX field offset within
946                  * the doorbell, but T5 and later shrank the field in order to
947                  * gain a bit for Doorbell Priority.  The field was absurdly
948                  * large in the first place (14 bits) so we just use the T5
949                  * and later limits and warn if a Queue ID is too large.
950                  */
951                 WARN_ON(val & DBPRIO_F);
952
953                 /* If we're only writing a single TX Descriptor and we can use
954                  * Inferred QID registers, we can use the Write Combining
955                  * Gather Buffer; otherwise we use the simple doorbell.
956                  */
957                 if (n == 1 && q->bar2_qid == 0) {
958                         int index = (q->pidx
959                                      ? (q->pidx - 1)
960                                      : (q->size - 1));
961                         u64 *wr = (u64 *)&q->desc[index];
962
963                         cxgb_pio_copy((u64 __iomem *)
964                                       (q->bar2_addr + SGE_UDB_WCDOORBELL),
965                                       wr);
966                 } else {
967                         writel(val | QID_V(q->bar2_qid),
968                                q->bar2_addr + SGE_UDB_KDOORBELL);
969                 }
970
971                 /* This Write Memory Barrier will force the write to the User
972                  * Doorbell area to be flushed.  This is needed to prevent
973                  * writes on different CPUs for the same queue from hitting
974                  * the adapter out of order.  This is required when some Work
975                  * Requests take the Write Combine Gather Buffer path (user
976                  * doorbell area offset [SGE_UDB_WCDOORBELL..+63]) and some
977                  * take the traditional path where we simply increment the
978                  * PIDX (User Doorbell area SGE_UDB_KDOORBELL) and have the
979                  * hardware DMA read the actual Work Request.
980                  */
981                 wmb();
982         }
983 }
984 EXPORT_SYMBOL(cxgb4_ring_tx_db);
985
986 /**
987  *      cxgb4_inline_tx_skb - inline a packet's data into Tx descriptors
988  *      @skb: the packet
989  *      @q: the Tx queue where the packet will be inlined
990  *      @pos: starting position in the Tx queue where to inline the packet
991  *
992  *      Inline a packet's contents directly into Tx descriptors, starting at
993  *      the given position within the Tx DMA ring.
994  *      Most of the complexity of this operation is dealing with wrap arounds
995  *      in the middle of the packet we want to inline.
996  */
997 void cxgb4_inline_tx_skb(const struct sk_buff *skb,
998                          const struct sge_txq *q, void *pos)
999 {
1000         int left = (void *)q->stat - pos;
1001         u64 *p;
1002
1003         if (likely(skb->len <= left)) {
1004                 if (likely(!skb->data_len))
1005                         skb_copy_from_linear_data(skb, pos, skb->len);
1006                 else
1007                         skb_copy_bits(skb, 0, pos, skb->len);
1008                 pos += skb->len;
1009         } else {
1010                 skb_copy_bits(skb, 0, pos, left);
1011                 skb_copy_bits(skb, left, q->desc, skb->len - left);
1012                 pos = (void *)q->desc + (skb->len - left);
1013         }
1014
1015         /* 0-pad to multiple of 16 */
1016         p = PTR_ALIGN(pos, 8);
1017         if ((uintptr_t)p & 8)
1018                 *p = 0;
1019 }
1020 EXPORT_SYMBOL(cxgb4_inline_tx_skb);
1021
1022 static void *inline_tx_skb_header(const struct sk_buff *skb,
1023                                   const struct sge_txq *q,  void *pos,
1024                                   int length)
1025 {
1026         u64 *p;
1027         int left = (void *)q->stat - pos;
1028
1029         if (likely(length <= left)) {
1030                 memcpy(pos, skb->data, length);
1031                 pos += length;
1032         } else {
1033                 memcpy(pos, skb->data, left);
1034                 memcpy(q->desc, skb->data + left, length - left);
1035                 pos = (void *)q->desc + (length - left);
1036         }
1037         /* 0-pad to multiple of 16 */
1038         p = PTR_ALIGN(pos, 8);
1039         if ((uintptr_t)p & 8) {
1040                 *p = 0;
1041                 return p + 1;
1042         }
1043         return p;
1044 }
1045
1046 /*
1047  * Figure out what HW csum a packet wants and return the appropriate control
1048  * bits.
1049  */
1050 static u64 hwcsum(enum chip_type chip, const struct sk_buff *skb)
1051 {
1052         int csum_type;
1053         bool inner_hdr_csum = false;
1054         u16 proto, ver;
1055
1056         if (skb->encapsulation &&
1057             (CHELSIO_CHIP_VERSION(chip) > CHELSIO_T5))
1058                 inner_hdr_csum = true;
1059
1060         if (inner_hdr_csum) {
1061                 ver = inner_ip_hdr(skb)->version;
1062                 proto = (ver == 4) ? inner_ip_hdr(skb)->protocol :
1063                         inner_ipv6_hdr(skb)->nexthdr;
1064         } else {
1065                 ver = ip_hdr(skb)->version;
1066                 proto = (ver == 4) ? ip_hdr(skb)->protocol :
1067                         ipv6_hdr(skb)->nexthdr;
1068         }
1069
1070         if (ver == 4) {
1071                 if (proto == IPPROTO_TCP)
1072                         csum_type = TX_CSUM_TCPIP;
1073                 else if (proto == IPPROTO_UDP)
1074                         csum_type = TX_CSUM_UDPIP;
1075                 else {
1076 nocsum:                 /*
1077                          * unknown protocol, disable HW csum
1078                          * and hope a bad packet is detected
1079                          */
1080                         return TXPKT_L4CSUM_DIS_F;
1081                 }
1082         } else {
1083                 /*
1084                  * this doesn't work with extension headers
1085                  */
1086                 if (proto == IPPROTO_TCP)
1087                         csum_type = TX_CSUM_TCPIP6;
1088                 else if (proto == IPPROTO_UDP)
1089                         csum_type = TX_CSUM_UDPIP6;
1090                 else
1091                         goto nocsum;
1092         }
1093
1094         if (likely(csum_type >= TX_CSUM_TCPIP)) {
1095                 int eth_hdr_len, l4_len;
1096                 u64 hdr_len;
1097
1098                 if (inner_hdr_csum) {
1099                         /* This allows checksum offload for all encapsulated
1100                          * packets like GRE etc..
1101                          */
1102                         l4_len = skb_inner_network_header_len(skb);
1103                         eth_hdr_len = skb_inner_network_offset(skb) - ETH_HLEN;
1104                 } else {
1105                         l4_len = skb_network_header_len(skb);
1106                         eth_hdr_len = skb_network_offset(skb) - ETH_HLEN;
1107                 }
1108                 hdr_len = TXPKT_IPHDR_LEN_V(l4_len);
1109
1110                 if (CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5)
1111                         hdr_len |= TXPKT_ETHHDR_LEN_V(eth_hdr_len);
1112                 else
1113                         hdr_len |= T6_TXPKT_ETHHDR_LEN_V(eth_hdr_len);
1114                 return TXPKT_CSUM_TYPE_V(csum_type) | hdr_len;
1115         } else {
1116                 int start = skb_transport_offset(skb);
1117
1118                 return TXPKT_CSUM_TYPE_V(csum_type) |
1119                         TXPKT_CSUM_START_V(start) |
1120                         TXPKT_CSUM_LOC_V(start + skb->csum_offset);
1121         }
1122 }
1123
1124 static void eth_txq_stop(struct sge_eth_txq *q)
1125 {
1126         netif_tx_stop_queue(q->txq);
1127         q->q.stops++;
1128 }
1129
1130 static inline void txq_advance(struct sge_txq *q, unsigned int n)
1131 {
1132         q->in_use += n;
1133         q->pidx += n;
1134         if (q->pidx >= q->size)
1135                 q->pidx -= q->size;
1136 }
1137
1138 #ifdef CONFIG_CHELSIO_T4_FCOE
1139 static inline int
1140 cxgb_fcoe_offload(struct sk_buff *skb, struct adapter *adap,
1141                   const struct port_info *pi, u64 *cntrl)
1142 {
1143         const struct cxgb_fcoe *fcoe = &pi->fcoe;
1144
1145         if (!(fcoe->flags & CXGB_FCOE_ENABLED))
1146                 return 0;
1147
1148         if (skb->protocol != htons(ETH_P_FCOE))
1149                 return 0;
1150
1151         skb_reset_mac_header(skb);
1152         skb->mac_len = sizeof(struct ethhdr);
1153
1154         skb_set_network_header(skb, skb->mac_len);
1155         skb_set_transport_header(skb, skb->mac_len + sizeof(struct fcoe_hdr));
1156
1157         if (!cxgb_fcoe_sof_eof_supported(adap, skb))
1158                 return -ENOTSUPP;
1159
1160         /* FC CRC offload */
1161         *cntrl = TXPKT_CSUM_TYPE_V(TX_CSUM_FCOE) |
1162                      TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F |
1163                      TXPKT_CSUM_START_V(CXGB_FCOE_TXPKT_CSUM_START) |
1164                      TXPKT_CSUM_END_V(CXGB_FCOE_TXPKT_CSUM_END) |
1165                      TXPKT_CSUM_LOC_V(CXGB_FCOE_TXPKT_CSUM_END);
1166         return 0;
1167 }
1168 #endif /* CONFIG_CHELSIO_T4_FCOE */
1169
1170 /* Returns tunnel type if hardware supports offloading of the same.
1171  * It is called only for T5 and onwards.
1172  */
1173 enum cpl_tx_tnl_lso_type cxgb_encap_offload_supported(struct sk_buff *skb)
1174 {
1175         u8 l4_hdr = 0;
1176         enum cpl_tx_tnl_lso_type tnl_type = TX_TNL_TYPE_OPAQUE;
1177         struct port_info *pi = netdev_priv(skb->dev);
1178         struct adapter *adapter = pi->adapter;
1179
1180         if (skb->inner_protocol_type != ENCAP_TYPE_ETHER ||
1181             skb->inner_protocol != htons(ETH_P_TEB))
1182                 return tnl_type;
1183
1184         switch (vlan_get_protocol(skb)) {
1185         case htons(ETH_P_IP):
1186                 l4_hdr = ip_hdr(skb)->protocol;
1187                 break;
1188         case htons(ETH_P_IPV6):
1189                 l4_hdr = ipv6_hdr(skb)->nexthdr;
1190                 break;
1191         default:
1192                 return tnl_type;
1193         }
1194
1195         switch (l4_hdr) {
1196         case IPPROTO_UDP:
1197                 if (adapter->vxlan_port == udp_hdr(skb)->dest)
1198                         tnl_type = TX_TNL_TYPE_VXLAN;
1199                 else if (adapter->geneve_port == udp_hdr(skb)->dest)
1200                         tnl_type = TX_TNL_TYPE_GENEVE;
1201                 break;
1202         default:
1203                 return tnl_type;
1204         }
1205
1206         return tnl_type;
1207 }
1208
1209 static inline void t6_fill_tnl_lso(struct sk_buff *skb,
1210                                    struct cpl_tx_tnl_lso *tnl_lso,
1211                                    enum cpl_tx_tnl_lso_type tnl_type)
1212 {
1213         u32 val;
1214         int in_eth_xtra_len;
1215         int l3hdr_len = skb_network_header_len(skb);
1216         int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1217         const struct skb_shared_info *ssi = skb_shinfo(skb);
1218         bool v6 = (ip_hdr(skb)->version == 6);
1219
1220         val = CPL_TX_TNL_LSO_OPCODE_V(CPL_TX_TNL_LSO) |
1221               CPL_TX_TNL_LSO_FIRST_F |
1222               CPL_TX_TNL_LSO_LAST_F |
1223               (v6 ? CPL_TX_TNL_LSO_IPV6OUT_F : 0) |
1224               CPL_TX_TNL_LSO_ETHHDRLENOUT_V(eth_xtra_len / 4) |
1225               CPL_TX_TNL_LSO_IPHDRLENOUT_V(l3hdr_len / 4) |
1226               (v6 ? 0 : CPL_TX_TNL_LSO_IPHDRCHKOUT_F) |
1227               CPL_TX_TNL_LSO_IPLENSETOUT_F |
1228               (v6 ? 0 : CPL_TX_TNL_LSO_IPIDINCOUT_F);
1229         tnl_lso->op_to_IpIdSplitOut = htonl(val);
1230
1231         tnl_lso->IpIdOffsetOut = 0;
1232
1233         /* Get the tunnel header length */
1234         val = skb_inner_mac_header(skb) - skb_mac_header(skb);
1235         in_eth_xtra_len = skb_inner_network_header(skb) -
1236                           skb_inner_mac_header(skb) - ETH_HLEN;
1237
1238         switch (tnl_type) {
1239         case TX_TNL_TYPE_VXLAN:
1240         case TX_TNL_TYPE_GENEVE:
1241                 tnl_lso->UdpLenSetOut_to_TnlHdrLen =
1242                         htons(CPL_TX_TNL_LSO_UDPCHKCLROUT_F |
1243                         CPL_TX_TNL_LSO_UDPLENSETOUT_F);
1244                 break;
1245         default:
1246                 tnl_lso->UdpLenSetOut_to_TnlHdrLen = 0;
1247                 break;
1248         }
1249
1250         tnl_lso->UdpLenSetOut_to_TnlHdrLen |=
1251                  htons(CPL_TX_TNL_LSO_TNLHDRLEN_V(val) |
1252                        CPL_TX_TNL_LSO_TNLTYPE_V(tnl_type));
1253
1254         tnl_lso->r1 = 0;
1255
1256         val = CPL_TX_TNL_LSO_ETHHDRLEN_V(in_eth_xtra_len / 4) |
1257               CPL_TX_TNL_LSO_IPV6_V(inner_ip_hdr(skb)->version == 6) |
1258               CPL_TX_TNL_LSO_IPHDRLEN_V(skb_inner_network_header_len(skb) / 4) |
1259               CPL_TX_TNL_LSO_TCPHDRLEN_V(inner_tcp_hdrlen(skb) / 4);
1260         tnl_lso->Flow_to_TcpHdrLen = htonl(val);
1261
1262         tnl_lso->IpIdOffset = htons(0);
1263
1264         tnl_lso->IpIdSplit_to_Mss = htons(CPL_TX_TNL_LSO_MSS_V(ssi->gso_size));
1265         tnl_lso->TCPSeqOffset = htonl(0);
1266         tnl_lso->EthLenOffset_Size = htonl(CPL_TX_TNL_LSO_SIZE_V(skb->len));
1267 }
1268
1269 static inline void *write_tso_wr(struct adapter *adap, struct sk_buff *skb,
1270                                  struct cpl_tx_pkt_lso_core *lso)
1271 {
1272         int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1273         int l3hdr_len = skb_network_header_len(skb);
1274         const struct skb_shared_info *ssi;
1275         bool ipv6 = false;
1276
1277         ssi = skb_shinfo(skb);
1278         if (ssi->gso_type & SKB_GSO_TCPV6)
1279                 ipv6 = true;
1280
1281         lso->lso_ctrl = htonl(LSO_OPCODE_V(CPL_TX_PKT_LSO) |
1282                               LSO_FIRST_SLICE_F | LSO_LAST_SLICE_F |
1283                               LSO_IPV6_V(ipv6) |
1284                               LSO_ETHHDR_LEN_V(eth_xtra_len / 4) |
1285                               LSO_IPHDR_LEN_V(l3hdr_len / 4) |
1286                               LSO_TCPHDR_LEN_V(tcp_hdr(skb)->doff));
1287         lso->ipid_ofst = htons(0);
1288         lso->mss = htons(ssi->gso_size);
1289         lso->seqno_offset = htonl(0);
1290         if (is_t4(adap->params.chip))
1291                 lso->len = htonl(skb->len);
1292         else
1293                 lso->len = htonl(LSO_T5_XFER_SIZE_V(skb->len));
1294
1295         return (void *)(lso + 1);
1296 }
1297
1298 /**
1299  *      t4_sge_eth_txq_egress_update - handle Ethernet TX Queue update
1300  *      @adap: the adapter
1301  *      @eq: the Ethernet TX Queue
1302  *      @maxreclaim: the maximum number of TX Descriptors to reclaim or -1
1303  *
1304  *      We're typically called here to update the state of an Ethernet TX
1305  *      Queue with respect to the hardware's progress in consuming the TX
1306  *      Work Requests that we've put on that Egress Queue.  This happens
1307  *      when we get Egress Queue Update messages and also prophylactically
1308  *      in regular timer-based Ethernet TX Queue maintenance.
1309  */
1310 int t4_sge_eth_txq_egress_update(struct adapter *adap, struct sge_eth_txq *eq,
1311                                  int maxreclaim)
1312 {
1313         unsigned int reclaimed, hw_cidx;
1314         struct sge_txq *q = &eq->q;
1315         int hw_in_use;
1316
1317         if (!q->in_use || !__netif_tx_trylock(eq->txq))
1318                 return 0;
1319
1320         /* Reclaim pending completed TX Descriptors. */
1321         reclaimed = reclaim_completed_tx(adap, &eq->q, maxreclaim, true);
1322
1323         hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
1324         hw_in_use = q->pidx - hw_cidx;
1325         if (hw_in_use < 0)
1326                 hw_in_use += q->size;
1327
1328         /* If the TX Queue is currently stopped and there's now more than half
1329          * the queue available, restart it.  Otherwise bail out since the rest
1330          * of what we want do here is with the possibility of shipping any
1331          * currently buffered Coalesced TX Work Request.
1332          */
1333         if (netif_tx_queue_stopped(eq->txq) && hw_in_use < (q->size / 2)) {
1334                 netif_tx_wake_queue(eq->txq);
1335                 eq->q.restarts++;
1336         }
1337
1338         __netif_tx_unlock(eq->txq);
1339         return reclaimed;
1340 }
1341
1342 static inline int cxgb4_validate_skb(struct sk_buff *skb,
1343                                      struct net_device *dev,
1344                                      u32 min_pkt_len)
1345 {
1346         u32 max_pkt_len;
1347
1348         /* The chip min packet length is 10 octets but some firmware
1349          * commands have a minimum packet length requirement. So, play
1350          * safe and reject anything shorter than @min_pkt_len.
1351          */
1352         if (unlikely(skb->len < min_pkt_len))
1353                 return -EINVAL;
1354
1355         /* Discard the packet if the length is greater than mtu */
1356         max_pkt_len = ETH_HLEN + dev->mtu;
1357
1358         if (skb_vlan_tagged(skb))
1359                 max_pkt_len += VLAN_HLEN;
1360
1361         if (!skb_shinfo(skb)->gso_size && (unlikely(skb->len > max_pkt_len)))
1362                 return -EINVAL;
1363
1364         return 0;
1365 }
1366
1367 static void *write_eo_udp_wr(struct sk_buff *skb, struct fw_eth_tx_eo_wr *wr,
1368                              u32 hdr_len)
1369 {
1370         wr->u.udpseg.type = FW_ETH_TX_EO_TYPE_UDPSEG;
1371         wr->u.udpseg.ethlen = skb_network_offset(skb);
1372         wr->u.udpseg.iplen = cpu_to_be16(skb_network_header_len(skb));
1373         wr->u.udpseg.udplen = sizeof(struct udphdr);
1374         wr->u.udpseg.rtplen = 0;
1375         wr->u.udpseg.r4 = 0;
1376         if (skb_shinfo(skb)->gso_size)
1377                 wr->u.udpseg.mss = cpu_to_be16(skb_shinfo(skb)->gso_size);
1378         else
1379                 wr->u.udpseg.mss = cpu_to_be16(skb->len - hdr_len);
1380         wr->u.udpseg.schedpktsize = wr->u.udpseg.mss;
1381         wr->u.udpseg.plen = cpu_to_be32(skb->len - hdr_len);
1382
1383         return (void *)(wr + 1);
1384 }
1385
1386 /**
1387  *      cxgb4_eth_xmit - add a packet to an Ethernet Tx queue
1388  *      @skb: the packet
1389  *      @dev: the egress net device
1390  *
1391  *      Add a packet to an SGE Ethernet Tx queue.  Runs with softirqs disabled.
1392  */
1393 static netdev_tx_t cxgb4_eth_xmit(struct sk_buff *skb, struct net_device *dev)
1394 {
1395         enum cpl_tx_tnl_lso_type tnl_type = TX_TNL_TYPE_OPAQUE;
1396         bool ptp_enabled = is_ptp_enabled(skb, dev);
1397         unsigned int last_desc, flits, ndesc;
1398         u32 wr_mid, ctrl0, op, sgl_off = 0;
1399         const struct skb_shared_info *ssi;
1400         int len, qidx, credits, ret, left;
1401         struct tx_sw_desc *sgl_sdesc;
1402         struct fw_eth_tx_eo_wr *eowr;
1403         struct fw_eth_tx_pkt_wr *wr;
1404         struct cpl_tx_pkt_core *cpl;
1405         const struct port_info *pi;
1406         bool immediate = false;
1407         u64 cntrl, *end, *sgl;
1408         struct sge_eth_txq *q;
1409         unsigned int chip_ver;
1410         struct adapter *adap;
1411
1412         ret = cxgb4_validate_skb(skb, dev, ETH_HLEN);
1413         if (ret)
1414                 goto out_free;
1415
1416         pi = netdev_priv(dev);
1417         adap = pi->adapter;
1418         ssi = skb_shinfo(skb);
1419 #ifdef CONFIG_CHELSIO_IPSEC_INLINE
1420         if (xfrm_offload(skb) && !ssi->gso_size)
1421                 return adap->uld[CXGB4_ULD_CRYPTO].tx_handler(skb, dev);
1422 #endif /* CHELSIO_IPSEC_INLINE */
1423
1424 #ifdef CONFIG_CHELSIO_TLS_DEVICE
1425         if (skb->decrypted)
1426                 return adap->uld[CXGB4_ULD_CRYPTO].tx_handler(skb, dev);
1427 #endif /* CHELSIO_TLS_DEVICE */
1428
1429         qidx = skb_get_queue_mapping(skb);
1430         if (ptp_enabled) {
1431                 if (!(adap->ptp_tx_skb)) {
1432                         skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
1433                         adap->ptp_tx_skb = skb_get(skb);
1434                 } else {
1435                         goto out_free;
1436                 }
1437                 q = &adap->sge.ptptxq;
1438         } else {
1439                 q = &adap->sge.ethtxq[qidx + pi->first_qset];
1440         }
1441         skb_tx_timestamp(skb);
1442
1443         reclaim_completed_tx(adap, &q->q, -1, true);
1444         cntrl = TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F;
1445
1446 #ifdef CONFIG_CHELSIO_T4_FCOE
1447         ret = cxgb_fcoe_offload(skb, adap, pi, &cntrl);
1448         if (unlikely(ret == -EOPNOTSUPP))
1449                 goto out_free;
1450 #endif /* CONFIG_CHELSIO_T4_FCOE */
1451
1452         chip_ver = CHELSIO_CHIP_VERSION(adap->params.chip);
1453         flits = calc_tx_flits(skb, chip_ver);
1454         ndesc = flits_to_desc(flits);
1455         credits = txq_avail(&q->q) - ndesc;
1456
1457         if (unlikely(credits < 0)) {
1458                 eth_txq_stop(q);
1459                 dev_err(adap->pdev_dev,
1460                         "%s: Tx ring %u full while queue awake!\n",
1461                         dev->name, qidx);
1462                 return NETDEV_TX_BUSY;
1463         }
1464
1465         if (is_eth_imm(skb, chip_ver))
1466                 immediate = true;
1467
1468         if (skb->encapsulation && chip_ver > CHELSIO_T5)
1469                 tnl_type = cxgb_encap_offload_supported(skb);
1470
1471         last_desc = q->q.pidx + ndesc - 1;
1472         if (last_desc >= q->q.size)
1473                 last_desc -= q->q.size;
1474         sgl_sdesc = &q->q.sdesc[last_desc];
1475
1476         if (!immediate &&
1477             unlikely(cxgb4_map_skb(adap->pdev_dev, skb, sgl_sdesc->addr) < 0)) {
1478                 memset(sgl_sdesc->addr, 0, sizeof(sgl_sdesc->addr));
1479                 q->mapping_err++;
1480                 goto out_free;
1481         }
1482
1483         wr_mid = FW_WR_LEN16_V(DIV_ROUND_UP(flits, 2));
1484         if (unlikely(credits < ETHTXQ_STOP_THRES)) {
1485                 /* After we're done injecting the Work Request for this
1486                  * packet, we'll be below our "stop threshold" so stop the TX
1487                  * Queue now and schedule a request for an SGE Egress Queue
1488                  * Update message. The queue will get started later on when
1489                  * the firmware processes this Work Request and sends us an
1490                  * Egress Queue Status Update message indicating that space
1491                  * has opened up.
1492                  */
1493                 eth_txq_stop(q);
1494                 wr_mid |= FW_WR_EQUEQ_F | FW_WR_EQUIQ_F;
1495         }
1496
1497         wr = (void *)&q->q.desc[q->q.pidx];
1498         eowr = (void *)&q->q.desc[q->q.pidx];
1499         wr->equiq_to_len16 = htonl(wr_mid);
1500         wr->r3 = cpu_to_be64(0);
1501         if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4)
1502                 end = (u64 *)eowr + flits;
1503         else
1504                 end = (u64 *)wr + flits;
1505
1506         len = immediate ? skb->len : 0;
1507         len += sizeof(*cpl);
1508         if (ssi->gso_size && !(ssi->gso_type & SKB_GSO_UDP_L4)) {
1509                 struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
1510                 struct cpl_tx_tnl_lso *tnl_lso = (void *)(wr + 1);
1511
1512                 if (tnl_type)
1513                         len += sizeof(*tnl_lso);
1514                 else
1515                         len += sizeof(*lso);
1516
1517                 wr->op_immdlen = htonl(FW_WR_OP_V(FW_ETH_TX_PKT_WR) |
1518                                        FW_WR_IMMDLEN_V(len));
1519                 if (tnl_type) {
1520                         struct iphdr *iph = ip_hdr(skb);
1521
1522                         t6_fill_tnl_lso(skb, tnl_lso, tnl_type);
1523                         cpl = (void *)(tnl_lso + 1);
1524                         /* Driver is expected to compute partial checksum that
1525                          * does not include the IP Total Length.
1526                          */
1527                         if (iph->version == 4) {
1528                                 iph->check = 0;
1529                                 iph->tot_len = 0;
1530                                 iph->check = ~ip_fast_csum((u8 *)iph, iph->ihl);
1531                         }
1532                         if (skb->ip_summed == CHECKSUM_PARTIAL)
1533                                 cntrl = hwcsum(adap->params.chip, skb);
1534                 } else {
1535                         cpl = write_tso_wr(adap, skb, lso);
1536                         cntrl = hwcsum(adap->params.chip, skb);
1537                 }
1538                 sgl = (u64 *)(cpl + 1); /* sgl start here */
1539                 q->tso++;
1540                 q->tx_cso += ssi->gso_segs;
1541         } else if (ssi->gso_size) {
1542                 u64 *start;
1543                 u32 hdrlen;
1544
1545                 hdrlen = eth_get_headlen(dev, skb->data, skb_headlen(skb));
1546                 len += hdrlen;
1547                 wr->op_immdlen = cpu_to_be32(FW_WR_OP_V(FW_ETH_TX_EO_WR) |
1548                                              FW_ETH_TX_EO_WR_IMMDLEN_V(len));
1549                 cpl = write_eo_udp_wr(skb, eowr, hdrlen);
1550                 cntrl = hwcsum(adap->params.chip, skb);
1551
1552                 start = (u64 *)(cpl + 1);
1553                 sgl = (u64 *)inline_tx_skb_header(skb, &q->q, (void *)start,
1554                                                   hdrlen);
1555                 if (unlikely(start > sgl)) {
1556                         left = (u8 *)end - (u8 *)q->q.stat;
1557                         end = (void *)q->q.desc + left;
1558                 }
1559                 sgl_off = hdrlen;
1560                 q->uso++;
1561                 q->tx_cso += ssi->gso_segs;
1562         } else {
1563                 if (ptp_enabled)
1564                         op = FW_PTP_TX_PKT_WR;
1565                 else
1566                         op = FW_ETH_TX_PKT_WR;
1567                 wr->op_immdlen = htonl(FW_WR_OP_V(op) |
1568                                        FW_WR_IMMDLEN_V(len));
1569                 cpl = (void *)(wr + 1);
1570                 sgl = (u64 *)(cpl + 1);
1571                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1572                         cntrl = hwcsum(adap->params.chip, skb) |
1573                                 TXPKT_IPCSUM_DIS_F;
1574                         q->tx_cso++;
1575                 }
1576         }
1577
1578         if (unlikely((u8 *)sgl >= (u8 *)q->q.stat)) {
1579                 /* If current position is already at the end of the
1580                  * txq, reset the current to point to start of the queue
1581                  * and update the end ptr as well.
1582                  */
1583                 left = (u8 *)end - (u8 *)q->q.stat;
1584                 end = (void *)q->q.desc + left;
1585                 sgl = (void *)q->q.desc;
1586         }
1587
1588         if (skb_vlan_tag_present(skb)) {
1589                 q->vlan_ins++;
1590                 cntrl |= TXPKT_VLAN_VLD_F | TXPKT_VLAN_V(skb_vlan_tag_get(skb));
1591 #ifdef CONFIG_CHELSIO_T4_FCOE
1592                 if (skb->protocol == htons(ETH_P_FCOE))
1593                         cntrl |= TXPKT_VLAN_V(
1594                                  ((skb->priority & 0x7) << VLAN_PRIO_SHIFT));
1595 #endif /* CONFIG_CHELSIO_T4_FCOE */
1596         }
1597
1598         ctrl0 = TXPKT_OPCODE_V(CPL_TX_PKT_XT) | TXPKT_INTF_V(pi->tx_chan) |
1599                 TXPKT_PF_V(adap->pf);
1600         if (ptp_enabled)
1601                 ctrl0 |= TXPKT_TSTAMP_F;
1602 #ifdef CONFIG_CHELSIO_T4_DCB
1603         if (is_t4(adap->params.chip))
1604                 ctrl0 |= TXPKT_OVLAN_IDX_V(q->dcb_prio);
1605         else
1606                 ctrl0 |= TXPKT_T5_OVLAN_IDX_V(q->dcb_prio);
1607 #endif
1608         cpl->ctrl0 = htonl(ctrl0);
1609         cpl->pack = htons(0);
1610         cpl->len = htons(skb->len);
1611         cpl->ctrl1 = cpu_to_be64(cntrl);
1612
1613         if (immediate) {
1614                 cxgb4_inline_tx_skb(skb, &q->q, sgl);
1615                 dev_consume_skb_any(skb);
1616         } else {
1617                 cxgb4_write_sgl(skb, &q->q, (void *)sgl, end, sgl_off,
1618                                 sgl_sdesc->addr);
1619                 skb_orphan(skb);
1620                 sgl_sdesc->skb = skb;
1621         }
1622
1623         txq_advance(&q->q, ndesc);
1624
1625         cxgb4_ring_tx_db(adap, &q->q, ndesc);
1626         return NETDEV_TX_OK;
1627
1628 out_free:
1629         dev_kfree_skb_any(skb);
1630         return NETDEV_TX_OK;
1631 }
1632
1633 /* Constants ... */
1634 enum {
1635         /* Egress Queue sizes, producer and consumer indices are all in units
1636          * of Egress Context Units bytes.  Note that as far as the hardware is
1637          * concerned, the free list is an Egress Queue (the host produces free
1638          * buffers which the hardware consumes) and free list entries are
1639          * 64-bit PCI DMA addresses.
1640          */
1641         EQ_UNIT = SGE_EQ_IDXSIZE,
1642         FL_PER_EQ_UNIT = EQ_UNIT / sizeof(__be64),
1643         TXD_PER_EQ_UNIT = EQ_UNIT / sizeof(__be64),
1644
1645         T4VF_ETHTXQ_MAX_HDR = (sizeof(struct fw_eth_tx_pkt_vm_wr) +
1646                                sizeof(struct cpl_tx_pkt_lso_core) +
1647                                sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64),
1648 };
1649
1650 /**
1651  *      t4vf_is_eth_imm - can an Ethernet packet be sent as immediate data?
1652  *      @skb: the packet
1653  *
1654  *      Returns whether an Ethernet packet is small enough to fit completely as
1655  *      immediate data.
1656  */
1657 static inline int t4vf_is_eth_imm(const struct sk_buff *skb)
1658 {
1659         /* The VF Driver uses the FW_ETH_TX_PKT_VM_WR firmware Work Request
1660          * which does not accommodate immediate data.  We could dike out all
1661          * of the support code for immediate data but that would tie our hands
1662          * too much if we ever want to enhace the firmware.  It would also
1663          * create more differences between the PF and VF Drivers.
1664          */
1665         return false;
1666 }
1667
1668 /**
1669  *      t4vf_calc_tx_flits - calculate the number of flits for a packet TX WR
1670  *      @skb: the packet
1671  *
1672  *      Returns the number of flits needed for a TX Work Request for the
1673  *      given Ethernet packet, including the needed WR and CPL headers.
1674  */
1675 static inline unsigned int t4vf_calc_tx_flits(const struct sk_buff *skb)
1676 {
1677         unsigned int flits;
1678
1679         /* If the skb is small enough, we can pump it out as a work request
1680          * with only immediate data.  In that case we just have to have the
1681          * TX Packet header plus the skb data in the Work Request.
1682          */
1683         if (t4vf_is_eth_imm(skb))
1684                 return DIV_ROUND_UP(skb->len + sizeof(struct cpl_tx_pkt),
1685                                     sizeof(__be64));
1686
1687         /* Otherwise, we're going to have to construct a Scatter gather list
1688          * of the skb body and fragments.  We also include the flits necessary
1689          * for the TX Packet Work Request and CPL.  We always have a firmware
1690          * Write Header (incorporated as part of the cpl_tx_pkt_lso and
1691          * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
1692          * message or, if we're doing a Large Send Offload, an LSO CPL message
1693          * with an embedded TX Packet Write CPL message.
1694          */
1695         flits = sgl_len(skb_shinfo(skb)->nr_frags + 1);
1696         if (skb_shinfo(skb)->gso_size)
1697                 flits += (sizeof(struct fw_eth_tx_pkt_vm_wr) +
1698                           sizeof(struct cpl_tx_pkt_lso_core) +
1699                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
1700         else
1701                 flits += (sizeof(struct fw_eth_tx_pkt_vm_wr) +
1702                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
1703         return flits;
1704 }
1705
1706 /**
1707  *      cxgb4_vf_eth_xmit - add a packet to an Ethernet TX queue
1708  *      @skb: the packet
1709  *      @dev: the egress net device
1710  *
1711  *      Add a packet to an SGE Ethernet TX queue.  Runs with softirqs disabled.
1712  */
1713 static netdev_tx_t cxgb4_vf_eth_xmit(struct sk_buff *skb,
1714                                      struct net_device *dev)
1715 {
1716         unsigned int last_desc, flits, ndesc;
1717         const struct skb_shared_info *ssi;
1718         struct fw_eth_tx_pkt_vm_wr *wr;
1719         struct tx_sw_desc *sgl_sdesc;
1720         struct cpl_tx_pkt_core *cpl;
1721         const struct port_info *pi;
1722         struct sge_eth_txq *txq;
1723         struct adapter *adapter;
1724         int qidx, credits, ret;
1725         size_t fw_hdr_copy_len;
1726         u64 cntrl, *end;
1727         u32 wr_mid;
1728
1729         /* The chip minimum packet length is 10 octets but the firmware
1730          * command that we are using requires that we copy the Ethernet header
1731          * (including the VLAN tag) into the header so we reject anything
1732          * smaller than that ...
1733          */
1734         fw_hdr_copy_len = sizeof(wr->ethmacdst) + sizeof(wr->ethmacsrc) +
1735                           sizeof(wr->ethtype) + sizeof(wr->vlantci);
1736         ret = cxgb4_validate_skb(skb, dev, fw_hdr_copy_len);
1737         if (ret)
1738                 goto out_free;
1739
1740         /* Figure out which TX Queue we're going to use. */
1741         pi = netdev_priv(dev);
1742         adapter = pi->adapter;
1743         qidx = skb_get_queue_mapping(skb);
1744         WARN_ON(qidx >= pi->nqsets);
1745         txq = &adapter->sge.ethtxq[pi->first_qset + qidx];
1746
1747         /* Take this opportunity to reclaim any TX Descriptors whose DMA
1748          * transfers have completed.
1749          */
1750         reclaim_completed_tx(adapter, &txq->q, -1, true);
1751
1752         /* Calculate the number of flits and TX Descriptors we're going to
1753          * need along with how many TX Descriptors will be left over after
1754          * we inject our Work Request.
1755          */
1756         flits = t4vf_calc_tx_flits(skb);
1757         ndesc = flits_to_desc(flits);
1758         credits = txq_avail(&txq->q) - ndesc;
1759
1760         if (unlikely(credits < 0)) {
1761                 /* Not enough room for this packet's Work Request.  Stop the
1762                  * TX Queue and return a "busy" condition.  The queue will get
1763                  * started later on when the firmware informs us that space
1764                  * has opened up.
1765                  */
1766                 eth_txq_stop(txq);
1767                 dev_err(adapter->pdev_dev,
1768                         "%s: TX ring %u full while queue awake!\n",
1769                         dev->name, qidx);
1770                 return NETDEV_TX_BUSY;
1771         }
1772
1773         last_desc = txq->q.pidx + ndesc - 1;
1774         if (last_desc >= txq->q.size)
1775                 last_desc -= txq->q.size;
1776         sgl_sdesc = &txq->q.sdesc[last_desc];
1777
1778         if (!t4vf_is_eth_imm(skb) &&
1779             unlikely(cxgb4_map_skb(adapter->pdev_dev, skb,
1780                                    sgl_sdesc->addr) < 0)) {
1781                 /* We need to map the skb into PCI DMA space (because it can't
1782                  * be in-lined directly into the Work Request) and the mapping
1783                  * operation failed.  Record the error and drop the packet.
1784                  */
1785                 memset(sgl_sdesc->addr, 0, sizeof(sgl_sdesc->addr));
1786                 txq->mapping_err++;
1787                 goto out_free;
1788         }
1789
1790         wr_mid = FW_WR_LEN16_V(DIV_ROUND_UP(flits, 2));
1791         if (unlikely(credits < ETHTXQ_STOP_THRES)) {
1792                 /* After we're done injecting the Work Request for this
1793                  * packet, we'll be below our "stop threshold" so stop the TX
1794                  * Queue now and schedule a request for an SGE Egress Queue
1795                  * Update message.  The queue will get started later on when
1796                  * the firmware processes this Work Request and sends us an
1797                  * Egress Queue Status Update message indicating that space
1798                  * has opened up.
1799                  */
1800                 eth_txq_stop(txq);
1801                 wr_mid |= FW_WR_EQUEQ_F | FW_WR_EQUIQ_F;
1802         }
1803
1804         /* Start filling in our Work Request.  Note that we do _not_ handle
1805          * the WR Header wrapping around the TX Descriptor Ring.  If our
1806          * maximum header size ever exceeds one TX Descriptor, we'll need to
1807          * do something else here.
1808          */
1809         WARN_ON(DIV_ROUND_UP(T4VF_ETHTXQ_MAX_HDR, TXD_PER_EQ_UNIT) > 1);
1810         wr = (void *)&txq->q.desc[txq->q.pidx];
1811         wr->equiq_to_len16 = cpu_to_be32(wr_mid);
1812         wr->r3[0] = cpu_to_be32(0);
1813         wr->r3[1] = cpu_to_be32(0);
1814         skb_copy_from_linear_data(skb, (void *)wr->ethmacdst, fw_hdr_copy_len);
1815         end = (u64 *)wr + flits;
1816
1817         /* If this is a Large Send Offload packet we'll put in an LSO CPL
1818          * message with an encapsulated TX Packet CPL message.  Otherwise we
1819          * just use a TX Packet CPL message.
1820          */
1821         ssi = skb_shinfo(skb);
1822         if (ssi->gso_size) {
1823                 struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
1824                 bool v6 = (ssi->gso_type & SKB_GSO_TCPV6) != 0;
1825                 int l3hdr_len = skb_network_header_len(skb);
1826                 int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1827
1828                 wr->op_immdlen =
1829                         cpu_to_be32(FW_WR_OP_V(FW_ETH_TX_PKT_VM_WR) |
1830                                     FW_WR_IMMDLEN_V(sizeof(*lso) +
1831                                                     sizeof(*cpl)));
1832                  /* Fill in the LSO CPL message. */
1833                 lso->lso_ctrl =
1834                         cpu_to_be32(LSO_OPCODE_V(CPL_TX_PKT_LSO) |
1835                                     LSO_FIRST_SLICE_F |
1836                                     LSO_LAST_SLICE_F |
1837                                     LSO_IPV6_V(v6) |
1838                                     LSO_ETHHDR_LEN_V(eth_xtra_len / 4) |
1839                                     LSO_IPHDR_LEN_V(l3hdr_len / 4) |
1840                                     LSO_TCPHDR_LEN_V(tcp_hdr(skb)->doff));
1841                 lso->ipid_ofst = cpu_to_be16(0);
1842                 lso->mss = cpu_to_be16(ssi->gso_size);
1843                 lso->seqno_offset = cpu_to_be32(0);
1844                 if (is_t4(adapter->params.chip))
1845                         lso->len = cpu_to_be32(skb->len);
1846                 else
1847                         lso->len = cpu_to_be32(LSO_T5_XFER_SIZE_V(skb->len));
1848
1849                 /* Set up TX Packet CPL pointer, control word and perform
1850                  * accounting.
1851                  */
1852                 cpl = (void *)(lso + 1);
1853
1854                 if (CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5)
1855                         cntrl = TXPKT_ETHHDR_LEN_V(eth_xtra_len);
1856                 else
1857                         cntrl = T6_TXPKT_ETHHDR_LEN_V(eth_xtra_len);
1858
1859                 cntrl |= TXPKT_CSUM_TYPE_V(v6 ?
1860                                            TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
1861                          TXPKT_IPHDR_LEN_V(l3hdr_len);
1862                 txq->tso++;
1863                 txq->tx_cso += ssi->gso_segs;
1864         } else {
1865                 int len;
1866
1867                 len = (t4vf_is_eth_imm(skb)
1868                        ? skb->len + sizeof(*cpl)
1869                        : sizeof(*cpl));
1870                 wr->op_immdlen =
1871                         cpu_to_be32(FW_WR_OP_V(FW_ETH_TX_PKT_VM_WR) |
1872                                     FW_WR_IMMDLEN_V(len));
1873
1874                 /* Set up TX Packet CPL pointer, control word and perform
1875                  * accounting.
1876                  */
1877                 cpl = (void *)(wr + 1);
1878                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1879                         cntrl = hwcsum(adapter->params.chip, skb) |
1880                                 TXPKT_IPCSUM_DIS_F;
1881                         txq->tx_cso++;
1882                 } else {
1883                         cntrl = TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F;
1884                 }
1885         }
1886
1887         /* If there's a VLAN tag present, add that to the list of things to
1888          * do in this Work Request.
1889          */
1890         if (skb_vlan_tag_present(skb)) {
1891                 txq->vlan_ins++;
1892                 cntrl |= TXPKT_VLAN_VLD_F | TXPKT_VLAN_V(skb_vlan_tag_get(skb));
1893         }
1894
1895          /* Fill in the TX Packet CPL message header. */
1896         cpl->ctrl0 = cpu_to_be32(TXPKT_OPCODE_V(CPL_TX_PKT_XT) |
1897                                  TXPKT_INTF_V(pi->port_id) |
1898                                  TXPKT_PF_V(0));
1899         cpl->pack = cpu_to_be16(0);
1900         cpl->len = cpu_to_be16(skb->len);
1901         cpl->ctrl1 = cpu_to_be64(cntrl);
1902
1903         /* Fill in the body of the TX Packet CPL message with either in-lined
1904          * data or a Scatter/Gather List.
1905          */
1906         if (t4vf_is_eth_imm(skb)) {
1907                 /* In-line the packet's data and free the skb since we don't
1908                  * need it any longer.
1909                  */
1910                 cxgb4_inline_tx_skb(skb, &txq->q, cpl + 1);
1911                 dev_consume_skb_any(skb);
1912         } else {
1913                 /* Write the skb's Scatter/Gather list into the TX Packet CPL
1914                  * message and retain a pointer to the skb so we can free it
1915                  * later when its DMA completes.  (We store the skb pointer
1916                  * in the Software Descriptor corresponding to the last TX
1917                  * Descriptor used by the Work Request.)
1918                  *
1919                  * The retained skb will be freed when the corresponding TX
1920                  * Descriptors are reclaimed after their DMAs complete.
1921                  * However, this could take quite a while since, in general,
1922                  * the hardware is set up to be lazy about sending DMA
1923                  * completion notifications to us and we mostly perform TX
1924                  * reclaims in the transmit routine.
1925                  *
1926                  * This is good for performamce but means that we rely on new
1927                  * TX packets arriving to run the destructors of completed
1928                  * packets, which open up space in their sockets' send queues.
1929                  * Sometimes we do not get such new packets causing TX to
1930                  * stall.  A single UDP transmitter is a good example of this
1931                  * situation.  We have a clean up timer that periodically
1932                  * reclaims completed packets but it doesn't run often enough
1933                  * (nor do we want it to) to prevent lengthy stalls.  A
1934                  * solution to this problem is to run the destructor early,
1935                  * after the packet is queued but before it's DMAd.  A con is
1936                  * that we lie to socket memory accounting, but the amount of
1937                  * extra memory is reasonable (limited by the number of TX
1938                  * descriptors), the packets do actually get freed quickly by
1939                  * new packets almost always, and for protocols like TCP that
1940                  * wait for acks to really free up the data the extra memory
1941                  * is even less.  On the positive side we run the destructors
1942                  * on the sending CPU rather than on a potentially different
1943                  * completing CPU, usually a good thing.
1944                  *
1945                  * Run the destructor before telling the DMA engine about the
1946                  * packet to make sure it doesn't complete and get freed
1947                  * prematurely.
1948                  */
1949                 struct ulptx_sgl *sgl = (struct ulptx_sgl *)(cpl + 1);
1950                 struct sge_txq *tq = &txq->q;
1951
1952                 /* If the Work Request header was an exact multiple of our TX
1953                  * Descriptor length, then it's possible that the starting SGL
1954                  * pointer lines up exactly with the end of our TX Descriptor
1955                  * ring.  If that's the case, wrap around to the beginning
1956                  * here ...
1957                  */
1958                 if (unlikely((void *)sgl == (void *)tq->stat)) {
1959                         sgl = (void *)tq->desc;
1960                         end = (void *)((void *)tq->desc +
1961                                        ((void *)end - (void *)tq->stat));
1962                 }
1963
1964                 cxgb4_write_sgl(skb, tq, sgl, end, 0, sgl_sdesc->addr);
1965                 skb_orphan(skb);
1966                 sgl_sdesc->skb = skb;
1967         }
1968
1969         /* Advance our internal TX Queue state, tell the hardware about
1970          * the new TX descriptors and return success.
1971          */
1972         txq_advance(&txq->q, ndesc);
1973
1974         cxgb4_ring_tx_db(adapter, &txq->q, ndesc);
1975         return NETDEV_TX_OK;
1976
1977 out_free:
1978         /* An error of some sort happened.  Free the TX skb and tell the
1979          * OS that we've "dealt" with the packet ...
1980          */
1981         dev_kfree_skb_any(skb);
1982         return NETDEV_TX_OK;
1983 }
1984
1985 /**
1986  * reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
1987  * @q: the SGE control Tx queue
1988  *
1989  * This is a variant of cxgb4_reclaim_completed_tx() that is used
1990  * for Tx queues that send only immediate data (presently just
1991  * the control queues) and      thus do not have any sk_buffs to release.
1992  */
1993 static inline void reclaim_completed_tx_imm(struct sge_txq *q)
1994 {
1995         int hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
1996         int reclaim = hw_cidx - q->cidx;
1997
1998         if (reclaim < 0)
1999                 reclaim += q->size;
2000
2001         q->in_use -= reclaim;
2002         q->cidx = hw_cidx;
2003 }
2004
2005 static inline void eosw_txq_advance_index(u32 *idx, u32 n, u32 max)
2006 {
2007         u32 val = *idx + n;
2008
2009         if (val >= max)
2010                 val -= max;
2011
2012         *idx = val;
2013 }
2014
2015 void cxgb4_eosw_txq_free_desc(struct adapter *adap,
2016                               struct sge_eosw_txq *eosw_txq, u32 ndesc)
2017 {
2018         struct tx_sw_desc *d;
2019
2020         d = &eosw_txq->desc[eosw_txq->last_cidx];
2021         while (ndesc--) {
2022                 if (d->skb) {
2023                         if (d->addr[0]) {
2024                                 unmap_skb(adap->pdev_dev, d->skb, d->addr);
2025                                 memset(d->addr, 0, sizeof(d->addr));
2026                         }
2027                         dev_consume_skb_any(d->skb);
2028                         d->skb = NULL;
2029                 }
2030                 eosw_txq_advance_index(&eosw_txq->last_cidx, 1,
2031                                        eosw_txq->ndesc);
2032                 d = &eosw_txq->desc[eosw_txq->last_cidx];
2033         }
2034 }
2035
2036 static inline void eosw_txq_advance(struct sge_eosw_txq *eosw_txq, u32 n)
2037 {
2038         eosw_txq_advance_index(&eosw_txq->pidx, n, eosw_txq->ndesc);
2039         eosw_txq->inuse += n;
2040 }
2041
2042 static inline int eosw_txq_enqueue(struct sge_eosw_txq *eosw_txq,
2043                                    struct sk_buff *skb)
2044 {
2045         if (eosw_txq->inuse == eosw_txq->ndesc)
2046                 return -ENOMEM;
2047
2048         eosw_txq->desc[eosw_txq->pidx].skb = skb;
2049         return 0;
2050 }
2051
2052 static inline struct sk_buff *eosw_txq_peek(struct sge_eosw_txq *eosw_txq)
2053 {
2054         return eosw_txq->desc[eosw_txq->last_pidx].skb;
2055 }
2056
2057 static inline u8 ethofld_calc_tx_flits(struct adapter *adap,
2058                                        struct sk_buff *skb, u32 hdr_len)
2059 {
2060         u8 flits, nsgl = 0;
2061         u32 wrlen;
2062
2063         wrlen = sizeof(struct fw_eth_tx_eo_wr) + sizeof(struct cpl_tx_pkt_core);
2064         if (skb_shinfo(skb)->gso_size &&
2065             !(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4))
2066                 wrlen += sizeof(struct cpl_tx_pkt_lso_core);
2067
2068         wrlen += roundup(hdr_len, 16);
2069
2070         /* Packet headers + WR + CPLs */
2071         flits = DIV_ROUND_UP(wrlen, 8);
2072
2073         if (skb_shinfo(skb)->nr_frags > 0) {
2074                 if (skb_headlen(skb) - hdr_len)
2075                         nsgl = sgl_len(skb_shinfo(skb)->nr_frags + 1);
2076                 else
2077                         nsgl = sgl_len(skb_shinfo(skb)->nr_frags);
2078         } else if (skb->len - hdr_len) {
2079                 nsgl = sgl_len(1);
2080         }
2081
2082         return flits + nsgl;
2083 }
2084
2085 static void *write_eo_wr(struct adapter *adap, struct sge_eosw_txq *eosw_txq,
2086                          struct sk_buff *skb, struct fw_eth_tx_eo_wr *wr,
2087                          u32 hdr_len, u32 wrlen)
2088 {
2089         const struct skb_shared_info *ssi = skb_shinfo(skb);
2090         struct cpl_tx_pkt_core *cpl;
2091         u32 immd_len, wrlen16;
2092         bool compl = false;
2093         u8 ver, proto;
2094
2095         ver = ip_hdr(skb)->version;
2096         proto = (ver == 6) ? ipv6_hdr(skb)->nexthdr : ip_hdr(skb)->protocol;
2097
2098         wrlen16 = DIV_ROUND_UP(wrlen, 16);
2099         immd_len = sizeof(struct cpl_tx_pkt_core);
2100         if (skb_shinfo(skb)->gso_size &&
2101             !(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4))
2102                 immd_len += sizeof(struct cpl_tx_pkt_lso_core);
2103         immd_len += hdr_len;
2104
2105         if (!eosw_txq->ncompl ||
2106             (eosw_txq->last_compl + wrlen16) >=
2107             (adap->params.ofldq_wr_cred / 2)) {
2108                 compl = true;
2109                 eosw_txq->ncompl++;
2110                 eosw_txq->last_compl = 0;
2111         }
2112
2113         wr->op_immdlen = cpu_to_be32(FW_WR_OP_V(FW_ETH_TX_EO_WR) |
2114                                      FW_ETH_TX_EO_WR_IMMDLEN_V(immd_len) |
2115                                      FW_WR_COMPL_V(compl));
2116         wr->equiq_to_len16 = cpu_to_be32(FW_WR_LEN16_V(wrlen16) |
2117                                          FW_WR_FLOWID_V(eosw_txq->hwtid));
2118         wr->r3 = 0;
2119         if (proto == IPPROTO_UDP) {
2120                 cpl = write_eo_udp_wr(skb, wr, hdr_len);
2121         } else {
2122                 wr->u.tcpseg.type = FW_ETH_TX_EO_TYPE_TCPSEG;
2123                 wr->u.tcpseg.ethlen = skb_network_offset(skb);
2124                 wr->u.tcpseg.iplen = cpu_to_be16(skb_network_header_len(skb));
2125                 wr->u.tcpseg.tcplen = tcp_hdrlen(skb);
2126                 wr->u.tcpseg.tsclk_tsoff = 0;
2127                 wr->u.tcpseg.r4 = 0;
2128                 wr->u.tcpseg.r5 = 0;
2129                 wr->u.tcpseg.plen = cpu_to_be32(skb->len - hdr_len);
2130
2131                 if (ssi->gso_size) {
2132                         struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
2133
2134                         wr->u.tcpseg.mss = cpu_to_be16(ssi->gso_size);
2135                         cpl = write_tso_wr(adap, skb, lso);
2136                 } else {
2137                         wr->u.tcpseg.mss = cpu_to_be16(0xffff);
2138                         cpl = (void *)(wr + 1);
2139                 }
2140         }
2141
2142         eosw_txq->cred -= wrlen16;
2143         eosw_txq->last_compl += wrlen16;
2144         return cpl;
2145 }
2146
2147 static int ethofld_hard_xmit(struct net_device *dev,
2148                              struct sge_eosw_txq *eosw_txq)
2149 {
2150         struct port_info *pi = netdev2pinfo(dev);
2151         struct adapter *adap = netdev2adap(dev);
2152         u32 wrlen, wrlen16, hdr_len, data_len;
2153         enum sge_eosw_state next_state;
2154         u64 cntrl, *start, *end, *sgl;
2155         struct sge_eohw_txq *eohw_txq;
2156         struct cpl_tx_pkt_core *cpl;
2157         struct fw_eth_tx_eo_wr *wr;
2158         bool skip_eotx_wr = false;
2159         struct tx_sw_desc *d;
2160         struct sk_buff *skb;
2161         int left, ret = 0;
2162         u8 flits, ndesc;
2163
2164         eohw_txq = &adap->sge.eohw_txq[eosw_txq->hwqid];
2165         spin_lock(&eohw_txq->lock);
2166         reclaim_completed_tx_imm(&eohw_txq->q);
2167
2168         d = &eosw_txq->desc[eosw_txq->last_pidx];
2169         skb = d->skb;
2170         skb_tx_timestamp(skb);
2171
2172         wr = (struct fw_eth_tx_eo_wr *)&eohw_txq->q.desc[eohw_txq->q.pidx];
2173         if (unlikely(eosw_txq->state != CXGB4_EO_STATE_ACTIVE &&
2174                      eosw_txq->last_pidx == eosw_txq->flowc_idx)) {
2175                 hdr_len = skb->len;
2176                 data_len = 0;
2177                 flits = DIV_ROUND_UP(hdr_len, 8);
2178                 if (eosw_txq->state == CXGB4_EO_STATE_FLOWC_OPEN_SEND)
2179                         next_state = CXGB4_EO_STATE_FLOWC_OPEN_REPLY;
2180                 else
2181                         next_state = CXGB4_EO_STATE_FLOWC_CLOSE_REPLY;
2182                 skip_eotx_wr = true;
2183         } else {
2184                 hdr_len = eth_get_headlen(dev, skb->data, skb_headlen(skb));
2185                 data_len = skb->len - hdr_len;
2186                 flits = ethofld_calc_tx_flits(adap, skb, hdr_len);
2187         }
2188         ndesc = flits_to_desc(flits);
2189         wrlen = flits * 8;
2190         wrlen16 = DIV_ROUND_UP(wrlen, 16);
2191
2192         left = txq_avail(&eohw_txq->q) - ndesc;
2193
2194         /* If there are no descriptors left in hardware queues or no
2195          * CPL credits left in software queues, then wait for them
2196          * to come back and retry again. Note that we always request
2197          * for credits update via interrupt for every half credits
2198          * consumed. So, the interrupt will eventually restore the
2199          * credits and invoke the Tx path again.
2200          */
2201         if (unlikely(left < 0 || wrlen16 > eosw_txq->cred)) {
2202                 ret = -ENOMEM;
2203                 goto out_unlock;
2204         }
2205
2206         if (unlikely(skip_eotx_wr)) {
2207                 start = (u64 *)wr;
2208                 eosw_txq->state = next_state;
2209                 eosw_txq->cred -= wrlen16;
2210                 eosw_txq->ncompl++;
2211                 eosw_txq->last_compl = 0;
2212                 goto write_wr_headers;
2213         }
2214
2215         cpl = write_eo_wr(adap, eosw_txq, skb, wr, hdr_len, wrlen);
2216         cntrl = hwcsum(adap->params.chip, skb);
2217         if (skb_vlan_tag_present(skb))
2218                 cntrl |= TXPKT_VLAN_VLD_F | TXPKT_VLAN_V(skb_vlan_tag_get(skb));
2219
2220         cpl->ctrl0 = cpu_to_be32(TXPKT_OPCODE_V(CPL_TX_PKT_XT) |
2221                                  TXPKT_INTF_V(pi->tx_chan) |
2222                                  TXPKT_PF_V(adap->pf));
2223         cpl->pack = 0;
2224         cpl->len = cpu_to_be16(skb->len);
2225         cpl->ctrl1 = cpu_to_be64(cntrl);
2226
2227         start = (u64 *)(cpl + 1);
2228
2229 write_wr_headers:
2230         sgl = (u64 *)inline_tx_skb_header(skb, &eohw_txq->q, (void *)start,
2231                                           hdr_len);
2232         if (data_len) {
2233                 ret = cxgb4_map_skb(adap->pdev_dev, skb, d->addr);
2234                 if (unlikely(ret)) {
2235                         memset(d->addr, 0, sizeof(d->addr));
2236                         eohw_txq->mapping_err++;
2237                         goto out_unlock;
2238                 }
2239
2240                 end = (u64 *)wr + flits;
2241                 if (unlikely(start > sgl)) {
2242                         left = (u8 *)end - (u8 *)eohw_txq->q.stat;
2243                         end = (void *)eohw_txq->q.desc + left;
2244                 }
2245
2246                 if (unlikely((u8 *)sgl >= (u8 *)eohw_txq->q.stat)) {
2247                         /* If current position is already at the end of the
2248                          * txq, reset the current to point to start of the queue
2249                          * and update the end ptr as well.
2250                          */
2251                         left = (u8 *)end - (u8 *)eohw_txq->q.stat;
2252
2253                         end = (void *)eohw_txq->q.desc + left;
2254                         sgl = (void *)eohw_txq->q.desc;
2255                 }
2256
2257                 cxgb4_write_sgl(skb, &eohw_txq->q, (void *)sgl, end, hdr_len,
2258                                 d->addr);
2259         }
2260
2261         if (skb_shinfo(skb)->gso_size) {
2262                 if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4)
2263                         eohw_txq->uso++;
2264                 else
2265                         eohw_txq->tso++;
2266                 eohw_txq->tx_cso += skb_shinfo(skb)->gso_segs;
2267         } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2268                 eohw_txq->tx_cso++;
2269         }
2270
2271         if (skb_vlan_tag_present(skb))
2272                 eohw_txq->vlan_ins++;
2273
2274         txq_advance(&eohw_txq->q, ndesc);
2275         cxgb4_ring_tx_db(adap, &eohw_txq->q, ndesc);
2276         eosw_txq_advance_index(&eosw_txq->last_pidx, 1, eosw_txq->ndesc);
2277
2278 out_unlock:
2279         spin_unlock(&eohw_txq->lock);
2280         return ret;
2281 }
2282
2283 static void ethofld_xmit(struct net_device *dev, struct sge_eosw_txq *eosw_txq)
2284 {
2285         struct sk_buff *skb;
2286         int pktcount, ret;
2287
2288         switch (eosw_txq->state) {
2289         case CXGB4_EO_STATE_ACTIVE:
2290         case CXGB4_EO_STATE_FLOWC_OPEN_SEND:
2291         case CXGB4_EO_STATE_FLOWC_CLOSE_SEND:
2292                 pktcount = eosw_txq->pidx - eosw_txq->last_pidx;
2293                 if (pktcount < 0)
2294                         pktcount += eosw_txq->ndesc;
2295                 break;
2296         case CXGB4_EO_STATE_FLOWC_OPEN_REPLY:
2297         case CXGB4_EO_STATE_FLOWC_CLOSE_REPLY:
2298         case CXGB4_EO_STATE_CLOSED:
2299         default:
2300                 return;
2301         }
2302
2303         while (pktcount--) {
2304                 skb = eosw_txq_peek(eosw_txq);
2305                 if (!skb) {
2306                         eosw_txq_advance_index(&eosw_txq->last_pidx, 1,
2307                                                eosw_txq->ndesc);
2308                         continue;
2309                 }
2310
2311                 ret = ethofld_hard_xmit(dev, eosw_txq);
2312                 if (ret)
2313                         break;
2314         }
2315 }
2316
2317 static netdev_tx_t cxgb4_ethofld_xmit(struct sk_buff *skb,
2318                                       struct net_device *dev)
2319 {
2320         struct cxgb4_tc_port_mqprio *tc_port_mqprio;
2321         struct port_info *pi = netdev2pinfo(dev);
2322         struct adapter *adap = netdev2adap(dev);
2323         struct sge_eosw_txq *eosw_txq;
2324         u32 qid;
2325         int ret;
2326
2327         ret = cxgb4_validate_skb(skb, dev, ETH_HLEN);
2328         if (ret)
2329                 goto out_free;
2330
2331         tc_port_mqprio = &adap->tc_mqprio->port_mqprio[pi->port_id];
2332         qid = skb_get_queue_mapping(skb) - pi->nqsets;
2333         eosw_txq = &tc_port_mqprio->eosw_txq[qid];
2334         spin_lock_bh(&eosw_txq->lock);
2335         if (eosw_txq->state != CXGB4_EO_STATE_ACTIVE)
2336                 goto out_unlock;
2337
2338         ret = eosw_txq_enqueue(eosw_txq, skb);
2339         if (ret)
2340                 goto out_unlock;
2341
2342         /* SKB is queued for processing until credits are available.
2343          * So, call the destructor now and we'll free the skb later
2344          * after it has been successfully transmitted.
2345          */
2346         skb_orphan(skb);
2347
2348         eosw_txq_advance(eosw_txq, 1);
2349         ethofld_xmit(dev, eosw_txq);
2350         spin_unlock_bh(&eosw_txq->lock);
2351         return NETDEV_TX_OK;
2352
2353 out_unlock:
2354         spin_unlock_bh(&eosw_txq->lock);
2355 out_free:
2356         dev_kfree_skb_any(skb);
2357         return NETDEV_TX_OK;
2358 }
2359
2360 netdev_tx_t t4_start_xmit(struct sk_buff *skb, struct net_device *dev)
2361 {
2362         struct port_info *pi = netdev_priv(dev);
2363         u16 qid = skb_get_queue_mapping(skb);
2364
2365         if (unlikely(pi->eth_flags & PRIV_FLAG_PORT_TX_VM))
2366                 return cxgb4_vf_eth_xmit(skb, dev);
2367
2368         if (unlikely(qid >= pi->nqsets))
2369                 return cxgb4_ethofld_xmit(skb, dev);
2370
2371         if (is_ptp_enabled(skb, dev)) {
2372                 struct adapter *adap = netdev2adap(dev);
2373                 netdev_tx_t ret;
2374
2375                 spin_lock(&adap->ptp_lock);
2376                 ret = cxgb4_eth_xmit(skb, dev);
2377                 spin_unlock(&adap->ptp_lock);
2378                 return ret;
2379         }
2380
2381         return cxgb4_eth_xmit(skb, dev);
2382 }
2383
2384 static void eosw_txq_flush_pending_skbs(struct sge_eosw_txq *eosw_txq)
2385 {
2386         int pktcount = eosw_txq->pidx - eosw_txq->last_pidx;
2387         int pidx = eosw_txq->pidx;
2388         struct sk_buff *skb;
2389
2390         if (!pktcount)
2391                 return;
2392
2393         if (pktcount < 0)
2394                 pktcount += eosw_txq->ndesc;
2395
2396         while (pktcount--) {
2397                 pidx--;
2398                 if (pidx < 0)
2399                         pidx += eosw_txq->ndesc;
2400
2401                 skb = eosw_txq->desc[pidx].skb;
2402                 if (skb) {
2403                         dev_consume_skb_any(skb);
2404                         eosw_txq->desc[pidx].skb = NULL;
2405                         eosw_txq->inuse--;
2406                 }
2407         }
2408
2409         eosw_txq->pidx = eosw_txq->last_pidx + 1;
2410 }
2411
2412 /**
2413  * cxgb4_ethofld_send_flowc - Send ETHOFLD flowc request to bind eotid to tc.
2414  * @dev: netdevice
2415  * @eotid: ETHOFLD tid to bind/unbind
2416  * @tc: traffic class. If set to FW_SCHED_CLS_NONE, then unbinds the @eotid
2417  *
2418  * Send a FLOWC work request to bind an ETHOFLD TID to a traffic class.
2419  * If @tc is set to FW_SCHED_CLS_NONE, then the @eotid is unbound from
2420  * a traffic class.
2421  */
2422 int cxgb4_ethofld_send_flowc(struct net_device *dev, u32 eotid, u32 tc)
2423 {
2424         struct port_info *pi = netdev2pinfo(dev);
2425         struct adapter *adap = netdev2adap(dev);
2426         enum sge_eosw_state next_state;
2427         struct sge_eosw_txq *eosw_txq;
2428         u32 len, len16, nparams = 6;
2429         struct fw_flowc_wr *flowc;
2430         struct eotid_entry *entry;
2431         struct sge_ofld_rxq *rxq;
2432         struct sk_buff *skb;
2433         int ret = 0;
2434
2435         len = struct_size(flowc, mnemval, nparams);
2436         len16 = DIV_ROUND_UP(len, 16);
2437
2438         entry = cxgb4_lookup_eotid(&adap->tids, eotid);
2439         if (!entry)
2440                 return -ENOMEM;
2441
2442         eosw_txq = (struct sge_eosw_txq *)entry->data;
2443         if (!eosw_txq)
2444                 return -ENOMEM;
2445
2446         skb = alloc_skb(len, GFP_KERNEL);
2447         if (!skb)
2448                 return -ENOMEM;
2449
2450         spin_lock_bh(&eosw_txq->lock);
2451         if (tc != FW_SCHED_CLS_NONE) {
2452                 if (eosw_txq->state != CXGB4_EO_STATE_CLOSED)
2453                         goto out_unlock;
2454
2455                 next_state = CXGB4_EO_STATE_FLOWC_OPEN_SEND;
2456         } else {
2457                 if (eosw_txq->state != CXGB4_EO_STATE_ACTIVE)
2458                         goto out_unlock;
2459
2460                 next_state = CXGB4_EO_STATE_FLOWC_CLOSE_SEND;
2461         }
2462
2463         flowc = __skb_put(skb, len);
2464         memset(flowc, 0, len);
2465
2466         rxq = &adap->sge.eohw_rxq[eosw_txq->hwqid];
2467         flowc->flowid_len16 = cpu_to_be32(FW_WR_LEN16_V(len16) |
2468                                           FW_WR_FLOWID_V(eosw_txq->hwtid));
2469         flowc->op_to_nparams = cpu_to_be32(FW_WR_OP_V(FW_FLOWC_WR) |
2470                                            FW_FLOWC_WR_NPARAMS_V(nparams) |
2471                                            FW_WR_COMPL_V(1));
2472         flowc->mnemval[0].mnemonic = FW_FLOWC_MNEM_PFNVFN;
2473         flowc->mnemval[0].val = cpu_to_be32(FW_PFVF_CMD_PFN_V(adap->pf));
2474         flowc->mnemval[1].mnemonic = FW_FLOWC_MNEM_CH;
2475         flowc->mnemval[1].val = cpu_to_be32(pi->tx_chan);
2476         flowc->mnemval[2].mnemonic = FW_FLOWC_MNEM_PORT;
2477         flowc->mnemval[2].val = cpu_to_be32(pi->tx_chan);
2478         flowc->mnemval[3].mnemonic = FW_FLOWC_MNEM_IQID;
2479         flowc->mnemval[3].val = cpu_to_be32(rxq->rspq.abs_id);
2480         flowc->mnemval[4].mnemonic = FW_FLOWC_MNEM_SCHEDCLASS;
2481         flowc->mnemval[4].val = cpu_to_be32(tc);
2482         flowc->mnemval[5].mnemonic = FW_FLOWC_MNEM_EOSTATE;
2483         flowc->mnemval[5].val = cpu_to_be32(tc == FW_SCHED_CLS_NONE ?
2484                                             FW_FLOWC_MNEM_EOSTATE_CLOSING :
2485                                             FW_FLOWC_MNEM_EOSTATE_ESTABLISHED);
2486
2487         /* Free up any pending skbs to ensure there's room for
2488          * termination FLOWC.
2489          */
2490         if (tc == FW_SCHED_CLS_NONE)
2491                 eosw_txq_flush_pending_skbs(eosw_txq);
2492
2493         ret = eosw_txq_enqueue(eosw_txq, skb);
2494         if (ret) {
2495                 dev_consume_skb_any(skb);
2496                 goto out_unlock;
2497         }
2498
2499         eosw_txq->state = next_state;
2500         eosw_txq->flowc_idx = eosw_txq->pidx;
2501         eosw_txq_advance(eosw_txq, 1);
2502         ethofld_xmit(dev, eosw_txq);
2503
2504 out_unlock:
2505         spin_unlock_bh(&eosw_txq->lock);
2506         return ret;
2507 }
2508
2509 /**
2510  *      is_imm - check whether a packet can be sent as immediate data
2511  *      @skb: the packet
2512  *
2513  *      Returns true if a packet can be sent as a WR with immediate data.
2514  */
2515 static inline int is_imm(const struct sk_buff *skb)
2516 {
2517         return skb->len <= MAX_CTRL_WR_LEN;
2518 }
2519
2520 /**
2521  *      ctrlq_check_stop - check if a control queue is full and should stop
2522  *      @q: the queue
2523  *      @wr: most recent WR written to the queue
2524  *
2525  *      Check if a control queue has become full and should be stopped.
2526  *      We clean up control queue descriptors very lazily, only when we are out.
2527  *      If the queue is still full after reclaiming any completed descriptors
2528  *      we suspend it and have the last WR wake it up.
2529  */
2530 static void ctrlq_check_stop(struct sge_ctrl_txq *q, struct fw_wr_hdr *wr)
2531 {
2532         reclaim_completed_tx_imm(&q->q);
2533         if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
2534                 wr->lo |= htonl(FW_WR_EQUEQ_F | FW_WR_EQUIQ_F);
2535                 q->q.stops++;
2536                 q->full = 1;
2537         }
2538 }
2539
2540 #define CXGB4_SELFTEST_LB_STR "CHELSIO_SELFTEST"
2541
2542 int cxgb4_selftest_lb_pkt(struct net_device *netdev)
2543 {
2544         struct port_info *pi = netdev_priv(netdev);
2545         struct adapter *adap = pi->adapter;
2546         struct cxgb4_ethtool_lb_test *lb;
2547         int ret, i = 0, pkt_len, credits;
2548         struct fw_eth_tx_pkt_wr *wr;
2549         struct cpl_tx_pkt_core *cpl;
2550         u32 ctrl0, ndesc, flits;
2551         struct sge_eth_txq *q;
2552         u8 *sgl;
2553
2554         pkt_len = ETH_HLEN + sizeof(CXGB4_SELFTEST_LB_STR);
2555
2556         flits = DIV_ROUND_UP(pkt_len + sizeof(struct cpl_tx_pkt) +
2557                              sizeof(*wr), sizeof(__be64));
2558         ndesc = flits_to_desc(flits);
2559
2560         lb = &pi->ethtool_lb;
2561         lb->loopback = 1;
2562
2563         q = &adap->sge.ethtxq[pi->first_qset];
2564
2565         reclaim_completed_tx(adap, &q->q, -1, true);
2566         credits = txq_avail(&q->q) - ndesc;
2567         if (unlikely(credits < 0))
2568                 return -ENOMEM;
2569
2570         wr = (void *)&q->q.desc[q->q.pidx];
2571         memset(wr, 0, sizeof(struct tx_desc));
2572
2573         wr->op_immdlen = htonl(FW_WR_OP_V(FW_ETH_TX_PKT_WR) |
2574                                FW_WR_IMMDLEN_V(pkt_len +
2575                                sizeof(*cpl)));
2576         wr->equiq_to_len16 = htonl(FW_WR_LEN16_V(DIV_ROUND_UP(flits, 2)));
2577         wr->r3 = cpu_to_be64(0);
2578
2579         cpl = (void *)(wr + 1);
2580         sgl = (u8 *)(cpl + 1);
2581
2582         ctrl0 = TXPKT_OPCODE_V(CPL_TX_PKT_XT) | TXPKT_PF_V(adap->pf) |
2583                 TXPKT_INTF_V(pi->tx_chan + 4);
2584
2585         cpl->ctrl0 = htonl(ctrl0);
2586         cpl->pack = htons(0);
2587         cpl->len = htons(pkt_len);
2588         cpl->ctrl1 = cpu_to_be64(TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F);
2589
2590         eth_broadcast_addr(sgl);
2591         i += ETH_ALEN;
2592         ether_addr_copy(&sgl[i], netdev->dev_addr);
2593         i += ETH_ALEN;
2594
2595         snprintf(&sgl[i], sizeof(CXGB4_SELFTEST_LB_STR), "%s",
2596                  CXGB4_SELFTEST_LB_STR);
2597
2598         init_completion(&lb->completion);
2599         txq_advance(&q->q, ndesc);
2600         cxgb4_ring_tx_db(adap, &q->q, ndesc);
2601
2602         /* wait for the pkt to return */
2603         ret = wait_for_completion_timeout(&lb->completion, 10 * HZ);
2604         if (!ret)
2605                 ret = -ETIMEDOUT;
2606         else
2607                 ret = lb->result;
2608
2609         lb->loopback = 0;
2610
2611         return ret;
2612 }
2613
2614 /**
2615  *      ctrl_xmit - send a packet through an SGE control Tx queue
2616  *      @q: the control queue
2617  *      @skb: the packet
2618  *
2619  *      Send a packet through an SGE control Tx queue.  Packets sent through
2620  *      a control queue must fit entirely as immediate data.
2621  */
2622 static int ctrl_xmit(struct sge_ctrl_txq *q, struct sk_buff *skb)
2623 {
2624         unsigned int ndesc;
2625         struct fw_wr_hdr *wr;
2626
2627         if (unlikely(!is_imm(skb))) {
2628                 WARN_ON(1);
2629                 dev_kfree_skb(skb);
2630                 return NET_XMIT_DROP;
2631         }
2632
2633         ndesc = DIV_ROUND_UP(skb->len, sizeof(struct tx_desc));
2634         spin_lock(&q->sendq.lock);
2635
2636         if (unlikely(q->full)) {
2637                 skb->priority = ndesc;                  /* save for restart */
2638                 __skb_queue_tail(&q->sendq, skb);
2639                 spin_unlock(&q->sendq.lock);
2640                 return NET_XMIT_CN;
2641         }
2642
2643         wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
2644         cxgb4_inline_tx_skb(skb, &q->q, wr);
2645
2646         txq_advance(&q->q, ndesc);
2647         if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES))
2648                 ctrlq_check_stop(q, wr);
2649
2650         cxgb4_ring_tx_db(q->adap, &q->q, ndesc);
2651         spin_unlock(&q->sendq.lock);
2652
2653         kfree_skb(skb);
2654         return NET_XMIT_SUCCESS;
2655 }
2656
2657 /**
2658  *      restart_ctrlq - restart a suspended control queue
2659  *      @data: the control queue to restart
2660  *
2661  *      Resumes transmission on a suspended Tx control queue.
2662  */
2663 static void restart_ctrlq(unsigned long data)
2664 {
2665         struct sk_buff *skb;
2666         unsigned int written = 0;
2667         struct sge_ctrl_txq *q = (struct sge_ctrl_txq *)data;
2668
2669         spin_lock(&q->sendq.lock);
2670         reclaim_completed_tx_imm(&q->q);
2671         BUG_ON(txq_avail(&q->q) < TXQ_STOP_THRES);  /* q should be empty */
2672
2673         while ((skb = __skb_dequeue(&q->sendq)) != NULL) {
2674                 struct fw_wr_hdr *wr;
2675                 unsigned int ndesc = skb->priority;     /* previously saved */
2676
2677                 written += ndesc;
2678                 /* Write descriptors and free skbs outside the lock to limit
2679                  * wait times.  q->full is still set so new skbs will be queued.
2680                  */
2681                 wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
2682                 txq_advance(&q->q, ndesc);
2683                 spin_unlock(&q->sendq.lock);
2684
2685                 cxgb4_inline_tx_skb(skb, &q->q, wr);
2686                 kfree_skb(skb);
2687
2688                 if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
2689                         unsigned long old = q->q.stops;
2690
2691                         ctrlq_check_stop(q, wr);
2692                         if (q->q.stops != old) {          /* suspended anew */
2693                                 spin_lock(&q->sendq.lock);
2694                                 goto ringdb;
2695                         }
2696                 }
2697                 if (written > 16) {
2698                         cxgb4_ring_tx_db(q->adap, &q->q, written);
2699                         written = 0;
2700                 }
2701                 spin_lock(&q->sendq.lock);
2702         }
2703         q->full = 0;
2704 ringdb:
2705         if (written)
2706                 cxgb4_ring_tx_db(q->adap, &q->q, written);
2707         spin_unlock(&q->sendq.lock);
2708 }
2709
2710 /**
2711  *      t4_mgmt_tx - send a management message
2712  *      @adap: the adapter
2713  *      @skb: the packet containing the management message
2714  *
2715  *      Send a management message through control queue 0.
2716  */
2717 int t4_mgmt_tx(struct adapter *adap, struct sk_buff *skb)
2718 {
2719         int ret;
2720
2721         local_bh_disable();
2722         ret = ctrl_xmit(&adap->sge.ctrlq[0], skb);
2723         local_bh_enable();
2724         return ret;
2725 }
2726
2727 /**
2728  *      is_ofld_imm - check whether a packet can be sent as immediate data
2729  *      @skb: the packet
2730  *
2731  *      Returns true if a packet can be sent as an offload WR with immediate
2732  *      data.  We currently use the same limit as for Ethernet packets.
2733  */
2734 static inline int is_ofld_imm(const struct sk_buff *skb)
2735 {
2736         struct work_request_hdr *req = (struct work_request_hdr *)skb->data;
2737         unsigned long opcode = FW_WR_OP_G(ntohl(req->wr_hi));
2738
2739         if (opcode == FW_CRYPTO_LOOKASIDE_WR)
2740                 return skb->len <= SGE_MAX_WR_LEN;
2741         else
2742                 return skb->len <= MAX_IMM_TX_PKT_LEN;
2743 }
2744
2745 /**
2746  *      calc_tx_flits_ofld - calculate # of flits for an offload packet
2747  *      @skb: the packet
2748  *
2749  *      Returns the number of flits needed for the given offload packet.
2750  *      These packets are already fully constructed and no additional headers
2751  *      will be added.
2752  */
2753 static inline unsigned int calc_tx_flits_ofld(const struct sk_buff *skb)
2754 {
2755         unsigned int flits, cnt;
2756
2757         if (is_ofld_imm(skb))
2758                 return DIV_ROUND_UP(skb->len, 8);
2759
2760         flits = skb_transport_offset(skb) / 8U;   /* headers */
2761         cnt = skb_shinfo(skb)->nr_frags;
2762         if (skb_tail_pointer(skb) != skb_transport_header(skb))
2763                 cnt++;
2764         return flits + sgl_len(cnt);
2765 }
2766
2767 /**
2768  *      txq_stop_maperr - stop a Tx queue due to I/O MMU exhaustion
2769  *      @q: the queue to stop
2770  *
2771  *      Mark a Tx queue stopped due to I/O MMU exhaustion and resulting
2772  *      inability to map packets.  A periodic timer attempts to restart
2773  *      queues so marked.
2774  */
2775 static void txq_stop_maperr(struct sge_uld_txq *q)
2776 {
2777         q->mapping_err++;
2778         q->q.stops++;
2779         set_bit(q->q.cntxt_id - q->adap->sge.egr_start,
2780                 q->adap->sge.txq_maperr);
2781 }
2782
2783 /**
2784  *      ofldtxq_stop - stop an offload Tx queue that has become full
2785  *      @q: the queue to stop
2786  *      @wr: the Work Request causing the queue to become full
2787  *
2788  *      Stops an offload Tx queue that has become full and modifies the packet
2789  *      being written to request a wakeup.
2790  */
2791 static void ofldtxq_stop(struct sge_uld_txq *q, struct fw_wr_hdr *wr)
2792 {
2793         wr->lo |= htonl(FW_WR_EQUEQ_F | FW_WR_EQUIQ_F);
2794         q->q.stops++;
2795         q->full = 1;
2796 }
2797
2798 /**
2799  *      service_ofldq - service/restart a suspended offload queue
2800  *      @q: the offload queue
2801  *
2802  *      Services an offload Tx queue by moving packets from its Pending Send
2803  *      Queue to the Hardware TX ring.  The function starts and ends with the
2804  *      Send Queue locked, but drops the lock while putting the skb at the
2805  *      head of the Send Queue onto the Hardware TX Ring.  Dropping the lock
2806  *      allows more skbs to be added to the Send Queue by other threads.
2807  *      The packet being processed at the head of the Pending Send Queue is
2808  *      left on the queue in case we experience DMA Mapping errors, etc.
2809  *      and need to give up and restart later.
2810  *
2811  *      service_ofldq() can be thought of as a task which opportunistically
2812  *      uses other threads execution contexts.  We use the Offload Queue
2813  *      boolean "service_ofldq_running" to make sure that only one instance
2814  *      is ever running at a time ...
2815  */
2816 static void service_ofldq(struct sge_uld_txq *q)
2817         __must_hold(&q->sendq.lock)
2818 {
2819         u64 *pos, *before, *end;
2820         int credits;
2821         struct sk_buff *skb;
2822         struct sge_txq *txq;
2823         unsigned int left;
2824         unsigned int written = 0;
2825         unsigned int flits, ndesc;
2826
2827         /* If another thread is currently in service_ofldq() processing the
2828          * Pending Send Queue then there's nothing to do. Otherwise, flag
2829          * that we're doing the work and continue.  Examining/modifying
2830          * the Offload Queue boolean "service_ofldq_running" must be done
2831          * while holding the Pending Send Queue Lock.
2832          */
2833         if (q->service_ofldq_running)
2834                 return;
2835         q->service_ofldq_running = true;
2836
2837         while ((skb = skb_peek(&q->sendq)) != NULL && !q->full) {
2838                 /* We drop the lock while we're working with the skb at the
2839                  * head of the Pending Send Queue.  This allows more skbs to
2840                  * be added to the Pending Send Queue while we're working on
2841                  * this one.  We don't need to lock to guard the TX Ring
2842                  * updates because only one thread of execution is ever
2843                  * allowed into service_ofldq() at a time.
2844                  */
2845                 spin_unlock(&q->sendq.lock);
2846
2847                 cxgb4_reclaim_completed_tx(q->adap, &q->q, false);
2848
2849                 flits = skb->priority;                /* previously saved */
2850                 ndesc = flits_to_desc(flits);
2851                 credits = txq_avail(&q->q) - ndesc;
2852                 BUG_ON(credits < 0);
2853                 if (unlikely(credits < TXQ_STOP_THRES))
2854                         ofldtxq_stop(q, (struct fw_wr_hdr *)skb->data);
2855
2856                 pos = (u64 *)&q->q.desc[q->q.pidx];
2857                 if (is_ofld_imm(skb))
2858                         cxgb4_inline_tx_skb(skb, &q->q, pos);
2859                 else if (cxgb4_map_skb(q->adap->pdev_dev, skb,
2860                                        (dma_addr_t *)skb->head)) {
2861                         txq_stop_maperr(q);
2862                         spin_lock(&q->sendq.lock);
2863                         break;
2864                 } else {
2865                         int last_desc, hdr_len = skb_transport_offset(skb);
2866
2867                         /* The WR headers  may not fit within one descriptor.
2868                          * So we need to deal with wrap-around here.
2869                          */
2870                         before = (u64 *)pos;
2871                         end = (u64 *)pos + flits;
2872                         txq = &q->q;
2873                         pos = (void *)inline_tx_skb_header(skb, &q->q,
2874                                                            (void *)pos,
2875                                                            hdr_len);
2876                         if (before > (u64 *)pos) {
2877                                 left = (u8 *)end - (u8 *)txq->stat;
2878                                 end = (void *)txq->desc + left;
2879                         }
2880
2881                         /* If current position is already at the end of the
2882                          * ofld queue, reset the current to point to
2883                          * start of the queue and update the end ptr as well.
2884                          */
2885                         if (pos == (u64 *)txq->stat) {
2886                                 left = (u8 *)end - (u8 *)txq->stat;
2887                                 end = (void *)txq->desc + left;
2888                                 pos = (void *)txq->desc;
2889                         }
2890
2891                         cxgb4_write_sgl(skb, &q->q, (void *)pos,
2892                                         end, hdr_len,
2893                                         (dma_addr_t *)skb->head);
2894 #ifdef CONFIG_NEED_DMA_MAP_STATE
2895                         skb->dev = q->adap->port[0];
2896                         skb->destructor = deferred_unmap_destructor;
2897 #endif
2898                         last_desc = q->q.pidx + ndesc - 1;
2899                         if (last_desc >= q->q.size)
2900                                 last_desc -= q->q.size;
2901                         q->q.sdesc[last_desc].skb = skb;
2902                 }
2903
2904                 txq_advance(&q->q, ndesc);
2905                 written += ndesc;
2906                 if (unlikely(written > 32)) {
2907                         cxgb4_ring_tx_db(q->adap, &q->q, written);
2908                         written = 0;
2909                 }
2910
2911                 /* Reacquire the Pending Send Queue Lock so we can unlink the
2912                  * skb we've just successfully transferred to the TX Ring and
2913                  * loop for the next skb which may be at the head of the
2914                  * Pending Send Queue.
2915                  */
2916                 spin_lock(&q->sendq.lock);
2917                 __skb_unlink(skb, &q->sendq);
2918                 if (is_ofld_imm(skb))
2919                         kfree_skb(skb);
2920         }
2921         if (likely(written))
2922                 cxgb4_ring_tx_db(q->adap, &q->q, written);
2923
2924         /*Indicate that no thread is processing the Pending Send Queue
2925          * currently.
2926          */
2927         q->service_ofldq_running = false;
2928 }
2929
2930 /**
2931  *      ofld_xmit - send a packet through an offload queue
2932  *      @q: the Tx offload queue
2933  *      @skb: the packet
2934  *
2935  *      Send an offload packet through an SGE offload queue.
2936  */
2937 static int ofld_xmit(struct sge_uld_txq *q, struct sk_buff *skb)
2938 {
2939         skb->priority = calc_tx_flits_ofld(skb);       /* save for restart */
2940         spin_lock(&q->sendq.lock);
2941
2942         /* Queue the new skb onto the Offload Queue's Pending Send Queue.  If
2943          * that results in this new skb being the only one on the queue, start
2944          * servicing it.  If there are other skbs already on the list, then
2945          * either the queue is currently being processed or it's been stopped
2946          * for some reason and it'll be restarted at a later time.  Restart
2947          * paths are triggered by events like experiencing a DMA Mapping Error
2948          * or filling the Hardware TX Ring.
2949          */
2950         __skb_queue_tail(&q->sendq, skb);
2951         if (q->sendq.qlen == 1)
2952                 service_ofldq(q);
2953
2954         spin_unlock(&q->sendq.lock);
2955         return NET_XMIT_SUCCESS;
2956 }
2957
2958 /**
2959  *      restart_ofldq - restart a suspended offload queue
2960  *      @data: the offload queue to restart
2961  *
2962  *      Resumes transmission on a suspended Tx offload queue.
2963  */
2964 static void restart_ofldq(unsigned long data)
2965 {
2966         struct sge_uld_txq *q = (struct sge_uld_txq *)data;
2967
2968         spin_lock(&q->sendq.lock);
2969         q->full = 0;            /* the queue actually is completely empty now */
2970         service_ofldq(q);
2971         spin_unlock(&q->sendq.lock);
2972 }
2973
2974 /**
2975  *      skb_txq - return the Tx queue an offload packet should use
2976  *      @skb: the packet
2977  *
2978  *      Returns the Tx queue an offload packet should use as indicated by bits
2979  *      1-15 in the packet's queue_mapping.
2980  */
2981 static inline unsigned int skb_txq(const struct sk_buff *skb)
2982 {
2983         return skb->queue_mapping >> 1;
2984 }
2985
2986 /**
2987  *      is_ctrl_pkt - return whether an offload packet is a control packet
2988  *      @skb: the packet
2989  *
2990  *      Returns whether an offload packet should use an OFLD or a CTRL
2991  *      Tx queue as indicated by bit 0 in the packet's queue_mapping.
2992  */
2993 static inline unsigned int is_ctrl_pkt(const struct sk_buff *skb)
2994 {
2995         return skb->queue_mapping & 1;
2996 }
2997
2998 static inline int uld_send(struct adapter *adap, struct sk_buff *skb,
2999                            unsigned int tx_uld_type)
3000 {
3001         struct sge_uld_txq_info *txq_info;
3002         struct sge_uld_txq *txq;
3003         unsigned int idx = skb_txq(skb);
3004
3005         if (unlikely(is_ctrl_pkt(skb))) {
3006                 /* Single ctrl queue is a requirement for LE workaround path */
3007                 if (adap->tids.nsftids)
3008                         idx = 0;
3009                 return ctrl_xmit(&adap->sge.ctrlq[idx], skb);
3010         }
3011
3012         txq_info = adap->sge.uld_txq_info[tx_uld_type];
3013         if (unlikely(!txq_info)) {
3014                 WARN_ON(true);
3015                 kfree_skb(skb);
3016                 return NET_XMIT_DROP;
3017         }
3018
3019         txq = &txq_info->uldtxq[idx];
3020         return ofld_xmit(txq, skb);
3021 }
3022
3023 /**
3024  *      t4_ofld_send - send an offload packet
3025  *      @adap: the adapter
3026  *      @skb: the packet
3027  *
3028  *      Sends an offload packet.  We use the packet queue_mapping to select the
3029  *      appropriate Tx queue as follows: bit 0 indicates whether the packet
3030  *      should be sent as regular or control, bits 1-15 select the queue.
3031  */
3032 int t4_ofld_send(struct adapter *adap, struct sk_buff *skb)
3033 {
3034         int ret;
3035
3036         local_bh_disable();
3037         ret = uld_send(adap, skb, CXGB4_TX_OFLD);
3038         local_bh_enable();
3039         return ret;
3040 }
3041
3042 /**
3043  *      cxgb4_ofld_send - send an offload packet
3044  *      @dev: the net device
3045  *      @skb: the packet
3046  *
3047  *      Sends an offload packet.  This is an exported version of @t4_ofld_send,
3048  *      intended for ULDs.
3049  */
3050 int cxgb4_ofld_send(struct net_device *dev, struct sk_buff *skb)
3051 {
3052         return t4_ofld_send(netdev2adap(dev), skb);
3053 }
3054 EXPORT_SYMBOL(cxgb4_ofld_send);
3055
3056 static void *inline_tx_header(const void *src,
3057                               const struct sge_txq *q,
3058                               void *pos, int length)
3059 {
3060         int left = (void *)q->stat - pos;
3061         u64 *p;
3062
3063         if (likely(length <= left)) {
3064                 memcpy(pos, src, length);
3065                 pos += length;
3066         } else {
3067                 memcpy(pos, src, left);
3068                 memcpy(q->desc, src + left, length - left);
3069                 pos = (void *)q->desc + (length - left);
3070         }
3071         /* 0-pad to multiple of 16 */
3072         p = PTR_ALIGN(pos, 8);
3073         if ((uintptr_t)p & 8) {
3074                 *p = 0;
3075                 return p + 1;
3076         }
3077         return p;
3078 }
3079
3080 /**
3081  *      ofld_xmit_direct - copy a WR into offload queue
3082  *      @q: the Tx offload queue
3083  *      @src: location of WR
3084  *      @len: WR length
3085  *
3086  *      Copy an immediate WR into an uncontended SGE offload queue.
3087  */
3088 static int ofld_xmit_direct(struct sge_uld_txq *q, const void *src,
3089                             unsigned int len)
3090 {
3091         unsigned int ndesc;
3092         int credits;
3093         u64 *pos;
3094
3095         /* Use the lower limit as the cut-off */
3096         if (len > MAX_IMM_OFLD_TX_DATA_WR_LEN) {
3097                 WARN_ON(1);
3098                 return NET_XMIT_DROP;
3099         }
3100
3101         /* Don't return NET_XMIT_CN here as the current
3102          * implementation doesn't queue the request
3103          * using an skb when the following conditions not met
3104          */
3105         if (!spin_trylock(&q->sendq.lock))
3106                 return NET_XMIT_DROP;
3107
3108         if (q->full || !skb_queue_empty(&q->sendq) ||
3109             q->service_ofldq_running) {
3110                 spin_unlock(&q->sendq.lock);
3111                 return NET_XMIT_DROP;
3112         }
3113         ndesc = flits_to_desc(DIV_ROUND_UP(len, 8));
3114         credits = txq_avail(&q->q) - ndesc;
3115         pos = (u64 *)&q->q.desc[q->q.pidx];
3116
3117         /* ofldtxq_stop modifies WR header in-situ */
3118         inline_tx_header(src, &q->q, pos, len);
3119         if (unlikely(credits < TXQ_STOP_THRES))
3120                 ofldtxq_stop(q, (struct fw_wr_hdr *)pos);
3121         txq_advance(&q->q, ndesc);
3122         cxgb4_ring_tx_db(q->adap, &q->q, ndesc);
3123
3124         spin_unlock(&q->sendq.lock);
3125         return NET_XMIT_SUCCESS;
3126 }
3127
3128 int cxgb4_immdata_send(struct net_device *dev, unsigned int idx,
3129                        const void *src, unsigned int len)
3130 {
3131         struct sge_uld_txq_info *txq_info;
3132         struct sge_uld_txq *txq;
3133         struct adapter *adap;
3134         int ret;
3135
3136         adap = netdev2adap(dev);
3137
3138         local_bh_disable();
3139         txq_info = adap->sge.uld_txq_info[CXGB4_TX_OFLD];
3140         if (unlikely(!txq_info)) {
3141                 WARN_ON(true);
3142                 local_bh_enable();
3143                 return NET_XMIT_DROP;
3144         }
3145         txq = &txq_info->uldtxq[idx];
3146
3147         ret = ofld_xmit_direct(txq, src, len);
3148         local_bh_enable();
3149         return net_xmit_eval(ret);
3150 }
3151 EXPORT_SYMBOL(cxgb4_immdata_send);
3152
3153 /**
3154  *      t4_crypto_send - send crypto packet
3155  *      @adap: the adapter
3156  *      @skb: the packet
3157  *
3158  *      Sends crypto packet.  We use the packet queue_mapping to select the
3159  *      appropriate Tx queue as follows: bit 0 indicates whether the packet
3160  *      should be sent as regular or control, bits 1-15 select the queue.
3161  */
3162 static int t4_crypto_send(struct adapter *adap, struct sk_buff *skb)
3163 {
3164         int ret;
3165
3166         local_bh_disable();
3167         ret = uld_send(adap, skb, CXGB4_TX_CRYPTO);
3168         local_bh_enable();
3169         return ret;
3170 }
3171
3172 /**
3173  *      cxgb4_crypto_send - send crypto packet
3174  *      @dev: the net device
3175  *      @skb: the packet
3176  *
3177  *      Sends crypto packet.  This is an exported version of @t4_crypto_send,
3178  *      intended for ULDs.
3179  */
3180 int cxgb4_crypto_send(struct net_device *dev, struct sk_buff *skb)
3181 {
3182         return t4_crypto_send(netdev2adap(dev), skb);
3183 }
3184 EXPORT_SYMBOL(cxgb4_crypto_send);
3185
3186 static inline void copy_frags(struct sk_buff *skb,
3187                               const struct pkt_gl *gl, unsigned int offset)
3188 {
3189         int i;
3190
3191         /* usually there's just one frag */
3192         __skb_fill_page_desc(skb, 0, gl->frags[0].page,
3193                              gl->frags[0].offset + offset,
3194                              gl->frags[0].size - offset);
3195         skb_shinfo(skb)->nr_frags = gl->nfrags;
3196         for (i = 1; i < gl->nfrags; i++)
3197                 __skb_fill_page_desc(skb, i, gl->frags[i].page,
3198                                      gl->frags[i].offset,
3199                                      gl->frags[i].size);
3200
3201         /* get a reference to the last page, we don't own it */
3202         get_page(gl->frags[gl->nfrags - 1].page);
3203 }
3204
3205 /**
3206  *      cxgb4_pktgl_to_skb - build an sk_buff from a packet gather list
3207  *      @gl: the gather list
3208  *      @skb_len: size of sk_buff main body if it carries fragments
3209  *      @pull_len: amount of data to move to the sk_buff's main body
3210  *
3211  *      Builds an sk_buff from the given packet gather list.  Returns the
3212  *      sk_buff or %NULL if sk_buff allocation failed.
3213  */
3214 struct sk_buff *cxgb4_pktgl_to_skb(const struct pkt_gl *gl,
3215                                    unsigned int skb_len, unsigned int pull_len)
3216 {
3217         struct sk_buff *skb;
3218
3219         /*
3220          * Below we rely on RX_COPY_THRES being less than the smallest Rx buffer
3221          * size, which is expected since buffers are at least PAGE_SIZEd.
3222          * In this case packets up to RX_COPY_THRES have only one fragment.
3223          */
3224         if (gl->tot_len <= RX_COPY_THRES) {
3225                 skb = dev_alloc_skb(gl->tot_len);
3226                 if (unlikely(!skb))
3227                         goto out;
3228                 __skb_put(skb, gl->tot_len);
3229                 skb_copy_to_linear_data(skb, gl->va, gl->tot_len);
3230         } else {
3231                 skb = dev_alloc_skb(skb_len);
3232                 if (unlikely(!skb))
3233                         goto out;
3234                 __skb_put(skb, pull_len);
3235                 skb_copy_to_linear_data(skb, gl->va, pull_len);
3236
3237                 copy_frags(skb, gl, pull_len);
3238                 skb->len = gl->tot_len;
3239                 skb->data_len = skb->len - pull_len;
3240                 skb->truesize += skb->data_len;
3241         }
3242 out:    return skb;
3243 }
3244 EXPORT_SYMBOL(cxgb4_pktgl_to_skb);
3245
3246 /**
3247  *      t4_pktgl_free - free a packet gather list
3248  *      @gl: the gather list
3249  *
3250  *      Releases the pages of a packet gather list.  We do not own the last
3251  *      page on the list and do not free it.
3252  */
3253 static void t4_pktgl_free(const struct pkt_gl *gl)
3254 {
3255         int n;
3256         const struct page_frag *p;
3257
3258         for (p = gl->frags, n = gl->nfrags - 1; n--; p++)
3259                 put_page(p->page);
3260 }
3261
3262 /*
3263  * Process an MPS trace packet.  Give it an unused protocol number so it won't
3264  * be delivered to anyone and send it to the stack for capture.
3265  */
3266 static noinline int handle_trace_pkt(struct adapter *adap,
3267                                      const struct pkt_gl *gl)
3268 {
3269         struct sk_buff *skb;
3270
3271         skb = cxgb4_pktgl_to_skb(gl, RX_PULL_LEN, RX_PULL_LEN);
3272         if (unlikely(!skb)) {
3273                 t4_pktgl_free(gl);
3274                 return 0;
3275         }
3276
3277         if (is_t4(adap->params.chip))
3278                 __skb_pull(skb, sizeof(struct cpl_trace_pkt));
3279         else
3280                 __skb_pull(skb, sizeof(struct cpl_t5_trace_pkt));
3281
3282         skb_reset_mac_header(skb);
3283         skb->protocol = htons(0xffff);
3284         skb->dev = adap->port[0];
3285         netif_receive_skb(skb);
3286         return 0;
3287 }
3288
3289 /**
3290  * cxgb4_sgetim_to_hwtstamp - convert sge time stamp to hw time stamp
3291  * @adap: the adapter
3292  * @hwtstamps: time stamp structure to update
3293  * @sgetstamp: 60bit iqe timestamp
3294  *
3295  * Every ingress queue entry has the 60-bit timestamp, convert that timestamp
3296  * which is in Core Clock ticks into ktime_t and assign it
3297  **/
3298 static void cxgb4_sgetim_to_hwtstamp(struct adapter *adap,
3299                                      struct skb_shared_hwtstamps *hwtstamps,
3300                                      u64 sgetstamp)
3301 {
3302         u64 ns;
3303         u64 tmp = (sgetstamp * 1000 * 1000 + adap->params.vpd.cclk / 2);
3304
3305         ns = div_u64(tmp, adap->params.vpd.cclk);
3306
3307         memset(hwtstamps, 0, sizeof(*hwtstamps));
3308         hwtstamps->hwtstamp = ns_to_ktime(ns);
3309 }
3310
3311 static void do_gro(struct sge_eth_rxq *rxq, const struct pkt_gl *gl,
3312                    const struct cpl_rx_pkt *pkt, unsigned long tnl_hdr_len)
3313 {
3314         struct adapter *adapter = rxq->rspq.adap;
3315         struct sge *s = &adapter->sge;
3316         struct port_info *pi;
3317         int ret;
3318         struct sk_buff *skb;
3319
3320         skb = napi_get_frags(&rxq->rspq.napi);
3321         if (unlikely(!skb)) {
3322                 t4_pktgl_free(gl);
3323                 rxq->stats.rx_drops++;
3324                 return;
3325         }
3326
3327         copy_frags(skb, gl, s->pktshift);
3328         if (tnl_hdr_len)
3329                 skb->csum_level = 1;
3330         skb->len = gl->tot_len - s->pktshift;
3331         skb->data_len = skb->len;
3332         skb->truesize += skb->data_len;
3333         skb->ip_summed = CHECKSUM_UNNECESSARY;
3334         skb_record_rx_queue(skb, rxq->rspq.idx);
3335         pi = netdev_priv(skb->dev);
3336         if (pi->rxtstamp)
3337                 cxgb4_sgetim_to_hwtstamp(adapter, skb_hwtstamps(skb),
3338                                          gl->sgetstamp);
3339         if (rxq->rspq.netdev->features & NETIF_F_RXHASH)
3340                 skb_set_hash(skb, (__force u32)pkt->rsshdr.hash_val,
3341                              PKT_HASH_TYPE_L3);
3342
3343         if (unlikely(pkt->vlan_ex)) {
3344                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(pkt->vlan));
3345                 rxq->stats.vlan_ex++;
3346         }
3347         ret = napi_gro_frags(&rxq->rspq.napi);
3348         if (ret == GRO_HELD)
3349                 rxq->stats.lro_pkts++;
3350         else if (ret == GRO_MERGED || ret == GRO_MERGED_FREE)
3351                 rxq->stats.lro_merged++;
3352         rxq->stats.pkts++;
3353         rxq->stats.rx_cso++;
3354 }
3355
3356 enum {
3357         RX_NON_PTP_PKT = 0,
3358         RX_PTP_PKT_SUC = 1,
3359         RX_PTP_PKT_ERR = 2
3360 };
3361
3362 /**
3363  *     t4_systim_to_hwstamp - read hardware time stamp
3364  *     @adapter: the adapter
3365  *     @skb: the packet
3366  *
3367  *     Read Time Stamp from MPS packet and insert in skb which
3368  *     is forwarded to PTP application
3369  */
3370 static noinline int t4_systim_to_hwstamp(struct adapter *adapter,
3371                                          struct sk_buff *skb)
3372 {
3373         struct skb_shared_hwtstamps *hwtstamps;
3374         struct cpl_rx_mps_pkt *cpl = NULL;
3375         unsigned char *data;
3376         int offset;
3377
3378         cpl = (struct cpl_rx_mps_pkt *)skb->data;
3379         if (!(CPL_RX_MPS_PKT_TYPE_G(ntohl(cpl->op_to_r1_hi)) &
3380              X_CPL_RX_MPS_PKT_TYPE_PTP))
3381                 return RX_PTP_PKT_ERR;
3382
3383         data = skb->data + sizeof(*cpl);
3384         skb_pull(skb, 2 * sizeof(u64) + sizeof(struct cpl_rx_mps_pkt));
3385         offset = ETH_HLEN + IPV4_HLEN(skb->data) + UDP_HLEN;
3386         if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(short))
3387                 return RX_PTP_PKT_ERR;
3388
3389         hwtstamps = skb_hwtstamps(skb);
3390         memset(hwtstamps, 0, sizeof(*hwtstamps));
3391         hwtstamps->hwtstamp = ns_to_ktime(get_unaligned_be64(data));
3392
3393         return RX_PTP_PKT_SUC;
3394 }
3395
3396 /**
3397  *     t4_rx_hststamp - Recv PTP Event Message
3398  *     @adapter: the adapter
3399  *     @rsp: the response queue descriptor holding the RX_PKT message
3400  *     @rxq: the response queue holding the RX_PKT message
3401  *     @skb: the packet
3402  *
3403  *     PTP enabled and MPS packet, read HW timestamp
3404  */
3405 static int t4_rx_hststamp(struct adapter *adapter, const __be64 *rsp,
3406                           struct sge_eth_rxq *rxq, struct sk_buff *skb)
3407 {
3408         int ret;
3409
3410         if (unlikely((*(u8 *)rsp == CPL_RX_MPS_PKT) &&
3411                      !is_t4(adapter->params.chip))) {
3412                 ret = t4_systim_to_hwstamp(adapter, skb);
3413                 if (ret == RX_PTP_PKT_ERR) {
3414                         kfree_skb(skb);
3415                         rxq->stats.rx_drops++;
3416                 }
3417                 return ret;
3418         }
3419         return RX_NON_PTP_PKT;
3420 }
3421
3422 /**
3423  *      t4_tx_hststamp - Loopback PTP Transmit Event Message
3424  *      @adapter: the adapter
3425  *      @skb: the packet
3426  *      @dev: the ingress net device
3427  *
3428  *      Read hardware timestamp for the loopback PTP Tx event message
3429  */
3430 static int t4_tx_hststamp(struct adapter *adapter, struct sk_buff *skb,
3431                           struct net_device *dev)
3432 {
3433         struct port_info *pi = netdev_priv(dev);
3434
3435         if (!is_t4(adapter->params.chip) && adapter->ptp_tx_skb) {
3436                 cxgb4_ptp_read_hwstamp(adapter, pi);
3437                 kfree_skb(skb);
3438                 return 0;
3439         }
3440         return 1;
3441 }
3442
3443 /**
3444  *      t4_tx_completion_handler - handle CPL_SGE_EGR_UPDATE messages
3445  *      @rspq: Ethernet RX Response Queue associated with Ethernet TX Queue
3446  *      @rsp: Response Entry pointer into Response Queue
3447  *      @gl: Gather List pointer
3448  *
3449  *      For adapters which support the SGE Doorbell Queue Timer facility,
3450  *      we configure the Ethernet TX Queues to send CIDX Updates to the
3451  *      Associated Ethernet RX Response Queue with CPL_SGE_EGR_UPDATE
3452  *      messages.  This adds a small load to PCIe Link RX bandwidth and,
3453  *      potentially, higher CPU Interrupt load, but allows us to respond
3454  *      much more quickly to the CIDX Updates.  This is important for
3455  *      Upper Layer Software which isn't willing to have a large amount
3456  *      of TX Data outstanding before receiving DMA Completions.
3457  */
3458 static void t4_tx_completion_handler(struct sge_rspq *rspq,
3459                                      const __be64 *rsp,
3460                                      const struct pkt_gl *gl)
3461 {
3462         u8 opcode = ((const struct rss_header *)rsp)->opcode;
3463         struct port_info *pi = netdev_priv(rspq->netdev);
3464         struct adapter *adapter = rspq->adap;
3465         struct sge *s = &adapter->sge;
3466         struct sge_eth_txq *txq;
3467
3468         /* skip RSS header */
3469         rsp++;
3470
3471         /* FW can send EGR_UPDATEs encapsulated in a CPL_FW4_MSG.
3472          */
3473         if (unlikely(opcode == CPL_FW4_MSG &&
3474                      ((const struct cpl_fw4_msg *)rsp)->type ==
3475                                                         FW_TYPE_RSSCPL)) {
3476                 rsp++;
3477                 opcode = ((const struct rss_header *)rsp)->opcode;
3478                 rsp++;
3479         }
3480
3481         if (unlikely(opcode != CPL_SGE_EGR_UPDATE)) {
3482                 pr_info("%s: unexpected FW4/CPL %#x on Rx queue\n",
3483                         __func__, opcode);
3484                 return;
3485         }
3486
3487         txq = &s->ethtxq[pi->first_qset + rspq->idx];
3488         t4_sge_eth_txq_egress_update(adapter, txq, -1);
3489 }
3490
3491 static int cxgb4_validate_lb_pkt(struct port_info *pi, const struct pkt_gl *si)
3492 {
3493         struct adapter *adap = pi->adapter;
3494         struct cxgb4_ethtool_lb_test *lb;
3495         struct sge *s = &adap->sge;
3496         struct net_device *netdev;
3497         u8 *data;
3498         int i;
3499
3500         netdev = adap->port[pi->port_id];
3501         lb = &pi->ethtool_lb;
3502         data = si->va + s->pktshift;
3503
3504         i = ETH_ALEN;
3505         if (!ether_addr_equal(data + i, netdev->dev_addr))
3506                 return -1;
3507
3508         i += ETH_ALEN;
3509         if (strcmp(&data[i], CXGB4_SELFTEST_LB_STR))
3510                 lb->result = -EIO;
3511
3512         complete(&lb->completion);
3513         return 0;
3514 }
3515
3516 /**
3517  *      t4_ethrx_handler - process an ingress ethernet packet
3518  *      @q: the response queue that received the packet
3519  *      @rsp: the response queue descriptor holding the RX_PKT message
3520  *      @si: the gather list of packet fragments
3521  *
3522  *      Process an ingress ethernet packet and deliver it to the stack.
3523  */
3524 int t4_ethrx_handler(struct sge_rspq *q, const __be64 *rsp,
3525                      const struct pkt_gl *si)
3526 {
3527         bool csum_ok;
3528         struct sk_buff *skb;
3529         const struct cpl_rx_pkt *pkt;
3530         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
3531         struct adapter *adapter = q->adap;
3532         struct sge *s = &q->adap->sge;
3533         int cpl_trace_pkt = is_t4(q->adap->params.chip) ?
3534                             CPL_TRACE_PKT : CPL_TRACE_PKT_T5;
3535         u16 err_vec, tnl_hdr_len = 0;
3536         struct port_info *pi;
3537         int ret = 0;
3538
3539         pi = netdev_priv(q->netdev);
3540         /* If we're looking at TX Queue CIDX Update, handle that separately
3541          * and return.
3542          */
3543         if (unlikely((*(u8 *)rsp == CPL_FW4_MSG) ||
3544                      (*(u8 *)rsp == CPL_SGE_EGR_UPDATE))) {
3545                 t4_tx_completion_handler(q, rsp, si);
3546                 return 0;
3547         }
3548
3549         if (unlikely(*(u8 *)rsp == cpl_trace_pkt))
3550                 return handle_trace_pkt(q->adap, si);
3551
3552         pkt = (const struct cpl_rx_pkt *)rsp;
3553         /* Compressed error vector is enabled for T6 only */
3554         if (q->adap->params.tp.rx_pkt_encap) {
3555                 err_vec = T6_COMPR_RXERR_VEC_G(be16_to_cpu(pkt->err_vec));
3556                 tnl_hdr_len = T6_RX_TNLHDR_LEN_G(ntohs(pkt->err_vec));
3557         } else {
3558                 err_vec = be16_to_cpu(pkt->err_vec);
3559         }
3560
3561         csum_ok = pkt->csum_calc && !err_vec &&
3562                   (q->netdev->features & NETIF_F_RXCSUM);
3563
3564         if (err_vec)
3565                 rxq->stats.bad_rx_pkts++;
3566
3567         if (unlikely(pi->ethtool_lb.loopback && pkt->iff >= NCHAN)) {
3568                 ret = cxgb4_validate_lb_pkt(pi, si);
3569                 if (!ret)
3570                         return 0;
3571         }
3572
3573         if (((pkt->l2info & htonl(RXF_TCP_F)) ||
3574              tnl_hdr_len) &&
3575             (q->netdev->features & NETIF_F_GRO) && csum_ok && !pkt->ip_frag) {
3576                 do_gro(rxq, si, pkt, tnl_hdr_len);
3577                 return 0;
3578         }
3579
3580         skb = cxgb4_pktgl_to_skb(si, RX_PKT_SKB_LEN, RX_PULL_LEN);
3581         if (unlikely(!skb)) {
3582                 t4_pktgl_free(si);
3583                 rxq->stats.rx_drops++;
3584                 return 0;
3585         }
3586
3587         /* Handle PTP Event Rx packet */
3588         if (unlikely(pi->ptp_enable)) {
3589                 ret = t4_rx_hststamp(adapter, rsp, rxq, skb);
3590                 if (ret == RX_PTP_PKT_ERR)
3591                         return 0;
3592         }
3593         if (likely(!ret))
3594                 __skb_pull(skb, s->pktshift); /* remove ethernet header pad */
3595
3596         /* Handle the PTP Event Tx Loopback packet */
3597         if (unlikely(pi->ptp_enable && !ret &&
3598                      (pkt->l2info & htonl(RXF_UDP_F)) &&
3599                      cxgb4_ptp_is_ptp_rx(skb))) {
3600                 if (!t4_tx_hststamp(adapter, skb, q->netdev))
3601                         return 0;
3602         }
3603
3604         skb->protocol = eth_type_trans(skb, q->netdev);
3605         skb_record_rx_queue(skb, q->idx);
3606         if (skb->dev->features & NETIF_F_RXHASH)
3607                 skb_set_hash(skb, (__force u32)pkt->rsshdr.hash_val,
3608                              PKT_HASH_TYPE_L3);
3609
3610         rxq->stats.pkts++;
3611
3612         if (pi->rxtstamp)
3613                 cxgb4_sgetim_to_hwtstamp(q->adap, skb_hwtstamps(skb),
3614                                          si->sgetstamp);
3615         if (csum_ok && (pkt->l2info & htonl(RXF_UDP_F | RXF_TCP_F))) {
3616                 if (!pkt->ip_frag) {
3617                         skb->ip_summed = CHECKSUM_UNNECESSARY;
3618                         rxq->stats.rx_cso++;
3619                 } else if (pkt->l2info & htonl(RXF_IP_F)) {
3620                         __sum16 c = (__force __sum16)pkt->csum;
3621                         skb->csum = csum_unfold(c);
3622
3623                         if (tnl_hdr_len) {
3624                                 skb->ip_summed = CHECKSUM_UNNECESSARY;
3625                                 skb->csum_level = 1;
3626                         } else {
3627                                 skb->ip_summed = CHECKSUM_COMPLETE;
3628                         }
3629                         rxq->stats.rx_cso++;
3630                 }
3631         } else {
3632                 skb_checksum_none_assert(skb);
3633 #ifdef CONFIG_CHELSIO_T4_FCOE
3634 #define CPL_RX_PKT_FLAGS (RXF_PSH_F | RXF_SYN_F | RXF_UDP_F | \
3635                           RXF_TCP_F | RXF_IP_F | RXF_IP6_F | RXF_LRO_F)
3636
3637                 if (!(pkt->l2info & cpu_to_be32(CPL_RX_PKT_FLAGS))) {
3638                         if ((pkt->l2info & cpu_to_be32(RXF_FCOE_F)) &&
3639                             (pi->fcoe.flags & CXGB_FCOE_ENABLED)) {
3640                                 if (q->adap->params.tp.rx_pkt_encap)
3641                                         csum_ok = err_vec &
3642                                                   T6_COMPR_RXERR_SUM_F;
3643                                 else
3644                                         csum_ok = err_vec & RXERR_CSUM_F;
3645                                 if (!csum_ok)
3646                                         skb->ip_summed = CHECKSUM_UNNECESSARY;
3647                         }
3648                 }
3649
3650 #undef CPL_RX_PKT_FLAGS
3651 #endif /* CONFIG_CHELSIO_T4_FCOE */
3652         }
3653
3654         if (unlikely(pkt->vlan_ex)) {
3655                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(pkt->vlan));
3656                 rxq->stats.vlan_ex++;
3657         }
3658         skb_mark_napi_id(skb, &q->napi);
3659         netif_receive_skb(skb);
3660         return 0;
3661 }
3662
3663 /**
3664  *      restore_rx_bufs - put back a packet's Rx buffers
3665  *      @si: the packet gather list
3666  *      @q: the SGE free list
3667  *      @frags: number of FL buffers to restore
3668  *
3669  *      Puts back on an FL the Rx buffers associated with @si.  The buffers
3670  *      have already been unmapped and are left unmapped, we mark them so to
3671  *      prevent further unmapping attempts.
3672  *
3673  *      This function undoes a series of @unmap_rx_buf calls when we find out
3674  *      that the current packet can't be processed right away afterall and we
3675  *      need to come back to it later.  This is a very rare event and there's
3676  *      no effort to make this particularly efficient.
3677  */
3678 static void restore_rx_bufs(const struct pkt_gl *si, struct sge_fl *q,
3679                             int frags)
3680 {
3681         struct rx_sw_desc *d;
3682
3683         while (frags--) {
3684                 if (q->cidx == 0)
3685                         q->cidx = q->size - 1;
3686                 else
3687                         q->cidx--;
3688                 d = &q->sdesc[q->cidx];
3689                 d->page = si->frags[frags].page;
3690                 d->dma_addr |= RX_UNMAPPED_BUF;
3691                 q->avail++;
3692         }
3693 }
3694
3695 /**
3696  *      is_new_response - check if a response is newly written
3697  *      @r: the response descriptor
3698  *      @q: the response queue
3699  *
3700  *      Returns true if a response descriptor contains a yet unprocessed
3701  *      response.
3702  */
3703 static inline bool is_new_response(const struct rsp_ctrl *r,
3704                                    const struct sge_rspq *q)
3705 {
3706         return (r->type_gen >> RSPD_GEN_S) == q->gen;
3707 }
3708
3709 /**
3710  *      rspq_next - advance to the next entry in a response queue
3711  *      @q: the queue
3712  *
3713  *      Updates the state of a response queue to advance it to the next entry.
3714  */
3715 static inline void rspq_next(struct sge_rspq *q)
3716 {
3717         q->cur_desc = (void *)q->cur_desc + q->iqe_len;
3718         if (unlikely(++q->cidx == q->size)) {
3719                 q->cidx = 0;
3720                 q->gen ^= 1;
3721                 q->cur_desc = q->desc;
3722         }
3723 }
3724
3725 /**
3726  *      process_responses - process responses from an SGE response queue
3727  *      @q: the ingress queue to process
3728  *      @budget: how many responses can be processed in this round
3729  *
3730  *      Process responses from an SGE response queue up to the supplied budget.
3731  *      Responses include received packets as well as control messages from FW
3732  *      or HW.
3733  *
3734  *      Additionally choose the interrupt holdoff time for the next interrupt
3735  *      on this queue.  If the system is under memory shortage use a fairly
3736  *      long delay to help recovery.
3737  */
3738 static int process_responses(struct sge_rspq *q, int budget)
3739 {
3740         int ret, rsp_type;
3741         int budget_left = budget;
3742         const struct rsp_ctrl *rc;
3743         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
3744         struct adapter *adapter = q->adap;
3745         struct sge *s = &adapter->sge;
3746
3747         while (likely(budget_left)) {
3748                 rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
3749                 if (!is_new_response(rc, q)) {
3750                         if (q->flush_handler)
3751                                 q->flush_handler(q);
3752                         break;
3753                 }
3754
3755                 dma_rmb();
3756                 rsp_type = RSPD_TYPE_G(rc->type_gen);
3757                 if (likely(rsp_type == RSPD_TYPE_FLBUF_X)) {
3758                         struct page_frag *fp;
3759                         struct pkt_gl si;
3760                         const struct rx_sw_desc *rsd;
3761                         u32 len = ntohl(rc->pldbuflen_qid), bufsz, frags;
3762
3763                         if (len & RSPD_NEWBUF_F) {
3764                                 if (likely(q->offset > 0)) {
3765                                         free_rx_bufs(q->adap, &rxq->fl, 1);
3766                                         q->offset = 0;
3767                                 }
3768                                 len = RSPD_LEN_G(len);
3769                         }
3770                         si.tot_len = len;
3771
3772                         /* gather packet fragments */
3773                         for (frags = 0, fp = si.frags; ; frags++, fp++) {
3774                                 rsd = &rxq->fl.sdesc[rxq->fl.cidx];
3775                                 bufsz = get_buf_size(adapter, rsd);
3776                                 fp->page = rsd->page;
3777                                 fp->offset = q->offset;
3778                                 fp->size = min(bufsz, len);
3779                                 len -= fp->size;
3780                                 if (!len)
3781                                         break;
3782                                 unmap_rx_buf(q->adap, &rxq->fl);
3783                         }
3784
3785                         si.sgetstamp = SGE_TIMESTAMP_G(
3786                                         be64_to_cpu(rc->last_flit));
3787                         /*
3788                          * Last buffer remains mapped so explicitly make it
3789                          * coherent for CPU access.
3790                          */
3791                         dma_sync_single_for_cpu(q->adap->pdev_dev,
3792                                                 get_buf_addr(rsd),
3793                                                 fp->size, DMA_FROM_DEVICE);
3794
3795                         si.va = page_address(si.frags[0].page) +
3796                                 si.frags[0].offset;
3797                         prefetch(si.va);
3798
3799                         si.nfrags = frags + 1;
3800                         ret = q->handler(q, q->cur_desc, &si);
3801                         if (likely(ret == 0))
3802                                 q->offset += ALIGN(fp->size, s->fl_align);
3803                         else
3804                                 restore_rx_bufs(&si, &rxq->fl, frags);
3805                 } else if (likely(rsp_type == RSPD_TYPE_CPL_X)) {
3806                         ret = q->handler(q, q->cur_desc, NULL);
3807                 } else {
3808                         ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
3809                 }
3810
3811                 if (unlikely(ret)) {
3812                         /* couldn't process descriptor, back off for recovery */
3813                         q->next_intr_params = QINTR_TIMER_IDX_V(NOMEM_TMR_IDX);
3814                         break;
3815                 }
3816
3817                 rspq_next(q);
3818                 budget_left--;
3819         }
3820
3821         if (q->offset >= 0 && fl_cap(&rxq->fl) - rxq->fl.avail >= 16)
3822                 __refill_fl(q->adap, &rxq->fl);
3823         return budget - budget_left;
3824 }
3825
3826 /**
3827  *      napi_rx_handler - the NAPI handler for Rx processing
3828  *      @napi: the napi instance
3829  *      @budget: how many packets we can process in this round
3830  *
3831  *      Handler for new data events when using NAPI.  This does not need any
3832  *      locking or protection from interrupts as data interrupts are off at
3833  *      this point and other adapter interrupts do not interfere (the latter
3834  *      in not a concern at all with MSI-X as non-data interrupts then have
3835  *      a separate handler).
3836  */
3837 static int napi_rx_handler(struct napi_struct *napi, int budget)
3838 {
3839         unsigned int params;
3840         struct sge_rspq *q = container_of(napi, struct sge_rspq, napi);
3841         int work_done;
3842         u32 val;
3843
3844         work_done = process_responses(q, budget);
3845         if (likely(work_done < budget)) {
3846                 int timer_index;
3847
3848                 napi_complete_done(napi, work_done);
3849                 timer_index = QINTR_TIMER_IDX_G(q->next_intr_params);
3850
3851                 if (q->adaptive_rx) {
3852                         if (work_done > max(timer_pkt_quota[timer_index],
3853                                             MIN_NAPI_WORK))
3854                                 timer_index = (timer_index + 1);
3855                         else
3856                                 timer_index = timer_index - 1;
3857
3858                         timer_index = clamp(timer_index, 0, SGE_TIMERREGS - 1);
3859                         q->next_intr_params =
3860                                         QINTR_TIMER_IDX_V(timer_index) |
3861                                         QINTR_CNT_EN_V(0);
3862                         params = q->next_intr_params;
3863                 } else {
3864                         params = q->next_intr_params;
3865                         q->next_intr_params = q->intr_params;
3866                 }
3867         } else
3868                 params = QINTR_TIMER_IDX_V(7);
3869
3870         val = CIDXINC_V(work_done) | SEINTARM_V(params);
3871
3872         /* If we don't have access to the new User GTS (T5+), use the old
3873          * doorbell mechanism; otherwise use the new BAR2 mechanism.
3874          */
3875         if (unlikely(q->bar2_addr == NULL)) {
3876                 t4_write_reg(q->adap, MYPF_REG(SGE_PF_GTS_A),
3877                              val | INGRESSQID_V((u32)q->cntxt_id));
3878         } else {
3879                 writel(val | INGRESSQID_V(q->bar2_qid),
3880                        q->bar2_addr + SGE_UDB_GTS);
3881                 wmb();
3882         }
3883         return work_done;
3884 }
3885
3886 void cxgb4_ethofld_restart(unsigned long data)
3887 {
3888         struct sge_eosw_txq *eosw_txq = (struct sge_eosw_txq *)data;
3889         int pktcount;
3890
3891         spin_lock(&eosw_txq->lock);
3892         pktcount = eosw_txq->cidx - eosw_txq->last_cidx;
3893         if (pktcount < 0)
3894                 pktcount += eosw_txq->ndesc;
3895
3896         if (pktcount) {
3897                 cxgb4_eosw_txq_free_desc(netdev2adap(eosw_txq->netdev),
3898                                          eosw_txq, pktcount);
3899                 eosw_txq->inuse -= pktcount;
3900         }
3901
3902         /* There may be some packets waiting for completions. So,
3903          * attempt to send these packets now.
3904          */
3905         ethofld_xmit(eosw_txq->netdev, eosw_txq);
3906         spin_unlock(&eosw_txq->lock);
3907 }
3908
3909 /* cxgb4_ethofld_rx_handler - Process ETHOFLD Tx completions
3910  * @q: the response queue that received the packet
3911  * @rsp: the response queue descriptor holding the CPL message
3912  * @si: the gather list of packet fragments
3913  *
3914  * Process a ETHOFLD Tx completion. Increment the cidx here, but
3915  * free up the descriptors in a tasklet later.
3916  */
3917 int cxgb4_ethofld_rx_handler(struct sge_rspq *q, const __be64 *rsp,
3918                              const struct pkt_gl *si)
3919 {
3920         u8 opcode = ((const struct rss_header *)rsp)->opcode;
3921
3922         /* skip RSS header */
3923         rsp++;
3924
3925         if (opcode == CPL_FW4_ACK) {
3926                 const struct cpl_fw4_ack *cpl;
3927                 struct sge_eosw_txq *eosw_txq;
3928                 struct eotid_entry *entry;
3929                 struct sk_buff *skb;
3930                 u32 hdr_len, eotid;
3931                 u8 flits, wrlen16;
3932                 int credits;
3933
3934                 cpl = (const struct cpl_fw4_ack *)rsp;
3935                 eotid = CPL_FW4_ACK_FLOWID_G(ntohl(OPCODE_TID(cpl))) -
3936                         q->adap->tids.eotid_base;
3937                 entry = cxgb4_lookup_eotid(&q->adap->tids, eotid);
3938                 if (!entry)
3939                         goto out_done;
3940
3941                 eosw_txq = (struct sge_eosw_txq *)entry->data;
3942                 if (!eosw_txq)
3943                         goto out_done;
3944
3945                 spin_lock(&eosw_txq->lock);
3946                 credits = cpl->credits;
3947                 while (credits > 0) {
3948                         skb = eosw_txq->desc[eosw_txq->cidx].skb;
3949                         if (!skb)
3950                                 break;
3951
3952                         if (unlikely((eosw_txq->state ==
3953                                       CXGB4_EO_STATE_FLOWC_OPEN_REPLY ||
3954                                       eosw_txq->state ==
3955                                       CXGB4_EO_STATE_FLOWC_CLOSE_REPLY) &&
3956                                      eosw_txq->cidx == eosw_txq->flowc_idx)) {
3957                                 flits = DIV_ROUND_UP(skb->len, 8);
3958                                 if (eosw_txq->state ==
3959                                     CXGB4_EO_STATE_FLOWC_OPEN_REPLY)
3960                                         eosw_txq->state = CXGB4_EO_STATE_ACTIVE;
3961                                 else
3962                                         eosw_txq->state = CXGB4_EO_STATE_CLOSED;
3963                                 complete(&eosw_txq->completion);
3964                         } else {
3965                                 hdr_len = eth_get_headlen(eosw_txq->netdev,
3966                                                           skb->data,
3967                                                           skb_headlen(skb));
3968                                 flits = ethofld_calc_tx_flits(q->adap, skb,
3969                                                               hdr_len);
3970                         }
3971                         eosw_txq_advance_index(&eosw_txq->cidx, 1,
3972                                                eosw_txq->ndesc);
3973                         wrlen16 = DIV_ROUND_UP(flits * 8, 16);
3974                         credits -= wrlen16;
3975                 }
3976
3977                 eosw_txq->cred += cpl->credits;
3978                 eosw_txq->ncompl--;
3979
3980                 spin_unlock(&eosw_txq->lock);
3981
3982                 /* Schedule a tasklet to reclaim SKBs and restart ETHOFLD Tx,
3983                  * if there were packets waiting for completion.
3984                  */
3985                 tasklet_schedule(&eosw_txq->qresume_tsk);
3986         }
3987
3988 out_done:
3989         return 0;
3990 }
3991
3992 /*
3993  * The MSI-X interrupt handler for an SGE response queue.
3994  */
3995 irqreturn_t t4_sge_intr_msix(int irq, void *cookie)
3996 {
3997         struct sge_rspq *q = cookie;
3998
3999         napi_schedule(&q->napi);
4000         return IRQ_HANDLED;
4001 }
4002
4003 /*
4004  * Process the indirect interrupt entries in the interrupt queue and kick off
4005  * NAPI for each queue that has generated an entry.
4006  */
4007 static unsigned int process_intrq(struct adapter *adap)
4008 {
4009         unsigned int credits;
4010         const struct rsp_ctrl *rc;
4011         struct sge_rspq *q = &adap->sge.intrq;
4012         u32 val;
4013
4014         spin_lock(&adap->sge.intrq_lock);
4015         for (credits = 0; ; credits++) {
4016                 rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
4017                 if (!is_new_response(rc, q))
4018                         break;
4019
4020                 dma_rmb();
4021                 if (RSPD_TYPE_G(rc->type_gen) == RSPD_TYPE_INTR_X) {
4022                         unsigned int qid = ntohl(rc->pldbuflen_qid);
4023
4024                         qid -= adap->sge.ingr_start;
4025                         napi_schedule(&adap->sge.ingr_map[qid]->napi);
4026                 }
4027
4028                 rspq_next(q);
4029         }
4030
4031         val =  CIDXINC_V(credits) | SEINTARM_V(q->intr_params);
4032
4033         /* If we don't have access to the new User GTS (T5+), use the old
4034          * doorbell mechanism; otherwise use the new BAR2 mechanism.
4035          */
4036         if (unlikely(q->bar2_addr == NULL)) {
4037                 t4_write_reg(adap, MYPF_REG(SGE_PF_GTS_A),
4038                              val | INGRESSQID_V(q->cntxt_id));
4039         } else {
4040                 writel(val | INGRESSQID_V(q->bar2_qid),
4041                        q->bar2_addr + SGE_UDB_GTS);
4042                 wmb();
4043         }
4044         spin_unlock(&adap->sge.intrq_lock);
4045         return credits;
4046 }
4047
4048 /*
4049  * The MSI interrupt handler, which handles data events from SGE response queues
4050  * as well as error and other async events as they all use the same MSI vector.
4051  */
4052 static irqreturn_t t4_intr_msi(int irq, void *cookie)
4053 {
4054         struct adapter *adap = cookie;
4055
4056         if (adap->flags & CXGB4_MASTER_PF)
4057                 t4_slow_intr_handler(adap);
4058         process_intrq(adap);
4059         return IRQ_HANDLED;
4060 }
4061
4062 /*
4063  * Interrupt handler for legacy INTx interrupts.
4064  * Handles data events from SGE response queues as well as error and other
4065  * async events as they all use the same interrupt line.
4066  */
4067 static irqreturn_t t4_intr_intx(int irq, void *cookie)
4068 {
4069         struct adapter *adap = cookie;
4070
4071         t4_write_reg(adap, MYPF_REG(PCIE_PF_CLI_A), 0);
4072         if (((adap->flags & CXGB4_MASTER_PF) && t4_slow_intr_handler(adap)) |
4073             process_intrq(adap))
4074                 return IRQ_HANDLED;
4075         return IRQ_NONE;             /* probably shared interrupt */
4076 }
4077
4078 /**
4079  *      t4_intr_handler - select the top-level interrupt handler
4080  *      @adap: the adapter
4081  *
4082  *      Selects the top-level interrupt handler based on the type of interrupts
4083  *      (MSI-X, MSI, or INTx).
4084  */
4085 irq_handler_t t4_intr_handler(struct adapter *adap)
4086 {
4087         if (adap->flags & CXGB4_USING_MSIX)
4088                 return t4_sge_intr_msix;
4089         if (adap->flags & CXGB4_USING_MSI)
4090                 return t4_intr_msi;
4091         return t4_intr_intx;
4092 }
4093
4094 static void sge_rx_timer_cb(struct timer_list *t)
4095 {
4096         unsigned long m;
4097         unsigned int i;
4098         struct adapter *adap = from_timer(adap, t, sge.rx_timer);
4099         struct sge *s = &adap->sge;
4100
4101         for (i = 0; i < BITS_TO_LONGS(s->egr_sz); i++)
4102                 for (m = s->starving_fl[i]; m; m &= m - 1) {
4103                         struct sge_eth_rxq *rxq;
4104                         unsigned int id = __ffs(m) + i * BITS_PER_LONG;
4105                         struct sge_fl *fl = s->egr_map[id];
4106
4107                         clear_bit(id, s->starving_fl);
4108                         smp_mb__after_atomic();
4109
4110                         if (fl_starving(adap, fl)) {
4111                                 rxq = container_of(fl, struct sge_eth_rxq, fl);
4112                                 if (napi_reschedule(&rxq->rspq.napi))
4113                                         fl->starving++;
4114                                 else
4115                                         set_bit(id, s->starving_fl);
4116                         }
4117                 }
4118         /* The remainder of the SGE RX Timer Callback routine is dedicated to
4119          * global Master PF activities like checking for chip ingress stalls,
4120          * etc.
4121          */
4122         if (!(adap->flags & CXGB4_MASTER_PF))
4123                 goto done;
4124
4125         t4_idma_monitor(adap, &s->idma_monitor, HZ, RX_QCHECK_PERIOD);
4126
4127 done:
4128         mod_timer(&s->rx_timer, jiffies + RX_QCHECK_PERIOD);
4129 }
4130
4131 static void sge_tx_timer_cb(struct timer_list *t)
4132 {
4133         struct adapter *adap = from_timer(adap, t, sge.tx_timer);
4134         struct sge *s = &adap->sge;
4135         unsigned long m, period;
4136         unsigned int i, budget;
4137
4138         for (i = 0; i < BITS_TO_LONGS(s->egr_sz); i++)
4139                 for (m = s->txq_maperr[i]; m; m &= m - 1) {
4140                         unsigned long id = __ffs(m) + i * BITS_PER_LONG;
4141                         struct sge_uld_txq *txq = s->egr_map[id];
4142
4143                         clear_bit(id, s->txq_maperr);
4144                         tasklet_schedule(&txq->qresume_tsk);
4145                 }
4146
4147         if (!is_t4(adap->params.chip)) {
4148                 struct sge_eth_txq *q = &s->ptptxq;
4149                 int avail;
4150
4151                 spin_lock(&adap->ptp_lock);
4152                 avail = reclaimable(&q->q);
4153
4154                 if (avail) {
4155                         free_tx_desc(adap, &q->q, avail, false);
4156                         q->q.in_use -= avail;
4157                 }
4158                 spin_unlock(&adap->ptp_lock);
4159         }
4160
4161         budget = MAX_TIMER_TX_RECLAIM;
4162         i = s->ethtxq_rover;
4163         do {
4164                 budget -= t4_sge_eth_txq_egress_update(adap, &s->ethtxq[i],
4165                                                        budget);
4166                 if (!budget)
4167                         break;
4168
4169                 if (++i >= s->ethqsets)
4170                         i = 0;
4171         } while (i != s->ethtxq_rover);
4172         s->ethtxq_rover = i;
4173
4174         if (budget == 0) {
4175                 /* If we found too many reclaimable packets schedule a timer
4176                  * in the near future to continue where we left off.
4177                  */
4178                 period = 2;
4179         } else {
4180                 /* We reclaimed all reclaimable TX Descriptors, so reschedule
4181                  * at the normal period.
4182                  */
4183                 period = TX_QCHECK_PERIOD;
4184         }
4185
4186         mod_timer(&s->tx_timer, jiffies + period);
4187 }
4188
4189 /**
4190  *      bar2_address - return the BAR2 address for an SGE Queue's Registers
4191  *      @adapter: the adapter
4192  *      @qid: the SGE Queue ID
4193  *      @qtype: the SGE Queue Type (Egress or Ingress)
4194  *      @pbar2_qid: BAR2 Queue ID or 0 for Queue ID inferred SGE Queues
4195  *
4196  *      Returns the BAR2 address for the SGE Queue Registers associated with
4197  *      @qid.  If BAR2 SGE Registers aren't available, returns NULL.  Also
4198  *      returns the BAR2 Queue ID to be used with writes to the BAR2 SGE
4199  *      Queue Registers.  If the BAR2 Queue ID is 0, then "Inferred Queue ID"
4200  *      Registers are supported (e.g. the Write Combining Doorbell Buffer).
4201  */
4202 static void __iomem *bar2_address(struct adapter *adapter,
4203                                   unsigned int qid,
4204                                   enum t4_bar2_qtype qtype,
4205                                   unsigned int *pbar2_qid)
4206 {
4207         u64 bar2_qoffset;
4208         int ret;
4209
4210         ret = t4_bar2_sge_qregs(adapter, qid, qtype, 0,
4211                                 &bar2_qoffset, pbar2_qid);
4212         if (ret)
4213                 return NULL;
4214
4215         return adapter->bar2 + bar2_qoffset;
4216 }
4217
4218 /* @intr_idx: MSI/MSI-X vector if >=0, -(absolute qid + 1) if < 0
4219  * @cong: < 0 -> no congestion feedback, >= 0 -> congestion channel map
4220  */
4221 int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
4222                      struct net_device *dev, int intr_idx,
4223                      struct sge_fl *fl, rspq_handler_t hnd,
4224                      rspq_flush_handler_t flush_hnd, int cong)
4225 {
4226         int ret, flsz = 0;
4227         struct fw_iq_cmd c;
4228         struct sge *s = &adap->sge;
4229         struct port_info *pi = netdev_priv(dev);
4230         int relaxed = !(adap->flags & CXGB4_ROOT_NO_RELAXED_ORDERING);
4231
4232         /* Size needs to be multiple of 16, including status entry. */
4233         iq->size = roundup(iq->size, 16);
4234
4235         iq->desc = alloc_ring(adap->pdev_dev, iq->size, iq->iqe_len, 0,
4236                               &iq->phys_addr, NULL, 0,
4237                               dev_to_node(adap->pdev_dev));
4238         if (!iq->desc)
4239                 return -ENOMEM;
4240
4241         memset(&c, 0, sizeof(c));
4242         c.op_to_vfn = htonl(FW_CMD_OP_V(FW_IQ_CMD) | FW_CMD_REQUEST_F |
4243                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
4244                             FW_IQ_CMD_PFN_V(adap->pf) | FW_IQ_CMD_VFN_V(0));
4245         c.alloc_to_len16 = htonl(FW_IQ_CMD_ALLOC_F | FW_IQ_CMD_IQSTART_F |
4246                                  FW_LEN16(c));
4247         c.type_to_iqandstindex = htonl(FW_IQ_CMD_TYPE_V(FW_IQ_TYPE_FL_INT_CAP) |
4248                 FW_IQ_CMD_IQASYNCH_V(fwevtq) | FW_IQ_CMD_VIID_V(pi->viid) |
4249                 FW_IQ_CMD_IQANDST_V(intr_idx < 0) |
4250                 FW_IQ_CMD_IQANUD_V(UPDATEDELIVERY_INTERRUPT_X) |
4251                 FW_IQ_CMD_IQANDSTINDEX_V(intr_idx >= 0 ? intr_idx :
4252                                                         -intr_idx - 1));
4253         c.iqdroprss_to_iqesize = htons(FW_IQ_CMD_IQPCIECH_V(pi->tx_chan) |
4254                 FW_IQ_CMD_IQGTSMODE_F |
4255                 FW_IQ_CMD_IQINTCNTTHRESH_V(iq->pktcnt_idx) |
4256                 FW_IQ_CMD_IQESIZE_V(ilog2(iq->iqe_len) - 4));
4257         c.iqsize = htons(iq->size);
4258         c.iqaddr = cpu_to_be64(iq->phys_addr);
4259         if (cong >= 0)
4260                 c.iqns_to_fl0congen = htonl(FW_IQ_CMD_IQFLINTCONGEN_F |
4261                                 FW_IQ_CMD_IQTYPE_V(cong ? FW_IQ_IQTYPE_NIC
4262                                                         :  FW_IQ_IQTYPE_OFLD));
4263
4264         if (fl) {
4265                 unsigned int chip_ver =
4266                         CHELSIO_CHIP_VERSION(adap->params.chip);
4267
4268                 /* Allocate the ring for the hardware free list (with space
4269                  * for its status page) along with the associated software
4270                  * descriptor ring.  The free list size needs to be a multiple
4271                  * of the Egress Queue Unit and at least 2 Egress Units larger
4272                  * than the SGE's Egress Congrestion Threshold
4273                  * (fl_starve_thres - 1).
4274                  */
4275                 if (fl->size < s->fl_starve_thres - 1 + 2 * 8)
4276                         fl->size = s->fl_starve_thres - 1 + 2 * 8;
4277                 fl->size = roundup(fl->size, 8);
4278                 fl->desc = alloc_ring(adap->pdev_dev, fl->size, sizeof(__be64),
4279                                       sizeof(struct rx_sw_desc), &fl->addr,
4280                                       &fl->sdesc, s->stat_len,
4281                                       dev_to_node(adap->pdev_dev));
4282                 if (!fl->desc)
4283                         goto fl_nomem;
4284
4285                 flsz = fl->size / 8 + s->stat_len / sizeof(struct tx_desc);
4286                 c.iqns_to_fl0congen |= htonl(FW_IQ_CMD_FL0PACKEN_F |
4287                                              FW_IQ_CMD_FL0FETCHRO_V(relaxed) |
4288                                              FW_IQ_CMD_FL0DATARO_V(relaxed) |
4289                                              FW_IQ_CMD_FL0PADEN_F);
4290                 if (cong >= 0)
4291                         c.iqns_to_fl0congen |=
4292                                 htonl(FW_IQ_CMD_FL0CNGCHMAP_V(cong) |
4293                                       FW_IQ_CMD_FL0CONGCIF_F |
4294                                       FW_IQ_CMD_FL0CONGEN_F);
4295                 /* In T6, for egress queue type FL there is internal overhead
4296                  * of 16B for header going into FLM module.  Hence the maximum
4297                  * allowed burst size is 448 bytes.  For T4/T5, the hardware
4298                  * doesn't coalesce fetch requests if more than 64 bytes of
4299                  * Free List pointers are provided, so we use a 128-byte Fetch
4300                  * Burst Minimum there (T6 implements coalescing so we can use
4301                  * the smaller 64-byte value there).
4302                  */
4303                 c.fl0dcaen_to_fl0cidxfthresh =
4304                         htons(FW_IQ_CMD_FL0FBMIN_V(chip_ver <= CHELSIO_T5 ?
4305                                                    FETCHBURSTMIN_128B_X :
4306                                                    FETCHBURSTMIN_64B_T6_X) |
4307                               FW_IQ_CMD_FL0FBMAX_V((chip_ver <= CHELSIO_T5) ?
4308                                                    FETCHBURSTMAX_512B_X :
4309                                                    FETCHBURSTMAX_256B_X));
4310                 c.fl0size = htons(flsz);
4311                 c.fl0addr = cpu_to_be64(fl->addr);
4312         }
4313
4314         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
4315         if (ret)
4316                 goto err;
4317
4318         netif_napi_add(dev, &iq->napi, napi_rx_handler, 64);
4319         iq->cur_desc = iq->desc;
4320         iq->cidx = 0;
4321         iq->gen = 1;
4322         iq->next_intr_params = iq->intr_params;
4323         iq->cntxt_id = ntohs(c.iqid);
4324         iq->abs_id = ntohs(c.physiqid);
4325         iq->bar2_addr = bar2_address(adap,
4326                                      iq->cntxt_id,
4327                                      T4_BAR2_QTYPE_INGRESS,
4328                                      &iq->bar2_qid);
4329         iq->size--;                           /* subtract status entry */
4330         iq->netdev = dev;
4331         iq->handler = hnd;
4332         iq->flush_handler = flush_hnd;
4333
4334         memset(&iq->lro_mgr, 0, sizeof(struct t4_lro_mgr));
4335         skb_queue_head_init(&iq->lro_mgr.lroq);
4336
4337         /* set offset to -1 to distinguish ingress queues without FL */
4338         iq->offset = fl ? 0 : -1;
4339
4340         adap->sge.ingr_map[iq->cntxt_id - adap->sge.ingr_start] = iq;
4341
4342         if (fl) {
4343                 fl->cntxt_id = ntohs(c.fl0id);
4344                 fl->avail = fl->pend_cred = 0;
4345                 fl->pidx = fl->cidx = 0;
4346                 fl->alloc_failed = fl->large_alloc_failed = fl->starving = 0;
4347                 adap->sge.egr_map[fl->cntxt_id - adap->sge.egr_start] = fl;
4348
4349                 /* Note, we must initialize the BAR2 Free List User Doorbell
4350                  * information before refilling the Free List!
4351                  */
4352                 fl->bar2_addr = bar2_address(adap,
4353                                              fl->cntxt_id,
4354                                              T4_BAR2_QTYPE_EGRESS,
4355                                              &fl->bar2_qid);
4356                 refill_fl(adap, fl, fl_cap(fl), GFP_KERNEL);
4357         }
4358
4359         /* For T5 and later we attempt to set up the Congestion Manager values
4360          * of the new RX Ethernet Queue.  This should really be handled by
4361          * firmware because it's more complex than any host driver wants to
4362          * get involved with and it's different per chip and this is almost
4363          * certainly wrong.  Firmware would be wrong as well, but it would be
4364          * a lot easier to fix in one place ...  For now we do something very
4365          * simple (and hopefully less wrong).
4366          */
4367         if (!is_t4(adap->params.chip) && cong >= 0) {
4368                 u32 param, val, ch_map = 0;
4369                 int i;
4370                 u16 cng_ch_bits_log = adap->params.arch.cng_ch_bits_log;
4371
4372                 param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
4373                          FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
4374                          FW_PARAMS_PARAM_YZ_V(iq->cntxt_id));
4375                 if (cong == 0) {
4376                         val = CONMCTXT_CNGTPMODE_V(CONMCTXT_CNGTPMODE_QUEUE_X);
4377                 } else {
4378                         val =
4379                             CONMCTXT_CNGTPMODE_V(CONMCTXT_CNGTPMODE_CHANNEL_X);
4380                         for (i = 0; i < 4; i++) {
4381                                 if (cong & (1 << i))
4382                                         ch_map |= 1 << (i << cng_ch_bits_log);
4383                         }
4384                         val |= CONMCTXT_CNGCHMAP_V(ch_map);
4385                 }
4386                 ret = t4_set_params(adap, adap->mbox, adap->pf, 0, 1,
4387                                     &param, &val);
4388                 if (ret)
4389                         dev_warn(adap->pdev_dev, "Failed to set Congestion"
4390                                  " Manager Context for Ingress Queue %d: %d\n",
4391                                  iq->cntxt_id, -ret);
4392         }
4393
4394         return 0;
4395
4396 fl_nomem:
4397         ret = -ENOMEM;
4398 err:
4399         if (iq->desc) {
4400                 dma_free_coherent(adap->pdev_dev, iq->size * iq->iqe_len,
4401                                   iq->desc, iq->phys_addr);
4402                 iq->desc = NULL;
4403         }
4404         if (fl && fl->desc) {
4405                 kfree(fl->sdesc);
4406                 fl->sdesc = NULL;
4407                 dma_free_coherent(adap->pdev_dev, flsz * sizeof(struct tx_desc),
4408                                   fl->desc, fl->addr);
4409                 fl->desc = NULL;
4410         }
4411         return ret;
4412 }
4413
4414 static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id)
4415 {
4416         q->cntxt_id = id;
4417         q->bar2_addr = bar2_address(adap,
4418                                     q->cntxt_id,
4419                                     T4_BAR2_QTYPE_EGRESS,
4420                                     &q->bar2_qid);
4421         q->in_use = 0;
4422         q->cidx = q->pidx = 0;
4423         q->stops = q->restarts = 0;
4424         q->stat = (void *)&q->desc[q->size];
4425         spin_lock_init(&q->db_lock);
4426         adap->sge.egr_map[id - adap->sge.egr_start] = q;
4427 }
4428
4429 /**
4430  *      t4_sge_alloc_eth_txq - allocate an Ethernet TX Queue
4431  *      @adap: the adapter
4432  *      @txq: the SGE Ethernet TX Queue to initialize
4433  *      @dev: the Linux Network Device
4434  *      @netdevq: the corresponding Linux TX Queue
4435  *      @iqid: the Ingress Queue to which to deliver CIDX Update messages
4436  *      @dbqt: whether this TX Queue will use the SGE Doorbell Queue Timers
4437  */
4438 int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
4439                          struct net_device *dev, struct netdev_queue *netdevq,
4440                          unsigned int iqid, u8 dbqt)
4441 {
4442         unsigned int chip_ver = CHELSIO_CHIP_VERSION(adap->params.chip);
4443         struct port_info *pi = netdev_priv(dev);
4444         struct sge *s = &adap->sge;
4445         struct fw_eq_eth_cmd c;
4446         int ret, nentries;
4447
4448         /* Add status entries */
4449         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
4450
4451         txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
4452                         sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
4453                         &txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
4454                         netdev_queue_numa_node_read(netdevq));
4455         if (!txq->q.desc)
4456                 return -ENOMEM;
4457
4458         memset(&c, 0, sizeof(c));
4459         c.op_to_vfn = htonl(FW_CMD_OP_V(FW_EQ_ETH_CMD) | FW_CMD_REQUEST_F |
4460                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
4461                             FW_EQ_ETH_CMD_PFN_V(adap->pf) |
4462                             FW_EQ_ETH_CMD_VFN_V(0));
4463         c.alloc_to_len16 = htonl(FW_EQ_ETH_CMD_ALLOC_F |
4464                                  FW_EQ_ETH_CMD_EQSTART_F | FW_LEN16(c));
4465
4466         /* For TX Ethernet Queues using the SGE Doorbell Queue Timer
4467          * mechanism, we use Ingress Queue messages for Hardware Consumer
4468          * Index Updates on the TX Queue.  Otherwise we have the Hardware
4469          * write the CIDX Updates into the Status Page at the end of the
4470          * TX Queue.
4471          */
4472         c.autoequiqe_to_viid = htonl(FW_EQ_ETH_CMD_AUTOEQUEQE_F |
4473                                      FW_EQ_ETH_CMD_VIID_V(pi->viid));
4474
4475         c.fetchszm_to_iqid =
4476                 htonl(FW_EQ_ETH_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
4477                       FW_EQ_ETH_CMD_PCIECHN_V(pi->tx_chan) |
4478                       FW_EQ_ETH_CMD_FETCHRO_F | FW_EQ_ETH_CMD_IQID_V(iqid));
4479
4480         /* Note that the CIDX Flush Threshold should match MAX_TX_RECLAIM. */
4481         c.dcaen_to_eqsize =
4482                 htonl(FW_EQ_ETH_CMD_FBMIN_V(chip_ver <= CHELSIO_T5
4483                                             ? FETCHBURSTMIN_64B_X
4484                                             : FETCHBURSTMIN_64B_T6_X) |
4485                       FW_EQ_ETH_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
4486                       FW_EQ_ETH_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
4487                       FW_EQ_ETH_CMD_EQSIZE_V(nentries));
4488
4489         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
4490
4491         /* If we're using the SGE Doorbell Queue Timer mechanism, pass in the
4492          * currently configured Timer Index.  THis can be changed later via an
4493          * ethtool -C tx-usecs {Timer Val} command.  Note that the SGE
4494          * Doorbell Queue mode is currently automatically enabled in the
4495          * Firmware by setting either AUTOEQUEQE or AUTOEQUIQE ...
4496          */
4497         if (dbqt)
4498                 c.timeren_timerix =
4499                         cpu_to_be32(FW_EQ_ETH_CMD_TIMEREN_F |
4500                                     FW_EQ_ETH_CMD_TIMERIX_V(txq->dbqtimerix));
4501
4502         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
4503         if (ret) {
4504                 kfree(txq->q.sdesc);
4505                 txq->q.sdesc = NULL;
4506                 dma_free_coherent(adap->pdev_dev,
4507                                   nentries * sizeof(struct tx_desc),
4508                                   txq->q.desc, txq->q.phys_addr);
4509                 txq->q.desc = NULL;
4510                 return ret;
4511         }
4512
4513         txq->q.q_type = CXGB4_TXQ_ETH;
4514         init_txq(adap, &txq->q, FW_EQ_ETH_CMD_EQID_G(ntohl(c.eqid_pkd)));
4515         txq->txq = netdevq;
4516         txq->tso = 0;
4517         txq->uso = 0;
4518         txq->tx_cso = 0;
4519         txq->vlan_ins = 0;
4520         txq->mapping_err = 0;
4521         txq->dbqt = dbqt;
4522
4523         return 0;
4524 }
4525
4526 int t4_sge_alloc_ctrl_txq(struct adapter *adap, struct sge_ctrl_txq *txq,
4527                           struct net_device *dev, unsigned int iqid,
4528                           unsigned int cmplqid)
4529 {
4530         unsigned int chip_ver = CHELSIO_CHIP_VERSION(adap->params.chip);
4531         struct port_info *pi = netdev_priv(dev);
4532         struct sge *s = &adap->sge;
4533         struct fw_eq_ctrl_cmd c;
4534         int ret, nentries;
4535
4536         /* Add status entries */
4537         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
4538
4539         txq->q.desc = alloc_ring(adap->pdev_dev, nentries,
4540                                  sizeof(struct tx_desc), 0, &txq->q.phys_addr,
4541                                  NULL, 0, dev_to_node(adap->pdev_dev));
4542         if (!txq->q.desc)
4543                 return -ENOMEM;
4544
4545         c.op_to_vfn = htonl(FW_CMD_OP_V(FW_EQ_CTRL_CMD) | FW_CMD_REQUEST_F |
4546                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
4547                             FW_EQ_CTRL_CMD_PFN_V(adap->pf) |
4548                             FW_EQ_CTRL_CMD_VFN_V(0));
4549         c.alloc_to_len16 = htonl(FW_EQ_CTRL_CMD_ALLOC_F |
4550                                  FW_EQ_CTRL_CMD_EQSTART_F | FW_LEN16(c));
4551         c.cmpliqid_eqid = htonl(FW_EQ_CTRL_CMD_CMPLIQID_V(cmplqid));
4552         c.physeqid_pkd = htonl(0);
4553         c.fetchszm_to_iqid =
4554                 htonl(FW_EQ_CTRL_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
4555                       FW_EQ_CTRL_CMD_PCIECHN_V(pi->tx_chan) |
4556                       FW_EQ_CTRL_CMD_FETCHRO_F | FW_EQ_CTRL_CMD_IQID_V(iqid));
4557         c.dcaen_to_eqsize =
4558                 htonl(FW_EQ_CTRL_CMD_FBMIN_V(chip_ver <= CHELSIO_T5
4559                                              ? FETCHBURSTMIN_64B_X
4560                                              : FETCHBURSTMIN_64B_T6_X) |
4561                       FW_EQ_CTRL_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
4562                       FW_EQ_CTRL_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
4563                       FW_EQ_CTRL_CMD_EQSIZE_V(nentries));
4564         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
4565
4566         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
4567         if (ret) {
4568                 dma_free_coherent(adap->pdev_dev,
4569                                   nentries * sizeof(struct tx_desc),
4570                                   txq->q.desc, txq->q.phys_addr);
4571                 txq->q.desc = NULL;
4572                 return ret;
4573         }
4574
4575         txq->q.q_type = CXGB4_TXQ_CTRL;
4576         init_txq(adap, &txq->q, FW_EQ_CTRL_CMD_EQID_G(ntohl(c.cmpliqid_eqid)));
4577         txq->adap = adap;
4578         skb_queue_head_init(&txq->sendq);
4579         tasklet_init(&txq->qresume_tsk, restart_ctrlq, (unsigned long)txq);
4580         txq->full = 0;
4581         return 0;
4582 }
4583
4584 int t4_sge_mod_ctrl_txq(struct adapter *adap, unsigned int eqid,
4585                         unsigned int cmplqid)
4586 {
4587         u32 param, val;
4588
4589         param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
4590                  FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DMAQ_EQ_CMPLIQID_CTRL) |
4591                  FW_PARAMS_PARAM_YZ_V(eqid));
4592         val = cmplqid;
4593         return t4_set_params(adap, adap->mbox, adap->pf, 0, 1, &param, &val);
4594 }
4595
4596 static int t4_sge_alloc_ofld_txq(struct adapter *adap, struct sge_txq *q,
4597                                  struct net_device *dev, u32 cmd, u32 iqid)
4598 {
4599         unsigned int chip_ver = CHELSIO_CHIP_VERSION(adap->params.chip);
4600         struct port_info *pi = netdev_priv(dev);
4601         struct sge *s = &adap->sge;
4602         struct fw_eq_ofld_cmd c;
4603         u32 fb_min, nentries;
4604         int ret;
4605
4606         /* Add status entries */
4607         nentries = q->size + s->stat_len / sizeof(struct tx_desc);
4608         q->desc = alloc_ring(adap->pdev_dev, q->size, sizeof(struct tx_desc),
4609                              sizeof(struct tx_sw_desc), &q->phys_addr,
4610                              &q->sdesc, s->stat_len, NUMA_NO_NODE);
4611         if (!q->desc)
4612                 return -ENOMEM;
4613
4614         if (chip_ver <= CHELSIO_T5)
4615                 fb_min = FETCHBURSTMIN_64B_X;
4616         else
4617                 fb_min = FETCHBURSTMIN_64B_T6_X;
4618
4619         memset(&c, 0, sizeof(c));
4620         c.op_to_vfn = htonl(FW_CMD_OP_V(cmd) | FW_CMD_REQUEST_F |
4621                             FW_CMD_WRITE_F | FW_CMD_EXEC_F |
4622                             FW_EQ_OFLD_CMD_PFN_V(adap->pf) |
4623                             FW_EQ_OFLD_CMD_VFN_V(0));
4624         c.alloc_to_len16 = htonl(FW_EQ_OFLD_CMD_ALLOC_F |
4625                                  FW_EQ_OFLD_CMD_EQSTART_F | FW_LEN16(c));
4626         c.fetchszm_to_iqid =
4627                 htonl(FW_EQ_OFLD_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
4628                       FW_EQ_OFLD_CMD_PCIECHN_V(pi->tx_chan) |
4629                       FW_EQ_OFLD_CMD_FETCHRO_F | FW_EQ_OFLD_CMD_IQID_V(iqid));
4630         c.dcaen_to_eqsize =
4631                 htonl(FW_EQ_OFLD_CMD_FBMIN_V(fb_min) |
4632                       FW_EQ_OFLD_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
4633                       FW_EQ_OFLD_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
4634                       FW_EQ_OFLD_CMD_EQSIZE_V(nentries));
4635         c.eqaddr = cpu_to_be64(q->phys_addr);
4636
4637         ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
4638         if (ret) {
4639                 kfree(q->sdesc);
4640                 q->sdesc = NULL;
4641                 dma_free_coherent(adap->pdev_dev,
4642                                   nentries * sizeof(struct tx_desc),
4643                                   q->desc, q->phys_addr);
4644                 q->desc = NULL;
4645                 return ret;
4646         }
4647
4648         init_txq(adap, q, FW_EQ_OFLD_CMD_EQID_G(ntohl(c.eqid_pkd)));
4649         return 0;
4650 }
4651
4652 int t4_sge_alloc_uld_txq(struct adapter *adap, struct sge_uld_txq *txq,
4653                          struct net_device *dev, unsigned int iqid,
4654                          unsigned int uld_type)
4655 {
4656         u32 cmd = FW_EQ_OFLD_CMD;
4657         int ret;
4658
4659         if (unlikely(uld_type == CXGB4_TX_CRYPTO))
4660                 cmd = FW_EQ_CTRL_CMD;
4661
4662         ret = t4_sge_alloc_ofld_txq(adap, &txq->q, dev, cmd, iqid);
4663         if (ret)
4664                 return ret;
4665
4666         txq->q.q_type = CXGB4_TXQ_ULD;
4667         txq->adap = adap;
4668         skb_queue_head_init(&txq->sendq);
4669         tasklet_init(&txq->qresume_tsk, restart_ofldq, (unsigned long)txq);
4670         txq->full = 0;
4671         txq->mapping_err = 0;
4672         return 0;
4673 }
4674
4675 int t4_sge_alloc_ethofld_txq(struct adapter *adap, struct sge_eohw_txq *txq,
4676                              struct net_device *dev, u32 iqid)
4677 {
4678         int ret;
4679
4680         ret = t4_sge_alloc_ofld_txq(adap, &txq->q, dev, FW_EQ_OFLD_CMD, iqid);
4681         if (ret)
4682                 return ret;
4683
4684         txq->q.q_type = CXGB4_TXQ_ULD;
4685         spin_lock_init(&txq->lock);
4686         txq->adap = adap;
4687         txq->tso = 0;
4688         txq->uso = 0;
4689         txq->tx_cso = 0;
4690         txq->vlan_ins = 0;
4691         txq->mapping_err = 0;
4692         return 0;
4693 }
4694
4695 void free_txq(struct adapter *adap, struct sge_txq *q)
4696 {
4697         struct sge *s = &adap->sge;
4698
4699         dma_free_coherent(adap->pdev_dev,
4700                           q->size * sizeof(struct tx_desc) + s->stat_len,
4701                           q->desc, q->phys_addr);
4702         q->cntxt_id = 0;
4703         q->sdesc = NULL;
4704         q->desc = NULL;
4705 }
4706
4707 void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
4708                   struct sge_fl *fl)
4709 {
4710         struct sge *s = &adap->sge;
4711         unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
4712
4713         adap->sge.ingr_map[rq->cntxt_id - adap->sge.ingr_start] = NULL;
4714         t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
4715                    rq->cntxt_id, fl_id, 0xffff);
4716         dma_free_coherent(adap->pdev_dev, (rq->size + 1) * rq->iqe_len,
4717                           rq->desc, rq->phys_addr);
4718         netif_napi_del(&rq->napi);
4719         rq->netdev = NULL;
4720         rq->cntxt_id = rq->abs_id = 0;
4721         rq->desc = NULL;
4722
4723         if (fl) {
4724                 free_rx_bufs(adap, fl, fl->avail);
4725                 dma_free_coherent(adap->pdev_dev, fl->size * 8 + s->stat_len,
4726                                   fl->desc, fl->addr);
4727                 kfree(fl->sdesc);
4728                 fl->sdesc = NULL;
4729                 fl->cntxt_id = 0;
4730                 fl->desc = NULL;
4731         }
4732 }
4733
4734 /**
4735  *      t4_free_ofld_rxqs - free a block of consecutive Rx queues
4736  *      @adap: the adapter
4737  *      @n: number of queues
4738  *      @q: pointer to first queue
4739  *
4740  *      Release the resources of a consecutive block of offload Rx queues.
4741  */
4742 void t4_free_ofld_rxqs(struct adapter *adap, int n, struct sge_ofld_rxq *q)
4743 {
4744         for ( ; n; n--, q++)
4745                 if (q->rspq.desc)
4746                         free_rspq_fl(adap, &q->rspq,
4747                                      q->fl.size ? &q->fl : NULL);
4748 }
4749
4750 void t4_sge_free_ethofld_txq(struct adapter *adap, struct sge_eohw_txq *txq)
4751 {
4752         if (txq->q.desc) {
4753                 t4_ofld_eq_free(adap, adap->mbox, adap->pf, 0,
4754                                 txq->q.cntxt_id);
4755                 free_tx_desc(adap, &txq->q, txq->q.in_use, false);
4756                 kfree(txq->q.sdesc);
4757                 free_txq(adap, &txq->q);
4758         }
4759 }
4760
4761 /**
4762  *      t4_free_sge_resources - free SGE resources
4763  *      @adap: the adapter
4764  *
4765  *      Frees resources used by the SGE queue sets.
4766  */
4767 void t4_free_sge_resources(struct adapter *adap)
4768 {
4769         int i;
4770         struct sge_eth_rxq *eq;
4771         struct sge_eth_txq *etq;
4772
4773         /* stop all Rx queues in order to start them draining */
4774         for (i = 0; i < adap->sge.ethqsets; i++) {
4775                 eq = &adap->sge.ethrxq[i];
4776                 if (eq->rspq.desc)
4777                         t4_iq_stop(adap, adap->mbox, adap->pf, 0,
4778                                    FW_IQ_TYPE_FL_INT_CAP,
4779                                    eq->rspq.cntxt_id,
4780                                    eq->fl.size ? eq->fl.cntxt_id : 0xffff,
4781                                    0xffff);
4782         }
4783
4784         /* clean up Ethernet Tx/Rx queues */
4785         for (i = 0; i < adap->sge.ethqsets; i++) {
4786                 eq = &adap->sge.ethrxq[i];
4787                 if (eq->rspq.desc)
4788                         free_rspq_fl(adap, &eq->rspq,
4789                                      eq->fl.size ? &eq->fl : NULL);
4790                 if (eq->msix) {
4791                         cxgb4_free_msix_idx_in_bmap(adap, eq->msix->idx);
4792                         eq->msix = NULL;
4793                 }
4794
4795                 etq = &adap->sge.ethtxq[i];
4796                 if (etq->q.desc) {
4797                         t4_eth_eq_free(adap, adap->mbox, adap->pf, 0,
4798                                        etq->q.cntxt_id);
4799                         __netif_tx_lock_bh(etq->txq);
4800                         free_tx_desc(adap, &etq->q, etq->q.in_use, true);
4801                         __netif_tx_unlock_bh(etq->txq);
4802                         kfree(etq->q.sdesc);
4803                         free_txq(adap, &etq->q);
4804                 }
4805         }
4806
4807         /* clean up control Tx queues */
4808         for (i = 0; i < ARRAY_SIZE(adap->sge.ctrlq); i++) {
4809                 struct sge_ctrl_txq *cq = &adap->sge.ctrlq[i];
4810
4811                 if (cq->q.desc) {
4812                         tasklet_kill(&cq->qresume_tsk);
4813                         t4_ctrl_eq_free(adap, adap->mbox, adap->pf, 0,
4814                                         cq->q.cntxt_id);
4815                         __skb_queue_purge(&cq->sendq);
4816                         free_txq(adap, &cq->q);
4817                 }
4818         }
4819
4820         if (adap->sge.fw_evtq.desc) {
4821                 free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
4822                 if (adap->sge.fwevtq_msix_idx >= 0)
4823                         cxgb4_free_msix_idx_in_bmap(adap,
4824                                                     adap->sge.fwevtq_msix_idx);
4825         }
4826
4827         if (adap->sge.nd_msix_idx >= 0)
4828                 cxgb4_free_msix_idx_in_bmap(adap, adap->sge.nd_msix_idx);
4829
4830         if (adap->sge.intrq.desc)
4831                 free_rspq_fl(adap, &adap->sge.intrq, NULL);
4832
4833         if (!is_t4(adap->params.chip)) {
4834                 etq = &adap->sge.ptptxq;
4835                 if (etq->q.desc) {
4836                         t4_eth_eq_free(adap, adap->mbox, adap->pf, 0,
4837                                        etq->q.cntxt_id);
4838                         spin_lock_bh(&adap->ptp_lock);
4839                         free_tx_desc(adap, &etq->q, etq->q.in_use, true);
4840                         spin_unlock_bh(&adap->ptp_lock);
4841                         kfree(etq->q.sdesc);
4842                         free_txq(adap, &etq->q);
4843                 }
4844         }
4845
4846         /* clear the reverse egress queue map */
4847         memset(adap->sge.egr_map, 0,
4848                adap->sge.egr_sz * sizeof(*adap->sge.egr_map));
4849 }
4850
4851 void t4_sge_start(struct adapter *adap)
4852 {
4853         adap->sge.ethtxq_rover = 0;
4854         mod_timer(&adap->sge.rx_timer, jiffies + RX_QCHECK_PERIOD);
4855         mod_timer(&adap->sge.tx_timer, jiffies + TX_QCHECK_PERIOD);
4856 }
4857
4858 /**
4859  *      t4_sge_stop - disable SGE operation
4860  *      @adap: the adapter
4861  *
4862  *      Stop tasklets and timers associated with the DMA engine.  Note that
4863  *      this is effective only if measures have been taken to disable any HW
4864  *      events that may restart them.
4865  */
4866 void t4_sge_stop(struct adapter *adap)
4867 {
4868         int i;
4869         struct sge *s = &adap->sge;
4870
4871         if (in_interrupt())  /* actions below require waiting */
4872                 return;
4873
4874         if (s->rx_timer.function)
4875                 del_timer_sync(&s->rx_timer);
4876         if (s->tx_timer.function)
4877                 del_timer_sync(&s->tx_timer);
4878
4879         if (is_offload(adap)) {
4880                 struct sge_uld_txq_info *txq_info;
4881
4882                 txq_info = adap->sge.uld_txq_info[CXGB4_TX_OFLD];
4883                 if (txq_info) {
4884                         struct sge_uld_txq *txq = txq_info->uldtxq;
4885
4886                         for_each_ofldtxq(&adap->sge, i) {
4887                                 if (txq->q.desc)
4888                                         tasklet_kill(&txq->qresume_tsk);
4889                         }
4890                 }
4891         }
4892
4893         if (is_pci_uld(adap)) {
4894                 struct sge_uld_txq_info *txq_info;
4895
4896                 txq_info = adap->sge.uld_txq_info[CXGB4_TX_CRYPTO];
4897                 if (txq_info) {
4898                         struct sge_uld_txq *txq = txq_info->uldtxq;
4899
4900                         for_each_ofldtxq(&adap->sge, i) {
4901                                 if (txq->q.desc)
4902                                         tasklet_kill(&txq->qresume_tsk);
4903                         }
4904                 }
4905         }
4906
4907         for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++) {
4908                 struct sge_ctrl_txq *cq = &s->ctrlq[i];
4909
4910                 if (cq->q.desc)
4911                         tasklet_kill(&cq->qresume_tsk);
4912         }
4913 }
4914
4915 /**
4916  *      t4_sge_init_soft - grab core SGE values needed by SGE code
4917  *      @adap: the adapter
4918  *
4919  *      We need to grab the SGE operating parameters that we need to have
4920  *      in order to do our job and make sure we can live with them.
4921  */
4922
4923 static int t4_sge_init_soft(struct adapter *adap)
4924 {
4925         struct sge *s = &adap->sge;
4926         u32 fl_small_pg, fl_large_pg, fl_small_mtu, fl_large_mtu;
4927         u32 timer_value_0_and_1, timer_value_2_and_3, timer_value_4_and_5;
4928         u32 ingress_rx_threshold;
4929
4930         /*
4931          * Verify that CPL messages are going to the Ingress Queue for
4932          * process_responses() and that only packet data is going to the
4933          * Free Lists.
4934          */
4935         if ((t4_read_reg(adap, SGE_CONTROL_A) & RXPKTCPLMODE_F) !=
4936             RXPKTCPLMODE_V(RXPKTCPLMODE_SPLIT_X)) {
4937                 dev_err(adap->pdev_dev, "bad SGE CPL MODE\n");
4938                 return -EINVAL;
4939         }
4940
4941         /*
4942          * Validate the Host Buffer Register Array indices that we want to
4943          * use ...
4944          *
4945          * XXX Note that we should really read through the Host Buffer Size
4946          * XXX register array and find the indices of the Buffer Sizes which
4947          * XXX meet our needs!
4948          */
4949         #define READ_FL_BUF(x) \
4950                 t4_read_reg(adap, SGE_FL_BUFFER_SIZE0_A+(x)*sizeof(u32))
4951
4952         fl_small_pg = READ_FL_BUF(RX_SMALL_PG_BUF);
4953         fl_large_pg = READ_FL_BUF(RX_LARGE_PG_BUF);
4954         fl_small_mtu = READ_FL_BUF(RX_SMALL_MTU_BUF);
4955         fl_large_mtu = READ_FL_BUF(RX_LARGE_MTU_BUF);
4956
4957         /* We only bother using the Large Page logic if the Large Page Buffer
4958          * is larger than our Page Size Buffer.
4959          */
4960         if (fl_large_pg <= fl_small_pg)
4961                 fl_large_pg = 0;
4962
4963         #undef READ_FL_BUF
4964
4965         /* The Page Size Buffer must be exactly equal to our Page Size and the
4966          * Large Page Size Buffer should be 0 (per above) or a power of 2.
4967          */
4968         if (fl_small_pg != PAGE_SIZE ||
4969             (fl_large_pg & (fl_large_pg-1)) != 0) {
4970                 dev_err(adap->pdev_dev, "bad SGE FL page buffer sizes [%d, %d]\n",
4971                         fl_small_pg, fl_large_pg);
4972                 return -EINVAL;
4973         }
4974         if (fl_large_pg)
4975                 s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
4976
4977         if (fl_small_mtu < FL_MTU_SMALL_BUFSIZE(adap) ||
4978             fl_large_mtu < FL_MTU_LARGE_BUFSIZE(adap)) {
4979                 dev_err(adap->pdev_dev, "bad SGE FL MTU sizes [%d, %d]\n",
4980                         fl_small_mtu, fl_large_mtu);
4981                 return -EINVAL;
4982         }
4983
4984         /*
4985          * Retrieve our RX interrupt holdoff timer values and counter
4986          * threshold values from the SGE parameters.
4987          */
4988         timer_value_0_and_1 = t4_read_reg(adap, SGE_TIMER_VALUE_0_AND_1_A);
4989         timer_value_2_and_3 = t4_read_reg(adap, SGE_TIMER_VALUE_2_AND_3_A);
4990         timer_value_4_and_5 = t4_read_reg(adap, SGE_TIMER_VALUE_4_AND_5_A);
4991         s->timer_val[0] = core_ticks_to_us(adap,
4992                 TIMERVALUE0_G(timer_value_0_and_1));
4993         s->timer_val[1] = core_ticks_to_us(adap,
4994                 TIMERVALUE1_G(timer_value_0_and_1));
4995         s->timer_val[2] = core_ticks_to_us(adap,
4996                 TIMERVALUE2_G(timer_value_2_and_3));
4997         s->timer_val[3] = core_ticks_to_us(adap,
4998                 TIMERVALUE3_G(timer_value_2_and_3));
4999         s->timer_val[4] = core_ticks_to_us(adap,
5000                 TIMERVALUE4_G(timer_value_4_and_5));
5001         s->timer_val[5] = core_ticks_to_us(adap,
5002                 TIMERVALUE5_G(timer_value_4_and_5));
5003
5004         ingress_rx_threshold = t4_read_reg(adap, SGE_INGRESS_RX_THRESHOLD_A);
5005         s->counter_val[0] = THRESHOLD_0_G(ingress_rx_threshold);
5006         s->counter_val[1] = THRESHOLD_1_G(ingress_rx_threshold);
5007         s->counter_val[2] = THRESHOLD_2_G(ingress_rx_threshold);
5008         s->counter_val[3] = THRESHOLD_3_G(ingress_rx_threshold);
5009
5010         return 0;
5011 }
5012
5013 /**
5014  *     t4_sge_init - initialize SGE
5015  *     @adap: the adapter
5016  *
5017  *     Perform low-level SGE code initialization needed every time after a
5018  *     chip reset.
5019  */
5020 int t4_sge_init(struct adapter *adap)
5021 {
5022         struct sge *s = &adap->sge;
5023         u32 sge_control, sge_conm_ctrl;
5024         int ret, egress_threshold;
5025
5026         /*
5027          * Ingress Padding Boundary and Egress Status Page Size are set up by
5028          * t4_fixup_host_params().
5029          */
5030         sge_control = t4_read_reg(adap, SGE_CONTROL_A);
5031         s->pktshift = PKTSHIFT_G(sge_control);
5032         s->stat_len = (sge_control & EGRSTATUSPAGESIZE_F) ? 128 : 64;
5033
5034         s->fl_align = t4_fl_pkt_align(adap);
5035         ret = t4_sge_init_soft(adap);
5036         if (ret < 0)
5037                 return ret;
5038
5039         /*
5040          * A FL with <= fl_starve_thres buffers is starving and a periodic
5041          * timer will attempt to refill it.  This needs to be larger than the
5042          * SGE's Egress Congestion Threshold.  If it isn't, then we can get
5043          * stuck waiting for new packets while the SGE is waiting for us to
5044          * give it more Free List entries.  (Note that the SGE's Egress
5045          * Congestion Threshold is in units of 2 Free List pointers.) For T4,
5046          * there was only a single field to control this.  For T5 there's the
5047          * original field which now only applies to Unpacked Mode Free List
5048          * buffers and a new field which only applies to Packed Mode Free List
5049          * buffers.
5050          */
5051         sge_conm_ctrl = t4_read_reg(adap, SGE_CONM_CTRL_A);
5052         switch (CHELSIO_CHIP_VERSION(adap->params.chip)) {
5053         case CHELSIO_T4:
5054                 egress_threshold = EGRTHRESHOLD_G(sge_conm_ctrl);
5055                 break;
5056         case CHELSIO_T5:
5057                 egress_threshold = EGRTHRESHOLDPACKING_G(sge_conm_ctrl);
5058                 break;
5059         case CHELSIO_T6:
5060                 egress_threshold = T6_EGRTHRESHOLDPACKING_G(sge_conm_ctrl);
5061                 break;
5062         default:
5063                 dev_err(adap->pdev_dev, "Unsupported Chip version %d\n",
5064                         CHELSIO_CHIP_VERSION(adap->params.chip));
5065                 return -EINVAL;
5066         }
5067         s->fl_starve_thres = 2*egress_threshold + 1;
5068
5069         t4_idma_monitor_init(adap, &s->idma_monitor);
5070
5071         /* Set up timers used for recuring callbacks to process RX and TX
5072          * administrative tasks.
5073          */
5074         timer_setup(&s->rx_timer, sge_rx_timer_cb, 0);
5075         timer_setup(&s->tx_timer, sge_tx_timer_cb, 0);
5076
5077         spin_lock_init(&s->intrq_lock);
5078
5079         return 0;
5080 }