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