linux/drivers/net/wireless/broadcom/brcm80211/brcmfmac/sdio.c
<<
>>
Prefs
   1/*
   2 * Copyright (c) 2010 Broadcom Corporation
   3 *
   4 * Permission to use, copy, modify, and/or distribute this software for any
   5 * purpose with or without fee is hereby granted, provided that the above
   6 * copyright notice and this permission notice appear in all copies.
   7 *
   8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  11 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  13 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  14 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15 */
  16
  17#include <linux/types.h>
  18#include <linux/atomic.h>
  19#include <linux/kernel.h>
  20#include <linux/kthread.h>
  21#include <linux/printk.h>
  22#include <linux/pci_ids.h>
  23#include <linux/netdevice.h>
  24#include <linux/interrupt.h>
  25#include <linux/sched/signal.h>
  26#include <linux/mmc/sdio.h>
  27#include <linux/mmc/sdio_ids.h>
  28#include <linux/mmc/sdio_func.h>
  29#include <linux/mmc/card.h>
  30#include <linux/semaphore.h>
  31#include <linux/firmware.h>
  32#include <linux/module.h>
  33#include <linux/bcma/bcma.h>
  34#include <linux/debugfs.h>
  35#include <linux/vmalloc.h>
  36#include <asm/unaligned.h>
  37#include <defs.h>
  38#include <brcmu_wifi.h>
  39#include <brcmu_utils.h>
  40#include <brcm_hw_ids.h>
  41#include <soc.h>
  42#include "sdio.h"
  43#include "chip.h"
  44#include "firmware.h"
  45#include "core.h"
  46#include "common.h"
  47#include "bcdc.h"
  48
  49#define DCMD_RESP_TIMEOUT       msecs_to_jiffies(2500)
  50#define CTL_DONE_TIMEOUT        msecs_to_jiffies(2500)
  51
  52#ifdef DEBUG
  53
  54#define BRCMF_TRAP_INFO_SIZE    80
  55
  56#define CBUF_LEN        (128)
  57
  58/* Device console log buffer state */
  59#define CONSOLE_BUFFER_MAX      2024
  60
  61struct rte_log_le {
  62        __le32 buf;             /* Can't be pointer on (64-bit) hosts */
  63        __le32 buf_size;
  64        __le32 idx;
  65        char *_buf_compat;      /* Redundant pointer for backward compat. */
  66};
  67
  68struct rte_console {
  69        /* Virtual UART
  70         * When there is no UART (e.g. Quickturn),
  71         * the host should write a complete
  72         * input line directly into cbuf and then write
  73         * the length into vcons_in.
  74         * This may also be used when there is a real UART
  75         * (at risk of conflicting with
  76         * the real UART).  vcons_out is currently unused.
  77         */
  78        uint vcons_in;
  79        uint vcons_out;
  80
  81        /* Output (logging) buffer
  82         * Console output is written to a ring buffer log_buf at index log_idx.
  83         * The host may read the output when it sees log_idx advance.
  84         * Output will be lost if the output wraps around faster than the host
  85         * polls.
  86         */
  87        struct rte_log_le log_le;
  88
  89        /* Console input line buffer
  90         * Characters are read one at a time into cbuf
  91         * until <CR> is received, then
  92         * the buffer is processed as a command line.
  93         * Also used for virtual UART.
  94         */
  95        uint cbuf_idx;
  96        char cbuf[CBUF_LEN];
  97};
  98
  99#endif                          /* DEBUG */
 100#include <chipcommon.h>
 101
 102#include "bus.h"
 103#include "debug.h"
 104#include "tracepoint.h"
 105
 106#define TXQLEN          2048    /* bulk tx queue length */
 107#define TXHI            (TXQLEN - 256)  /* turn on flow control above TXHI */
 108#define TXLOW           (TXHI - 256)    /* turn off flow control below TXLOW */
 109#define PRIOMASK        7
 110
 111#define TXRETRIES       2       /* # of retries for tx frames */
 112
 113#define BRCMF_RXBOUND   50      /* Default for max rx frames in
 114                                 one scheduling */
 115
 116#define BRCMF_TXBOUND   20      /* Default for max tx frames in
 117                                 one scheduling */
 118
 119#define BRCMF_TXMINMAX  1       /* Max tx frames if rx still pending */
 120
 121#define MEMBLOCK        2048    /* Block size used for downloading
 122                                 of dongle image */
 123#define MAX_DATA_BUF    (32 * 1024)     /* Must be large enough to hold
 124                                 biggest possible glom */
 125
 126#define BRCMF_FIRSTREAD (1 << 6)
 127
 128#define BRCMF_CONSOLE   10      /* watchdog interval to poll console */
 129
 130/* SBSDIO_DEVICE_CTL */
 131
 132/* 1: device will assert busy signal when receiving CMD53 */
 133#define SBSDIO_DEVCTL_SETBUSY           0x01
 134/* 1: assertion of sdio interrupt is synchronous to the sdio clock */
 135#define SBSDIO_DEVCTL_SPI_INTR_SYNC     0x02
 136/* 1: mask all interrupts to host except the chipActive (rev 8) */
 137#define SBSDIO_DEVCTL_CA_INT_ONLY       0x04
 138/* 1: isolate internal sdio signals, put external pads in tri-state; requires
 139 * sdio bus power cycle to clear (rev 9) */
 140#define SBSDIO_DEVCTL_PADS_ISO          0x08
 141/* Force SD->SB reset mapping (rev 11) */
 142#define SBSDIO_DEVCTL_SB_RST_CTL        0x30
 143/*   Determined by CoreControl bit */
 144#define SBSDIO_DEVCTL_RST_CORECTL       0x00
 145/*   Force backplane reset */
 146#define SBSDIO_DEVCTL_RST_BPRESET       0x10
 147/*   Force no backplane reset */
 148#define SBSDIO_DEVCTL_RST_NOBPRESET     0x20
 149
 150/* direct(mapped) cis space */
 151
 152/* MAPPED common CIS address */
 153#define SBSDIO_CIS_BASE_COMMON          0x1000
 154/* maximum bytes in one CIS */
 155#define SBSDIO_CIS_SIZE_LIMIT           0x200
 156/* cis offset addr is < 17 bits */
 157#define SBSDIO_CIS_OFT_ADDR_MASK        0x1FFFF
 158
 159/* manfid tuple length, include tuple, link bytes */
 160#define SBSDIO_CIS_MANFID_TUPLE_LEN     6
 161
 162#define CORE_BUS_REG(base, field) \
 163                (base + offsetof(struct sdpcmd_regs, field))
 164
 165/* SDIO function 1 register CHIPCLKCSR */
 166/* Force ALP request to backplane */
 167#define SBSDIO_FORCE_ALP                0x01
 168/* Force HT request to backplane */
 169#define SBSDIO_FORCE_HT                 0x02
 170/* Force ILP request to backplane */
 171#define SBSDIO_FORCE_ILP                0x04
 172/* Make ALP ready (power up xtal) */
 173#define SBSDIO_ALP_AVAIL_REQ            0x08
 174/* Make HT ready (power up PLL) */
 175#define SBSDIO_HT_AVAIL_REQ             0x10
 176/* Squelch clock requests from HW */
 177#define SBSDIO_FORCE_HW_CLKREQ_OFF      0x20
 178/* Status: ALP is ready */
 179#define SBSDIO_ALP_AVAIL                0x40
 180/* Status: HT is ready */
 181#define SBSDIO_HT_AVAIL                 0x80
 182#define SBSDIO_CSR_MASK                 0x1F
 183#define SBSDIO_AVBITS           (SBSDIO_HT_AVAIL | SBSDIO_ALP_AVAIL)
 184#define SBSDIO_ALPAV(regval)    ((regval) & SBSDIO_AVBITS)
 185#define SBSDIO_HTAV(regval)     (((regval) & SBSDIO_AVBITS) == SBSDIO_AVBITS)
 186#define SBSDIO_ALPONLY(regval)  (SBSDIO_ALPAV(regval) && !SBSDIO_HTAV(regval))
 187#define SBSDIO_CLKAV(regval, alponly) \
 188        (SBSDIO_ALPAV(regval) && (alponly ? 1 : SBSDIO_HTAV(regval)))
 189
 190/* intstatus */
 191#define I_SMB_SW0       (1 << 0)        /* To SB Mail S/W interrupt 0 */
 192#define I_SMB_SW1       (1 << 1)        /* To SB Mail S/W interrupt 1 */
 193#define I_SMB_SW2       (1 << 2)        /* To SB Mail S/W interrupt 2 */
 194#define I_SMB_SW3       (1 << 3)        /* To SB Mail S/W interrupt 3 */
 195#define I_SMB_SW_MASK   0x0000000f      /* To SB Mail S/W interrupts mask */
 196#define I_SMB_SW_SHIFT  0       /* To SB Mail S/W interrupts shift */
 197#define I_HMB_SW0       (1 << 4)        /* To Host Mail S/W interrupt 0 */
 198#define I_HMB_SW1       (1 << 5)        /* To Host Mail S/W interrupt 1 */
 199#define I_HMB_SW2       (1 << 6)        /* To Host Mail S/W interrupt 2 */
 200#define I_HMB_SW3       (1 << 7)        /* To Host Mail S/W interrupt 3 */
 201#define I_HMB_SW_MASK   0x000000f0      /* To Host Mail S/W interrupts mask */
 202#define I_HMB_SW_SHIFT  4       /* To Host Mail S/W interrupts shift */
 203#define I_WR_OOSYNC     (1 << 8)        /* Write Frame Out Of Sync */
 204#define I_RD_OOSYNC     (1 << 9)        /* Read Frame Out Of Sync */
 205#define I_PC            (1 << 10)       /* descriptor error */
 206#define I_PD            (1 << 11)       /* data error */
 207#define I_DE            (1 << 12)       /* Descriptor protocol Error */
 208#define I_RU            (1 << 13)       /* Receive descriptor Underflow */
 209#define I_RO            (1 << 14)       /* Receive fifo Overflow */
 210#define I_XU            (1 << 15)       /* Transmit fifo Underflow */
 211#define I_RI            (1 << 16)       /* Receive Interrupt */
 212#define I_BUSPWR        (1 << 17)       /* SDIO Bus Power Change (rev 9) */
 213#define I_XMTDATA_AVAIL (1 << 23)       /* bits in fifo */
 214#define I_XI            (1 << 24)       /* Transmit Interrupt */
 215#define I_RF_TERM       (1 << 25)       /* Read Frame Terminate */
 216#define I_WF_TERM       (1 << 26)       /* Write Frame Terminate */
 217#define I_PCMCIA_XU     (1 << 27)       /* PCMCIA Transmit FIFO Underflow */
 218#define I_SBINT         (1 << 28)       /* sbintstatus Interrupt */
 219#define I_CHIPACTIVE    (1 << 29)       /* chip from doze to active state */
 220#define I_SRESET        (1 << 30)       /* CCCR RES interrupt */
 221#define I_IOE2          (1U << 31)      /* CCCR IOE2 Bit Changed */
 222#define I_ERRORS        (I_PC | I_PD | I_DE | I_RU | I_RO | I_XU)
 223#define I_DMA           (I_RI | I_XI | I_ERRORS)
 224
 225/* corecontrol */
 226#define CC_CISRDY               (1 << 0)        /* CIS Ready */
 227#define CC_BPRESEN              (1 << 1)        /* CCCR RES signal */
 228#define CC_F2RDY                (1 << 2)        /* set CCCR IOR2 bit */
 229#define CC_CLRPADSISO           (1 << 3)        /* clear SDIO pads isolation */
 230#define CC_XMTDATAAVAIL_MODE    (1 << 4)
 231#define CC_XMTDATAAVAIL_CTRL    (1 << 5)
 232
 233/* SDA_FRAMECTRL */
 234#define SFC_RF_TERM     (1 << 0)        /* Read Frame Terminate */
 235#define SFC_WF_TERM     (1 << 1)        /* Write Frame Terminate */
 236#define SFC_CRC4WOOS    (1 << 2)        /* CRC error for write out of sync */
 237#define SFC_ABORTALL    (1 << 3)        /* Abort all in-progress frames */
 238
 239/*
 240 * Software allocation of To SB Mailbox resources
 241 */
 242
 243/* tosbmailbox bits corresponding to intstatus bits */
 244#define SMB_NAK         (1 << 0)        /* Frame NAK */
 245#define SMB_INT_ACK     (1 << 1)        /* Host Interrupt ACK */
 246#define SMB_USE_OOB     (1 << 2)        /* Use OOB Wakeup */
 247#define SMB_DEV_INT     (1 << 3)        /* Miscellaneous Interrupt */
 248
 249/* tosbmailboxdata */
 250#define SMB_DATA_VERSION_SHIFT  16      /* host protocol version */
 251
 252/*
 253 * Software allocation of To Host Mailbox resources
 254 */
 255
 256/* intstatus bits */
 257#define I_HMB_FC_STATE  I_HMB_SW0       /* Flow Control State */
 258#define I_HMB_FC_CHANGE I_HMB_SW1       /* Flow Control State Changed */
 259#define I_HMB_FRAME_IND I_HMB_SW2       /* Frame Indication */
 260#define I_HMB_HOST_INT  I_HMB_SW3       /* Miscellaneous Interrupt */
 261
 262/* tohostmailboxdata */
 263#define HMB_DATA_NAKHANDLED     1       /* retransmit NAK'd frame */
 264#define HMB_DATA_DEVREADY       2       /* talk to host after enable */
 265#define HMB_DATA_FC             4       /* per prio flowcontrol update flag */
 266#define HMB_DATA_FWREADY        8       /* fw ready for protocol activity */
 267
 268#define HMB_DATA_FCDATA_MASK    0xff000000
 269#define HMB_DATA_FCDATA_SHIFT   24
 270
 271#define HMB_DATA_VERSION_MASK   0x00ff0000
 272#define HMB_DATA_VERSION_SHIFT  16
 273
 274/*
 275 * Software-defined protocol header
 276 */
 277
 278/* Current protocol version */
 279#define SDPCM_PROT_VERSION      4
 280
 281/*
 282 * Shared structure between dongle and the host.
 283 * The structure contains pointers to trap or assert information.
 284 */
 285#define SDPCM_SHARED_VERSION       0x0003
 286#define SDPCM_SHARED_VERSION_MASK  0x00FF
 287#define SDPCM_SHARED_ASSERT_BUILT  0x0100
 288#define SDPCM_SHARED_ASSERT        0x0200
 289#define SDPCM_SHARED_TRAP          0x0400
 290
 291/* Space for header read, limit for data packets */
 292#define MAX_HDR_READ    (1 << 6)
 293#define MAX_RX_DATASZ   2048
 294
 295/* Bump up limit on waiting for HT to account for first startup;
 296 * if the image is doing a CRC calculation before programming the PMU
 297 * for HT availability, it could take a couple hundred ms more, so
 298 * max out at a 1 second (1000000us).
 299 */
 300#undef PMU_MAX_TRANSITION_DLY
 301#define PMU_MAX_TRANSITION_DLY 1000000
 302
 303/* Value for ChipClockCSR during initial setup */
 304#define BRCMF_INIT_CLKCTL1      (SBSDIO_FORCE_HW_CLKREQ_OFF |   \
 305                                        SBSDIO_ALP_AVAIL_REQ)
 306
 307/* Flags for SDH calls */
 308#define F2SYNC  (SDIO_REQ_4BYTE | SDIO_REQ_FIXED)
 309
 310#define BRCMF_IDLE_ACTIVE       0       /* Do not request any SD clock change
 311                                         * when idle
 312                                         */
 313#define BRCMF_IDLE_INTERVAL     1
 314
 315#define KSO_WAIT_US 50
 316#define MAX_KSO_ATTEMPTS (PMU_MAX_TRANSITION_DLY/KSO_WAIT_US)
 317#define BRCMF_SDIO_MAX_ACCESS_ERRORS    5
 318
 319/*
 320 * Conversion of 802.1D priority to precedence level
 321 */
 322static uint prio2prec(u32 prio)
 323{
 324        return (prio == PRIO_8021D_NONE || prio == PRIO_8021D_BE) ?
 325               (prio^2) : prio;
 326}
 327
 328#ifdef DEBUG
 329/* Device console log buffer state */
 330struct brcmf_console {
 331        uint count;             /* Poll interval msec counter */
 332        uint log_addr;          /* Log struct address (fixed) */
 333        struct rte_log_le log_le;       /* Log struct (host copy) */
 334        uint bufsize;           /* Size of log buffer */
 335        u8 *buf;                /* Log buffer (host copy) */
 336        uint last;              /* Last buffer read index */
 337};
 338
 339struct brcmf_trap_info {
 340        __le32          type;
 341        __le32          epc;
 342        __le32          cpsr;
 343        __le32          spsr;
 344        __le32          r0;     /* a1 */
 345        __le32          r1;     /* a2 */
 346        __le32          r2;     /* a3 */
 347        __le32          r3;     /* a4 */
 348        __le32          r4;     /* v1 */
 349        __le32          r5;     /* v2 */
 350        __le32          r6;     /* v3 */
 351        __le32          r7;     /* v4 */
 352        __le32          r8;     /* v5 */
 353        __le32          r9;     /* sb/v6 */
 354        __le32          r10;    /* sl/v7 */
 355        __le32          r11;    /* fp/v8 */
 356        __le32          r12;    /* ip */
 357        __le32          r13;    /* sp */
 358        __le32          r14;    /* lr */
 359        __le32          pc;     /* r15 */
 360};
 361#endif                          /* DEBUG */
 362
 363struct sdpcm_shared {
 364        u32 flags;
 365        u32 trap_addr;
 366        u32 assert_exp_addr;
 367        u32 assert_file_addr;
 368        u32 assert_line;
 369        u32 console_addr;       /* Address of struct rte_console */
 370        u32 msgtrace_addr;
 371        u8 tag[32];
 372        u32 brpt_addr;
 373};
 374
 375struct sdpcm_shared_le {
 376        __le32 flags;
 377        __le32 trap_addr;
 378        __le32 assert_exp_addr;
 379        __le32 assert_file_addr;
 380        __le32 assert_line;
 381        __le32 console_addr;    /* Address of struct rte_console */
 382        __le32 msgtrace_addr;
 383        u8 tag[32];
 384        __le32 brpt_addr;
 385};
 386
 387/* dongle SDIO bus specific header info */
 388struct brcmf_sdio_hdrinfo {
 389        u8 seq_num;
 390        u8 channel;
 391        u16 len;
 392        u16 len_left;
 393        u16 len_nxtfrm;
 394        u8 dat_offset;
 395        bool lastfrm;
 396        u16 tail_pad;
 397};
 398
 399/*
 400 * hold counter variables
 401 */
 402struct brcmf_sdio_count {
 403        uint intrcount;         /* Count of device interrupt callbacks */
 404        uint lastintrs;         /* Count as of last watchdog timer */
 405        uint pollcnt;           /* Count of active polls */
 406        uint regfails;          /* Count of R_REG failures */
 407        uint tx_sderrs;         /* Count of tx attempts with sd errors */
 408        uint fcqueued;          /* Tx packets that got queued */
 409        uint rxrtx;             /* Count of rtx requests (NAK to dongle) */
 410        uint rx_toolong;        /* Receive frames too long to receive */
 411        uint rxc_errors;        /* SDIO errors when reading control frames */
 412        uint rx_hdrfail;        /* SDIO errors on header reads */
 413        uint rx_badhdr;         /* Bad received headers (roosync?) */
 414        uint rx_badseq;         /* Mismatched rx sequence number */
 415        uint fc_rcvd;           /* Number of flow-control events received */
 416        uint fc_xoff;           /* Number which turned on flow-control */
 417        uint fc_xon;            /* Number which turned off flow-control */
 418        uint rxglomfail;        /* Failed deglom attempts */
 419        uint rxglomframes;      /* Number of glom frames (superframes) */
 420        uint rxglompkts;        /* Number of packets from glom frames */
 421        uint f2rxhdrs;          /* Number of header reads */
 422        uint f2rxdata;          /* Number of frame data reads */
 423        uint f2txdata;          /* Number of f2 frame writes */
 424        uint f1regdata;         /* Number of f1 register accesses */
 425        uint tickcnt;           /* Number of watchdog been schedule */
 426        ulong tx_ctlerrs;       /* Err of sending ctrl frames */
 427        ulong tx_ctlpkts;       /* Ctrl frames sent to dongle */
 428        ulong rx_ctlerrs;       /* Err of processing rx ctrl frames */
 429        ulong rx_ctlpkts;       /* Ctrl frames processed from dongle */
 430        ulong rx_readahead_cnt; /* packets where header read-ahead was used */
 431};
 432
 433/* misc chip info needed by some of the routines */
 434/* Private data for SDIO bus interaction */
 435struct brcmf_sdio {
 436        struct brcmf_sdio_dev *sdiodev; /* sdio device handler */
 437        struct brcmf_chip *ci;  /* Chip info struct */
 438
 439        u32 hostintmask;        /* Copy of Host Interrupt Mask */
 440        atomic_t intstatus;     /* Intstatus bits (events) pending */
 441        atomic_t fcstate;       /* State of dongle flow-control */
 442
 443        uint blocksize;         /* Block size of SDIO transfers */
 444        uint roundup;           /* Max roundup limit */
 445
 446        struct pktq txq;        /* Queue length used for flow-control */
 447        u8 flowcontrol; /* per prio flow control bitmask */
 448        u8 tx_seq;              /* Transmit sequence number (next) */
 449        u8 tx_max;              /* Maximum transmit sequence allowed */
 450
 451        u8 *hdrbuf;             /* buffer for handling rx frame */
 452        u8 *rxhdr;              /* Header of current rx frame (in hdrbuf) */
 453        u8 rx_seq;              /* Receive sequence number (expected) */
 454        struct brcmf_sdio_hdrinfo cur_read;
 455                                /* info of current read frame */
 456        bool rxskip;            /* Skip receive (awaiting NAK ACK) */
 457        bool rxpending;         /* Data frame pending in dongle */
 458
 459        uint rxbound;           /* Rx frames to read before resched */
 460        uint txbound;           /* Tx frames to send before resched */
 461        uint txminmax;
 462
 463        struct sk_buff *glomd;  /* Packet containing glomming descriptor */
 464        struct sk_buff_head glom; /* Packet list for glommed superframe */
 465
 466        u8 *rxbuf;              /* Buffer for receiving control packets */
 467        uint rxblen;            /* Allocated length of rxbuf */
 468        u8 *rxctl;              /* Aligned pointer into rxbuf */
 469        u8 *rxctl_orig;         /* pointer for freeing rxctl */
 470        uint rxlen;             /* Length of valid data in buffer */
 471        spinlock_t rxctl_lock;  /* protection lock for ctrl frame resources */
 472
 473        u8 sdpcm_ver;   /* Bus protocol reported by dongle */
 474
 475        bool intr;              /* Use interrupts */
 476        bool poll;              /* Use polling */
 477        atomic_t ipend;         /* Device interrupt is pending */
 478        uint spurious;          /* Count of spurious interrupts */
 479        uint pollrate;          /* Ticks between device polls */
 480        uint polltick;          /* Tick counter */
 481
 482#ifdef DEBUG
 483        uint console_interval;
 484        struct brcmf_console console;   /* Console output polling support */
 485        uint console_addr;      /* Console address from shared struct */
 486#endif                          /* DEBUG */
 487
 488        uint clkstate;          /* State of sd and backplane clock(s) */
 489        s32 idletime;           /* Control for activity timeout */
 490        s32 idlecount;          /* Activity timeout counter */
 491        s32 idleclock;          /* How to set bus driver when idle */
 492        bool rxflow_mode;       /* Rx flow control mode */
 493        bool rxflow;            /* Is rx flow control on */
 494        bool alp_only;          /* Don't use HT clock (ALP only) */
 495
 496        u8 *ctrl_frame_buf;
 497        u16 ctrl_frame_len;
 498        bool ctrl_frame_stat;
 499        int ctrl_frame_err;
 500
 501        spinlock_t txq_lock;            /* protect bus->txq */
 502        wait_queue_head_t ctrl_wait;
 503        wait_queue_head_t dcmd_resp_wait;
 504
 505        struct timer_list timer;
 506        struct completion watchdog_wait;
 507        struct task_struct *watchdog_tsk;
 508        bool wd_active;
 509
 510        struct workqueue_struct *brcmf_wq;
 511        struct work_struct datawork;
 512        bool dpc_triggered;
 513        bool dpc_running;
 514
 515        bool txoff;             /* Transmit flow-controlled */
 516        struct brcmf_sdio_count sdcnt;
 517        bool sr_enabled; /* SaveRestore enabled */
 518        bool sleeping;
 519
 520        u8 tx_hdrlen;           /* sdio bus header length for tx packet */
 521        bool txglom;            /* host tx glomming enable flag */
 522        u16 head_align;         /* buffer pointer alignment */
 523        u16 sgentry_align;      /* scatter-gather buffer alignment */
 524};
 525
 526/* clkstate */
 527#define CLK_NONE        0
 528#define CLK_SDONLY      1
 529#define CLK_PENDING     2
 530#define CLK_AVAIL       3
 531
 532#ifdef DEBUG
 533static int qcount[NUMPRIO];
 534#endif                          /* DEBUG */
 535
 536#define DEFAULT_SDIO_DRIVE_STRENGTH     6       /* in milliamps */
 537
 538#define RETRYCHAN(chan) ((chan) == SDPCM_EVENT_CHANNEL)
 539
 540/* Limit on rounding up frames */
 541static const uint max_roundup = 512;
 542
 543#ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
 544#define ALIGNMENT  8
 545#else
 546#define ALIGNMENT  4
 547#endif
 548
 549enum brcmf_sdio_frmtype {
 550        BRCMF_SDIO_FT_NORMAL,
 551        BRCMF_SDIO_FT_SUPER,
 552        BRCMF_SDIO_FT_SUB,
 553};
 554
 555#define SDIOD_DRVSTR_KEY(chip, pmu)     (((chip) << 16) | (pmu))
 556
 557/* SDIO Pad drive strength to select value mappings */
 558struct sdiod_drive_str {
 559        u8 strength;    /* Pad Drive Strength in mA */
 560        u8 sel;         /* Chip-specific select value */
 561};
 562
 563/* SDIO Drive Strength to sel value table for PMU Rev 11 (1.8V) */
 564static const struct sdiod_drive_str sdiod_drvstr_tab1_1v8[] = {
 565        {32, 0x6},
 566        {26, 0x7},
 567        {22, 0x4},
 568        {16, 0x5},
 569        {12, 0x2},
 570        {8, 0x3},
 571        {4, 0x0},
 572        {0, 0x1}
 573};
 574
 575/* SDIO Drive Strength to sel value table for PMU Rev 13 (1.8v) */
 576static const struct sdiod_drive_str sdiod_drive_strength_tab5_1v8[] = {
 577        {6, 0x7},
 578        {5, 0x6},
 579        {4, 0x5},
 580        {3, 0x4},
 581        {2, 0x2},
 582        {1, 0x1},
 583        {0, 0x0}
 584};
 585
 586/* SDIO Drive Strength to sel value table for PMU Rev 17 (1.8v) */
 587static const struct sdiod_drive_str sdiod_drvstr_tab6_1v8[] = {
 588        {3, 0x3},
 589        {2, 0x2},
 590        {1, 0x1},
 591        {0, 0x0} };
 592
 593/* SDIO Drive Strength to sel value table for 43143 PMU Rev 17 (3.3V) */
 594static const struct sdiod_drive_str sdiod_drvstr_tab2_3v3[] = {
 595        {16, 0x7},
 596        {12, 0x5},
 597        {8,  0x3},
 598        {4,  0x1}
 599};
 600
 601BRCMF_FW_NVRAM_DEF(43143, "brcmfmac43143-sdio.bin", "brcmfmac43143-sdio.txt");
 602BRCMF_FW_NVRAM_DEF(43241B0, "brcmfmac43241b0-sdio.bin",
 603                   "brcmfmac43241b0-sdio.txt");
 604BRCMF_FW_NVRAM_DEF(43241B4, "brcmfmac43241b4-sdio.bin",
 605                   "brcmfmac43241b4-sdio.txt");
 606BRCMF_FW_NVRAM_DEF(43241B5, "brcmfmac43241b5-sdio.bin",
 607                   "brcmfmac43241b5-sdio.txt");
 608BRCMF_FW_NVRAM_DEF(4329, "brcmfmac4329-sdio.bin", "brcmfmac4329-sdio.txt");
 609BRCMF_FW_NVRAM_DEF(4330, "brcmfmac4330-sdio.bin", "brcmfmac4330-sdio.txt");
 610BRCMF_FW_NVRAM_DEF(4334, "brcmfmac4334-sdio.bin", "brcmfmac4334-sdio.txt");
 611BRCMF_FW_NVRAM_DEF(43340, "brcmfmac43340-sdio.bin", "brcmfmac43340-sdio.txt");
 612BRCMF_FW_NVRAM_DEF(4335, "brcmfmac4335-sdio.bin", "brcmfmac4335-sdio.txt");
 613BRCMF_FW_NVRAM_DEF(43362, "brcmfmac43362-sdio.bin", "brcmfmac43362-sdio.txt");
 614BRCMF_FW_NVRAM_DEF(4339, "brcmfmac4339-sdio.bin", "brcmfmac4339-sdio.txt");
 615BRCMF_FW_NVRAM_DEF(43430A0, "brcmfmac43430a0-sdio.bin", "brcmfmac43430a0-sdio.txt");
 616/* Note the names are not postfixed with a1 for backward compatibility */
 617BRCMF_FW_NVRAM_DEF(43430A1, "brcmfmac43430-sdio.bin", "brcmfmac43430-sdio.txt");
 618BRCMF_FW_NVRAM_DEF(43455, "brcmfmac43455-sdio.bin", "brcmfmac43455-sdio.txt");
 619BRCMF_FW_NVRAM_DEF(4354, "brcmfmac4354-sdio.bin", "brcmfmac4354-sdio.txt");
 620BRCMF_FW_NVRAM_DEF(4356, "brcmfmac4356-sdio.bin", "brcmfmac4356-sdio.txt");
 621BRCMF_FW_NVRAM_DEF(4373, "brcmfmac4373-sdio.bin", "brcmfmac4373-sdio.txt");
 622
 623static struct brcmf_firmware_mapping brcmf_sdio_fwnames[] = {
 624        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43143_CHIP_ID, 0xFFFFFFFF, 43143),
 625        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43241_CHIP_ID, 0x0000001F, 43241B0),
 626        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43241_CHIP_ID, 0x00000020, 43241B4),
 627        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43241_CHIP_ID, 0xFFFFFFC0, 43241B5),
 628        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4329_CHIP_ID, 0xFFFFFFFF, 4329),
 629        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4330_CHIP_ID, 0xFFFFFFFF, 4330),
 630        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4334_CHIP_ID, 0xFFFFFFFF, 4334),
 631        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43340_CHIP_ID, 0xFFFFFFFF, 43340),
 632        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43341_CHIP_ID, 0xFFFFFFFF, 43340),
 633        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4335_CHIP_ID, 0xFFFFFFFF, 4335),
 634        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43362_CHIP_ID, 0xFFFFFFFE, 43362),
 635        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4339_CHIP_ID, 0xFFFFFFFF, 4339),
 636        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43430_CHIP_ID, 0x00000001, 43430A0),
 637        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_43430_CHIP_ID, 0xFFFFFFFE, 43430A1),
 638        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4345_CHIP_ID, 0xFFFFFFC0, 43455),
 639        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4354_CHIP_ID, 0xFFFFFFFF, 4354),
 640        BRCMF_FW_NVRAM_ENTRY(BRCM_CC_4356_CHIP_ID, 0xFFFFFFFF, 4356),
 641        BRCMF_FW_NVRAM_ENTRY(CY_CC_4373_CHIP_ID, 0xFFFFFFFF, 4373)
 642};
 643
 644static void pkt_align(struct sk_buff *p, int len, int align)
 645{
 646        uint datalign;
 647        datalign = (unsigned long)(p->data);
 648        datalign = roundup(datalign, (align)) - datalign;
 649        if (datalign)
 650                skb_pull(p, datalign);
 651        __skb_trim(p, len);
 652}
 653
 654/* To check if there's window offered */
 655static bool data_ok(struct brcmf_sdio *bus)
 656{
 657        return (u8)(bus->tx_max - bus->tx_seq) != 0 &&
 658               ((u8)(bus->tx_max - bus->tx_seq) & 0x80) == 0;
 659}
 660
 661/*
 662 * Reads a register in the SDIO hardware block. This block occupies a series of
 663 * adresses on the 32 bit backplane bus.
 664 */
 665static int r_sdreg32(struct brcmf_sdio *bus, u32 *regvar, u32 offset)
 666{
 667        struct brcmf_core *core;
 668        int ret;
 669
 670        core = brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV);
 671        *regvar = brcmf_sdiod_regrl(bus->sdiodev, core->base + offset, &ret);
 672
 673        return ret;
 674}
 675
 676static int w_sdreg32(struct brcmf_sdio *bus, u32 regval, u32 reg_offset)
 677{
 678        struct brcmf_core *core;
 679        int ret;
 680
 681        core = brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV);
 682        brcmf_sdiod_regwl(bus->sdiodev, core->base + reg_offset, regval, &ret);
 683
 684        return ret;
 685}
 686
 687static int
 688brcmf_sdio_kso_control(struct brcmf_sdio *bus, bool on)
 689{
 690        u8 wr_val = 0, rd_val, cmp_val, bmask;
 691        int err = 0;
 692        int err_cnt = 0;
 693        int try_cnt = 0;
 694
 695        brcmf_dbg(TRACE, "Enter: on=%d\n", on);
 696
 697        wr_val = (on << SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT);
 698        /* 1st KSO write goes to AOS wake up core if device is asleep  */
 699        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
 700                          wr_val, &err);
 701
 702        if (on) {
 703                /* device WAKEUP through KSO:
 704                 * write bit 0 & read back until
 705                 * both bits 0 (kso bit) & 1 (dev on status) are set
 706                 */
 707                cmp_val = SBSDIO_FUNC1_SLEEPCSR_KSO_MASK |
 708                          SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK;
 709                bmask = cmp_val;
 710                usleep_range(2000, 3000);
 711        } else {
 712                /* Put device to sleep, turn off KSO */
 713                cmp_val = 0;
 714                /* only check for bit0, bit1(dev on status) may not
 715                 * get cleared right away
 716                 */
 717                bmask = SBSDIO_FUNC1_SLEEPCSR_KSO_MASK;
 718        }
 719
 720        do {
 721                /* reliable KSO bit set/clr:
 722                 * the sdiod sleep write access is synced to PMU 32khz clk
 723                 * just one write attempt may fail,
 724                 * read it back until it matches written value
 725                 */
 726                rd_val = brcmf_sdiod_regrb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
 727                                           &err);
 728                if (!err) {
 729                        if ((rd_val & bmask) == cmp_val)
 730                                break;
 731                        err_cnt = 0;
 732                }
 733                /* bail out upon subsequent access errors */
 734                if (err && (err_cnt++ > BRCMF_SDIO_MAX_ACCESS_ERRORS))
 735                        break;
 736                udelay(KSO_WAIT_US);
 737                brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
 738                                  wr_val, &err);
 739        } while (try_cnt++ < MAX_KSO_ATTEMPTS);
 740
 741        if (try_cnt > 2)
 742                brcmf_dbg(SDIO, "try_cnt=%d rd_val=0x%x err=%d\n", try_cnt,
 743                          rd_val, err);
 744
 745        if (try_cnt > MAX_KSO_ATTEMPTS)
 746                brcmf_err("max tries: rd_val=0x%x err=%d\n", rd_val, err);
 747
 748        return err;
 749}
 750
 751#define HOSTINTMASK             (I_HMB_SW_MASK | I_CHIPACTIVE)
 752
 753/* Turn backplane clock on or off */
 754static int brcmf_sdio_htclk(struct brcmf_sdio *bus, bool on, bool pendok)
 755{
 756        int err;
 757        u8 clkctl, clkreq, devctl;
 758        unsigned long timeout;
 759
 760        brcmf_dbg(SDIO, "Enter\n");
 761
 762        clkctl = 0;
 763
 764        if (bus->sr_enabled) {
 765                bus->clkstate = (on ? CLK_AVAIL : CLK_SDONLY);
 766                return 0;
 767        }
 768
 769        if (on) {
 770                /* Request HT Avail */
 771                clkreq =
 772                    bus->alp_only ? SBSDIO_ALP_AVAIL_REQ : SBSDIO_HT_AVAIL_REQ;
 773
 774                brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
 775                                  clkreq, &err);
 776                if (err) {
 777                        brcmf_err("HT Avail request error: %d\n", err);
 778                        return -EBADE;
 779                }
 780
 781                /* Check current status */
 782                clkctl = brcmf_sdiod_regrb(bus->sdiodev,
 783                                           SBSDIO_FUNC1_CHIPCLKCSR, &err);
 784                if (err) {
 785                        brcmf_err("HT Avail read error: %d\n", err);
 786                        return -EBADE;
 787                }
 788
 789                /* Go to pending and await interrupt if appropriate */
 790                if (!SBSDIO_CLKAV(clkctl, bus->alp_only) && pendok) {
 791                        /* Allow only clock-available interrupt */
 792                        devctl = brcmf_sdiod_regrb(bus->sdiodev,
 793                                                   SBSDIO_DEVICE_CTL, &err);
 794                        if (err) {
 795                                brcmf_err("Devctl error setting CA: %d\n",
 796                                          err);
 797                                return -EBADE;
 798                        }
 799
 800                        devctl |= SBSDIO_DEVCTL_CA_INT_ONLY;
 801                        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_DEVICE_CTL,
 802                                          devctl, &err);
 803                        brcmf_dbg(SDIO, "CLKCTL: set PENDING\n");
 804                        bus->clkstate = CLK_PENDING;
 805
 806                        return 0;
 807                } else if (bus->clkstate == CLK_PENDING) {
 808                        /* Cancel CA-only interrupt filter */
 809                        devctl = brcmf_sdiod_regrb(bus->sdiodev,
 810                                                   SBSDIO_DEVICE_CTL, &err);
 811                        devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
 812                        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_DEVICE_CTL,
 813                                          devctl, &err);
 814                }
 815
 816                /* Otherwise, wait here (polling) for HT Avail */
 817                timeout = jiffies +
 818                          msecs_to_jiffies(PMU_MAX_TRANSITION_DLY/1000);
 819                while (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
 820                        clkctl = brcmf_sdiod_regrb(bus->sdiodev,
 821                                                   SBSDIO_FUNC1_CHIPCLKCSR,
 822                                                   &err);
 823                        if (time_after(jiffies, timeout))
 824                                break;
 825                        else
 826                                usleep_range(5000, 10000);
 827                }
 828                if (err) {
 829                        brcmf_err("HT Avail request error: %d\n", err);
 830                        return -EBADE;
 831                }
 832                if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
 833                        brcmf_err("HT Avail timeout (%d): clkctl 0x%02x\n",
 834                                  PMU_MAX_TRANSITION_DLY, clkctl);
 835                        return -EBADE;
 836                }
 837
 838                /* Mark clock available */
 839                bus->clkstate = CLK_AVAIL;
 840                brcmf_dbg(SDIO, "CLKCTL: turned ON\n");
 841
 842#if defined(DEBUG)
 843                if (!bus->alp_only) {
 844                        if (SBSDIO_ALPONLY(clkctl))
 845                                brcmf_err("HT Clock should be on\n");
 846                }
 847#endif                          /* defined (DEBUG) */
 848
 849        } else {
 850                clkreq = 0;
 851
 852                if (bus->clkstate == CLK_PENDING) {
 853                        /* Cancel CA-only interrupt filter */
 854                        devctl = brcmf_sdiod_regrb(bus->sdiodev,
 855                                                   SBSDIO_DEVICE_CTL, &err);
 856                        devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
 857                        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_DEVICE_CTL,
 858                                          devctl, &err);
 859                }
 860
 861                bus->clkstate = CLK_SDONLY;
 862                brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
 863                                  clkreq, &err);
 864                brcmf_dbg(SDIO, "CLKCTL: turned OFF\n");
 865                if (err) {
 866                        brcmf_err("Failed access turning clock off: %d\n",
 867                                  err);
 868                        return -EBADE;
 869                }
 870        }
 871        return 0;
 872}
 873
 874/* Change idle/active SD state */
 875static int brcmf_sdio_sdclk(struct brcmf_sdio *bus, bool on)
 876{
 877        brcmf_dbg(SDIO, "Enter\n");
 878
 879        if (on)
 880                bus->clkstate = CLK_SDONLY;
 881        else
 882                bus->clkstate = CLK_NONE;
 883
 884        return 0;
 885}
 886
 887/* Transition SD and backplane clock readiness */
 888static int brcmf_sdio_clkctl(struct brcmf_sdio *bus, uint target, bool pendok)
 889{
 890#ifdef DEBUG
 891        uint oldstate = bus->clkstate;
 892#endif                          /* DEBUG */
 893
 894        brcmf_dbg(SDIO, "Enter\n");
 895
 896        /* Early exit if we're already there */
 897        if (bus->clkstate == target)
 898                return 0;
 899
 900        switch (target) {
 901        case CLK_AVAIL:
 902                /* Make sure SD clock is available */
 903                if (bus->clkstate == CLK_NONE)
 904                        brcmf_sdio_sdclk(bus, true);
 905                /* Now request HT Avail on the backplane */
 906                brcmf_sdio_htclk(bus, true, pendok);
 907                break;
 908
 909        case CLK_SDONLY:
 910                /* Remove HT request, or bring up SD clock */
 911                if (bus->clkstate == CLK_NONE)
 912                        brcmf_sdio_sdclk(bus, true);
 913                else if (bus->clkstate == CLK_AVAIL)
 914                        brcmf_sdio_htclk(bus, false, false);
 915                else
 916                        brcmf_err("request for %d -> %d\n",
 917                                  bus->clkstate, target);
 918                break;
 919
 920        case CLK_NONE:
 921                /* Make sure to remove HT request */
 922                if (bus->clkstate == CLK_AVAIL)
 923                        brcmf_sdio_htclk(bus, false, false);
 924                /* Now remove the SD clock */
 925                brcmf_sdio_sdclk(bus, false);
 926                break;
 927        }
 928#ifdef DEBUG
 929        brcmf_dbg(SDIO, "%d -> %d\n", oldstate, bus->clkstate);
 930#endif                          /* DEBUG */
 931
 932        return 0;
 933}
 934
 935static int
 936brcmf_sdio_bus_sleep(struct brcmf_sdio *bus, bool sleep, bool pendok)
 937{
 938        int err = 0;
 939        u8 clkcsr;
 940
 941        brcmf_dbg(SDIO, "Enter: request %s currently %s\n",
 942                  (sleep ? "SLEEP" : "WAKE"),
 943                  (bus->sleeping ? "SLEEP" : "WAKE"));
 944
 945        /* If SR is enabled control bus state with KSO */
 946        if (bus->sr_enabled) {
 947                /* Done if we're already in the requested state */
 948                if (sleep == bus->sleeping)
 949                        goto end;
 950
 951                /* Going to sleep */
 952                if (sleep) {
 953                        clkcsr = brcmf_sdiod_regrb(bus->sdiodev,
 954                                                   SBSDIO_FUNC1_CHIPCLKCSR,
 955                                                   &err);
 956                        if ((clkcsr & SBSDIO_CSR_MASK) == 0) {
 957                                brcmf_dbg(SDIO, "no clock, set ALP\n");
 958                                brcmf_sdiod_regwb(bus->sdiodev,
 959                                                  SBSDIO_FUNC1_CHIPCLKCSR,
 960                                                  SBSDIO_ALP_AVAIL_REQ, &err);
 961                        }
 962                        err = brcmf_sdio_kso_control(bus, false);
 963                } else {
 964                        err = brcmf_sdio_kso_control(bus, true);
 965                }
 966                if (err) {
 967                        brcmf_err("error while changing bus sleep state %d\n",
 968                                  err);
 969                        goto done;
 970                }
 971        }
 972
 973end:
 974        /* control clocks */
 975        if (sleep) {
 976                if (!bus->sr_enabled)
 977                        brcmf_sdio_clkctl(bus, CLK_NONE, pendok);
 978        } else {
 979                brcmf_sdio_clkctl(bus, CLK_AVAIL, pendok);
 980                brcmf_sdio_wd_timer(bus, true);
 981        }
 982        bus->sleeping = sleep;
 983        brcmf_dbg(SDIO, "new state %s\n",
 984                  (sleep ? "SLEEP" : "WAKE"));
 985done:
 986        brcmf_dbg(SDIO, "Exit: err=%d\n", err);
 987        return err;
 988
 989}
 990
 991#ifdef DEBUG
 992static inline bool brcmf_sdio_valid_shared_address(u32 addr)
 993{
 994        return !(addr == 0 || ((~addr >> 16) & 0xffff) == (addr & 0xffff));
 995}
 996
 997static int brcmf_sdio_readshared(struct brcmf_sdio *bus,
 998                                 struct sdpcm_shared *sh)
 999{
1000        u32 addr = 0;
1001        int rv;
1002        u32 shaddr = 0;
1003        struct sdpcm_shared_le sh_le;
1004        __le32 addr_le;
1005
1006        sdio_claim_host(bus->sdiodev->func[1]);
1007        brcmf_sdio_bus_sleep(bus, false, false);
1008
1009        /*
1010         * Read last word in socram to determine
1011         * address of sdpcm_shared structure
1012         */
1013        shaddr = bus->ci->rambase + bus->ci->ramsize - 4;
1014        if (!bus->ci->rambase && brcmf_chip_sr_capable(bus->ci))
1015                shaddr -= bus->ci->srsize;
1016        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, shaddr,
1017                               (u8 *)&addr_le, 4);
1018        if (rv < 0)
1019                goto fail;
1020
1021        /*
1022         * Check if addr is valid.
1023         * NVRAM length at the end of memory should have been overwritten.
1024         */
1025        addr = le32_to_cpu(addr_le);
1026        if (!brcmf_sdio_valid_shared_address(addr)) {
1027                brcmf_err("invalid sdpcm_shared address 0x%08X\n", addr);
1028                rv = -EINVAL;
1029                goto fail;
1030        }
1031
1032        brcmf_dbg(INFO, "sdpcm_shared address 0x%08X\n", addr);
1033
1034        /* Read hndrte_shared structure */
1035        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr, (u8 *)&sh_le,
1036                               sizeof(struct sdpcm_shared_le));
1037        if (rv < 0)
1038                goto fail;
1039
1040        sdio_release_host(bus->sdiodev->func[1]);
1041
1042        /* Endianness */
1043        sh->flags = le32_to_cpu(sh_le.flags);
1044        sh->trap_addr = le32_to_cpu(sh_le.trap_addr);
1045        sh->assert_exp_addr = le32_to_cpu(sh_le.assert_exp_addr);
1046        sh->assert_file_addr = le32_to_cpu(sh_le.assert_file_addr);
1047        sh->assert_line = le32_to_cpu(sh_le.assert_line);
1048        sh->console_addr = le32_to_cpu(sh_le.console_addr);
1049        sh->msgtrace_addr = le32_to_cpu(sh_le.msgtrace_addr);
1050
1051        if ((sh->flags & SDPCM_SHARED_VERSION_MASK) > SDPCM_SHARED_VERSION) {
1052                brcmf_err("sdpcm shared version unsupported: dhd %d dongle %d\n",
1053                          SDPCM_SHARED_VERSION,
1054                          sh->flags & SDPCM_SHARED_VERSION_MASK);
1055                return -EPROTO;
1056        }
1057        return 0;
1058
1059fail:
1060        brcmf_err("unable to obtain sdpcm_shared info: rv=%d (addr=0x%x)\n",
1061                  rv, addr);
1062        sdio_release_host(bus->sdiodev->func[1]);
1063        return rv;
1064}
1065
1066static void brcmf_sdio_get_console_addr(struct brcmf_sdio *bus)
1067{
1068        struct sdpcm_shared sh;
1069
1070        if (brcmf_sdio_readshared(bus, &sh) == 0)
1071                bus->console_addr = sh.console_addr;
1072}
1073#else
1074static void brcmf_sdio_get_console_addr(struct brcmf_sdio *bus)
1075{
1076}
1077#endif /* DEBUG */
1078
1079static u32 brcmf_sdio_hostmail(struct brcmf_sdio *bus)
1080{
1081        u32 intstatus = 0;
1082        u32 hmb_data;
1083        u8 fcbits;
1084        int ret;
1085
1086        brcmf_dbg(SDIO, "Enter\n");
1087
1088        /* Read mailbox data and ack that we did so */
1089        ret = r_sdreg32(bus, &hmb_data,
1090                        offsetof(struct sdpcmd_regs, tohostmailboxdata));
1091
1092        if (ret == 0)
1093                w_sdreg32(bus, SMB_INT_ACK,
1094                          offsetof(struct sdpcmd_regs, tosbmailbox));
1095        bus->sdcnt.f1regdata += 2;
1096
1097        /* Dongle recomposed rx frames, accept them again */
1098        if (hmb_data & HMB_DATA_NAKHANDLED) {
1099                brcmf_dbg(SDIO, "Dongle reports NAK handled, expect rtx of %d\n",
1100                          bus->rx_seq);
1101                if (!bus->rxskip)
1102                        brcmf_err("unexpected NAKHANDLED!\n");
1103
1104                bus->rxskip = false;
1105                intstatus |= I_HMB_FRAME_IND;
1106        }
1107
1108        /*
1109         * DEVREADY does not occur with gSPI.
1110         */
1111        if (hmb_data & (HMB_DATA_DEVREADY | HMB_DATA_FWREADY)) {
1112                bus->sdpcm_ver =
1113                    (hmb_data & HMB_DATA_VERSION_MASK) >>
1114                    HMB_DATA_VERSION_SHIFT;
1115                if (bus->sdpcm_ver != SDPCM_PROT_VERSION)
1116                        brcmf_err("Version mismatch, dongle reports %d, "
1117                                  "expecting %d\n",
1118                                  bus->sdpcm_ver, SDPCM_PROT_VERSION);
1119                else
1120                        brcmf_dbg(SDIO, "Dongle ready, protocol version %d\n",
1121                                  bus->sdpcm_ver);
1122
1123                /*
1124                 * Retrieve console state address now that firmware should have
1125                 * updated it.
1126                 */
1127                brcmf_sdio_get_console_addr(bus);
1128        }
1129
1130        /*
1131         * Flow Control has been moved into the RX headers and this out of band
1132         * method isn't used any more.
1133         * remaining backward compatible with older dongles.
1134         */
1135        if (hmb_data & HMB_DATA_FC) {
1136                fcbits = (hmb_data & HMB_DATA_FCDATA_MASK) >>
1137                                                        HMB_DATA_FCDATA_SHIFT;
1138
1139                if (fcbits & ~bus->flowcontrol)
1140                        bus->sdcnt.fc_xoff++;
1141
1142                if (bus->flowcontrol & ~fcbits)
1143                        bus->sdcnt.fc_xon++;
1144
1145                bus->sdcnt.fc_rcvd++;
1146                bus->flowcontrol = fcbits;
1147        }
1148
1149        /* Shouldn't be any others */
1150        if (hmb_data & ~(HMB_DATA_DEVREADY |
1151                         HMB_DATA_NAKHANDLED |
1152                         HMB_DATA_FC |
1153                         HMB_DATA_FWREADY |
1154                         HMB_DATA_FCDATA_MASK | HMB_DATA_VERSION_MASK))
1155                brcmf_err("Unknown mailbox data content: 0x%02x\n",
1156                          hmb_data);
1157
1158        return intstatus;
1159}
1160
1161static void brcmf_sdio_rxfail(struct brcmf_sdio *bus, bool abort, bool rtx)
1162{
1163        uint retries = 0;
1164        u16 lastrbc;
1165        u8 hi, lo;
1166        int err;
1167
1168        brcmf_err("%sterminate frame%s\n",
1169                  abort ? "abort command, " : "",
1170                  rtx ? ", send NAK" : "");
1171
1172        if (abort)
1173                brcmf_sdiod_abort(bus->sdiodev, SDIO_FUNC_2);
1174
1175        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_FRAMECTRL,
1176                          SFC_RF_TERM, &err);
1177        bus->sdcnt.f1regdata++;
1178
1179        /* Wait until the packet has been flushed (device/FIFO stable) */
1180        for (lastrbc = retries = 0xffff; retries > 0; retries--) {
1181                hi = brcmf_sdiod_regrb(bus->sdiodev,
1182                                       SBSDIO_FUNC1_RFRAMEBCHI, &err);
1183                lo = brcmf_sdiod_regrb(bus->sdiodev,
1184                                       SBSDIO_FUNC1_RFRAMEBCLO, &err);
1185                bus->sdcnt.f1regdata += 2;
1186
1187                if ((hi == 0) && (lo == 0))
1188                        break;
1189
1190                if ((hi > (lastrbc >> 8)) && (lo > (lastrbc & 0x00ff))) {
1191                        brcmf_err("count growing: last 0x%04x now 0x%04x\n",
1192                                  lastrbc, (hi << 8) + lo);
1193                }
1194                lastrbc = (hi << 8) + lo;
1195        }
1196
1197        if (!retries)
1198                brcmf_err("count never zeroed: last 0x%04x\n", lastrbc);
1199        else
1200                brcmf_dbg(SDIO, "flush took %d iterations\n", 0xffff - retries);
1201
1202        if (rtx) {
1203                bus->sdcnt.rxrtx++;
1204                err = w_sdreg32(bus, SMB_NAK,
1205                                offsetof(struct sdpcmd_regs, tosbmailbox));
1206
1207                bus->sdcnt.f1regdata++;
1208                if (err == 0)
1209                        bus->rxskip = true;
1210        }
1211
1212        /* Clear partial in any case */
1213        bus->cur_read.len = 0;
1214}
1215
1216static void brcmf_sdio_txfail(struct brcmf_sdio *bus)
1217{
1218        struct brcmf_sdio_dev *sdiodev = bus->sdiodev;
1219        u8 i, hi, lo;
1220
1221        /* On failure, abort the command and terminate the frame */
1222        brcmf_err("sdio error, abort command and terminate frame\n");
1223        bus->sdcnt.tx_sderrs++;
1224
1225        brcmf_sdiod_abort(sdiodev, SDIO_FUNC_2);
1226        brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM, NULL);
1227        bus->sdcnt.f1regdata++;
1228
1229        for (i = 0; i < 3; i++) {
1230                hi = brcmf_sdiod_regrb(sdiodev, SBSDIO_FUNC1_WFRAMEBCHI, NULL);
1231                lo = brcmf_sdiod_regrb(sdiodev, SBSDIO_FUNC1_WFRAMEBCLO, NULL);
1232                bus->sdcnt.f1regdata += 2;
1233                if ((hi == 0) && (lo == 0))
1234                        break;
1235        }
1236}
1237
1238/* return total length of buffer chain */
1239static uint brcmf_sdio_glom_len(struct brcmf_sdio *bus)
1240{
1241        struct sk_buff *p;
1242        uint total;
1243
1244        total = 0;
1245        skb_queue_walk(&bus->glom, p)
1246                total += p->len;
1247        return total;
1248}
1249
1250static void brcmf_sdio_free_glom(struct brcmf_sdio *bus)
1251{
1252        struct sk_buff *cur, *next;
1253
1254        skb_queue_walk_safe(&bus->glom, cur, next) {
1255                skb_unlink(cur, &bus->glom);
1256                brcmu_pkt_buf_free_skb(cur);
1257        }
1258}
1259
1260/**
1261 * brcmfmac sdio bus specific header
1262 * This is the lowest layer header wrapped on the packets transmitted between
1263 * host and WiFi dongle which contains information needed for SDIO core and
1264 * firmware
1265 *
1266 * It consists of 3 parts: hardware header, hardware extension header and
1267 * software header
1268 * hardware header (frame tag) - 4 bytes
1269 * Byte 0~1: Frame length
1270 * Byte 2~3: Checksum, bit-wise inverse of frame length
1271 * hardware extension header - 8 bytes
1272 * Tx glom mode only, N/A for Rx or normal Tx
1273 * Byte 0~1: Packet length excluding hw frame tag
1274 * Byte 2: Reserved
1275 * Byte 3: Frame flags, bit 0: last frame indication
1276 * Byte 4~5: Reserved
1277 * Byte 6~7: Tail padding length
1278 * software header - 8 bytes
1279 * Byte 0: Rx/Tx sequence number
1280 * Byte 1: 4 MSB Channel number, 4 LSB arbitrary flag
1281 * Byte 2: Length of next data frame, reserved for Tx
1282 * Byte 3: Data offset
1283 * Byte 4: Flow control bits, reserved for Tx
1284 * Byte 5: Maximum Sequence number allowed by firmware for Tx, N/A for Tx packet
1285 * Byte 6~7: Reserved
1286 */
1287#define SDPCM_HWHDR_LEN                 4
1288#define SDPCM_HWEXT_LEN                 8
1289#define SDPCM_SWHDR_LEN                 8
1290#define SDPCM_HDRLEN                    (SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN)
1291/* software header */
1292#define SDPCM_SEQ_MASK                  0x000000ff
1293#define SDPCM_SEQ_WRAP                  256
1294#define SDPCM_CHANNEL_MASK              0x00000f00
1295#define SDPCM_CHANNEL_SHIFT             8
1296#define SDPCM_CONTROL_CHANNEL           0       /* Control */
1297#define SDPCM_EVENT_CHANNEL             1       /* Asyc Event Indication */
1298#define SDPCM_DATA_CHANNEL              2       /* Data Xmit/Recv */
1299#define SDPCM_GLOM_CHANNEL              3       /* Coalesced packets */
1300#define SDPCM_TEST_CHANNEL              15      /* Test/debug packets */
1301#define SDPCM_GLOMDESC(p)               (((u8 *)p)[1] & 0x80)
1302#define SDPCM_NEXTLEN_MASK              0x00ff0000
1303#define SDPCM_NEXTLEN_SHIFT             16
1304#define SDPCM_DOFFSET_MASK              0xff000000
1305#define SDPCM_DOFFSET_SHIFT             24
1306#define SDPCM_FCMASK_MASK               0x000000ff
1307#define SDPCM_WINDOW_MASK               0x0000ff00
1308#define SDPCM_WINDOW_SHIFT              8
1309
1310static inline u8 brcmf_sdio_getdatoffset(u8 *swheader)
1311{
1312        u32 hdrvalue;
1313        hdrvalue = *(u32 *)swheader;
1314        return (u8)((hdrvalue & SDPCM_DOFFSET_MASK) >> SDPCM_DOFFSET_SHIFT);
1315}
1316
1317static inline bool brcmf_sdio_fromevntchan(u8 *swheader)
1318{
1319        u32 hdrvalue;
1320        u8 ret;
1321
1322        hdrvalue = *(u32 *)swheader;
1323        ret = (u8)((hdrvalue & SDPCM_CHANNEL_MASK) >> SDPCM_CHANNEL_SHIFT);
1324
1325        return (ret == SDPCM_EVENT_CHANNEL);
1326}
1327
1328static int brcmf_sdio_hdparse(struct brcmf_sdio *bus, u8 *header,
1329                              struct brcmf_sdio_hdrinfo *rd,
1330                              enum brcmf_sdio_frmtype type)
1331{
1332        u16 len, checksum;
1333        u8 rx_seq, fc, tx_seq_max;
1334        u32 swheader;
1335
1336        trace_brcmf_sdpcm_hdr(SDPCM_RX, header);
1337
1338        /* hw header */
1339        len = get_unaligned_le16(header);
1340        checksum = get_unaligned_le16(header + sizeof(u16));
1341        /* All zero means no more to read */
1342        if (!(len | checksum)) {
1343                bus->rxpending = false;
1344                return -ENODATA;
1345        }
1346        if ((u16)(~(len ^ checksum))) {
1347                brcmf_err("HW header checksum error\n");
1348                bus->sdcnt.rx_badhdr++;
1349                brcmf_sdio_rxfail(bus, false, false);
1350                return -EIO;
1351        }
1352        if (len < SDPCM_HDRLEN) {
1353                brcmf_err("HW header length error\n");
1354                return -EPROTO;
1355        }
1356        if (type == BRCMF_SDIO_FT_SUPER &&
1357            (roundup(len, bus->blocksize) != rd->len)) {
1358                brcmf_err("HW superframe header length error\n");
1359                return -EPROTO;
1360        }
1361        if (type == BRCMF_SDIO_FT_SUB && len > rd->len) {
1362                brcmf_err("HW subframe header length error\n");
1363                return -EPROTO;
1364        }
1365        rd->len = len;
1366
1367        /* software header */
1368        header += SDPCM_HWHDR_LEN;
1369        swheader = le32_to_cpu(*(__le32 *)header);
1370        if (type == BRCMF_SDIO_FT_SUPER && SDPCM_GLOMDESC(header)) {
1371                brcmf_err("Glom descriptor found in superframe head\n");
1372                rd->len = 0;
1373                return -EINVAL;
1374        }
1375        rx_seq = (u8)(swheader & SDPCM_SEQ_MASK);
1376        rd->channel = (swheader & SDPCM_CHANNEL_MASK) >> SDPCM_CHANNEL_SHIFT;
1377        if (len > MAX_RX_DATASZ && rd->channel != SDPCM_CONTROL_CHANNEL &&
1378            type != BRCMF_SDIO_FT_SUPER) {
1379                brcmf_err("HW header length too long\n");
1380                bus->sdcnt.rx_toolong++;
1381                brcmf_sdio_rxfail(bus, false, false);
1382                rd->len = 0;
1383                return -EPROTO;
1384        }
1385        if (type == BRCMF_SDIO_FT_SUPER && rd->channel != SDPCM_GLOM_CHANNEL) {
1386                brcmf_err("Wrong channel for superframe\n");
1387                rd->len = 0;
1388                return -EINVAL;
1389        }
1390        if (type == BRCMF_SDIO_FT_SUB && rd->channel != SDPCM_DATA_CHANNEL &&
1391            rd->channel != SDPCM_EVENT_CHANNEL) {
1392                brcmf_err("Wrong channel for subframe\n");
1393                rd->len = 0;
1394                return -EINVAL;
1395        }
1396        rd->dat_offset = brcmf_sdio_getdatoffset(header);
1397        if (rd->dat_offset < SDPCM_HDRLEN || rd->dat_offset > rd->len) {
1398                brcmf_err("seq %d: bad data offset\n", rx_seq);
1399                bus->sdcnt.rx_badhdr++;
1400                brcmf_sdio_rxfail(bus, false, false);
1401                rd->len = 0;
1402                return -ENXIO;
1403        }
1404        if (rd->seq_num != rx_seq) {
1405                brcmf_dbg(SDIO, "seq %d, expected %d\n", rx_seq, rd->seq_num);
1406                bus->sdcnt.rx_badseq++;
1407                rd->seq_num = rx_seq;
1408        }
1409        /* no need to check the reset for subframe */
1410        if (type == BRCMF_SDIO_FT_SUB)
1411                return 0;
1412        rd->len_nxtfrm = (swheader & SDPCM_NEXTLEN_MASK) >> SDPCM_NEXTLEN_SHIFT;
1413        if (rd->len_nxtfrm << 4 > MAX_RX_DATASZ) {
1414                /* only warm for NON glom packet */
1415                if (rd->channel != SDPCM_GLOM_CHANNEL)
1416                        brcmf_err("seq %d: next length error\n", rx_seq);
1417                rd->len_nxtfrm = 0;
1418        }
1419        swheader = le32_to_cpu(*(__le32 *)(header + 4));
1420        fc = swheader & SDPCM_FCMASK_MASK;
1421        if (bus->flowcontrol != fc) {
1422                if (~bus->flowcontrol & fc)
1423                        bus->sdcnt.fc_xoff++;
1424                if (bus->flowcontrol & ~fc)
1425                        bus->sdcnt.fc_xon++;
1426                bus->sdcnt.fc_rcvd++;
1427                bus->flowcontrol = fc;
1428        }
1429        tx_seq_max = (swheader & SDPCM_WINDOW_MASK) >> SDPCM_WINDOW_SHIFT;
1430        if ((u8)(tx_seq_max - bus->tx_seq) > 0x40) {
1431                brcmf_err("seq %d: max tx seq number error\n", rx_seq);
1432                tx_seq_max = bus->tx_seq + 2;
1433        }
1434        bus->tx_max = tx_seq_max;
1435
1436        return 0;
1437}
1438
1439static inline void brcmf_sdio_update_hwhdr(u8 *header, u16 frm_length)
1440{
1441        *(__le16 *)header = cpu_to_le16(frm_length);
1442        *(((__le16 *)header) + 1) = cpu_to_le16(~frm_length);
1443}
1444
1445static void brcmf_sdio_hdpack(struct brcmf_sdio *bus, u8 *header,
1446                              struct brcmf_sdio_hdrinfo *hd_info)
1447{
1448        u32 hdrval;
1449        u8 hdr_offset;
1450
1451        brcmf_sdio_update_hwhdr(header, hd_info->len);
1452        hdr_offset = SDPCM_HWHDR_LEN;
1453
1454        if (bus->txglom) {
1455                hdrval = (hd_info->len - hdr_offset) | (hd_info->lastfrm << 24);
1456                *((__le32 *)(header + hdr_offset)) = cpu_to_le32(hdrval);
1457                hdrval = (u16)hd_info->tail_pad << 16;
1458                *(((__le32 *)(header + hdr_offset)) + 1) = cpu_to_le32(hdrval);
1459                hdr_offset += SDPCM_HWEXT_LEN;
1460        }
1461
1462        hdrval = hd_info->seq_num;
1463        hdrval |= (hd_info->channel << SDPCM_CHANNEL_SHIFT) &
1464                  SDPCM_CHANNEL_MASK;
1465        hdrval |= (hd_info->dat_offset << SDPCM_DOFFSET_SHIFT) &
1466                  SDPCM_DOFFSET_MASK;
1467        *((__le32 *)(header + hdr_offset)) = cpu_to_le32(hdrval);
1468        *(((__le32 *)(header + hdr_offset)) + 1) = 0;
1469        trace_brcmf_sdpcm_hdr(SDPCM_TX + !!(bus->txglom), header);
1470}
1471
1472static u8 brcmf_sdio_rxglom(struct brcmf_sdio *bus, u8 rxseq)
1473{
1474        u16 dlen, totlen;
1475        u8 *dptr, num = 0;
1476        u16 sublen;
1477        struct sk_buff *pfirst, *pnext;
1478
1479        int errcode;
1480        u8 doff, sfdoff;
1481
1482        struct brcmf_sdio_hdrinfo rd_new;
1483
1484        /* If packets, issue read(s) and send up packet chain */
1485        /* Return sequence numbers consumed? */
1486
1487        brcmf_dbg(SDIO, "start: glomd %p glom %p\n",
1488                  bus->glomd, skb_peek(&bus->glom));
1489
1490        /* If there's a descriptor, generate the packet chain */
1491        if (bus->glomd) {
1492                pfirst = pnext = NULL;
1493                dlen = (u16) (bus->glomd->len);
1494                dptr = bus->glomd->data;
1495                if (!dlen || (dlen & 1)) {
1496                        brcmf_err("bad glomd len(%d), ignore descriptor\n",
1497                                  dlen);
1498                        dlen = 0;
1499                }
1500
1501                for (totlen = num = 0; dlen; num++) {
1502                        /* Get (and move past) next length */
1503                        sublen = get_unaligned_le16(dptr);
1504                        dlen -= sizeof(u16);
1505                        dptr += sizeof(u16);
1506                        if ((sublen < SDPCM_HDRLEN) ||
1507                            ((num == 0) && (sublen < (2 * SDPCM_HDRLEN)))) {
1508                                brcmf_err("descriptor len %d bad: %d\n",
1509                                          num, sublen);
1510                                pnext = NULL;
1511                                break;
1512                        }
1513                        if (sublen % bus->sgentry_align) {
1514                                brcmf_err("sublen %d not multiple of %d\n",
1515                                          sublen, bus->sgentry_align);
1516                        }
1517                        totlen += sublen;
1518
1519                        /* For last frame, adjust read len so total
1520                                 is a block multiple */
1521                        if (!dlen) {
1522                                sublen +=
1523                                    (roundup(totlen, bus->blocksize) - totlen);
1524                                totlen = roundup(totlen, bus->blocksize);
1525                        }
1526
1527                        /* Allocate/chain packet for next subframe */
1528                        pnext = brcmu_pkt_buf_get_skb(sublen + bus->sgentry_align);
1529                        if (pnext == NULL) {
1530                                brcmf_err("bcm_pkt_buf_get_skb failed, num %d len %d\n",
1531                                          num, sublen);
1532                                break;
1533                        }
1534                        skb_queue_tail(&bus->glom, pnext);
1535
1536                        /* Adhere to start alignment requirements */
1537                        pkt_align(pnext, sublen, bus->sgentry_align);
1538                }
1539
1540                /* If all allocations succeeded, save packet chain
1541                         in bus structure */
1542                if (pnext) {
1543                        brcmf_dbg(GLOM, "allocated %d-byte packet chain for %d subframes\n",
1544                                  totlen, num);
1545                        if (BRCMF_GLOM_ON() && bus->cur_read.len &&
1546                            totlen != bus->cur_read.len) {
1547                                brcmf_dbg(GLOM, "glomdesc mismatch: nextlen %d glomdesc %d rxseq %d\n",
1548                                          bus->cur_read.len, totlen, rxseq);
1549                        }
1550                        pfirst = pnext = NULL;
1551                } else {
1552                        brcmf_sdio_free_glom(bus);
1553                        num = 0;
1554                }
1555
1556                /* Done with descriptor packet */
1557                brcmu_pkt_buf_free_skb(bus->glomd);
1558                bus->glomd = NULL;
1559                bus->cur_read.len = 0;
1560        }
1561
1562        /* Ok -- either we just generated a packet chain,
1563                 or had one from before */
1564        if (!skb_queue_empty(&bus->glom)) {
1565                if (BRCMF_GLOM_ON()) {
1566                        brcmf_dbg(GLOM, "try superframe read, packet chain:\n");
1567                        skb_queue_walk(&bus->glom, pnext) {
1568                                brcmf_dbg(GLOM, "    %p: %p len 0x%04x (%d)\n",
1569                                          pnext, (u8 *) (pnext->data),
1570                                          pnext->len, pnext->len);
1571                        }
1572                }
1573
1574                pfirst = skb_peek(&bus->glom);
1575                dlen = (u16) brcmf_sdio_glom_len(bus);
1576
1577                /* Do an SDIO read for the superframe.  Configurable iovar to
1578                 * read directly into the chained packet, or allocate a large
1579                 * packet and and copy into the chain.
1580                 */
1581                sdio_claim_host(bus->sdiodev->func[1]);
1582                errcode = brcmf_sdiod_recv_chain(bus->sdiodev,
1583                                                 &bus->glom, dlen);
1584                sdio_release_host(bus->sdiodev->func[1]);
1585                bus->sdcnt.f2rxdata++;
1586
1587                /* On failure, kill the superframe */
1588                if (errcode < 0) {
1589                        brcmf_err("glom read of %d bytes failed: %d\n",
1590                                  dlen, errcode);
1591
1592                        sdio_claim_host(bus->sdiodev->func[1]);
1593                        brcmf_sdio_rxfail(bus, true, false);
1594                        bus->sdcnt.rxglomfail++;
1595                        brcmf_sdio_free_glom(bus);
1596                        sdio_release_host(bus->sdiodev->func[1]);
1597                        return 0;
1598                }
1599
1600                brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1601                                   pfirst->data, min_t(int, pfirst->len, 48),
1602                                   "SUPERFRAME:\n");
1603
1604                rd_new.seq_num = rxseq;
1605                rd_new.len = dlen;
1606                sdio_claim_host(bus->sdiodev->func[1]);
1607                errcode = brcmf_sdio_hdparse(bus, pfirst->data, &rd_new,
1608                                             BRCMF_SDIO_FT_SUPER);
1609                sdio_release_host(bus->sdiodev->func[1]);
1610                bus->cur_read.len = rd_new.len_nxtfrm << 4;
1611
1612                /* Remove superframe header, remember offset */
1613                skb_pull(pfirst, rd_new.dat_offset);
1614                sfdoff = rd_new.dat_offset;
1615                num = 0;
1616
1617                /* Validate all the subframe headers */
1618                skb_queue_walk(&bus->glom, pnext) {
1619                        /* leave when invalid subframe is found */
1620                        if (errcode)
1621                                break;
1622
1623                        rd_new.len = pnext->len;
1624                        rd_new.seq_num = rxseq++;
1625                        sdio_claim_host(bus->sdiodev->func[1]);
1626                        errcode = brcmf_sdio_hdparse(bus, pnext->data, &rd_new,
1627                                                     BRCMF_SDIO_FT_SUB);
1628                        sdio_release_host(bus->sdiodev->func[1]);
1629                        brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1630                                           pnext->data, 32, "subframe:\n");
1631
1632                        num++;
1633                }
1634
1635                if (errcode) {
1636                        /* Terminate frame on error */
1637                        sdio_claim_host(bus->sdiodev->func[1]);
1638                        brcmf_sdio_rxfail(bus, true, false);
1639                        bus->sdcnt.rxglomfail++;
1640                        brcmf_sdio_free_glom(bus);
1641                        sdio_release_host(bus->sdiodev->func[1]);
1642                        bus->cur_read.len = 0;
1643                        return 0;
1644                }
1645
1646                /* Basic SD framing looks ok - process each packet (header) */
1647
1648                skb_queue_walk_safe(&bus->glom, pfirst, pnext) {
1649                        dptr = (u8 *) (pfirst->data);
1650                        sublen = get_unaligned_le16(dptr);
1651                        doff = brcmf_sdio_getdatoffset(&dptr[SDPCM_HWHDR_LEN]);
1652
1653                        brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
1654                                           dptr, pfirst->len,
1655                                           "Rx Subframe Data:\n");
1656
1657                        __skb_trim(pfirst, sublen);
1658                        skb_pull(pfirst, doff);
1659
1660                        if (pfirst->len == 0) {
1661                                skb_unlink(pfirst, &bus->glom);
1662                                brcmu_pkt_buf_free_skb(pfirst);
1663                                continue;
1664                        }
1665
1666                        brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1667                                           pfirst->data,
1668                                           min_t(int, pfirst->len, 32),
1669                                           "subframe %d to stack, %p (%p/%d) nxt/lnk %p/%p\n",
1670                                           bus->glom.qlen, pfirst, pfirst->data,
1671                                           pfirst->len, pfirst->next,
1672                                           pfirst->prev);
1673                        skb_unlink(pfirst, &bus->glom);
1674                        if (brcmf_sdio_fromevntchan(&dptr[SDPCM_HWHDR_LEN]))
1675                                brcmf_rx_event(bus->sdiodev->dev, pfirst);
1676                        else
1677                                brcmf_rx_frame(bus->sdiodev->dev, pfirst,
1678                                               false);
1679                        bus->sdcnt.rxglompkts++;
1680                }
1681
1682                bus->sdcnt.rxglomframes++;
1683        }
1684        return num;
1685}
1686
1687static int brcmf_sdio_dcmd_resp_wait(struct brcmf_sdio *bus, uint *condition,
1688                                     bool *pending)
1689{
1690        DECLARE_WAITQUEUE(wait, current);
1691        int timeout = DCMD_RESP_TIMEOUT;
1692
1693        /* Wait until control frame is available */
1694        add_wait_queue(&bus->dcmd_resp_wait, &wait);
1695        set_current_state(TASK_INTERRUPTIBLE);
1696
1697        while (!(*condition) && (!signal_pending(current) && timeout))
1698                timeout = schedule_timeout(timeout);
1699
1700        if (signal_pending(current))
1701                *pending = true;
1702
1703        set_current_state(TASK_RUNNING);
1704        remove_wait_queue(&bus->dcmd_resp_wait, &wait);
1705
1706        return timeout;
1707}
1708
1709static int brcmf_sdio_dcmd_resp_wake(struct brcmf_sdio *bus)
1710{
1711        wake_up_interruptible(&bus->dcmd_resp_wait);
1712
1713        return 0;
1714}
1715static void
1716brcmf_sdio_read_control(struct brcmf_sdio *bus, u8 *hdr, uint len, uint doff)
1717{
1718        uint rdlen, pad;
1719        u8 *buf = NULL, *rbuf;
1720        int sdret;
1721
1722        brcmf_dbg(TRACE, "Enter\n");
1723
1724        if (bus->rxblen)
1725                buf = vzalloc(bus->rxblen);
1726        if (!buf)
1727                goto done;
1728
1729        rbuf = bus->rxbuf;
1730        pad = ((unsigned long)rbuf % bus->head_align);
1731        if (pad)
1732                rbuf += (bus->head_align - pad);
1733
1734        /* Copy the already-read portion over */
1735        memcpy(buf, hdr, BRCMF_FIRSTREAD);
1736        if (len <= BRCMF_FIRSTREAD)
1737                goto gotpkt;
1738
1739        /* Raise rdlen to next SDIO block to avoid tail command */
1740        rdlen = len - BRCMF_FIRSTREAD;
1741        if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) {
1742                pad = bus->blocksize - (rdlen % bus->blocksize);
1743                if ((pad <= bus->roundup) && (pad < bus->blocksize) &&
1744                    ((len + pad) < bus->sdiodev->bus_if->maxctl))
1745                        rdlen += pad;
1746        } else if (rdlen % bus->head_align) {
1747                rdlen += bus->head_align - (rdlen % bus->head_align);
1748        }
1749
1750        /* Drop if the read is too big or it exceeds our maximum */
1751        if ((rdlen + BRCMF_FIRSTREAD) > bus->sdiodev->bus_if->maxctl) {
1752                brcmf_err("%d-byte control read exceeds %d-byte buffer\n",
1753                          rdlen, bus->sdiodev->bus_if->maxctl);
1754                brcmf_sdio_rxfail(bus, false, false);
1755                goto done;
1756        }
1757
1758        if ((len - doff) > bus->sdiodev->bus_if->maxctl) {
1759                brcmf_err("%d-byte ctl frame (%d-byte ctl data) exceeds %d-byte limit\n",
1760                          len, len - doff, bus->sdiodev->bus_if->maxctl);
1761                bus->sdcnt.rx_toolong++;
1762                brcmf_sdio_rxfail(bus, false, false);
1763                goto done;
1764        }
1765
1766        /* Read remain of frame body */
1767        sdret = brcmf_sdiod_recv_buf(bus->sdiodev, rbuf, rdlen);
1768        bus->sdcnt.f2rxdata++;
1769
1770        /* Control frame failures need retransmission */
1771        if (sdret < 0) {
1772                brcmf_err("read %d control bytes failed: %d\n",
1773                          rdlen, sdret);
1774                bus->sdcnt.rxc_errors++;
1775                brcmf_sdio_rxfail(bus, true, true);
1776                goto done;
1777        } else
1778                memcpy(buf + BRCMF_FIRSTREAD, rbuf, rdlen);
1779
1780gotpkt:
1781
1782        brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_CTL_ON(),
1783                           buf, len, "RxCtrl:\n");
1784
1785        /* Point to valid data and indicate its length */
1786        spin_lock_bh(&bus->rxctl_lock);
1787        if (bus->rxctl) {
1788                brcmf_err("last control frame is being processed.\n");
1789                spin_unlock_bh(&bus->rxctl_lock);
1790                vfree(buf);
1791                goto done;
1792        }
1793        bus->rxctl = buf + doff;
1794        bus->rxctl_orig = buf;
1795        bus->rxlen = len - doff;
1796        spin_unlock_bh(&bus->rxctl_lock);
1797
1798done:
1799        /* Awake any waiters */
1800        brcmf_sdio_dcmd_resp_wake(bus);
1801}
1802
1803/* Pad read to blocksize for efficiency */
1804static void brcmf_sdio_pad(struct brcmf_sdio *bus, u16 *pad, u16 *rdlen)
1805{
1806        if (bus->roundup && bus->blocksize && *rdlen > bus->blocksize) {
1807                *pad = bus->blocksize - (*rdlen % bus->blocksize);
1808                if (*pad <= bus->roundup && *pad < bus->blocksize &&
1809                    *rdlen + *pad + BRCMF_FIRSTREAD < MAX_RX_DATASZ)
1810                        *rdlen += *pad;
1811        } else if (*rdlen % bus->head_align) {
1812                *rdlen += bus->head_align - (*rdlen % bus->head_align);
1813        }
1814}
1815
1816static uint brcmf_sdio_readframes(struct brcmf_sdio *bus, uint maxframes)
1817{
1818        struct sk_buff *pkt;            /* Packet for event or data frames */
1819        u16 pad;                /* Number of pad bytes to read */
1820        uint rxleft = 0;        /* Remaining number of frames allowed */
1821        int ret;                /* Return code from calls */
1822        uint rxcount = 0;       /* Total frames read */
1823        struct brcmf_sdio_hdrinfo *rd = &bus->cur_read, rd_new;
1824        u8 head_read = 0;
1825
1826        brcmf_dbg(TRACE, "Enter\n");
1827
1828        /* Not finished unless we encounter no more frames indication */
1829        bus->rxpending = true;
1830
1831        for (rd->seq_num = bus->rx_seq, rxleft = maxframes;
1832             !bus->rxskip && rxleft && bus->sdiodev->state == BRCMF_SDIOD_DATA;
1833             rd->seq_num++, rxleft--) {
1834
1835                /* Handle glomming separately */
1836                if (bus->glomd || !skb_queue_empty(&bus->glom)) {
1837                        u8 cnt;
1838                        brcmf_dbg(GLOM, "calling rxglom: glomd %p, glom %p\n",
1839                                  bus->glomd, skb_peek(&bus->glom));
1840                        cnt = brcmf_sdio_rxglom(bus, rd->seq_num);
1841                        brcmf_dbg(GLOM, "rxglom returned %d\n", cnt);
1842                        rd->seq_num += cnt - 1;
1843                        rxleft = (rxleft > cnt) ? (rxleft - cnt) : 1;
1844                        continue;
1845                }
1846
1847                rd->len_left = rd->len;
1848                /* read header first for unknow frame length */
1849                sdio_claim_host(bus->sdiodev->func[1]);
1850                if (!rd->len) {
1851                        ret = brcmf_sdiod_recv_buf(bus->sdiodev,
1852                                                   bus->rxhdr, BRCMF_FIRSTREAD);
1853                        bus->sdcnt.f2rxhdrs++;
1854                        if (ret < 0) {
1855                                brcmf_err("RXHEADER FAILED: %d\n",
1856                                          ret);
1857                                bus->sdcnt.rx_hdrfail++;
1858                                brcmf_sdio_rxfail(bus, true, true);
1859                                sdio_release_host(bus->sdiodev->func[1]);
1860                                continue;
1861                        }
1862
1863                        brcmf_dbg_hex_dump(BRCMF_BYTES_ON() || BRCMF_HDRS_ON(),
1864                                           bus->rxhdr, SDPCM_HDRLEN,
1865                                           "RxHdr:\n");
1866
1867                        if (brcmf_sdio_hdparse(bus, bus->rxhdr, rd,
1868                                               BRCMF_SDIO_FT_NORMAL)) {
1869                                sdio_release_host(bus->sdiodev->func[1]);
1870                                if (!bus->rxpending)
1871                                        break;
1872                                else
1873                                        continue;
1874                        }
1875
1876                        if (rd->channel == SDPCM_CONTROL_CHANNEL) {
1877                                brcmf_sdio_read_control(bus, bus->rxhdr,
1878                                                        rd->len,
1879                                                        rd->dat_offset);
1880                                /* prepare the descriptor for the next read */
1881                                rd->len = rd->len_nxtfrm << 4;
1882                                rd->len_nxtfrm = 0;
1883                                /* treat all packet as event if we don't know */
1884                                rd->channel = SDPCM_EVENT_CHANNEL;
1885                                sdio_release_host(bus->sdiodev->func[1]);
1886                                continue;
1887                        }
1888                        rd->len_left = rd->len > BRCMF_FIRSTREAD ?
1889                                       rd->len - BRCMF_FIRSTREAD : 0;
1890                        head_read = BRCMF_FIRSTREAD;
1891                }
1892
1893                brcmf_sdio_pad(bus, &pad, &rd->len_left);
1894
1895                pkt = brcmu_pkt_buf_get_skb(rd->len_left + head_read +
1896                                            bus->head_align);
1897                if (!pkt) {
1898                        /* Give up on data, request rtx of events */
1899                        brcmf_err("brcmu_pkt_buf_get_skb failed\n");
1900                        brcmf_sdio_rxfail(bus, false,
1901                                            RETRYCHAN(rd->channel));
1902                        sdio_release_host(bus->sdiodev->func[1]);
1903                        continue;
1904                }
1905                skb_pull(pkt, head_read);
1906                pkt_align(pkt, rd->len_left, bus->head_align);
1907
1908                ret = brcmf_sdiod_recv_pkt(bus->sdiodev, pkt);
1909                bus->sdcnt.f2rxdata++;
1910                sdio_release_host(bus->sdiodev->func[1]);
1911
1912                if (ret < 0) {
1913                        brcmf_err("read %d bytes from channel %d failed: %d\n",
1914                                  rd->len, rd->channel, ret);
1915                        brcmu_pkt_buf_free_skb(pkt);
1916                        sdio_claim_host(bus->sdiodev->func[1]);
1917                        brcmf_sdio_rxfail(bus, true,
1918                                            RETRYCHAN(rd->channel));
1919                        sdio_release_host(bus->sdiodev->func[1]);
1920                        continue;
1921                }
1922
1923                if (head_read) {
1924                        skb_push(pkt, head_read);
1925                        memcpy(pkt->data, bus->rxhdr, head_read);
1926                        head_read = 0;
1927                } else {
1928                        memcpy(bus->rxhdr, pkt->data, SDPCM_HDRLEN);
1929                        rd_new.seq_num = rd->seq_num;
1930                        sdio_claim_host(bus->sdiodev->func[1]);
1931                        if (brcmf_sdio_hdparse(bus, bus->rxhdr, &rd_new,
1932                                               BRCMF_SDIO_FT_NORMAL)) {
1933                                rd->len = 0;
1934                                brcmu_pkt_buf_free_skb(pkt);
1935                        }
1936                        bus->sdcnt.rx_readahead_cnt++;
1937                        if (rd->len != roundup(rd_new.len, 16)) {
1938                                brcmf_err("frame length mismatch:read %d, should be %d\n",
1939                                          rd->len,
1940                                          roundup(rd_new.len, 16) >> 4);
1941                                rd->len = 0;
1942                                brcmf_sdio_rxfail(bus, true, true);
1943                                sdio_release_host(bus->sdiodev->func[1]);
1944                                brcmu_pkt_buf_free_skb(pkt);
1945                                continue;
1946                        }
1947                        sdio_release_host(bus->sdiodev->func[1]);
1948                        rd->len_nxtfrm = rd_new.len_nxtfrm;
1949                        rd->channel = rd_new.channel;
1950                        rd->dat_offset = rd_new.dat_offset;
1951
1952                        brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() &&
1953                                             BRCMF_DATA_ON()) &&
1954                                           BRCMF_HDRS_ON(),
1955                                           bus->rxhdr, SDPCM_HDRLEN,
1956                                           "RxHdr:\n");
1957
1958                        if (rd_new.channel == SDPCM_CONTROL_CHANNEL) {
1959                                brcmf_err("readahead on control packet %d?\n",
1960                                          rd_new.seq_num);
1961                                /* Force retry w/normal header read */
1962                                rd->len = 0;
1963                                sdio_claim_host(bus->sdiodev->func[1]);
1964                                brcmf_sdio_rxfail(bus, false, true);
1965                                sdio_release_host(bus->sdiodev->func[1]);
1966                                brcmu_pkt_buf_free_skb(pkt);
1967                                continue;
1968                        }
1969                }
1970
1971                brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
1972                                   pkt->data, rd->len, "Rx Data:\n");
1973
1974                /* Save superframe descriptor and allocate packet frame */
1975                if (rd->channel == SDPCM_GLOM_CHANNEL) {
1976                        if (SDPCM_GLOMDESC(&bus->rxhdr[SDPCM_HWHDR_LEN])) {
1977                                brcmf_dbg(GLOM, "glom descriptor, %d bytes:\n",
1978                                          rd->len);
1979                                brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1980                                                   pkt->data, rd->len,
1981                                                   "Glom Data:\n");
1982                                __skb_trim(pkt, rd->len);
1983                                skb_pull(pkt, SDPCM_HDRLEN);
1984                                bus->glomd = pkt;
1985                        } else {
1986                                brcmf_err("%s: glom superframe w/o "
1987                                          "descriptor!\n", __func__);
1988                                sdio_claim_host(bus->sdiodev->func[1]);
1989                                brcmf_sdio_rxfail(bus, false, false);
1990                                sdio_release_host(bus->sdiodev->func[1]);
1991                        }
1992                        /* prepare the descriptor for the next read */
1993                        rd->len = rd->len_nxtfrm << 4;
1994                        rd->len_nxtfrm = 0;
1995                        /* treat all packet as event if we don't know */
1996                        rd->channel = SDPCM_EVENT_CHANNEL;
1997                        continue;
1998                }
1999
2000                /* Fill in packet len and prio, deliver upward */
2001                __skb_trim(pkt, rd->len);
2002                skb_pull(pkt, rd->dat_offset);
2003
2004                if (pkt->len == 0)
2005                        brcmu_pkt_buf_free_skb(pkt);
2006                else if (rd->channel == SDPCM_EVENT_CHANNEL)
2007                        brcmf_rx_event(bus->sdiodev->dev, pkt);
2008                else
2009                        brcmf_rx_frame(bus->sdiodev->dev, pkt,
2010                                       false);
2011
2012                /* prepare the descriptor for the next read */
2013                rd->len = rd->len_nxtfrm << 4;
2014                rd->len_nxtfrm = 0;
2015                /* treat all packet as event if we don't know */
2016                rd->channel = SDPCM_EVENT_CHANNEL;
2017        }
2018
2019        rxcount = maxframes - rxleft;
2020        /* Message if we hit the limit */
2021        if (!rxleft)
2022                brcmf_dbg(DATA, "hit rx limit of %d frames\n", maxframes);
2023        else
2024                brcmf_dbg(DATA, "processed %d frames\n", rxcount);
2025        /* Back off rxseq if awaiting rtx, update rx_seq */
2026        if (bus->rxskip)
2027                rd->seq_num--;
2028        bus->rx_seq = rd->seq_num;
2029
2030        return rxcount;
2031}
2032
2033static void
2034brcmf_sdio_wait_event_wakeup(struct brcmf_sdio *bus)
2035{
2036        wake_up_interruptible(&bus->ctrl_wait);
2037        return;
2038}
2039
2040static int brcmf_sdio_txpkt_hdalign(struct brcmf_sdio *bus, struct sk_buff *pkt)
2041{
2042        struct brcmf_bus_stats *stats;
2043        u16 head_pad;
2044        u8 *dat_buf;
2045
2046        dat_buf = (u8 *)(pkt->data);
2047
2048        /* Check head padding */
2049        head_pad = ((unsigned long)dat_buf % bus->head_align);
2050        if (head_pad) {
2051                if (skb_headroom(pkt) < head_pad) {
2052                        stats = &bus->sdiodev->bus_if->stats;
2053                        atomic_inc(&stats->pktcowed);
2054                        if (skb_cow_head(pkt, head_pad)) {
2055                                atomic_inc(&stats->pktcow_failed);
2056                                return -ENOMEM;
2057                        }
2058                        head_pad = 0;
2059                }
2060                skb_push(pkt, head_pad);
2061                dat_buf = (u8 *)(pkt->data);
2062        }
2063        memset(dat_buf, 0, head_pad + bus->tx_hdrlen);
2064        return head_pad;
2065}
2066
2067/**
2068 * struct brcmf_skbuff_cb reserves first two bytes in sk_buff::cb for
2069 * bus layer usage.
2070 */
2071/* flag marking a dummy skb added for DMA alignment requirement */
2072#define ALIGN_SKB_FLAG          0x8000
2073/* bit mask of data length chopped from the previous packet */
2074#define ALIGN_SKB_CHOP_LEN_MASK 0x7fff
2075
2076static int brcmf_sdio_txpkt_prep_sg(struct brcmf_sdio *bus,
2077                                    struct sk_buff_head *pktq,
2078                                    struct sk_buff *pkt, u16 total_len)
2079{
2080        struct brcmf_sdio_dev *sdiodev;
2081        struct sk_buff *pkt_pad;
2082        u16 tail_pad, tail_chop, chain_pad;
2083        unsigned int blksize;
2084        bool lastfrm;
2085        int ntail, ret;
2086
2087        sdiodev = bus->sdiodev;
2088        blksize = sdiodev->func[SDIO_FUNC_2]->cur_blksize;
2089        /* sg entry alignment should be a divisor of block size */
2090        WARN_ON(blksize % bus->sgentry_align);
2091
2092        /* Check tail padding */
2093        lastfrm = skb_queue_is_last(pktq, pkt);
2094        tail_pad = 0;
2095        tail_chop = pkt->len % bus->sgentry_align;
2096        if (tail_chop)
2097                tail_pad = bus->sgentry_align - tail_chop;
2098        chain_pad = (total_len + tail_pad) % blksize;
2099        if (lastfrm && chain_pad)
2100                tail_pad += blksize - chain_pad;
2101        if (skb_tailroom(pkt) < tail_pad && pkt->len > blksize) {
2102                pkt_pad = brcmu_pkt_buf_get_skb(tail_pad + tail_chop +
2103                                                bus->head_align);
2104                if (pkt_pad == NULL)
2105                        return -ENOMEM;
2106                ret = brcmf_sdio_txpkt_hdalign(bus, pkt_pad);
2107                if (unlikely(ret < 0)) {
2108                        kfree_skb(pkt_pad);
2109                        return ret;
2110                }
2111                memcpy(pkt_pad->data,
2112                       pkt->data + pkt->len - tail_chop,
2113                       tail_chop);
2114                *(u16 *)(pkt_pad->cb) = ALIGN_SKB_FLAG + tail_chop;
2115                skb_trim(pkt, pkt->len - tail_chop);
2116                skb_trim(pkt_pad, tail_pad + tail_chop);
2117                __skb_queue_after(pktq, pkt, pkt_pad);
2118        } else {
2119                ntail = pkt->data_len + tail_pad -
2120                        (pkt->end - pkt->tail);
2121                if (skb_cloned(pkt) || ntail > 0)
2122                        if (pskb_expand_head(pkt, 0, ntail, GFP_ATOMIC))
2123                                return -ENOMEM;
2124                if (skb_linearize(pkt))
2125                        return -ENOMEM;
2126                __skb_put(pkt, tail_pad);
2127        }
2128
2129        return tail_pad;
2130}
2131
2132/**
2133 * brcmf_sdio_txpkt_prep - packet preparation for transmit
2134 * @bus: brcmf_sdio structure pointer
2135 * @pktq: packet list pointer
2136 * @chan: virtual channel to transmit the packet
2137 *
2138 * Processes to be applied to the packet
2139 *      - Align data buffer pointer
2140 *      - Align data buffer length
2141 *      - Prepare header
2142 * Return: negative value if there is error
2143 */
2144static int
2145brcmf_sdio_txpkt_prep(struct brcmf_sdio *bus, struct sk_buff_head *pktq,
2146                      uint chan)
2147{
2148        u16 head_pad, total_len;
2149        struct sk_buff *pkt_next;
2150        u8 txseq;
2151        int ret;
2152        struct brcmf_sdio_hdrinfo hd_info = {0};
2153
2154        txseq = bus->tx_seq;
2155        total_len = 0;
2156        skb_queue_walk(pktq, pkt_next) {
2157                /* alignment packet inserted in previous
2158                 * loop cycle can be skipped as it is
2159                 * already properly aligned and does not
2160                 * need an sdpcm header.
2161                 */
2162                if (*(u16 *)(pkt_next->cb) & ALIGN_SKB_FLAG)
2163                        continue;
2164
2165                /* align packet data pointer */
2166                ret = brcmf_sdio_txpkt_hdalign(bus, pkt_next);
2167                if (ret < 0)
2168                        return ret;
2169                head_pad = (u16)ret;
2170                if (head_pad)
2171                        memset(pkt_next->data + bus->tx_hdrlen, 0, head_pad);
2172
2173                total_len += pkt_next->len;
2174
2175                hd_info.len = pkt_next->len;
2176                hd_info.lastfrm = skb_queue_is_last(pktq, pkt_next);
2177                if (bus->txglom && pktq->qlen > 1) {
2178                        ret = brcmf_sdio_txpkt_prep_sg(bus, pktq,
2179                                                       pkt_next, total_len);
2180                        if (ret < 0)
2181                                return ret;
2182                        hd_info.tail_pad = (u16)ret;
2183                        total_len += (u16)ret;
2184                }
2185
2186                hd_info.channel = chan;
2187                hd_info.dat_offset = head_pad + bus->tx_hdrlen;
2188                hd_info.seq_num = txseq++;
2189
2190                /* Now fill the header */
2191                brcmf_sdio_hdpack(bus, pkt_next->data, &hd_info);
2192
2193                if (BRCMF_BYTES_ON() &&
2194                    ((BRCMF_CTL_ON() && chan == SDPCM_CONTROL_CHANNEL) ||
2195                     (BRCMF_DATA_ON() && chan != SDPCM_CONTROL_CHANNEL)))
2196                        brcmf_dbg_hex_dump(true, pkt_next->data, hd_info.len,
2197                                           "Tx Frame:\n");
2198                else if (BRCMF_HDRS_ON())
2199                        brcmf_dbg_hex_dump(true, pkt_next->data,
2200                                           head_pad + bus->tx_hdrlen,
2201                                           "Tx Header:\n");
2202        }
2203        /* Hardware length tag of the first packet should be total
2204         * length of the chain (including padding)
2205         */
2206        if (bus->txglom)
2207                brcmf_sdio_update_hwhdr(pktq->next->data, total_len);
2208        return 0;
2209}
2210
2211/**
2212 * brcmf_sdio_txpkt_postp - packet post processing for transmit
2213 * @bus: brcmf_sdio structure pointer
2214 * @pktq: packet list pointer
2215 *
2216 * Processes to be applied to the packet
2217 *      - Remove head padding
2218 *      - Remove tail padding
2219 */
2220static void
2221brcmf_sdio_txpkt_postp(struct brcmf_sdio *bus, struct sk_buff_head *pktq)
2222{
2223        u8 *hdr;
2224        u32 dat_offset;
2225        u16 tail_pad;
2226        u16 dummy_flags, chop_len;
2227        struct sk_buff *pkt_next, *tmp, *pkt_prev;
2228
2229        skb_queue_walk_safe(pktq, pkt_next, tmp) {
2230                dummy_flags = *(u16 *)(pkt_next->cb);
2231                if (dummy_flags & ALIGN_SKB_FLAG) {
2232                        chop_len = dummy_flags & ALIGN_SKB_CHOP_LEN_MASK;
2233                        if (chop_len) {
2234                                pkt_prev = pkt_next->prev;
2235                                skb_put(pkt_prev, chop_len);
2236                        }
2237                        __skb_unlink(pkt_next, pktq);
2238                        brcmu_pkt_buf_free_skb(pkt_next);
2239                } else {
2240                        hdr = pkt_next->data + bus->tx_hdrlen - SDPCM_SWHDR_LEN;
2241                        dat_offset = le32_to_cpu(*(__le32 *)hdr);
2242                        dat_offset = (dat_offset & SDPCM_DOFFSET_MASK) >>
2243                                     SDPCM_DOFFSET_SHIFT;
2244                        skb_pull(pkt_next, dat_offset);
2245                        if (bus->txglom) {
2246                                tail_pad = le16_to_cpu(*(__le16 *)(hdr - 2));
2247                                skb_trim(pkt_next, pkt_next->len - tail_pad);
2248                        }
2249                }
2250        }
2251}
2252
2253/* Writes a HW/SW header into the packet and sends it. */
2254/* Assumes: (a) header space already there, (b) caller holds lock */
2255static int brcmf_sdio_txpkt(struct brcmf_sdio *bus, struct sk_buff_head *pktq,
2256                            uint chan)
2257{
2258        int ret;
2259        struct sk_buff *pkt_next, *tmp;
2260
2261        brcmf_dbg(TRACE, "Enter\n");
2262
2263        ret = brcmf_sdio_txpkt_prep(bus, pktq, chan);
2264        if (ret)
2265                goto done;
2266
2267        sdio_claim_host(bus->sdiodev->func[1]);
2268        ret = brcmf_sdiod_send_pkt(bus->sdiodev, pktq);
2269        bus->sdcnt.f2txdata++;
2270
2271        if (ret < 0)
2272                brcmf_sdio_txfail(bus);
2273
2274        sdio_release_host(bus->sdiodev->func[1]);
2275
2276done:
2277        brcmf_sdio_txpkt_postp(bus, pktq);
2278        if (ret == 0)
2279                bus->tx_seq = (bus->tx_seq + pktq->qlen) % SDPCM_SEQ_WRAP;
2280        skb_queue_walk_safe(pktq, pkt_next, tmp) {
2281                __skb_unlink(pkt_next, pktq);
2282                brcmf_proto_bcdc_txcomplete(bus->sdiodev->dev, pkt_next,
2283                                            ret == 0);
2284        }
2285        return ret;
2286}
2287
2288static uint brcmf_sdio_sendfromq(struct brcmf_sdio *bus, uint maxframes)
2289{
2290        struct sk_buff *pkt;
2291        struct sk_buff_head pktq;
2292        u32 intstatus = 0;
2293        int ret = 0, prec_out, i;
2294        uint cnt = 0;
2295        u8 tx_prec_map, pkt_num;
2296
2297        brcmf_dbg(TRACE, "Enter\n");
2298
2299        tx_prec_map = ~bus->flowcontrol;
2300
2301        /* Send frames until the limit or some other event */
2302        for (cnt = 0; (cnt < maxframes) && data_ok(bus);) {
2303                pkt_num = 1;
2304                if (bus->txglom)
2305                        pkt_num = min_t(u8, bus->tx_max - bus->tx_seq,
2306                                        bus->sdiodev->txglomsz);
2307                pkt_num = min_t(u32, pkt_num,
2308                                brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol));
2309                __skb_queue_head_init(&pktq);
2310                spin_lock_bh(&bus->txq_lock);
2311                for (i = 0; i < pkt_num; i++) {
2312                        pkt = brcmu_pktq_mdeq(&bus->txq, tx_prec_map,
2313                                              &prec_out);
2314                        if (pkt == NULL)
2315                                break;
2316                        __skb_queue_tail(&pktq, pkt);
2317                }
2318                spin_unlock_bh(&bus->txq_lock);
2319                if (i == 0)
2320                        break;
2321
2322                ret = brcmf_sdio_txpkt(bus, &pktq, SDPCM_DATA_CHANNEL);
2323
2324                cnt += i;
2325
2326                /* In poll mode, need to check for other events */
2327                if (!bus->intr) {
2328                        /* Check device status, signal pending interrupt */
2329                        sdio_claim_host(bus->sdiodev->func[1]);
2330                        ret = r_sdreg32(bus, &intstatus,
2331                                        offsetof(struct sdpcmd_regs,
2332                                                 intstatus));
2333                        sdio_release_host(bus->sdiodev->func[1]);
2334                        bus->sdcnt.f2txdata++;
2335                        if (ret != 0)
2336                                break;
2337                        if (intstatus & bus->hostintmask)
2338                                atomic_set(&bus->ipend, 1);
2339                }
2340        }
2341
2342        /* Deflow-control stack if needed */
2343        if ((bus->sdiodev->state == BRCMF_SDIOD_DATA) &&
2344            bus->txoff && (pktq_len(&bus->txq) < TXLOW)) {
2345                bus->txoff = false;
2346                brcmf_proto_bcdc_txflowblock(bus->sdiodev->dev, false);
2347        }
2348
2349        return cnt;
2350}
2351
2352static int brcmf_sdio_tx_ctrlframe(struct brcmf_sdio *bus, u8 *frame, u16 len)
2353{
2354        u8 doff;
2355        u16 pad;
2356        uint retries = 0;
2357        struct brcmf_sdio_hdrinfo hd_info = {0};
2358        int ret;
2359
2360        brcmf_dbg(TRACE, "Enter\n");
2361
2362        /* Back the pointer to make room for bus header */
2363        frame -= bus->tx_hdrlen;
2364        len += bus->tx_hdrlen;
2365
2366        /* Add alignment padding (optional for ctl frames) */
2367        doff = ((unsigned long)frame % bus->head_align);
2368        if (doff) {
2369                frame -= doff;
2370                len += doff;
2371                memset(frame + bus->tx_hdrlen, 0, doff);
2372        }
2373
2374        /* Round send length to next SDIO block */
2375        pad = 0;
2376        if (bus->roundup && bus->blocksize && (len > bus->blocksize)) {
2377                pad = bus->blocksize - (len % bus->blocksize);
2378                if ((pad > bus->roundup) || (pad >= bus->blocksize))
2379                        pad = 0;
2380        } else if (len % bus->head_align) {
2381                pad = bus->head_align - (len % bus->head_align);
2382        }
2383        len += pad;
2384
2385        hd_info.len = len - pad;
2386        hd_info.channel = SDPCM_CONTROL_CHANNEL;
2387        hd_info.dat_offset = doff + bus->tx_hdrlen;
2388        hd_info.seq_num = bus->tx_seq;
2389        hd_info.lastfrm = true;
2390        hd_info.tail_pad = pad;
2391        brcmf_sdio_hdpack(bus, frame, &hd_info);
2392
2393        if (bus->txglom)
2394                brcmf_sdio_update_hwhdr(frame, len);
2395
2396        brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_CTL_ON(),
2397                           frame, len, "Tx Frame:\n");
2398        brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() && BRCMF_CTL_ON()) &&
2399                           BRCMF_HDRS_ON(),
2400                           frame, min_t(u16, len, 16), "TxHdr:\n");
2401
2402        do {
2403                ret = brcmf_sdiod_send_buf(bus->sdiodev, frame, len);
2404
2405                if (ret < 0)
2406                        brcmf_sdio_txfail(bus);
2407                else
2408                        bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQ_WRAP;
2409        } while (ret < 0 && retries++ < TXRETRIES);
2410
2411        return ret;
2412}
2413
2414static void brcmf_sdio_bus_stop(struct device *dev)
2415{
2416        u32 local_hostintmask;
2417        u8 saveclk;
2418        int err;
2419        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2420        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2421        struct brcmf_sdio *bus = sdiodev->bus;
2422
2423        brcmf_dbg(TRACE, "Enter\n");
2424
2425        if (bus->watchdog_tsk) {
2426                send_sig(SIGTERM, bus->watchdog_tsk, 1);
2427                kthread_stop(bus->watchdog_tsk);
2428                bus->watchdog_tsk = NULL;
2429        }
2430
2431        if (sdiodev->state != BRCMF_SDIOD_NOMEDIUM) {
2432                sdio_claim_host(sdiodev->func[1]);
2433
2434                /* Enable clock for device interrupts */
2435                brcmf_sdio_bus_sleep(bus, false, false);
2436
2437                /* Disable and clear interrupts at the chip level also */
2438                w_sdreg32(bus, 0, offsetof(struct sdpcmd_regs, hostintmask));
2439                local_hostintmask = bus->hostintmask;
2440                bus->hostintmask = 0;
2441
2442                /* Force backplane clocks to assure F2 interrupt propagates */
2443                saveclk = brcmf_sdiod_regrb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
2444                                            &err);
2445                if (!err)
2446                        brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
2447                                          (saveclk | SBSDIO_FORCE_HT), &err);
2448                if (err)
2449                        brcmf_err("Failed to force clock for F2: err %d\n",
2450                                  err);
2451
2452                /* Turn off the bus (F2), free any pending packets */
2453                brcmf_dbg(INTR, "disable SDIO interrupts\n");
2454                sdio_disable_func(sdiodev->func[SDIO_FUNC_2]);
2455
2456                /* Clear any pending interrupts now that F2 is disabled */
2457                w_sdreg32(bus, local_hostintmask,
2458                          offsetof(struct sdpcmd_regs, intstatus));
2459
2460                sdio_release_host(sdiodev->func[1]);
2461        }
2462        /* Clear the data packet queues */
2463        brcmu_pktq_flush(&bus->txq, true, NULL, NULL);
2464
2465        /* Clear any held glomming stuff */
2466        brcmu_pkt_buf_free_skb(bus->glomd);
2467        brcmf_sdio_free_glom(bus);
2468
2469        /* Clear rx control and wake any waiters */
2470        spin_lock_bh(&bus->rxctl_lock);
2471        bus->rxlen = 0;
2472        spin_unlock_bh(&bus->rxctl_lock);
2473        brcmf_sdio_dcmd_resp_wake(bus);
2474
2475        /* Reset some F2 state stuff */
2476        bus->rxskip = false;
2477        bus->tx_seq = bus->rx_seq = 0;
2478}
2479
2480static inline void brcmf_sdio_clrintr(struct brcmf_sdio *bus)
2481{
2482        struct brcmf_sdio_dev *sdiodev;
2483        unsigned long flags;
2484
2485        sdiodev = bus->sdiodev;
2486        if (sdiodev->oob_irq_requested) {
2487                spin_lock_irqsave(&sdiodev->irq_en_lock, flags);
2488                if (!sdiodev->irq_en && !atomic_read(&bus->ipend)) {
2489                        enable_irq(sdiodev->settings->bus.sdio.oob_irq_nr);
2490                        sdiodev->irq_en = true;
2491                }
2492                spin_unlock_irqrestore(&sdiodev->irq_en_lock, flags);
2493        }
2494}
2495
2496static int brcmf_sdio_intr_rstatus(struct brcmf_sdio *bus)
2497{
2498        struct brcmf_core *buscore;
2499        u32 addr;
2500        unsigned long val;
2501        int ret;
2502
2503        buscore = brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV);
2504        addr = buscore->base + offsetof(struct sdpcmd_regs, intstatus);
2505
2506        val = brcmf_sdiod_regrl(bus->sdiodev, addr, &ret);
2507        bus->sdcnt.f1regdata++;
2508        if (ret != 0)
2509                return ret;
2510
2511        val &= bus->hostintmask;
2512        atomic_set(&bus->fcstate, !!(val & I_HMB_FC_STATE));
2513
2514        /* Clear interrupts */
2515        if (val) {
2516                brcmf_sdiod_regwl(bus->sdiodev, addr, val, &ret);
2517                bus->sdcnt.f1regdata++;
2518                atomic_or(val, &bus->intstatus);
2519        }
2520
2521        return ret;
2522}
2523
2524static void brcmf_sdio_dpc(struct brcmf_sdio *bus)
2525{
2526        u32 newstatus = 0;
2527        unsigned long intstatus;
2528        uint txlimit = bus->txbound;    /* Tx frames to send before resched */
2529        uint framecnt;                  /* Temporary counter of tx/rx frames */
2530        int err = 0;
2531
2532        brcmf_dbg(TRACE, "Enter\n");
2533
2534        sdio_claim_host(bus->sdiodev->func[1]);
2535
2536        /* If waiting for HTAVAIL, check status */
2537        if (!bus->sr_enabled && bus->clkstate == CLK_PENDING) {
2538                u8 clkctl, devctl = 0;
2539
2540#ifdef DEBUG
2541                /* Check for inconsistent device control */
2542                devctl = brcmf_sdiod_regrb(bus->sdiodev,
2543                                           SBSDIO_DEVICE_CTL, &err);
2544#endif                          /* DEBUG */
2545
2546                /* Read CSR, if clock on switch to AVAIL, else ignore */
2547                clkctl = brcmf_sdiod_regrb(bus->sdiodev,
2548                                           SBSDIO_FUNC1_CHIPCLKCSR, &err);
2549
2550                brcmf_dbg(SDIO, "DPC: PENDING, devctl 0x%02x clkctl 0x%02x\n",
2551                          devctl, clkctl);
2552
2553                if (SBSDIO_HTAV(clkctl)) {
2554                        devctl = brcmf_sdiod_regrb(bus->sdiodev,
2555                                                   SBSDIO_DEVICE_CTL, &err);
2556                        devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
2557                        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_DEVICE_CTL,
2558                                          devctl, &err);
2559                        bus->clkstate = CLK_AVAIL;
2560                }
2561        }
2562
2563        /* Make sure backplane clock is on */
2564        brcmf_sdio_bus_sleep(bus, false, true);
2565
2566        /* Pending interrupt indicates new device status */
2567        if (atomic_read(&bus->ipend) > 0) {
2568                atomic_set(&bus->ipend, 0);
2569                err = brcmf_sdio_intr_rstatus(bus);
2570        }
2571
2572        /* Start with leftover status bits */
2573        intstatus = atomic_xchg(&bus->intstatus, 0);
2574
2575        /* Handle flow-control change: read new state in case our ack
2576         * crossed another change interrupt.  If change still set, assume
2577         * FC ON for safety, let next loop through do the debounce.
2578         */
2579        if (intstatus & I_HMB_FC_CHANGE) {
2580                intstatus &= ~I_HMB_FC_CHANGE;
2581                err = w_sdreg32(bus, I_HMB_FC_CHANGE,
2582                                offsetof(struct sdpcmd_regs, intstatus));
2583
2584                err = r_sdreg32(bus, &newstatus,
2585                                offsetof(struct sdpcmd_regs, intstatus));
2586                bus->sdcnt.f1regdata += 2;
2587                atomic_set(&bus->fcstate,
2588                           !!(newstatus & (I_HMB_FC_STATE | I_HMB_FC_CHANGE)));
2589                intstatus |= (newstatus & bus->hostintmask);
2590        }
2591
2592        /* Handle host mailbox indication */
2593        if (intstatus & I_HMB_HOST_INT) {
2594                intstatus &= ~I_HMB_HOST_INT;
2595                intstatus |= brcmf_sdio_hostmail(bus);
2596        }
2597
2598        sdio_release_host(bus->sdiodev->func[1]);
2599
2600        /* Generally don't ask for these, can get CRC errors... */
2601        if (intstatus & I_WR_OOSYNC) {
2602                brcmf_err("Dongle reports WR_OOSYNC\n");
2603                intstatus &= ~I_WR_OOSYNC;
2604        }
2605
2606        if (intstatus & I_RD_OOSYNC) {
2607                brcmf_err("Dongle reports RD_OOSYNC\n");
2608                intstatus &= ~I_RD_OOSYNC;
2609        }
2610
2611        if (intstatus & I_SBINT) {
2612                brcmf_err("Dongle reports SBINT\n");
2613                intstatus &= ~I_SBINT;
2614        }
2615
2616        /* Would be active due to wake-wlan in gSPI */
2617        if (intstatus & I_CHIPACTIVE) {
2618                brcmf_dbg(INFO, "Dongle reports CHIPACTIVE\n");
2619                intstatus &= ~I_CHIPACTIVE;
2620        }
2621
2622        /* Ignore frame indications if rxskip is set */
2623        if (bus->rxskip)
2624                intstatus &= ~I_HMB_FRAME_IND;
2625
2626        /* On frame indication, read available frames */
2627        if ((intstatus & I_HMB_FRAME_IND) && (bus->clkstate == CLK_AVAIL)) {
2628                brcmf_sdio_readframes(bus, bus->rxbound);
2629                if (!bus->rxpending)
2630                        intstatus &= ~I_HMB_FRAME_IND;
2631        }
2632
2633        /* Keep still-pending events for next scheduling */
2634        if (intstatus)
2635                atomic_or(intstatus, &bus->intstatus);
2636
2637        brcmf_sdio_clrintr(bus);
2638
2639        if (bus->ctrl_frame_stat && (bus->clkstate == CLK_AVAIL) &&
2640            data_ok(bus)) {
2641                sdio_claim_host(bus->sdiodev->func[1]);
2642                if (bus->ctrl_frame_stat) {
2643                        err = brcmf_sdio_tx_ctrlframe(bus,  bus->ctrl_frame_buf,
2644                                                      bus->ctrl_frame_len);
2645                        bus->ctrl_frame_err = err;
2646                        wmb();
2647                        bus->ctrl_frame_stat = false;
2648                }
2649                sdio_release_host(bus->sdiodev->func[1]);
2650                brcmf_sdio_wait_event_wakeup(bus);
2651        }
2652        /* Send queued frames (limit 1 if rx may still be pending) */
2653        if ((bus->clkstate == CLK_AVAIL) && !atomic_read(&bus->fcstate) &&
2654            brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol) && txlimit &&
2655            data_ok(bus)) {
2656                framecnt = bus->rxpending ? min(txlimit, bus->txminmax) :
2657                                            txlimit;
2658                brcmf_sdio_sendfromq(bus, framecnt);
2659        }
2660
2661        if ((bus->sdiodev->state != BRCMF_SDIOD_DATA) || (err != 0)) {
2662                brcmf_err("failed backplane access over SDIO, halting operation\n");
2663                atomic_set(&bus->intstatus, 0);
2664                if (bus->ctrl_frame_stat) {
2665                        sdio_claim_host(bus->sdiodev->func[1]);
2666                        if (bus->ctrl_frame_stat) {
2667                                bus->ctrl_frame_err = -ENODEV;
2668                                wmb();
2669                                bus->ctrl_frame_stat = false;
2670                                brcmf_sdio_wait_event_wakeup(bus);
2671                        }
2672                        sdio_release_host(bus->sdiodev->func[1]);
2673                }
2674        } else if (atomic_read(&bus->intstatus) ||
2675                   atomic_read(&bus->ipend) > 0 ||
2676                   (!atomic_read(&bus->fcstate) &&
2677                    brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol) &&
2678                    data_ok(bus))) {
2679                bus->dpc_triggered = true;
2680        }
2681}
2682
2683static struct pktq *brcmf_sdio_bus_gettxq(struct device *dev)
2684{
2685        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2686        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2687        struct brcmf_sdio *bus = sdiodev->bus;
2688
2689        return &bus->txq;
2690}
2691
2692static bool brcmf_sdio_prec_enq(struct pktq *q, struct sk_buff *pkt, int prec)
2693{
2694        struct sk_buff *p;
2695        int eprec = -1;         /* precedence to evict from */
2696
2697        /* Fast case, precedence queue is not full and we are also not
2698         * exceeding total queue length
2699         */
2700        if (!pktq_pfull(q, prec) && !pktq_full(q)) {
2701                brcmu_pktq_penq(q, prec, pkt);
2702                return true;
2703        }
2704
2705        /* Determine precedence from which to evict packet, if any */
2706        if (pktq_pfull(q, prec)) {
2707                eprec = prec;
2708        } else if (pktq_full(q)) {
2709                p = brcmu_pktq_peek_tail(q, &eprec);
2710                if (eprec > prec)
2711                        return false;
2712        }
2713
2714        /* Evict if needed */
2715        if (eprec >= 0) {
2716                /* Detect queueing to unconfigured precedence */
2717                if (eprec == prec)
2718                        return false;   /* refuse newer (incoming) packet */
2719                /* Evict packet according to discard policy */
2720                p = brcmu_pktq_pdeq_tail(q, eprec);
2721                if (p == NULL)
2722                        brcmf_err("brcmu_pktq_pdeq_tail() failed\n");
2723                brcmu_pkt_buf_free_skb(p);
2724        }
2725
2726        /* Enqueue */
2727        p = brcmu_pktq_penq(q, prec, pkt);
2728        if (p == NULL)
2729                brcmf_err("brcmu_pktq_penq() failed\n");
2730
2731        return p != NULL;
2732}
2733
2734static int brcmf_sdio_bus_txdata(struct device *dev, struct sk_buff *pkt)
2735{
2736        int ret = -EBADE;
2737        uint prec;
2738        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2739        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2740        struct brcmf_sdio *bus = sdiodev->bus;
2741
2742        brcmf_dbg(TRACE, "Enter: pkt: data %p len %d\n", pkt->data, pkt->len);
2743        if (sdiodev->state != BRCMF_SDIOD_DATA)
2744                return -EIO;
2745
2746        /* Add space for the header */
2747        skb_push(pkt, bus->tx_hdrlen);
2748        /* precondition: IS_ALIGNED((unsigned long)(pkt->data), 2) */
2749
2750        prec = prio2prec((pkt->priority & PRIOMASK));
2751
2752        /* Check for existing queue, current flow-control,
2753                         pending event, or pending clock */
2754        brcmf_dbg(TRACE, "deferring pktq len %d\n", pktq_len(&bus->txq));
2755        bus->sdcnt.fcqueued++;
2756
2757        /* Priority based enq */
2758        spin_lock_bh(&bus->txq_lock);
2759        /* reset bus_flags in packet cb */
2760        *(u16 *)(pkt->cb) = 0;
2761        if (!brcmf_sdio_prec_enq(&bus->txq, pkt, prec)) {
2762                skb_pull(pkt, bus->tx_hdrlen);
2763                brcmf_err("out of bus->txq !!!\n");
2764                ret = -ENOSR;
2765        } else {
2766                ret = 0;
2767        }
2768
2769        if (pktq_len(&bus->txq) >= TXHI) {
2770                bus->txoff = true;
2771                brcmf_proto_bcdc_txflowblock(dev, true);
2772        }
2773        spin_unlock_bh(&bus->txq_lock);
2774
2775#ifdef DEBUG
2776        if (pktq_plen(&bus->txq, prec) > qcount[prec])
2777                qcount[prec] = pktq_plen(&bus->txq, prec);
2778#endif
2779
2780        brcmf_sdio_trigger_dpc(bus);
2781        return ret;
2782}
2783
2784#ifdef DEBUG
2785#define CONSOLE_LINE_MAX        192
2786
2787static int brcmf_sdio_readconsole(struct brcmf_sdio *bus)
2788{
2789        struct brcmf_console *c = &bus->console;
2790        u8 line[CONSOLE_LINE_MAX], ch;
2791        u32 n, idx, addr;
2792        int rv;
2793
2794        /* Don't do anything until FWREADY updates console address */
2795        if (bus->console_addr == 0)
2796                return 0;
2797
2798        /* Read console log struct */
2799        addr = bus->console_addr + offsetof(struct rte_console, log_le);
2800        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr, (u8 *)&c->log_le,
2801                               sizeof(c->log_le));
2802        if (rv < 0)
2803                return rv;
2804
2805        /* Allocate console buffer (one time only) */
2806        if (c->buf == NULL) {
2807                c->bufsize = le32_to_cpu(c->log_le.buf_size);
2808                c->buf = kmalloc(c->bufsize, GFP_ATOMIC);
2809                if (c->buf == NULL)
2810                        return -ENOMEM;
2811        }
2812
2813        idx = le32_to_cpu(c->log_le.idx);
2814
2815        /* Protect against corrupt value */
2816        if (idx > c->bufsize)
2817                return -EBADE;
2818
2819        /* Skip reading the console buffer if the index pointer
2820         has not moved */
2821        if (idx == c->last)
2822                return 0;
2823
2824        /* Read the console buffer */
2825        addr = le32_to_cpu(c->log_le.buf);
2826        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr, c->buf, c->bufsize);
2827        if (rv < 0)
2828                return rv;
2829
2830        while (c->last != idx) {
2831                for (n = 0; n < CONSOLE_LINE_MAX - 2; n++) {
2832                        if (c->last == idx) {
2833                                /* This would output a partial line.
2834                                 * Instead, back up
2835                                 * the buffer pointer and output this
2836                                 * line next time around.
2837                                 */
2838                                if (c->last >= n)
2839                                        c->last -= n;
2840                                else
2841                                        c->last = c->bufsize - n;
2842                                goto break2;
2843                        }
2844                        ch = c->buf[c->last];
2845                        c->last = (c->last + 1) % c->bufsize;
2846                        if (ch == '\n')
2847                                break;
2848                        line[n] = ch;
2849                }
2850
2851                if (n > 0) {
2852                        if (line[n - 1] == '\r')
2853                                n--;
2854                        line[n] = 0;
2855                        pr_debug("CONSOLE: %s\n", line);
2856                }
2857        }
2858break2:
2859
2860        return 0;
2861}
2862#endif                          /* DEBUG */
2863
2864static int
2865brcmf_sdio_bus_txctl(struct device *dev, unsigned char *msg, uint msglen)
2866{
2867        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2868        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2869        struct brcmf_sdio *bus = sdiodev->bus;
2870        int ret;
2871
2872        brcmf_dbg(TRACE, "Enter\n");
2873        if (sdiodev->state != BRCMF_SDIOD_DATA)
2874                return -EIO;
2875
2876        /* Send from dpc */
2877        bus->ctrl_frame_buf = msg;
2878        bus->ctrl_frame_len = msglen;
2879        wmb();
2880        bus->ctrl_frame_stat = true;
2881
2882        brcmf_sdio_trigger_dpc(bus);
2883        wait_event_interruptible_timeout(bus->ctrl_wait, !bus->ctrl_frame_stat,
2884                                         CTL_DONE_TIMEOUT);
2885        ret = 0;
2886        if (bus->ctrl_frame_stat) {
2887                sdio_claim_host(bus->sdiodev->func[1]);
2888                if (bus->ctrl_frame_stat) {
2889                        brcmf_dbg(SDIO, "ctrl_frame timeout\n");
2890                        bus->ctrl_frame_stat = false;
2891                        ret = -ETIMEDOUT;
2892                }
2893                sdio_release_host(bus->sdiodev->func[1]);
2894        }
2895        if (!ret) {
2896                brcmf_dbg(SDIO, "ctrl_frame complete, err=%d\n",
2897                          bus->ctrl_frame_err);
2898                rmb();
2899                ret = bus->ctrl_frame_err;
2900        }
2901
2902        if (ret)
2903                bus->sdcnt.tx_ctlerrs++;
2904        else
2905                bus->sdcnt.tx_ctlpkts++;
2906
2907        return ret;
2908}
2909
2910#ifdef DEBUG
2911static int brcmf_sdio_dump_console(struct seq_file *seq, struct brcmf_sdio *bus,
2912                                   struct sdpcm_shared *sh)
2913{
2914        u32 addr, console_ptr, console_size, console_index;
2915        char *conbuf = NULL;
2916        __le32 sh_val;
2917        int rv;
2918
2919        /* obtain console information from device memory */
2920        addr = sh->console_addr + offsetof(struct rte_console, log_le);
2921        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr,
2922                               (u8 *)&sh_val, sizeof(u32));
2923        if (rv < 0)
2924                return rv;
2925        console_ptr = le32_to_cpu(sh_val);
2926
2927        addr = sh->console_addr + offsetof(struct rte_console, log_le.buf_size);
2928        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr,
2929                               (u8 *)&sh_val, sizeof(u32));
2930        if (rv < 0)
2931                return rv;
2932        console_size = le32_to_cpu(sh_val);
2933
2934        addr = sh->console_addr + offsetof(struct rte_console, log_le.idx);
2935        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr,
2936                               (u8 *)&sh_val, sizeof(u32));
2937        if (rv < 0)
2938                return rv;
2939        console_index = le32_to_cpu(sh_val);
2940
2941        /* allocate buffer for console data */
2942        if (console_size <= CONSOLE_BUFFER_MAX)
2943                conbuf = vzalloc(console_size+1);
2944
2945        if (!conbuf)
2946                return -ENOMEM;
2947
2948        /* obtain the console data from device */
2949        conbuf[console_size] = '\0';
2950        rv = brcmf_sdiod_ramrw(bus->sdiodev, false, console_ptr, (u8 *)conbuf,
2951                               console_size);
2952        if (rv < 0)
2953                goto done;
2954
2955        rv = seq_write(seq, conbuf + console_index,
2956                       console_size - console_index);
2957        if (rv < 0)
2958                goto done;
2959
2960        if (console_index > 0)
2961                rv = seq_write(seq, conbuf, console_index - 1);
2962
2963done:
2964        vfree(conbuf);
2965        return rv;
2966}
2967
2968static int brcmf_sdio_trap_info(struct seq_file *seq, struct brcmf_sdio *bus,
2969                                struct sdpcm_shared *sh)
2970{
2971        int error;
2972        struct brcmf_trap_info tr;
2973
2974        if ((sh->flags & SDPCM_SHARED_TRAP) == 0) {
2975                brcmf_dbg(INFO, "no trap in firmware\n");
2976                return 0;
2977        }
2978
2979        error = brcmf_sdiod_ramrw(bus->sdiodev, false, sh->trap_addr, (u8 *)&tr,
2980                                  sizeof(struct brcmf_trap_info));
2981        if (error < 0)
2982                return error;
2983
2984        seq_printf(seq,
2985                   "dongle trap info: type 0x%x @ epc 0x%08x\n"
2986                   "  cpsr 0x%08x spsr 0x%08x sp 0x%08x\n"
2987                   "  lr   0x%08x pc   0x%08x offset 0x%x\n"
2988                   "  r0   0x%08x r1   0x%08x r2 0x%08x r3 0x%08x\n"
2989                   "  r4   0x%08x r5   0x%08x r6 0x%08x r7 0x%08x\n",
2990                   le32_to_cpu(tr.type), le32_to_cpu(tr.epc),
2991                   le32_to_cpu(tr.cpsr), le32_to_cpu(tr.spsr),
2992                   le32_to_cpu(tr.r13), le32_to_cpu(tr.r14),
2993                   le32_to_cpu(tr.pc), sh->trap_addr,
2994                   le32_to_cpu(tr.r0), le32_to_cpu(tr.r1),
2995                   le32_to_cpu(tr.r2), le32_to_cpu(tr.r3),
2996                   le32_to_cpu(tr.r4), le32_to_cpu(tr.r5),
2997                   le32_to_cpu(tr.r6), le32_to_cpu(tr.r7));
2998
2999        return 0;
3000}
3001
3002static int brcmf_sdio_assert_info(struct seq_file *seq, struct brcmf_sdio *bus,
3003                                  struct sdpcm_shared *sh)
3004{
3005        int error = 0;
3006        char file[80] = "?";
3007        char expr[80] = "<???>";
3008
3009        if ((sh->flags & SDPCM_SHARED_ASSERT_BUILT) == 0) {
3010                brcmf_dbg(INFO, "firmware not built with -assert\n");
3011                return 0;
3012        } else if ((sh->flags & SDPCM_SHARED_ASSERT) == 0) {
3013                brcmf_dbg(INFO, "no assert in dongle\n");
3014                return 0;
3015        }
3016
3017        sdio_claim_host(bus->sdiodev->func[1]);
3018        if (sh->assert_file_addr != 0) {
3019                error = brcmf_sdiod_ramrw(bus->sdiodev, false,
3020                                          sh->assert_file_addr, (u8 *)file, 80);
3021                if (error < 0)
3022                        return error;
3023        }
3024        if (sh->assert_exp_addr != 0) {
3025                error = brcmf_sdiod_ramrw(bus->sdiodev, false,
3026                                          sh->assert_exp_addr, (u8 *)expr, 80);
3027                if (error < 0)
3028                        return error;
3029        }
3030        sdio_release_host(bus->sdiodev->func[1]);
3031
3032        seq_printf(seq, "dongle assert: %s:%d: assert(%s)\n",
3033                   file, sh->assert_line, expr);
3034        return 0;
3035}
3036
3037static int brcmf_sdio_checkdied(struct brcmf_sdio *bus)
3038{
3039        int error;
3040        struct sdpcm_shared sh;
3041
3042        error = brcmf_sdio_readshared(bus, &sh);
3043
3044        if (error < 0)
3045                return error;
3046
3047        if ((sh.flags & SDPCM_SHARED_ASSERT_BUILT) == 0)
3048                brcmf_dbg(INFO, "firmware not built with -assert\n");
3049        else if (sh.flags & SDPCM_SHARED_ASSERT)
3050                brcmf_err("assertion in dongle\n");
3051
3052        if (sh.flags & SDPCM_SHARED_TRAP)
3053                brcmf_err("firmware trap in dongle\n");
3054
3055        return 0;
3056}
3057
3058static int brcmf_sdio_died_dump(struct seq_file *seq, struct brcmf_sdio *bus)
3059{
3060        int error = 0;
3061        struct sdpcm_shared sh;
3062
3063        error = brcmf_sdio_readshared(bus, &sh);
3064        if (error < 0)
3065                goto done;
3066
3067        error = brcmf_sdio_assert_info(seq, bus, &sh);
3068        if (error < 0)
3069                goto done;
3070
3071        error = brcmf_sdio_trap_info(seq, bus, &sh);
3072        if (error < 0)
3073                goto done;
3074
3075        error = brcmf_sdio_dump_console(seq, bus, &sh);
3076
3077done:
3078        return error;
3079}
3080
3081static int brcmf_sdio_forensic_read(struct seq_file *seq, void *data)
3082{
3083        struct brcmf_bus *bus_if = dev_get_drvdata(seq->private);
3084        struct brcmf_sdio *bus = bus_if->bus_priv.sdio->bus;
3085
3086        return brcmf_sdio_died_dump(seq, bus);
3087}
3088
3089static int brcmf_debugfs_sdio_count_read(struct seq_file *seq, void *data)
3090{
3091        struct brcmf_bus *bus_if = dev_get_drvdata(seq->private);
3092        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3093        struct brcmf_sdio_count *sdcnt = &sdiodev->bus->sdcnt;
3094
3095        seq_printf(seq,
3096                   "intrcount:    %u\nlastintrs:    %u\n"
3097                   "pollcnt:      %u\nregfails:     %u\n"
3098                   "tx_sderrs:    %u\nfcqueued:     %u\n"
3099                   "rxrtx:        %u\nrx_toolong:   %u\n"
3100                   "rxc_errors:   %u\nrx_hdrfail:   %u\n"
3101                   "rx_badhdr:    %u\nrx_badseq:    %u\n"
3102                   "fc_rcvd:      %u\nfc_xoff:      %u\n"
3103                   "fc_xon:       %u\nrxglomfail:   %u\n"
3104                   "rxglomframes: %u\nrxglompkts:   %u\n"
3105                   "f2rxhdrs:     %u\nf2rxdata:     %u\n"
3106                   "f2txdata:     %u\nf1regdata:    %u\n"
3107                   "tickcnt:      %u\ntx_ctlerrs:   %lu\n"
3108                   "tx_ctlpkts:   %lu\nrx_ctlerrs:   %lu\n"
3109                   "rx_ctlpkts:   %lu\nrx_readahead: %lu\n",
3110                   sdcnt->intrcount, sdcnt->lastintrs,
3111                   sdcnt->pollcnt, sdcnt->regfails,
3112                   sdcnt->tx_sderrs, sdcnt->fcqueued,
3113                   sdcnt->rxrtx, sdcnt->rx_toolong,
3114                   sdcnt->rxc_errors, sdcnt->rx_hdrfail,
3115                   sdcnt->rx_badhdr, sdcnt->rx_badseq,
3116                   sdcnt->fc_rcvd, sdcnt->fc_xoff,
3117                   sdcnt->fc_xon, sdcnt->rxglomfail,
3118                   sdcnt->rxglomframes, sdcnt->rxglompkts,
3119                   sdcnt->f2rxhdrs, sdcnt->f2rxdata,
3120                   sdcnt->f2txdata, sdcnt->f1regdata,
3121                   sdcnt->tickcnt, sdcnt->tx_ctlerrs,
3122                   sdcnt->tx_ctlpkts, sdcnt->rx_ctlerrs,
3123                   sdcnt->rx_ctlpkts, sdcnt->rx_readahead_cnt);
3124
3125        return 0;
3126}
3127
3128static void brcmf_sdio_debugfs_create(struct brcmf_sdio *bus)
3129{
3130        struct brcmf_pub *drvr = bus->sdiodev->bus_if->drvr;
3131        struct dentry *dentry = brcmf_debugfs_get_devdir(drvr);
3132
3133        if (IS_ERR_OR_NULL(dentry))
3134                return;
3135
3136        bus->console_interval = BRCMF_CONSOLE;
3137
3138        brcmf_debugfs_add_entry(drvr, "forensics", brcmf_sdio_forensic_read);
3139        brcmf_debugfs_add_entry(drvr, "counters",
3140                                brcmf_debugfs_sdio_count_read);
3141        debugfs_create_u32("console_interval", 0644, dentry,
3142                           &bus->console_interval);
3143}
3144#else
3145static int brcmf_sdio_checkdied(struct brcmf_sdio *bus)
3146{
3147        return 0;
3148}
3149
3150static void brcmf_sdio_debugfs_create(struct brcmf_sdio *bus)
3151{
3152}
3153#endif /* DEBUG */
3154
3155static int
3156brcmf_sdio_bus_rxctl(struct device *dev, unsigned char *msg, uint msglen)
3157{
3158        int timeleft;
3159        uint rxlen = 0;
3160        bool pending;
3161        u8 *buf;
3162        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3163        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3164        struct brcmf_sdio *bus = sdiodev->bus;
3165
3166        brcmf_dbg(TRACE, "Enter\n");
3167        if (sdiodev->state != BRCMF_SDIOD_DATA)
3168                return -EIO;
3169
3170        /* Wait until control frame is available */
3171        timeleft = brcmf_sdio_dcmd_resp_wait(bus, &bus->rxlen, &pending);
3172
3173        spin_lock_bh(&bus->rxctl_lock);
3174        rxlen = bus->rxlen;
3175        memcpy(msg, bus->rxctl, min(msglen, rxlen));
3176        bus->rxctl = NULL;
3177        buf = bus->rxctl_orig;
3178        bus->rxctl_orig = NULL;
3179        bus->rxlen = 0;
3180        spin_unlock_bh(&bus->rxctl_lock);
3181        vfree(buf);
3182
3183        if (rxlen) {
3184                brcmf_dbg(CTL, "resumed on rxctl frame, got %d expected %d\n",
3185                          rxlen, msglen);
3186        } else if (timeleft == 0) {
3187                brcmf_err("resumed on timeout\n");
3188                brcmf_sdio_checkdied(bus);
3189        } else if (pending) {
3190                brcmf_dbg(CTL, "cancelled\n");
3191                return -ERESTARTSYS;
3192        } else {
3193                brcmf_dbg(CTL, "resumed for unknown reason?\n");
3194                brcmf_sdio_checkdied(bus);
3195        }
3196
3197        if (rxlen)
3198                bus->sdcnt.rx_ctlpkts++;
3199        else
3200                bus->sdcnt.rx_ctlerrs++;
3201
3202        return rxlen ? (int)rxlen : -ETIMEDOUT;
3203}
3204
3205#ifdef DEBUG
3206static bool
3207brcmf_sdio_verifymemory(struct brcmf_sdio_dev *sdiodev, u32 ram_addr,
3208                        u8 *ram_data, uint ram_sz)
3209{
3210        char *ram_cmp;
3211        int err;
3212        bool ret = true;
3213        int address;
3214        int offset;
3215        int len;
3216
3217        /* read back and verify */
3218        brcmf_dbg(INFO, "Compare RAM dl & ul at 0x%08x; size=%d\n", ram_addr,
3219                  ram_sz);
3220        ram_cmp = kmalloc(MEMBLOCK, GFP_KERNEL);
3221        /* do not proceed while no memory but  */
3222        if (!ram_cmp)
3223                return true;
3224
3225        address = ram_addr;
3226        offset = 0;
3227        while (offset < ram_sz) {
3228                len = ((offset + MEMBLOCK) < ram_sz) ? MEMBLOCK :
3229                      ram_sz - offset;
3230                err = brcmf_sdiod_ramrw(sdiodev, false, address, ram_cmp, len);
3231                if (err) {
3232                        brcmf_err("error %d on reading %d membytes at 0x%08x\n",
3233                                  err, len, address);
3234                        ret = false;
3235                        break;
3236                } else if (memcmp(ram_cmp, &ram_data[offset], len)) {
3237                        brcmf_err("Downloaded RAM image is corrupted, block offset is %d, len is %d\n",
3238                                  offset, len);
3239                        ret = false;
3240                        break;
3241                }
3242                offset += len;
3243                address += len;
3244        }
3245
3246        kfree(ram_cmp);
3247
3248        return ret;
3249}
3250#else   /* DEBUG */
3251static bool
3252brcmf_sdio_verifymemory(struct brcmf_sdio_dev *sdiodev, u32 ram_addr,
3253                        u8 *ram_data, uint ram_sz)
3254{
3255        return true;
3256}
3257#endif  /* DEBUG */
3258
3259static int brcmf_sdio_download_code_file(struct brcmf_sdio *bus,
3260                                         const struct firmware *fw)
3261{
3262        int err;
3263
3264        brcmf_dbg(TRACE, "Enter\n");
3265
3266        err = brcmf_sdiod_ramrw(bus->sdiodev, true, bus->ci->rambase,
3267                                (u8 *)fw->data, fw->size);
3268        if (err)
3269                brcmf_err("error %d on writing %d membytes at 0x%08x\n",
3270                          err, (int)fw->size, bus->ci->rambase);
3271        else if (!brcmf_sdio_verifymemory(bus->sdiodev, bus->ci->rambase,
3272                                          (u8 *)fw->data, fw->size))
3273                err = -EIO;
3274
3275        return err;
3276}
3277
3278static int brcmf_sdio_download_nvram(struct brcmf_sdio *bus,
3279                                     void *vars, u32 varsz)
3280{
3281        int address;
3282        int err;
3283
3284        brcmf_dbg(TRACE, "Enter\n");
3285
3286        address = bus->ci->ramsize - varsz + bus->ci->rambase;
3287        err = brcmf_sdiod_ramrw(bus->sdiodev, true, address, vars, varsz);
3288        if (err)
3289                brcmf_err("error %d on writing %d nvram bytes at 0x%08x\n",
3290                          err, varsz, address);
3291        else if (!brcmf_sdio_verifymemory(bus->sdiodev, address, vars, varsz))
3292                err = -EIO;
3293
3294        return err;
3295}
3296
3297static int brcmf_sdio_download_firmware(struct brcmf_sdio *bus,
3298                                        const struct firmware *fw,
3299                                        void *nvram, u32 nvlen)
3300{
3301        int bcmerror;
3302        u32 rstvec;
3303
3304        sdio_claim_host(bus->sdiodev->func[1]);
3305        brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
3306
3307        rstvec = get_unaligned_le32(fw->data);
3308        brcmf_dbg(SDIO, "firmware rstvec: %x\n", rstvec);
3309
3310        bcmerror = brcmf_sdio_download_code_file(bus, fw);
3311        release_firmware(fw);
3312        if (bcmerror) {
3313                brcmf_err("dongle image file download failed\n");
3314                brcmf_fw_nvram_free(nvram);
3315                goto err;
3316        }
3317
3318        bcmerror = brcmf_sdio_download_nvram(bus, nvram, nvlen);
3319        brcmf_fw_nvram_free(nvram);
3320        if (bcmerror) {
3321                brcmf_err("dongle nvram file download failed\n");
3322                goto err;
3323        }
3324
3325        /* Take arm out of reset */
3326        if (!brcmf_chip_set_active(bus->ci, rstvec)) {
3327                brcmf_err("error getting out of ARM core reset\n");
3328                goto err;
3329        }
3330
3331err:
3332        brcmf_sdio_clkctl(bus, CLK_SDONLY, false);
3333        sdio_release_host(bus->sdiodev->func[1]);
3334        return bcmerror;
3335}
3336
3337static void brcmf_sdio_sr_init(struct brcmf_sdio *bus)
3338{
3339        int err = 0;
3340        u8 val;
3341
3342        brcmf_dbg(TRACE, "Enter\n");
3343
3344        val = brcmf_sdiod_regrb(bus->sdiodev, SBSDIO_FUNC1_WAKEUPCTRL, &err);
3345        if (err) {
3346                brcmf_err("error reading SBSDIO_FUNC1_WAKEUPCTRL\n");
3347                return;
3348        }
3349
3350        val |= 1 << SBSDIO_FUNC1_WCTRL_HTWAIT_SHIFT;
3351        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_WAKEUPCTRL, val, &err);
3352        if (err) {
3353                brcmf_err("error writing SBSDIO_FUNC1_WAKEUPCTRL\n");
3354                return;
3355        }
3356
3357        /* Add CMD14 Support */
3358        brcmf_sdiod_regwb(bus->sdiodev, SDIO_CCCR_BRCM_CARDCAP,
3359                          (SDIO_CCCR_BRCM_CARDCAP_CMD14_SUPPORT |
3360                           SDIO_CCCR_BRCM_CARDCAP_CMD14_EXT),
3361                          &err);
3362        if (err) {
3363                brcmf_err("error writing SDIO_CCCR_BRCM_CARDCAP\n");
3364                return;
3365        }
3366
3367        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3368                          SBSDIO_FORCE_HT, &err);
3369        if (err) {
3370                brcmf_err("error writing SBSDIO_FUNC1_CHIPCLKCSR\n");
3371                return;
3372        }
3373
3374        /* set flag */
3375        bus->sr_enabled = true;
3376        brcmf_dbg(INFO, "SR enabled\n");
3377}
3378
3379/* enable KSO bit */
3380static int brcmf_sdio_kso_init(struct brcmf_sdio *bus)
3381{
3382        u8 val;
3383        int err = 0;
3384
3385        brcmf_dbg(TRACE, "Enter\n");
3386
3387        /* KSO bit added in SDIO core rev 12 */
3388        if (brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV)->rev < 12)
3389                return 0;
3390
3391        val = brcmf_sdiod_regrb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR, &err);
3392        if (err) {
3393                brcmf_err("error reading SBSDIO_FUNC1_SLEEPCSR\n");
3394                return err;
3395        }
3396
3397        if (!(val & SBSDIO_FUNC1_SLEEPCSR_KSO_MASK)) {
3398                val |= (SBSDIO_FUNC1_SLEEPCSR_KSO_EN <<
3399                        SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT);
3400                brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
3401                                  val, &err);
3402                if (err) {
3403                        brcmf_err("error writing SBSDIO_FUNC1_SLEEPCSR\n");
3404                        return err;
3405                }
3406        }
3407
3408        return 0;
3409}
3410
3411
3412static int brcmf_sdio_bus_preinit(struct device *dev)
3413{
3414        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3415        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3416        struct brcmf_sdio *bus = sdiodev->bus;
3417        uint pad_size;
3418        u32 value;
3419        int err;
3420
3421        /* the commands below use the terms tx and rx from
3422         * a device perspective, ie. bus:txglom affects the
3423         * bus transfers from device to host.
3424         */
3425        if (brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV)->rev < 12) {
3426                /* for sdio core rev < 12, disable txgloming */
3427                value = 0;
3428                err = brcmf_iovar_data_set(dev, "bus:txglom", &value,
3429                                           sizeof(u32));
3430        } else {
3431                /* otherwise, set txglomalign */
3432                value = sdiodev->settings->bus.sdio.sd_sgentry_align;
3433                /* SDIO ADMA requires at least 32 bit alignment */
3434                value = max_t(u32, value, ALIGNMENT);
3435                err = brcmf_iovar_data_set(dev, "bus:txglomalign", &value,
3436                                           sizeof(u32));
3437        }
3438
3439        if (err < 0)
3440                goto done;
3441
3442        bus->tx_hdrlen = SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN;
3443        if (sdiodev->sg_support) {
3444                bus->txglom = false;
3445                value = 1;
3446                pad_size = bus->sdiodev->func[2]->cur_blksize << 1;
3447                err = brcmf_iovar_data_set(bus->sdiodev->dev, "bus:rxglom",
3448                                           &value, sizeof(u32));
3449                if (err < 0) {
3450                        /* bus:rxglom is allowed to fail */
3451                        err = 0;
3452                } else {
3453                        bus->txglom = true;
3454                        bus->tx_hdrlen += SDPCM_HWEXT_LEN;
3455                }
3456        }
3457        brcmf_bus_add_txhdrlen(bus->sdiodev->dev, bus->tx_hdrlen);
3458
3459done:
3460        return err;
3461}
3462
3463static size_t brcmf_sdio_bus_get_ramsize(struct device *dev)
3464{
3465        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3466        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3467        struct brcmf_sdio *bus = sdiodev->bus;
3468
3469        return bus->ci->ramsize - bus->ci->srsize;
3470}
3471
3472static int brcmf_sdio_bus_get_memdump(struct device *dev, void *data,
3473                                      size_t mem_size)
3474{
3475        struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3476        struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3477        struct brcmf_sdio *bus = sdiodev->bus;
3478        int err;
3479        int address;
3480        int offset;
3481        int len;
3482
3483        brcmf_dbg(INFO, "dump at 0x%08x: size=%zu\n", bus->ci->rambase,
3484                  mem_size);
3485
3486        address = bus->ci->rambase;
3487        offset = err = 0;
3488        sdio_claim_host(sdiodev->func[1]);
3489        while (offset < mem_size) {
3490                len = ((offset + MEMBLOCK) < mem_size) ? MEMBLOCK :
3491                      mem_size - offset;
3492                err = brcmf_sdiod_ramrw(sdiodev, false, address, data, len);
3493                if (err) {
3494                        brcmf_err("error %d on reading %d membytes at 0x%08x\n",
3495                                  err, len, address);
3496                        goto done;
3497                }
3498                data += len;
3499                offset += len;
3500                address += len;
3501        }
3502
3503done:
3504        sdio_release_host(sdiodev->func[1]);
3505        return err;
3506}
3507
3508void brcmf_sdio_trigger_dpc(struct brcmf_sdio *bus)
3509{
3510        if (!bus->dpc_triggered) {
3511                bus->dpc_triggered = true;
3512                queue_work(bus->brcmf_wq, &bus->datawork);
3513        }
3514}
3515
3516void brcmf_sdio_isr(struct brcmf_sdio *bus)
3517{
3518        brcmf_dbg(TRACE, "Enter\n");
3519
3520        if (!bus) {
3521                brcmf_err("bus is null pointer, exiting\n");
3522                return;
3523        }
3524
3525        /* Count the interrupt call */
3526        bus->sdcnt.intrcount++;
3527        if (in_interrupt())
3528                atomic_set(&bus->ipend, 1);
3529        else
3530                if (brcmf_sdio_intr_rstatus(bus)) {
3531                        brcmf_err("failed backplane access\n");
3532                }
3533
3534        /* Disable additional interrupts (is this needed now)? */
3535        if (!bus->intr)
3536                brcmf_err("isr w/o interrupt configured!\n");
3537
3538        bus->dpc_triggered = true;
3539        queue_work(bus->brcmf_wq, &bus->datawork);
3540}
3541
3542static void brcmf_sdio_bus_watchdog(struct brcmf_sdio *bus)
3543{
3544        brcmf_dbg(TIMER, "Enter\n");
3545
3546        /* Poll period: check device if appropriate. */
3547        if (!bus->sr_enabled &&
3548            bus->poll && (++bus->polltick >= bus->pollrate)) {
3549                u32 intstatus = 0;
3550
3551                /* Reset poll tick */
3552                bus->polltick = 0;
3553
3554                /* Check device if no interrupts */
3555                if (!bus->intr ||
3556                    (bus->sdcnt.intrcount == bus->sdcnt.lastintrs)) {
3557
3558                        if (!bus->dpc_triggered) {
3559                                u8 devpend;
3560
3561                                sdio_claim_host(bus->sdiodev->func[1]);
3562                                devpend = brcmf_sdiod_regrb(bus->sdiodev,
3563                                                            SDIO_CCCR_INTx,
3564                                                            NULL);
3565                                sdio_release_host(bus->sdiodev->func[1]);
3566                                intstatus = devpend & (INTR_STATUS_FUNC1 |
3567                                                       INTR_STATUS_FUNC2);
3568                        }
3569
3570                        /* If there is something, make like the ISR and
3571                                 schedule the DPC */
3572                        if (intstatus) {
3573                                bus->sdcnt.pollcnt++;
3574                                atomic_set(&bus->ipend, 1);
3575
3576                                bus->dpc_triggered = true;
3577                                queue_work(bus->brcmf_wq, &bus->datawork);
3578                        }
3579                }
3580
3581                /* Update interrupt tracking */
3582                bus->sdcnt.lastintrs = bus->sdcnt.intrcount;
3583        }
3584#ifdef DEBUG
3585        /* Poll for console output periodically */
3586        if (bus->sdiodev->state == BRCMF_SDIOD_DATA && BRCMF_FWCON_ON() &&
3587            bus->console_interval != 0) {
3588                bus->console.count += jiffies_to_msecs(BRCMF_WD_POLL);
3589                if (bus->console.count >= bus->console_interval) {
3590                        bus->console.count -= bus->console_interval;
3591                        sdio_claim_host(bus->sdiodev->func[1]);
3592                        /* Make sure backplane clock is on */
3593                        brcmf_sdio_bus_sleep(bus, false, false);
3594                        if (brcmf_sdio_readconsole(bus) < 0)
3595                                /* stop on error */
3596                                bus->console_interval = 0;
3597                        sdio_release_host(bus->sdiodev->func[1]);
3598                }
3599        }
3600#endif                          /* DEBUG */
3601
3602        /* On idle timeout clear activity flag and/or turn off clock */
3603        if (!bus->dpc_triggered) {
3604                rmb();
3605                if ((!bus->dpc_running) && (bus->idletime > 0) &&
3606                    (bus->clkstate == CLK_AVAIL)) {
3607                        bus->idlecount++;
3608                        if (bus->idlecount > bus->idletime) {
3609                                brcmf_dbg(SDIO, "idle\n");
3610                                sdio_claim_host(bus->sdiodev->func[1]);
3611                                brcmf_sdio_wd_timer(bus, false);
3612                                bus->idlecount = 0;
3613                                brcmf_sdio_bus_sleep(bus, true, false);
3614                                sdio_release_host(bus->sdiodev->func[1]);
3615                        }
3616                } else {
3617                        bus->idlecount = 0;
3618                }
3619        } else {
3620                bus->idlecount = 0;
3621        }
3622}
3623
3624static void brcmf_sdio_dataworker(struct work_struct *work)
3625{
3626        struct brcmf_sdio *bus = container_of(work, struct brcmf_sdio,
3627                                              datawork);
3628
3629        bus->dpc_running = true;
3630        wmb();
3631        while (ACCESS_ONCE(bus->dpc_triggered)) {
3632                bus->dpc_triggered = false;
3633                brcmf_sdio_dpc(bus);
3634                bus->idlecount = 0;
3635        }
3636        bus->dpc_running = false;
3637        if (brcmf_sdiod_freezing(bus->sdiodev)) {
3638                brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DOWN);
3639                brcmf_sdiod_try_freeze(bus->sdiodev);
3640                brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DATA);
3641        }
3642}
3643
3644static void
3645brcmf_sdio_drivestrengthinit(struct brcmf_sdio_dev *sdiodev,
3646                             struct brcmf_chip *ci, u32 drivestrength)
3647{
3648        const struct sdiod_drive_str *str_tab = NULL;
3649        u32 str_mask;
3650        u32 str_shift;
3651        u32 i;
3652        u32 drivestrength_sel = 0;
3653        u32 cc_data_temp;
3654        u32 addr;
3655
3656        if (!(ci->cc_caps & CC_CAP_PMU))
3657                return;
3658
3659        switch (SDIOD_DRVSTR_KEY(ci->chip, ci->pmurev)) {
3660        case SDIOD_DRVSTR_KEY(BRCM_CC_4330_CHIP_ID, 12):
3661                str_tab = sdiod_drvstr_tab1_1v8;
3662                str_mask = 0x00003800;
3663                str_shift = 11;
3664                break;
3665        case SDIOD_DRVSTR_KEY(BRCM_CC_4334_CHIP_ID, 17):
3666                str_tab = sdiod_drvstr_tab6_1v8;
3667                str_mask = 0x00001800;
3668                str_shift = 11;
3669                break;
3670        case SDIOD_DRVSTR_KEY(BRCM_CC_43143_CHIP_ID, 17):
3671                /* note: 43143 does not support tristate */
3672                i = ARRAY_SIZE(sdiod_drvstr_tab2_3v3) - 1;
3673                if (drivestrength >= sdiod_drvstr_tab2_3v3[i].strength) {
3674                        str_tab = sdiod_drvstr_tab2_3v3;
3675                        str_mask = 0x00000007;
3676                        str_shift = 0;
3677                } else
3678                        brcmf_err("Invalid SDIO Drive strength for chip %s, strength=%d\n",
3679                                  ci->name, drivestrength);
3680                break;
3681        case SDIOD_DRVSTR_KEY(BRCM_CC_43362_CHIP_ID, 13):
3682                str_tab = sdiod_drive_strength_tab5_1v8;
3683                str_mask = 0x00003800;
3684                str_shift = 11;
3685                break;
3686        default:
3687                brcmf_dbg(INFO, "No SDIO driver strength init needed for chip %s rev %d pmurev %d\n",
3688                          ci->name, ci->chiprev, ci->pmurev);
3689                break;
3690        }
3691
3692        if (str_tab != NULL) {
3693                struct brcmf_core *pmu = brcmf_chip_get_pmu(ci);
3694
3695                for (i = 0; str_tab[i].strength != 0; i++) {
3696                        if (drivestrength >= str_tab[i].strength) {
3697                                drivestrength_sel = str_tab[i].sel;
3698                                break;
3699                        }
3700                }
3701                addr = CORE_CC_REG(pmu->base, chipcontrol_addr);
3702                brcmf_sdiod_regwl(sdiodev, addr, 1, NULL);
3703                cc_data_temp = brcmf_sdiod_regrl(sdiodev, addr, NULL);
3704                cc_data_temp &= ~str_mask;
3705                drivestrength_sel <<= str_shift;
3706                cc_data_temp |= drivestrength_sel;
3707                brcmf_sdiod_regwl(sdiodev, addr, cc_data_temp, NULL);
3708
3709                brcmf_dbg(INFO, "SDIO: %d mA (req=%d mA) drive strength selected, set to 0x%08x\n",
3710                          str_tab[i].strength, drivestrength, cc_data_temp);
3711        }
3712}
3713
3714static int brcmf_sdio_buscoreprep(void *ctx)
3715{
3716        struct brcmf_sdio_dev *sdiodev = ctx;
3717        int err = 0;
3718        u8 clkval, clkset;
3719
3720        /* Try forcing SDIO core to do ALPAvail request only */
3721        clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
3722        brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
3723        if (err) {
3724                brcmf_err("error writing for HT off\n");
3725                return err;
3726        }
3727
3728        /* If register supported, wait for ALPAvail and then force ALP */
3729        /* This may take up to 15 milliseconds */
3730        clkval = brcmf_sdiod_regrb(sdiodev,
3731                                   SBSDIO_FUNC1_CHIPCLKCSR, NULL);
3732
3733        if ((clkval & ~SBSDIO_AVBITS) != clkset) {
3734                brcmf_err("ChipClkCSR access: wrote 0x%02x read 0x%02x\n",
3735                          clkset, clkval);
3736                return -EACCES;
3737        }
3738
3739        SPINWAIT(((clkval = brcmf_sdiod_regrb(sdiodev,
3740                                              SBSDIO_FUNC1_CHIPCLKCSR, NULL)),
3741                        !SBSDIO_ALPAV(clkval)),
3742                        PMU_MAX_TRANSITION_DLY);
3743        if (!SBSDIO_ALPAV(clkval)) {
3744                brcmf_err("timeout on ALPAV wait, clkval 0x%02x\n",
3745                          clkval);
3746                return -EBUSY;
3747        }
3748
3749        clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP;
3750        brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
3751        udelay(65);
3752
3753        /* Also, disable the extra SDIO pull-ups */
3754        brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_SDIOPULLUP, 0, NULL);
3755
3756        return 0;
3757}
3758
3759static void brcmf_sdio_buscore_activate(void *ctx, struct brcmf_chip *chip,
3760                                        u32 rstvec)
3761{
3762        struct brcmf_sdio_dev *sdiodev = ctx;
3763        struct brcmf_core *core;
3764        u32 reg_addr;
3765
3766        /* clear all interrupts */
3767        core = brcmf_chip_get_core(chip, BCMA_CORE_SDIO_DEV);
3768        reg_addr = core->base + offsetof(struct sdpcmd_regs, intstatus);
3769        brcmf_sdiod_regwl(sdiodev, reg_addr, 0xFFFFFFFF, NULL);
3770
3771        if (rstvec)
3772                /* Write reset vector to address 0 */
3773                brcmf_sdiod_ramrw(sdiodev, true, 0, (void *)&rstvec,
3774                                  sizeof(rstvec));
3775}
3776
3777static u32 brcmf_sdio_buscore_read32(void *ctx, u32 addr)
3778{
3779        struct brcmf_sdio_dev *sdiodev = ctx;
3780        u32 val, rev;
3781
3782        val = brcmf_sdiod_regrl(sdiodev, addr, NULL);
3783        if ((sdiodev->func[0]->device == SDIO_DEVICE_ID_BROADCOM_4335_4339 ||
3784             sdiodev->func[0]->device == SDIO_DEVICE_ID_BROADCOM_4339) &&
3785            addr == CORE_CC_REG(SI_ENUM_BASE, chipid)) {
3786                rev = (val & CID_REV_MASK) >> CID_REV_SHIFT;
3787                if (rev >= 2) {
3788                        val &= ~CID_ID_MASK;
3789                        val |= BRCM_CC_4339_CHIP_ID;
3790                }
3791        }
3792        return val;
3793}
3794
3795static void brcmf_sdio_buscore_write32(void *ctx, u32 addr, u32 val)
3796{
3797        struct brcmf_sdio_dev *sdiodev = ctx;
3798
3799        brcmf_sdiod_regwl(sdiodev, addr, val, NULL);
3800}
3801
3802static const struct brcmf_buscore_ops brcmf_sdio_buscore_ops = {
3803        .prepare = brcmf_sdio_buscoreprep,
3804        .activate = brcmf_sdio_buscore_activate,
3805        .read32 = brcmf_sdio_buscore_read32,
3806        .write32 = brcmf_sdio_buscore_write32,
3807};
3808
3809static bool
3810brcmf_sdio_probe_attach(struct brcmf_sdio *bus)
3811{
3812        struct brcmf_sdio_dev *sdiodev;
3813        u8 clkctl = 0;
3814        int err = 0;
3815        int reg_addr;
3816        u32 reg_val;
3817        u32 drivestrength;
3818
3819        sdiodev = bus->sdiodev;
3820        sdio_claim_host(sdiodev->func[1]);
3821
3822        pr_debug("F1 signature read @0x18000000=0x%4x\n",
3823                 brcmf_sdiod_regrl(sdiodev, SI_ENUM_BASE, NULL));
3824
3825        /*
3826         * Force PLL off until brcmf_chip_attach()
3827         * programs PLL control regs
3828         */
3829
3830        brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3831                          BRCMF_INIT_CLKCTL1, &err);
3832        if (!err)
3833                clkctl = brcmf_sdiod_regrb(sdiodev,
3834                                           SBSDIO_FUNC1_CHIPCLKCSR, &err);
3835
3836        if (err || ((clkctl & ~SBSDIO_AVBITS) != BRCMF_INIT_CLKCTL1)) {
3837                brcmf_err("ChipClkCSR access: err %d wrote 0x%02x read 0x%02x\n",
3838                          err, BRCMF_INIT_CLKCTL1, clkctl);
3839                goto fail;
3840        }
3841
3842        bus->ci = brcmf_chip_attach(sdiodev, &brcmf_sdio_buscore_ops);
3843        if (IS_ERR(bus->ci)) {
3844                brcmf_err("brcmf_chip_attach failed!\n");
3845                bus->ci = NULL;
3846                goto fail;
3847        }
3848        sdiodev->settings = brcmf_get_module_param(sdiodev->dev,
3849                                                   BRCMF_BUSTYPE_SDIO,
3850                                                   bus->ci->chip,
3851                                                   bus->ci->chiprev);
3852        if (!sdiodev->settings) {
3853                brcmf_err("Failed to get device parameters\n");
3854                goto fail;
3855        }
3856        /* platform specific configuration:
3857         *   alignments must be at least 4 bytes for ADMA
3858         */
3859        bus->head_align = ALIGNMENT;
3860        bus->sgentry_align = ALIGNMENT;
3861        if (sdiodev->settings->bus.sdio.sd_head_align > ALIGNMENT)
3862                bus->head_align = sdiodev->settings->bus.sdio.sd_head_align;
3863        if (sdiodev->settings->bus.sdio.sd_sgentry_align > ALIGNMENT)
3864                bus->sgentry_align =
3865                                sdiodev->settings->bus.sdio.sd_sgentry_align;
3866
3867        /* allocate scatter-gather table. sg support
3868         * will be disabled upon allocation failure.
3869         */
3870        brcmf_sdiod_sgtable_alloc(sdiodev);
3871
3872#ifdef CONFIG_PM_SLEEP
3873        /* wowl can be supported when KEEP_POWER is true and (WAKE_SDIO_IRQ
3874         * is true or when platform data OOB irq is true).
3875         */
3876        if ((sdio_get_host_pm_caps(sdiodev->func[1]) & MMC_PM_KEEP_POWER) &&
3877            ((sdio_get_host_pm_caps(sdiodev->func[1]) & MMC_PM_WAKE_SDIO_IRQ) ||
3878             (sdiodev->settings->bus.sdio.oob_irq_supported)))
3879                sdiodev->bus_if->wowl_supported = true;
3880#endif
3881
3882        if (brcmf_sdio_kso_init(bus)) {
3883                brcmf_err("error enabling KSO\n");
3884                goto fail;
3885        }
3886
3887        if (sdiodev->settings->bus.sdio.drive_strength)
3888                drivestrength = sdiodev->settings->bus.sdio.drive_strength;
3889        else
3890                drivestrength = DEFAULT_SDIO_DRIVE_STRENGTH;
3891        brcmf_sdio_drivestrengthinit(sdiodev, bus->ci, drivestrength);
3892
3893        /* Set card control so an SDIO card reset does a WLAN backplane reset */
3894        reg_val = brcmf_sdiod_regrb(sdiodev, SDIO_CCCR_BRCM_CARDCTRL, &err);
3895        if (err)
3896                goto fail;
3897
3898        reg_val |= SDIO_CCCR_BRCM_CARDCTRL_WLANRESET;
3899
3900        brcmf_sdiod_regwb(sdiodev, SDIO_CCCR_BRCM_CARDCTRL, reg_val, &err);
3901        if (err)
3902                goto fail;
3903
3904        /* set PMUControl so a backplane reset does PMU state reload */
3905        reg_addr = CORE_CC_REG(brcmf_chip_get_pmu(bus->ci)->base, pmucontrol);
3906        reg_val = brcmf_sdiod_regrl(sdiodev, reg_addr, &err);
3907        if (err)
3908                goto fail;
3909
3910        reg_val |= (BCMA_CC_PMU_CTL_RES_RELOAD << BCMA_CC_PMU_CTL_RES_SHIFT);
3911
3912        brcmf_sdiod_regwl(sdiodev, reg_addr, reg_val, &err);
3913        if (err)
3914                goto fail;
3915
3916        sdio_release_host(sdiodev->func[1]);
3917
3918        brcmu_pktq_init(&bus->txq, (PRIOMASK + 1), TXQLEN);
3919
3920        /* allocate header buffer */
3921        bus->hdrbuf = kzalloc(MAX_HDR_READ + bus->head_align, GFP_KERNEL);
3922        if (!bus->hdrbuf)
3923                return false;
3924        /* Locate an appropriately-aligned portion of hdrbuf */
3925        bus->rxhdr = (u8 *) roundup((unsigned long)&bus->hdrbuf[0],
3926                                    bus->head_align);
3927
3928        /* Set the poll and/or interrupt flags */
3929        bus->intr = true;
3930        bus->poll = false;
3931        if (bus->poll)
3932                bus->pollrate = 1;
3933
3934        return true;
3935
3936fail:
3937        sdio_release_host(sdiodev->func[1]);
3938        return false;
3939}
3940
3941static int
3942brcmf_sdio_watchdog_thread(void *data)
3943{
3944        struct brcmf_sdio *bus = (struct brcmf_sdio *)data;
3945        int wait;
3946
3947        allow_signal(SIGTERM);
3948        /* Run until signal received */
3949        brcmf_sdiod_freezer_count(bus->sdiodev);
3950        while (1) {
3951                if (kthread_should_stop())
3952                        break;
3953                brcmf_sdiod_freezer_uncount(bus->sdiodev);
3954                wait = wait_for_completion_interruptible(&bus->watchdog_wait);
3955                brcmf_sdiod_freezer_count(bus->sdiodev);
3956                brcmf_sdiod_try_freeze(bus->sdiodev);
3957                if (!wait) {
3958                        brcmf_sdio_bus_watchdog(bus);
3959                        /* Count the tick for reference */
3960                        bus->sdcnt.tickcnt++;
3961                        reinit_completion(&bus->watchdog_wait);
3962                } else
3963                        break;
3964        }
3965        return 0;
3966}
3967
3968static void
3969brcmf_sdio_watchdog(unsigned long data)
3970{
3971        struct brcmf_sdio *bus = (struct brcmf_sdio *)data;
3972
3973        if (bus->watchdog_tsk) {
3974                complete(&bus->watchdog_wait);
3975                /* Reschedule the watchdog */
3976                if (bus->wd_active)
3977                        mod_timer(&bus->timer,
3978                                  jiffies + BRCMF_WD_POLL);
3979        }
3980}
3981
3982static const struct brcmf_bus_ops brcmf_sdio_bus_ops = {
3983        .stop = brcmf_sdio_bus_stop,
3984        .preinit = brcmf_sdio_bus_preinit,
3985        .txdata = brcmf_sdio_bus_txdata,
3986        .txctl = brcmf_sdio_bus_txctl,
3987        .rxctl = brcmf_sdio_bus_rxctl,
3988        .gettxq = brcmf_sdio_bus_gettxq,
3989        .wowl_config = brcmf_sdio_wowl_config,
3990        .get_ramsize = brcmf_sdio_bus_get_ramsize,
3991        .get_memdump = brcmf_sdio_bus_get_memdump,
3992};
3993
3994static void brcmf_sdio_firmware_callback(struct device *dev, int err,
3995                                         const struct firmware *code,
3996                                         void *nvram, u32 nvram_len)
3997{
3998        struct brcmf_bus *bus_if;
3999        struct brcmf_sdio_dev *sdiodev;
4000        struct brcmf_sdio *bus;
4001        u8 saveclk;
4002
4003        brcmf_dbg(TRACE, "Enter: dev=%s, err=%d\n", dev_name(dev), err);
4004        bus_if = dev_get_drvdata(dev);
4005        sdiodev = bus_if->bus_priv.sdio;
4006        if (err)
4007                goto fail;
4008
4009        if (!bus_if->drvr)
4010                return;
4011
4012        bus = sdiodev->bus;
4013
4014        /* try to download image and nvram to the dongle */
4015        bus->alp_only = true;
4016        err = brcmf_sdio_download_firmware(bus, code, nvram, nvram_len);
4017        if (err)
4018                goto fail;
4019        bus->alp_only = false;
4020
4021        /* Start the watchdog timer */
4022        bus->sdcnt.tickcnt = 0;
4023        brcmf_sdio_wd_timer(bus, true);
4024
4025        sdio_claim_host(sdiodev->func[1]);
4026
4027        /* Make sure backplane clock is on, needed to generate F2 interrupt */
4028        brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
4029        if (bus->clkstate != CLK_AVAIL)
4030                goto release;
4031
4032        /* Force clocks on backplane to be sure F2 interrupt propagates */
4033        saveclk = brcmf_sdiod_regrb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, &err);
4034        if (!err) {
4035                brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
4036                                  (saveclk | SBSDIO_FORCE_HT), &err);
4037        }
4038        if (err) {
4039                brcmf_err("Failed to force clock for F2: err %d\n", err);
4040                goto release;
4041        }
4042
4043        /* Enable function 2 (frame transfers) */
4044        w_sdreg32(bus, SDPCM_PROT_VERSION << SMB_DATA_VERSION_SHIFT,
4045                  offsetof(struct sdpcmd_regs, tosbmailboxdata));
4046        err = sdio_enable_func(sdiodev->func[SDIO_FUNC_2]);
4047
4048
4049        brcmf_dbg(INFO, "enable F2: err=%d\n", err);
4050
4051        /* If F2 successfully enabled, set core and enable interrupts */
4052        if (!err) {
4053                /* Set up the interrupt mask and enable interrupts */
4054                bus->hostintmask = HOSTINTMASK;
4055                w_sdreg32(bus, bus->hostintmask,
4056                          offsetof(struct sdpcmd_regs, hostintmask));
4057
4058                brcmf_sdiod_regwb(sdiodev, SBSDIO_WATERMARK, 8, &err);
4059        } else {
4060                /* Disable F2 again */
4061                sdio_disable_func(sdiodev->func[SDIO_FUNC_2]);
4062                goto release;
4063        }
4064
4065        if (brcmf_chip_sr_capable(bus->ci)) {
4066                brcmf_sdio_sr_init(bus);
4067        } else {
4068                /* Restore previous clock setting */
4069                brcmf_sdiod_regwb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
4070                                  saveclk, &err);
4071        }
4072
4073        if (err == 0) {
4074                /* Allow full data communication using DPC from now on. */
4075                brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DATA);
4076
4077                err = brcmf_sdiod_intr_register(sdiodev);
4078                if (err != 0)
4079                        brcmf_err("intr register failed:%d\n", err);
4080        }
4081
4082        /* If we didn't come up, turn off backplane clock */
4083        if (err != 0)
4084                brcmf_sdio_clkctl(bus, CLK_NONE, false);
4085
4086        sdio_release_host(sdiodev->func[1]);
4087
4088        err = brcmf_bus_started(dev);
4089        if (err != 0) {
4090                brcmf_err("dongle is not responding\n");
4091                goto fail;
4092        }
4093        return;
4094
4095release:
4096        sdio_release_host(sdiodev->func[1]);
4097fail:
4098        brcmf_dbg(TRACE, "failed: dev=%s, err=%d\n", dev_name(dev), err);
4099        device_release_driver(dev);
4100        device_release_driver(&sdiodev->func[2]->dev);
4101}
4102
4103struct brcmf_sdio *brcmf_sdio_probe(struct brcmf_sdio_dev *sdiodev)
4104{
4105        int ret;
4106        struct brcmf_sdio *bus;
4107        struct workqueue_struct *wq;
4108
4109        brcmf_dbg(TRACE, "Enter\n");
4110
4111        /* Allocate private bus interface state */
4112        bus = kzalloc(sizeof(struct brcmf_sdio), GFP_ATOMIC);
4113        if (!bus)
4114                goto fail;
4115
4116        bus->sdiodev = sdiodev;
4117        sdiodev->bus = bus;
4118        skb_queue_head_init(&bus->glom);
4119        bus->txbound = BRCMF_TXBOUND;
4120        bus->rxbound = BRCMF_RXBOUND;
4121        bus->txminmax = BRCMF_TXMINMAX;
4122        bus->tx_seq = SDPCM_SEQ_WRAP - 1;
4123
4124        /* single-threaded workqueue */
4125        wq = alloc_ordered_workqueue("brcmf_wq/%s", WQ_MEM_RECLAIM,
4126                                     dev_name(&sdiodev->func[1]->dev));
4127        if (!wq) {
4128                brcmf_err("insufficient memory to create txworkqueue\n");
4129                goto fail;
4130        }
4131        brcmf_sdiod_freezer_count(sdiodev);
4132        INIT_WORK(&bus->datawork, brcmf_sdio_dataworker);
4133        bus->brcmf_wq = wq;
4134
4135        /* attempt to attach to the dongle */
4136        if (!(brcmf_sdio_probe_attach(bus))) {
4137                brcmf_err("brcmf_sdio_probe_attach failed\n");
4138                goto fail;
4139        }
4140
4141        spin_lock_init(&bus->rxctl_lock);
4142        spin_lock_init(&bus->txq_lock);
4143        init_waitqueue_head(&bus->ctrl_wait);
4144        init_waitqueue_head(&bus->dcmd_resp_wait);
4145
4146        /* Set up the watchdog timer */
4147        init_timer(&bus->timer);
4148        bus->timer.data = (unsigned long)bus;
4149        bus->timer.function = brcmf_sdio_watchdog;
4150
4151        /* Initialize watchdog thread */
4152        init_completion(&bus->watchdog_wait);
4153        bus->watchdog_tsk = kthread_run(brcmf_sdio_watchdog_thread,
4154                                        bus, "brcmf_wdog/%s",
4155                                        dev_name(&sdiodev->func[1]->dev));
4156        if (IS_ERR(bus->watchdog_tsk)) {
4157                pr_warn("brcmf_watchdog thread failed to start\n");
4158                bus->watchdog_tsk = NULL;
4159        }
4160        /* Initialize DPC thread */
4161        bus->dpc_triggered = false;
4162        bus->dpc_running = false;
4163
4164        /* Assign bus interface call back */
4165        bus->sdiodev->bus_if->dev = bus->sdiodev->dev;
4166        bus->sdiodev->bus_if->ops = &brcmf_sdio_bus_ops;
4167        bus->sdiodev->bus_if->chip = bus->ci->chip;
4168        bus->sdiodev->bus_if->chiprev = bus->ci->chiprev;
4169
4170        /* default sdio bus header length for tx packet */
4171        bus->tx_hdrlen = SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN;
4172
4173        /* Attach to the common layer, reserve hdr space */
4174        ret = brcmf_attach(bus->sdiodev->dev, bus->sdiodev->settings);
4175        if (ret != 0) {
4176                brcmf_err("brcmf_attach failed\n");
4177                goto fail;
4178        }
4179
4180        /* Query the F2 block size, set roundup accordingly */
4181        bus->blocksize = bus->sdiodev->func[2]->cur_blksize;
4182        bus->roundup = min(max_roundup, bus->blocksize);
4183
4184        /* Allocate buffers */
4185        if (bus->sdiodev->bus_if->maxctl) {
4186                bus->sdiodev->bus_if->maxctl += bus->roundup;
4187                bus->rxblen =
4188                    roundup((bus->sdiodev->bus_if->maxctl + SDPCM_HDRLEN),
4189                            ALIGNMENT) + bus->head_align;
4190                bus->rxbuf = kmalloc(bus->rxblen, GFP_ATOMIC);
4191                if (!(bus->rxbuf)) {
4192                        brcmf_err("rxbuf allocation failed\n");
4193                        goto fail;
4194                }
4195        }
4196
4197        sdio_claim_host(bus->sdiodev->func[1]);
4198
4199        /* Disable F2 to clear any intermediate frame state on the dongle */
4200        sdio_disable_func(bus->sdiodev->func[SDIO_FUNC_2]);
4201
4202        bus->rxflow = false;
4203
4204        /* Done with backplane-dependent accesses, can drop clock... */
4205        brcmf_sdiod_regwb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL);
4206
4207        sdio_release_host(bus->sdiodev->func[1]);
4208
4209        /* ...and initialize clock/power states */
4210        bus->clkstate = CLK_SDONLY;
4211        bus->idletime = BRCMF_IDLE_INTERVAL;
4212        bus->idleclock = BRCMF_IDLE_ACTIVE;
4213
4214        /* SR state */
4215        bus->sr_enabled = false;
4216
4217        brcmf_sdio_debugfs_create(bus);
4218        brcmf_dbg(INFO, "completed!!\n");
4219
4220        ret = brcmf_fw_map_chip_to_name(bus->ci->chip, bus->ci->chiprev,
4221                                        brcmf_sdio_fwnames,
4222                                        ARRAY_SIZE(brcmf_sdio_fwnames),
4223                                        sdiodev->fw_name, sdiodev->nvram_name);
4224        if (ret)
4225                goto fail;
4226
4227        ret = brcmf_fw_get_firmwares(sdiodev->dev, BRCMF_FW_REQUEST_NVRAM,
4228                                     sdiodev->fw_name, sdiodev->nvram_name,
4229                                     brcmf_sdio_firmware_callback);
4230        if (ret != 0) {
4231                brcmf_err("async firmware request failed: %d\n", ret);
4232                goto fail;
4233        }
4234
4235        return bus;
4236
4237fail:
4238        brcmf_sdio_remove(bus);
4239        return NULL;
4240}
4241
4242/* Detach and free everything */
4243void brcmf_sdio_remove(struct brcmf_sdio *bus)
4244{
4245        brcmf_dbg(TRACE, "Enter\n");
4246
4247        if (bus) {
4248                /* De-register interrupt handler */
4249                brcmf_sdiod_intr_unregister(bus->sdiodev);
4250
4251                brcmf_detach(bus->sdiodev->dev);
4252
4253                cancel_work_sync(&bus->datawork);
4254                if (bus->brcmf_wq)
4255                        destroy_workqueue(bus->brcmf_wq);
4256
4257                if (bus->ci) {
4258                        if (bus->sdiodev->state != BRCMF_SDIOD_NOMEDIUM) {
4259                                sdio_claim_host(bus->sdiodev->func[1]);
4260                                brcmf_sdio_wd_timer(bus, false);
4261                                brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
4262                                /* Leave the device in state where it is
4263                                 * 'passive'. This is done by resetting all
4264                                 * necessary cores.
4265                                 */
4266                                msleep(20);
4267                                brcmf_chip_set_passive(bus->ci);
4268                                brcmf_sdio_clkctl(bus, CLK_NONE, false);
4269                                sdio_release_host(bus->sdiodev->func[1]);
4270                        }
4271                        brcmf_chip_detach(bus->ci);
4272                }
4273                if (bus->sdiodev->settings)
4274                        brcmf_release_module_param(bus->sdiodev->settings);
4275
4276                kfree(bus->rxbuf);
4277                kfree(bus->hdrbuf);
4278                kfree(bus);
4279        }
4280
4281        brcmf_dbg(TRACE, "Disconnected\n");
4282}
4283
4284void brcmf_sdio_wd_timer(struct brcmf_sdio *bus, bool active)
4285{
4286        /* Totally stop the timer */
4287        if (!active && bus->wd_active) {
4288                del_timer_sync(&bus->timer);
4289                bus->wd_active = false;
4290                return;
4291        }
4292
4293        /* don't start the wd until fw is loaded */
4294        if (bus->sdiodev->state != BRCMF_SDIOD_DATA)
4295                return;
4296
4297        if (active) {
4298                if (!bus->wd_active) {
4299                        /* Create timer again when watchdog period is
4300                           dynamically changed or in the first instance
4301                         */
4302                        bus->timer.expires = jiffies + BRCMF_WD_POLL;
4303                        add_timer(&bus->timer);
4304                        bus->wd_active = true;
4305                } else {
4306                        /* Re arm the timer, at last watchdog period */
4307                        mod_timer(&bus->timer, jiffies + BRCMF_WD_POLL);
4308                }
4309        }
4310}
4311
4312int brcmf_sdio_sleep(struct brcmf_sdio *bus, bool sleep)
4313{
4314        int ret;
4315
4316        sdio_claim_host(bus->sdiodev->func[1]);
4317        ret = brcmf_sdio_bus_sleep(bus, sleep, false);
4318        sdio_release_host(bus->sdiodev->func[1]);
4319
4320        return ret;
4321}
4322
4323