cxgb4: Initialize T5
[firefly-linux-kernel-4.4.55.git] / drivers / net / ethernet / chelsio / cxgb4 / sge.c
1 /*
2  * This file is part of the Chelsio T4 Ethernet driver for Linux.
3  *
4  * Copyright (c) 2003-2010 Chelsio Communications, Inc. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34
35 #include <linux/skbuff.h>
36 #include <linux/netdevice.h>
37 #include <linux/etherdevice.h>
38 #include <linux/if_vlan.h>
39 #include <linux/ip.h>
40 #include <linux/dma-mapping.h>
41 #include <linux/jiffies.h>
42 #include <linux/prefetch.h>
43 #include <linux/export.h>
44 #include <net/ipv6.h>
45 #include <net/tcp.h>
46 #include "cxgb4.h"
47 #include "t4_regs.h"
48 #include "t4_msg.h"
49 #include "t4fw_api.h"
50
51 /*
52  * Rx buffer size.  We use largish buffers if possible but settle for single
53  * pages under memory shortage.
54  */
55 #if PAGE_SHIFT >= 16
56 # define FL_PG_ORDER 0
57 #else
58 # define FL_PG_ORDER (16 - PAGE_SHIFT)
59 #endif
60
61 /* RX_PULL_LEN should be <= RX_COPY_THRES */
62 #define RX_COPY_THRES    256
63 #define RX_PULL_LEN      128
64
65 /*
66  * Main body length for sk_buffs used for Rx Ethernet packets with fragments.
67  * Should be >= RX_PULL_LEN but possibly bigger to give pskb_may_pull some room.
68  */
69 #define RX_PKT_SKB_LEN   512
70
71 /*
72  * Max number of Tx descriptors we clean up at a time.  Should be modest as
73  * freeing skbs isn't cheap and it happens while holding locks.  We just need
74  * to free packets faster than they arrive, we eventually catch up and keep
75  * the amortized cost reasonable.  Must be >= 2 * TXQ_STOP_THRES.
76  */
77 #define MAX_TX_RECLAIM 16
78
79 /*
80  * Max number of Rx buffers we replenish at a time.  Again keep this modest,
81  * allocating buffers isn't cheap either.
82  */
83 #define MAX_RX_REFILL 16U
84
85 /*
86  * Period of the Rx queue check timer.  This timer is infrequent as it has
87  * something to do only when the system experiences severe memory shortage.
88  */
89 #define RX_QCHECK_PERIOD (HZ / 2)
90
91 /*
92  * Period of the Tx queue check timer.
93  */
94 #define TX_QCHECK_PERIOD (HZ / 2)
95
96 /*
97  * Max number of Tx descriptors to be reclaimed by the Tx timer.
98  */
99 #define MAX_TIMER_TX_RECLAIM 100
100
101 /*
102  * Timer index used when backing off due to memory shortage.
103  */
104 #define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
105
106 /*
107  * An FL with <= FL_STARVE_THRES buffers is starving and a periodic timer will
108  * attempt to refill it.
109  */
110 #define FL_STARVE_THRES 4
111
112 /*
113  * Suspend an Ethernet Tx queue with fewer available descriptors than this.
114  * This is the same as calc_tx_descs() for a TSO packet with
115  * nr_frags == MAX_SKB_FRAGS.
116  */
117 #define ETHTXQ_STOP_THRES \
118         (1 + DIV_ROUND_UP((3 * MAX_SKB_FRAGS) / 2 + (MAX_SKB_FRAGS & 1), 8))
119
120 /*
121  * Suspension threshold for non-Ethernet Tx queues.  We require enough room
122  * for a full sized WR.
123  */
124 #define TXQ_STOP_THRES (SGE_MAX_WR_LEN / sizeof(struct tx_desc))
125
126 /*
127  * Max Tx descriptor space we allow for an Ethernet packet to be inlined
128  * into a WR.
129  */
130 #define MAX_IMM_TX_PKT_LEN 128
131
132 /*
133  * Max size of a WR sent through a control Tx queue.
134  */
135 #define MAX_CTRL_WR_LEN SGE_MAX_WR_LEN
136
137 struct tx_sw_desc {                /* SW state per Tx descriptor */
138         struct sk_buff *skb;
139         struct ulptx_sgl *sgl;
140 };
141
142 struct rx_sw_desc {                /* SW state per Rx descriptor */
143         struct page *page;
144         dma_addr_t dma_addr;
145 };
146
147 /*
148  * Rx buffer sizes for "useskbs" Free List buffers (one ingress packet pe skb
149  * buffer).  We currently only support two sizes for 1500- and 9000-byte MTUs.
150  * We could easily support more but there doesn't seem to be much need for
151  * that ...
152  */
153 #define FL_MTU_SMALL 1500
154 #define FL_MTU_LARGE 9000
155
156 static inline unsigned int fl_mtu_bufsize(struct adapter *adapter,
157                                           unsigned int mtu)
158 {
159         struct sge *s = &adapter->sge;
160
161         return ALIGN(s->pktshift + ETH_HLEN + VLAN_HLEN + mtu, s->fl_align);
162 }
163
164 #define FL_MTU_SMALL_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_SMALL)
165 #define FL_MTU_LARGE_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_LARGE)
166
167 /*
168  * Bits 0..3 of rx_sw_desc.dma_addr have special meaning.  The hardware uses
169  * these to specify the buffer size as an index into the SGE Free List Buffer
170  * Size register array.  We also use bit 4, when the buffer has been unmapped
171  * for DMA, but this is of course never sent to the hardware and is only used
172  * to prevent double unmappings.  All of the above requires that the Free List
173  * Buffers which we allocate have the bottom 5 bits free (0) -- i.e. are
174  * 32-byte or or a power of 2 greater in alignment.  Since the SGE's minimal
175  * Free List Buffer alignment is 32 bytes, this works out for us ...
176  */
177 enum {
178         RX_BUF_FLAGS     = 0x1f,   /* bottom five bits are special */
179         RX_BUF_SIZE      = 0x0f,   /* bottom three bits are for buf sizes */
180         RX_UNMAPPED_BUF  = 0x10,   /* buffer is not mapped */
181
182         /*
183          * XXX We shouldn't depend on being able to use these indices.
184          * XXX Especially when some other Master PF has initialized the
185          * XXX adapter or we use the Firmware Configuration File.  We
186          * XXX should really search through the Host Buffer Size register
187          * XXX array for the appropriately sized buffer indices.
188          */
189         RX_SMALL_PG_BUF  = 0x0,   /* small (PAGE_SIZE) page buffer */
190         RX_LARGE_PG_BUF  = 0x1,   /* buffer large (FL_PG_ORDER) page buffer */
191
192         RX_SMALL_MTU_BUF = 0x2,   /* small MTU buffer */
193         RX_LARGE_MTU_BUF = 0x3,   /* large MTU buffer */
194 };
195
196 static inline dma_addr_t get_buf_addr(const struct rx_sw_desc *d)
197 {
198         return d->dma_addr & ~(dma_addr_t)RX_BUF_FLAGS;
199 }
200
201 static inline bool is_buf_mapped(const struct rx_sw_desc *d)
202 {
203         return !(d->dma_addr & RX_UNMAPPED_BUF);
204 }
205
206 /**
207  *      txq_avail - return the number of available slots in a Tx queue
208  *      @q: the Tx queue
209  *
210  *      Returns the number of descriptors in a Tx queue available to write new
211  *      packets.
212  */
213 static inline unsigned int txq_avail(const struct sge_txq *q)
214 {
215         return q->size - 1 - q->in_use;
216 }
217
218 /**
219  *      fl_cap - return the capacity of a free-buffer list
220  *      @fl: the FL
221  *
222  *      Returns the capacity of a free-buffer list.  The capacity is less than
223  *      the size because one descriptor needs to be left unpopulated, otherwise
224  *      HW will think the FL is empty.
225  */
226 static inline unsigned int fl_cap(const struct sge_fl *fl)
227 {
228         return fl->size - 8;   /* 1 descriptor = 8 buffers */
229 }
230
231 static inline bool fl_starving(const struct sge_fl *fl)
232 {
233         return fl->avail - fl->pend_cred <= FL_STARVE_THRES;
234 }
235
236 static int map_skb(struct device *dev, const struct sk_buff *skb,
237                    dma_addr_t *addr)
238 {
239         const skb_frag_t *fp, *end;
240         const struct skb_shared_info *si;
241
242         *addr = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
243         if (dma_mapping_error(dev, *addr))
244                 goto out_err;
245
246         si = skb_shinfo(skb);
247         end = &si->frags[si->nr_frags];
248
249         for (fp = si->frags; fp < end; fp++) {
250                 *++addr = skb_frag_dma_map(dev, fp, 0, skb_frag_size(fp),
251                                            DMA_TO_DEVICE);
252                 if (dma_mapping_error(dev, *addr))
253                         goto unwind;
254         }
255         return 0;
256
257 unwind:
258         while (fp-- > si->frags)
259                 dma_unmap_page(dev, *--addr, skb_frag_size(fp), DMA_TO_DEVICE);
260
261         dma_unmap_single(dev, addr[-1], skb_headlen(skb), DMA_TO_DEVICE);
262 out_err:
263         return -ENOMEM;
264 }
265
266 #ifdef CONFIG_NEED_DMA_MAP_STATE
267 static void unmap_skb(struct device *dev, const struct sk_buff *skb,
268                       const dma_addr_t *addr)
269 {
270         const skb_frag_t *fp, *end;
271         const struct skb_shared_info *si;
272
273         dma_unmap_single(dev, *addr++, skb_headlen(skb), DMA_TO_DEVICE);
274
275         si = skb_shinfo(skb);
276         end = &si->frags[si->nr_frags];
277         for (fp = si->frags; fp < end; fp++)
278                 dma_unmap_page(dev, *addr++, skb_frag_size(fp), DMA_TO_DEVICE);
279 }
280
281 /**
282  *      deferred_unmap_destructor - unmap a packet when it is freed
283  *      @skb: the packet
284  *
285  *      This is the packet destructor used for Tx packets that need to remain
286  *      mapped until they are freed rather than until their Tx descriptors are
287  *      freed.
288  */
289 static void deferred_unmap_destructor(struct sk_buff *skb)
290 {
291         unmap_skb(skb->dev->dev.parent, skb, (dma_addr_t *)skb->head);
292 }
293 #endif
294
295 static void unmap_sgl(struct device *dev, const struct sk_buff *skb,
296                       const struct ulptx_sgl *sgl, const struct sge_txq *q)
297 {
298         const struct ulptx_sge_pair *p;
299         unsigned int nfrags = skb_shinfo(skb)->nr_frags;
300
301         if (likely(skb_headlen(skb)))
302                 dma_unmap_single(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
303                                  DMA_TO_DEVICE);
304         else {
305                 dma_unmap_page(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
306                                DMA_TO_DEVICE);
307                 nfrags--;
308         }
309
310         /*
311          * the complexity below is because of the possibility of a wrap-around
312          * in the middle of an SGL
313          */
314         for (p = sgl->sge; nfrags >= 2; nfrags -= 2) {
315                 if (likely((u8 *)(p + 1) <= (u8 *)q->stat)) {
316 unmap:                  dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
317                                        ntohl(p->len[0]), DMA_TO_DEVICE);
318                         dma_unmap_page(dev, be64_to_cpu(p->addr[1]),
319                                        ntohl(p->len[1]), DMA_TO_DEVICE);
320                         p++;
321                 } else if ((u8 *)p == (u8 *)q->stat) {
322                         p = (const struct ulptx_sge_pair *)q->desc;
323                         goto unmap;
324                 } else if ((u8 *)p + 8 == (u8 *)q->stat) {
325                         const __be64 *addr = (const __be64 *)q->desc;
326
327                         dma_unmap_page(dev, be64_to_cpu(addr[0]),
328                                        ntohl(p->len[0]), DMA_TO_DEVICE);
329                         dma_unmap_page(dev, be64_to_cpu(addr[1]),
330                                        ntohl(p->len[1]), DMA_TO_DEVICE);
331                         p = (const struct ulptx_sge_pair *)&addr[2];
332                 } else {
333                         const __be64 *addr = (const __be64 *)q->desc;
334
335                         dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
336                                        ntohl(p->len[0]), DMA_TO_DEVICE);
337                         dma_unmap_page(dev, be64_to_cpu(addr[0]),
338                                        ntohl(p->len[1]), DMA_TO_DEVICE);
339                         p = (const struct ulptx_sge_pair *)&addr[1];
340                 }
341         }
342         if (nfrags) {
343                 __be64 addr;
344
345                 if ((u8 *)p == (u8 *)q->stat)
346                         p = (const struct ulptx_sge_pair *)q->desc;
347                 addr = (u8 *)p + 16 <= (u8 *)q->stat ? p->addr[0] :
348                                                        *(const __be64 *)q->desc;
349                 dma_unmap_page(dev, be64_to_cpu(addr), ntohl(p->len[0]),
350                                DMA_TO_DEVICE);
351         }
352 }
353
354 /**
355  *      free_tx_desc - reclaims Tx descriptors and their buffers
356  *      @adapter: the adapter
357  *      @q: the Tx queue to reclaim descriptors from
358  *      @n: the number of descriptors to reclaim
359  *      @unmap: whether the buffers should be unmapped for DMA
360  *
361  *      Reclaims Tx descriptors from an SGE Tx queue and frees the associated
362  *      Tx buffers.  Called with the Tx queue lock held.
363  */
364 static void free_tx_desc(struct adapter *adap, struct sge_txq *q,
365                          unsigned int n, bool unmap)
366 {
367         struct tx_sw_desc *d;
368         unsigned int cidx = q->cidx;
369         struct device *dev = adap->pdev_dev;
370
371         d = &q->sdesc[cidx];
372         while (n--) {
373                 if (d->skb) {                       /* an SGL is present */
374                         if (unmap)
375                                 unmap_sgl(dev, d->skb, d->sgl, q);
376                         kfree_skb(d->skb);
377                         d->skb = NULL;
378                 }
379                 ++d;
380                 if (++cidx == q->size) {
381                         cidx = 0;
382                         d = q->sdesc;
383                 }
384         }
385         q->cidx = cidx;
386 }
387
388 /*
389  * Return the number of reclaimable descriptors in a Tx queue.
390  */
391 static inline int reclaimable(const struct sge_txq *q)
392 {
393         int hw_cidx = ntohs(q->stat->cidx);
394         hw_cidx -= q->cidx;
395         return hw_cidx < 0 ? hw_cidx + q->size : hw_cidx;
396 }
397
398 /**
399  *      reclaim_completed_tx - reclaims completed Tx descriptors
400  *      @adap: the adapter
401  *      @q: the Tx queue to reclaim completed descriptors from
402  *      @unmap: whether the buffers should be unmapped for DMA
403  *
404  *      Reclaims Tx descriptors that the SGE has indicated it has processed,
405  *      and frees the associated buffers if possible.  Called with the Tx
406  *      queue locked.
407  */
408 static inline void reclaim_completed_tx(struct adapter *adap, struct sge_txq *q,
409                                         bool unmap)
410 {
411         int avail = reclaimable(q);
412
413         if (avail) {
414                 /*
415                  * Limit the amount of clean up work we do at a time to keep
416                  * the Tx lock hold time O(1).
417                  */
418                 if (avail > MAX_TX_RECLAIM)
419                         avail = MAX_TX_RECLAIM;
420
421                 free_tx_desc(adap, q, avail, unmap);
422                 q->in_use -= avail;
423         }
424 }
425
426 static inline int get_buf_size(struct adapter *adapter,
427                                const struct rx_sw_desc *d)
428 {
429         struct sge *s = &adapter->sge;
430         unsigned int rx_buf_size_idx = d->dma_addr & RX_BUF_SIZE;
431         int buf_size;
432
433         switch (rx_buf_size_idx) {
434         case RX_SMALL_PG_BUF:
435                 buf_size = PAGE_SIZE;
436                 break;
437
438         case RX_LARGE_PG_BUF:
439                 buf_size = PAGE_SIZE << s->fl_pg_order;
440                 break;
441
442         case RX_SMALL_MTU_BUF:
443                 buf_size = FL_MTU_SMALL_BUFSIZE(adapter);
444                 break;
445
446         case RX_LARGE_MTU_BUF:
447                 buf_size = FL_MTU_LARGE_BUFSIZE(adapter);
448                 break;
449
450         default:
451                 BUG_ON(1);
452         }
453
454         return buf_size;
455 }
456
457 /**
458  *      free_rx_bufs - free the Rx buffers on an SGE free list
459  *      @adap: the adapter
460  *      @q: the SGE free list to free buffers from
461  *      @n: how many buffers to free
462  *
463  *      Release the next @n buffers on an SGE free-buffer Rx queue.   The
464  *      buffers must be made inaccessible to HW before calling this function.
465  */
466 static void free_rx_bufs(struct adapter *adap, struct sge_fl *q, int n)
467 {
468         while (n--) {
469                 struct rx_sw_desc *d = &q->sdesc[q->cidx];
470
471                 if (is_buf_mapped(d))
472                         dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
473                                        get_buf_size(adap, d),
474                                        PCI_DMA_FROMDEVICE);
475                 put_page(d->page);
476                 d->page = NULL;
477                 if (++q->cidx == q->size)
478                         q->cidx = 0;
479                 q->avail--;
480         }
481 }
482
483 /**
484  *      unmap_rx_buf - unmap the current Rx buffer on an SGE free list
485  *      @adap: the adapter
486  *      @q: the SGE free list
487  *
488  *      Unmap the current buffer on an SGE free-buffer Rx queue.   The
489  *      buffer must be made inaccessible to HW before calling this function.
490  *
491  *      This is similar to @free_rx_bufs above but does not free the buffer.
492  *      Do note that the FL still loses any further access to the buffer.
493  */
494 static void unmap_rx_buf(struct adapter *adap, struct sge_fl *q)
495 {
496         struct rx_sw_desc *d = &q->sdesc[q->cidx];
497
498         if (is_buf_mapped(d))
499                 dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
500                                get_buf_size(adap, d), PCI_DMA_FROMDEVICE);
501         d->page = NULL;
502         if (++q->cidx == q->size)
503                 q->cidx = 0;
504         q->avail--;
505 }
506
507 static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
508 {
509         u32 val;
510         if (q->pend_cred >= 8) {
511                 val = PIDX(q->pend_cred / 8);
512                 if (!is_t4(adap->chip))
513                         val |= DBTYPE(1);
514                 wmb();
515                 t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL), DBPRIO(1) |
516                              QID(q->cntxt_id) | val);
517                 q->pend_cred &= 7;
518         }
519 }
520
521 static inline void set_rx_sw_desc(struct rx_sw_desc *sd, struct page *pg,
522                                   dma_addr_t mapping)
523 {
524         sd->page = pg;
525         sd->dma_addr = mapping;      /* includes size low bits */
526 }
527
528 /**
529  *      refill_fl - refill an SGE Rx buffer ring
530  *      @adap: the adapter
531  *      @q: the ring to refill
532  *      @n: the number of new buffers to allocate
533  *      @gfp: the gfp flags for the allocations
534  *
535  *      (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
536  *      allocated with the supplied gfp flags.  The caller must assure that
537  *      @n does not exceed the queue's capacity.  If afterwards the queue is
538  *      found critically low mark it as starving in the bitmap of starving FLs.
539  *
540  *      Returns the number of buffers allocated.
541  */
542 static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n,
543                               gfp_t gfp)
544 {
545         struct sge *s = &adap->sge;
546         struct page *pg;
547         dma_addr_t mapping;
548         unsigned int cred = q->avail;
549         __be64 *d = &q->desc[q->pidx];
550         struct rx_sw_desc *sd = &q->sdesc[q->pidx];
551
552         gfp |= __GFP_NOWARN | __GFP_COLD;
553
554         if (s->fl_pg_order == 0)
555                 goto alloc_small_pages;
556
557         /*
558          * Prefer large buffers
559          */
560         while (n) {
561                 pg = alloc_pages(gfp | __GFP_COMP, s->fl_pg_order);
562                 if (unlikely(!pg)) {
563                         q->large_alloc_failed++;
564                         break;       /* fall back to single pages */
565                 }
566
567                 mapping = dma_map_page(adap->pdev_dev, pg, 0,
568                                        PAGE_SIZE << s->fl_pg_order,
569                                        PCI_DMA_FROMDEVICE);
570                 if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
571                         __free_pages(pg, s->fl_pg_order);
572                         goto out;   /* do not try small pages for this error */
573                 }
574                 mapping |= RX_LARGE_PG_BUF;
575                 *d++ = cpu_to_be64(mapping);
576
577                 set_rx_sw_desc(sd, pg, mapping);
578                 sd++;
579
580                 q->avail++;
581                 if (++q->pidx == q->size) {
582                         q->pidx = 0;
583                         sd = q->sdesc;
584                         d = q->desc;
585                 }
586                 n--;
587         }
588
589 alloc_small_pages:
590         while (n--) {
591                 pg = __skb_alloc_page(gfp, NULL);
592                 if (unlikely(!pg)) {
593                         q->alloc_failed++;
594                         break;
595                 }
596
597                 mapping = dma_map_page(adap->pdev_dev, pg, 0, PAGE_SIZE,
598                                        PCI_DMA_FROMDEVICE);
599                 if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
600                         put_page(pg);
601                         goto out;
602                 }
603                 *d++ = cpu_to_be64(mapping);
604
605                 set_rx_sw_desc(sd, pg, mapping);
606                 sd++;
607
608                 q->avail++;
609                 if (++q->pidx == q->size) {
610                         q->pidx = 0;
611                         sd = q->sdesc;
612                         d = q->desc;
613                 }
614         }
615
616 out:    cred = q->avail - cred;
617         q->pend_cred += cred;
618         ring_fl_db(adap, q);
619
620         if (unlikely(fl_starving(q))) {
621                 smp_wmb();
622                 set_bit(q->cntxt_id - adap->sge.egr_start,
623                         adap->sge.starving_fl);
624         }
625
626         return cred;
627 }
628
629 static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
630 {
631         refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail),
632                   GFP_ATOMIC);
633 }
634
635 /**
636  *      alloc_ring - allocate resources for an SGE descriptor ring
637  *      @dev: the PCI device's core device
638  *      @nelem: the number of descriptors
639  *      @elem_size: the size of each descriptor
640  *      @sw_size: the size of the SW state associated with each ring element
641  *      @phys: the physical address of the allocated ring
642  *      @metadata: address of the array holding the SW state for the ring
643  *      @stat_size: extra space in HW ring for status information
644  *      @node: preferred node for memory allocations
645  *
646  *      Allocates resources for an SGE descriptor ring, such as Tx queues,
647  *      free buffer lists, or response queues.  Each SGE ring requires
648  *      space for its HW descriptors plus, optionally, space for the SW state
649  *      associated with each HW entry (the metadata).  The function returns
650  *      three values: the virtual address for the HW ring (the return value
651  *      of the function), the bus address of the HW ring, and the address
652  *      of the SW ring.
653  */
654 static void *alloc_ring(struct device *dev, size_t nelem, size_t elem_size,
655                         size_t sw_size, dma_addr_t *phys, void *metadata,
656                         size_t stat_size, int node)
657 {
658         size_t len = nelem * elem_size + stat_size;
659         void *s = NULL;
660         void *p = dma_alloc_coherent(dev, len, phys, GFP_KERNEL);
661
662         if (!p)
663                 return NULL;
664         if (sw_size) {
665                 s = kzalloc_node(nelem * sw_size, GFP_KERNEL, node);
666
667                 if (!s) {
668                         dma_free_coherent(dev, len, p, *phys);
669                         return NULL;
670                 }
671         }
672         if (metadata)
673                 *(void **)metadata = s;
674         memset(p, 0, len);
675         return p;
676 }
677
678 /**
679  *      sgl_len - calculates the size of an SGL of the given capacity
680  *      @n: the number of SGL entries
681  *
682  *      Calculates the number of flits needed for a scatter/gather list that
683  *      can hold the given number of entries.
684  */
685 static inline unsigned int sgl_len(unsigned int n)
686 {
687         n--;
688         return (3 * n) / 2 + (n & 1) + 2;
689 }
690
691 /**
692  *      flits_to_desc - returns the num of Tx descriptors for the given flits
693  *      @n: the number of flits
694  *
695  *      Returns the number of Tx descriptors needed for the supplied number
696  *      of flits.
697  */
698 static inline unsigned int flits_to_desc(unsigned int n)
699 {
700         BUG_ON(n > SGE_MAX_WR_LEN / 8);
701         return DIV_ROUND_UP(n, 8);
702 }
703
704 /**
705  *      is_eth_imm - can an Ethernet packet be sent as immediate data?
706  *      @skb: the packet
707  *
708  *      Returns whether an Ethernet packet is small enough to fit as
709  *      immediate data.
710  */
711 static inline int is_eth_imm(const struct sk_buff *skb)
712 {
713         return skb->len <= MAX_IMM_TX_PKT_LEN - sizeof(struct cpl_tx_pkt);
714 }
715
716 /**
717  *      calc_tx_flits - calculate the number of flits for a packet Tx WR
718  *      @skb: the packet
719  *
720  *      Returns the number of flits needed for a Tx WR for the given Ethernet
721  *      packet, including the needed WR and CPL headers.
722  */
723 static inline unsigned int calc_tx_flits(const struct sk_buff *skb)
724 {
725         unsigned int flits;
726
727         if (is_eth_imm(skb))
728                 return DIV_ROUND_UP(skb->len + sizeof(struct cpl_tx_pkt), 8);
729
730         flits = sgl_len(skb_shinfo(skb)->nr_frags + 1) + 4;
731         if (skb_shinfo(skb)->gso_size)
732                 flits += 2;
733         return flits;
734 }
735
736 /**
737  *      calc_tx_descs - calculate the number of Tx descriptors for a packet
738  *      @skb: the packet
739  *
740  *      Returns the number of Tx descriptors needed for the given Ethernet
741  *      packet, including the needed WR and CPL headers.
742  */
743 static inline unsigned int calc_tx_descs(const struct sk_buff *skb)
744 {
745         return flits_to_desc(calc_tx_flits(skb));
746 }
747
748 /**
749  *      write_sgl - populate a scatter/gather list for a packet
750  *      @skb: the packet
751  *      @q: the Tx queue we are writing into
752  *      @sgl: starting location for writing the SGL
753  *      @end: points right after the end of the SGL
754  *      @start: start offset into skb main-body data to include in the SGL
755  *      @addr: the list of bus addresses for the SGL elements
756  *
757  *      Generates a gather list for the buffers that make up a packet.
758  *      The caller must provide adequate space for the SGL that will be written.
759  *      The SGL includes all of the packet's page fragments and the data in its
760  *      main body except for the first @start bytes.  @sgl must be 16-byte
761  *      aligned and within a Tx descriptor with available space.  @end points
762  *      right after the end of the SGL but does not account for any potential
763  *      wrap around, i.e., @end > @sgl.
764  */
765 static void write_sgl(const struct sk_buff *skb, struct sge_txq *q,
766                       struct ulptx_sgl *sgl, u64 *end, unsigned int start,
767                       const dma_addr_t *addr)
768 {
769         unsigned int i, len;
770         struct ulptx_sge_pair *to;
771         const struct skb_shared_info *si = skb_shinfo(skb);
772         unsigned int nfrags = si->nr_frags;
773         struct ulptx_sge_pair buf[MAX_SKB_FRAGS / 2 + 1];
774
775         len = skb_headlen(skb) - start;
776         if (likely(len)) {
777                 sgl->len0 = htonl(len);
778                 sgl->addr0 = cpu_to_be64(addr[0] + start);
779                 nfrags++;
780         } else {
781                 sgl->len0 = htonl(skb_frag_size(&si->frags[0]));
782                 sgl->addr0 = cpu_to_be64(addr[1]);
783         }
784
785         sgl->cmd_nsge = htonl(ULPTX_CMD(ULP_TX_SC_DSGL) | ULPTX_NSGE(nfrags));
786         if (likely(--nfrags == 0))
787                 return;
788         /*
789          * Most of the complexity below deals with the possibility we hit the
790          * end of the queue in the middle of writing the SGL.  For this case
791          * only we create the SGL in a temporary buffer and then copy it.
792          */
793         to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
794
795         for (i = (nfrags != si->nr_frags); nfrags >= 2; nfrags -= 2, to++) {
796                 to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
797                 to->len[1] = cpu_to_be32(skb_frag_size(&si->frags[++i]));
798                 to->addr[0] = cpu_to_be64(addr[i]);
799                 to->addr[1] = cpu_to_be64(addr[++i]);
800         }
801         if (nfrags) {
802                 to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
803                 to->len[1] = cpu_to_be32(0);
804                 to->addr[0] = cpu_to_be64(addr[i + 1]);
805         }
806         if (unlikely((u8 *)end > (u8 *)q->stat)) {
807                 unsigned int part0 = (u8 *)q->stat - (u8 *)sgl->sge, part1;
808
809                 if (likely(part0))
810                         memcpy(sgl->sge, buf, part0);
811                 part1 = (u8 *)end - (u8 *)q->stat;
812                 memcpy(q->desc, (u8 *)buf + part0, part1);
813                 end = (void *)q->desc + part1;
814         }
815         if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
816                 *end = 0;
817 }
818
819 /**
820  *      ring_tx_db - check and potentially ring a Tx queue's doorbell
821  *      @adap: the adapter
822  *      @q: the Tx queue
823  *      @n: number of new descriptors to give to HW
824  *
825  *      Ring the doorbel for a Tx queue.
826  */
827 static inline void ring_tx_db(struct adapter *adap, struct sge_txq *q, int n)
828 {
829         wmb();            /* write descriptors before telling HW */
830         spin_lock(&q->db_lock);
831         if (!q->db_disabled) {
832                 t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL),
833                              QID(q->cntxt_id) | PIDX(n));
834         }
835         q->db_pidx = q->pidx;
836         spin_unlock(&q->db_lock);
837 }
838
839 /**
840  *      inline_tx_skb - inline a packet's data into Tx descriptors
841  *      @skb: the packet
842  *      @q: the Tx queue where the packet will be inlined
843  *      @pos: starting position in the Tx queue where to inline the packet
844  *
845  *      Inline a packet's contents directly into Tx descriptors, starting at
846  *      the given position within the Tx DMA ring.
847  *      Most of the complexity of this operation is dealing with wrap arounds
848  *      in the middle of the packet we want to inline.
849  */
850 static void inline_tx_skb(const struct sk_buff *skb, const struct sge_txq *q,
851                           void *pos)
852 {
853         u64 *p;
854         int left = (void *)q->stat - pos;
855
856         if (likely(skb->len <= left)) {
857                 if (likely(!skb->data_len))
858                         skb_copy_from_linear_data(skb, pos, skb->len);
859                 else
860                         skb_copy_bits(skb, 0, pos, skb->len);
861                 pos += skb->len;
862         } else {
863                 skb_copy_bits(skb, 0, pos, left);
864                 skb_copy_bits(skb, left, q->desc, skb->len - left);
865                 pos = (void *)q->desc + (skb->len - left);
866         }
867
868         /* 0-pad to multiple of 16 */
869         p = PTR_ALIGN(pos, 8);
870         if ((uintptr_t)p & 8)
871                 *p = 0;
872 }
873
874 /*
875  * Figure out what HW csum a packet wants and return the appropriate control
876  * bits.
877  */
878 static u64 hwcsum(const struct sk_buff *skb)
879 {
880         int csum_type;
881         const struct iphdr *iph = ip_hdr(skb);
882
883         if (iph->version == 4) {
884                 if (iph->protocol == IPPROTO_TCP)
885                         csum_type = TX_CSUM_TCPIP;
886                 else if (iph->protocol == IPPROTO_UDP)
887                         csum_type = TX_CSUM_UDPIP;
888                 else {
889 nocsum:                 /*
890                          * unknown protocol, disable HW csum
891                          * and hope a bad packet is detected
892                          */
893                         return TXPKT_L4CSUM_DIS;
894                 }
895         } else {
896                 /*
897                  * this doesn't work with extension headers
898                  */
899                 const struct ipv6hdr *ip6h = (const struct ipv6hdr *)iph;
900
901                 if (ip6h->nexthdr == IPPROTO_TCP)
902                         csum_type = TX_CSUM_TCPIP6;
903                 else if (ip6h->nexthdr == IPPROTO_UDP)
904                         csum_type = TX_CSUM_UDPIP6;
905                 else
906                         goto nocsum;
907         }
908
909         if (likely(csum_type >= TX_CSUM_TCPIP))
910                 return TXPKT_CSUM_TYPE(csum_type) |
911                         TXPKT_IPHDR_LEN(skb_network_header_len(skb)) |
912                         TXPKT_ETHHDR_LEN(skb_network_offset(skb) - ETH_HLEN);
913         else {
914                 int start = skb_transport_offset(skb);
915
916                 return TXPKT_CSUM_TYPE(csum_type) | TXPKT_CSUM_START(start) |
917                         TXPKT_CSUM_LOC(start + skb->csum_offset);
918         }
919 }
920
921 static void eth_txq_stop(struct sge_eth_txq *q)
922 {
923         netif_tx_stop_queue(q->txq);
924         q->q.stops++;
925 }
926
927 static inline void txq_advance(struct sge_txq *q, unsigned int n)
928 {
929         q->in_use += n;
930         q->pidx += n;
931         if (q->pidx >= q->size)
932                 q->pidx -= q->size;
933 }
934
935 /**
936  *      t4_eth_xmit - add a packet to an Ethernet Tx queue
937  *      @skb: the packet
938  *      @dev: the egress net device
939  *
940  *      Add a packet to an SGE Ethernet Tx queue.  Runs with softirqs disabled.
941  */
942 netdev_tx_t t4_eth_xmit(struct sk_buff *skb, struct net_device *dev)
943 {
944         u32 wr_mid;
945         u64 cntrl, *end;
946         int qidx, credits;
947         unsigned int flits, ndesc;
948         struct adapter *adap;
949         struct sge_eth_txq *q;
950         const struct port_info *pi;
951         struct fw_eth_tx_pkt_wr *wr;
952         struct cpl_tx_pkt_core *cpl;
953         const struct skb_shared_info *ssi;
954         dma_addr_t addr[MAX_SKB_FRAGS + 1];
955
956         /*
957          * The chip min packet length is 10 octets but play safe and reject
958          * anything shorter than an Ethernet header.
959          */
960         if (unlikely(skb->len < ETH_HLEN)) {
961 out_free:       dev_kfree_skb(skb);
962                 return NETDEV_TX_OK;
963         }
964
965         pi = netdev_priv(dev);
966         adap = pi->adapter;
967         qidx = skb_get_queue_mapping(skb);
968         q = &adap->sge.ethtxq[qidx + pi->first_qset];
969
970         reclaim_completed_tx(adap, &q->q, true);
971
972         flits = calc_tx_flits(skb);
973         ndesc = flits_to_desc(flits);
974         credits = txq_avail(&q->q) - ndesc;
975
976         if (unlikely(credits < 0)) {
977                 eth_txq_stop(q);
978                 dev_err(adap->pdev_dev,
979                         "%s: Tx ring %u full while queue awake!\n",
980                         dev->name, qidx);
981                 return NETDEV_TX_BUSY;
982         }
983
984         if (!is_eth_imm(skb) &&
985             unlikely(map_skb(adap->pdev_dev, skb, addr) < 0)) {
986                 q->mapping_err++;
987                 goto out_free;
988         }
989
990         wr_mid = FW_WR_LEN16(DIV_ROUND_UP(flits, 2));
991         if (unlikely(credits < ETHTXQ_STOP_THRES)) {
992                 eth_txq_stop(q);
993                 wr_mid |= FW_WR_EQUEQ | FW_WR_EQUIQ;
994         }
995
996         wr = (void *)&q->q.desc[q->q.pidx];
997         wr->equiq_to_len16 = htonl(wr_mid);
998         wr->r3 = cpu_to_be64(0);
999         end = (u64 *)wr + flits;
1000
1001         ssi = skb_shinfo(skb);
1002         if (ssi->gso_size) {
1003                 struct cpl_tx_pkt_lso *lso = (void *)wr;
1004                 bool v6 = (ssi->gso_type & SKB_GSO_TCPV6) != 0;
1005                 int l3hdr_len = skb_network_header_len(skb);
1006                 int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1007
1008                 wr->op_immdlen = htonl(FW_WR_OP(FW_ETH_TX_PKT_WR) |
1009                                        FW_WR_IMMDLEN(sizeof(*lso)));
1010                 lso->c.lso_ctrl = htonl(LSO_OPCODE(CPL_TX_PKT_LSO) |
1011                                         LSO_FIRST_SLICE | LSO_LAST_SLICE |
1012                                         LSO_IPV6(v6) |
1013                                         LSO_ETHHDR_LEN(eth_xtra_len / 4) |
1014                                         LSO_IPHDR_LEN(l3hdr_len / 4) |
1015                                         LSO_TCPHDR_LEN(tcp_hdr(skb)->doff));
1016                 lso->c.ipid_ofst = htons(0);
1017                 lso->c.mss = htons(ssi->gso_size);
1018                 lso->c.seqno_offset = htonl(0);
1019                 lso->c.len = htonl(skb->len);
1020                 cpl = (void *)(lso + 1);
1021                 cntrl = TXPKT_CSUM_TYPE(v6 ? TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
1022                         TXPKT_IPHDR_LEN(l3hdr_len) |
1023                         TXPKT_ETHHDR_LEN(eth_xtra_len);
1024                 q->tso++;
1025                 q->tx_cso += ssi->gso_segs;
1026         } else {
1027                 int len;
1028
1029                 len = is_eth_imm(skb) ? skb->len + sizeof(*cpl) : sizeof(*cpl);
1030                 wr->op_immdlen = htonl(FW_WR_OP(FW_ETH_TX_PKT_WR) |
1031                                        FW_WR_IMMDLEN(len));
1032                 cpl = (void *)(wr + 1);
1033                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1034                         cntrl = hwcsum(skb) | TXPKT_IPCSUM_DIS;
1035                         q->tx_cso++;
1036                 } else
1037                         cntrl = TXPKT_L4CSUM_DIS | TXPKT_IPCSUM_DIS;
1038         }
1039
1040         if (vlan_tx_tag_present(skb)) {
1041                 q->vlan_ins++;
1042                 cntrl |= TXPKT_VLAN_VLD | TXPKT_VLAN(vlan_tx_tag_get(skb));
1043         }
1044
1045         cpl->ctrl0 = htonl(TXPKT_OPCODE(CPL_TX_PKT_XT) |
1046                            TXPKT_INTF(pi->tx_chan) | TXPKT_PF(adap->fn));
1047         cpl->pack = htons(0);
1048         cpl->len = htons(skb->len);
1049         cpl->ctrl1 = cpu_to_be64(cntrl);
1050
1051         if (is_eth_imm(skb)) {
1052                 inline_tx_skb(skb, &q->q, cpl + 1);
1053                 dev_kfree_skb(skb);
1054         } else {
1055                 int last_desc;
1056
1057                 write_sgl(skb, &q->q, (struct ulptx_sgl *)(cpl + 1), end, 0,
1058                           addr);
1059                 skb_orphan(skb);
1060
1061                 last_desc = q->q.pidx + ndesc - 1;
1062                 if (last_desc >= q->q.size)
1063                         last_desc -= q->q.size;
1064                 q->q.sdesc[last_desc].skb = skb;
1065                 q->q.sdesc[last_desc].sgl = (struct ulptx_sgl *)(cpl + 1);
1066         }
1067
1068         txq_advance(&q->q, ndesc);
1069
1070         ring_tx_db(adap, &q->q, ndesc);
1071         return NETDEV_TX_OK;
1072 }
1073
1074 /**
1075  *      reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
1076  *      @q: the SGE control Tx queue
1077  *
1078  *      This is a variant of reclaim_completed_tx() that is used for Tx queues
1079  *      that send only immediate data (presently just the control queues) and
1080  *      thus do not have any sk_buffs to release.
1081  */
1082 static inline void reclaim_completed_tx_imm(struct sge_txq *q)
1083 {
1084         int hw_cidx = ntohs(q->stat->cidx);
1085         int reclaim = hw_cidx - q->cidx;
1086
1087         if (reclaim < 0)
1088                 reclaim += q->size;
1089
1090         q->in_use -= reclaim;
1091         q->cidx = hw_cidx;
1092 }
1093
1094 /**
1095  *      is_imm - check whether a packet can be sent as immediate data
1096  *      @skb: the packet
1097  *
1098  *      Returns true if a packet can be sent as a WR with immediate data.
1099  */
1100 static inline int is_imm(const struct sk_buff *skb)
1101 {
1102         return skb->len <= MAX_CTRL_WR_LEN;
1103 }
1104
1105 /**
1106  *      ctrlq_check_stop - check if a control queue is full and should stop
1107  *      @q: the queue
1108  *      @wr: most recent WR written to the queue
1109  *
1110  *      Check if a control queue has become full and should be stopped.
1111  *      We clean up control queue descriptors very lazily, only when we are out.
1112  *      If the queue is still full after reclaiming any completed descriptors
1113  *      we suspend it and have the last WR wake it up.
1114  */
1115 static void ctrlq_check_stop(struct sge_ctrl_txq *q, struct fw_wr_hdr *wr)
1116 {
1117         reclaim_completed_tx_imm(&q->q);
1118         if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
1119                 wr->lo |= htonl(FW_WR_EQUEQ | FW_WR_EQUIQ);
1120                 q->q.stops++;
1121                 q->full = 1;
1122         }
1123 }
1124
1125 /**
1126  *      ctrl_xmit - send a packet through an SGE control Tx queue
1127  *      @q: the control queue
1128  *      @skb: the packet
1129  *
1130  *      Send a packet through an SGE control Tx queue.  Packets sent through
1131  *      a control queue must fit entirely as immediate data.
1132  */
1133 static int ctrl_xmit(struct sge_ctrl_txq *q, struct sk_buff *skb)
1134 {
1135         unsigned int ndesc;
1136         struct fw_wr_hdr *wr;
1137
1138         if (unlikely(!is_imm(skb))) {
1139                 WARN_ON(1);
1140                 dev_kfree_skb(skb);
1141                 return NET_XMIT_DROP;
1142         }
1143
1144         ndesc = DIV_ROUND_UP(skb->len, sizeof(struct tx_desc));
1145         spin_lock(&q->sendq.lock);
1146
1147         if (unlikely(q->full)) {
1148                 skb->priority = ndesc;                  /* save for restart */
1149                 __skb_queue_tail(&q->sendq, skb);
1150                 spin_unlock(&q->sendq.lock);
1151                 return NET_XMIT_CN;
1152         }
1153
1154         wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1155         inline_tx_skb(skb, &q->q, wr);
1156
1157         txq_advance(&q->q, ndesc);
1158         if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES))
1159                 ctrlq_check_stop(q, wr);
1160
1161         ring_tx_db(q->adap, &q->q, ndesc);
1162         spin_unlock(&q->sendq.lock);
1163
1164         kfree_skb(skb);
1165         return NET_XMIT_SUCCESS;
1166 }
1167
1168 /**
1169  *      restart_ctrlq - restart a suspended control queue
1170  *      @data: the control queue to restart
1171  *
1172  *      Resumes transmission on a suspended Tx control queue.
1173  */
1174 static void restart_ctrlq(unsigned long data)
1175 {
1176         struct sk_buff *skb;
1177         unsigned int written = 0;
1178         struct sge_ctrl_txq *q = (struct sge_ctrl_txq *)data;
1179
1180         spin_lock(&q->sendq.lock);
1181         reclaim_completed_tx_imm(&q->q);
1182         BUG_ON(txq_avail(&q->q) < TXQ_STOP_THRES);  /* q should be empty */
1183
1184         while ((skb = __skb_dequeue(&q->sendq)) != NULL) {
1185                 struct fw_wr_hdr *wr;
1186                 unsigned int ndesc = skb->priority;     /* previously saved */
1187
1188                 /*
1189                  * Write descriptors and free skbs outside the lock to limit
1190                  * wait times.  q->full is still set so new skbs will be queued.
1191                  */
1192                 spin_unlock(&q->sendq.lock);
1193
1194                 wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1195                 inline_tx_skb(skb, &q->q, wr);
1196                 kfree_skb(skb);
1197
1198                 written += ndesc;
1199                 txq_advance(&q->q, ndesc);
1200                 if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
1201                         unsigned long old = q->q.stops;
1202
1203                         ctrlq_check_stop(q, wr);
1204                         if (q->q.stops != old) {          /* suspended anew */
1205                                 spin_lock(&q->sendq.lock);
1206                                 goto ringdb;
1207                         }
1208                 }
1209                 if (written > 16) {
1210                         ring_tx_db(q->adap, &q->q, written);
1211                         written = 0;
1212                 }
1213                 spin_lock(&q->sendq.lock);
1214         }
1215         q->full = 0;
1216 ringdb: if (written)
1217                 ring_tx_db(q->adap, &q->q, written);
1218         spin_unlock(&q->sendq.lock);
1219 }
1220
1221 /**
1222  *      t4_mgmt_tx - send a management message
1223  *      @adap: the adapter
1224  *      @skb: the packet containing the management message
1225  *
1226  *      Send a management message through control queue 0.
1227  */
1228 int t4_mgmt_tx(struct adapter *adap, struct sk_buff *skb)
1229 {
1230         int ret;
1231
1232         local_bh_disable();
1233         ret = ctrl_xmit(&adap->sge.ctrlq[0], skb);
1234         local_bh_enable();
1235         return ret;
1236 }
1237
1238 /**
1239  *      is_ofld_imm - check whether a packet can be sent as immediate data
1240  *      @skb: the packet
1241  *
1242  *      Returns true if a packet can be sent as an offload WR with immediate
1243  *      data.  We currently use the same limit as for Ethernet packets.
1244  */
1245 static inline int is_ofld_imm(const struct sk_buff *skb)
1246 {
1247         return skb->len <= MAX_IMM_TX_PKT_LEN;
1248 }
1249
1250 /**
1251  *      calc_tx_flits_ofld - calculate # of flits for an offload packet
1252  *      @skb: the packet
1253  *
1254  *      Returns the number of flits needed for the given offload packet.
1255  *      These packets are already fully constructed and no additional headers
1256  *      will be added.
1257  */
1258 static inline unsigned int calc_tx_flits_ofld(const struct sk_buff *skb)
1259 {
1260         unsigned int flits, cnt;
1261
1262         if (is_ofld_imm(skb))
1263                 return DIV_ROUND_UP(skb->len, 8);
1264
1265         flits = skb_transport_offset(skb) / 8U;   /* headers */
1266         cnt = skb_shinfo(skb)->nr_frags;
1267         if (skb->tail != skb->transport_header)
1268                 cnt++;
1269         return flits + sgl_len(cnt);
1270 }
1271
1272 /**
1273  *      txq_stop_maperr - stop a Tx queue due to I/O MMU exhaustion
1274  *      @adap: the adapter
1275  *      @q: the queue to stop
1276  *
1277  *      Mark a Tx queue stopped due to I/O MMU exhaustion and resulting
1278  *      inability to map packets.  A periodic timer attempts to restart
1279  *      queues so marked.
1280  */
1281 static void txq_stop_maperr(struct sge_ofld_txq *q)
1282 {
1283         q->mapping_err++;
1284         q->q.stops++;
1285         set_bit(q->q.cntxt_id - q->adap->sge.egr_start,
1286                 q->adap->sge.txq_maperr);
1287 }
1288
1289 /**
1290  *      ofldtxq_stop - stop an offload Tx queue that has become full
1291  *      @q: the queue to stop
1292  *      @skb: the packet causing the queue to become full
1293  *
1294  *      Stops an offload Tx queue that has become full and modifies the packet
1295  *      being written to request a wakeup.
1296  */
1297 static void ofldtxq_stop(struct sge_ofld_txq *q, struct sk_buff *skb)
1298 {
1299         struct fw_wr_hdr *wr = (struct fw_wr_hdr *)skb->data;
1300
1301         wr->lo |= htonl(FW_WR_EQUEQ | FW_WR_EQUIQ);
1302         q->q.stops++;
1303         q->full = 1;
1304 }
1305
1306 /**
1307  *      service_ofldq - restart a suspended offload queue
1308  *      @q: the offload queue
1309  *
1310  *      Services an offload Tx queue by moving packets from its packet queue
1311  *      to the HW Tx ring.  The function starts and ends with the queue locked.
1312  */
1313 static void service_ofldq(struct sge_ofld_txq *q)
1314 {
1315         u64 *pos;
1316         int credits;
1317         struct sk_buff *skb;
1318         unsigned int written = 0;
1319         unsigned int flits, ndesc;
1320
1321         while ((skb = skb_peek(&q->sendq)) != NULL && !q->full) {
1322                 /*
1323                  * We drop the lock but leave skb on sendq, thus retaining
1324                  * exclusive access to the state of the queue.
1325                  */
1326                 spin_unlock(&q->sendq.lock);
1327
1328                 reclaim_completed_tx(q->adap, &q->q, false);
1329
1330                 flits = skb->priority;                /* previously saved */
1331                 ndesc = flits_to_desc(flits);
1332                 credits = txq_avail(&q->q) - ndesc;
1333                 BUG_ON(credits < 0);
1334                 if (unlikely(credits < TXQ_STOP_THRES))
1335                         ofldtxq_stop(q, skb);
1336
1337                 pos = (u64 *)&q->q.desc[q->q.pidx];
1338                 if (is_ofld_imm(skb))
1339                         inline_tx_skb(skb, &q->q, pos);
1340                 else if (map_skb(q->adap->pdev_dev, skb,
1341                                  (dma_addr_t *)skb->head)) {
1342                         txq_stop_maperr(q);
1343                         spin_lock(&q->sendq.lock);
1344                         break;
1345                 } else {
1346                         int last_desc, hdr_len = skb_transport_offset(skb);
1347
1348                         memcpy(pos, skb->data, hdr_len);
1349                         write_sgl(skb, &q->q, (void *)pos + hdr_len,
1350                                   pos + flits, hdr_len,
1351                                   (dma_addr_t *)skb->head);
1352 #ifdef CONFIG_NEED_DMA_MAP_STATE
1353                         skb->dev = q->adap->port[0];
1354                         skb->destructor = deferred_unmap_destructor;
1355 #endif
1356                         last_desc = q->q.pidx + ndesc - 1;
1357                         if (last_desc >= q->q.size)
1358                                 last_desc -= q->q.size;
1359                         q->q.sdesc[last_desc].skb = skb;
1360                 }
1361
1362                 txq_advance(&q->q, ndesc);
1363                 written += ndesc;
1364                 if (unlikely(written > 32)) {
1365                         ring_tx_db(q->adap, &q->q, written);
1366                         written = 0;
1367                 }
1368
1369                 spin_lock(&q->sendq.lock);
1370                 __skb_unlink(skb, &q->sendq);
1371                 if (is_ofld_imm(skb))
1372                         kfree_skb(skb);
1373         }
1374         if (likely(written))
1375                 ring_tx_db(q->adap, &q->q, written);
1376 }
1377
1378 /**
1379  *      ofld_xmit - send a packet through an offload queue
1380  *      @q: the Tx offload queue
1381  *      @skb: the packet
1382  *
1383  *      Send an offload packet through an SGE offload queue.
1384  */
1385 static int ofld_xmit(struct sge_ofld_txq *q, struct sk_buff *skb)
1386 {
1387         skb->priority = calc_tx_flits_ofld(skb);       /* save for restart */
1388         spin_lock(&q->sendq.lock);
1389         __skb_queue_tail(&q->sendq, skb);
1390         if (q->sendq.qlen == 1)
1391                 service_ofldq(q);
1392         spin_unlock(&q->sendq.lock);
1393         return NET_XMIT_SUCCESS;
1394 }
1395
1396 /**
1397  *      restart_ofldq - restart a suspended offload queue
1398  *      @data: the offload queue to restart
1399  *
1400  *      Resumes transmission on a suspended Tx offload queue.
1401  */
1402 static void restart_ofldq(unsigned long data)
1403 {
1404         struct sge_ofld_txq *q = (struct sge_ofld_txq *)data;
1405
1406         spin_lock(&q->sendq.lock);
1407         q->full = 0;            /* the queue actually is completely empty now */
1408         service_ofldq(q);
1409         spin_unlock(&q->sendq.lock);
1410 }
1411
1412 /**
1413  *      skb_txq - return the Tx queue an offload packet should use
1414  *      @skb: the packet
1415  *
1416  *      Returns the Tx queue an offload packet should use as indicated by bits
1417  *      1-15 in the packet's queue_mapping.
1418  */
1419 static inline unsigned int skb_txq(const struct sk_buff *skb)
1420 {
1421         return skb->queue_mapping >> 1;
1422 }
1423
1424 /**
1425  *      is_ctrl_pkt - return whether an offload packet is a control packet
1426  *      @skb: the packet
1427  *
1428  *      Returns whether an offload packet should use an OFLD or a CTRL
1429  *      Tx queue as indicated by bit 0 in the packet's queue_mapping.
1430  */
1431 static inline unsigned int is_ctrl_pkt(const struct sk_buff *skb)
1432 {
1433         return skb->queue_mapping & 1;
1434 }
1435
1436 static inline int ofld_send(struct adapter *adap, struct sk_buff *skb)
1437 {
1438         unsigned int idx = skb_txq(skb);
1439
1440         if (unlikely(is_ctrl_pkt(skb)))
1441                 return ctrl_xmit(&adap->sge.ctrlq[idx], skb);
1442         return ofld_xmit(&adap->sge.ofldtxq[idx], skb);
1443 }
1444
1445 /**
1446  *      t4_ofld_send - send an offload packet
1447  *      @adap: the adapter
1448  *      @skb: the packet
1449  *
1450  *      Sends an offload packet.  We use the packet queue_mapping to select the
1451  *      appropriate Tx queue as follows: bit 0 indicates whether the packet
1452  *      should be sent as regular or control, bits 1-15 select the queue.
1453  */
1454 int t4_ofld_send(struct adapter *adap, struct sk_buff *skb)
1455 {
1456         int ret;
1457
1458         local_bh_disable();
1459         ret = ofld_send(adap, skb);
1460         local_bh_enable();
1461         return ret;
1462 }
1463
1464 /**
1465  *      cxgb4_ofld_send - send an offload packet
1466  *      @dev: the net device
1467  *      @skb: the packet
1468  *
1469  *      Sends an offload packet.  This is an exported version of @t4_ofld_send,
1470  *      intended for ULDs.
1471  */
1472 int cxgb4_ofld_send(struct net_device *dev, struct sk_buff *skb)
1473 {
1474         return t4_ofld_send(netdev2adap(dev), skb);
1475 }
1476 EXPORT_SYMBOL(cxgb4_ofld_send);
1477
1478 static inline void copy_frags(struct sk_buff *skb,
1479                               const struct pkt_gl *gl, unsigned int offset)
1480 {
1481         int i;
1482
1483         /* usually there's just one frag */
1484         __skb_fill_page_desc(skb, 0, gl->frags[0].page,
1485                              gl->frags[0].offset + offset,
1486                              gl->frags[0].size - offset);
1487         skb_shinfo(skb)->nr_frags = gl->nfrags;
1488         for (i = 1; i < gl->nfrags; i++)
1489                 __skb_fill_page_desc(skb, i, gl->frags[i].page,
1490                                      gl->frags[i].offset,
1491                                      gl->frags[i].size);
1492
1493         /* get a reference to the last page, we don't own it */
1494         get_page(gl->frags[gl->nfrags - 1].page);
1495 }
1496
1497 /**
1498  *      cxgb4_pktgl_to_skb - build an sk_buff from a packet gather list
1499  *      @gl: the gather list
1500  *      @skb_len: size of sk_buff main body if it carries fragments
1501  *      @pull_len: amount of data to move to the sk_buff's main body
1502  *
1503  *      Builds an sk_buff from the given packet gather list.  Returns the
1504  *      sk_buff or %NULL if sk_buff allocation failed.
1505  */
1506 struct sk_buff *cxgb4_pktgl_to_skb(const struct pkt_gl *gl,
1507                                    unsigned int skb_len, unsigned int pull_len)
1508 {
1509         struct sk_buff *skb;
1510
1511         /*
1512          * Below we rely on RX_COPY_THRES being less than the smallest Rx buffer
1513          * size, which is expected since buffers are at least PAGE_SIZEd.
1514          * In this case packets up to RX_COPY_THRES have only one fragment.
1515          */
1516         if (gl->tot_len <= RX_COPY_THRES) {
1517                 skb = dev_alloc_skb(gl->tot_len);
1518                 if (unlikely(!skb))
1519                         goto out;
1520                 __skb_put(skb, gl->tot_len);
1521                 skb_copy_to_linear_data(skb, gl->va, gl->tot_len);
1522         } else {
1523                 skb = dev_alloc_skb(skb_len);
1524                 if (unlikely(!skb))
1525                         goto out;
1526                 __skb_put(skb, pull_len);
1527                 skb_copy_to_linear_data(skb, gl->va, pull_len);
1528
1529                 copy_frags(skb, gl, pull_len);
1530                 skb->len = gl->tot_len;
1531                 skb->data_len = skb->len - pull_len;
1532                 skb->truesize += skb->data_len;
1533         }
1534 out:    return skb;
1535 }
1536 EXPORT_SYMBOL(cxgb4_pktgl_to_skb);
1537
1538 /**
1539  *      t4_pktgl_free - free a packet gather list
1540  *      @gl: the gather list
1541  *
1542  *      Releases the pages of a packet gather list.  We do not own the last
1543  *      page on the list and do not free it.
1544  */
1545 static void t4_pktgl_free(const struct pkt_gl *gl)
1546 {
1547         int n;
1548         const struct page_frag *p;
1549
1550         for (p = gl->frags, n = gl->nfrags - 1; n--; p++)
1551                 put_page(p->page);
1552 }
1553
1554 /*
1555  * Process an MPS trace packet.  Give it an unused protocol number so it won't
1556  * be delivered to anyone and send it to the stack for capture.
1557  */
1558 static noinline int handle_trace_pkt(struct adapter *adap,
1559                                      const struct pkt_gl *gl)
1560 {
1561         struct sk_buff *skb;
1562
1563         skb = cxgb4_pktgl_to_skb(gl, RX_PULL_LEN, RX_PULL_LEN);
1564         if (unlikely(!skb)) {
1565                 t4_pktgl_free(gl);
1566                 return 0;
1567         }
1568
1569         if (is_t4(adap->chip))
1570                 __skb_pull(skb, sizeof(struct cpl_trace_pkt));
1571         else
1572                 __skb_pull(skb, sizeof(struct cpl_t5_trace_pkt));
1573
1574         skb_reset_mac_header(skb);
1575         skb->protocol = htons(0xffff);
1576         skb->dev = adap->port[0];
1577         netif_receive_skb(skb);
1578         return 0;
1579 }
1580
1581 static void do_gro(struct sge_eth_rxq *rxq, const struct pkt_gl *gl,
1582                    const struct cpl_rx_pkt *pkt)
1583 {
1584         struct adapter *adapter = rxq->rspq.adap;
1585         struct sge *s = &adapter->sge;
1586         int ret;
1587         struct sk_buff *skb;
1588
1589         skb = napi_get_frags(&rxq->rspq.napi);
1590         if (unlikely(!skb)) {
1591                 t4_pktgl_free(gl);
1592                 rxq->stats.rx_drops++;
1593                 return;
1594         }
1595
1596         copy_frags(skb, gl, s->pktshift);
1597         skb->len = gl->tot_len - s->pktshift;
1598         skb->data_len = skb->len;
1599         skb->truesize += skb->data_len;
1600         skb->ip_summed = CHECKSUM_UNNECESSARY;
1601         skb_record_rx_queue(skb, rxq->rspq.idx);
1602         if (rxq->rspq.netdev->features & NETIF_F_RXHASH)
1603                 skb->rxhash = (__force u32)pkt->rsshdr.hash_val;
1604
1605         if (unlikely(pkt->vlan_ex)) {
1606                 __vlan_hwaccel_put_tag(skb, ntohs(pkt->vlan));
1607                 rxq->stats.vlan_ex++;
1608         }
1609         ret = napi_gro_frags(&rxq->rspq.napi);
1610         if (ret == GRO_HELD)
1611                 rxq->stats.lro_pkts++;
1612         else if (ret == GRO_MERGED || ret == GRO_MERGED_FREE)
1613                 rxq->stats.lro_merged++;
1614         rxq->stats.pkts++;
1615         rxq->stats.rx_cso++;
1616 }
1617
1618 /**
1619  *      t4_ethrx_handler - process an ingress ethernet packet
1620  *      @q: the response queue that received the packet
1621  *      @rsp: the response queue descriptor holding the RX_PKT message
1622  *      @si: the gather list of packet fragments
1623  *
1624  *      Process an ingress ethernet packet and deliver it to the stack.
1625  */
1626 int t4_ethrx_handler(struct sge_rspq *q, const __be64 *rsp,
1627                      const struct pkt_gl *si)
1628 {
1629         bool csum_ok;
1630         struct sk_buff *skb;
1631         const struct cpl_rx_pkt *pkt;
1632         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
1633         struct sge *s = &q->adap->sge;
1634         int cpl_trace_pkt = is_t4(q->adap->chip) ?
1635                             CPL_TRACE_PKT : CPL_TRACE_PKT_T5;
1636
1637         if (unlikely(*(u8 *)rsp == cpl_trace_pkt))
1638                 return handle_trace_pkt(q->adap, si);
1639
1640         pkt = (const struct cpl_rx_pkt *)rsp;
1641         csum_ok = pkt->csum_calc && !pkt->err_vec;
1642         if ((pkt->l2info & htonl(RXF_TCP)) &&
1643             (q->netdev->features & NETIF_F_GRO) && csum_ok && !pkt->ip_frag) {
1644                 do_gro(rxq, si, pkt);
1645                 return 0;
1646         }
1647
1648         skb = cxgb4_pktgl_to_skb(si, RX_PKT_SKB_LEN, RX_PULL_LEN);
1649         if (unlikely(!skb)) {
1650                 t4_pktgl_free(si);
1651                 rxq->stats.rx_drops++;
1652                 return 0;
1653         }
1654
1655         __skb_pull(skb, s->pktshift);      /* remove ethernet header padding */
1656         skb->protocol = eth_type_trans(skb, q->netdev);
1657         skb_record_rx_queue(skb, q->idx);
1658         if (skb->dev->features & NETIF_F_RXHASH)
1659                 skb->rxhash = (__force u32)pkt->rsshdr.hash_val;
1660
1661         rxq->stats.pkts++;
1662
1663         if (csum_ok && (q->netdev->features & NETIF_F_RXCSUM) &&
1664             (pkt->l2info & htonl(RXF_UDP | RXF_TCP))) {
1665                 if (!pkt->ip_frag) {
1666                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1667                         rxq->stats.rx_cso++;
1668                 } else if (pkt->l2info & htonl(RXF_IP)) {
1669                         __sum16 c = (__force __sum16)pkt->csum;
1670                         skb->csum = csum_unfold(c);
1671                         skb->ip_summed = CHECKSUM_COMPLETE;
1672                         rxq->stats.rx_cso++;
1673                 }
1674         } else
1675                 skb_checksum_none_assert(skb);
1676
1677         if (unlikely(pkt->vlan_ex)) {
1678                 __vlan_hwaccel_put_tag(skb, ntohs(pkt->vlan));
1679                 rxq->stats.vlan_ex++;
1680         }
1681         netif_receive_skb(skb);
1682         return 0;
1683 }
1684
1685 /**
1686  *      restore_rx_bufs - put back a packet's Rx buffers
1687  *      @si: the packet gather list
1688  *      @q: the SGE free list
1689  *      @frags: number of FL buffers to restore
1690  *
1691  *      Puts back on an FL the Rx buffers associated with @si.  The buffers
1692  *      have already been unmapped and are left unmapped, we mark them so to
1693  *      prevent further unmapping attempts.
1694  *
1695  *      This function undoes a series of @unmap_rx_buf calls when we find out
1696  *      that the current packet can't be processed right away afterall and we
1697  *      need to come back to it later.  This is a very rare event and there's
1698  *      no effort to make this particularly efficient.
1699  */
1700 static void restore_rx_bufs(const struct pkt_gl *si, struct sge_fl *q,
1701                             int frags)
1702 {
1703         struct rx_sw_desc *d;
1704
1705         while (frags--) {
1706                 if (q->cidx == 0)
1707                         q->cidx = q->size - 1;
1708                 else
1709                         q->cidx--;
1710                 d = &q->sdesc[q->cidx];
1711                 d->page = si->frags[frags].page;
1712                 d->dma_addr |= RX_UNMAPPED_BUF;
1713                 q->avail++;
1714         }
1715 }
1716
1717 /**
1718  *      is_new_response - check if a response is newly written
1719  *      @r: the response descriptor
1720  *      @q: the response queue
1721  *
1722  *      Returns true if a response descriptor contains a yet unprocessed
1723  *      response.
1724  */
1725 static inline bool is_new_response(const struct rsp_ctrl *r,
1726                                    const struct sge_rspq *q)
1727 {
1728         return RSPD_GEN(r->type_gen) == q->gen;
1729 }
1730
1731 /**
1732  *      rspq_next - advance to the next entry in a response queue
1733  *      @q: the queue
1734  *
1735  *      Updates the state of a response queue to advance it to the next entry.
1736  */
1737 static inline void rspq_next(struct sge_rspq *q)
1738 {
1739         q->cur_desc = (void *)q->cur_desc + q->iqe_len;
1740         if (unlikely(++q->cidx == q->size)) {
1741                 q->cidx = 0;
1742                 q->gen ^= 1;
1743                 q->cur_desc = q->desc;
1744         }
1745 }
1746
1747 /**
1748  *      process_responses - process responses from an SGE response queue
1749  *      @q: the ingress queue to process
1750  *      @budget: how many responses can be processed in this round
1751  *
1752  *      Process responses from an SGE response queue up to the supplied budget.
1753  *      Responses include received packets as well as control messages from FW
1754  *      or HW.
1755  *
1756  *      Additionally choose the interrupt holdoff time for the next interrupt
1757  *      on this queue.  If the system is under memory shortage use a fairly
1758  *      long delay to help recovery.
1759  */
1760 static int process_responses(struct sge_rspq *q, int budget)
1761 {
1762         int ret, rsp_type;
1763         int budget_left = budget;
1764         const struct rsp_ctrl *rc;
1765         struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
1766         struct adapter *adapter = q->adap;
1767         struct sge *s = &adapter->sge;
1768
1769         while (likely(budget_left)) {
1770                 rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
1771                 if (!is_new_response(rc, q))
1772                         break;
1773
1774                 rmb();
1775                 rsp_type = RSPD_TYPE(rc->type_gen);
1776                 if (likely(rsp_type == RSP_TYPE_FLBUF)) {
1777                         struct page_frag *fp;
1778                         struct pkt_gl si;
1779                         const struct rx_sw_desc *rsd;
1780                         u32 len = ntohl(rc->pldbuflen_qid), bufsz, frags;
1781
1782                         if (len & RSPD_NEWBUF) {
1783                                 if (likely(q->offset > 0)) {
1784                                         free_rx_bufs(q->adap, &rxq->fl, 1);
1785                                         q->offset = 0;
1786                                 }
1787                                 len = RSPD_LEN(len);
1788                         }
1789                         si.tot_len = len;
1790
1791                         /* gather packet fragments */
1792                         for (frags = 0, fp = si.frags; ; frags++, fp++) {
1793                                 rsd = &rxq->fl.sdesc[rxq->fl.cidx];
1794                                 bufsz = get_buf_size(adapter, rsd);
1795                                 fp->page = rsd->page;
1796                                 fp->offset = q->offset;
1797                                 fp->size = min(bufsz, len);
1798                                 len -= fp->size;
1799                                 if (!len)
1800                                         break;
1801                                 unmap_rx_buf(q->adap, &rxq->fl);
1802                         }
1803
1804                         /*
1805                          * Last buffer remains mapped so explicitly make it
1806                          * coherent for CPU access.
1807                          */
1808                         dma_sync_single_for_cpu(q->adap->pdev_dev,
1809                                                 get_buf_addr(rsd),
1810                                                 fp->size, DMA_FROM_DEVICE);
1811
1812                         si.va = page_address(si.frags[0].page) +
1813                                 si.frags[0].offset;
1814                         prefetch(si.va);
1815
1816                         si.nfrags = frags + 1;
1817                         ret = q->handler(q, q->cur_desc, &si);
1818                         if (likely(ret == 0))
1819                                 q->offset += ALIGN(fp->size, s->fl_align);
1820                         else
1821                                 restore_rx_bufs(&si, &rxq->fl, frags);
1822                 } else if (likely(rsp_type == RSP_TYPE_CPL)) {
1823                         ret = q->handler(q, q->cur_desc, NULL);
1824                 } else {
1825                         ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
1826                 }
1827
1828                 if (unlikely(ret)) {
1829                         /* couldn't process descriptor, back off for recovery */
1830                         q->next_intr_params = QINTR_TIMER_IDX(NOMEM_TMR_IDX);
1831                         break;
1832                 }
1833
1834                 rspq_next(q);
1835                 budget_left--;
1836         }
1837
1838         if (q->offset >= 0 && rxq->fl.size - rxq->fl.avail >= 16)
1839                 __refill_fl(q->adap, &rxq->fl);
1840         return budget - budget_left;
1841 }
1842
1843 /**
1844  *      napi_rx_handler - the NAPI handler for Rx processing
1845  *      @napi: the napi instance
1846  *      @budget: how many packets we can process in this round
1847  *
1848  *      Handler for new data events when using NAPI.  This does not need any
1849  *      locking or protection from interrupts as data interrupts are off at
1850  *      this point and other adapter interrupts do not interfere (the latter
1851  *      in not a concern at all with MSI-X as non-data interrupts then have
1852  *      a separate handler).
1853  */
1854 static int napi_rx_handler(struct napi_struct *napi, int budget)
1855 {
1856         unsigned int params;
1857         struct sge_rspq *q = container_of(napi, struct sge_rspq, napi);
1858         int work_done = process_responses(q, budget);
1859
1860         if (likely(work_done < budget)) {
1861                 napi_complete(napi);
1862                 params = q->next_intr_params;
1863                 q->next_intr_params = q->intr_params;
1864         } else
1865                 params = QINTR_TIMER_IDX(7);
1866
1867         t4_write_reg(q->adap, MYPF_REG(SGE_PF_GTS), CIDXINC(work_done) |
1868                      INGRESSQID((u32)q->cntxt_id) | SEINTARM(params));
1869         return work_done;
1870 }
1871
1872 /*
1873  * The MSI-X interrupt handler for an SGE response queue.
1874  */
1875 irqreturn_t t4_sge_intr_msix(int irq, void *cookie)
1876 {
1877         struct sge_rspq *q = cookie;
1878
1879         napi_schedule(&q->napi);
1880         return IRQ_HANDLED;
1881 }
1882
1883 /*
1884  * Process the indirect interrupt entries in the interrupt queue and kick off
1885  * NAPI for each queue that has generated an entry.
1886  */
1887 static unsigned int process_intrq(struct adapter *adap)
1888 {
1889         unsigned int credits;
1890         const struct rsp_ctrl *rc;
1891         struct sge_rspq *q = &adap->sge.intrq;
1892
1893         spin_lock(&adap->sge.intrq_lock);
1894         for (credits = 0; ; credits++) {
1895                 rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
1896                 if (!is_new_response(rc, q))
1897                         break;
1898
1899                 rmb();
1900                 if (RSPD_TYPE(rc->type_gen) == RSP_TYPE_INTR) {
1901                         unsigned int qid = ntohl(rc->pldbuflen_qid);
1902
1903                         qid -= adap->sge.ingr_start;
1904                         napi_schedule(&adap->sge.ingr_map[qid]->napi);
1905                 }
1906
1907                 rspq_next(q);
1908         }
1909
1910         t4_write_reg(adap, MYPF_REG(SGE_PF_GTS), CIDXINC(credits) |
1911                      INGRESSQID(q->cntxt_id) | SEINTARM(q->intr_params));
1912         spin_unlock(&adap->sge.intrq_lock);
1913         return credits;
1914 }
1915
1916 /*
1917  * The MSI interrupt handler, which handles data events from SGE response queues
1918  * as well as error and other async events as they all use the same MSI vector.
1919  */
1920 static irqreturn_t t4_intr_msi(int irq, void *cookie)
1921 {
1922         struct adapter *adap = cookie;
1923
1924         t4_slow_intr_handler(adap);
1925         process_intrq(adap);
1926         return IRQ_HANDLED;
1927 }
1928
1929 /*
1930  * Interrupt handler for legacy INTx interrupts.
1931  * Handles data events from SGE response queues as well as error and other
1932  * async events as they all use the same interrupt line.
1933  */
1934 static irqreturn_t t4_intr_intx(int irq, void *cookie)
1935 {
1936         struct adapter *adap = cookie;
1937
1938         t4_write_reg(adap, MYPF_REG(PCIE_PF_CLI), 0);
1939         if (t4_slow_intr_handler(adap) | process_intrq(adap))
1940                 return IRQ_HANDLED;
1941         return IRQ_NONE;             /* probably shared interrupt */
1942 }
1943
1944 /**
1945  *      t4_intr_handler - select the top-level interrupt handler
1946  *      @adap: the adapter
1947  *
1948  *      Selects the top-level interrupt handler based on the type of interrupts
1949  *      (MSI-X, MSI, or INTx).
1950  */
1951 irq_handler_t t4_intr_handler(struct adapter *adap)
1952 {
1953         if (adap->flags & USING_MSIX)
1954                 return t4_sge_intr_msix;
1955         if (adap->flags & USING_MSI)
1956                 return t4_intr_msi;
1957         return t4_intr_intx;
1958 }
1959
1960 static void sge_rx_timer_cb(unsigned long data)
1961 {
1962         unsigned long m;
1963         unsigned int i, cnt[2];
1964         struct adapter *adap = (struct adapter *)data;
1965         struct sge *s = &adap->sge;
1966
1967         for (i = 0; i < ARRAY_SIZE(s->starving_fl); i++)
1968                 for (m = s->starving_fl[i]; m; m &= m - 1) {
1969                         struct sge_eth_rxq *rxq;
1970                         unsigned int id = __ffs(m) + i * BITS_PER_LONG;
1971                         struct sge_fl *fl = s->egr_map[id];
1972
1973                         clear_bit(id, s->starving_fl);
1974                         smp_mb__after_clear_bit();
1975
1976                         if (fl_starving(fl)) {
1977                                 rxq = container_of(fl, struct sge_eth_rxq, fl);
1978                                 if (napi_reschedule(&rxq->rspq.napi))
1979                                         fl->starving++;
1980                                 else
1981                                         set_bit(id, s->starving_fl);
1982                         }
1983                 }
1984
1985         t4_write_reg(adap, SGE_DEBUG_INDEX, 13);
1986         cnt[0] = t4_read_reg(adap, SGE_DEBUG_DATA_HIGH);
1987         cnt[1] = t4_read_reg(adap, SGE_DEBUG_DATA_LOW);
1988
1989         for (i = 0; i < 2; i++)
1990                 if (cnt[i] >= s->starve_thres) {
1991                         if (s->idma_state[i] || cnt[i] == 0xffffffff)
1992                                 continue;
1993                         s->idma_state[i] = 1;
1994                         t4_write_reg(adap, SGE_DEBUG_INDEX, 11);
1995                         m = t4_read_reg(adap, SGE_DEBUG_DATA_LOW) >> (i * 16);
1996                         dev_warn(adap->pdev_dev,
1997                                  "SGE idma%u starvation detected for "
1998                                  "queue %lu\n", i, m & 0xffff);
1999                 } else if (s->idma_state[i])
2000                         s->idma_state[i] = 0;
2001
2002         mod_timer(&s->rx_timer, jiffies + RX_QCHECK_PERIOD);
2003 }
2004
2005 static void sge_tx_timer_cb(unsigned long data)
2006 {
2007         unsigned long m;
2008         unsigned int i, budget;
2009         struct adapter *adap = (struct adapter *)data;
2010         struct sge *s = &adap->sge;
2011
2012         for (i = 0; i < ARRAY_SIZE(s->txq_maperr); i++)
2013                 for (m = s->txq_maperr[i]; m; m &= m - 1) {
2014                         unsigned long id = __ffs(m) + i * BITS_PER_LONG;
2015                         struct sge_ofld_txq *txq = s->egr_map[id];
2016
2017                         clear_bit(id, s->txq_maperr);
2018                         tasklet_schedule(&txq->qresume_tsk);
2019                 }
2020
2021         budget = MAX_TIMER_TX_RECLAIM;
2022         i = s->ethtxq_rover;
2023         do {
2024                 struct sge_eth_txq *q = &s->ethtxq[i];
2025
2026                 if (q->q.in_use &&
2027                     time_after_eq(jiffies, q->txq->trans_start + HZ / 100) &&
2028                     __netif_tx_trylock(q->txq)) {
2029                         int avail = reclaimable(&q->q);
2030
2031                         if (avail) {
2032                                 if (avail > budget)
2033                                         avail = budget;
2034
2035                                 free_tx_desc(adap, &q->q, avail, true);
2036                                 q->q.in_use -= avail;
2037                                 budget -= avail;
2038                         }
2039                         __netif_tx_unlock(q->txq);
2040                 }
2041
2042                 if (++i >= s->ethqsets)
2043                         i = 0;
2044         } while (budget && i != s->ethtxq_rover);
2045         s->ethtxq_rover = i;
2046         mod_timer(&s->tx_timer, jiffies + (budget ? TX_QCHECK_PERIOD : 2));
2047 }
2048
2049 int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
2050                      struct net_device *dev, int intr_idx,
2051                      struct sge_fl *fl, rspq_handler_t hnd)
2052 {
2053         int ret, flsz = 0;
2054         struct fw_iq_cmd c;
2055         struct sge *s = &adap->sge;
2056         struct port_info *pi = netdev_priv(dev);
2057
2058         /* Size needs to be multiple of 16, including status entry. */
2059         iq->size = roundup(iq->size, 16);
2060
2061         iq->desc = alloc_ring(adap->pdev_dev, iq->size, iq->iqe_len, 0,
2062                               &iq->phys_addr, NULL, 0, NUMA_NO_NODE);
2063         if (!iq->desc)
2064                 return -ENOMEM;
2065
2066         memset(&c, 0, sizeof(c));
2067         c.op_to_vfn = htonl(FW_CMD_OP(FW_IQ_CMD) | FW_CMD_REQUEST |
2068                             FW_CMD_WRITE | FW_CMD_EXEC |
2069                             FW_IQ_CMD_PFN(adap->fn) | FW_IQ_CMD_VFN(0));
2070         c.alloc_to_len16 = htonl(FW_IQ_CMD_ALLOC | FW_IQ_CMD_IQSTART(1) |
2071                                  FW_LEN16(c));
2072         c.type_to_iqandstindex = htonl(FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
2073                 FW_IQ_CMD_IQASYNCH(fwevtq) | FW_IQ_CMD_VIID(pi->viid) |
2074                 FW_IQ_CMD_IQANDST(intr_idx < 0) | FW_IQ_CMD_IQANUD(1) |
2075                 FW_IQ_CMD_IQANDSTINDEX(intr_idx >= 0 ? intr_idx :
2076                                                         -intr_idx - 1));
2077         c.iqdroprss_to_iqesize = htons(FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
2078                 FW_IQ_CMD_IQGTSMODE |
2079                 FW_IQ_CMD_IQINTCNTTHRESH(iq->pktcnt_idx) |
2080                 FW_IQ_CMD_IQESIZE(ilog2(iq->iqe_len) - 4));
2081         c.iqsize = htons(iq->size);
2082         c.iqaddr = cpu_to_be64(iq->phys_addr);
2083
2084         if (fl) {
2085                 fl->size = roundup(fl->size, 8);
2086                 fl->desc = alloc_ring(adap->pdev_dev, fl->size, sizeof(__be64),
2087                                       sizeof(struct rx_sw_desc), &fl->addr,
2088                                       &fl->sdesc, s->stat_len, NUMA_NO_NODE);
2089                 if (!fl->desc)
2090                         goto fl_nomem;
2091
2092                 flsz = fl->size / 8 + s->stat_len / sizeof(struct tx_desc);
2093                 c.iqns_to_fl0congen = htonl(FW_IQ_CMD_FL0PACKEN(1) |
2094                                             FW_IQ_CMD_FL0FETCHRO(1) |
2095                                             FW_IQ_CMD_FL0DATARO(1) |
2096                                             FW_IQ_CMD_FL0PADEN(1));
2097                 c.fl0dcaen_to_fl0cidxfthresh = htons(FW_IQ_CMD_FL0FBMIN(2) |
2098                                 FW_IQ_CMD_FL0FBMAX(3));
2099                 c.fl0size = htons(flsz);
2100                 c.fl0addr = cpu_to_be64(fl->addr);
2101         }
2102
2103         ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
2104         if (ret)
2105                 goto err;
2106
2107         netif_napi_add(dev, &iq->napi, napi_rx_handler, 64);
2108         iq->cur_desc = iq->desc;
2109         iq->cidx = 0;
2110         iq->gen = 1;
2111         iq->next_intr_params = iq->intr_params;
2112         iq->cntxt_id = ntohs(c.iqid);
2113         iq->abs_id = ntohs(c.physiqid);
2114         iq->size--;                           /* subtract status entry */
2115         iq->adap = adap;
2116         iq->netdev = dev;
2117         iq->handler = hnd;
2118
2119         /* set offset to -1 to distinguish ingress queues without FL */
2120         iq->offset = fl ? 0 : -1;
2121
2122         adap->sge.ingr_map[iq->cntxt_id - adap->sge.ingr_start] = iq;
2123
2124         if (fl) {
2125                 fl->cntxt_id = ntohs(c.fl0id);
2126                 fl->avail = fl->pend_cred = 0;
2127                 fl->pidx = fl->cidx = 0;
2128                 fl->alloc_failed = fl->large_alloc_failed = fl->starving = 0;
2129                 adap->sge.egr_map[fl->cntxt_id - adap->sge.egr_start] = fl;
2130                 refill_fl(adap, fl, fl_cap(fl), GFP_KERNEL);
2131         }
2132         return 0;
2133
2134 fl_nomem:
2135         ret = -ENOMEM;
2136 err:
2137         if (iq->desc) {
2138                 dma_free_coherent(adap->pdev_dev, iq->size * iq->iqe_len,
2139                                   iq->desc, iq->phys_addr);
2140                 iq->desc = NULL;
2141         }
2142         if (fl && fl->desc) {
2143                 kfree(fl->sdesc);
2144                 fl->sdesc = NULL;
2145                 dma_free_coherent(adap->pdev_dev, flsz * sizeof(struct tx_desc),
2146                                   fl->desc, fl->addr);
2147                 fl->desc = NULL;
2148         }
2149         return ret;
2150 }
2151
2152 static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id)
2153 {
2154         q->in_use = 0;
2155         q->cidx = q->pidx = 0;
2156         q->stops = q->restarts = 0;
2157         q->stat = (void *)&q->desc[q->size];
2158         q->cntxt_id = id;
2159         spin_lock_init(&q->db_lock);
2160         adap->sge.egr_map[id - adap->sge.egr_start] = q;
2161 }
2162
2163 int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
2164                          struct net_device *dev, struct netdev_queue *netdevq,
2165                          unsigned int iqid)
2166 {
2167         int ret, nentries;
2168         struct fw_eq_eth_cmd c;
2169         struct sge *s = &adap->sge;
2170         struct port_info *pi = netdev_priv(dev);
2171
2172         /* Add status entries */
2173         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2174
2175         txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
2176                         sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
2177                         &txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
2178                         netdev_queue_numa_node_read(netdevq));
2179         if (!txq->q.desc)
2180                 return -ENOMEM;
2181
2182         memset(&c, 0, sizeof(c));
2183         c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_ETH_CMD) | FW_CMD_REQUEST |
2184                             FW_CMD_WRITE | FW_CMD_EXEC |
2185                             FW_EQ_ETH_CMD_PFN(adap->fn) | FW_EQ_ETH_CMD_VFN(0));
2186         c.alloc_to_len16 = htonl(FW_EQ_ETH_CMD_ALLOC |
2187                                  FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
2188         c.viid_pkd = htonl(FW_EQ_ETH_CMD_VIID(pi->viid));
2189         c.fetchszm_to_iqid = htonl(FW_EQ_ETH_CMD_HOSTFCMODE(2) |
2190                                    FW_EQ_ETH_CMD_PCIECHN(pi->tx_chan) |
2191                                    FW_EQ_ETH_CMD_FETCHRO(1) |
2192                                    FW_EQ_ETH_CMD_IQID(iqid));
2193         c.dcaen_to_eqsize = htonl(FW_EQ_ETH_CMD_FBMIN(2) |
2194                                   FW_EQ_ETH_CMD_FBMAX(3) |
2195                                   FW_EQ_ETH_CMD_CIDXFTHRESH(5) |
2196                                   FW_EQ_ETH_CMD_EQSIZE(nentries));
2197         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
2198
2199         ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
2200         if (ret) {
2201                 kfree(txq->q.sdesc);
2202                 txq->q.sdesc = NULL;
2203                 dma_free_coherent(adap->pdev_dev,
2204                                   nentries * sizeof(struct tx_desc),
2205                                   txq->q.desc, txq->q.phys_addr);
2206                 txq->q.desc = NULL;
2207                 return ret;
2208         }
2209
2210         init_txq(adap, &txq->q, FW_EQ_ETH_CMD_EQID_GET(ntohl(c.eqid_pkd)));
2211         txq->txq = netdevq;
2212         txq->tso = txq->tx_cso = txq->vlan_ins = 0;
2213         txq->mapping_err = 0;
2214         return 0;
2215 }
2216
2217 int t4_sge_alloc_ctrl_txq(struct adapter *adap, struct sge_ctrl_txq *txq,
2218                           struct net_device *dev, unsigned int iqid,
2219                           unsigned int cmplqid)
2220 {
2221         int ret, nentries;
2222         struct fw_eq_ctrl_cmd c;
2223         struct sge *s = &adap->sge;
2224         struct port_info *pi = netdev_priv(dev);
2225
2226         /* Add status entries */
2227         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2228
2229         txq->q.desc = alloc_ring(adap->pdev_dev, nentries,
2230                                  sizeof(struct tx_desc), 0, &txq->q.phys_addr,
2231                                  NULL, 0, NUMA_NO_NODE);
2232         if (!txq->q.desc)
2233                 return -ENOMEM;
2234
2235         c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_CTRL_CMD) | FW_CMD_REQUEST |
2236                             FW_CMD_WRITE | FW_CMD_EXEC |
2237                             FW_EQ_CTRL_CMD_PFN(adap->fn) |
2238                             FW_EQ_CTRL_CMD_VFN(0));
2239         c.alloc_to_len16 = htonl(FW_EQ_CTRL_CMD_ALLOC |
2240                                  FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
2241         c.cmpliqid_eqid = htonl(FW_EQ_CTRL_CMD_CMPLIQID(cmplqid));
2242         c.physeqid_pkd = htonl(0);
2243         c.fetchszm_to_iqid = htonl(FW_EQ_CTRL_CMD_HOSTFCMODE(2) |
2244                                    FW_EQ_CTRL_CMD_PCIECHN(pi->tx_chan) |
2245                                    FW_EQ_CTRL_CMD_FETCHRO |
2246                                    FW_EQ_CTRL_CMD_IQID(iqid));
2247         c.dcaen_to_eqsize = htonl(FW_EQ_CTRL_CMD_FBMIN(2) |
2248                                   FW_EQ_CTRL_CMD_FBMAX(3) |
2249                                   FW_EQ_CTRL_CMD_CIDXFTHRESH(5) |
2250                                   FW_EQ_CTRL_CMD_EQSIZE(nentries));
2251         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
2252
2253         ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
2254         if (ret) {
2255                 dma_free_coherent(adap->pdev_dev,
2256                                   nentries * sizeof(struct tx_desc),
2257                                   txq->q.desc, txq->q.phys_addr);
2258                 txq->q.desc = NULL;
2259                 return ret;
2260         }
2261
2262         init_txq(adap, &txq->q, FW_EQ_CTRL_CMD_EQID_GET(ntohl(c.cmpliqid_eqid)));
2263         txq->adap = adap;
2264         skb_queue_head_init(&txq->sendq);
2265         tasklet_init(&txq->qresume_tsk, restart_ctrlq, (unsigned long)txq);
2266         txq->full = 0;
2267         return 0;
2268 }
2269
2270 int t4_sge_alloc_ofld_txq(struct adapter *adap, struct sge_ofld_txq *txq,
2271                           struct net_device *dev, unsigned int iqid)
2272 {
2273         int ret, nentries;
2274         struct fw_eq_ofld_cmd c;
2275         struct sge *s = &adap->sge;
2276         struct port_info *pi = netdev_priv(dev);
2277
2278         /* Add status entries */
2279         nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2280
2281         txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
2282                         sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
2283                         &txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
2284                         NUMA_NO_NODE);
2285         if (!txq->q.desc)
2286                 return -ENOMEM;
2287
2288         memset(&c, 0, sizeof(c));
2289         c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_OFLD_CMD) | FW_CMD_REQUEST |
2290                             FW_CMD_WRITE | FW_CMD_EXEC |
2291                             FW_EQ_OFLD_CMD_PFN(adap->fn) |
2292                             FW_EQ_OFLD_CMD_VFN(0));
2293         c.alloc_to_len16 = htonl(FW_EQ_OFLD_CMD_ALLOC |
2294                                  FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
2295         c.fetchszm_to_iqid = htonl(FW_EQ_OFLD_CMD_HOSTFCMODE(2) |
2296                                    FW_EQ_OFLD_CMD_PCIECHN(pi->tx_chan) |
2297                                    FW_EQ_OFLD_CMD_FETCHRO(1) |
2298                                    FW_EQ_OFLD_CMD_IQID(iqid));
2299         c.dcaen_to_eqsize = htonl(FW_EQ_OFLD_CMD_FBMIN(2) |
2300                                   FW_EQ_OFLD_CMD_FBMAX(3) |
2301                                   FW_EQ_OFLD_CMD_CIDXFTHRESH(5) |
2302                                   FW_EQ_OFLD_CMD_EQSIZE(nentries));
2303         c.eqaddr = cpu_to_be64(txq->q.phys_addr);
2304
2305         ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
2306         if (ret) {
2307                 kfree(txq->q.sdesc);
2308                 txq->q.sdesc = NULL;
2309                 dma_free_coherent(adap->pdev_dev,
2310                                   nentries * sizeof(struct tx_desc),
2311                                   txq->q.desc, txq->q.phys_addr);
2312                 txq->q.desc = NULL;
2313                 return ret;
2314         }
2315
2316         init_txq(adap, &txq->q, FW_EQ_OFLD_CMD_EQID_GET(ntohl(c.eqid_pkd)));
2317         txq->adap = adap;
2318         skb_queue_head_init(&txq->sendq);
2319         tasklet_init(&txq->qresume_tsk, restart_ofldq, (unsigned long)txq);
2320         txq->full = 0;
2321         txq->mapping_err = 0;
2322         return 0;
2323 }
2324
2325 static void free_txq(struct adapter *adap, struct sge_txq *q)
2326 {
2327         struct sge *s = &adap->sge;
2328
2329         dma_free_coherent(adap->pdev_dev,
2330                           q->size * sizeof(struct tx_desc) + s->stat_len,
2331                           q->desc, q->phys_addr);
2332         q->cntxt_id = 0;
2333         q->sdesc = NULL;
2334         q->desc = NULL;
2335 }
2336
2337 static void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
2338                          struct sge_fl *fl)
2339 {
2340         struct sge *s = &adap->sge;
2341         unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
2342
2343         adap->sge.ingr_map[rq->cntxt_id - adap->sge.ingr_start] = NULL;
2344         t4_iq_free(adap, adap->fn, adap->fn, 0, FW_IQ_TYPE_FL_INT_CAP,
2345                    rq->cntxt_id, fl_id, 0xffff);
2346         dma_free_coherent(adap->pdev_dev, (rq->size + 1) * rq->iqe_len,
2347                           rq->desc, rq->phys_addr);
2348         netif_napi_del(&rq->napi);
2349         rq->netdev = NULL;
2350         rq->cntxt_id = rq->abs_id = 0;
2351         rq->desc = NULL;
2352
2353         if (fl) {
2354                 free_rx_bufs(adap, fl, fl->avail);
2355                 dma_free_coherent(adap->pdev_dev, fl->size * 8 + s->stat_len,
2356                                   fl->desc, fl->addr);
2357                 kfree(fl->sdesc);
2358                 fl->sdesc = NULL;
2359                 fl->cntxt_id = 0;
2360                 fl->desc = NULL;
2361         }
2362 }
2363
2364 /**
2365  *      t4_free_sge_resources - free SGE resources
2366  *      @adap: the adapter
2367  *
2368  *      Frees resources used by the SGE queue sets.
2369  */
2370 void t4_free_sge_resources(struct adapter *adap)
2371 {
2372         int i;
2373         struct sge_eth_rxq *eq = adap->sge.ethrxq;
2374         struct sge_eth_txq *etq = adap->sge.ethtxq;
2375         struct sge_ofld_rxq *oq = adap->sge.ofldrxq;
2376
2377         /* clean up Ethernet Tx/Rx queues */
2378         for (i = 0; i < adap->sge.ethqsets; i++, eq++, etq++) {
2379                 if (eq->rspq.desc)
2380                         free_rspq_fl(adap, &eq->rspq, &eq->fl);
2381                 if (etq->q.desc) {
2382                         t4_eth_eq_free(adap, adap->fn, adap->fn, 0,
2383                                        etq->q.cntxt_id);
2384                         free_tx_desc(adap, &etq->q, etq->q.in_use, true);
2385                         kfree(etq->q.sdesc);
2386                         free_txq(adap, &etq->q);
2387                 }
2388         }
2389
2390         /* clean up RDMA and iSCSI Rx queues */
2391         for (i = 0; i < adap->sge.ofldqsets; i++, oq++) {
2392                 if (oq->rspq.desc)
2393                         free_rspq_fl(adap, &oq->rspq, &oq->fl);
2394         }
2395         for (i = 0, oq = adap->sge.rdmarxq; i < adap->sge.rdmaqs; i++, oq++) {
2396                 if (oq->rspq.desc)
2397                         free_rspq_fl(adap, &oq->rspq, &oq->fl);
2398         }
2399
2400         /* clean up offload Tx queues */
2401         for (i = 0; i < ARRAY_SIZE(adap->sge.ofldtxq); i++) {
2402                 struct sge_ofld_txq *q = &adap->sge.ofldtxq[i];
2403
2404                 if (q->q.desc) {
2405                         tasklet_kill(&q->qresume_tsk);
2406                         t4_ofld_eq_free(adap, adap->fn, adap->fn, 0,
2407                                         q->q.cntxt_id);
2408                         free_tx_desc(adap, &q->q, q->q.in_use, false);
2409                         kfree(q->q.sdesc);
2410                         __skb_queue_purge(&q->sendq);
2411                         free_txq(adap, &q->q);
2412                 }
2413         }
2414
2415         /* clean up control Tx queues */
2416         for (i = 0; i < ARRAY_SIZE(adap->sge.ctrlq); i++) {
2417                 struct sge_ctrl_txq *cq = &adap->sge.ctrlq[i];
2418
2419                 if (cq->q.desc) {
2420                         tasklet_kill(&cq->qresume_tsk);
2421                         t4_ctrl_eq_free(adap, adap->fn, adap->fn, 0,
2422                                         cq->q.cntxt_id);
2423                         __skb_queue_purge(&cq->sendq);
2424                         free_txq(adap, &cq->q);
2425                 }
2426         }
2427
2428         if (adap->sge.fw_evtq.desc)
2429                 free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
2430
2431         if (adap->sge.intrq.desc)
2432                 free_rspq_fl(adap, &adap->sge.intrq, NULL);
2433
2434         /* clear the reverse egress queue map */
2435         memset(adap->sge.egr_map, 0, sizeof(adap->sge.egr_map));
2436 }
2437
2438 void t4_sge_start(struct adapter *adap)
2439 {
2440         adap->sge.ethtxq_rover = 0;
2441         mod_timer(&adap->sge.rx_timer, jiffies + RX_QCHECK_PERIOD);
2442         mod_timer(&adap->sge.tx_timer, jiffies + TX_QCHECK_PERIOD);
2443 }
2444
2445 /**
2446  *      t4_sge_stop - disable SGE operation
2447  *      @adap: the adapter
2448  *
2449  *      Stop tasklets and timers associated with the DMA engine.  Note that
2450  *      this is effective only if measures have been taken to disable any HW
2451  *      events that may restart them.
2452  */
2453 void t4_sge_stop(struct adapter *adap)
2454 {
2455         int i;
2456         struct sge *s = &adap->sge;
2457
2458         if (in_interrupt())  /* actions below require waiting */
2459                 return;
2460
2461         if (s->rx_timer.function)
2462                 del_timer_sync(&s->rx_timer);
2463         if (s->tx_timer.function)
2464                 del_timer_sync(&s->tx_timer);
2465
2466         for (i = 0; i < ARRAY_SIZE(s->ofldtxq); i++) {
2467                 struct sge_ofld_txq *q = &s->ofldtxq[i];
2468
2469                 if (q->q.desc)
2470                         tasklet_kill(&q->qresume_tsk);
2471         }
2472         for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++) {
2473                 struct sge_ctrl_txq *cq = &s->ctrlq[i];
2474
2475                 if (cq->q.desc)
2476                         tasklet_kill(&cq->qresume_tsk);
2477         }
2478 }
2479
2480 /**
2481  *      t4_sge_init - initialize SGE
2482  *      @adap: the adapter
2483  *
2484  *      Performs SGE initialization needed every time after a chip reset.
2485  *      We do not initialize any of the queues here, instead the driver
2486  *      top-level must request them individually.
2487  *
2488  *      Called in two different modes:
2489  *
2490  *       1. Perform actual hardware initialization and record hard-coded
2491  *          parameters which were used.  This gets used when we're the
2492  *          Master PF and the Firmware Configuration File support didn't
2493  *          work for some reason.
2494  *
2495  *       2. We're not the Master PF or initialization was performed with
2496  *          a Firmware Configuration File.  In this case we need to grab
2497  *          any of the SGE operating parameters that we need to have in
2498  *          order to do our job and make sure we can live with them ...
2499  */
2500
2501 static int t4_sge_init_soft(struct adapter *adap)
2502 {
2503         struct sge *s = &adap->sge;
2504         u32 fl_small_pg, fl_large_pg, fl_small_mtu, fl_large_mtu;
2505         u32 timer_value_0_and_1, timer_value_2_and_3, timer_value_4_and_5;
2506         u32 ingress_rx_threshold;
2507
2508         /*
2509          * Verify that CPL messages are going to the Ingress Queue for
2510          * process_responses() and that only packet data is going to the
2511          * Free Lists.
2512          */
2513         if ((t4_read_reg(adap, SGE_CONTROL) & RXPKTCPLMODE_MASK) !=
2514             RXPKTCPLMODE(X_RXPKTCPLMODE_SPLIT)) {
2515                 dev_err(adap->pdev_dev, "bad SGE CPL MODE\n");
2516                 return -EINVAL;
2517         }
2518
2519         /*
2520          * Validate the Host Buffer Register Array indices that we want to
2521          * use ...
2522          *
2523          * XXX Note that we should really read through the Host Buffer Size
2524          * XXX register array and find the indices of the Buffer Sizes which
2525          * XXX meet our needs!
2526          */
2527         #define READ_FL_BUF(x) \
2528                 t4_read_reg(adap, SGE_FL_BUFFER_SIZE0+(x)*sizeof(u32))
2529
2530         fl_small_pg = READ_FL_BUF(RX_SMALL_PG_BUF);
2531         fl_large_pg = READ_FL_BUF(RX_LARGE_PG_BUF);
2532         fl_small_mtu = READ_FL_BUF(RX_SMALL_MTU_BUF);
2533         fl_large_mtu = READ_FL_BUF(RX_LARGE_MTU_BUF);
2534
2535         #undef READ_FL_BUF
2536
2537         if (fl_small_pg != PAGE_SIZE ||
2538             (fl_large_pg != 0 && (fl_large_pg <= fl_small_pg ||
2539                                   (fl_large_pg & (fl_large_pg-1)) != 0))) {
2540                 dev_err(adap->pdev_dev, "bad SGE FL page buffer sizes [%d, %d]\n",
2541                         fl_small_pg, fl_large_pg);
2542                 return -EINVAL;
2543         }
2544         if (fl_large_pg)
2545                 s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
2546
2547         if (fl_small_mtu < FL_MTU_SMALL_BUFSIZE(adap) ||
2548             fl_large_mtu < FL_MTU_LARGE_BUFSIZE(adap)) {
2549                 dev_err(adap->pdev_dev, "bad SGE FL MTU sizes [%d, %d]\n",
2550                         fl_small_mtu, fl_large_mtu);
2551                 return -EINVAL;
2552         }
2553
2554         /*
2555          * Retrieve our RX interrupt holdoff timer values and counter
2556          * threshold values from the SGE parameters.
2557          */
2558         timer_value_0_and_1 = t4_read_reg(adap, SGE_TIMER_VALUE_0_AND_1);
2559         timer_value_2_and_3 = t4_read_reg(adap, SGE_TIMER_VALUE_2_AND_3);
2560         timer_value_4_and_5 = t4_read_reg(adap, SGE_TIMER_VALUE_4_AND_5);
2561         s->timer_val[0] = core_ticks_to_us(adap,
2562                 TIMERVALUE0_GET(timer_value_0_and_1));
2563         s->timer_val[1] = core_ticks_to_us(adap,
2564                 TIMERVALUE1_GET(timer_value_0_and_1));
2565         s->timer_val[2] = core_ticks_to_us(adap,
2566                 TIMERVALUE2_GET(timer_value_2_and_3));
2567         s->timer_val[3] = core_ticks_to_us(adap,
2568                 TIMERVALUE3_GET(timer_value_2_and_3));
2569         s->timer_val[4] = core_ticks_to_us(adap,
2570                 TIMERVALUE4_GET(timer_value_4_and_5));
2571         s->timer_val[5] = core_ticks_to_us(adap,
2572                 TIMERVALUE5_GET(timer_value_4_and_5));
2573
2574         ingress_rx_threshold = t4_read_reg(adap, SGE_INGRESS_RX_THRESHOLD);
2575         s->counter_val[0] = THRESHOLD_0_GET(ingress_rx_threshold);
2576         s->counter_val[1] = THRESHOLD_1_GET(ingress_rx_threshold);
2577         s->counter_val[2] = THRESHOLD_2_GET(ingress_rx_threshold);
2578         s->counter_val[3] = THRESHOLD_3_GET(ingress_rx_threshold);
2579
2580         return 0;
2581 }
2582
2583 static int t4_sge_init_hard(struct adapter *adap)
2584 {
2585         struct sge *s = &adap->sge;
2586
2587         /*
2588          * Set up our basic SGE mode to deliver CPL messages to our Ingress
2589          * Queue and Packet Date to the Free List.
2590          */
2591         t4_set_reg_field(adap, SGE_CONTROL, RXPKTCPLMODE_MASK,
2592                          RXPKTCPLMODE_MASK);
2593
2594         /*
2595          * Set up to drop DOORBELL writes when the DOORBELL FIFO overflows
2596          * and generate an interrupt when this occurs so we can recover.
2597          */
2598         if (is_t4(adap->chip)) {
2599                 t4_set_reg_field(adap, A_SGE_DBFIFO_STATUS,
2600                                  V_HP_INT_THRESH(M_HP_INT_THRESH) |
2601                                  V_LP_INT_THRESH(M_LP_INT_THRESH),
2602                                  V_HP_INT_THRESH(dbfifo_int_thresh) |
2603                                  V_LP_INT_THRESH(dbfifo_int_thresh));
2604         } else {
2605                 t4_set_reg_field(adap, A_SGE_DBFIFO_STATUS,
2606                                  V_LP_INT_THRESH_T5(M_LP_INT_THRESH_T5),
2607                                  V_LP_INT_THRESH_T5(dbfifo_int_thresh));
2608                 t4_set_reg_field(adap, SGE_DBFIFO_STATUS2,
2609                                  V_HP_INT_THRESH_T5(M_HP_INT_THRESH_T5),
2610                                  V_HP_INT_THRESH_T5(dbfifo_int_thresh));
2611         }
2612         t4_set_reg_field(adap, A_SGE_DOORBELL_CONTROL, F_ENABLE_DROP,
2613                         F_ENABLE_DROP);
2614
2615         /*
2616          * SGE_FL_BUFFER_SIZE0 (RX_SMALL_PG_BUF) is set up by
2617          * t4_fixup_host_params().
2618          */
2619         s->fl_pg_order = FL_PG_ORDER;
2620         if (s->fl_pg_order)
2621                 t4_write_reg(adap,
2622                              SGE_FL_BUFFER_SIZE0+RX_LARGE_PG_BUF*sizeof(u32),
2623                              PAGE_SIZE << FL_PG_ORDER);
2624         t4_write_reg(adap, SGE_FL_BUFFER_SIZE0+RX_SMALL_MTU_BUF*sizeof(u32),
2625                      FL_MTU_SMALL_BUFSIZE(adap));
2626         t4_write_reg(adap, SGE_FL_BUFFER_SIZE0+RX_LARGE_MTU_BUF*sizeof(u32),
2627                      FL_MTU_LARGE_BUFSIZE(adap));
2628
2629         /*
2630          * Note that the SGE Ingress Packet Count Interrupt Threshold and
2631          * Timer Holdoff values must be supplied by our caller.
2632          */
2633         t4_write_reg(adap, SGE_INGRESS_RX_THRESHOLD,
2634                      THRESHOLD_0(s->counter_val[0]) |
2635                      THRESHOLD_1(s->counter_val[1]) |
2636                      THRESHOLD_2(s->counter_val[2]) |
2637                      THRESHOLD_3(s->counter_val[3]));
2638         t4_write_reg(adap, SGE_TIMER_VALUE_0_AND_1,
2639                      TIMERVALUE0(us_to_core_ticks(adap, s->timer_val[0])) |
2640                      TIMERVALUE1(us_to_core_ticks(adap, s->timer_val[1])));
2641         t4_write_reg(adap, SGE_TIMER_VALUE_2_AND_3,
2642                      TIMERVALUE2(us_to_core_ticks(adap, s->timer_val[2])) |
2643                      TIMERVALUE3(us_to_core_ticks(adap, s->timer_val[3])));
2644         t4_write_reg(adap, SGE_TIMER_VALUE_4_AND_5,
2645                      TIMERVALUE4(us_to_core_ticks(adap, s->timer_val[4])) |
2646                      TIMERVALUE5(us_to_core_ticks(adap, s->timer_val[5])));
2647
2648         return 0;
2649 }
2650
2651 int t4_sge_init(struct adapter *adap)
2652 {
2653         struct sge *s = &adap->sge;
2654         u32 sge_control;
2655         int ret;
2656
2657         /*
2658          * Ingress Padding Boundary and Egress Status Page Size are set up by
2659          * t4_fixup_host_params().
2660          */
2661         sge_control = t4_read_reg(adap, SGE_CONTROL);
2662         s->pktshift = PKTSHIFT_GET(sge_control);
2663         s->stat_len = (sge_control & EGRSTATUSPAGESIZE_MASK) ? 128 : 64;
2664         s->fl_align = 1 << (INGPADBOUNDARY_GET(sge_control) +
2665                             X_INGPADBOUNDARY_SHIFT);
2666
2667         if (adap->flags & USING_SOFT_PARAMS)
2668                 ret = t4_sge_init_soft(adap);
2669         else
2670                 ret = t4_sge_init_hard(adap);
2671         if (ret < 0)
2672                 return ret;
2673
2674         /*
2675          * A FL with <= fl_starve_thres buffers is starving and a periodic
2676          * timer will attempt to refill it.  This needs to be larger than the
2677          * SGE's Egress Congestion Threshold.  If it isn't, then we can get
2678          * stuck waiting for new packets while the SGE is waiting for us to
2679          * give it more Free List entries.  (Note that the SGE's Egress
2680          * Congestion Threshold is in units of 2 Free List pointers.)
2681          */
2682         s->fl_starve_thres
2683                 = EGRTHRESHOLD_GET(t4_read_reg(adap, SGE_CONM_CTRL))*2 + 1;
2684
2685         setup_timer(&s->rx_timer, sge_rx_timer_cb, (unsigned long)adap);
2686         setup_timer(&s->tx_timer, sge_tx_timer_cb, (unsigned long)adap);
2687         s->starve_thres = core_ticks_per_usec(adap) * 1000000;  /* 1 s */
2688         s->idma_state[0] = s->idma_state[1] = 0;
2689         spin_lock_init(&s->intrq_lock);
2690
2691         return 0;
2692 }