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