Merge branch 'usb-next' into musb-merge
[firefly-linux-kernel-4.4.55.git] / drivers / net / cxgb4vf / sge.c
1 /*
2  * This file is part of the Chelsio T4 PCI-E SR-IOV Virtual Function Ethernet
3  * driver for Linux.
4  *
5  * Copyright (c) 2009-2010 Chelsio Communications, Inc. All rights reserved.
6  *
7  * This software is available to you under a choice of one of two
8  * licenses.  You may choose to be licensed under the terms of the GNU
9  * General Public License (GPL) Version 2, available from the file
10  * COPYING in the main directory of this source tree, or the
11  * OpenIB.org BSD license below:
12  *
13  *     Redistribution and use in source and binary forms, with or
14  *     without modification, are permitted provided that the following
15  *     conditions are met:
16  *
17  *      - Redistributions of source code must retain the above
18  *        copyright notice, this list of conditions and the following
19  *        disclaimer.
20  *
21  *      - Redistributions in binary form must reproduce the above
22  *        copyright notice, this list of conditions and the following
23  *        disclaimer in the documentation and/or other materials
24  *        provided with the distribution.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
30  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
31  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
32  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33  * SOFTWARE.
34  */
35
36 #include <linux/skbuff.h>
37 #include <linux/netdevice.h>
38 #include <linux/etherdevice.h>
39 #include <linux/if_vlan.h>
40 #include <linux/ip.h>
41 #include <net/ipv6.h>
42 #include <net/tcp.h>
43 #include <linux/dma-mapping.h>
44
45 #include "t4vf_common.h"
46 #include "t4vf_defs.h"
47
48 #include "../cxgb4/t4_regs.h"
49 #include "../cxgb4/t4fw_api.h"
50 #include "../cxgb4/t4_msg.h"
51
52 /*
53  * Decoded Adapter Parameters.
54  */
55 static u32 FL_PG_ORDER;         /* large page allocation size */
56 static u32 STAT_LEN;            /* length of status page at ring end */
57 static u32 PKTSHIFT;            /* padding between CPL and packet data */
58 static u32 FL_ALIGN;            /* response queue message alignment */
59
60 /*
61  * Constants ...
62  */
63 enum {
64         /*
65          * Egress Queue sizes, producer and consumer indices are all in units
66          * of Egress Context Units bytes.  Note that as far as the hardware is
67          * concerned, the free list is an Egress Queue (the host produces free
68          * buffers which the hardware consumes) and free list entries are
69          * 64-bit PCI DMA addresses.
70          */
71         EQ_UNIT = SGE_EQ_IDXSIZE,
72         FL_PER_EQ_UNIT = EQ_UNIT / sizeof(__be64),
73         TXD_PER_EQ_UNIT = EQ_UNIT / sizeof(__be64),
74
75         /*
76          * Max number of TX descriptors we clean up at a time.  Should be
77          * modest as freeing skbs isn't cheap and it happens while holding
78          * locks.  We just need to free packets faster than they arrive, we
79          * eventually catch up and keep the amortized cost reasonable.
80          */
81         MAX_TX_RECLAIM = 16,
82
83         /*
84          * Max number of Rx buffers we replenish at a time.  Again keep this
85          * modest, allocating buffers isn't cheap either.
86          */
87         MAX_RX_REFILL = 16,
88
89         /*
90          * Period of the Rx queue check timer.  This timer is infrequent as it
91          * has something to do only when the system experiences severe memory
92          * shortage.
93          */
94         RX_QCHECK_PERIOD = (HZ / 2),
95
96         /*
97          * Period of the TX queue check timer and the maximum number of TX
98          * descriptors to be reclaimed by the TX timer.
99          */
100         TX_QCHECK_PERIOD = (HZ / 2),
101         MAX_TIMER_TX_RECLAIM = 100,
102
103         /*
104          * An FL with <= FL_STARVE_THRES buffers is starving and a periodic
105          * timer will attempt to refill it.
106          */
107         FL_STARVE_THRES = 4,
108
109         /*
110          * Suspend an Ethernet TX queue with fewer available descriptors than
111          * this.  We always want to have room for a maximum sized packet:
112          * inline immediate data + MAX_SKB_FRAGS. This is the same as
113          * calc_tx_flits() for a TSO packet with nr_frags == MAX_SKB_FRAGS
114          * (see that function and its helpers for a description of the
115          * calculation).
116          */
117         ETHTXQ_MAX_FRAGS = MAX_SKB_FRAGS + 1,
118         ETHTXQ_MAX_SGL_LEN = ((3 * (ETHTXQ_MAX_FRAGS-1))/2 +
119                                    ((ETHTXQ_MAX_FRAGS-1) & 1) +
120                                    2),
121         ETHTXQ_MAX_HDR = (sizeof(struct fw_eth_tx_pkt_vm_wr) +
122                           sizeof(struct cpl_tx_pkt_lso_core) +
123                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64),
124         ETHTXQ_MAX_FLITS = ETHTXQ_MAX_SGL_LEN + ETHTXQ_MAX_HDR,
125
126         ETHTXQ_STOP_THRES = 1 + DIV_ROUND_UP(ETHTXQ_MAX_FLITS, TXD_PER_EQ_UNIT),
127
128         /*
129          * Max TX descriptor space we allow for an Ethernet packet to be
130          * inlined into a WR.  This is limited by the maximum value which
131          * we can specify for immediate data in the firmware Ethernet TX
132          * Work Request.
133          */
134         MAX_IMM_TX_PKT_LEN = FW_WR_IMMDLEN_MASK,
135
136         /*
137          * Max size of a WR sent through a control TX queue.
138          */
139         MAX_CTRL_WR_LEN = 256,
140
141         /*
142          * Maximum amount of data which we'll ever need to inline into a
143          * TX ring: max(MAX_IMM_TX_PKT_LEN, MAX_CTRL_WR_LEN).
144          */
145         MAX_IMM_TX_LEN = (MAX_IMM_TX_PKT_LEN > MAX_CTRL_WR_LEN
146                           ? MAX_IMM_TX_PKT_LEN
147                           : MAX_CTRL_WR_LEN),
148
149         /*
150          * For incoming packets less than RX_COPY_THRES, we copy the data into
151          * an skb rather than referencing the data.  We allocate enough
152          * in-line room in skb's to accommodate pulling in RX_PULL_LEN bytes
153          * of the data (header).
154          */
155         RX_COPY_THRES = 256,
156         RX_PULL_LEN = 128,
157
158         /*
159          * Main body length for sk_buffs used for RX Ethernet packets with
160          * fragments.  Should be >= RX_PULL_LEN but possibly bigger to give
161          * pskb_may_pull() some room.
162          */
163         RX_SKB_LEN = 512,
164 };
165
166 /*
167  * Software state per TX descriptor.
168  */
169 struct tx_sw_desc {
170         struct sk_buff *skb;            /* socket buffer of TX data source */
171         struct ulptx_sgl *sgl;          /* scatter/gather list in TX Queue */
172 };
173
174 /*
175  * Software state per RX Free List descriptor.  We keep track of the allocated
176  * FL page, its size, and its PCI DMA address (if the page is mapped).  The FL
177  * page size and its PCI DMA mapped state are stored in the low bits of the
178  * PCI DMA address as per below.
179  */
180 struct rx_sw_desc {
181         struct page *page;              /* Free List page buffer */
182         dma_addr_t dma_addr;            /* PCI DMA address (if mapped) */
183                                         /*   and flags (see below) */
184 };
185
186 /*
187  * The low bits of rx_sw_desc.dma_addr have special meaning.  Note that the
188  * SGE also uses the low 4 bits to determine the size of the buffer.  It uses
189  * those bits to index into the SGE_FL_BUFFER_SIZE[index] register array.
190  * Since we only use SGE_FL_BUFFER_SIZE0 and SGE_FL_BUFFER_SIZE1, these low 4
191  * bits can only contain a 0 or a 1 to indicate which size buffer we're giving
192  * to the SGE.  Thus, our software state of "is the buffer mapped for DMA" is
193  * maintained in an inverse sense so the hardware never sees that bit high.
194  */
195 enum {
196         RX_LARGE_BUF    = 1 << 0,       /* buffer is SGE_FL_BUFFER_SIZE[1] */
197         RX_UNMAPPED_BUF = 1 << 1,       /* buffer is not mapped */
198 };
199
200 /**
201  *      get_buf_addr - return DMA buffer address of software descriptor
202  *      @sdesc: pointer to the software buffer descriptor
203  *
204  *      Return the DMA buffer address of a software descriptor (stripping out
205  *      our low-order flag bits).
206  */
207 static inline dma_addr_t get_buf_addr(const struct rx_sw_desc *sdesc)
208 {
209         return sdesc->dma_addr & ~(dma_addr_t)(RX_LARGE_BUF | RX_UNMAPPED_BUF);
210 }
211
212 /**
213  *      is_buf_mapped - is buffer mapped for DMA?
214  *      @sdesc: pointer to the software buffer descriptor
215  *
216  *      Determine whether the buffer associated with a software descriptor in
217  *      mapped for DMA or not.
218  */
219 static inline bool is_buf_mapped(const struct rx_sw_desc *sdesc)
220 {
221         return !(sdesc->dma_addr & RX_UNMAPPED_BUF);
222 }
223
224 /**
225  *      need_skb_unmap - does the platform need unmapping of sk_buffs?
226  *
227  *      Returns true if the platfrom needs sk_buff unmapping.  The compiler
228  *      optimizes away unecessary code if this returns true.
229  */
230 static inline int need_skb_unmap(void)
231 {
232 #ifdef CONFIG_NEED_DMA_MAP_STATE
233         return 1;
234 #else
235         return 0;
236 #endif
237 }
238
239 /**
240  *      txq_avail - return the number of available slots in a TX queue
241  *      @tq: the TX queue
242  *
243  *      Returns the number of available descriptors in a TX queue.
244  */
245 static inline unsigned int txq_avail(const struct sge_txq *tq)
246 {
247         return tq->size - 1 - tq->in_use;
248 }
249
250 /**
251  *      fl_cap - return the capacity of a Free List
252  *      @fl: the Free List
253  *
254  *      Returns the capacity of a Free List.  The capacity is less than the
255  *      size because an Egress Queue Index Unit worth of descriptors needs to
256  *      be left unpopulated, otherwise the Producer and Consumer indices PIDX
257  *      and CIDX will match and the hardware will think the FL is empty.
258  */
259 static inline unsigned int fl_cap(const struct sge_fl *fl)
260 {
261         return fl->size - FL_PER_EQ_UNIT;
262 }
263
264 /**
265  *      fl_starving - return whether a Free List is starving.
266  *      @fl: the Free List
267  *
268  *      Tests specified Free List to see whether the number of buffers
269  *      available to the hardware has falled below our "starvation"
270  *      threshhold.
271  */
272 static inline bool fl_starving(const struct sge_fl *fl)
273 {
274         return fl->avail - fl->pend_cred <= FL_STARVE_THRES;
275 }
276
277 /**
278  *      map_skb -  map an skb for DMA to the device
279  *      @dev: the egress net device
280  *      @skb: the packet to map
281  *      @addr: a pointer to the base of the DMA mapping array
282  *
283  *      Map an skb for DMA to the device and return an array of DMA addresses.
284  */
285 static int map_skb(struct device *dev, const struct sk_buff *skb,
286                    dma_addr_t *addr)
287 {
288         const skb_frag_t *fp, *end;
289         const struct skb_shared_info *si;
290
291         *addr = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
292         if (dma_mapping_error(dev, *addr))
293                 goto out_err;
294
295         si = skb_shinfo(skb);
296         end = &si->frags[si->nr_frags];
297         for (fp = si->frags; fp < end; fp++) {
298                 *++addr = dma_map_page(dev, fp->page, fp->page_offset, fp->size,
299                                        DMA_TO_DEVICE);
300                 if (dma_mapping_error(dev, *addr))
301                         goto unwind;
302         }
303         return 0;
304
305 unwind:
306         while (fp-- > si->frags)
307                 dma_unmap_page(dev, *--addr, fp->size, DMA_TO_DEVICE);
308         dma_unmap_single(dev, addr[-1], skb_headlen(skb), DMA_TO_DEVICE);
309
310 out_err:
311         return -ENOMEM;
312 }
313
314 static void unmap_sgl(struct device *dev, const struct sk_buff *skb,
315                       const struct ulptx_sgl *sgl, const struct sge_txq *tq)
316 {
317         const struct ulptx_sge_pair *p;
318         unsigned int nfrags = skb_shinfo(skb)->nr_frags;
319
320         if (likely(skb_headlen(skb)))
321                 dma_unmap_single(dev, be64_to_cpu(sgl->addr0),
322                                  be32_to_cpu(sgl->len0), DMA_TO_DEVICE);
323         else {
324                 dma_unmap_page(dev, be64_to_cpu(sgl->addr0),
325                                be32_to_cpu(sgl->len0), DMA_TO_DEVICE);
326                 nfrags--;
327         }
328
329         /*
330          * the complexity below is because of the possibility of a wrap-around
331          * in the middle of an SGL
332          */
333         for (p = sgl->sge; nfrags >= 2; nfrags -= 2) {
334                 if (likely((u8 *)(p + 1) <= (u8 *)tq->stat)) {
335 unmap:
336                         dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
337                                        be32_to_cpu(p->len[0]), DMA_TO_DEVICE);
338                         dma_unmap_page(dev, be64_to_cpu(p->addr[1]),
339                                        be32_to_cpu(p->len[1]), DMA_TO_DEVICE);
340                         p++;
341                 } else if ((u8 *)p == (u8 *)tq->stat) {
342                         p = (const struct ulptx_sge_pair *)tq->desc;
343                         goto unmap;
344                 } else if ((u8 *)p + 8 == (u8 *)tq->stat) {
345                         const __be64 *addr = (const __be64 *)tq->desc;
346
347                         dma_unmap_page(dev, be64_to_cpu(addr[0]),
348                                        be32_to_cpu(p->len[0]), DMA_TO_DEVICE);
349                         dma_unmap_page(dev, be64_to_cpu(addr[1]),
350                                        be32_to_cpu(p->len[1]), DMA_TO_DEVICE);
351                         p = (const struct ulptx_sge_pair *)&addr[2];
352                 } else {
353                         const __be64 *addr = (const __be64 *)tq->desc;
354
355                         dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
356                                        be32_to_cpu(p->len[0]), DMA_TO_DEVICE);
357                         dma_unmap_page(dev, be64_to_cpu(addr[0]),
358                                        be32_to_cpu(p->len[1]), DMA_TO_DEVICE);
359                         p = (const struct ulptx_sge_pair *)&addr[1];
360                 }
361         }
362         if (nfrags) {
363                 __be64 addr;
364
365                 if ((u8 *)p == (u8 *)tq->stat)
366                         p = (const struct ulptx_sge_pair *)tq->desc;
367                 addr = ((u8 *)p + 16 <= (u8 *)tq->stat
368                         ? p->addr[0]
369                         : *(const __be64 *)tq->desc);
370                 dma_unmap_page(dev, be64_to_cpu(addr), be32_to_cpu(p->len[0]),
371                                DMA_TO_DEVICE);
372         }
373 }
374
375 /**
376  *      free_tx_desc - reclaims TX descriptors and their buffers
377  *      @adapter: the adapter
378  *      @tq: the TX queue to reclaim descriptors from
379  *      @n: the number of descriptors to reclaim
380  *      @unmap: whether the buffers should be unmapped for DMA
381  *
382  *      Reclaims TX descriptors from an SGE TX queue and frees the associated
383  *      TX buffers.  Called with the TX queue lock held.
384  */
385 static void free_tx_desc(struct adapter *adapter, struct sge_txq *tq,
386                          unsigned int n, bool unmap)
387 {
388         struct tx_sw_desc *sdesc;
389         unsigned int cidx = tq->cidx;
390         struct device *dev = adapter->pdev_dev;
391
392         const int need_unmap = need_skb_unmap() && unmap;
393
394         sdesc = &tq->sdesc[cidx];
395         while (n--) {
396                 /*
397                  * If we kept a reference to the original TX skb, we need to
398                  * unmap it from PCI DMA space (if required) and free it.
399                  */
400                 if (sdesc->skb) {
401                         if (need_unmap)
402                                 unmap_sgl(dev, sdesc->skb, sdesc->sgl, tq);
403                         kfree_skb(sdesc->skb);
404                         sdesc->skb = NULL;
405                 }
406
407                 sdesc++;
408                 if (++cidx == tq->size) {
409                         cidx = 0;
410                         sdesc = tq->sdesc;
411                 }
412         }
413         tq->cidx = cidx;
414 }
415
416 /*
417  * Return the number of reclaimable descriptors in a TX queue.
418  */
419 static inline int reclaimable(const struct sge_txq *tq)
420 {
421         int hw_cidx = be16_to_cpu(tq->stat->cidx);
422         int reclaimable = hw_cidx - tq->cidx;
423         if (reclaimable < 0)
424                 reclaimable += tq->size;
425         return reclaimable;
426 }
427
428 /**
429  *      reclaim_completed_tx - reclaims completed TX descriptors
430  *      @adapter: the adapter
431  *      @tq: the TX queue to reclaim completed descriptors from
432  *      @unmap: whether the buffers should be unmapped for DMA
433  *
434  *      Reclaims TX descriptors that the SGE has indicated it has processed,
435  *      and frees the associated buffers if possible.  Called with the TX
436  *      queue locked.
437  */
438 static inline void reclaim_completed_tx(struct adapter *adapter,
439                                         struct sge_txq *tq,
440                                         bool unmap)
441 {
442         int avail = reclaimable(tq);
443
444         if (avail) {
445                 /*
446                  * Limit the amount of clean up work we do at a time to keep
447                  * the TX lock hold time O(1).
448                  */
449                 if (avail > MAX_TX_RECLAIM)
450                         avail = MAX_TX_RECLAIM;
451
452                 free_tx_desc(adapter, tq, avail, unmap);
453                 tq->in_use -= avail;
454         }
455 }
456
457 /**
458  *      get_buf_size - return the size of an RX Free List buffer.
459  *      @sdesc: pointer to the software buffer descriptor
460  */
461 static inline int get_buf_size(const struct rx_sw_desc *sdesc)
462 {
463         return FL_PG_ORDER > 0 && (sdesc->dma_addr & RX_LARGE_BUF)
464                 ? (PAGE_SIZE << FL_PG_ORDER)
465                 : PAGE_SIZE;
466 }
467
468 /**
469  *      free_rx_bufs - free RX buffers on an SGE Free List
470  *      @adapter: the adapter
471  *      @fl: the SGE Free List to free buffers from
472  *      @n: how many buffers to free
473  *
474  *      Release the next @n buffers on an SGE Free List RX queue.   The
475  *      buffers must be made inaccessible to hardware before calling this
476  *      function.
477  */
478 static void free_rx_bufs(struct adapter *adapter, struct sge_fl *fl, int n)
479 {
480         while (n--) {
481                 struct rx_sw_desc *sdesc = &fl->sdesc[fl->cidx];
482
483                 if (is_buf_mapped(sdesc))
484                         dma_unmap_page(adapter->pdev_dev, get_buf_addr(sdesc),
485                                        get_buf_size(sdesc), PCI_DMA_FROMDEVICE);
486                 put_page(sdesc->page);
487                 sdesc->page = NULL;
488                 if (++fl->cidx == fl->size)
489                         fl->cidx = 0;
490                 fl->avail--;
491         }
492 }
493
494 /**
495  *      unmap_rx_buf - unmap the current RX buffer on an SGE Free List
496  *      @adapter: the adapter
497  *      @fl: the SGE Free List
498  *
499  *      Unmap the current buffer on an SGE Free List RX queue.   The
500  *      buffer must be made inaccessible to HW before calling this function.
501  *
502  *      This is similar to @free_rx_bufs above but does not free the buffer.
503  *      Do note that the FL still loses any further access to the buffer.
504  *      This is used predominantly to "transfer ownership" of an FL buffer
505  *      to another entity (typically an skb's fragment list).
506  */
507 static void unmap_rx_buf(struct adapter *adapter, struct sge_fl *fl)
508 {
509         struct rx_sw_desc *sdesc = &fl->sdesc[fl->cidx];
510
511         if (is_buf_mapped(sdesc))
512                 dma_unmap_page(adapter->pdev_dev, get_buf_addr(sdesc),
513                                get_buf_size(sdesc), PCI_DMA_FROMDEVICE);
514         sdesc->page = NULL;
515         if (++fl->cidx == fl->size)
516                 fl->cidx = 0;
517         fl->avail--;
518 }
519
520 /**
521  *      ring_fl_db - righ doorbell on free list
522  *      @adapter: the adapter
523  *      @fl: the Free List whose doorbell should be rung ...
524  *
525  *      Tell the Scatter Gather Engine that there are new free list entries
526  *      available.
527  */
528 static inline void ring_fl_db(struct adapter *adapter, struct sge_fl *fl)
529 {
530         /*
531          * The SGE keeps track of its Producer and Consumer Indices in terms
532          * of Egress Queue Units so we can only tell it about integral numbers
533          * of multiples of Free List Entries per Egress Queue Units ...
534          */
535         if (fl->pend_cred >= FL_PER_EQ_UNIT) {
536                 wmb();
537                 t4_write_reg(adapter, T4VF_SGE_BASE_ADDR + SGE_VF_KDOORBELL,
538                              DBPRIO |
539                              QID(fl->cntxt_id) |
540                              PIDX(fl->pend_cred / FL_PER_EQ_UNIT));
541                 fl->pend_cred %= FL_PER_EQ_UNIT;
542         }
543 }
544
545 /**
546  *      set_rx_sw_desc - initialize software RX buffer descriptor
547  *      @sdesc: pointer to the softwore RX buffer descriptor
548  *      @page: pointer to the page data structure backing the RX buffer
549  *      @dma_addr: PCI DMA address (possibly with low-bit flags)
550  */
551 static inline void set_rx_sw_desc(struct rx_sw_desc *sdesc, struct page *page,
552                                   dma_addr_t dma_addr)
553 {
554         sdesc->page = page;
555         sdesc->dma_addr = dma_addr;
556 }
557
558 /*
559  * Support for poisoning RX buffers ...
560  */
561 #define POISON_BUF_VAL -1
562
563 static inline void poison_buf(struct page *page, size_t sz)
564 {
565 #if POISON_BUF_VAL >= 0
566         memset(page_address(page), POISON_BUF_VAL, sz);
567 #endif
568 }
569
570 /**
571  *      refill_fl - refill an SGE RX buffer ring
572  *      @adapter: the adapter
573  *      @fl: the Free List ring to refill
574  *      @n: the number of new buffers to allocate
575  *      @gfp: the gfp flags for the allocations
576  *
577  *      (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
578  *      allocated with the supplied gfp flags.  The caller must assure that
579  *      @n does not exceed the queue's capacity -- i.e. (cidx == pidx) _IN
580  *      EGRESS QUEUE UNITS_ indicates an empty Free List!  Returns the number
581  *      of buffers allocated.  If afterwards the queue is found critically low,
582  *      mark it as starving in the bitmap of starving FLs.
583  */
584 static unsigned int refill_fl(struct adapter *adapter, struct sge_fl *fl,
585                               int n, gfp_t gfp)
586 {
587         struct page *page;
588         dma_addr_t dma_addr;
589         unsigned int cred = fl->avail;
590         __be64 *d = &fl->desc[fl->pidx];
591         struct rx_sw_desc *sdesc = &fl->sdesc[fl->pidx];
592
593         /*
594          * Sanity: ensure that the result of adding n Free List buffers
595          * won't result in wrapping the SGE's Producer Index around to
596          * it's Consumer Index thereby indicating an empty Free List ...
597          */
598         BUG_ON(fl->avail + n > fl->size - FL_PER_EQ_UNIT);
599
600         /*
601          * If we support large pages, prefer large buffers and fail over to
602          * small pages if we can't allocate large pages to satisfy the refill.
603          * If we don't support large pages, drop directly into the small page
604          * allocation code.
605          */
606         if (FL_PG_ORDER == 0)
607                 goto alloc_small_pages;
608
609         while (n) {
610                 page = alloc_pages(gfp | __GFP_COMP | __GFP_NOWARN,
611                                    FL_PG_ORDER);
612                 if (unlikely(!page)) {
613                         /*
614                          * We've failed inour attempt to allocate a "large
615                          * page".  Fail over to the "small page" allocation
616                          * below.
617                          */
618                         fl->large_alloc_failed++;
619                         break;
620                 }
621                 poison_buf(page, PAGE_SIZE << FL_PG_ORDER);
622
623                 dma_addr = dma_map_page(adapter->pdev_dev, page, 0,
624                                         PAGE_SIZE << FL_PG_ORDER,
625                                         PCI_DMA_FROMDEVICE);
626                 if (unlikely(dma_mapping_error(adapter->pdev_dev, dma_addr))) {
627                         /*
628                          * We've run out of DMA mapping space.  Free up the
629                          * buffer and return with what we've managed to put
630                          * into the free list.  We don't want to fail over to
631                          * the small page allocation below in this case
632                          * because DMA mapping resources are typically
633                          * critical resources once they become scarse.
634                          */
635                         __free_pages(page, FL_PG_ORDER);
636                         goto out;
637                 }
638                 dma_addr |= RX_LARGE_BUF;
639                 *d++ = cpu_to_be64(dma_addr);
640
641                 set_rx_sw_desc(sdesc, page, dma_addr);
642                 sdesc++;
643
644                 fl->avail++;
645                 if (++fl->pidx == fl->size) {
646                         fl->pidx = 0;
647                         sdesc = fl->sdesc;
648                         d = fl->desc;
649                 }
650                 n--;
651         }
652
653 alloc_small_pages:
654         while (n--) {
655                 page = __netdev_alloc_page(adapter->port[0],
656                                            gfp | __GFP_NOWARN);
657                 if (unlikely(!page)) {
658                         fl->alloc_failed++;
659                         break;
660                 }
661                 poison_buf(page, PAGE_SIZE);
662
663                 dma_addr = dma_map_page(adapter->pdev_dev, page, 0, PAGE_SIZE,
664                                        PCI_DMA_FROMDEVICE);
665                 if (unlikely(dma_mapping_error(adapter->pdev_dev, dma_addr))) {
666                         netdev_free_page(adapter->port[0], page);
667                         break;
668                 }
669                 *d++ = cpu_to_be64(dma_addr);
670
671                 set_rx_sw_desc(sdesc, page, dma_addr);
672                 sdesc++;
673
674                 fl->avail++;
675                 if (++fl->pidx == fl->size) {
676                         fl->pidx = 0;
677                         sdesc = fl->sdesc;
678                         d = fl->desc;
679                 }
680         }
681
682 out:
683         /*
684          * Update our accounting state to incorporate the new Free List
685          * buffers, tell the hardware about them and return the number of
686          * bufers which we were able to allocate.
687          */
688         cred = fl->avail - cred;
689         fl->pend_cred += cred;
690         ring_fl_db(adapter, fl);
691
692         if (unlikely(fl_starving(fl))) {
693                 smp_wmb();
694                 set_bit(fl->cntxt_id, adapter->sge.starving_fl);
695         }
696
697         return cred;
698 }
699
700 /*
701  * Refill a Free List to its capacity or the Maximum Refill Increment,
702  * whichever is smaller ...
703  */
704 static inline void __refill_fl(struct adapter *adapter, struct sge_fl *fl)
705 {
706         refill_fl(adapter, fl,
707                   min((unsigned int)MAX_RX_REFILL, fl_cap(fl) - fl->avail),
708                   GFP_ATOMIC);
709 }
710
711 /**
712  *      alloc_ring - allocate resources for an SGE descriptor ring
713  *      @dev: the PCI device's core device
714  *      @nelem: the number of descriptors
715  *      @hwsize: the size of each hardware descriptor
716  *      @swsize: the size of each software descriptor
717  *      @busaddrp: the physical PCI bus address of the allocated ring
718  *      @swringp: return address pointer for software ring
719  *      @stat_size: extra space in hardware ring for status information
720  *
721  *      Allocates resources for an SGE descriptor ring, such as TX queues,
722  *      free buffer lists, response queues, etc.  Each SGE ring requires
723  *      space for its hardware descriptors plus, optionally, space for software
724  *      state associated with each hardware entry (the metadata).  The function
725  *      returns three values: the virtual address for the hardware ring (the
726  *      return value of the function), the PCI bus address of the hardware
727  *      ring (in *busaddrp), and the address of the software ring (in swringp).
728  *      Both the hardware and software rings are returned zeroed out.
729  */
730 static void *alloc_ring(struct device *dev, size_t nelem, size_t hwsize,
731                         size_t swsize, dma_addr_t *busaddrp, void *swringp,
732                         size_t stat_size)
733 {
734         /*
735          * Allocate the hardware ring and PCI DMA bus address space for said.
736          */
737         size_t hwlen = nelem * hwsize + stat_size;
738         void *hwring = dma_alloc_coherent(dev, hwlen, busaddrp, GFP_KERNEL);
739
740         if (!hwring)
741                 return NULL;
742
743         /*
744          * If the caller wants a software ring, allocate it and return a
745          * pointer to it in *swringp.
746          */
747         BUG_ON((swsize != 0) != (swringp != NULL));
748         if (swsize) {
749                 void *swring = kcalloc(nelem, swsize, GFP_KERNEL);
750
751                 if (!swring) {
752                         dma_free_coherent(dev, hwlen, hwring, *busaddrp);
753                         return NULL;
754                 }
755                 *(void **)swringp = swring;
756         }
757
758         /*
759          * Zero out the hardware ring and return its address as our function
760          * value.
761          */
762         memset(hwring, 0, hwlen);
763         return hwring;
764 }
765
766 /**
767  *      sgl_len - calculates the size of an SGL of the given capacity
768  *      @n: the number of SGL entries
769  *
770  *      Calculates the number of flits (8-byte units) needed for a Direct
771  *      Scatter/Gather List that can hold the given number of entries.
772  */
773 static inline unsigned int sgl_len(unsigned int n)
774 {
775         /*
776          * A Direct Scatter Gather List uses 32-bit lengths and 64-bit PCI DMA
777          * addresses.  The DSGL Work Request starts off with a 32-bit DSGL
778          * ULPTX header, then Length0, then Address0, then, for 1 <= i <= N,
779          * repeated sequences of { Length[i], Length[i+1], Address[i],
780          * Address[i+1] } (this ensures that all addresses are on 64-bit
781          * boundaries).  If N is even, then Length[N+1] should be set to 0 and
782          * Address[N+1] is omitted.
783          *
784          * The following calculation incorporates all of the above.  It's
785          * somewhat hard to follow but, briefly: the "+2" accounts for the
786          * first two flits which include the DSGL header, Length0 and
787          * Address0; the "(3*(n-1))/2" covers the main body of list entries (3
788          * flits for every pair of the remaining N) +1 if (n-1) is odd; and
789          * finally the "+((n-1)&1)" adds the one remaining flit needed if
790          * (n-1) is odd ...
791          */
792         n--;
793         return (3 * n) / 2 + (n & 1) + 2;
794 }
795
796 /**
797  *      flits_to_desc - returns the num of TX descriptors for the given flits
798  *      @flits: the number of flits
799  *
800  *      Returns the number of TX descriptors needed for the supplied number
801  *      of flits.
802  */
803 static inline unsigned int flits_to_desc(unsigned int flits)
804 {
805         BUG_ON(flits > SGE_MAX_WR_LEN / sizeof(__be64));
806         return DIV_ROUND_UP(flits, TXD_PER_EQ_UNIT);
807 }
808
809 /**
810  *      is_eth_imm - can an Ethernet packet be sent as immediate data?
811  *      @skb: the packet
812  *
813  *      Returns whether an Ethernet packet is small enough to fit completely as
814  *      immediate data.
815  */
816 static inline int is_eth_imm(const struct sk_buff *skb)
817 {
818         /*
819          * The VF Driver uses the FW_ETH_TX_PKT_VM_WR firmware Work Request
820          * which does not accommodate immediate data.  We could dike out all
821          * of the support code for immediate data but that would tie our hands
822          * too much if we ever want to enhace the firmware.  It would also
823          * create more differences between the PF and VF Drivers.
824          */
825         return false;
826 }
827
828 /**
829  *      calc_tx_flits - calculate the number of flits for a packet TX WR
830  *      @skb: the packet
831  *
832  *      Returns the number of flits needed for a TX Work Request for the
833  *      given Ethernet packet, including the needed WR and CPL headers.
834  */
835 static inline unsigned int calc_tx_flits(const struct sk_buff *skb)
836 {
837         unsigned int flits;
838
839         /*
840          * If the skb is small enough, we can pump it out as a work request
841          * with only immediate data.  In that case we just have to have the
842          * TX Packet header plus the skb data in the Work Request.
843          */
844         if (is_eth_imm(skb))
845                 return DIV_ROUND_UP(skb->len + sizeof(struct cpl_tx_pkt),
846                                     sizeof(__be64));
847
848         /*
849          * Otherwise, we're going to have to construct a Scatter gather list
850          * of the skb body and fragments.  We also include the flits necessary
851          * for the TX Packet Work Request and CPL.  We always have a firmware
852          * Write Header (incorporated as part of the cpl_tx_pkt_lso and
853          * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
854          * message or, if we're doing a Large Send Offload, an LSO CPL message
855          * with an embeded TX Packet Write CPL message.
856          */
857         flits = sgl_len(skb_shinfo(skb)->nr_frags + 1);
858         if (skb_shinfo(skb)->gso_size)
859                 flits += (sizeof(struct fw_eth_tx_pkt_vm_wr) +
860                           sizeof(struct cpl_tx_pkt_lso_core) +
861                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
862         else
863                 flits += (sizeof(struct fw_eth_tx_pkt_vm_wr) +
864                           sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
865         return flits;
866 }
867
868 /**
869  *      write_sgl - populate a Scatter/Gather List for a packet
870  *      @skb: the packet
871  *      @tq: the TX queue we are writing into
872  *      @sgl: starting location for writing the SGL
873  *      @end: points right after the end of the SGL
874  *      @start: start offset into skb main-body data to include in the SGL
875  *      @addr: the list of DMA bus addresses for the SGL elements
876  *
877  *      Generates a Scatter/Gather List for the buffers that make up a packet.
878  *      The caller must provide adequate space for the SGL that will be written.
879  *      The SGL includes all of the packet's page fragments and the data in its
880  *      main body except for the first @start bytes.  @pos must be 16-byte
881  *      aligned and within a TX descriptor with available space.  @end points
882  *      write after the end of the SGL but does not account for any potential
883  *      wrap around, i.e., @end > @tq->stat.
884  */
885 static void write_sgl(const struct sk_buff *skb, struct sge_txq *tq,
886                       struct ulptx_sgl *sgl, u64 *end, unsigned int start,
887                       const dma_addr_t *addr)
888 {
889         unsigned int i, len;
890         struct ulptx_sge_pair *to;
891         const struct skb_shared_info *si = skb_shinfo(skb);
892         unsigned int nfrags = si->nr_frags;
893         struct ulptx_sge_pair buf[MAX_SKB_FRAGS / 2 + 1];
894
895         len = skb_headlen(skb) - start;
896         if (likely(len)) {
897                 sgl->len0 = htonl(len);
898                 sgl->addr0 = cpu_to_be64(addr[0] + start);
899                 nfrags++;
900         } else {
901                 sgl->len0 = htonl(si->frags[0].size);
902                 sgl->addr0 = cpu_to_be64(addr[1]);
903         }
904
905         sgl->cmd_nsge = htonl(ULPTX_CMD(ULP_TX_SC_DSGL) |
906                               ULPTX_NSGE(nfrags));
907         if (likely(--nfrags == 0))
908                 return;
909         /*
910          * Most of the complexity below deals with the possibility we hit the
911          * end of the queue in the middle of writing the SGL.  For this case
912          * only we create the SGL in a temporary buffer and then copy it.
913          */
914         to = (u8 *)end > (u8 *)tq->stat ? buf : sgl->sge;
915
916         for (i = (nfrags != si->nr_frags); nfrags >= 2; nfrags -= 2, to++) {
917                 to->len[0] = cpu_to_be32(si->frags[i].size);
918                 to->len[1] = cpu_to_be32(si->frags[++i].size);
919                 to->addr[0] = cpu_to_be64(addr[i]);
920                 to->addr[1] = cpu_to_be64(addr[++i]);
921         }
922         if (nfrags) {
923                 to->len[0] = cpu_to_be32(si->frags[i].size);
924                 to->len[1] = cpu_to_be32(0);
925                 to->addr[0] = cpu_to_be64(addr[i + 1]);
926         }
927         if (unlikely((u8 *)end > (u8 *)tq->stat)) {
928                 unsigned int part0 = (u8 *)tq->stat - (u8 *)sgl->sge, part1;
929
930                 if (likely(part0))
931                         memcpy(sgl->sge, buf, part0);
932                 part1 = (u8 *)end - (u8 *)tq->stat;
933                 memcpy(tq->desc, (u8 *)buf + part0, part1);
934                 end = (void *)tq->desc + part1;
935         }
936         if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
937                 *(u64 *)end = 0;
938 }
939
940 /**
941  *      check_ring_tx_db - check and potentially ring a TX queue's doorbell
942  *      @adapter: the adapter
943  *      @tq: the TX queue
944  *      @n: number of new descriptors to give to HW
945  *
946  *      Ring the doorbel for a TX queue.
947  */
948 static inline void ring_tx_db(struct adapter *adapter, struct sge_txq *tq,
949                               int n)
950 {
951         /*
952          * Warn if we write doorbells with the wrong priority and write
953          * descriptors before telling HW.
954          */
955         WARN_ON((QID(tq->cntxt_id) | PIDX(n)) & DBPRIO);
956         wmb();
957         t4_write_reg(adapter, T4VF_SGE_BASE_ADDR + SGE_VF_KDOORBELL,
958                      QID(tq->cntxt_id) | PIDX(n));
959 }
960
961 /**
962  *      inline_tx_skb - inline a packet's data into TX descriptors
963  *      @skb: the packet
964  *      @tq: the TX queue where the packet will be inlined
965  *      @pos: starting position in the TX queue to inline the packet
966  *
967  *      Inline a packet's contents directly into TX descriptors, starting at
968  *      the given position within the TX DMA ring.
969  *      Most of the complexity of this operation is dealing with wrap arounds
970  *      in the middle of the packet we want to inline.
971  */
972 static void inline_tx_skb(const struct sk_buff *skb, const struct sge_txq *tq,
973                           void *pos)
974 {
975         u64 *p;
976         int left = (void *)tq->stat - pos;
977
978         if (likely(skb->len <= left)) {
979                 if (likely(!skb->data_len))
980                         skb_copy_from_linear_data(skb, pos, skb->len);
981                 else
982                         skb_copy_bits(skb, 0, pos, skb->len);
983                 pos += skb->len;
984         } else {
985                 skb_copy_bits(skb, 0, pos, left);
986                 skb_copy_bits(skb, left, tq->desc, skb->len - left);
987                 pos = (void *)tq->desc + (skb->len - left);
988         }
989
990         /* 0-pad to multiple of 16 */
991         p = PTR_ALIGN(pos, 8);
992         if ((uintptr_t)p & 8)
993                 *p = 0;
994 }
995
996 /*
997  * Figure out what HW csum a packet wants and return the appropriate control
998  * bits.
999  */
1000 static u64 hwcsum(const struct sk_buff *skb)
1001 {
1002         int csum_type;
1003         const struct iphdr *iph = ip_hdr(skb);
1004
1005         if (iph->version == 4) {
1006                 if (iph->protocol == IPPROTO_TCP)
1007                         csum_type = TX_CSUM_TCPIP;
1008                 else if (iph->protocol == IPPROTO_UDP)
1009                         csum_type = TX_CSUM_UDPIP;
1010                 else {
1011 nocsum:
1012                         /*
1013                          * unknown protocol, disable HW csum
1014                          * and hope a bad packet is detected
1015                          */
1016                         return TXPKT_L4CSUM_DIS;
1017                 }
1018         } else {
1019                 /*
1020                  * this doesn't work with extension headers
1021                  */
1022                 const struct ipv6hdr *ip6h = (const struct ipv6hdr *)iph;
1023
1024                 if (ip6h->nexthdr == IPPROTO_TCP)
1025                         csum_type = TX_CSUM_TCPIP6;
1026                 else if (ip6h->nexthdr == IPPROTO_UDP)
1027                         csum_type = TX_CSUM_UDPIP6;
1028                 else
1029                         goto nocsum;
1030         }
1031
1032         if (likely(csum_type >= TX_CSUM_TCPIP))
1033                 return TXPKT_CSUM_TYPE(csum_type) |
1034                         TXPKT_IPHDR_LEN(skb_network_header_len(skb)) |
1035                         TXPKT_ETHHDR_LEN(skb_network_offset(skb) - ETH_HLEN);
1036         else {
1037                 int start = skb_transport_offset(skb);
1038
1039                 return TXPKT_CSUM_TYPE(csum_type) |
1040                         TXPKT_CSUM_START(start) |
1041                         TXPKT_CSUM_LOC(start + skb->csum_offset);
1042         }
1043 }
1044
1045 /*
1046  * Stop an Ethernet TX queue and record that state change.
1047  */
1048 static void txq_stop(struct sge_eth_txq *txq)
1049 {
1050         netif_tx_stop_queue(txq->txq);
1051         txq->q.stops++;
1052 }
1053
1054 /*
1055  * Advance our software state for a TX queue by adding n in use descriptors.
1056  */
1057 static inline void txq_advance(struct sge_txq *tq, unsigned int n)
1058 {
1059         tq->in_use += n;
1060         tq->pidx += n;
1061         if (tq->pidx >= tq->size)
1062                 tq->pidx -= tq->size;
1063 }
1064
1065 /**
1066  *      t4vf_eth_xmit - add a packet to an Ethernet TX queue
1067  *      @skb: the packet
1068  *      @dev: the egress net device
1069  *
1070  *      Add a packet to an SGE Ethernet TX queue.  Runs with softirqs disabled.
1071  */
1072 int t4vf_eth_xmit(struct sk_buff *skb, struct net_device *dev)
1073 {
1074         u32 wr_mid;
1075         u64 cntrl, *end;
1076         int qidx, credits;
1077         unsigned int flits, ndesc;
1078         struct adapter *adapter;
1079         struct sge_eth_txq *txq;
1080         const struct port_info *pi;
1081         struct fw_eth_tx_pkt_vm_wr *wr;
1082         struct cpl_tx_pkt_core *cpl;
1083         const struct skb_shared_info *ssi;
1084         dma_addr_t addr[MAX_SKB_FRAGS + 1];
1085         const size_t fw_hdr_copy_len = (sizeof(wr->ethmacdst) +
1086                                         sizeof(wr->ethmacsrc) +
1087                                         sizeof(wr->ethtype) +
1088                                         sizeof(wr->vlantci));
1089
1090         /*
1091          * The chip minimum packet length is 10 octets but the firmware
1092          * command that we are using requires that we copy the Ethernet header
1093          * (including the VLAN tag) into the header so we reject anything
1094          * smaller than that ...
1095          */
1096         if (unlikely(skb->len < fw_hdr_copy_len))
1097                 goto out_free;
1098
1099         /*
1100          * Figure out which TX Queue we're going to use.
1101          */
1102         pi = netdev_priv(dev);
1103         adapter = pi->adapter;
1104         qidx = skb_get_queue_mapping(skb);
1105         BUG_ON(qidx >= pi->nqsets);
1106         txq = &adapter->sge.ethtxq[pi->first_qset + qidx];
1107
1108         /*
1109          * Take this opportunity to reclaim any TX Descriptors whose DMA
1110          * transfers have completed.
1111          */
1112         reclaim_completed_tx(adapter, &txq->q, true);
1113
1114         /*
1115          * Calculate the number of flits and TX Descriptors we're going to
1116          * need along with how many TX Descriptors will be left over after
1117          * we inject our Work Request.
1118          */
1119         flits = calc_tx_flits(skb);
1120         ndesc = flits_to_desc(flits);
1121         credits = txq_avail(&txq->q) - ndesc;
1122
1123         if (unlikely(credits < 0)) {
1124                 /*
1125                  * Not enough room for this packet's Work Request.  Stop the
1126                  * TX Queue and return a "busy" condition.  The queue will get
1127                  * started later on when the firmware informs us that space
1128                  * has opened up.
1129                  */
1130                 txq_stop(txq);
1131                 dev_err(adapter->pdev_dev,
1132                         "%s: TX ring %u full while queue awake!\n",
1133                         dev->name, qidx);
1134                 return NETDEV_TX_BUSY;
1135         }
1136
1137         if (!is_eth_imm(skb) &&
1138             unlikely(map_skb(adapter->pdev_dev, skb, addr) < 0)) {
1139                 /*
1140                  * We need to map the skb into PCI DMA space (because it can't
1141                  * be in-lined directly into the Work Request) and the mapping
1142                  * operation failed.  Record the error and drop the packet.
1143                  */
1144                 txq->mapping_err++;
1145                 goto out_free;
1146         }
1147
1148         wr_mid = FW_WR_LEN16(DIV_ROUND_UP(flits, 2));
1149         if (unlikely(credits < ETHTXQ_STOP_THRES)) {
1150                 /*
1151                  * After we're done injecting the Work Request for this
1152                  * packet, we'll be below our "stop threshhold" so stop the TX
1153                  * Queue now and schedule a request for an SGE Egress Queue
1154                  * Update message.  The queue will get started later on when
1155                  * the firmware processes this Work Request and sends us an
1156                  * Egress Queue Status Update message indicating that space
1157                  * has opened up.
1158                  */
1159                 txq_stop(txq);
1160                 wr_mid |= FW_WR_EQUEQ | FW_WR_EQUIQ;
1161         }
1162
1163         /*
1164          * Start filling in our Work Request.  Note that we do _not_ handle
1165          * the WR Header wrapping around the TX Descriptor Ring.  If our
1166          * maximum header size ever exceeds one TX Descriptor, we'll need to
1167          * do something else here.
1168          */
1169         BUG_ON(DIV_ROUND_UP(ETHTXQ_MAX_HDR, TXD_PER_EQ_UNIT) > 1);
1170         wr = (void *)&txq->q.desc[txq->q.pidx];
1171         wr->equiq_to_len16 = cpu_to_be32(wr_mid);
1172         wr->r3[0] = cpu_to_be64(0);
1173         wr->r3[1] = cpu_to_be64(0);
1174         skb_copy_from_linear_data(skb, (void *)wr->ethmacdst, fw_hdr_copy_len);
1175         end = (u64 *)wr + flits;
1176
1177         /*
1178          * If this is a Large Send Offload packet we'll put in an LSO CPL
1179          * message with an encapsulated TX Packet CPL message.  Otherwise we
1180          * just use a TX Packet CPL message.
1181          */
1182         ssi = skb_shinfo(skb);
1183         if (ssi->gso_size) {
1184                 struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
1185                 bool v6 = (ssi->gso_type & SKB_GSO_TCPV6) != 0;
1186                 int l3hdr_len = skb_network_header_len(skb);
1187                 int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1188
1189                 wr->op_immdlen =
1190                         cpu_to_be32(FW_WR_OP(FW_ETH_TX_PKT_VM_WR) |
1191                                     FW_WR_IMMDLEN(sizeof(*lso) +
1192                                                   sizeof(*cpl)));
1193                 /*
1194                  * Fill in the LSO CPL message.
1195                  */
1196                 lso->lso_ctrl =
1197                         cpu_to_be32(LSO_OPCODE(CPL_TX_PKT_LSO) |
1198                                     LSO_FIRST_SLICE |
1199                                     LSO_LAST_SLICE |
1200                                     LSO_IPV6(v6) |
1201                                     LSO_ETHHDR_LEN(eth_xtra_len/4) |
1202                                     LSO_IPHDR_LEN(l3hdr_len/4) |
1203                                     LSO_TCPHDR_LEN(tcp_hdr(skb)->doff));
1204                 lso->ipid_ofst = cpu_to_be16(0);
1205                 lso->mss = cpu_to_be16(ssi->gso_size);
1206                 lso->seqno_offset = cpu_to_be32(0);
1207                 lso->len = cpu_to_be32(skb->len);
1208
1209                 /*
1210                  * Set up TX Packet CPL pointer, control word and perform
1211                  * accounting.
1212                  */
1213                 cpl = (void *)(lso + 1);
1214                 cntrl = (TXPKT_CSUM_TYPE(v6 ? TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
1215                          TXPKT_IPHDR_LEN(l3hdr_len) |
1216                          TXPKT_ETHHDR_LEN(eth_xtra_len));
1217                 txq->tso++;
1218                 txq->tx_cso += ssi->gso_segs;
1219         } else {
1220                 int len;
1221
1222                 len = is_eth_imm(skb) ? skb->len + sizeof(*cpl) : sizeof(*cpl);
1223                 wr->op_immdlen =
1224                         cpu_to_be32(FW_WR_OP(FW_ETH_TX_PKT_VM_WR) |
1225                                     FW_WR_IMMDLEN(len));
1226
1227                 /*
1228                  * Set up TX Packet CPL pointer, control word and perform
1229                  * accounting.
1230                  */
1231                 cpl = (void *)(wr + 1);
1232                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1233                         cntrl = hwcsum(skb) | TXPKT_IPCSUM_DIS;
1234                         txq->tx_cso++;
1235                 } else
1236                         cntrl = TXPKT_L4CSUM_DIS | TXPKT_IPCSUM_DIS;
1237         }
1238
1239         /*
1240          * If there's a VLAN tag present, add that to the list of things to
1241          * do in this Work Request.
1242          */
1243         if (vlan_tx_tag_present(skb)) {
1244                 txq->vlan_ins++;
1245                 cntrl |= TXPKT_VLAN_VLD | TXPKT_VLAN(vlan_tx_tag_get(skb));
1246         }
1247
1248         /*
1249          * Fill in the TX Packet CPL message header.
1250          */
1251         cpl->ctrl0 = cpu_to_be32(TXPKT_OPCODE(CPL_TX_PKT_XT) |
1252                                  TXPKT_INTF(pi->port_id) |
1253                                  TXPKT_PF(0));
1254         cpl->pack = cpu_to_be16(0);
1255         cpl->len = cpu_to_be16(skb->len);
1256         cpl->ctrl1 = cpu_to_be64(cntrl);
1257
1258 #ifdef T4_TRACE
1259         T4_TRACE5(adapter->tb[txq->q.cntxt_id & 7],
1260                   "eth_xmit: ndesc %u, credits %u, pidx %u, len %u, frags %u",
1261                   ndesc, credits, txq->q.pidx, skb->len, ssi->nr_frags);
1262 #endif
1263
1264         /*
1265          * Fill in the body of the TX Packet CPL message with either in-lined
1266          * data or a Scatter/Gather List.
1267          */
1268         if (is_eth_imm(skb)) {
1269                 /*
1270                  * In-line the packet's data and free the skb since we don't
1271                  * need it any longer.
1272                  */
1273                 inline_tx_skb(skb, &txq->q, cpl + 1);
1274                 dev_kfree_skb(skb);
1275         } else {
1276                 /*
1277                  * Write the skb's Scatter/Gather list into the TX Packet CPL
1278                  * message and retain a pointer to the skb so we can free it
1279                  * later when its DMA completes.  (We store the skb pointer
1280                  * in the Software Descriptor corresponding to the last TX
1281                  * Descriptor used by the Work Request.)
1282                  *
1283                  * The retained skb will be freed when the corresponding TX
1284                  * Descriptors are reclaimed after their DMAs complete.
1285                  * However, this could take quite a while since, in general,
1286                  * the hardware is set up to be lazy about sending DMA
1287                  * completion notifications to us and we mostly perform TX
1288                  * reclaims in the transmit routine.
1289                  *
1290                  * This is good for performamce but means that we rely on new
1291                  * TX packets arriving to run the destructors of completed
1292                  * packets, which open up space in their sockets' send queues.
1293                  * Sometimes we do not get such new packets causing TX to
1294                  * stall.  A single UDP transmitter is a good example of this
1295                  * situation.  We have a clean up timer that periodically
1296                  * reclaims completed packets but it doesn't run often enough
1297                  * (nor do we want it to) to prevent lengthy stalls.  A
1298                  * solution to this problem is to run the destructor early,
1299                  * after the packet is queued but before it's DMAd.  A con is
1300                  * that we lie to socket memory accounting, but the amount of
1301                  * extra memory is reasonable (limited by the number of TX
1302                  * descriptors), the packets do actually get freed quickly by
1303                  * new packets almost always, and for protocols like TCP that
1304                  * wait for acks to really free up the data the extra memory
1305                  * is even less.  On the positive side we run the destructors
1306                  * on the sending CPU rather than on a potentially different
1307                  * completing CPU, usually a good thing.
1308                  *
1309                  * Run the destructor before telling the DMA engine about the
1310                  * packet to make sure it doesn't complete and get freed
1311                  * prematurely.
1312                  */
1313                 struct ulptx_sgl *sgl = (struct ulptx_sgl *)(cpl + 1);
1314                 struct sge_txq *tq = &txq->q;
1315                 int last_desc;
1316
1317                 /*
1318                  * If the Work Request header was an exact multiple of our TX
1319                  * Descriptor length, then it's possible that the starting SGL
1320                  * pointer lines up exactly with the end of our TX Descriptor
1321                  * ring.  If that's the case, wrap around to the beginning
1322                  * here ...
1323                  */
1324                 if (unlikely((void *)sgl == (void *)tq->stat)) {
1325                         sgl = (void *)tq->desc;
1326                         end = (void *)((void *)tq->desc +
1327                                        ((void *)end - (void *)tq->stat));
1328                 }
1329
1330                 write_sgl(skb, tq, sgl, end, 0, addr);
1331                 skb_orphan(skb);
1332
1333                 last_desc = tq->pidx + ndesc - 1;
1334                 if (last_desc >= tq->size)
1335                         last_desc -= tq->size;
1336                 tq->sdesc[last_desc].skb = skb;
1337                 tq->sdesc[last_desc].sgl = sgl;
1338         }
1339
1340         /*
1341          * Advance our internal TX Queue state, tell the hardware about
1342          * the new TX descriptors and return success.
1343          */
1344         txq_advance(&txq->q, ndesc);
1345         dev->trans_start = jiffies;
1346         ring_tx_db(adapter, &txq->q, ndesc);
1347         return NETDEV_TX_OK;
1348
1349 out_free:
1350         /*
1351          * An error of some sort happened.  Free the TX skb and tell the
1352          * OS that we've "dealt" with the packet ...
1353          */
1354         dev_kfree_skb(skb);
1355         return NETDEV_TX_OK;
1356 }
1357
1358 /**
1359  *      t4vf_pktgl_to_skb - build an sk_buff from a packet gather list
1360  *      @gl: the gather list
1361  *      @skb_len: size of sk_buff main body if it carries fragments
1362  *      @pull_len: amount of data to move to the sk_buff's main body
1363  *
1364  *      Builds an sk_buff from the given packet gather list.  Returns the
1365  *      sk_buff or %NULL if sk_buff allocation failed.
1366  */
1367 struct sk_buff *t4vf_pktgl_to_skb(const struct pkt_gl *gl,
1368                                   unsigned int skb_len, unsigned int pull_len)
1369 {
1370         struct sk_buff *skb;
1371         struct skb_shared_info *ssi;
1372
1373         /*
1374          * If the ingress packet is small enough, allocate an skb large enough
1375          * for all of the data and copy it inline.  Otherwise, allocate an skb
1376          * with enough room to pull in the header and reference the rest of
1377          * the data via the skb fragment list.
1378          *
1379          * Below we rely on RX_COPY_THRES being less than the smallest Rx
1380          * buff!  size, which is expected since buffers are at least
1381          * PAGE_SIZEd.  In this case packets up to RX_COPY_THRES have only one
1382          * fragment.
1383          */
1384         if (gl->tot_len <= RX_COPY_THRES) {
1385                 /* small packets have only one fragment */
1386                 skb = alloc_skb(gl->tot_len, GFP_ATOMIC);
1387                 if (unlikely(!skb))
1388                         goto out;
1389                 __skb_put(skb, gl->tot_len);
1390                 skb_copy_to_linear_data(skb, gl->va, gl->tot_len);
1391         } else {
1392                 skb = alloc_skb(skb_len, GFP_ATOMIC);
1393                 if (unlikely(!skb))
1394                         goto out;
1395                 __skb_put(skb, pull_len);
1396                 skb_copy_to_linear_data(skb, gl->va, pull_len);
1397
1398                 ssi = skb_shinfo(skb);
1399                 ssi->frags[0].page = gl->frags[0].page;
1400                 ssi->frags[0].page_offset = gl->frags[0].page_offset + pull_len;
1401                 ssi->frags[0].size = gl->frags[0].size - pull_len;
1402                 if (gl->nfrags > 1)
1403                         memcpy(&ssi->frags[1], &gl->frags[1],
1404                                (gl->nfrags-1) * sizeof(skb_frag_t));
1405                 ssi->nr_frags = gl->nfrags;
1406
1407                 skb->len = gl->tot_len;
1408                 skb->data_len = skb->len - pull_len;
1409                 skb->truesize += skb->data_len;
1410
1411                 /* Get a reference for the last page, we don't own it */
1412                 get_page(gl->frags[gl->nfrags - 1].page);
1413         }
1414
1415 out:
1416         return skb;
1417 }
1418
1419 /**
1420  *      t4vf_pktgl_free - free a packet gather list
1421  *      @gl: the gather list
1422  *
1423  *      Releases the pages of a packet gather list.  We do not own the last
1424  *      page on the list and do not free it.
1425  */
1426 void t4vf_pktgl_free(const struct pkt_gl *gl)
1427 {
1428         int frag;
1429
1430         frag = gl->nfrags - 1;
1431         while (frag--)
1432                 put_page(gl->frags[frag].page);
1433 }
1434
1435 /**
1436  *      copy_frags - copy fragments from gather list into skb_shared_info
1437  *      @si: destination skb shared info structure
1438  *      @gl: source internal packet gather list
1439  *      @offset: packet start offset in first page
1440  *
1441  *      Copy an internal packet gather list into a Linux skb_shared_info
1442  *      structure.
1443  */
1444 static inline void copy_frags(struct skb_shared_info *si,
1445                               const struct pkt_gl *gl,
1446                               unsigned int offset)
1447 {
1448         unsigned int n;
1449
1450         /* usually there's just one frag */
1451         si->frags[0].page = gl->frags[0].page;
1452         si->frags[0].page_offset = gl->frags[0].page_offset + offset;
1453         si->frags[0].size = gl->frags[0].size - offset;
1454         si->nr_frags = gl->nfrags;
1455
1456         n = gl->nfrags - 1;
1457         if (n)
1458                 memcpy(&si->frags[1], &gl->frags[1], n * sizeof(skb_frag_t));
1459
1460         /* get a reference to the last page, we don't own it */
1461         get_page(gl->frags[n].page);
1462 }
1463
1464 /**
1465  *      do_gro - perform Generic Receive Offload ingress packet processing
1466  *      @rxq: ingress RX Ethernet Queue
1467  *      @gl: gather list for ingress packet
1468  *      @pkt: CPL header for last packet fragment
1469  *
1470  *      Perform Generic Receive Offload (GRO) ingress packet processing.
1471  *      We use the standard Linux GRO interfaces for this.
1472  */
1473 static void do_gro(struct sge_eth_rxq *rxq, const struct pkt_gl *gl,
1474                    const struct cpl_rx_pkt *pkt)
1475 {
1476         int ret;
1477         struct sk_buff *skb;
1478
1479         skb = napi_get_frags(&rxq->rspq.napi);
1480         if (unlikely(!skb)) {
1481                 t4vf_pktgl_free(gl);
1482                 rxq->stats.rx_drops++;
1483                 return;
1484         }
1485
1486         copy_frags(skb_shinfo(skb), gl, PKTSHIFT);
1487         skb->len = gl->tot_len - PKTSHIFT;
1488         skb->data_len = skb->len;
1489         skb->truesize += skb->data_len;
1490         skb->ip_summed = CHECKSUM_UNNECESSARY;
1491         skb_record_rx_queue(skb, rxq->rspq.idx);
1492
1493         if (unlikely(pkt->vlan_ex)) {
1494                 struct port_info *pi = netdev_priv(rxq->rspq.netdev);
1495                 struct vlan_group *grp = pi->vlan_grp;
1496
1497                 rxq->stats.vlan_ex++;
1498                 if (likely(grp)) {
1499                         ret = vlan_gro_frags(&rxq->rspq.napi, grp,
1500                                              be16_to_cpu(pkt->vlan));
1501                         goto stats;
1502                 }
1503         }
1504         ret = napi_gro_frags(&rxq->rspq.napi);
1505
1506 stats:
1507         if (ret == GRO_HELD)
1508                 rxq->stats.lro_pkts++;
1509         else if (ret == GRO_MERGED || ret == GRO_MERGED_FREE)
1510                 rxq->stats.lro_merged++;
1511         rxq->stats.pkts++;
1512         rxq->stats.rx_cso++;
1513 }
1514
1515 /**
1516  *      t4vf_ethrx_handler - process an ingress ethernet packet
1517  *      @rspq: the response queue that received the packet
1518  *      @rsp: the response queue descriptor holding the RX_PKT message
1519  *      @gl: the gather list of packet fragments
1520  *
1521  *      Process an ingress ethernet packet and deliver it to the stack.
1522  */
1523 int t4vf_ethrx_handler(struct sge_rspq *rspq, const __be64 *rsp,
1524                        const struct pkt_gl *gl)
1525 {
1526         struct sk_buff *skb;
1527         struct port_info *pi;
1528         const struct cpl_rx_pkt *pkt = (void *)&rsp[1];
1529         bool csum_ok = pkt->csum_calc && !pkt->err_vec;
1530         struct sge_eth_rxq *rxq = container_of(rspq, struct sge_eth_rxq, rspq);
1531
1532         /*
1533          * If this is a good TCP packet and we have Generic Receive Offload
1534          * enabled, handle the packet in the GRO path.
1535          */
1536         if ((pkt->l2info & cpu_to_be32(RXF_TCP)) &&
1537             (rspq->netdev->features & NETIF_F_GRO) && csum_ok &&
1538             !pkt->ip_frag) {
1539                 do_gro(rxq, gl, pkt);
1540                 return 0;
1541         }
1542
1543         /*
1544          * Convert the Packet Gather List into an skb.
1545          */
1546         skb = t4vf_pktgl_to_skb(gl, RX_SKB_LEN, RX_PULL_LEN);
1547         if (unlikely(!skb)) {
1548                 t4vf_pktgl_free(gl);
1549                 rxq->stats.rx_drops++;
1550                 return 0;
1551         }
1552         __skb_pull(skb, PKTSHIFT);
1553         skb->protocol = eth_type_trans(skb, rspq->netdev);
1554         skb_record_rx_queue(skb, rspq->idx);
1555         pi = netdev_priv(skb->dev);
1556         rxq->stats.pkts++;
1557
1558         if (csum_ok && (pi->rx_offload & RX_CSO) && !pkt->err_vec &&
1559             (be32_to_cpu(pkt->l2info) & (RXF_UDP|RXF_TCP))) {
1560                 if (!pkt->ip_frag)
1561                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1562                 else {
1563                         __sum16 c = (__force __sum16)pkt->csum;
1564                         skb->csum = csum_unfold(c);
1565                         skb->ip_summed = CHECKSUM_COMPLETE;
1566                 }
1567                 rxq->stats.rx_cso++;
1568         } else
1569                 skb_checksum_none_assert(skb);
1570
1571         if (unlikely(pkt->vlan_ex)) {
1572                 struct vlan_group *grp = pi->vlan_grp;
1573
1574                 rxq->stats.vlan_ex++;
1575                 if (likely(grp))
1576                         vlan_hwaccel_receive_skb(skb, grp,
1577                                                  be16_to_cpu(pkt->vlan));
1578                 else
1579                         dev_kfree_skb_any(skb);
1580         } else
1581                 netif_receive_skb(skb);
1582
1583         return 0;
1584 }
1585
1586 /**
1587  *      is_new_response - check if a response is newly written
1588  *      @rc: the response control descriptor
1589  *      @rspq: the response queue
1590  *
1591  *      Returns true if a response descriptor contains a yet unprocessed
1592  *      response.
1593  */
1594 static inline bool is_new_response(const struct rsp_ctrl *rc,
1595                                    const struct sge_rspq *rspq)
1596 {
1597         return RSPD_GEN(rc->type_gen) == rspq->gen;
1598 }
1599
1600 /**
1601  *      restore_rx_bufs - put back a packet's RX buffers
1602  *      @gl: the packet gather list
1603  *      @fl: the SGE Free List
1604  *      @nfrags: how many fragments in @si
1605  *
1606  *      Called when we find out that the current packet, @si, can't be
1607  *      processed right away for some reason.  This is a very rare event and
1608  *      there's no effort to make this suspension/resumption process
1609  *      particularly efficient.
1610  *
1611  *      We implement the suspension by putting all of the RX buffers associated
1612  *      with the current packet back on the original Free List.  The buffers
1613  *      have already been unmapped and are left unmapped, we mark them as
1614  *      unmapped in order to prevent further unmapping attempts.  (Effectively
1615  *      this function undoes the series of @unmap_rx_buf calls which were done
1616  *      to create the current packet's gather list.)  This leaves us ready to
1617  *      restart processing of the packet the next time we start processing the
1618  *      RX Queue ...
1619  */
1620 static void restore_rx_bufs(const struct pkt_gl *gl, struct sge_fl *fl,
1621                             int frags)
1622 {
1623         struct rx_sw_desc *sdesc;
1624
1625         while (frags--) {
1626                 if (fl->cidx == 0)
1627                         fl->cidx = fl->size - 1;
1628                 else
1629                         fl->cidx--;
1630                 sdesc = &fl->sdesc[fl->cidx];
1631                 sdesc->page = gl->frags[frags].page;
1632                 sdesc->dma_addr |= RX_UNMAPPED_BUF;
1633                 fl->avail++;
1634         }
1635 }
1636
1637 /**
1638  *      rspq_next - advance to the next entry in a response queue
1639  *      @rspq: the queue
1640  *
1641  *      Updates the state of a response queue to advance it to the next entry.
1642  */
1643 static inline void rspq_next(struct sge_rspq *rspq)
1644 {
1645         rspq->cur_desc = (void *)rspq->cur_desc + rspq->iqe_len;
1646         if (unlikely(++rspq->cidx == rspq->size)) {
1647                 rspq->cidx = 0;
1648                 rspq->gen ^= 1;
1649                 rspq->cur_desc = rspq->desc;
1650         }
1651 }
1652
1653 /**
1654  *      process_responses - process responses from an SGE response queue
1655  *      @rspq: the ingress response queue to process
1656  *      @budget: how many responses can be processed in this round
1657  *
1658  *      Process responses from a Scatter Gather Engine response queue up to
1659  *      the supplied budget.  Responses include received packets as well as
1660  *      control messages from firmware or hardware.
1661  *
1662  *      Additionally choose the interrupt holdoff time for the next interrupt
1663  *      on this queue.  If the system is under memory shortage use a fairly
1664  *      long delay to help recovery.
1665  */
1666 int process_responses(struct sge_rspq *rspq, int budget)
1667 {
1668         struct sge_eth_rxq *rxq = container_of(rspq, struct sge_eth_rxq, rspq);
1669         int budget_left = budget;
1670
1671         while (likely(budget_left)) {
1672                 int ret, rsp_type;
1673                 const struct rsp_ctrl *rc;
1674
1675                 rc = (void *)rspq->cur_desc + (rspq->iqe_len - sizeof(*rc));
1676                 if (!is_new_response(rc, rspq))
1677                         break;
1678
1679                 /*
1680                  * Figure out what kind of response we've received from the
1681                  * SGE.
1682                  */
1683                 rmb();
1684                 rsp_type = RSPD_TYPE(rc->type_gen);
1685                 if (likely(rsp_type == RSP_TYPE_FLBUF)) {
1686                         skb_frag_t *fp;
1687                         struct pkt_gl gl;
1688                         const struct rx_sw_desc *sdesc;
1689                         u32 bufsz, frag;
1690                         u32 len = be32_to_cpu(rc->pldbuflen_qid);
1691
1692                         /*
1693                          * If we get a "new buffer" message from the SGE we
1694                          * need to move on to the next Free List buffer.
1695                          */
1696                         if (len & RSPD_NEWBUF) {
1697                                 /*
1698                                  * We get one "new buffer" message when we
1699                                  * first start up a queue so we need to ignore
1700                                  * it when our offset into the buffer is 0.
1701                                  */
1702                                 if (likely(rspq->offset > 0)) {
1703                                         free_rx_bufs(rspq->adapter, &rxq->fl,
1704                                                      1);
1705                                         rspq->offset = 0;
1706                                 }
1707                                 len = RSPD_LEN(len);
1708                         }
1709                         gl.tot_len = len;
1710
1711                         /*
1712                          * Gather packet fragments.
1713                          */
1714                         for (frag = 0, fp = gl.frags; /**/; frag++, fp++) {
1715                                 BUG_ON(frag >= MAX_SKB_FRAGS);
1716                                 BUG_ON(rxq->fl.avail == 0);
1717                                 sdesc = &rxq->fl.sdesc[rxq->fl.cidx];
1718                                 bufsz = get_buf_size(sdesc);
1719                                 fp->page = sdesc->page;
1720                                 fp->page_offset = rspq->offset;
1721                                 fp->size = min(bufsz, len);
1722                                 len -= fp->size;
1723                                 if (!len)
1724                                         break;
1725                                 unmap_rx_buf(rspq->adapter, &rxq->fl);
1726                         }
1727                         gl.nfrags = frag+1;
1728
1729                         /*
1730                          * Last buffer remains mapped so explicitly make it
1731                          * coherent for CPU access and start preloading first
1732                          * cache line ...
1733                          */
1734                         dma_sync_single_for_cpu(rspq->adapter->pdev_dev,
1735                                                 get_buf_addr(sdesc),
1736                                                 fp->size, DMA_FROM_DEVICE);
1737                         gl.va = (page_address(gl.frags[0].page) +
1738                                  gl.frags[0].page_offset);
1739                         prefetch(gl.va);
1740
1741                         /*
1742                          * Hand the new ingress packet to the handler for
1743                          * this Response Queue.
1744                          */
1745                         ret = rspq->handler(rspq, rspq->cur_desc, &gl);
1746                         if (likely(ret == 0))
1747                                 rspq->offset += ALIGN(fp->size, FL_ALIGN);
1748                         else
1749                                 restore_rx_bufs(&gl, &rxq->fl, frag);
1750                 } else if (likely(rsp_type == RSP_TYPE_CPL)) {
1751                         ret = rspq->handler(rspq, rspq->cur_desc, NULL);
1752                 } else {
1753                         WARN_ON(rsp_type > RSP_TYPE_CPL);
1754                         ret = 0;
1755                 }
1756
1757                 if (unlikely(ret)) {
1758                         /*
1759                          * Couldn't process descriptor, back off for recovery.
1760                          * We use the SGE's last timer which has the longest
1761                          * interrupt coalescing value ...
1762                          */
1763                         const int NOMEM_TIMER_IDX = SGE_NTIMERS-1;
1764                         rspq->next_intr_params =
1765                                 QINTR_TIMER_IDX(NOMEM_TIMER_IDX);
1766                         break;
1767                 }
1768
1769                 rspq_next(rspq);
1770                 budget_left--;
1771         }
1772
1773         /*
1774          * If this is a Response Queue with an associated Free List and
1775          * at least two Egress Queue units available in the Free List
1776          * for new buffer pointers, refill the Free List.
1777          */
1778         if (rspq->offset >= 0 &&
1779             rxq->fl.size - rxq->fl.avail >= 2*FL_PER_EQ_UNIT)
1780                 __refill_fl(rspq->adapter, &rxq->fl);
1781         return budget - budget_left;
1782 }
1783
1784 /**
1785  *      napi_rx_handler - the NAPI handler for RX processing
1786  *      @napi: the napi instance
1787  *      @budget: how many packets we can process in this round
1788  *
1789  *      Handler for new data events when using NAPI.  This does not need any
1790  *      locking or protection from interrupts as data interrupts are off at
1791  *      this point and other adapter interrupts do not interfere (the latter
1792  *      in not a concern at all with MSI-X as non-data interrupts then have
1793  *      a separate handler).
1794  */
1795 static int napi_rx_handler(struct napi_struct *napi, int budget)
1796 {
1797         unsigned int intr_params;
1798         struct sge_rspq *rspq = container_of(napi, struct sge_rspq, napi);
1799         int work_done = process_responses(rspq, budget);
1800
1801         if (likely(work_done < budget)) {
1802                 napi_complete(napi);
1803                 intr_params = rspq->next_intr_params;
1804                 rspq->next_intr_params = rspq->intr_params;
1805         } else
1806                 intr_params = QINTR_TIMER_IDX(SGE_TIMER_UPD_CIDX);
1807
1808         if (unlikely(work_done == 0))
1809                 rspq->unhandled_irqs++;
1810
1811         t4_write_reg(rspq->adapter,
1812                      T4VF_SGE_BASE_ADDR + SGE_VF_GTS,
1813                      CIDXINC(work_done) |
1814                      INGRESSQID((u32)rspq->cntxt_id) |
1815                      SEINTARM(intr_params));
1816         return work_done;
1817 }
1818
1819 /*
1820  * The MSI-X interrupt handler for an SGE response queue for the NAPI case
1821  * (i.e., response queue serviced by NAPI polling).
1822  */
1823 irqreturn_t t4vf_sge_intr_msix(int irq, void *cookie)
1824 {
1825         struct sge_rspq *rspq = cookie;
1826
1827         napi_schedule(&rspq->napi);
1828         return IRQ_HANDLED;
1829 }
1830
1831 /*
1832  * Process the indirect interrupt entries in the interrupt queue and kick off
1833  * NAPI for each queue that has generated an entry.
1834  */
1835 static unsigned int process_intrq(struct adapter *adapter)
1836 {
1837         struct sge *s = &adapter->sge;
1838         struct sge_rspq *intrq = &s->intrq;
1839         unsigned int work_done;
1840
1841         spin_lock(&adapter->sge.intrq_lock);
1842         for (work_done = 0; ; work_done++) {
1843                 const struct rsp_ctrl *rc;
1844                 unsigned int qid, iq_idx;
1845                 struct sge_rspq *rspq;
1846
1847                 /*
1848                  * Grab the next response from the interrupt queue and bail
1849                  * out if it's not a new response.
1850                  */
1851                 rc = (void *)intrq->cur_desc + (intrq->iqe_len - sizeof(*rc));
1852                 if (!is_new_response(rc, intrq))
1853                         break;
1854
1855                 /*
1856                  * If the response isn't a forwarded interrupt message issue a
1857                  * error and go on to the next response message.  This should
1858                  * never happen ...
1859                  */
1860                 rmb();
1861                 if (unlikely(RSPD_TYPE(rc->type_gen) != RSP_TYPE_INTR)) {
1862                         dev_err(adapter->pdev_dev,
1863                                 "Unexpected INTRQ response type %d\n",
1864                                 RSPD_TYPE(rc->type_gen));
1865                         continue;
1866                 }
1867
1868                 /*
1869                  * Extract the Queue ID from the interrupt message and perform
1870                  * sanity checking to make sure it really refers to one of our
1871                  * Ingress Queues which is active and matches the queue's ID.
1872                  * None of these error conditions should ever happen so we may
1873                  * want to either make them fatal and/or conditionalized under
1874                  * DEBUG.
1875                  */
1876                 qid = RSPD_QID(be32_to_cpu(rc->pldbuflen_qid));
1877                 iq_idx = IQ_IDX(s, qid);
1878                 if (unlikely(iq_idx >= MAX_INGQ)) {
1879                         dev_err(adapter->pdev_dev,
1880                                 "Ingress QID %d out of range\n", qid);
1881                         continue;
1882                 }
1883                 rspq = s->ingr_map[iq_idx];
1884                 if (unlikely(rspq == NULL)) {
1885                         dev_err(adapter->pdev_dev,
1886                                 "Ingress QID %d RSPQ=NULL\n", qid);
1887                         continue;
1888                 }
1889                 if (unlikely(rspq->abs_id != qid)) {
1890                         dev_err(adapter->pdev_dev,
1891                                 "Ingress QID %d refers to RSPQ %d\n",
1892                                 qid, rspq->abs_id);
1893                         continue;
1894                 }
1895
1896                 /*
1897                  * Schedule NAPI processing on the indicated Response Queue
1898                  * and move on to the next entry in the Forwarded Interrupt
1899                  * Queue.
1900                  */
1901                 napi_schedule(&rspq->napi);
1902                 rspq_next(intrq);
1903         }
1904
1905         t4_write_reg(adapter, T4VF_SGE_BASE_ADDR + SGE_VF_GTS,
1906                      CIDXINC(work_done) |
1907                      INGRESSQID(intrq->cntxt_id) |
1908                      SEINTARM(intrq->intr_params));
1909
1910         spin_unlock(&adapter->sge.intrq_lock);
1911
1912         return work_done;
1913 }
1914
1915 /*
1916  * The MSI interrupt handler handles data events from SGE response queues as
1917  * well as error and other async events as they all use the same MSI vector.
1918  */
1919 irqreturn_t t4vf_intr_msi(int irq, void *cookie)
1920 {
1921         struct adapter *adapter = cookie;
1922
1923         process_intrq(adapter);
1924         return IRQ_HANDLED;
1925 }
1926
1927 /**
1928  *      t4vf_intr_handler - select the top-level interrupt handler
1929  *      @adapter: the adapter
1930  *
1931  *      Selects the top-level interrupt handler based on the type of interrupts
1932  *      (MSI-X or MSI).
1933  */
1934 irq_handler_t t4vf_intr_handler(struct adapter *adapter)
1935 {
1936         BUG_ON((adapter->flags & (USING_MSIX|USING_MSI)) == 0);
1937         if (adapter->flags & USING_MSIX)
1938                 return t4vf_sge_intr_msix;
1939         else
1940                 return t4vf_intr_msi;
1941 }
1942
1943 /**
1944  *      sge_rx_timer_cb - perform periodic maintenance of SGE RX queues
1945  *      @data: the adapter
1946  *
1947  *      Runs periodically from a timer to perform maintenance of SGE RX queues.
1948  *
1949  *      a) Replenishes RX queues that have run out due to memory shortage.
1950  *      Normally new RX buffers are added when existing ones are consumed but
1951  *      when out of memory a queue can become empty.  We schedule NAPI to do
1952  *      the actual refill.
1953  */
1954 static void sge_rx_timer_cb(unsigned long data)
1955 {
1956         struct adapter *adapter = (struct adapter *)data;
1957         struct sge *s = &adapter->sge;
1958         unsigned int i;
1959
1960         /*
1961          * Scan the "Starving Free Lists" flag array looking for any Free
1962          * Lists in need of more free buffers.  If we find one and it's not
1963          * being actively polled, then bump its "starving" counter and attempt
1964          * to refill it.  If we're successful in adding enough buffers to push
1965          * the Free List over the starving threshold, then we can clear its
1966          * "starving" status.
1967          */
1968         for (i = 0; i < ARRAY_SIZE(s->starving_fl); i++) {
1969                 unsigned long m;
1970
1971                 for (m = s->starving_fl[i]; m; m &= m - 1) {
1972                         unsigned int id = __ffs(m) + i * BITS_PER_LONG;
1973                         struct sge_fl *fl = s->egr_map[id];
1974
1975                         clear_bit(id, s->starving_fl);
1976                         smp_mb__after_clear_bit();
1977
1978                         /*
1979                          * Since we are accessing fl without a lock there's a
1980                          * small probability of a false positive where we
1981                          * schedule napi but the FL is no longer starving.
1982                          * No biggie.
1983                          */
1984                         if (fl_starving(fl)) {
1985                                 struct sge_eth_rxq *rxq;
1986
1987                                 rxq = container_of(fl, struct sge_eth_rxq, fl);
1988                                 if (napi_reschedule(&rxq->rspq.napi))
1989                                         fl->starving++;
1990                                 else
1991                                         set_bit(id, s->starving_fl);
1992                         }
1993                 }
1994         }
1995
1996         /*
1997          * Reschedule the next scan for starving Free Lists ...
1998          */
1999         mod_timer(&s->rx_timer, jiffies + RX_QCHECK_PERIOD);
2000 }
2001
2002 /**
2003  *      sge_tx_timer_cb - perform periodic maintenance of SGE Tx queues
2004  *      @data: the adapter
2005  *
2006  *      Runs periodically from a timer to perform maintenance of SGE TX queues.
2007  *
2008  *      b) Reclaims completed Tx packets for the Ethernet queues.  Normally
2009  *      packets are cleaned up by new Tx packets, this timer cleans up packets
2010  *      when no new packets are being submitted.  This is essential for pktgen,
2011  *      at least.
2012  */
2013 static void sge_tx_timer_cb(unsigned long data)
2014 {
2015         struct adapter *adapter = (struct adapter *)data;
2016         struct sge *s = &adapter->sge;
2017         unsigned int i, budget;
2018
2019         budget = MAX_TIMER_TX_RECLAIM;
2020         i = s->ethtxq_rover;
2021         do {
2022                 struct sge_eth_txq *txq = &s->ethtxq[i];
2023
2024                 if (reclaimable(&txq->q) && __netif_tx_trylock(txq->txq)) {
2025                         int avail = reclaimable(&txq->q);
2026
2027                         if (avail > budget)
2028                                 avail = budget;
2029
2030                         free_tx_desc(adapter, &txq->q, avail, true);
2031                         txq->q.in_use -= avail;
2032                         __netif_tx_unlock(txq->txq);
2033
2034                         budget -= avail;
2035                         if (!budget)
2036                                 break;
2037                 }
2038
2039                 i++;
2040                 if (i >= s->ethqsets)
2041                         i = 0;
2042         } while (i != s->ethtxq_rover);
2043         s->ethtxq_rover = i;
2044
2045         /*
2046          * If we found too many reclaimable packets schedule a timer in the
2047          * near future to continue where we left off.  Otherwise the next timer
2048          * will be at its normal interval.
2049          */
2050         mod_timer(&s->tx_timer, jiffies + (budget ? TX_QCHECK_PERIOD : 2));
2051 }
2052
2053 /**
2054  *      t4vf_sge_alloc_rxq - allocate an SGE RX Queue
2055  *      @adapter: the adapter
2056  *      @rspq: pointer to to the new rxq's Response Queue to be filled in
2057  *      @iqasynch: if 0, a normal rspq; if 1, an asynchronous event queue
2058  *      @dev: the network device associated with the new rspq
2059  *      @intr_dest: MSI-X vector index (overriden in MSI mode)
2060  *      @fl: pointer to the new rxq's Free List to be filled in
2061  *      @hnd: the interrupt handler to invoke for the rspq
2062  */
2063 int t4vf_sge_alloc_rxq(struct adapter *adapter, struct sge_rspq *rspq,
2064                        bool iqasynch, struct net_device *dev,
2065                        int intr_dest,
2066                        struct sge_fl *fl, rspq_handler_t hnd)
2067 {
2068         struct port_info *pi = netdev_priv(dev);
2069         struct fw_iq_cmd cmd, rpl;
2070         int ret, iqandst, flsz = 0;
2071
2072         /*
2073          * If we're using MSI interrupts and we're not initializing the
2074          * Forwarded Interrupt Queue itself, then set up this queue for
2075          * indirect interrupts to the Forwarded Interrupt Queue.  Obviously
2076          * the Forwarded Interrupt Queue must be set up before any other
2077          * ingress queue ...
2078          */
2079         if ((adapter->flags & USING_MSI) && rspq != &adapter->sge.intrq) {
2080                 iqandst = SGE_INTRDST_IQ;
2081                 intr_dest = adapter->sge.intrq.abs_id;
2082         } else
2083                 iqandst = SGE_INTRDST_PCI;
2084
2085         /*
2086          * Allocate the hardware ring for the Response Queue.  The size needs
2087          * to be a multiple of 16 which includes the mandatory status entry
2088          * (regardless of whether the Status Page capabilities are enabled or
2089          * not).
2090          */
2091         rspq->size = roundup(rspq->size, 16);
2092         rspq->desc = alloc_ring(adapter->pdev_dev, rspq->size, rspq->iqe_len,
2093                                 0, &rspq->phys_addr, NULL, 0);
2094         if (!rspq->desc)
2095                 return -ENOMEM;
2096
2097         /*
2098          * Fill in the Ingress Queue Command.  Note: Ideally this code would
2099          * be in t4vf_hw.c but there are so many parameters and dependencies
2100          * on our Linux SGE state that we would end up having to pass tons of
2101          * parameters.  We'll have to think about how this might be migrated
2102          * into OS-independent common code ...
2103          */
2104         memset(&cmd, 0, sizeof(cmd));
2105         cmd.op_to_vfn = cpu_to_be32(FW_CMD_OP(FW_IQ_CMD) |
2106                                     FW_CMD_REQUEST |
2107                                     FW_CMD_WRITE |
2108                                     FW_CMD_EXEC);
2109         cmd.alloc_to_len16 = cpu_to_be32(FW_IQ_CMD_ALLOC |
2110                                          FW_IQ_CMD_IQSTART(1) |
2111                                          FW_LEN16(cmd));
2112         cmd.type_to_iqandstindex =
2113                 cpu_to_be32(FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
2114                             FW_IQ_CMD_IQASYNCH(iqasynch) |
2115                             FW_IQ_CMD_VIID(pi->viid) |
2116                             FW_IQ_CMD_IQANDST(iqandst) |
2117                             FW_IQ_CMD_IQANUS(1) |
2118                             FW_IQ_CMD_IQANUD(SGE_UPDATEDEL_INTR) |
2119                             FW_IQ_CMD_IQANDSTINDEX(intr_dest));
2120         cmd.iqdroprss_to_iqesize =
2121                 cpu_to_be16(FW_IQ_CMD_IQPCIECH(pi->port_id) |
2122                             FW_IQ_CMD_IQGTSMODE |
2123                             FW_IQ_CMD_IQINTCNTTHRESH(rspq->pktcnt_idx) |
2124                             FW_IQ_CMD_IQESIZE(ilog2(rspq->iqe_len) - 4));
2125         cmd.iqsize = cpu_to_be16(rspq->size);
2126         cmd.iqaddr = cpu_to_be64(rspq->phys_addr);
2127
2128         if (fl) {
2129                 /*
2130                  * Allocate the ring for the hardware free list (with space
2131                  * for its status page) along with the associated software
2132                  * descriptor ring.  The free list size needs to be a multiple
2133                  * of the Egress Queue Unit.
2134                  */
2135                 fl->size = roundup(fl->size, FL_PER_EQ_UNIT);
2136                 fl->desc = alloc_ring(adapter->pdev_dev, fl->size,
2137                                       sizeof(__be64), sizeof(struct rx_sw_desc),
2138                                       &fl->addr, &fl->sdesc, STAT_LEN);
2139                 if (!fl->desc) {
2140                         ret = -ENOMEM;
2141                         goto err;
2142                 }
2143
2144                 /*
2145                  * Calculate the size of the hardware free list ring plus
2146                  * status page (which the SGE will place at the end of the
2147                  * free list ring) in Egress Queue Units.
2148                  */
2149                 flsz = (fl->size / FL_PER_EQ_UNIT +
2150                         STAT_LEN / EQ_UNIT);
2151
2152                 /*
2153                  * Fill in all the relevant firmware Ingress Queue Command
2154                  * fields for the free list.
2155                  */
2156                 cmd.iqns_to_fl0congen =
2157                         cpu_to_be32(
2158                                 FW_IQ_CMD_FL0HOSTFCMODE(SGE_HOSTFCMODE_NONE) |
2159                                 FW_IQ_CMD_FL0PACKEN |
2160                                 FW_IQ_CMD_FL0PADEN);
2161                 cmd.fl0dcaen_to_fl0cidxfthresh =
2162                         cpu_to_be16(
2163                                 FW_IQ_CMD_FL0FBMIN(SGE_FETCHBURSTMIN_64B) |
2164                                 FW_IQ_CMD_FL0FBMAX(SGE_FETCHBURSTMAX_512B));
2165                 cmd.fl0size = cpu_to_be16(flsz);
2166                 cmd.fl0addr = cpu_to_be64(fl->addr);
2167         }
2168
2169         /*
2170          * Issue the firmware Ingress Queue Command and extract the results if
2171          * it completes successfully.
2172          */
2173         ret = t4vf_wr_mbox(adapter, &cmd, sizeof(cmd), &rpl);
2174         if (ret)
2175                 goto err;
2176
2177         netif_napi_add(dev, &rspq->napi, napi_rx_handler, 64);
2178         rspq->cur_desc = rspq->desc;
2179         rspq->cidx = 0;
2180         rspq->gen = 1;
2181         rspq->next_intr_params = rspq->intr_params;
2182         rspq->cntxt_id = be16_to_cpu(rpl.iqid);
2183         rspq->abs_id = be16_to_cpu(rpl.physiqid);
2184         rspq->size--;                   /* subtract status entry */
2185         rspq->adapter = adapter;
2186         rspq->netdev = dev;
2187         rspq->handler = hnd;
2188
2189         /* set offset to -1 to distinguish ingress queues without FL */
2190         rspq->offset = fl ? 0 : -1;
2191
2192         if (fl) {
2193                 fl->cntxt_id = be16_to_cpu(rpl.fl0id);
2194                 fl->avail = 0;
2195                 fl->pend_cred = 0;
2196                 fl->pidx = 0;
2197                 fl->cidx = 0;
2198                 fl->alloc_failed = 0;
2199                 fl->large_alloc_failed = 0;
2200                 fl->starving = 0;
2201                 refill_fl(adapter, fl, fl_cap(fl), GFP_KERNEL);
2202         }
2203
2204         return 0;
2205
2206 err:
2207         /*
2208          * An error occurred.  Clean up our partial allocation state and
2209          * return the error.
2210          */
2211         if (rspq->desc) {
2212                 dma_free_coherent(adapter->pdev_dev, rspq->size * rspq->iqe_len,
2213                                   rspq->desc, rspq->phys_addr);
2214                 rspq->desc = NULL;
2215         }
2216         if (fl && fl->desc) {
2217                 kfree(fl->sdesc);
2218                 fl->sdesc = NULL;
2219                 dma_free_coherent(adapter->pdev_dev, flsz * EQ_UNIT,
2220                                   fl->desc, fl->addr);
2221                 fl->desc = NULL;
2222         }
2223         return ret;
2224 }
2225
2226 /**
2227  *      t4vf_sge_alloc_eth_txq - allocate an SGE Ethernet TX Queue
2228  *      @adapter: the adapter
2229  *      @txq: pointer to the new txq to be filled in
2230  *      @devq: the network TX queue associated with the new txq
2231  *      @iqid: the relative ingress queue ID to which events relating to
2232  *              the new txq should be directed
2233  */
2234 int t4vf_sge_alloc_eth_txq(struct adapter *adapter, struct sge_eth_txq *txq,
2235                            struct net_device *dev, struct netdev_queue *devq,
2236                            unsigned int iqid)
2237 {
2238         int ret, nentries;
2239         struct fw_eq_eth_cmd cmd, rpl;
2240         struct port_info *pi = netdev_priv(dev);
2241
2242         /*
2243          * Calculate the size of the hardware TX Queue (including the
2244          * status age on the end) in units of TX Descriptors.
2245          */
2246         nentries = txq->q.size + STAT_LEN / sizeof(struct tx_desc);
2247
2248         /*
2249          * Allocate the hardware ring for the TX ring (with space for its
2250          * status page) along with the associated software descriptor ring.
2251          */
2252         txq->q.desc = alloc_ring(adapter->pdev_dev, txq->q.size,
2253                                  sizeof(struct tx_desc),
2254                                  sizeof(struct tx_sw_desc),
2255                                  &txq->q.phys_addr, &txq->q.sdesc, STAT_LEN);
2256         if (!txq->q.desc)
2257                 return -ENOMEM;
2258
2259         /*
2260          * Fill in the Egress Queue Command.  Note: As with the direct use of
2261          * the firmware Ingress Queue COmmand above in our RXQ allocation
2262          * routine, ideally, this code would be in t4vf_hw.c.  Again, we'll
2263          * have to see if there's some reasonable way to parameterize it
2264          * into the common code ...
2265          */
2266         memset(&cmd, 0, sizeof(cmd));
2267         cmd.op_to_vfn = cpu_to_be32(FW_CMD_OP(FW_EQ_ETH_CMD) |
2268                                     FW_CMD_REQUEST |
2269                                     FW_CMD_WRITE |
2270                                     FW_CMD_EXEC);
2271         cmd.alloc_to_len16 = cpu_to_be32(FW_EQ_ETH_CMD_ALLOC |
2272                                          FW_EQ_ETH_CMD_EQSTART |
2273                                          FW_LEN16(cmd));
2274         cmd.viid_pkd = cpu_to_be32(FW_EQ_ETH_CMD_VIID(pi->viid));
2275         cmd.fetchszm_to_iqid =
2276                 cpu_to_be32(FW_EQ_ETH_CMD_HOSTFCMODE(SGE_HOSTFCMODE_STPG) |
2277                             FW_EQ_ETH_CMD_PCIECHN(pi->port_id) |
2278                             FW_EQ_ETH_CMD_IQID(iqid));
2279         cmd.dcaen_to_eqsize =
2280                 cpu_to_be32(FW_EQ_ETH_CMD_FBMIN(SGE_FETCHBURSTMIN_64B) |
2281                             FW_EQ_ETH_CMD_FBMAX(SGE_FETCHBURSTMAX_512B) |
2282                             FW_EQ_ETH_CMD_CIDXFTHRESH(SGE_CIDXFLUSHTHRESH_32) |
2283                             FW_EQ_ETH_CMD_EQSIZE(nentries));
2284         cmd.eqaddr = cpu_to_be64(txq->q.phys_addr);
2285
2286         /*
2287          * Issue the firmware Egress Queue Command and extract the results if
2288          * it completes successfully.
2289          */
2290         ret = t4vf_wr_mbox(adapter, &cmd, sizeof(cmd), &rpl);
2291         if (ret) {
2292                 /*
2293                  * The girmware Ingress Queue Command failed for some reason.
2294                  * Free up our partial allocation state and return the error.
2295                  */
2296                 kfree(txq->q.sdesc);
2297                 txq->q.sdesc = NULL;
2298                 dma_free_coherent(adapter->pdev_dev,
2299                                   nentries * sizeof(struct tx_desc),
2300                                   txq->q.desc, txq->q.phys_addr);
2301                 txq->q.desc = NULL;
2302                 return ret;
2303         }
2304
2305         txq->q.in_use = 0;
2306         txq->q.cidx = 0;
2307         txq->q.pidx = 0;
2308         txq->q.stat = (void *)&txq->q.desc[txq->q.size];
2309         txq->q.cntxt_id = FW_EQ_ETH_CMD_EQID_GET(be32_to_cpu(rpl.eqid_pkd));
2310         txq->q.abs_id =
2311                 FW_EQ_ETH_CMD_PHYSEQID_GET(be32_to_cpu(rpl.physeqid_pkd));
2312         txq->txq = devq;
2313         txq->tso = 0;
2314         txq->tx_cso = 0;
2315         txq->vlan_ins = 0;
2316         txq->q.stops = 0;
2317         txq->q.restarts = 0;
2318         txq->mapping_err = 0;
2319         return 0;
2320 }
2321
2322 /*
2323  * Free the DMA map resources associated with a TX queue.
2324  */
2325 static void free_txq(struct adapter *adapter, struct sge_txq *tq)
2326 {
2327         dma_free_coherent(adapter->pdev_dev,
2328                           tq->size * sizeof(*tq->desc) + STAT_LEN,
2329                           tq->desc, tq->phys_addr);
2330         tq->cntxt_id = 0;
2331         tq->sdesc = NULL;
2332         tq->desc = NULL;
2333 }
2334
2335 /*
2336  * Free the resources associated with a response queue (possibly including a
2337  * free list).
2338  */
2339 static void free_rspq_fl(struct adapter *adapter, struct sge_rspq *rspq,
2340                          struct sge_fl *fl)
2341 {
2342         unsigned int flid = fl ? fl->cntxt_id : 0xffff;
2343
2344         t4vf_iq_free(adapter, FW_IQ_TYPE_FL_INT_CAP,
2345                      rspq->cntxt_id, flid, 0xffff);
2346         dma_free_coherent(adapter->pdev_dev, (rspq->size + 1) * rspq->iqe_len,
2347                           rspq->desc, rspq->phys_addr);
2348         netif_napi_del(&rspq->napi);
2349         rspq->netdev = NULL;
2350         rspq->cntxt_id = 0;
2351         rspq->abs_id = 0;
2352         rspq->desc = NULL;
2353
2354         if (fl) {
2355                 free_rx_bufs(adapter, fl, fl->avail);
2356                 dma_free_coherent(adapter->pdev_dev,
2357                                   fl->size * sizeof(*fl->desc) + STAT_LEN,
2358                                   fl->desc, fl->addr);
2359                 kfree(fl->sdesc);
2360                 fl->sdesc = NULL;
2361                 fl->cntxt_id = 0;
2362                 fl->desc = NULL;
2363         }
2364 }
2365
2366 /**
2367  *      t4vf_free_sge_resources - free SGE resources
2368  *      @adapter: the adapter
2369  *
2370  *      Frees resources used by the SGE queue sets.
2371  */
2372 void t4vf_free_sge_resources(struct adapter *adapter)
2373 {
2374         struct sge *s = &adapter->sge;
2375         struct sge_eth_rxq *rxq = s->ethrxq;
2376         struct sge_eth_txq *txq = s->ethtxq;
2377         struct sge_rspq *evtq = &s->fw_evtq;
2378         struct sge_rspq *intrq = &s->intrq;
2379         int qs;
2380
2381         for (qs = 0; qs < adapter->sge.ethqsets; qs++, rxq++, txq++) {
2382                 if (rxq->rspq.desc)
2383                         free_rspq_fl(adapter, &rxq->rspq, &rxq->fl);
2384                 if (txq->q.desc) {
2385                         t4vf_eth_eq_free(adapter, txq->q.cntxt_id);
2386                         free_tx_desc(adapter, &txq->q, txq->q.in_use, true);
2387                         kfree(txq->q.sdesc);
2388                         free_txq(adapter, &txq->q);
2389                 }
2390         }
2391         if (evtq->desc)
2392                 free_rspq_fl(adapter, evtq, NULL);
2393         if (intrq->desc)
2394                 free_rspq_fl(adapter, intrq, NULL);
2395 }
2396
2397 /**
2398  *      t4vf_sge_start - enable SGE operation
2399  *      @adapter: the adapter
2400  *
2401  *      Start tasklets and timers associated with the DMA engine.
2402  */
2403 void t4vf_sge_start(struct adapter *adapter)
2404 {
2405         adapter->sge.ethtxq_rover = 0;
2406         mod_timer(&adapter->sge.rx_timer, jiffies + RX_QCHECK_PERIOD);
2407         mod_timer(&adapter->sge.tx_timer, jiffies + TX_QCHECK_PERIOD);
2408 }
2409
2410 /**
2411  *      t4vf_sge_stop - disable SGE operation
2412  *      @adapter: the adapter
2413  *
2414  *      Stop tasklets and timers associated with the DMA engine.  Note that
2415  *      this is effective only if measures have been taken to disable any HW
2416  *      events that may restart them.
2417  */
2418 void t4vf_sge_stop(struct adapter *adapter)
2419 {
2420         struct sge *s = &adapter->sge;
2421
2422         if (s->rx_timer.function)
2423                 del_timer_sync(&s->rx_timer);
2424         if (s->tx_timer.function)
2425                 del_timer_sync(&s->tx_timer);
2426 }
2427
2428 /**
2429  *      t4vf_sge_init - initialize SGE
2430  *      @adapter: the adapter
2431  *
2432  *      Performs SGE initialization needed every time after a chip reset.
2433  *      We do not initialize any of the queue sets here, instead the driver
2434  *      top-level must request those individually.  We also do not enable DMA
2435  *      here, that should be done after the queues have been set up.
2436  */
2437 int t4vf_sge_init(struct adapter *adapter)
2438 {
2439         struct sge_params *sge_params = &adapter->params.sge;
2440         u32 fl0 = sge_params->sge_fl_buffer_size[0];
2441         u32 fl1 = sge_params->sge_fl_buffer_size[1];
2442         struct sge *s = &adapter->sge;
2443
2444         /*
2445          * Start by vetting the basic SGE parameters which have been set up by
2446          * the Physical Function Driver.  Ideally we should be able to deal
2447          * with _any_ configuration.  Practice is different ...
2448          */
2449         if (fl0 != PAGE_SIZE || (fl1 != 0 && fl1 <= fl0)) {
2450                 dev_err(adapter->pdev_dev, "bad SGE FL buffer sizes [%d, %d]\n",
2451                         fl0, fl1);
2452                 return -EINVAL;
2453         }
2454         if ((sge_params->sge_control & RXPKTCPLMODE) == 0) {
2455                 dev_err(adapter->pdev_dev, "bad SGE CPL MODE\n");
2456                 return -EINVAL;
2457         }
2458
2459         /*
2460          * Now translate the adapter parameters into our internal forms.
2461          */
2462         if (fl1)
2463                 FL_PG_ORDER = ilog2(fl1) - PAGE_SHIFT;
2464         STAT_LEN = ((sge_params->sge_control & EGRSTATUSPAGESIZE) ? 128 : 64);
2465         PKTSHIFT = PKTSHIFT_GET(sge_params->sge_control);
2466         FL_ALIGN = 1 << (INGPADBOUNDARY_GET(sge_params->sge_control) +
2467                          SGE_INGPADBOUNDARY_SHIFT);
2468
2469         /*
2470          * Set up tasklet timers.
2471          */
2472         setup_timer(&s->rx_timer, sge_rx_timer_cb, (unsigned long)adapter);
2473         setup_timer(&s->tx_timer, sge_tx_timer_cb, (unsigned long)adapter);
2474
2475         /*
2476          * Initialize Forwarded Interrupt Queue lock.
2477          */
2478         spin_lock_init(&s->intrq_lock);
2479
2480         return 0;
2481 }