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