2ede425f2194fe67acbc146a603f727c6210f441
[cascardo/linux.git] / drivers / staging / brcm80211 / brcmfmac / dhd_sdio.c
1 /*
2  * Copyright (c) 2010 Broadcom Corporation
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
11  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
13  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <linux/types.h>
18 #include <linux/kernel.h>
19 #include <linux/printk.h>
20 #include <linux/pci_ids.h>
21 #include <linux/netdevice.h>
22 #include <linux/sched.h>
23 #include <linux/mmc/sdio.h>
24 #include <asm/unaligned.h>
25 #include <defs.h>
26 #include <brcmu_wifi.h>
27 #include <brcmu_utils.h>
28 #include <brcm_hw_ids.h>
29 #include <soc.h>
30 #include "sdio_host.h"
31
32 /* register access macros */
33 #ifndef __BIG_ENDIAN
34 #ifndef __mips__
35 #define R_REG(r) \
36         brcmf_sdcard_reg_read(NULL, (unsigned long)(r), sizeof(*(r)))
37 #else                           /* __mips__ */
38 #define R_REG(r) \
39         ({ \
40                 __typeof(*(r)) __osl_v; \
41                 __asm__ __volatile__("sync"); \
42                 __osl_v = brcmf_sdcard_reg_read(NULL, (unsigned long)(r),\
43                                           sizeof(*(r))); \
44                 __asm__ __volatile__("sync"); \
45                 __osl_v; \
46         })
47 #endif                          /* __mips__ */
48
49 #define W_REG(r, v) do { \
50                 brcmf_sdcard_reg_write(NULL, (unsigned long)(r), sizeof(*(r)), \
51                                        (v)); \
52         } while (0)
53 #else                           /* __BIG_ENDIAN */
54 #define R_REG(r) \
55         brcmf_sdcard_reg_read(NULL, (unsigned long)(r), sizeof(*(r)))
56 #define W_REG(r, v) do { \
57                 brcmf_sdcard_reg_write(NULL, (unsigned long)(r), sizeof(*(r)), \
58                                        (v)); \
59         } while (0)
60 #endif                          /* __BIG_ENDIAN */
61
62 #define AND_REG(r, v)   W_REG((r), R_REG(r) & (v))
63 #define OR_REG(r, v)    W_REG((r), R_REG(r) | (v))
64
65 #define SET_REG(r, mask, val) \
66                 W_REG((r), ((R_REG(r) & ~(mask)) | (val)))
67
68 #ifdef DHD_DEBUG
69
70 /* ARM trap handling */
71
72 /* Trap types defined by ARM (see arminc.h) */
73
74 /* Trap locations in lo memory */
75 #define TRAP_STRIDE     4
76 #define FIRST_TRAP      TR_RST
77 #define LAST_TRAP       (TR_FIQ * TRAP_STRIDE)
78
79 #if defined(__ARM_ARCH_4T__)
80 #define MAX_TRAP_TYPE   (TR_FIQ + 1)
81 #elif defined(__ARM_ARCH_7M__)
82 #define MAX_TRAP_TYPE   (TR_ISR + ARMCM3_NUMINTS)
83 #endif                          /* __ARM_ARCH_7M__ */
84
85 /* The trap structure is defined here as offsets for assembly */
86 #define TR_TYPE         0x00
87 #define TR_EPC          0x04
88 #define TR_CPSR         0x08
89 #define TR_SPSR         0x0c
90 #define TR_REGS         0x10
91 #define TR_REG(n)       (TR_REGS + (n) * 4)
92 #define TR_SP           TR_REG(13)
93 #define TR_LR           TR_REG(14)
94 #define TR_PC           TR_REG(15)
95
96 #define TRAP_T_SIZE     80
97
98 typedef struct _trap_struct {
99         u32 type;
100         u32 epc;
101         u32 cpsr;
102         u32 spsr;
103         u32 r0;
104         u32 r1;
105         u32 r2;
106         u32 r3;
107         u32 r4;
108         u32 r5;
109         u32 r6;
110         u32 r7;
111         u32 r8;
112         u32 r9;
113         u32 r10;
114         u32 r11;
115         u32 r12;
116         u32 r13;
117         u32 r14;
118         u32 pc;
119 } trap_t;
120
121 #define CBUF_LEN        (128)
122
123 #define LOG_BUF_LEN     1024
124
125 typedef struct {
126         u32 buf;                /* Can't be pointer on (64-bit) hosts */
127         uint buf_size;
128         uint idx;
129         char *_buf_compat;      /* Redundant pointer for backward compat. */
130 } rte_log_t;
131
132 typedef struct {
133         /* Virtual UART
134          * When there is no UART (e.g. Quickturn),
135          * the host should write a complete
136          * input line directly into cbuf and then write
137          * the length into vcons_in.
138          * This may also be used when there is a real UART
139          * (at risk of conflicting with
140          * the real UART).  vcons_out is currently unused.
141          */
142         volatile uint vcons_in;
143         volatile uint vcons_out;
144
145         /* Output (logging) buffer
146          * Console output is written to a ring buffer log_buf at index log_idx.
147          * The host may read the output when it sees log_idx advance.
148          * Output will be lost if the output wraps around faster than the host
149          * polls.
150          */
151         rte_log_t log;
152
153         /* Console input line buffer
154          * Characters are read one at a time into cbuf
155          * until <CR> is received, then
156          * the buffer is processed as a command line.
157          * Also used for virtual UART.
158          */
159         uint cbuf_idx;
160         char cbuf[CBUF_LEN];
161 } rte_cons_t;
162
163 #endif                          /* DHD_DEBUG */
164 #include <chipcommon.h>
165
166 #include "sbsdio.h"
167
168 #include "dngl_stats.h"
169 #include "dhd.h"
170 #include "dhd_bus.h"
171 #include "dhd_proto.h"
172 #include "dhd_dbg.h"
173 #include <sdiovar.h>
174 #include <bcmchip.h>
175
176 #ifndef DHDSDIO_MEM_DUMP_FNAME
177 #define DHDSDIO_MEM_DUMP_FNAME         "mem_dump"
178 #endif
179
180 #define TXQLEN          2048    /* bulk tx queue length */
181 #define TXHI            (TXQLEN - 256)  /* turn on flow control above TXHI */
182 #define TXLOW           (TXHI - 256)    /* turn off flow control below TXLOW */
183 #define PRIOMASK        7
184
185 #define TXRETRIES       2       /* # of retries for tx frames */
186
187 #if defined(CONFIG_MACH_SANDGATE2G)
188 #define DHD_RXBOUND     250     /* Default for max rx frames in
189                                  one scheduling */
190 #else
191 #define DHD_RXBOUND     50      /* Default for max rx frames in
192                                  one scheduling */
193 #endif                          /* defined(CONFIG_MACH_SANDGATE2G) */
194
195 #define DHD_TXBOUND     20      /* Default for max tx frames in
196                                  one scheduling */
197
198 #define DHD_TXMINMAX    1       /* Max tx frames if rx still pending */
199
200 #define MEMBLOCK        2048    /* Block size used for downloading
201                                  of dongle image */
202 #define MAX_DATA_BUF    (32 * 1024)     /* Must be large enough to hold
203                                  biggest possible glom */
204
205 /* Packet alignment for most efficient SDIO (can change based on platform) */
206 #ifndef DHD_SDALIGN
207 #define DHD_SDALIGN     32
208 #endif
209 #if !ISPOWEROF2(DHD_SDALIGN)
210 #error DHD_SDALIGN is not a power of 2!
211 #endif
212
213 #ifndef DHD_FIRSTREAD
214 #define DHD_FIRSTREAD   32
215 #endif
216 #if !ISPOWEROF2(DHD_FIRSTREAD)
217 #error DHD_FIRSTREAD is not a power of 2!
218 #endif
219
220 /* Total length of frame header for dongle protocol */
221 #define SDPCM_HDRLEN    (SDPCM_FRAMETAG_LEN + SDPCM_SWHEADER_LEN)
222 #ifdef SDTEST
223 #define SDPCM_RESERVE   (SDPCM_HDRLEN + SDPCM_TEST_HDRLEN + DHD_SDALIGN)
224 #else
225 #define SDPCM_RESERVE   (SDPCM_HDRLEN + DHD_SDALIGN)
226 #endif
227
228 /*
229  * Software allocation of To SB Mailbox resources
230  */
231
232 /* tosbmailbox bits corresponding to intstatus bits */
233 #define SMB_NAK         (1 << 0)        /* Frame NAK */
234 #define SMB_INT_ACK     (1 << 1)        /* Host Interrupt ACK */
235 #define SMB_USE_OOB     (1 << 2)        /* Use OOB Wakeup */
236 #define SMB_DEV_INT     (1 << 3)        /* Miscellaneous Interrupt */
237
238 /* tosbmailboxdata */
239 #define SMB_DATA_VERSION_SHIFT  16      /* host protocol version */
240
241 /*
242  * Software allocation of To Host Mailbox resources
243  */
244
245 /* intstatus bits */
246 #define I_HMB_FC_STATE  I_HMB_SW0       /* Flow Control State */
247 #define I_HMB_FC_CHANGE I_HMB_SW1       /* Flow Control State Changed */
248 #define I_HMB_FRAME_IND I_HMB_SW2       /* Frame Indication */
249 #define I_HMB_HOST_INT  I_HMB_SW3       /* Miscellaneous Interrupt */
250
251 /* tohostmailboxdata */
252 #define HMB_DATA_NAKHANDLED     1       /* retransmit NAK'd frame */
253 #define HMB_DATA_DEVREADY       2       /* talk to host after enable */
254 #define HMB_DATA_FC             4       /* per prio flowcontrol update flag */
255 #define HMB_DATA_FWREADY        8       /* fw ready for protocol activity */
256
257 #define HMB_DATA_FCDATA_MASK    0xff000000
258 #define HMB_DATA_FCDATA_SHIFT   24
259
260 #define HMB_DATA_VERSION_MASK   0x00ff0000
261 #define HMB_DATA_VERSION_SHIFT  16
262
263 /*
264  * Software-defined protocol header
265  */
266
267 /* Current protocol version */
268 #define SDPCM_PROT_VERSION      4
269
270 /* SW frame header */
271 #define SDPCM_PACKET_SEQUENCE(p)        (((u8 *)p)[0] & 0xff)
272
273 #define SDPCM_CHANNEL_MASK              0x00000f00
274 #define SDPCM_CHANNEL_SHIFT             8
275 #define SDPCM_PACKET_CHANNEL(p)         (((u8 *)p)[1] & 0x0f)
276
277 #define SDPCM_NEXTLEN_OFFSET            2
278
279 /* Data Offset from SOF (HW Tag, SW Tag, Pad) */
280 #define SDPCM_DOFFSET_OFFSET            3       /* Data Offset */
281 #define SDPCM_DOFFSET_VALUE(p)          (((u8 *)p)[SDPCM_DOFFSET_OFFSET] & 0xff)
282 #define SDPCM_DOFFSET_MASK              0xff000000
283 #define SDPCM_DOFFSET_SHIFT             24
284 #define SDPCM_FCMASK_OFFSET             4       /* Flow control */
285 #define SDPCM_FCMASK_VALUE(p)           (((u8 *)p)[SDPCM_FCMASK_OFFSET] & 0xff)
286 #define SDPCM_WINDOW_OFFSET             5       /* Credit based fc */
287 #define SDPCM_WINDOW_VALUE(p)           (((u8 *)p)[SDPCM_WINDOW_OFFSET] & 0xff)
288
289 #define SDPCM_SWHEADER_LEN      8       /* SW header is 64 bits */
290
291 /* logical channel numbers */
292 #define SDPCM_CONTROL_CHANNEL   0       /* Control channel Id */
293 #define SDPCM_EVENT_CHANNEL     1       /* Asyc Event Indication Channel Id */
294 #define SDPCM_DATA_CHANNEL      2       /* Data Xmit/Recv Channel Id */
295 #define SDPCM_GLOM_CHANNEL      3       /* For coalesced packets */
296 #define SDPCM_TEST_CHANNEL      15      /* Reserved for test/debug packets */
297
298 #define SDPCM_SEQUENCE_WRAP     256     /* wrap-around val for 8bit frame seq */
299
300 #define SDPCM_GLOMDESC(p)       (((u8 *)p)[1] & 0x80)
301
302 /* For TEST_CHANNEL packets, define another 4-byte header */
303 #define SDPCM_TEST_HDRLEN       4       /*
304                                          * Generally: Cmd(1), Ext(1), Len(2);
305                                          * Semantics of Ext byte depend on
306                                          * command. Len is current or requested
307                                          * frame length, not including test
308                                          * header; sent little-endian.
309                                          */
310 #define SDPCM_TEST_DISCARD      0x01    /* Receiver discards. Ext:pattern id. */
311 #define SDPCM_TEST_ECHOREQ      0x02    /* Echo request. Ext:pattern id. */
312 #define SDPCM_TEST_ECHORSP      0x03    /* Echo response. Ext:pattern id. */
313 #define SDPCM_TEST_BURST        0x04    /*
314                                          * Receiver to send a burst.
315                                          * Ext is a frame count
316                                          */
317 #define SDPCM_TEST_SEND         0x05    /*
318                                          * Receiver sets send mode.
319                                          * Ext is boolean on/off
320                                          */
321
322 /* Handy macro for filling in datagen packets with a pattern */
323 #define SDPCM_TEST_FILL(byteno, id)     ((u8)(id + byteno))
324
325 /*
326  * Shared structure between dongle and the host.
327  * The structure contains pointers to trap or assert information.
328  */
329 #define SDPCM_SHARED_VERSION       0x0002
330 #define SDPCM_SHARED_VERSION_MASK  0x00FF
331 #define SDPCM_SHARED_ASSERT_BUILT  0x0100
332 #define SDPCM_SHARED_ASSERT        0x0200
333 #define SDPCM_SHARED_TRAP          0x0400
334
335
336 /* Space for header read, limit for data packets */
337 #ifndef MAX_HDR_READ
338 #define MAX_HDR_READ    32
339 #endif
340 #if !ISPOWEROF2(MAX_HDR_READ)
341 #error MAX_HDR_READ is not a power of 2!
342 #endif
343
344 #define MAX_RX_DATASZ   2048
345
346 /* Maximum milliseconds to wait for F2 to come up */
347 #define DHD_WAIT_F2RDY  3000
348
349 /* Bump up limit on waiting for HT to account for first startup;
350  * if the image is doing a CRC calculation before programming the PMU
351  * for HT availability, it could take a couple hundred ms more, so
352  * max out at a 1 second (1000000us).
353  */
354 #if (PMU_MAX_TRANSITION_DLY <= 1000000)
355 #undef PMU_MAX_TRANSITION_DLY
356 #define PMU_MAX_TRANSITION_DLY 1000000
357 #endif
358
359 /* Value for ChipClockCSR during initial setup */
360 #define DHD_INIT_CLKCTL1        (SBSDIO_FORCE_HW_CLKREQ_OFF |   \
361                                         SBSDIO_ALP_AVAIL_REQ)
362 #define DHD_INIT_CLKCTL2        (SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP)
363
364 /* Flags for SDH calls */
365 #define F2SYNC  (SDIO_REQ_4BYTE | SDIO_REQ_FIXED)
366
367 /* sbimstate */
368 #define SBIM_IBE                0x20000 /* inbanderror */
369 #define SBIM_TO                 0x40000 /* timeout */
370 #define SBIM_BY                 0x01800000      /* busy (sonics >= 2.3) */
371 #define SBIM_RJ                 0x02000000      /* reject (sonics >= 2.3) */
372
373 /* sbtmstatelow */
374 #define SBTML_RESET             0x0001  /* reset */
375 #define SBTML_REJ_MASK          0x0006  /* reject field */
376 #define SBTML_REJ               0x0002  /* reject */
377 #define SBTML_TMPREJ            0x0004  /* temporary reject, for error recovery */
378
379 #define SBTML_SICF_SHIFT        16      /* Shift to locate the SI control flags in sbtml */
380
381 /* sbtmstatehigh */
382 #define SBTMH_SERR              0x0001  /* serror */
383 #define SBTMH_INT               0x0002  /* interrupt */
384 #define SBTMH_BUSY              0x0004  /* busy */
385 #define SBTMH_TO                0x0020  /* timeout (sonics >= 2.3) */
386
387 #define SBTMH_SISF_SHIFT        16      /* Shift to locate the SI status flags in sbtmh */
388
389 /* sbidlow */
390 #define SBIDL_INIT              0x80    /* initiator */
391
392 /* sbidhigh */
393 #define SBIDH_RC_MASK           0x000f  /* revision code */
394 #define SBIDH_RCE_MASK          0x7000  /* revision code extension field */
395 #define SBIDH_RCE_SHIFT         8
396 #define SBCOREREV(sbidh) \
397         ((((sbidh) & SBIDH_RCE_MASK) >> SBIDH_RCE_SHIFT) | ((sbidh) & SBIDH_RC_MASK))
398 #define SBIDH_CC_MASK           0x8ff0  /* core code */
399 #define SBIDH_CC_SHIFT          4
400 #define SBIDH_VC_MASK           0xffff0000      /* vendor code */
401 #define SBIDH_VC_SHIFT          16
402
403 /*
404  * Conversion of 802.1D priority to precedence level
405  */
406 #define PRIO2PREC(prio) \
407         (((prio) == PRIO_8021D_NONE || (prio) == PRIO_8021D_BE) ? \
408         ((prio^2)) : (prio))
409
410 DHD_SPINWAIT_SLEEP_INIT(sdioh_spinwait_sleep);
411
412 /* Core reg address translation */
413 #define CORE_CC_REG(base, field)        (base + offsetof(chipcregs_t, field))
414 #define CORE_BUS_REG(base, field) \
415                 (base + offsetof(struct sdpcmd_regs, field))
416 #define CORE_SB(base, field) \
417                 (base + SBCONFIGOFF + offsetof(sbconfig_t, field))
418
419 #ifdef DHD_DEBUG
420 /* Device console log buffer state */
421 typedef struct dhd_console {
422         uint count;             /* Poll interval msec counter */
423         uint log_addr;          /* Log struct address (fixed) */
424         rte_log_t log;  /* Log struct (host copy) */
425         uint bufsize;           /* Size of log buffer */
426         u8 *buf;                /* Log buffer (host copy) */
427         uint last;              /* Last buffer read index */
428 } dhd_console_t;
429 #endif                          /* DHD_DEBUG */
430
431 struct sdpcm_shared {
432         u32 flags;
433         u32 trap_addr;
434         u32 assert_exp_addr;
435         u32 assert_file_addr;
436         u32 assert_line;
437         u32 console_addr;       /* Address of rte_cons_t */
438         u32 msgtrace_addr;
439         u8 tag[32];
440 };
441
442
443 /* misc chip info needed by some of the routines */
444 struct chip_info {
445         u32 chip;
446         u32 chiprev;
447         u32 cccorebase;
448         u32 ccrev;
449         u32 cccaps;
450         u32 buscorebase;
451         u32 buscorerev;
452         u32 buscoretype;
453         u32 ramcorebase;
454         u32 armcorebase;
455         u32 pmurev;
456         u32 ramsize;
457 };
458
459 /* Private data for SDIO bus interaction */
460 typedef struct dhd_bus {
461         dhd_pub_t *dhd;
462
463         struct brcmf_sdio *sdh; /* Handle for BCMSDH calls */
464         struct chip_info *ci;   /* Chip info struct */
465         char *vars;             /* Variables (from CIS and/or other) */
466         uint varsz;             /* Size of variables buffer */
467         u32 sbaddr;             /* Current SB window pointer (-1, invalid) */
468
469         struct sdpcmd_regs *regs;       /* SDIO core */
470         uint sdpcmrev;          /* SDIO core revision */
471         uint armrev;            /* CPU core revision */
472         uint ramrev;            /* SOCRAM core revision */
473         u32 ramsize;            /* Size of RAM in SOCRAM (bytes) */
474         u32 orig_ramsize;       /* Size of RAM in SOCRAM (bytes) */
475
476         u32 bus;                /* gSPI or SDIO bus */
477         u32 hostintmask;        /* Copy of Host Interrupt Mask */
478         u32 intstatus;  /* Intstatus bits (events) pending */
479         bool dpc_sched;         /* Indicates DPC schedule (intrpt rcvd) */
480         bool fcstate;           /* State of dongle flow-control */
481
482         u16 cl_devid;   /* cached devid for brcmf_sdio_probe_attach() */
483         char *fw_path;          /* module_param: path to firmware image */
484         char *nv_path;          /* module_param: path to nvram vars file */
485         const char *nvram_params;       /* user specified nvram params. */
486
487         uint blocksize;         /* Block size of SDIO transfers */
488         uint roundup;           /* Max roundup limit */
489
490         struct pktq txq;        /* Queue length used for flow-control */
491         u8 flowcontrol; /* per prio flow control bitmask */
492         u8 tx_seq;              /* Transmit sequence number (next) */
493         u8 tx_max;              /* Maximum transmit sequence allowed */
494
495         u8 hdrbuf[MAX_HDR_READ + DHD_SDALIGN];
496         u8 *rxhdr;              /* Header of current rx frame (in hdrbuf) */
497         u16 nextlen;            /* Next Read Len from last header */
498         u8 rx_seq;              /* Receive sequence number (expected) */
499         bool rxskip;            /* Skip receive (awaiting NAK ACK) */
500
501         struct sk_buff *glomd;  /* Packet containing glomming descriptor */
502         struct sk_buff *glom;   /* Packet chain for glommed superframe */
503         uint glomerr;           /* Glom packet read errors */
504
505         u8 *rxbuf;              /* Buffer for receiving control packets */
506         uint rxblen;            /* Allocated length of rxbuf */
507         u8 *rxctl;              /* Aligned pointer into rxbuf */
508         u8 *databuf;            /* Buffer for receiving big glom packet */
509         u8 *dataptr;            /* Aligned pointer into databuf */
510         uint rxlen;             /* Length of valid data in buffer */
511
512         u8 sdpcm_ver;   /* Bus protocol reported by dongle */
513
514         bool intr;              /* Use interrupts */
515         bool poll;              /* Use polling */
516         bool ipend;             /* Device interrupt is pending */
517         bool intdis;            /* Interrupts disabled by isr */
518         uint intrcount;         /* Count of device interrupt callbacks */
519         uint lastintrs;         /* Count as of last watchdog timer */
520         uint spurious;          /* Count of spurious interrupts */
521         uint pollrate;          /* Ticks between device polls */
522         uint polltick;          /* Tick counter */
523         uint pollcnt;           /* Count of active polls */
524
525 #ifdef DHD_DEBUG
526         dhd_console_t console;  /* Console output polling support */
527         uint console_addr;      /* Console address from shared struct */
528 #endif                          /* DHD_DEBUG */
529
530         uint regfails;          /* Count of R_REG/W_REG failures */
531
532         uint clkstate;          /* State of sd and backplane clock(s) */
533         bool activity;          /* Activity flag for clock down */
534         s32 idletime;           /* Control for activity timeout */
535         s32 idlecount;  /* Activity timeout counter */
536         s32 idleclock;  /* How to set bus driver when idle */
537         s32 sd_rxchain; /* If bcmsdh api accepts PKT chains */
538         bool use_rxchain;       /* If dhd should use PKT chains */
539         bool sleeping;          /* Is SDIO bus sleeping? */
540         bool rxflow_mode;       /* Rx flow control mode */
541         bool rxflow;            /* Is rx flow control on */
542         uint prev_rxlim_hit;    /* Is prev rx limit exceeded
543                                          (per dpc schedule) */
544         bool alp_only;          /* Don't use HT clock (ALP only) */
545 /* Field to decide if rx of control frames happen in rxbuf or lb-pool */
546         bool usebufpool;
547
548 #ifdef SDTEST
549         /* external loopback */
550         bool ext_loop;
551         u8 loopid;
552
553         /* pktgen configuration */
554         uint pktgen_freq;       /* Ticks between bursts */
555         uint pktgen_count;      /* Packets to send each burst */
556         uint pktgen_print;      /* Bursts between count displays */
557         uint pktgen_total;      /* Stop after this many */
558         uint pktgen_minlen;     /* Minimum packet data len */
559         uint pktgen_maxlen;     /* Maximum packet data len */
560         uint pktgen_mode;       /* Configured mode: tx, rx, or echo */
561         uint pktgen_stop;       /* Number of tx failures causing stop */
562
563         /* active pktgen fields */
564         uint pktgen_tick;       /* Tick counter for bursts */
565         uint pktgen_ptick;      /* Burst counter for printing */
566         uint pktgen_sent;       /* Number of test packets generated */
567         uint pktgen_rcvd;       /* Number of test packets received */
568         uint pktgen_fail;       /* Number of failed send attempts */
569         u16 pktgen_len; /* Length of next packet to send */
570 #endif                          /* SDTEST */
571
572         /* Some additional counters */
573         uint tx_sderrs;         /* Count of tx attempts with sd errors */
574         uint fcqueued;          /* Tx packets that got queued */
575         uint rxrtx;             /* Count of rtx requests (NAK to dongle) */
576         uint rx_toolong;        /* Receive frames too long to receive */
577         uint rxc_errors;        /* SDIO errors when reading control frames */
578         uint rx_hdrfail;        /* SDIO errors on header reads */
579         uint rx_badhdr;         /* Bad received headers (roosync?) */
580         uint rx_badseq;         /* Mismatched rx sequence number */
581         uint fc_rcvd;           /* Number of flow-control events received */
582         uint fc_xoff;           /* Number which turned on flow-control */
583         uint fc_xon;            /* Number which turned off flow-control */
584         uint rxglomfail;        /* Failed deglom attempts */
585         uint rxglomframes;      /* Number of glom frames (superframes) */
586         uint rxglompkts;        /* Number of packets from glom frames */
587         uint f2rxhdrs;          /* Number of header reads */
588         uint f2rxdata;          /* Number of frame data reads */
589         uint f2txdata;          /* Number of f2 frame writes */
590         uint f1regdata;         /* Number of f1 register accesses */
591
592         u8 *ctrl_frame_buf;
593         u32 ctrl_frame_len;
594         bool ctrl_frame_stat;
595
596         spinlock_t txqlock;
597 } dhd_bus_t;
598
599 typedef volatile struct _sbconfig {
600         u32 PAD[2];
601         u32 sbipsflag;  /* initiator port ocp slave flag */
602         u32 PAD[3];
603         u32 sbtpsflag;  /* target port ocp slave flag */
604         u32 PAD[11];
605         u32 sbtmerrloga;        /* (sonics >= 2.3) */
606         u32 PAD;
607         u32 sbtmerrlog; /* (sonics >= 2.3) */
608         u32 PAD[3];
609         u32 sbadmatch3; /* address match3 */
610         u32 PAD;
611         u32 sbadmatch2; /* address match2 */
612         u32 PAD;
613         u32 sbadmatch1; /* address match1 */
614         u32 PAD[7];
615         u32 sbimstate;  /* initiator agent state */
616         u32 sbintvec;   /* interrupt mask */
617         u32 sbtmstatelow;       /* target state */
618         u32 sbtmstatehigh;      /* target state */
619         u32 sbbwa0;             /* bandwidth allocation table0 */
620         u32 PAD;
621         u32 sbimconfiglow;      /* initiator configuration */
622         u32 sbimconfighigh;     /* initiator configuration */
623         u32 sbadmatch0; /* address match0 */
624         u32 PAD;
625         u32 sbtmconfiglow;      /* target configuration */
626         u32 sbtmconfighigh;     /* target configuration */
627         u32 sbbconfig;  /* broadcast configuration */
628         u32 PAD;
629         u32 sbbstate;   /* broadcast state */
630         u32 PAD[3];
631         u32 sbactcnfg;  /* activate configuration */
632         u32 PAD[3];
633         u32 sbflagst;   /* current sbflags */
634         u32 PAD[3];
635         u32 sbidlow;            /* identification */
636         u32 sbidhigh;   /* identification */
637 } sbconfig_t;
638
639 /* clkstate */
640 #define CLK_NONE        0
641 #define CLK_SDONLY      1
642 #define CLK_PENDING     2       /* Not used yet */
643 #define CLK_AVAIL       3
644
645 #define DHD_NOPMU(dhd)  (false)
646
647 #ifdef DHD_DEBUG
648 static int qcount[NUMPRIO];
649 static int tx_packets[NUMPRIO];
650 #endif                          /* DHD_DEBUG */
651
652 /* Deferred transmit */
653 const uint brcmf_deferred_tx = 1;
654
655 /* Tx/Rx bounds */
656 uint brcmf_txbound;
657 uint brcmf_rxbound;
658 uint dhd_txminmax;
659
660 /* override the RAM size if possible */
661 #define DONGLE_MIN_MEMSIZE (128 * 1024)
662 int brcmf_dongle_memsize;
663
664 static bool dhd_alignctl;
665
666 static bool sd1idle;
667
668 static bool retrydata;
669 #define RETRYCHAN(chan) (((chan) == SDPCM_EVENT_CHANNEL) || retrydata)
670
671 static const uint watermark = 8;
672 static const uint firstread = DHD_FIRSTREAD;
673
674 #define HDATLEN (firstread - (SDPCM_HDRLEN))
675
676 /* Retry count for register access failures */
677 static const uint retry_limit = 2;
678
679 /* Force even SD lengths (some host controllers mess up on odd bytes) */
680 static bool forcealign;
681
682 #define ALIGNMENT  4
683
684 #if defined(OOB_INTR_ONLY) && defined(HW_OOB)
685 extern void brcmf_sdcard_enable_hw_oob_intr(void *sdh, bool enable);
686 #endif
687
688 #if defined(OOB_INTR_ONLY) && defined(SDIO_ISR_THREAD)
689 #error OOB_INTR_ONLY is NOT working with SDIO_ISR_THREAD
690 #endif  /* defined(OOB_INTR_ONLY) && defined(SDIO_ISR_THREAD) */
691 #define PKTALIGN(_p, _len, _align)                              \
692         do {                                                            \
693                 uint datalign;                                          \
694                 datalign = (unsigned long)((_p)->data);                 \
695                 datalign = roundup(datalign, (_align)) - datalign;      \
696                 ASSERT(datalign < (_align));                            \
697                 ASSERT((_p)->len >= ((_len) + datalign));               \
698                 if (datalign)                                           \
699                         skb_pull((_p), datalign);                       \
700                 __skb_trim((_p), (_len));                               \
701         } while (0)
702
703 /* Limit on rounding up frames */
704 static const uint max_roundup = 512;
705
706 /* Try doing readahead */
707 static bool dhd_readahead;
708
709 /* To check if there's window offered */
710 #define DATAOK(bus) \
711         (((u8)(bus->tx_max - bus->tx_seq) != 0) && \
712         (((u8)(bus->tx_max - bus->tx_seq) & 0x80) == 0))
713
714 /* Macros to get register read/write status */
715 /* NOTE: these assume a local dhdsdio_bus_t *bus! */
716 #define R_SDREG(regvar, regaddr, retryvar) \
717 do { \
718         retryvar = 0; \
719         do { \
720                 regvar = R_REG(regaddr); \
721         } while (brcmf_sdcard_regfail(bus->sdh) && \
722                  (++retryvar <= retry_limit)); \
723         if (retryvar) { \
724                 bus->regfails += (retryvar-1); \
725                 if (retryvar > retry_limit) { \
726                         DHD_ERROR(("%s: FAILED" #regvar "READ, LINE %d\n", \
727                         __func__, __LINE__)); \
728                         regvar = 0; \
729                 } \
730         } \
731 } while (0)
732
733 #define W_SDREG(regval, regaddr, retryvar) \
734 do { \
735         retryvar = 0; \
736         do { \
737                 W_REG(regaddr, regval); \
738         } while (brcmf_sdcard_regfail(bus->sdh) && \
739                  (++retryvar <= retry_limit)); \
740         if (retryvar) { \
741                 bus->regfails += (retryvar-1); \
742                 if (retryvar > retry_limit) \
743                         DHD_ERROR(("%s: FAILED REGISTER WRITE, LINE %d\n", \
744                         __func__, __LINE__)); \
745         } \
746 } while (0)
747
748 #define DHD_BUS                 SDIO_BUS
749
750 #define PKT_AVAILABLE()         (intstatus & I_HMB_FRAME_IND)
751
752 #define HOSTINTMASK             (I_HMB_SW_MASK | I_CHIPACTIVE)
753
754 #ifdef SDTEST
755 static void brcmf_sdbrcm_checkdied(dhd_bus_t *bus, void *pkt, uint seq);
756 static void brcmf_sdbrcm_sdtest_set(dhd_bus_t *bus, bool start);
757 #endif
758
759 #ifdef DHD_DEBUG
760 static int brcmf_sdbrcm_checkdied(dhd_bus_t *bus, u8 *data, uint size);
761 static int brcmf_sdbrcm_mem_dump(dhd_bus_t *bus);
762 #endif                          /* DHD_DEBUG  */
763 static int brcmf_sdbrcm_download_state(dhd_bus_t *bus, bool enter);
764
765 static void brcmf_sdbrcm_release(dhd_bus_t *bus);
766 static void brcmf_sdbrcm_release_malloc(dhd_bus_t *bus);
767 static void brcmf_sdbrcm_disconnect(void *ptr);
768 static bool brcmf_sdbrcm_chipmatch(u16 chipid);
769 static bool brcmf_sdbrcm_probe_attach(dhd_bus_t *bus, void *sdh,
770                                  void *regsva, u16 devid);
771 static bool brcmf_sdbrcm_probe_malloc(dhd_bus_t *bus, void *sdh);
772 static bool brcmf_sdbrcm_probe_init(dhd_bus_t *bus, void *sdh);
773 static void brcmf_sdbrcm_release_dongle(dhd_bus_t *bus);
774
775 static uint brcmf_process_nvram_vars(char *varbuf, uint len);
776
777 static void brcmf_sdbrcm_setmemsize(struct dhd_bus *bus, int mem_size);
778 static int brcmf_sdbrcm_send_buf(dhd_bus_t *bus, u32 addr, uint fn,
779                                uint flags, u8 *buf, uint nbytes,
780                                struct sk_buff *pkt, bcmsdh_cmplt_fn_t complete,
781                                void *handle);
782
783 static bool brcmf_sdbrcm_download_firmware(struct dhd_bus *bus, void *sdh);
784 static int  _brcmf_sdbrcm_download_firmware(struct dhd_bus *bus);
785
786 static int
787 brcmf_sdbrcm_download_code_file(struct dhd_bus *bus, char *image_path);
788 static int brcmf_sdbrcm_download_nvram(struct dhd_bus *bus);
789 static void brcmf_sdbrcm_chip_disablecore(struct brcmf_sdio *sdh, u32 corebase);
790 static int brcmf_sdbrcm_chip_attach(struct dhd_bus *bus, void *regs);
791 static void brcmf_sdbrcm_chip_resetcore(struct brcmf_sdio *sdh, u32 corebase);
792 static void brcmf_sdbrcm_sdiod_drive_strength_init(struct dhd_bus *bus,
793                                         u32 drivestrength);
794 static void brcmf_sdbrcm_chip_detach(struct dhd_bus *bus);
795
796 /* Packet free applicable unconditionally for sdio and sdspi.
797  * Conditional if bufpool was present for gspi bus.
798  */
799 static void brcmf_sdbrcm_pktfree2(dhd_bus_t *bus, struct sk_buff *pkt)
800 {
801         if ((bus->bus != SPI_BUS) || bus->usebufpool)
802                 brcmu_pkt_buf_free_skb(pkt);
803 }
804
805 static void brcmf_sdbrcm_setmemsize(struct dhd_bus *bus, int mem_size)
806 {
807         s32 min_size = DONGLE_MIN_MEMSIZE;
808         /* Restrict the memsize to user specified limit */
809         DHD_ERROR(("user: Restrict the dongle ram size to %d, min %d\n",
810                 brcmf_dongle_memsize, min_size));
811         if ((brcmf_dongle_memsize > min_size) &&
812             (brcmf_dongle_memsize < (s32) bus->orig_ramsize))
813                 bus->ramsize = brcmf_dongle_memsize;
814 }
815
816 static int brcmf_sdbrcm_set_siaddr_window(dhd_bus_t *bus, u32 address)
817 {
818         int err = 0;
819         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SBADDRLOW,
820                          (address >> 8) & SBSDIO_SBADDRLOW_MASK, &err);
821         if (!err)
822                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1,
823                                  SBSDIO_FUNC1_SBADDRMID,
824                                  (address >> 16) & SBSDIO_SBADDRMID_MASK, &err);
825         if (!err)
826                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1,
827                                        SBSDIO_FUNC1_SBADDRHIGH,
828                                        (address >> 24) & SBSDIO_SBADDRHIGH_MASK,
829                                        &err);
830         return err;
831 }
832
833 /* Turn backplane clock on or off */
834 static int brcmf_sdbrcm_htclk(dhd_bus_t *bus, bool on, bool pendok)
835 {
836         int err;
837         u8 clkctl, clkreq, devctl;
838         struct brcmf_sdio *sdh;
839
840         DHD_TRACE(("%s: Enter\n", __func__));
841
842 #if defined(OOB_INTR_ONLY)
843         pendok = false;
844 #endif
845         clkctl = 0;
846         sdh = bus->sdh;
847
848         if (on) {
849                 /* Request HT Avail */
850                 clkreq =
851                     bus->alp_only ? SBSDIO_ALP_AVAIL_REQ : SBSDIO_HT_AVAIL_REQ;
852
853                 if ((bus->ci->chip == BCM4329_CHIP_ID)
854                     && (bus->ci->chiprev == 0))
855                         clkreq |= SBSDIO_FORCE_ALP;
856
857                 brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
858                                        SBSDIO_FUNC1_CHIPCLKCSR, clkreq, &err);
859                 if (err) {
860                         DHD_ERROR(("%s: HT Avail request error: %d\n",
861                                    __func__, err));
862                         return -EBADE;
863                 }
864
865                 if (pendok && ((bus->ci->buscoretype == PCMCIA_CORE_ID)
866                                && (bus->ci->buscorerev == 9))) {
867                         u32 dummy, retries;
868                         R_SDREG(dummy, &bus->regs->clockctlstatus, retries);
869                 }
870
871                 /* Check current status */
872                 clkctl = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
873                                                SBSDIO_FUNC1_CHIPCLKCSR, &err);
874                 if (err) {
875                         DHD_ERROR(("%s: HT Avail read error: %d\n",
876                                    __func__, err));
877                         return -EBADE;
878                 }
879
880                 /* Go to pending and await interrupt if appropriate */
881                 if (!SBSDIO_CLKAV(clkctl, bus->alp_only) && pendok) {
882                         /* Allow only clock-available interrupt */
883                         devctl = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
884                                         SBSDIO_DEVICE_CTL, &err);
885                         if (err) {
886                                 DHD_ERROR(("%s: Devctl error setting CA: %d\n",
887                                         __func__, err));
888                                 return -EBADE;
889                         }
890
891                         devctl |= SBSDIO_DEVCTL_CA_INT_ONLY;
892                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
893                                                SBSDIO_DEVICE_CTL, devctl, &err);
894                         DHD_INFO(("CLKCTL: set PENDING\n"));
895                         bus->clkstate = CLK_PENDING;
896
897                         return 0;
898                 } else if (bus->clkstate == CLK_PENDING) {
899                         /* Cancel CA-only interrupt filter */
900                         devctl =
901                             brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
902                                                   SBSDIO_DEVICE_CTL, &err);
903                         devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
904                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
905                                 SBSDIO_DEVICE_CTL, devctl, &err);
906                 }
907
908                 /* Otherwise, wait here (polling) for HT Avail */
909                 if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
910                         SPINWAIT_SLEEP(sdioh_spinwait_sleep,
911                                        ((clkctl =
912                                          brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
913                                                  SBSDIO_FUNC1_CHIPCLKCSR,
914                                                          &err)),
915                                         !SBSDIO_CLKAV(clkctl, bus->alp_only)),
916                                        PMU_MAX_TRANSITION_DLY);
917                 }
918                 if (err) {
919                         DHD_ERROR(("%s: HT Avail request error: %d\n",
920                                    __func__, err));
921                         return -EBADE;
922                 }
923                 if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
924                         DHD_ERROR(("%s: HT Avail timeout (%d): clkctl 0x%02x\n",
925                                    __func__, PMU_MAX_TRANSITION_DLY, clkctl));
926                         return -EBADE;
927                 }
928
929                 /* Mark clock available */
930                 bus->clkstate = CLK_AVAIL;
931                 DHD_INFO(("CLKCTL: turned ON\n"));
932
933 #if defined(DHD_DEBUG)
934                 if (bus->alp_only == true) {
935 #if !defined(BCMLXSDMMC)
936                         if (!SBSDIO_ALPONLY(clkctl)) {
937                                 DHD_ERROR(("%s: HT Clock, when ALP Only\n",
938                                            __func__));
939                         }
940 #endif                          /* !defined(BCMLXSDMMC) */
941                 } else {
942                         if (SBSDIO_ALPONLY(clkctl)) {
943                                 DHD_ERROR(("%s: HT Clock should be on.\n",
944                                            __func__));
945                         }
946                 }
947 #endif                          /* defined (DHD_DEBUG) */
948
949                 bus->activity = true;
950         } else {
951                 clkreq = 0;
952
953                 if (bus->clkstate == CLK_PENDING) {
954                         /* Cancel CA-only interrupt filter */
955                         devctl = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
956                                         SBSDIO_DEVICE_CTL, &err);
957                         devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
958                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
959                                 SBSDIO_DEVICE_CTL, devctl, &err);
960                 }
961
962                 bus->clkstate = CLK_SDONLY;
963                 brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
964                         SBSDIO_FUNC1_CHIPCLKCSR, clkreq, &err);
965                 DHD_INFO(("CLKCTL: turned OFF\n"));
966                 if (err) {
967                         DHD_ERROR(("%s: Failed access turning clock off: %d\n",
968                                    __func__, err));
969                         return -EBADE;
970                 }
971         }
972         return 0;
973 }
974
975 /* Change idle/active SD state */
976 static int brcmf_sdbrcm_sdclk(dhd_bus_t *bus, bool on)
977 {
978         DHD_TRACE(("%s: Enter\n", __func__));
979
980         if (on)
981                 bus->clkstate = CLK_SDONLY;
982         else
983                 bus->clkstate = CLK_NONE;
984
985         return 0;
986 }
987
988 /* Transition SD and backplane clock readiness */
989 static int brcmf_sdbrcm_clkctl(dhd_bus_t *bus, uint target, bool pendok)
990 {
991 #ifdef DHD_DEBUG
992         uint oldstate = bus->clkstate;
993 #endif                          /* DHD_DEBUG */
994
995         DHD_TRACE(("%s: Enter\n", __func__));
996
997         /* Early exit if we're already there */
998         if (bus->clkstate == target) {
999                 if (target == CLK_AVAIL) {
1000                         brcmf_os_wd_timer(bus->dhd, brcmf_watchdog_ms);
1001                         bus->activity = true;
1002                 }
1003                 return 0;
1004         }
1005
1006         switch (target) {
1007         case CLK_AVAIL:
1008                 /* Make sure SD clock is available */
1009                 if (bus->clkstate == CLK_NONE)
1010                         brcmf_sdbrcm_sdclk(bus, true);
1011                 /* Now request HT Avail on the backplane */
1012                 brcmf_sdbrcm_htclk(bus, true, pendok);
1013                 brcmf_os_wd_timer(bus->dhd, brcmf_watchdog_ms);
1014                 bus->activity = true;
1015                 break;
1016
1017         case CLK_SDONLY:
1018                 /* Remove HT request, or bring up SD clock */
1019                 if (bus->clkstate == CLK_NONE)
1020                         brcmf_sdbrcm_sdclk(bus, true);
1021                 else if (bus->clkstate == CLK_AVAIL)
1022                         brcmf_sdbrcm_htclk(bus, false, false);
1023                 else
1024                         DHD_ERROR(("brcmf_sdbrcm_clkctl: request for %d -> %d"
1025                                    "\n", bus->clkstate, target));
1026                 brcmf_os_wd_timer(bus->dhd, brcmf_watchdog_ms);
1027                 break;
1028
1029         case CLK_NONE:
1030                 /* Make sure to remove HT request */
1031                 if (bus->clkstate == CLK_AVAIL)
1032                         brcmf_sdbrcm_htclk(bus, false, false);
1033                 /* Now remove the SD clock */
1034                 brcmf_sdbrcm_sdclk(bus, false);
1035                 brcmf_os_wd_timer(bus->dhd, 0);
1036                 break;
1037         }
1038 #ifdef DHD_DEBUG
1039         DHD_INFO(("brcmf_sdbrcm_clkctl: %d -> %d\n", oldstate, bus->clkstate));
1040 #endif                          /* DHD_DEBUG */
1041
1042         return 0;
1043 }
1044
1045 int brcmf_sdbrcm_bussleep(dhd_bus_t *bus, bool sleep)
1046 {
1047         struct brcmf_sdio *sdh = bus->sdh;
1048         struct sdpcmd_regs *regs = bus->regs;
1049         uint retries = 0;
1050
1051         DHD_INFO(("brcmf_sdbrcm_bussleep: request %s (currently %s)\n",
1052                   (sleep ? "SLEEP" : "WAKE"),
1053                   (bus->sleeping ? "SLEEP" : "WAKE")));
1054
1055         /* Done if we're already in the requested state */
1056         if (sleep == bus->sleeping)
1057                 return 0;
1058
1059         /* Going to sleep: set the alarm and turn off the lights... */
1060         if (sleep) {
1061                 /* Don't sleep if something is pending */
1062                 if (bus->dpc_sched || bus->rxskip || pktq_len(&bus->txq))
1063                         return -EBUSY;
1064
1065                 /* Disable SDIO interrupts (no longer interested) */
1066                 brcmf_sdcard_intr_disable(bus->sdh);
1067
1068                 /* Make sure the controller has the bus up */
1069                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
1070
1071                 /* Tell device to start using OOB wakeup */
1072                 W_SDREG(SMB_USE_OOB, &regs->tosbmailbox, retries);
1073                 if (retries > retry_limit)
1074                         DHD_ERROR(("CANNOT SIGNAL CHIP, WILL NOT WAKE UP!!\n"));
1075
1076                 /* Turn off our contribution to the HT clock request */
1077                 brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
1078
1079                 brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
1080                         SBSDIO_FUNC1_CHIPCLKCSR,
1081                         SBSDIO_FORCE_HW_CLKREQ_OFF, NULL);
1082
1083                 /* Isolate the bus */
1084                 if (bus->ci->chip != BCM4329_CHIP_ID
1085                     && bus->ci->chip != BCM4319_CHIP_ID) {
1086                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
1087                                 SBSDIO_DEVICE_CTL,
1088                                 SBSDIO_DEVCTL_PADS_ISO, NULL);
1089                 }
1090
1091                 /* Change state */
1092                 bus->sleeping = true;
1093
1094         } else {
1095                 /* Waking up: bus power up is ok, set local state */
1096
1097                 brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
1098                         SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL);
1099
1100                 /* Force pad isolation off if possible
1101                          (in case power never toggled) */
1102                 if ((bus->ci->buscoretype == PCMCIA_CORE_ID)
1103                     && (bus->ci->buscorerev >= 10))
1104                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
1105                                 SBSDIO_DEVICE_CTL, 0, NULL);
1106
1107                 /* Make sure the controller has the bus up */
1108                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
1109
1110                 /* Send misc interrupt to indicate OOB not needed */
1111                 W_SDREG(0, &regs->tosbmailboxdata, retries);
1112                 if (retries <= retry_limit)
1113                         W_SDREG(SMB_DEV_INT, &regs->tosbmailbox, retries);
1114
1115                 if (retries > retry_limit)
1116                         DHD_ERROR(("CANNOT SIGNAL CHIP TO CLEAR OOB!!\n"));
1117
1118                 /* Make sure we have SD bus access */
1119                 brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
1120
1121                 /* Change state */
1122                 bus->sleeping = false;
1123
1124                 /* Enable interrupts again */
1125                 if (bus->intr && (bus->dhd->busstate == DHD_BUS_DATA)) {
1126                         bus->intdis = false;
1127                         brcmf_sdcard_intr_enable(bus->sdh);
1128                 }
1129         }
1130
1131         return 0;
1132 }
1133
1134 #if defined(OOB_INTR_ONLY)
1135 void brcmf_sdbrcm_enable_oob_intr(struct dhd_bus *bus, bool enable)
1136 {
1137 #if defined(HW_OOB)
1138         brcmf_sdcard_enable_hw_oob_intr(bus->sdh, enable);
1139 #else
1140         sdpcmd_regs_t *regs = bus->regs;
1141         uint retries = 0;
1142
1143         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
1144         if (enable == true) {
1145
1146                 /* Tell device to start using OOB wakeup */
1147                 W_SDREG(SMB_USE_OOB, &regs->tosbmailbox, retries);
1148                 if (retries > retry_limit)
1149                         DHD_ERROR(("CANNOT SIGNAL CHIP, WILL NOT WAKE UP!!\n"));
1150
1151         } else {
1152                 /* Send misc interrupt to indicate OOB not needed */
1153                 W_SDREG(0, &regs->tosbmailboxdata, retries);
1154                 if (retries <= retry_limit)
1155                         W_SDREG(SMB_DEV_INT, &regs->tosbmailbox, retries);
1156         }
1157
1158         /* Turn off our contribution to the HT clock request */
1159         brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
1160 #endif                          /* !defined(HW_OOB) */
1161 }
1162 #endif                          /* defined(OOB_INTR_ONLY) */
1163
1164 #define BUS_WAKE(bus) \
1165         do { \
1166                 if ((bus)->sleeping) \
1167                         brcmf_sdbrcm_bussleep((bus), false); \
1168         } while (0);
1169
1170 /* Writes a HW/SW header into the packet and sends it. */
1171 /* Assumes: (a) header space already there, (b) caller holds lock */
1172 static int brcmf_sdbrcm_txpkt(dhd_bus_t *bus, struct sk_buff *pkt, uint chan,
1173                          bool free_pkt)
1174 {
1175         int ret;
1176         u8 *frame;
1177         u16 len, pad = 0;
1178         u32 swheader;
1179         uint retries = 0;
1180         struct brcmf_sdio *sdh;
1181         struct sk_buff *new;
1182         int i;
1183
1184         DHD_TRACE(("%s: Enter\n", __func__));
1185
1186         sdh = bus->sdh;
1187
1188         if (bus->dhd->dongle_reset) {
1189                 ret = -EPERM;
1190                 goto done;
1191         }
1192
1193         frame = (u8 *) (pkt->data);
1194
1195         /* Add alignment padding, allocate new packet if needed */
1196         pad = ((unsigned long)frame % DHD_SDALIGN);
1197         if (pad) {
1198                 if (skb_headroom(pkt) < pad) {
1199                         DHD_INFO(("%s: insufficient headroom %d for %d pad\n",
1200                                   __func__, skb_headroom(pkt), pad));
1201                         bus->dhd->tx_realloc++;
1202                         new = brcmu_pkt_buf_get_skb(pkt->len + DHD_SDALIGN);
1203                         if (!new) {
1204                                 DHD_ERROR(("%s: couldn't allocate new %d-byte "
1205                                         "packet\n",
1206                                         __func__, pkt->len + DHD_SDALIGN));
1207                                 ret = -ENOMEM;
1208                                 goto done;
1209                         }
1210
1211                         PKTALIGN(new, pkt->len, DHD_SDALIGN);
1212                         memcpy(new->data, pkt->data, pkt->len);
1213                         if (free_pkt)
1214                                 brcmu_pkt_buf_free_skb(pkt);
1215                         /* free the pkt if canned one is not used */
1216                         free_pkt = true;
1217                         pkt = new;
1218                         frame = (u8 *) (pkt->data);
1219                         ASSERT(((unsigned long)frame % DHD_SDALIGN) == 0);
1220                         pad = 0;
1221                 } else {
1222                         skb_push(pkt, pad);
1223                         frame = (u8 *) (pkt->data);
1224
1225                         ASSERT((pad + SDPCM_HDRLEN) <= (int)(pkt->len));
1226                         memset(frame, 0, pad + SDPCM_HDRLEN);
1227                 }
1228         }
1229         ASSERT(pad < DHD_SDALIGN);
1230
1231         /* Hardware tag: 2 byte len followed by 2 byte ~len check (all LE) */
1232         len = (u16) (pkt->len);
1233         *(u16 *) frame = cpu_to_le16(len);
1234         *(((u16 *) frame) + 1) = cpu_to_le16(~len);
1235
1236         /* Software tag: channel, sequence number, data offset */
1237         swheader =
1238             ((chan << SDPCM_CHANNEL_SHIFT) & SDPCM_CHANNEL_MASK) | bus->tx_seq |
1239             (((pad +
1240                SDPCM_HDRLEN) << SDPCM_DOFFSET_SHIFT) & SDPCM_DOFFSET_MASK);
1241
1242         put_unaligned_le32(swheader, frame + SDPCM_FRAMETAG_LEN);
1243         put_unaligned_le32(0, frame + SDPCM_FRAMETAG_LEN + sizeof(swheader));
1244
1245 #ifdef DHD_DEBUG
1246         tx_packets[pkt->priority]++;
1247         if (DHD_BYTES_ON() &&
1248             (((DHD_CTL_ON() && (chan == SDPCM_CONTROL_CHANNEL)) ||
1249               (DHD_DATA_ON() && (chan != SDPCM_CONTROL_CHANNEL))))) {
1250                 printk(KERN_DEBUG "Tx Frame:\n");
1251                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, frame, len);
1252         } else if (DHD_HDRS_ON()) {
1253                 printk(KERN_DEBUG "TxHdr:\n");
1254                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
1255                                      frame, min_t(u16, len, 16));
1256         }
1257 #endif
1258
1259         /* Raise len to next SDIO block to eliminate tail command */
1260         if (bus->roundup && bus->blocksize && (len > bus->blocksize)) {
1261                 u16 pad = bus->blocksize - (len % bus->blocksize);
1262                 if ((pad <= bus->roundup) && (pad < bus->blocksize))
1263 #ifdef NOTUSED
1264                         if (pad <= skb_tailroom(pkt))
1265 #endif                          /* NOTUSED */
1266                                 len += pad;
1267         } else if (len % DHD_SDALIGN) {
1268                 len += DHD_SDALIGN - (len % DHD_SDALIGN);
1269         }
1270
1271         /* Some controllers have trouble with odd bytes -- round to even */
1272         if (forcealign && (len & (ALIGNMENT - 1))) {
1273 #ifdef NOTUSED
1274                 if (skb_tailroom(pkt))
1275 #endif
1276                         len = roundup(len, ALIGNMENT);
1277 #ifdef NOTUSED
1278                 else
1279                         DHD_ERROR(("%s: sending unrounded %d-byte packet\n",
1280                                    __func__, len));
1281 #endif
1282         }
1283
1284         do {
1285                 ret = brcmf_sdbrcm_send_buf(bus, brcmf_sdcard_cur_sbwad(sdh),
1286                         SDIO_FUNC_2, F2SYNC, frame, len, pkt, NULL, NULL);
1287                 bus->f2txdata++;
1288                 ASSERT(ret != -BCME_PENDING);
1289
1290                 if (ret < 0) {
1291                         /* On failure, abort the command
1292                          and terminate the frame */
1293                         DHD_INFO(("%s: sdio error %d, abort command and "
1294                                 "terminate frame.\n", __func__, ret));
1295                         bus->tx_sderrs++;
1296
1297                         brcmf_sdcard_abort(sdh, SDIO_FUNC_2);
1298                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
1299                                          SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM,
1300                                          NULL);
1301                         bus->f1regdata++;
1302
1303                         for (i = 0; i < 3; i++) {
1304                                 u8 hi, lo;
1305                                 hi = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
1306                                                      SBSDIO_FUNC1_WFRAMEBCHI,
1307                                                      NULL);
1308                                 lo = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
1309                                                      SBSDIO_FUNC1_WFRAMEBCLO,
1310                                                      NULL);
1311                                 bus->f1regdata += 2;
1312                                 if ((hi == 0) && (lo == 0))
1313                                         break;
1314                         }
1315
1316                 }
1317                 if (ret == 0)
1318                         bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP;
1319
1320         } while ((ret < 0) && retrydata && retries++ < TXRETRIES);
1321
1322 done:
1323         /* restore pkt buffer pointer before calling tx complete routine */
1324         skb_pull(pkt, SDPCM_HDRLEN + pad);
1325         brcmf_os_sdunlock(bus->dhd);
1326         brcmf_txcomplete(bus->dhd, pkt, ret != 0);
1327         brcmf_os_sdlock(bus->dhd);
1328
1329         if (free_pkt)
1330                 brcmu_pkt_buf_free_skb(pkt);
1331
1332         return ret;
1333 }
1334
1335 int brcmf_sdbrcm_bus_txdata(struct dhd_bus *bus, struct sk_buff *pkt)
1336 {
1337         int ret = -EBADE;
1338         uint datalen, prec;
1339
1340         DHD_TRACE(("%s: Enter\n", __func__));
1341
1342         datalen = pkt->len;
1343
1344 #ifdef SDTEST
1345         /* Push the test header if doing loopback */
1346         if (bus->ext_loop) {
1347                 u8 *data;
1348                 skb_push(pkt, SDPCM_TEST_HDRLEN);
1349                 data = pkt->data;
1350                 *data++ = SDPCM_TEST_ECHOREQ;
1351                 *data++ = (u8) bus->loopid++;
1352                 *data++ = (datalen >> 0);
1353                 *data++ = (datalen >> 8);
1354                 datalen += SDPCM_TEST_HDRLEN;
1355         }
1356 #endif                          /* SDTEST */
1357
1358         /* Add space for the header */
1359         skb_push(pkt, SDPCM_HDRLEN);
1360         ASSERT(IS_ALIGNED((unsigned long)(pkt->data), 2));
1361
1362         prec = PRIO2PREC((pkt->priority & PRIOMASK));
1363
1364         /* Check for existing queue, current flow-control,
1365                          pending event, or pending clock */
1366         if (brcmf_deferred_tx || bus->fcstate || pktq_len(&bus->txq)
1367             || bus->dpc_sched || (!DATAOK(bus))
1368             || (bus->flowcontrol & NBITVAL(prec))
1369             || (bus->clkstate != CLK_AVAIL)) {
1370                 DHD_TRACE(("%s: deferring pktq len %d\n", __func__,
1371                            pktq_len(&bus->txq)));
1372                 bus->fcqueued++;
1373
1374                 /* Priority based enq */
1375                 spin_lock_bh(&bus->txqlock);
1376                 if (brcmf_c_prec_enq(bus->dhd, &bus->txq, pkt, prec) == false) {
1377                         skb_pull(pkt, SDPCM_HDRLEN);
1378                         brcmf_txcomplete(bus->dhd, pkt, false);
1379                         brcmu_pkt_buf_free_skb(pkt);
1380                         DHD_ERROR(("%s: out of bus->txq !!!\n", __func__));
1381                         ret = -ENOSR;
1382                 } else {
1383                         ret = 0;
1384                 }
1385                 spin_unlock_bh(&bus->txqlock);
1386
1387                 if (pktq_len(&bus->txq) >= TXHI)
1388                         brcmf_txflowcontrol(bus->dhd, 0, ON);
1389
1390 #ifdef DHD_DEBUG
1391                 if (pktq_plen(&bus->txq, prec) > qcount[prec])
1392                         qcount[prec] = pktq_plen(&bus->txq, prec);
1393 #endif
1394                 /* Schedule DPC if needed to send queued packet(s) */
1395                 if (brcmf_deferred_tx && !bus->dpc_sched) {
1396                         bus->dpc_sched = true;
1397                         brcmf_sched_dpc(bus->dhd);
1398                 }
1399         } else {
1400                 /* Lock: we're about to use shared data/code (and SDIO) */
1401                 brcmf_os_sdlock(bus->dhd);
1402
1403                 /* Otherwise, send it now */
1404                 BUS_WAKE(bus);
1405                 /* Make sure back plane ht clk is on, no pending allowed */
1406                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, true);
1407
1408 #ifndef SDTEST
1409                 DHD_TRACE(("%s: calling txpkt\n", __func__));
1410                 ret = brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_DATA_CHANNEL, true);
1411 #else
1412                 ret = brcmf_sdbrcm_txpkt(bus, pkt,
1413                                     (bus->ext_loop ? SDPCM_TEST_CHANNEL :
1414                                      SDPCM_DATA_CHANNEL), true);
1415 #endif
1416                 if (ret)
1417                         bus->dhd->tx_errors++;
1418                 else
1419                         bus->dhd->dstats.tx_bytes += datalen;
1420
1421                 if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) {
1422                         bus->activity = false;
1423                         brcmf_sdbrcm_clkctl(bus, CLK_NONE, true);
1424                 }
1425
1426                 brcmf_os_sdunlock(bus->dhd);
1427         }
1428
1429         return ret;
1430 }
1431
1432 static uint brcmf_sdbrcm_sendfromq(dhd_bus_t *bus, uint maxframes)
1433 {
1434         struct sk_buff *pkt;
1435         u32 intstatus = 0;
1436         uint retries = 0;
1437         int ret = 0, prec_out;
1438         uint cnt = 0;
1439         uint datalen;
1440         u8 tx_prec_map;
1441
1442         dhd_pub_t *dhd = bus->dhd;
1443         struct sdpcmd_regs *regs = bus->regs;
1444
1445         DHD_TRACE(("%s: Enter\n", __func__));
1446
1447         tx_prec_map = ~bus->flowcontrol;
1448
1449         /* Send frames until the limit or some other event */
1450         for (cnt = 0; (cnt < maxframes) && DATAOK(bus); cnt++) {
1451                 spin_lock_bh(&bus->txqlock);
1452                 pkt = brcmu_pktq_mdeq(&bus->txq, tx_prec_map, &prec_out);
1453                 if (pkt == NULL) {
1454                         spin_unlock_bh(&bus->txqlock);
1455                         break;
1456                 }
1457                 spin_unlock_bh(&bus->txqlock);
1458                 datalen = pkt->len - SDPCM_HDRLEN;
1459
1460 #ifndef SDTEST
1461                 ret = brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_DATA_CHANNEL, true);
1462 #else
1463                 ret = brcmf_sdbrcm_txpkt(bus, pkt,
1464                                     (bus->ext_loop ? SDPCM_TEST_CHANNEL :
1465                                      SDPCM_DATA_CHANNEL), true);
1466 #endif
1467                 if (ret)
1468                         bus->dhd->tx_errors++;
1469                 else
1470                         bus->dhd->dstats.tx_bytes += datalen;
1471
1472                 /* In poll mode, need to check for other events */
1473                 if (!bus->intr && cnt) {
1474                         /* Check device status, signal pending interrupt */
1475                         R_SDREG(intstatus, &regs->intstatus, retries);
1476                         bus->f2txdata++;
1477                         if (brcmf_sdcard_regfail(bus->sdh))
1478                                 break;
1479                         if (intstatus & bus->hostintmask)
1480                                 bus->ipend = true;
1481                 }
1482         }
1483
1484         /* Deflow-control stack if needed */
1485         if (dhd->up && (dhd->busstate == DHD_BUS_DATA) &&
1486             dhd->txoff && (pktq_len(&bus->txq) < TXLOW))
1487                 brcmf_txflowcontrol(dhd, 0, OFF);
1488
1489         return cnt;
1490 }
1491
1492 int
1493 brcmf_sdbrcm_bus_txctl(struct dhd_bus *bus, unsigned char *msg, uint msglen)
1494 {
1495         u8 *frame;
1496         u16 len;
1497         u32 swheader;
1498         uint retries = 0;
1499         struct brcmf_sdio *sdh = bus->sdh;
1500         u8 doff = 0;
1501         int ret = -1;
1502         int i;
1503
1504         DHD_TRACE(("%s: Enter\n", __func__));
1505
1506         if (bus->dhd->dongle_reset)
1507                 return -EIO;
1508
1509         /* Back the pointer to make a room for bus header */
1510         frame = msg - SDPCM_HDRLEN;
1511         len = (msglen += SDPCM_HDRLEN);
1512
1513         /* Add alignment padding (optional for ctl frames) */
1514         if (dhd_alignctl) {
1515                 doff = ((unsigned long)frame % DHD_SDALIGN);
1516                 if (doff) {
1517                         frame -= doff;
1518                         len += doff;
1519                         msglen += doff;
1520                         memset(frame, 0, doff + SDPCM_HDRLEN);
1521                 }
1522                 ASSERT(doff < DHD_SDALIGN);
1523         }
1524         doff += SDPCM_HDRLEN;
1525
1526         /* Round send length to next SDIO block */
1527         if (bus->roundup && bus->blocksize && (len > bus->blocksize)) {
1528                 u16 pad = bus->blocksize - (len % bus->blocksize);
1529                 if ((pad <= bus->roundup) && (pad < bus->blocksize))
1530                         len += pad;
1531         } else if (len % DHD_SDALIGN) {
1532                 len += DHD_SDALIGN - (len % DHD_SDALIGN);
1533         }
1534
1535         /* Satisfy length-alignment requirements */
1536         if (forcealign && (len & (ALIGNMENT - 1)))
1537                 len = roundup(len, ALIGNMENT);
1538
1539         ASSERT(IS_ALIGNED((unsigned long)frame, 2));
1540
1541         /* Need to lock here to protect txseq and SDIO tx calls */
1542         brcmf_os_sdlock(bus->dhd);
1543
1544         BUS_WAKE(bus);
1545
1546         /* Make sure backplane clock is on */
1547         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
1548
1549         /* Hardware tag: 2 byte len followed by 2 byte ~len check (all LE) */
1550         *(u16 *) frame = cpu_to_le16((u16) msglen);
1551         *(((u16 *) frame) + 1) = cpu_to_le16(~msglen);
1552
1553         /* Software tag: channel, sequence number, data offset */
1554         swheader =
1555             ((SDPCM_CONTROL_CHANNEL << SDPCM_CHANNEL_SHIFT) &
1556              SDPCM_CHANNEL_MASK)
1557             | bus->tx_seq | ((doff << SDPCM_DOFFSET_SHIFT) &
1558                              SDPCM_DOFFSET_MASK);
1559         put_unaligned_le32(swheader, frame + SDPCM_FRAMETAG_LEN);
1560         put_unaligned_le32(0, frame + SDPCM_FRAMETAG_LEN + sizeof(swheader));
1561
1562         if (!DATAOK(bus)) {
1563                 DHD_INFO(("%s: No bus credit bus->tx_max %d, bus->tx_seq %d\n",
1564                           __func__, bus->tx_max, bus->tx_seq));
1565                 bus->ctrl_frame_stat = true;
1566                 /* Send from dpc */
1567                 bus->ctrl_frame_buf = frame;
1568                 bus->ctrl_frame_len = len;
1569
1570                 brcmf_wait_for_event(bus->dhd, &bus->ctrl_frame_stat);
1571
1572                 if (bus->ctrl_frame_stat == false) {
1573                         DHD_INFO(("%s: ctrl_frame_stat == false\n", __func__));
1574                         ret = 0;
1575                 } else {
1576                         DHD_INFO(("%s: ctrl_frame_stat == true\n", __func__));
1577                         ret = -1;
1578                 }
1579         }
1580
1581         if (ret == -1) {
1582 #ifdef DHD_DEBUG
1583                 if (DHD_BYTES_ON() && DHD_CTL_ON()) {
1584                         printk(KERN_DEBUG "Tx Frame:\n");
1585                         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
1586                                              frame, len);
1587                 } else if (DHD_HDRS_ON()) {
1588                         printk(KERN_DEBUG "TxHdr:\n");
1589                         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
1590                                              frame, min_t(u16, len, 16));
1591                 }
1592 #endif
1593
1594                 do {
1595                         bus->ctrl_frame_stat = false;
1596                         ret = brcmf_sdbrcm_send_buf(bus,
1597                                 brcmf_sdcard_cur_sbwad(sdh), SDIO_FUNC_2,
1598                                 F2SYNC, frame, len, NULL, NULL, NULL);
1599
1600                         ASSERT(ret != -BCME_PENDING);
1601
1602                         if (ret < 0) {
1603                                 /* On failure, abort the command and
1604                                  terminate the frame */
1605                                 DHD_INFO(("%s: sdio error %d, abort command and terminate frame.\n",
1606                                         __func__, ret));
1607                                 bus->tx_sderrs++;
1608
1609                                 brcmf_sdcard_abort(sdh, SDIO_FUNC_2);
1610
1611                                 brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
1612                                                  SBSDIO_FUNC1_FRAMECTRL,
1613                                                  SFC_WF_TERM, NULL);
1614                                 bus->f1regdata++;
1615
1616                                 for (i = 0; i < 3; i++) {
1617                                         u8 hi, lo;
1618                                         hi = brcmf_sdcard_cfg_read(sdh,
1619                                              SDIO_FUNC_1,
1620                                              SBSDIO_FUNC1_WFRAMEBCHI,
1621                                              NULL);
1622                                         lo = brcmf_sdcard_cfg_read(sdh,
1623                                              SDIO_FUNC_1,
1624                                              SBSDIO_FUNC1_WFRAMEBCLO,
1625                                              NULL);
1626                                         bus->f1regdata += 2;
1627                                         if ((hi == 0) && (lo == 0))
1628                                                 break;
1629                                 }
1630
1631                         }
1632                         if (ret == 0) {
1633                                 bus->tx_seq =
1634                                     (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP;
1635                         }
1636                 } while ((ret < 0) && retries++ < TXRETRIES);
1637         }
1638
1639         if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) {
1640                 bus->activity = false;
1641                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, true);
1642         }
1643
1644         brcmf_os_sdunlock(bus->dhd);
1645
1646         if (ret)
1647                 bus->dhd->tx_ctlerrs++;
1648         else
1649                 bus->dhd->tx_ctlpkts++;
1650
1651         return ret ? -EIO : 0;
1652 }
1653
1654 int brcmf_sdbrcm_bus_rxctl(struct dhd_bus *bus, unsigned char *msg, uint msglen)
1655 {
1656         int timeleft;
1657         uint rxlen = 0;
1658         bool pending;
1659
1660         DHD_TRACE(("%s: Enter\n", __func__));
1661
1662         if (bus->dhd->dongle_reset)
1663                 return -EIO;
1664
1665         /* Wait until control frame is available */
1666         timeleft = brcmf_os_ioctl_resp_wait(bus->dhd, &bus->rxlen, &pending);
1667
1668         brcmf_os_sdlock(bus->dhd);
1669         rxlen = bus->rxlen;
1670         memcpy(msg, bus->rxctl, min(msglen, rxlen));
1671         bus->rxlen = 0;
1672         brcmf_os_sdunlock(bus->dhd);
1673
1674         if (rxlen) {
1675                 DHD_CTL(("%s: resumed on rxctl frame, got %d expected %d\n",
1676                          __func__, rxlen, msglen));
1677         } else if (timeleft == 0) {
1678                 DHD_ERROR(("%s: resumed on timeout\n", __func__));
1679 #ifdef DHD_DEBUG
1680                 brcmf_os_sdlock(bus->dhd);
1681                 brcmf_sdbrcm_checkdied(bus, NULL, 0);
1682                 brcmf_os_sdunlock(bus->dhd);
1683 #endif                          /* DHD_DEBUG */
1684         } else if (pending == true) {
1685                 DHD_CTL(("%s: cancelled\n", __func__));
1686                 return -ERESTARTSYS;
1687         } else {
1688                 DHD_CTL(("%s: resumed for unknown reason?\n", __func__));
1689 #ifdef DHD_DEBUG
1690                 brcmf_os_sdlock(bus->dhd);
1691                 brcmf_sdbrcm_checkdied(bus, NULL, 0);
1692                 brcmf_os_sdunlock(bus->dhd);
1693 #endif                          /* DHD_DEBUG */
1694         }
1695
1696         if (rxlen)
1697                 bus->dhd->rx_ctlpkts++;
1698         else
1699                 bus->dhd->rx_ctlerrs++;
1700
1701         return rxlen ? (int)rxlen : -ETIMEDOUT;
1702 }
1703
1704 /* IOVar table */
1705 enum {
1706         IOV_INTR = 1,
1707         IOV_POLLRATE,
1708         IOV_SDREG,
1709         IOV_SBREG,
1710         IOV_SDCIS,
1711         IOV_MEMBYTES,
1712         IOV_MEMSIZE,
1713 #ifdef DHD_DEBUG
1714         IOV_CHECKDIED,
1715 #endif
1716         IOV_DOWNLOAD,
1717         IOV_FORCEEVEN,
1718         IOV_SDIOD_DRIVE,
1719         IOV_READAHEAD,
1720         IOV_SDRXCHAIN,
1721         IOV_ALIGNCTL,
1722         IOV_SDALIGN,
1723         IOV_DEVRESET,
1724         IOV_CPU,
1725 #ifdef SDTEST
1726         IOV_PKTGEN,
1727         IOV_EXTLOOP,
1728 #endif                          /* SDTEST */
1729         IOV_SPROM,
1730         IOV_TXBOUND,
1731         IOV_RXBOUND,
1732         IOV_TXMINMAX,
1733         IOV_IDLETIME,
1734         IOV_IDLECLOCK,
1735         IOV_SD1IDLE,
1736         IOV_SLEEP,
1737         IOV_VARS
1738 };
1739
1740 const struct brcmu_iovar dhdsdio_iovars[] = {
1741         {"intr", IOV_INTR, 0, IOVT_BOOL, 0},
1742         {"sleep", IOV_SLEEP, 0, IOVT_BOOL, 0},
1743         {"pollrate", IOV_POLLRATE, 0, IOVT_UINT32, 0},
1744         {"idletime", IOV_IDLETIME, 0, IOVT_INT32, 0},
1745         {"idleclock", IOV_IDLECLOCK, 0, IOVT_INT32, 0},
1746         {"sd1idle", IOV_SD1IDLE, 0, IOVT_BOOL, 0},
1747         {"membytes", IOV_MEMBYTES, 0, IOVT_BUFFER, 2 * sizeof(int)},
1748         {"memsize", IOV_MEMSIZE, 0, IOVT_UINT32, 0},
1749         {"download", IOV_DOWNLOAD, 0, IOVT_BOOL, 0},
1750         {"vars", IOV_VARS, 0, IOVT_BUFFER, 0},
1751         {"sdiod_drive", IOV_SDIOD_DRIVE, 0, IOVT_UINT32, 0},
1752         {"readahead", IOV_READAHEAD, 0, IOVT_BOOL, 0},
1753         {"sdrxchain", IOV_SDRXCHAIN, 0, IOVT_BOOL, 0},
1754         {"alignctl", IOV_ALIGNCTL, 0, IOVT_BOOL, 0},
1755         {"sdalign", IOV_SDALIGN, 0, IOVT_BOOL, 0},
1756         {"devreset", IOV_DEVRESET, 0, IOVT_BOOL, 0},
1757 #ifdef DHD_DEBUG
1758         {"sdreg", IOV_SDREG, 0, IOVT_BUFFER, sizeof(sdreg_t)}
1759         ,
1760         {"sbreg", IOV_SBREG, 0, IOVT_BUFFER, sizeof(sdreg_t)}
1761         ,
1762         {"sd_cis", IOV_SDCIS, 0, IOVT_BUFFER, DHD_IOCTL_MAXLEN}
1763         ,
1764         {"forcealign", IOV_FORCEEVEN, 0, IOVT_BOOL, 0}
1765         ,
1766         {"txbound", IOV_TXBOUND, 0, IOVT_UINT32, 0}
1767         ,
1768         {"rxbound", IOV_RXBOUND, 0, IOVT_UINT32, 0}
1769         ,
1770         {"txminmax", IOV_TXMINMAX, 0, IOVT_UINT32, 0}
1771         ,
1772         {"cpu", IOV_CPU, 0, IOVT_BOOL, 0}
1773         ,
1774 #ifdef DHD_DEBUG
1775         {"checkdied", IOV_CHECKDIED, 0, IOVT_BUFFER, 0}
1776         ,
1777 #endif                          /* DHD_DEBUG  */
1778 #endif                          /* DHD_DEBUG */
1779 #ifdef SDTEST
1780         {"extloop", IOV_EXTLOOP, 0, IOVT_BOOL, 0}
1781         ,
1782         {"pktgen", IOV_PKTGEN, 0, IOVT_BUFFER, sizeof(brcmf_pktgen_t)}
1783         ,
1784 #endif                          /* SDTEST */
1785
1786         {NULL, 0, 0, 0, 0}
1787 };
1788
1789 static void
1790 dhd_dump_pct(struct brcmu_strbuf *strbuf, char *desc, uint num, uint div)
1791 {
1792         uint q1, q2;
1793
1794         if (!div) {
1795                 brcmu_bprintf(strbuf, "%s N/A", desc);
1796         } else {
1797                 q1 = num / div;
1798                 q2 = (100 * (num - (q1 * div))) / div;
1799                 brcmu_bprintf(strbuf, "%s %d.%02d", desc, q1, q2);
1800         }
1801 }
1802
1803 void brcmf_sdbrcm_bus_dump(dhd_pub_t *dhdp, struct brcmu_strbuf *strbuf)
1804 {
1805         dhd_bus_t *bus = dhdp->bus;
1806
1807         brcmu_bprintf(strbuf, "Bus SDIO structure:\n");
1808         brcmu_bprintf(strbuf,
1809                     "hostintmask 0x%08x intstatus 0x%08x sdpcm_ver %d\n",
1810                     bus->hostintmask, bus->intstatus, bus->sdpcm_ver);
1811         brcmu_bprintf(strbuf,
1812                     "fcstate %d qlen %d tx_seq %d, max %d, rxskip %d rxlen %d rx_seq %d\n",
1813                     bus->fcstate, pktq_len(&bus->txq), bus->tx_seq, bus->tx_max,
1814                     bus->rxskip, bus->rxlen, bus->rx_seq);
1815         brcmu_bprintf(strbuf, "intr %d intrcount %d lastintrs %d spurious %d\n",
1816                     bus->intr, bus->intrcount, bus->lastintrs, bus->spurious);
1817         brcmu_bprintf(strbuf, "pollrate %d pollcnt %d regfails %d\n",
1818                     bus->pollrate, bus->pollcnt, bus->regfails);
1819
1820         brcmu_bprintf(strbuf, "\nAdditional counters:\n");
1821         brcmu_bprintf(strbuf,
1822                     "tx_sderrs %d fcqueued %d rxrtx %d rx_toolong %d rxc_errors %d\n",
1823                     bus->tx_sderrs, bus->fcqueued, bus->rxrtx, bus->rx_toolong,
1824                     bus->rxc_errors);
1825         brcmu_bprintf(strbuf, "rx_hdrfail %d badhdr %d badseq %d\n",
1826                     bus->rx_hdrfail, bus->rx_badhdr, bus->rx_badseq);
1827         brcmu_bprintf(strbuf, "fc_rcvd %d, fc_xoff %d, fc_xon %d\n",
1828                       bus->fc_rcvd, bus->fc_xoff, bus->fc_xon);
1829         brcmu_bprintf(strbuf, "rxglomfail %d, rxglomframes %d, rxglompkts %d\n",
1830                     bus->rxglomfail, bus->rxglomframes, bus->rxglompkts);
1831         brcmu_bprintf(strbuf, "f2rx (hdrs/data) %d (%d/%d), f2tx %d f1regs"
1832                       " %d\n",
1833                       (bus->f2rxhdrs + bus->f2rxdata), bus->f2rxhdrs,
1834                       bus->f2rxdata, bus->f2txdata, bus->f1regdata);
1835         {
1836                 dhd_dump_pct(strbuf, "\nRx: pkts/f2rd", bus->dhd->rx_packets,
1837                              (bus->f2rxhdrs + bus->f2rxdata));
1838                 dhd_dump_pct(strbuf, ", pkts/f1sd", bus->dhd->rx_packets,
1839                              bus->f1regdata);
1840                 dhd_dump_pct(strbuf, ", pkts/sd", bus->dhd->rx_packets,
1841                              (bus->f2rxhdrs + bus->f2rxdata + bus->f1regdata));
1842                 dhd_dump_pct(strbuf, ", pkts/int", bus->dhd->rx_packets,
1843                              bus->intrcount);
1844                 brcmu_bprintf(strbuf, "\n");
1845
1846                 dhd_dump_pct(strbuf, "Rx: glom pct", (100 * bus->rxglompkts),
1847                              bus->dhd->rx_packets);
1848                 dhd_dump_pct(strbuf, ", pkts/glom", bus->rxglompkts,
1849                              bus->rxglomframes);
1850                 brcmu_bprintf(strbuf, "\n");
1851
1852                 dhd_dump_pct(strbuf, "Tx: pkts/f2wr", bus->dhd->tx_packets,
1853                              bus->f2txdata);
1854                 dhd_dump_pct(strbuf, ", pkts/f1sd", bus->dhd->tx_packets,
1855                              bus->f1regdata);
1856                 dhd_dump_pct(strbuf, ", pkts/sd", bus->dhd->tx_packets,
1857                              (bus->f2txdata + bus->f1regdata));
1858                 dhd_dump_pct(strbuf, ", pkts/int", bus->dhd->tx_packets,
1859                              bus->intrcount);
1860                 brcmu_bprintf(strbuf, "\n");
1861
1862                 dhd_dump_pct(strbuf, "Total: pkts/f2rw",
1863                              (bus->dhd->tx_packets + bus->dhd->rx_packets),
1864                              (bus->f2txdata + bus->f2rxhdrs + bus->f2rxdata));
1865                 dhd_dump_pct(strbuf, ", pkts/f1sd",
1866                              (bus->dhd->tx_packets + bus->dhd->rx_packets),
1867                              bus->f1regdata);
1868                 dhd_dump_pct(strbuf, ", pkts/sd",
1869                              (bus->dhd->tx_packets + bus->dhd->rx_packets),
1870                              (bus->f2txdata + bus->f2rxhdrs + bus->f2rxdata +
1871                               bus->f1regdata));
1872                 dhd_dump_pct(strbuf, ", pkts/int",
1873                              (bus->dhd->tx_packets + bus->dhd->rx_packets),
1874                              bus->intrcount);
1875                 brcmu_bprintf(strbuf, "\n\n");
1876         }
1877
1878 #ifdef SDTEST
1879         if (bus->pktgen_count) {
1880                 brcmu_bprintf(strbuf, "pktgen config and count:\n");
1881                 brcmu_bprintf(strbuf,
1882                             "freq %d count %d print %d total %d min %d len %d\n",
1883                             bus->pktgen_freq, bus->pktgen_count,
1884                             bus->pktgen_print, bus->pktgen_total,
1885                             bus->pktgen_minlen, bus->pktgen_maxlen);
1886                 brcmu_bprintf(strbuf, "send attempts %d rcvd %d fail %d\n",
1887                             bus->pktgen_sent, bus->pktgen_rcvd,
1888                             bus->pktgen_fail);
1889         }
1890 #endif                          /* SDTEST */
1891 #ifdef DHD_DEBUG
1892         brcmu_bprintf(strbuf, "dpc_sched %d host interrupt%spending\n",
1893                     bus->dpc_sched,
1894                     (brcmf_sdcard_intr_pending(bus->sdh) ? " " : " not "));
1895         brcmu_bprintf(strbuf, "blocksize %d roundup %d\n", bus->blocksize,
1896                     bus->roundup);
1897 #endif                          /* DHD_DEBUG */
1898         brcmu_bprintf(strbuf,
1899                     "clkstate %d activity %d idletime %d idlecount %d sleeping %d\n",
1900                     bus->clkstate, bus->activity, bus->idletime, bus->idlecount,
1901                     bus->sleeping);
1902 }
1903
1904 void dhd_bus_clearcounts(dhd_pub_t *dhdp)
1905 {
1906         dhd_bus_t *bus = (dhd_bus_t *) dhdp->bus;
1907
1908         bus->intrcount = bus->lastintrs = bus->spurious = bus->regfails = 0;
1909         bus->rxrtx = bus->rx_toolong = bus->rxc_errors = 0;
1910         bus->rx_hdrfail = bus->rx_badhdr = bus->rx_badseq = 0;
1911         bus->tx_sderrs = bus->fc_rcvd = bus->fc_xoff = bus->fc_xon = 0;
1912         bus->rxglomfail = bus->rxglomframes = bus->rxglompkts = 0;
1913         bus->f2rxhdrs = bus->f2rxdata = bus->f2txdata = bus->f1regdata = 0;
1914 }
1915
1916 #ifdef SDTEST
1917 static int brcmf_sdbrcm_pktgen_get(dhd_bus_t *bus, u8 *arg)
1918 {
1919         brcmf_pktgen_t pktgen;
1920
1921         pktgen.version = DHD_PKTGEN_VERSION;
1922         pktgen.freq = bus->pktgen_freq;
1923         pktgen.count = bus->pktgen_count;
1924         pktgen.print = bus->pktgen_print;
1925         pktgen.total = bus->pktgen_total;
1926         pktgen.minlen = bus->pktgen_minlen;
1927         pktgen.maxlen = bus->pktgen_maxlen;
1928         pktgen.numsent = bus->pktgen_sent;
1929         pktgen.numrcvd = bus->pktgen_rcvd;
1930         pktgen.numfail = bus->pktgen_fail;
1931         pktgen.mode = bus->pktgen_mode;
1932         pktgen.stop = bus->pktgen_stop;
1933
1934         memcpy(arg, &pktgen, sizeof(pktgen));
1935
1936         return 0;
1937 }
1938
1939 static int brcmf_sdbrcm_pktgen_set(dhd_bus_t *bus, u8 *arg)
1940 {
1941         brcmf_pktgen_t pktgen;
1942         uint oldcnt, oldmode;
1943
1944         memcpy(&pktgen, arg, sizeof(pktgen));
1945         if (pktgen.version != DHD_PKTGEN_VERSION)
1946                 return -EINVAL;
1947
1948         oldcnt = bus->pktgen_count;
1949         oldmode = bus->pktgen_mode;
1950
1951         bus->pktgen_freq = pktgen.freq;
1952         bus->pktgen_count = pktgen.count;
1953         bus->pktgen_print = pktgen.print;
1954         bus->pktgen_total = pktgen.total;
1955         bus->pktgen_minlen = pktgen.minlen;
1956         bus->pktgen_maxlen = pktgen.maxlen;
1957         bus->pktgen_mode = pktgen.mode;
1958         bus->pktgen_stop = pktgen.stop;
1959
1960         bus->pktgen_tick = bus->pktgen_ptick = 0;
1961         bus->pktgen_len = max(bus->pktgen_len, bus->pktgen_minlen);
1962         bus->pktgen_len = min(bus->pktgen_len, bus->pktgen_maxlen);
1963
1964         /* Clear counts for a new pktgen (mode change, or was stopped) */
1965         if (bus->pktgen_count && (!oldcnt || oldmode != bus->pktgen_mode))
1966                 bus->pktgen_sent = bus->pktgen_rcvd = bus->pktgen_fail = 0;
1967
1968         return 0;
1969 }
1970 #endif                          /* SDTEST */
1971
1972 static int
1973 brcmf_sdbrcm_membytes(dhd_bus_t *bus, bool write, u32 address, u8 *data,
1974                  uint size)
1975 {
1976         int bcmerror = 0;
1977         u32 sdaddr;
1978         uint dsize;
1979
1980         /* Determine initial transfer parameters */
1981         sdaddr = address & SBSDIO_SB_OFT_ADDR_MASK;
1982         if ((sdaddr + size) & SBSDIO_SBWINDOW_MASK)
1983                 dsize = (SBSDIO_SB_OFT_ADDR_LIMIT - sdaddr);
1984         else
1985                 dsize = size;
1986
1987         /* Set the backplane window to include the start address */
1988         bcmerror = brcmf_sdbrcm_set_siaddr_window(bus, address);
1989         if (bcmerror) {
1990                 DHD_ERROR(("%s: window change failed\n", __func__));
1991                 goto xfer_done;
1992         }
1993
1994         /* Do the transfer(s) */
1995         while (size) {
1996                 DHD_INFO(("%s: %s %d bytes at offset 0x%08x in window 0x%08x\n",
1997                           __func__, (write ? "write" : "read"), dsize,
1998                           sdaddr, (address & SBSDIO_SBWINDOW_MASK)));
1999                 bcmerror =
2000                      brcmf_sdcard_rwdata(bus->sdh, write, sdaddr, data, dsize);
2001                 if (bcmerror) {
2002                         DHD_ERROR(("%s: membytes transfer failed\n", __func__));
2003                         break;
2004                 }
2005
2006                 /* Adjust for next transfer (if any) */
2007                 size -= dsize;
2008                 if (size) {
2009                         data += dsize;
2010                         address += dsize;
2011                         bcmerror = brcmf_sdbrcm_set_siaddr_window(bus, address);
2012                         if (bcmerror) {
2013                                 DHD_ERROR(("%s: window change failed\n",
2014                                            __func__));
2015                                 break;
2016                         }
2017                         sdaddr = 0;
2018                         dsize = min_t(uint, SBSDIO_SB_OFT_ADDR_LIMIT, size);
2019                 }
2020         }
2021
2022 xfer_done:
2023         /* Return the window to backplane enumeration space for core access */
2024         if (brcmf_sdbrcm_set_siaddr_window(bus,
2025                                            brcmf_sdcard_cur_sbwad(bus->sdh))) {
2026                 DHD_ERROR(("%s: FAILED to set window back to 0x%x\n",
2027                            __func__, brcmf_sdcard_cur_sbwad(bus->sdh)));
2028         }
2029
2030         return bcmerror;
2031 }
2032
2033 #ifdef DHD_DEBUG
2034 static int brcmf_sdbrcm_readshared(dhd_bus_t *bus, struct sdpcm_shared *sh)
2035 {
2036         u32 addr;
2037         int rv;
2038
2039         /* Read last word in memory to determine address of
2040                          sdpcm_shared structure */
2041         rv = brcmf_sdbrcm_membytes(bus, false, bus->ramsize - 4, (u8 *)&addr,
2042                                    4);
2043         if (rv < 0)
2044                 return rv;
2045
2046         addr = le32_to_cpu(addr);
2047
2048         DHD_INFO(("sdpcm_shared address 0x%08X\n", addr));
2049
2050         /*
2051          * Check if addr is valid.
2052          * NVRAM length at the end of memory should have been overwritten.
2053          */
2054         if (addr == 0 || ((~addr >> 16) & 0xffff) == (addr & 0xffff)) {
2055                 DHD_ERROR(("%s: address (0x%08x) of sdpcm_shared invalid\n",
2056                            __func__, addr));
2057                 return -EBADE;
2058         }
2059
2060         /* Read rte_shared structure */
2061         rv = brcmf_sdbrcm_membytes(bus, false, addr, (u8 *) sh,
2062                               sizeof(struct sdpcm_shared));
2063         if (rv < 0)
2064                 return rv;
2065
2066         /* Endianness */
2067         sh->flags = le32_to_cpu(sh->flags);
2068         sh->trap_addr = le32_to_cpu(sh->trap_addr);
2069         sh->assert_exp_addr = le32_to_cpu(sh->assert_exp_addr);
2070         sh->assert_file_addr = le32_to_cpu(sh->assert_file_addr);
2071         sh->assert_line = le32_to_cpu(sh->assert_line);
2072         sh->console_addr = le32_to_cpu(sh->console_addr);
2073         sh->msgtrace_addr = le32_to_cpu(sh->msgtrace_addr);
2074
2075         if ((sh->flags & SDPCM_SHARED_VERSION_MASK) != SDPCM_SHARED_VERSION) {
2076                 DHD_ERROR(("%s: sdpcm_shared version %d in dhd "
2077                            "is different than sdpcm_shared version %d in dongle\n",
2078                            __func__, SDPCM_SHARED_VERSION,
2079                            sh->flags & SDPCM_SHARED_VERSION_MASK));
2080                 return -EBADE;
2081         }
2082
2083         return 0;
2084 }
2085
2086 static int brcmf_sdbrcm_checkdied(dhd_bus_t *bus, u8 *data, uint size)
2087 {
2088         int bcmerror = 0;
2089         uint msize = 512;
2090         char *mbuffer = NULL;
2091         uint maxstrlen = 256;
2092         char *str = NULL;
2093         trap_t tr;
2094         struct sdpcm_shared sdpcm_shared;
2095         struct brcmu_strbuf strbuf;
2096
2097         DHD_TRACE(("%s: Enter\n", __func__));
2098
2099         if (data == NULL) {
2100                 /*
2101                  * Called after a rx ctrl timeout. "data" is NULL.
2102                  * allocate memory to trace the trap or assert.
2103                  */
2104                 size = msize;
2105                 mbuffer = data = kmalloc(msize, GFP_ATOMIC);
2106                 if (mbuffer == NULL) {
2107                         DHD_ERROR(("%s: kmalloc(%d) failed\n", __func__,
2108                                    msize));
2109                         bcmerror = -ENOMEM;
2110                         goto done;
2111                 }
2112         }
2113
2114         str = kmalloc(maxstrlen, GFP_ATOMIC);
2115         if (str == NULL) {
2116                 DHD_ERROR(("%s: kmalloc(%d) failed\n", __func__, maxstrlen));
2117                 bcmerror = -ENOMEM;
2118                 goto done;
2119         }
2120
2121         bcmerror = brcmf_sdbrcm_readshared(bus, &sdpcm_shared);
2122         if (bcmerror < 0)
2123                 goto done;
2124
2125         brcmu_binit(&strbuf, data, size);
2126
2127         brcmu_bprintf(&strbuf,
2128                     "msgtrace address : 0x%08X\nconsole address  : 0x%08X\n",
2129                     sdpcm_shared.msgtrace_addr, sdpcm_shared.console_addr);
2130
2131         if ((sdpcm_shared.flags & SDPCM_SHARED_ASSERT_BUILT) == 0) {
2132                 /* NOTE: Misspelled assert is intentional - DO NOT FIX.
2133                  * (Avoids conflict with real asserts for programmatic
2134                  * parsing of output.)
2135                  */
2136                 brcmu_bprintf(&strbuf, "Assrt not built in dongle\n");
2137         }
2138
2139         if ((sdpcm_shared.flags & (SDPCM_SHARED_ASSERT | SDPCM_SHARED_TRAP)) ==
2140             0) {
2141                 /* NOTE: Misspelled assert is intentional - DO NOT FIX.
2142                  * (Avoids conflict with real asserts for programmatic
2143                  * parsing of output.)
2144                  */
2145                 brcmu_bprintf(&strbuf, "No trap%s in dongle",
2146                             (sdpcm_shared.flags & SDPCM_SHARED_ASSERT_BUILT)
2147                             ? "/assrt" : "");
2148         } else {
2149                 if (sdpcm_shared.flags & SDPCM_SHARED_ASSERT) {
2150                         /* Download assert */
2151                         brcmu_bprintf(&strbuf, "Dongle assert");
2152                         if (sdpcm_shared.assert_exp_addr != 0) {
2153                                 str[0] = '\0';
2154                                 bcmerror = brcmf_sdbrcm_membytes(bus, false,
2155                                                 sdpcm_shared.assert_exp_addr,
2156                                                 (u8 *) str, maxstrlen);
2157                                 if (bcmerror < 0)
2158                                         goto done;
2159
2160                                 str[maxstrlen - 1] = '\0';
2161                                 brcmu_bprintf(&strbuf, " expr \"%s\"", str);
2162                         }
2163
2164                         if (sdpcm_shared.assert_file_addr != 0) {
2165                                 str[0] = '\0';
2166                                 bcmerror = brcmf_sdbrcm_membytes(bus, false,
2167                                                 sdpcm_shared.assert_file_addr,
2168                                                 (u8 *) str, maxstrlen);
2169                                 if (bcmerror < 0)
2170                                         goto done;
2171
2172                                 str[maxstrlen - 1] = '\0';
2173                                 brcmu_bprintf(&strbuf, " file \"%s\"", str);
2174                         }
2175
2176                         brcmu_bprintf(&strbuf, " line %d ",
2177                                     sdpcm_shared.assert_line);
2178                 }
2179
2180                 if (sdpcm_shared.flags & SDPCM_SHARED_TRAP) {
2181                         bcmerror = brcmf_sdbrcm_membytes(bus, false,
2182                                         sdpcm_shared.trap_addr, (u8 *)&tr,
2183                                         sizeof(trap_t));
2184                         if (bcmerror < 0)
2185                                 goto done;
2186
2187                         brcmu_bprintf(&strbuf,
2188                                     "Dongle trap type 0x%x @ epc 0x%x, cpsr 0x%x, spsr 0x%x, sp 0x%x,"
2189                                     "lp 0x%x, rpc 0x%x Trap offset 0x%x, "
2190                                     "r0 0x%x, r1 0x%x, r2 0x%x, r3 0x%x, r4 0x%x, r5 0x%x, r6 0x%x, r7 0x%x\n",
2191                                     tr.type, tr.epc, tr.cpsr, tr.spsr, tr.r13,
2192                                     tr.r14, tr.pc, sdpcm_shared.trap_addr,
2193                                     tr.r0, tr.r1, tr.r2, tr.r3, tr.r4, tr.r5,
2194                                     tr.r6, tr.r7);
2195                 }
2196         }
2197
2198         if (sdpcm_shared.flags & (SDPCM_SHARED_ASSERT | SDPCM_SHARED_TRAP))
2199                 DHD_ERROR(("%s: %s\n", __func__, strbuf.origbuf));
2200
2201 #ifdef DHD_DEBUG
2202         if (sdpcm_shared.flags & SDPCM_SHARED_TRAP) {
2203                 /* Mem dump to a file on device */
2204                 brcmf_sdbrcm_mem_dump(bus);
2205         }
2206 #endif                          /* DHD_DEBUG */
2207
2208 done:
2209         kfree(mbuffer);
2210         kfree(str);
2211
2212         return bcmerror;
2213 }
2214
2215 static int brcmf_sdbrcm_mem_dump(dhd_bus_t *bus)
2216 {
2217         int ret = 0;
2218         int size;               /* Full mem size */
2219         int start = 0;          /* Start address */
2220         int read_size = 0;      /* Read size of each iteration */
2221         u8 *buf = NULL, *databuf = NULL;
2222
2223         /* Get full mem size */
2224         size = bus->ramsize;
2225         buf = kmalloc(size, GFP_ATOMIC);
2226         if (!buf) {
2227                 DHD_ERROR(("%s: Out of memory (%d bytes)\n", __func__, size));
2228                 return -1;
2229         }
2230
2231         /* Read mem content */
2232         printk(KERN_DEBUG "Dump dongle memory");
2233         databuf = buf;
2234         while (size) {
2235                 read_size = min(MEMBLOCK, size);
2236                 ret = brcmf_sdbrcm_membytes(bus, false, start, databuf,
2237                                           read_size);
2238                 if (ret) {
2239                         DHD_ERROR(("%s: Error membytes %d\n", __func__, ret));
2240                         kfree(buf);
2241                         return -1;
2242                 }
2243                 printk(".");
2244
2245                 /* Decrement size and increment start address */
2246                 size -= read_size;
2247                 start += read_size;
2248                 databuf += read_size;
2249         }
2250         printk(KERN_DEBUG "Done\n");
2251
2252         /* free buf before return !!! */
2253         if (brcmf_write_to_file(bus->dhd, buf, bus->ramsize)) {
2254                 DHD_ERROR(("%s: Error writing to files\n", __func__));
2255                 return -1;
2256         }
2257
2258         /* buf free handled in brcmf_write_to_file, not here */
2259         return 0;
2260 }
2261
2262 #define CONSOLE_LINE_MAX        192
2263
2264 static int brcmf_sdbrcm_readconsole(dhd_bus_t *bus)
2265 {
2266         dhd_console_t *c = &bus->console;
2267         u8 line[CONSOLE_LINE_MAX], ch;
2268         u32 n, idx, addr;
2269         int rv;
2270
2271         /* Don't do anything until FWREADY updates console address */
2272         if (bus->console_addr == 0)
2273                 return 0;
2274
2275         /* Read console log struct */
2276         addr = bus->console_addr + offsetof(rte_cons_t, log);
2277         rv = brcmf_sdbrcm_membytes(bus, false, addr, (u8 *)&c->log,
2278                                 sizeof(c->log));
2279         if (rv < 0)
2280                 return rv;
2281
2282         /* Allocate console buffer (one time only) */
2283         if (c->buf == NULL) {
2284                 c->bufsize = le32_to_cpu(c->log.buf_size);
2285                 c->buf = kmalloc(c->bufsize, GFP_ATOMIC);
2286                 if (c->buf == NULL)
2287                         return -ENOMEM;
2288         }
2289
2290         idx = le32_to_cpu(c->log.idx);
2291
2292         /* Protect against corrupt value */
2293         if (idx > c->bufsize)
2294                 return -EBADE;
2295
2296         /* Skip reading the console buffer if the index pointer
2297          has not moved */
2298         if (idx == c->last)
2299                 return 0;
2300
2301         /* Read the console buffer */
2302         addr = le32_to_cpu(c->log.buf);
2303         rv = brcmf_sdbrcm_membytes(bus, false, addr, c->buf, c->bufsize);
2304         if (rv < 0)
2305                 return rv;
2306
2307         while (c->last != idx) {
2308                 for (n = 0; n < CONSOLE_LINE_MAX - 2; n++) {
2309                         if (c->last == idx) {
2310                                 /* This would output a partial line.
2311                                  * Instead, back up
2312                                  * the buffer pointer and output this
2313                                  * line next time around.
2314                                  */
2315                                 if (c->last >= n)
2316                                         c->last -= n;
2317                                 else
2318                                         c->last = c->bufsize - n;
2319                                 goto break2;
2320                         }
2321                         ch = c->buf[c->last];
2322                         c->last = (c->last + 1) % c->bufsize;
2323                         if (ch == '\n')
2324                                 break;
2325                         line[n] = ch;
2326                 }
2327
2328                 if (n > 0) {
2329                         if (line[n - 1] == '\r')
2330                                 n--;
2331                         line[n] = 0;
2332                         printk(KERN_DEBUG "CONSOLE: %s\n", line);
2333                 }
2334         }
2335 break2:
2336
2337         return 0;
2338 }
2339 #endif                          /* DHD_DEBUG */
2340
2341 int brcmf_sdbrcm_downloadvars(dhd_bus_t *bus, void *arg, int len)
2342 {
2343         int bcmerror = 0;
2344
2345         DHD_TRACE(("%s: Enter\n", __func__));
2346
2347         /* Basic sanity checks */
2348         if (bus->dhd->up) {
2349                 bcmerror = -EISCONN;
2350                 goto err;
2351         }
2352         if (!len) {
2353                 bcmerror = -EOVERFLOW;
2354                 goto err;
2355         }
2356
2357         /* Free the old ones and replace with passed variables */
2358         kfree(bus->vars);
2359
2360         bus->vars = kmalloc(len, GFP_ATOMIC);
2361         bus->varsz = bus->vars ? len : 0;
2362         if (bus->vars == NULL) {
2363                 bcmerror = -ENOMEM;
2364                 goto err;
2365         }
2366
2367         /* Copy the passed variables, which should include the
2368                  terminating double-null */
2369         memcpy(bus->vars, arg, bus->varsz);
2370 err:
2371         return bcmerror;
2372 }
2373
2374 static int
2375 brcmf_sdbrcm_doiovar(dhd_bus_t *bus, const struct brcmu_iovar *vi, u32 actionid,
2376                 const char *name, void *params, int plen, void *arg, int len,
2377                 int val_size)
2378 {
2379         int bcmerror = 0;
2380         s32 int_val = 0;
2381         bool bool_val = 0;
2382
2383         DHD_TRACE(("%s: Enter, action %d name %s params %p plen %d arg %p "
2384                 "len %d val_size %d\n",
2385                 __func__, actionid, name, params, plen, arg, len, val_size));
2386
2387         bcmerror = brcmu_iovar_lencheck(vi, arg, len, IOV_ISSET(actionid));
2388         if (bcmerror != 0)
2389                 goto exit;
2390
2391         if (plen >= (int)sizeof(int_val))
2392                 memcpy(&int_val, params, sizeof(int_val));
2393
2394         bool_val = (int_val != 0) ? true : false;
2395
2396         /* Some ioctls use the bus */
2397         brcmf_os_sdlock(bus->dhd);
2398
2399         /* Check if dongle is in reset. If so, only allow DEVRESET iovars */
2400         if (bus->dhd->dongle_reset && !(actionid == IOV_SVAL(IOV_DEVRESET) ||
2401                                         actionid == IOV_GVAL(IOV_DEVRESET))) {
2402                 bcmerror = -EPERM;
2403                 goto exit;
2404         }
2405
2406         /* Handle sleep stuff before any clock mucking */
2407         if (vi->varid == IOV_SLEEP) {
2408                 if (IOV_ISSET(actionid)) {
2409                         bcmerror = brcmf_sdbrcm_bussleep(bus, bool_val);
2410                 } else {
2411                         int_val = (s32) bus->sleeping;
2412                         memcpy(arg, &int_val, val_size);
2413                 }
2414                 goto exit;
2415         }
2416
2417         /* Request clock to allow SDIO accesses */
2418         if (!bus->dhd->dongle_reset) {
2419                 BUS_WAKE(bus);
2420                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
2421         }
2422
2423         switch (actionid) {
2424         case IOV_GVAL(IOV_INTR):
2425                 int_val = (s32) bus->intr;
2426                 memcpy(arg, &int_val, val_size);
2427                 break;
2428
2429         case IOV_SVAL(IOV_INTR):
2430                 bus->intr = bool_val;
2431                 bus->intdis = false;
2432                 if (bus->dhd->up) {
2433                         if (bus->intr) {
2434                                 DHD_INTR(("%s: enable SDIO device interrupts\n",
2435                                           __func__));
2436                                 brcmf_sdcard_intr_enable(bus->sdh);
2437                         } else {
2438                                 DHD_INTR(("%s: disable SDIO interrupts\n",
2439                                           __func__));
2440                                 brcmf_sdcard_intr_disable(bus->sdh);
2441                         }
2442                 }
2443                 break;
2444
2445         case IOV_GVAL(IOV_POLLRATE):
2446                 int_val = (s32) bus->pollrate;
2447                 memcpy(arg, &int_val, val_size);
2448                 break;
2449
2450         case IOV_SVAL(IOV_POLLRATE):
2451                 bus->pollrate = (uint) int_val;
2452                 bus->poll = (bus->pollrate != 0);
2453                 break;
2454
2455         case IOV_GVAL(IOV_IDLETIME):
2456                 int_val = bus->idletime;
2457                 memcpy(arg, &int_val, val_size);
2458                 break;
2459
2460         case IOV_SVAL(IOV_IDLETIME):
2461                 if ((int_val < 0) && (int_val != DHD_IDLE_IMMEDIATE))
2462                         bcmerror = -EINVAL;
2463                 else
2464                         bus->idletime = int_val;
2465                 break;
2466
2467         case IOV_GVAL(IOV_IDLECLOCK):
2468                 int_val = (s32) bus->idleclock;
2469                 memcpy(arg, &int_val, val_size);
2470                 break;
2471
2472         case IOV_SVAL(IOV_IDLECLOCK):
2473                 bus->idleclock = int_val;
2474                 break;
2475
2476         case IOV_GVAL(IOV_SD1IDLE):
2477                 int_val = (s32) sd1idle;
2478                 memcpy(arg, &int_val, val_size);
2479                 break;
2480
2481         case IOV_SVAL(IOV_SD1IDLE):
2482                 sd1idle = bool_val;
2483                 break;
2484
2485         case IOV_SVAL(IOV_MEMBYTES):
2486         case IOV_GVAL(IOV_MEMBYTES):
2487                 {
2488                         u32 address;
2489                         uint size, dsize;
2490                         u8 *data;
2491
2492                         bool set = (actionid == IOV_SVAL(IOV_MEMBYTES));
2493
2494                         ASSERT(plen >= 2 * sizeof(int));
2495
2496                         address = (u32) int_val;
2497                         memcpy(&int_val, (char *)params + sizeof(int_val),
2498                                sizeof(int_val));
2499                         size = (uint) int_val;
2500
2501                         /* Do some validation */
2502                         dsize = set ? plen - (2 * sizeof(int)) : len;
2503                         if (dsize < size) {
2504                                 DHD_ERROR(("%s: error on %s membytes, addr "
2505                                 "0x%08x size %d dsize %d\n",
2506                                 __func__, (set ? "set" : "get"),
2507                                 address, size, dsize));
2508                                 bcmerror = -EINVAL;
2509                                 break;
2510                         }
2511
2512                         DHD_INFO(("%s: Request to %s %d bytes at address "
2513                         "0x%08x\n",
2514                         __func__, (set ? "write" : "read"), size, address));
2515
2516                         /* If we know about SOCRAM, check for a fit */
2517                         if ((bus->orig_ramsize) &&
2518                             ((address > bus->orig_ramsize)
2519                              || (address + size > bus->orig_ramsize))) {
2520                                 DHD_ERROR(("%s: ramsize 0x%08x doesn't have %d "
2521                                 "bytes at 0x%08x\n",
2522                                 __func__, bus->orig_ramsize, size, address));
2523                                 bcmerror = -EINVAL;
2524                                 break;
2525                         }
2526
2527                         /* Generate the actual data pointer */
2528                         data =
2529                             set ? (u8 *) params +
2530                             2 * sizeof(int) : (u8 *) arg;
2531
2532                         /* Call to do the transfer */
2533                         bcmerror = brcmf_sdbrcm_membytes(bus, set, address,
2534                                                          data, size);
2535
2536                         break;
2537                 }
2538
2539         case IOV_GVAL(IOV_MEMSIZE):
2540                 int_val = (s32) bus->ramsize;
2541                 memcpy(arg, &int_val, val_size);
2542                 break;
2543
2544         case IOV_GVAL(IOV_SDIOD_DRIVE):
2545                 int_val = (s32) brcmf_sdiod_drive_strength;
2546                 memcpy(arg, &int_val, val_size);
2547                 break;
2548
2549         case IOV_SVAL(IOV_SDIOD_DRIVE):
2550                 brcmf_sdiod_drive_strength = int_val;
2551                 brcmf_sdbrcm_sdiod_drive_strength_init(bus,
2552                                              brcmf_sdiod_drive_strength);
2553                 break;
2554
2555         case IOV_SVAL(IOV_DOWNLOAD):
2556                 bcmerror = brcmf_sdbrcm_download_state(bus, bool_val);
2557                 break;
2558
2559         case IOV_SVAL(IOV_VARS):
2560                 bcmerror = brcmf_sdbrcm_downloadvars(bus, arg, len);
2561                 break;
2562
2563         case IOV_GVAL(IOV_READAHEAD):
2564                 int_val = (s32) dhd_readahead;
2565                 memcpy(arg, &int_val, val_size);
2566                 break;
2567
2568         case IOV_SVAL(IOV_READAHEAD):
2569                 if (bool_val && !dhd_readahead)
2570                         bus->nextlen = 0;
2571                 dhd_readahead = bool_val;
2572                 break;
2573
2574         case IOV_GVAL(IOV_SDRXCHAIN):
2575                 int_val = (s32) bus->use_rxchain;
2576                 memcpy(arg, &int_val, val_size);
2577                 break;
2578
2579         case IOV_SVAL(IOV_SDRXCHAIN):
2580                 if (bool_val && !bus->sd_rxchain)
2581                         bcmerror = -ENOTSUPP;
2582                 else
2583                         bus->use_rxchain = bool_val;
2584                 break;
2585         case IOV_GVAL(IOV_ALIGNCTL):
2586                 int_val = (s32) dhd_alignctl;
2587                 memcpy(arg, &int_val, val_size);
2588                 break;
2589
2590         case IOV_SVAL(IOV_ALIGNCTL):
2591                 dhd_alignctl = bool_val;
2592                 break;
2593
2594         case IOV_GVAL(IOV_SDALIGN):
2595                 int_val = DHD_SDALIGN;
2596                 memcpy(arg, &int_val, val_size);
2597                 break;
2598
2599 #ifdef DHD_DEBUG
2600         case IOV_GVAL(IOV_VARS):
2601                 if (bus->varsz < (uint) len)
2602                         memcpy(arg, bus->vars, bus->varsz);
2603                 else
2604                         bcmerror = -EOVERFLOW;
2605                 break;
2606 #endif                          /* DHD_DEBUG */
2607
2608 #ifdef DHD_DEBUG
2609         case IOV_GVAL(IOV_SDREG):
2610                 {
2611                         sdreg_t *sd_ptr;
2612                         u32 addr, size;
2613
2614                         sd_ptr = (sdreg_t *) params;
2615
2616                         addr = (unsigned long)bus->regs + sd_ptr->offset;
2617                         size = sd_ptr->func;
2618                         int_val = (s32) brcmf_sdcard_reg_read(bus->sdh, addr,
2619                                                               size);
2620                         if (brcmf_sdcard_regfail(bus->sdh))
2621                                 bcmerror = -EIO;
2622                         memcpy(arg, &int_val, sizeof(s32));
2623                         break;
2624                 }
2625
2626         case IOV_SVAL(IOV_SDREG):
2627                 {
2628                         sdreg_t *sd_ptr;
2629                         u32 addr, size;
2630
2631                         sd_ptr = (sdreg_t *) params;
2632
2633                         addr = (unsigned long)bus->regs + sd_ptr->offset;
2634                         size = sd_ptr->func;
2635                         brcmf_sdcard_reg_write(bus->sdh, addr, size,
2636                                                sd_ptr->value);
2637                         if (brcmf_sdcard_regfail(bus->sdh))
2638                                 bcmerror = -EIO;
2639                         break;
2640                 }
2641
2642                 /* Same as above, but offset is not backplane
2643                  (not SDIO core) */
2644         case IOV_GVAL(IOV_SBREG):
2645                 {
2646                         sdreg_t sdreg;
2647                         u32 addr, size;
2648
2649                         memcpy(&sdreg, params, sizeof(sdreg));
2650
2651                         addr = SI_ENUM_BASE + sdreg.offset;
2652                         size = sdreg.func;
2653                         int_val = (s32) brcmf_sdcard_reg_read(bus->sdh, addr,
2654                                                               size);
2655                         if (brcmf_sdcard_regfail(bus->sdh))
2656                                 bcmerror = -EIO;
2657                         memcpy(arg, &int_val, sizeof(s32));
2658                         break;
2659                 }
2660
2661         case IOV_SVAL(IOV_SBREG):
2662                 {
2663                         sdreg_t sdreg;
2664                         u32 addr, size;
2665
2666                         memcpy(&sdreg, params, sizeof(sdreg));
2667
2668                         addr = SI_ENUM_BASE + sdreg.offset;
2669                         size = sdreg.func;
2670                         brcmf_sdcard_reg_write(bus->sdh, addr, size,
2671                                                sdreg.value);
2672                         if (brcmf_sdcard_regfail(bus->sdh))
2673                                 bcmerror = -EIO;
2674                         break;
2675                 }
2676
2677         case IOV_GVAL(IOV_SDCIS):
2678                 {
2679                         *(char *)arg = 0;
2680
2681                         strcat(arg, "\nFunc 0\n");
2682                         brcmf_sdcard_cis_read(bus->sdh, 0x10,
2683                                         (u8 *) arg + strlen(arg),
2684                                         SBSDIO_CIS_SIZE_LIMIT);
2685                         strcat(arg, "\nFunc 1\n");
2686                         brcmf_sdcard_cis_read(bus->sdh, 0x11,
2687                                         (u8 *) arg + strlen(arg),
2688                                         SBSDIO_CIS_SIZE_LIMIT);
2689                         strcat(arg, "\nFunc 2\n");
2690                         brcmf_sdcard_cis_read(bus->sdh, 0x12,
2691                                         (u8 *) arg + strlen(arg),
2692                                         SBSDIO_CIS_SIZE_LIMIT);
2693                         break;
2694                 }
2695
2696         case IOV_GVAL(IOV_FORCEEVEN):
2697                 int_val = (s32) forcealign;
2698                 memcpy(arg, &int_val, val_size);
2699                 break;
2700
2701         case IOV_SVAL(IOV_FORCEEVEN):
2702                 forcealign = bool_val;
2703                 break;
2704
2705         case IOV_GVAL(IOV_TXBOUND):
2706                 int_val = (s32) brcmf_txbound;
2707                 memcpy(arg, &int_val, val_size);
2708                 break;
2709
2710         case IOV_SVAL(IOV_TXBOUND):
2711                 brcmf_txbound = (uint) int_val;
2712                 break;
2713
2714         case IOV_GVAL(IOV_RXBOUND):
2715                 int_val = (s32) brcmf_rxbound;
2716                 memcpy(arg, &int_val, val_size);
2717                 break;
2718
2719         case IOV_SVAL(IOV_RXBOUND):
2720                 brcmf_rxbound = (uint) int_val;
2721                 break;
2722
2723         case IOV_GVAL(IOV_TXMINMAX):
2724                 int_val = (s32) dhd_txminmax;
2725                 memcpy(arg, &int_val, val_size);
2726                 break;
2727
2728         case IOV_SVAL(IOV_TXMINMAX):
2729                 dhd_txminmax = (uint) int_val;
2730                 break;
2731 #endif                          /* DHD_DEBUG */
2732
2733 #ifdef SDTEST
2734         case IOV_GVAL(IOV_EXTLOOP):
2735                 int_val = (s32) bus->ext_loop;
2736                 memcpy(arg, &int_val, val_size);
2737                 break;
2738
2739         case IOV_SVAL(IOV_EXTLOOP):
2740                 bus->ext_loop = bool_val;
2741                 break;
2742
2743         case IOV_GVAL(IOV_PKTGEN):
2744                 bcmerror = brcmf_sdbrcm_pktgen_get(bus, arg);
2745                 break;
2746
2747         case IOV_SVAL(IOV_PKTGEN):
2748                 bcmerror = brcmf_sdbrcm_pktgen_set(bus, arg);
2749                 break;
2750 #endif                          /* SDTEST */
2751
2752         case IOV_SVAL(IOV_DEVRESET):
2753                 DHD_TRACE(("%s: Called set IOV_DEVRESET=%d dongle_reset=%d "
2754                         "busstate=%d\n",
2755                         __func__, bool_val, bus->dhd->dongle_reset,
2756                         bus->dhd->busstate));
2757
2758                 brcmf_bus_devreset(bus->dhd, (u8) bool_val);
2759
2760                 break;
2761
2762         case IOV_GVAL(IOV_DEVRESET):
2763                 DHD_TRACE(("%s: Called get IOV_DEVRESET\n", __func__));
2764
2765                 /* Get its status */
2766                 int_val = (bool) bus->dhd->dongle_reset;
2767                 memcpy(arg, &int_val, val_size);
2768
2769                 break;
2770
2771         default:
2772                 bcmerror = -ENOTSUPP;
2773                 break;
2774         }
2775
2776 exit:
2777         if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) {
2778                 bus->activity = false;
2779                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, true);
2780         }
2781
2782         brcmf_os_sdunlock(bus->dhd);
2783
2784         if (actionid == IOV_SVAL(IOV_DEVRESET) && bool_val == false)
2785                 brcmf_c_preinit_ioctls((dhd_pub_t *) bus->dhd);
2786
2787         return bcmerror;
2788 }
2789
2790 static int brcmf_sdbrcm_write_vars(dhd_bus_t *bus)
2791 {
2792         int bcmerror = 0;
2793         u32 varsize;
2794         u32 varaddr;
2795         u8 *vbuffer;
2796         u32 varsizew;
2797 #ifdef DHD_DEBUG
2798         char *nvram_ularray;
2799 #endif                          /* DHD_DEBUG */
2800
2801         /* Even if there are no vars are to be written, we still
2802                  need to set the ramsize. */
2803         varsize = bus->varsz ? roundup(bus->varsz, 4) : 0;
2804         varaddr = (bus->ramsize - 4) - varsize;
2805
2806         if (bus->vars) {
2807                 vbuffer = kzalloc(varsize, GFP_ATOMIC);
2808                 if (!vbuffer)
2809                         return -ENOMEM;
2810
2811                 memcpy(vbuffer, bus->vars, bus->varsz);
2812
2813                 /* Write the vars list */
2814                 bcmerror =
2815                     brcmf_sdbrcm_membytes(bus, true, varaddr, vbuffer, varsize);
2816 #ifdef DHD_DEBUG
2817                 /* Verify NVRAM bytes */
2818                 DHD_INFO(("Compare NVRAM dl & ul; varsize=%d\n", varsize));
2819                 nvram_ularray = kmalloc(varsize, GFP_ATOMIC);
2820                 if (!nvram_ularray)
2821                         return -ENOMEM;
2822
2823                 /* Upload image to verify downloaded contents. */
2824                 memset(nvram_ularray, 0xaa, varsize);
2825
2826                 /* Read the vars list to temp buffer for comparison */
2827                 bcmerror =
2828                     brcmf_sdbrcm_membytes(bus, false, varaddr, nvram_ularray,
2829                                      varsize);
2830                 if (bcmerror) {
2831                         DHD_ERROR(("%s: error %d on reading %d nvram bytes at "
2832                         "0x%08x\n", __func__, bcmerror, varsize, varaddr));
2833                 }
2834                 /* Compare the org NVRAM with the one read from RAM */
2835                 if (memcmp(vbuffer, nvram_ularray, varsize)) {
2836                         DHD_ERROR(("%s: Downloaded NVRAM image is corrupted.\n",
2837                                    __func__));
2838                 } else
2839                         DHD_ERROR(("%s: Download/Upload/Compare of NVRAM ok.\n",
2840                                 __func__));
2841
2842                 kfree(nvram_ularray);
2843 #endif                          /* DHD_DEBUG */
2844
2845                 kfree(vbuffer);
2846         }
2847
2848         /* adjust to the user specified RAM */
2849         DHD_INFO(("Physical memory size: %d, usable memory size: %d\n",
2850                   bus->orig_ramsize, bus->ramsize));
2851         DHD_INFO(("Vars are at %d, orig varsize is %d\n", varaddr, varsize));
2852         varsize = ((bus->orig_ramsize - 4) - varaddr);
2853
2854         /*
2855          * Determine the length token:
2856          * Varsize, converted to words, in lower 16-bits, checksum
2857          * in upper 16-bits.
2858          */
2859         if (bcmerror) {
2860                 varsizew = 0;
2861         } else {
2862                 varsizew = varsize / 4;
2863                 varsizew = (~varsizew << 16) | (varsizew & 0x0000FFFF);
2864                 varsizew = cpu_to_le32(varsizew);
2865         }
2866
2867         DHD_INFO(("New varsize is %d, length token=0x%08x\n", varsize,
2868                   varsizew));
2869
2870         /* Write the length token to the last word */
2871         bcmerror = brcmf_sdbrcm_membytes(bus, true, (bus->orig_ramsize - 4),
2872                                     (u8 *)&varsizew, 4);
2873
2874         return bcmerror;
2875 }
2876
2877 static int brcmf_sdbrcm_download_state(dhd_bus_t *bus, bool enter)
2878 {
2879         uint retries;
2880         u32 regdata;
2881         int bcmerror = 0;
2882
2883         /* To enter download state, disable ARM and reset SOCRAM.
2884          * To exit download state, simply reset ARM (default is RAM boot).
2885          */
2886         if (enter) {
2887                 bus->alp_only = true;
2888
2889                 brcmf_sdbrcm_chip_disablecore(bus->sdh, bus->ci->armcorebase);
2890
2891                 brcmf_sdbrcm_chip_resetcore(bus->sdh, bus->ci->ramcorebase);
2892
2893                 /* Clear the top bit of memory */
2894                 if (bus->ramsize) {
2895                         u32 zeros = 0;
2896                         brcmf_sdbrcm_membytes(bus, true, bus->ramsize - 4,
2897                                          (u8 *)&zeros, 4);
2898                 }
2899         } else {
2900                 regdata = brcmf_sdcard_reg_read(bus->sdh,
2901                         CORE_SB(bus->ci->ramcorebase, sbtmstatelow), 4);
2902                 regdata &= (SBTML_RESET | SBTML_REJ_MASK |
2903                         (SICF_CLOCK_EN << SBTML_SICF_SHIFT));
2904                 if ((SICF_CLOCK_EN << SBTML_SICF_SHIFT) != regdata) {
2905                         DHD_ERROR(("%s: SOCRAM core is down after reset?\n",
2906                                    __func__));
2907                         bcmerror = -EBADE;
2908                         goto fail;
2909                 }
2910
2911                 bcmerror = brcmf_sdbrcm_write_vars(bus);
2912                 if (bcmerror) {
2913                         DHD_ERROR(("%s: no vars written to RAM\n", __func__));
2914                         bcmerror = 0;
2915                 }
2916
2917                 W_SDREG(0xFFFFFFFF, &bus->regs->intstatus, retries);
2918
2919                 brcmf_sdbrcm_chip_resetcore(bus->sdh, bus->ci->armcorebase);
2920
2921                 /* Allow HT Clock now that the ARM is running. */
2922                 bus->alp_only = false;
2923
2924                 bus->dhd->busstate = DHD_BUS_LOAD;
2925         }
2926 fail:
2927         return bcmerror;
2928 }
2929
2930 int
2931 brcmf_sdbrcm_bus_iovar_op(dhd_pub_t *dhdp, const char *name,
2932                           void *params, int plen, void *arg, int len, bool set)
2933 {
2934         dhd_bus_t *bus = dhdp->bus;
2935         const struct brcmu_iovar *vi = NULL;
2936         int bcmerror = 0;
2937         int val_size;
2938         u32 actionid;
2939
2940         DHD_TRACE(("%s: Enter\n", __func__));
2941
2942         ASSERT(name);
2943         ASSERT(len >= 0);
2944
2945         /* Get MUST have return space */
2946         ASSERT(set || (arg && len));
2947
2948         /* Set does NOT take qualifiers */
2949         ASSERT(!set || (!params && !plen));
2950
2951         /* Look up var locally; if not found pass to host driver */
2952         vi = brcmu_iovar_lookup(dhdsdio_iovars, name);
2953         if (vi == NULL) {
2954                 brcmf_os_sdlock(bus->dhd);
2955
2956                 BUS_WAKE(bus);
2957
2958                 /* Turn on clock in case SD command needs backplane */
2959                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
2960
2961                 bcmerror = brcmf_sdcard_iovar_op(bus->sdh, name, params, plen,
2962                                                  arg, len, set);
2963
2964                 /* Similar check for blocksize change */
2965                 if (set && strcmp(name, "sd_blocksize") == 0) {
2966                         s32 fnum = 2;
2967                         if (brcmf_sdcard_iovar_op
2968                             (bus->sdh, "sd_blocksize", &fnum, sizeof(s32),
2969                              &bus->blocksize, sizeof(s32),
2970                              false) != 0) {
2971                                 bus->blocksize = 0;
2972                                 DHD_ERROR(("%s: fail on %s get\n", __func__,
2973                                            "sd_blocksize"));
2974                         } else {
2975                                 DHD_INFO(("%s: noted %s update, value now %d\n",
2976                                           __func__, "sd_blocksize",
2977                                           bus->blocksize));
2978                         }
2979                 }
2980                 bus->roundup = min(max_roundup, bus->blocksize);
2981
2982                 if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) {
2983                         bus->activity = false;
2984                         brcmf_sdbrcm_clkctl(bus, CLK_NONE, true);
2985                 }
2986
2987                 brcmf_os_sdunlock(bus->dhd);
2988                 goto exit;
2989         }
2990
2991         DHD_CTL(("%s: %s %s, len %d plen %d\n", __func__,
2992                  name, (set ? "set" : "get"), len, plen));
2993
2994         /* set up 'params' pointer in case this is a set command so that
2995          * the convenience int and bool code can be common to set and get
2996          */
2997         if (params == NULL) {
2998                 params = arg;
2999                 plen = len;
3000         }
3001
3002         if (vi->type == IOVT_VOID)
3003                 val_size = 0;
3004         else if (vi->type == IOVT_BUFFER)
3005                 val_size = len;
3006         else
3007                 /* all other types are integer sized */
3008                 val_size = sizeof(int);
3009
3010         actionid = set ? IOV_SVAL(vi->varid) : IOV_GVAL(vi->varid);
3011         bcmerror = brcmf_sdbrcm_doiovar(bus, vi, actionid, name, params, plen,
3012                                         arg, len, val_size);
3013
3014 exit:
3015         return bcmerror;
3016 }
3017
3018 void brcmf_sdbrcm_bus_stop(struct dhd_bus *bus, bool enforce_mutex)
3019 {
3020         u32 local_hostintmask;
3021         u8 saveclk;
3022         uint retries;
3023         int err;
3024
3025         DHD_TRACE(("%s: Enter\n", __func__));
3026
3027         if (enforce_mutex)
3028                 brcmf_os_sdlock(bus->dhd);
3029
3030         BUS_WAKE(bus);
3031
3032         /* Enable clock for device interrupts */
3033         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
3034
3035         /* Disable and clear interrupts at the chip level also */
3036         W_SDREG(0, &bus->regs->hostintmask, retries);
3037         local_hostintmask = bus->hostintmask;
3038         bus->hostintmask = 0;
3039
3040         /* Change our idea of bus state */
3041         bus->dhd->busstate = DHD_BUS_DOWN;
3042
3043         /* Force clocks on backplane to be sure F2 interrupt propagates */
3044         saveclk = brcmf_sdcard_cfg_read(bus->sdh, SDIO_FUNC_1,
3045                                         SBSDIO_FUNC1_CHIPCLKCSR, &err);
3046         if (!err) {
3047                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1,
3048                                        SBSDIO_FUNC1_CHIPCLKCSR,
3049                                        (saveclk | SBSDIO_FORCE_HT), &err);
3050         }
3051         if (err) {
3052                 DHD_ERROR(("%s: Failed to force clock for F2: err %d\n",
3053                            __func__, err));
3054         }
3055
3056         /* Turn off the bus (F2), free any pending packets */
3057         DHD_INTR(("%s: disable SDIO interrupts\n", __func__));
3058         brcmf_sdcard_intr_disable(bus->sdh);
3059         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_0, SDIO_CCCR_IOEx,
3060                          SDIO_FUNC_ENABLE_1, NULL);
3061
3062         /* Clear any pending interrupts now that F2 is disabled */
3063         W_SDREG(local_hostintmask, &bus->regs->intstatus, retries);
3064
3065         /* Turn off the backplane clock (only) */
3066         brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
3067
3068         /* Clear the data packet queues */
3069         brcmu_pktq_flush(&bus->txq, true, NULL, NULL);
3070
3071         /* Clear any held glomming stuff */
3072         if (bus->glomd)
3073                 brcmu_pkt_buf_free_skb(bus->glomd);
3074
3075         if (bus->glom)
3076                 brcmu_pkt_buf_free_skb(bus->glom);
3077
3078         bus->glom = bus->glomd = NULL;
3079
3080         /* Clear rx control and wake any waiters */
3081         bus->rxlen = 0;
3082         brcmf_os_ioctl_resp_wake(bus->dhd);
3083
3084         /* Reset some F2 state stuff */
3085         bus->rxskip = false;
3086         bus->tx_seq = bus->rx_seq = 0;
3087
3088         if (enforce_mutex)
3089                 brcmf_os_sdunlock(bus->dhd);
3090 }
3091
3092 int brcmf_sdbrcm_bus_init(dhd_pub_t *dhdp, bool enforce_mutex)
3093 {
3094         dhd_bus_t *bus = dhdp->bus;
3095         dhd_timeout_t tmo;
3096         uint retries = 0;
3097         u8 ready, enable;
3098         int err, ret = 0;
3099         u8 saveclk;
3100
3101         DHD_TRACE(("%s: Enter\n", __func__));
3102
3103         ASSERT(bus->dhd);
3104         if (!bus->dhd)
3105                 return 0;
3106
3107         if (enforce_mutex)
3108                 brcmf_os_sdlock(bus->dhd);
3109
3110         /* Make sure backplane clock is on, needed to generate F2 interrupt */
3111         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
3112         if (bus->clkstate != CLK_AVAIL)
3113                 goto exit;
3114
3115         /* Force clocks on backplane to be sure F2 interrupt propagates */
3116         saveclk =
3117             brcmf_sdcard_cfg_read(bus->sdh, SDIO_FUNC_1,
3118                                   SBSDIO_FUNC1_CHIPCLKCSR, &err);
3119         if (!err) {
3120                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1,
3121                                        SBSDIO_FUNC1_CHIPCLKCSR,
3122                                        (saveclk | SBSDIO_FORCE_HT), &err);
3123         }
3124         if (err) {
3125                 DHD_ERROR(("%s: Failed to force clock for F2: err %d\n",
3126                            __func__, err));
3127                 goto exit;
3128         }
3129
3130         /* Enable function 2 (frame transfers) */
3131         W_SDREG((SDPCM_PROT_VERSION << SMB_DATA_VERSION_SHIFT),
3132                 &bus->regs->tosbmailboxdata, retries);
3133         enable = (SDIO_FUNC_ENABLE_1 | SDIO_FUNC_ENABLE_2);
3134
3135         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_0, SDIO_CCCR_IOEx, enable,
3136                                NULL);
3137
3138         /* Give the dongle some time to do its thing and set IOR2 */
3139         brcmf_timeout_start(&tmo, DHD_WAIT_F2RDY * 1000);
3140
3141         ready = 0;
3142         while (ready != enable && !brcmf_timeout_expired(&tmo))
3143                 ready =
3144                     brcmf_sdcard_cfg_read(bus->sdh, SDIO_FUNC_0, SDIO_CCCR_IORx,
3145                                     NULL);
3146
3147         DHD_INFO(("%s: enable 0x%02x, ready 0x%02x (waited %uus)\n",
3148                   __func__, enable, ready, tmo.elapsed));
3149
3150         /* If F2 successfully enabled, set core and enable interrupts */
3151         if (ready == enable) {
3152                 /* Set up the interrupt mask and enable interrupts */
3153                 bus->hostintmask = HOSTINTMASK;
3154                 W_SDREG(bus->hostintmask,
3155                         (unsigned int *)CORE_BUS_REG(bus->ci->buscorebase,
3156                         hostintmask), retries);
3157
3158                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_WATERMARK,
3159                                  (u8) watermark, &err);
3160
3161                 /* Set bus state according to enable result */
3162                 dhdp->busstate = DHD_BUS_DATA;
3163
3164                 /* bcmsdh_intr_unmask(bus->sdh); */
3165
3166                 bus->intdis = false;
3167                 if (bus->intr) {
3168                         DHD_INTR(("%s: enable SDIO device interrupts\n",
3169                                   __func__));
3170                         brcmf_sdcard_intr_enable(bus->sdh);
3171                 } else {
3172                         DHD_INTR(("%s: disable SDIO interrupts\n", __func__));
3173                         brcmf_sdcard_intr_disable(bus->sdh);
3174                 }
3175
3176         }
3177
3178         else {
3179                 /* Disable F2 again */
3180                 enable = SDIO_FUNC_ENABLE_1;
3181                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_0, SDIO_CCCR_IOEx,
3182                                        enable, NULL);
3183         }
3184
3185         /* Restore previous clock setting */
3186         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
3187                          saveclk, &err);
3188
3189         /* If we didn't come up, turn off backplane clock */
3190         if (dhdp->busstate != DHD_BUS_DATA)
3191                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
3192
3193 exit:
3194         if (enforce_mutex)
3195                 brcmf_os_sdunlock(bus->dhd);
3196
3197         return ret;
3198 }
3199
3200 static void brcmf_sdbrcm_rxfail(dhd_bus_t *bus, bool abort, bool rtx)
3201 {
3202         struct brcmf_sdio *sdh = bus->sdh;
3203         struct sdpcmd_regs *regs = bus->regs;
3204         uint retries = 0;
3205         u16 lastrbc;
3206         u8 hi, lo;
3207         int err;
3208
3209         DHD_ERROR(("%s: %sterminate frame%s\n", __func__,
3210                    (abort ? "abort command, " : ""),
3211                    (rtx ? ", send NAK" : "")));
3212
3213         if (abort)
3214                 brcmf_sdcard_abort(sdh, SDIO_FUNC_2);
3215
3216         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_FRAMECTRL,
3217                                SFC_RF_TERM, &err);
3218         bus->f1regdata++;
3219
3220         /* Wait until the packet has been flushed (device/FIFO stable) */
3221         for (lastrbc = retries = 0xffff; retries > 0; retries--) {
3222                 hi = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
3223                                            SBSDIO_FUNC1_RFRAMEBCHI, NULL);
3224                 lo = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
3225                                            SBSDIO_FUNC1_RFRAMEBCLO, NULL);
3226                 bus->f1regdata += 2;
3227
3228                 if ((hi == 0) && (lo == 0))
3229                         break;
3230
3231                 if ((hi > (lastrbc >> 8)) && (lo > (lastrbc & 0x00ff))) {
3232                         DHD_ERROR(("%s: count growing: last 0x%04x now "
3233                                 "0x%04x\n",
3234                                 __func__, lastrbc, ((hi << 8) + lo)));
3235                 }
3236                 lastrbc = (hi << 8) + lo;
3237         }
3238
3239         if (!retries) {
3240                 DHD_ERROR(("%s: count never zeroed: last 0x%04x\n",
3241                            __func__, lastrbc));
3242         } else {
3243                 DHD_INFO(("%s: flush took %d iterations\n", __func__,
3244                           (0xffff - retries)));
3245         }
3246
3247         if (rtx) {
3248                 bus->rxrtx++;
3249                 W_SDREG(SMB_NAK, &regs->tosbmailbox, retries);
3250                 bus->f1regdata++;
3251                 if (retries <= retry_limit)
3252                         bus->rxskip = true;
3253         }
3254
3255         /* Clear partial in any case */
3256         bus->nextlen = 0;
3257
3258         /* If we can't reach the device, signal failure */
3259         if (err || brcmf_sdcard_regfail(sdh))
3260                 bus->dhd->busstate = DHD_BUS_DOWN;
3261 }
3262
3263 static void
3264 brcmf_sdbrcm_read_control(dhd_bus_t *bus, u8 *hdr, uint len, uint doff)
3265 {
3266         struct brcmf_sdio *sdh = bus->sdh;
3267         uint rdlen, pad;
3268
3269         int sdret;
3270
3271         DHD_TRACE(("%s: Enter\n", __func__));
3272
3273         /* Control data already received in aligned rxctl */
3274         if ((bus->bus == SPI_BUS) && (!bus->usebufpool))
3275                 goto gotpkt;
3276
3277         ASSERT(bus->rxbuf);
3278         /* Set rxctl for frame (w/optional alignment) */
3279         bus->rxctl = bus->rxbuf;
3280         if (dhd_alignctl) {
3281                 bus->rxctl += firstread;
3282                 pad = ((unsigned long)bus->rxctl % DHD_SDALIGN);
3283                 if (pad)
3284                         bus->rxctl += (DHD_SDALIGN - pad);
3285                 bus->rxctl -= firstread;
3286         }
3287         ASSERT(bus->rxctl >= bus->rxbuf);
3288
3289         /* Copy the already-read portion over */
3290         memcpy(bus->rxctl, hdr, firstread);
3291         if (len <= firstread)
3292                 goto gotpkt;
3293
3294         /* Copy the full data pkt in gSPI case and process ioctl. */
3295         if (bus->bus == SPI_BUS) {
3296                 memcpy(bus->rxctl, hdr, len);
3297                 goto gotpkt;
3298         }
3299
3300         /* Raise rdlen to next SDIO block to avoid tail command */
3301         rdlen = len - firstread;
3302         if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) {
3303                 pad = bus->blocksize - (rdlen % bus->blocksize);
3304                 if ((pad <= bus->roundup) && (pad < bus->blocksize) &&
3305                     ((len + pad) < bus->dhd->maxctl))
3306                         rdlen += pad;
3307         } else if (rdlen % DHD_SDALIGN) {
3308                 rdlen += DHD_SDALIGN - (rdlen % DHD_SDALIGN);
3309         }
3310
3311         /* Satisfy length-alignment requirements */
3312         if (forcealign && (rdlen & (ALIGNMENT - 1)))
3313                 rdlen = roundup(rdlen, ALIGNMENT);
3314
3315         /* Drop if the read is too big or it exceeds our maximum */
3316         if ((rdlen + firstread) > bus->dhd->maxctl) {
3317                 DHD_ERROR(("%s: %d-byte control read exceeds %d-byte buffer\n",
3318                            __func__, rdlen, bus->dhd->maxctl));
3319                 bus->dhd->rx_errors++;
3320                 brcmf_sdbrcm_rxfail(bus, false, false);
3321                 goto done;
3322         }
3323
3324         if ((len - doff) > bus->dhd->maxctl) {
3325                 DHD_ERROR(("%s: %d-byte ctl frame (%d-byte ctl data) exceeds "
3326                         "%d-byte limit\n",
3327                         __func__, len, (len - doff), bus->dhd->maxctl));
3328                 bus->dhd->rx_errors++;
3329                 bus->rx_toolong++;
3330                 brcmf_sdbrcm_rxfail(bus, false, false);
3331                 goto done;
3332         }
3333
3334         /* Read remainder of frame body into the rxctl buffer */
3335         sdret = brcmf_sdcard_recv_buf(sdh, brcmf_sdcard_cur_sbwad(sdh),
3336                                 SDIO_FUNC_2,
3337                                 F2SYNC, (bus->rxctl + firstread), rdlen,
3338                                 NULL, NULL, NULL);
3339         bus->f2rxdata++;
3340         ASSERT(sdret != -BCME_PENDING);
3341
3342         /* Control frame failures need retransmission */
3343         if (sdret < 0) {
3344                 DHD_ERROR(("%s: read %d control bytes failed: %d\n",
3345                            __func__, rdlen, sdret));
3346                 bus->rxc_errors++;      /* dhd.rx_ctlerrs is higher level */
3347                 brcmf_sdbrcm_rxfail(bus, true, true);
3348                 goto done;
3349         }
3350
3351 gotpkt:
3352
3353 #ifdef DHD_DEBUG
3354         if (DHD_BYTES_ON() && DHD_CTL_ON()) {
3355                 printk(KERN_DEBUG "RxCtrl:\n");
3356                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, bus->rxctl, len);
3357         }
3358 #endif
3359
3360         /* Point to valid data and indicate its length */
3361         bus->rxctl += doff;
3362         bus->rxlen = len - doff;
3363
3364 done:
3365         /* Awake any waiters */
3366         brcmf_os_ioctl_resp_wake(bus->dhd);
3367 }
3368
3369 static u8 brcmf_sdbrcm_rxglom(dhd_bus_t *bus, u8 rxseq)
3370 {
3371         u16 dlen, totlen;
3372         u8 *dptr, num = 0;
3373
3374         u16 sublen, check;
3375         struct sk_buff *pfirst, *plast, *pnext, *save_pfirst;
3376
3377         int errcode;
3378         u8 chan, seq, doff, sfdoff;
3379         u8 txmax;
3380
3381         int ifidx = 0;
3382         bool usechain = bus->use_rxchain;
3383
3384         /* If packets, issue read(s) and send up packet chain */
3385         /* Return sequence numbers consumed? */
3386
3387         DHD_TRACE(("brcmf_sdbrcm_rxglom: start: glomd %p glom %p\n", bus->glomd,
3388                    bus->glom));
3389
3390         /* If there's a descriptor, generate the packet chain */
3391         if (bus->glomd) {
3392                 pfirst = plast = pnext = NULL;
3393                 dlen = (u16) (bus->glomd->len);
3394                 dptr = bus->glomd->data;
3395                 if (!dlen || (dlen & 1)) {
3396                         DHD_ERROR(("%s: bad glomd len(%d), ignore descriptor\n",
3397                         __func__, dlen));
3398                         dlen = 0;
3399                 }
3400
3401                 for (totlen = num = 0; dlen; num++) {
3402                         /* Get (and move past) next length */
3403                         sublen = get_unaligned_le16(dptr);
3404                         dlen -= sizeof(u16);
3405                         dptr += sizeof(u16);
3406                         if ((sublen < SDPCM_HDRLEN) ||
3407                             ((num == 0) && (sublen < (2 * SDPCM_HDRLEN)))) {
3408                                 DHD_ERROR(("%s: descriptor len %d bad: %d\n",
3409                                            __func__, num, sublen));
3410                                 pnext = NULL;
3411                                 break;
3412                         }
3413                         if (sublen % DHD_SDALIGN) {
3414                                 DHD_ERROR(("%s: sublen %d not multiple of %d\n",
3415                                 __func__, sublen, DHD_SDALIGN));
3416                                 usechain = false;
3417                         }
3418                         totlen += sublen;
3419
3420                         /* For last frame, adjust read len so total
3421                                  is a block multiple */
3422                         if (!dlen) {
3423                                 sublen +=
3424                                     (roundup(totlen, bus->blocksize) - totlen);
3425                                 totlen = roundup(totlen, bus->blocksize);
3426                         }
3427
3428                         /* Allocate/chain packet for next subframe */
3429                         pnext = brcmu_pkt_buf_get_skb(sublen + DHD_SDALIGN);
3430                         if (pnext == NULL) {
3431                                 DHD_ERROR(("%s: bcm_pkt_buf_get_skb failed, "
3432                                         "num %d len %d\n", __func__,
3433                                         num, sublen));
3434                                 break;
3435                         }
3436                         ASSERT(!(pnext->prev));
3437                         if (!pfirst) {
3438                                 ASSERT(!plast);
3439                                 pfirst = plast = pnext;
3440                         } else {
3441                                 ASSERT(plast);
3442                                 plast->next = pnext;
3443                                 plast = pnext;
3444                         }
3445
3446                         /* Adhere to start alignment requirements */
3447                         PKTALIGN(pnext, sublen, DHD_SDALIGN);
3448                 }
3449
3450                 /* If all allocations succeeded, save packet chain
3451                          in bus structure */
3452                 if (pnext) {
3453                         DHD_GLOM(("%s: allocated %d-byte packet chain for %d "
3454                                 "subframes\n", __func__, totlen, num));
3455                         if (DHD_GLOM_ON() && bus->nextlen) {
3456                                 if (totlen != bus->nextlen) {
3457                                         DHD_GLOM(("%s: glomdesc mismatch: nextlen %d glomdesc %d " "rxseq %d\n",
3458                                                 __func__, bus->nextlen,
3459                                                 totlen, rxseq));
3460                                 }
3461                         }
3462                         bus->glom = pfirst;
3463                         pfirst = pnext = NULL;
3464                 } else {
3465                         if (pfirst)
3466                                 brcmu_pkt_buf_free_skb(pfirst);
3467                         bus->glom = NULL;
3468                         num = 0;
3469                 }
3470
3471                 /* Done with descriptor packet */
3472                 brcmu_pkt_buf_free_skb(bus->glomd);
3473                 bus->glomd = NULL;
3474                 bus->nextlen = 0;
3475         }
3476
3477         /* Ok -- either we just generated a packet chain,
3478                  or had one from before */
3479         if (bus->glom) {
3480                 if (DHD_GLOM_ON()) {
3481                         DHD_GLOM(("%s: try superframe read, packet chain:\n",
3482                                 __func__));
3483                         for (pnext = bus->glom; pnext; pnext = pnext->next) {
3484                                 DHD_GLOM(("    %p: %p len 0x%04x (%d)\n",
3485                                           pnext, (u8 *) (pnext->data),
3486                                           pnext->len, pnext->len));
3487                         }
3488                 }
3489
3490                 pfirst = bus->glom;
3491                 dlen = (u16) brcmu_pkttotlen(pfirst);
3492
3493                 /* Do an SDIO read for the superframe.  Configurable iovar to
3494                  * read directly into the chained packet, or allocate a large
3495                  * packet and and copy into the chain.
3496                  */
3497                 if (usechain) {
3498                         errcode = brcmf_sdcard_recv_buf(bus->sdh,
3499                                         brcmf_sdcard_cur_sbwad(bus->sdh),
3500                                         SDIO_FUNC_2,
3501                                         F2SYNC, (u8 *) pfirst->data, dlen,
3502                                         pfirst, NULL, NULL);
3503                 } else if (bus->dataptr) {
3504                         errcode = brcmf_sdcard_recv_buf(bus->sdh,
3505                                         brcmf_sdcard_cur_sbwad(bus->sdh),
3506                                         SDIO_FUNC_2,
3507                                         F2SYNC, bus->dataptr, dlen,
3508                                         NULL, NULL, NULL);
3509                         sublen = (u16) brcmu_pktfrombuf(pfirst, 0, dlen,
3510                                                 bus->dataptr);
3511                         if (sublen != dlen) {
3512                                 DHD_ERROR(("%s: FAILED TO COPY, dlen %d sublen %d\n",
3513                                         __func__, dlen, sublen));
3514                                 errcode = -1;
3515                         }
3516                         pnext = NULL;
3517                 } else {
3518                         DHD_ERROR(("COULDN'T ALLOC %d-BYTE GLOM, FORCE FAILURE\n",
3519                                 dlen));
3520                         errcode = -1;
3521                 }
3522                 bus->f2rxdata++;
3523                 ASSERT(errcode != -BCME_PENDING);
3524
3525                 /* On failure, kill the superframe, allow a couple retries */
3526                 if (errcode < 0) {
3527                         DHD_ERROR(("%s: glom read of %d bytes failed: %d\n",
3528                                    __func__, dlen, errcode));
3529                         bus->dhd->rx_errors++;
3530
3531                         if (bus->glomerr++ < 3) {
3532                                 brcmf_sdbrcm_rxfail(bus, true, true);
3533                         } else {
3534                                 bus->glomerr = 0;
3535                                 brcmf_sdbrcm_rxfail(bus, true, false);
3536                                 brcmu_pkt_buf_free_skb(bus->glom);
3537                                 bus->rxglomfail++;
3538                                 bus->glom = NULL;
3539                         }
3540                         return 0;
3541                 }
3542 #ifdef DHD_DEBUG
3543                 if (DHD_GLOM_ON()) {
3544                         printk(KERN_DEBUG "SUPERFRAME:\n");
3545                         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
3546                                 pfirst->data, min_t(int, pfirst->len, 48));
3547                 }
3548 #endif
3549
3550                 /* Validate the superframe header */
3551                 dptr = (u8 *) (pfirst->data);
3552                 sublen = get_unaligned_le16(dptr);
3553                 check = get_unaligned_le16(dptr + sizeof(u16));
3554
3555                 chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]);
3556                 seq = SDPCM_PACKET_SEQUENCE(&dptr[SDPCM_FRAMETAG_LEN]);
3557                 bus->nextlen = dptr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET];
3558                 if ((bus->nextlen << 4) > MAX_RX_DATASZ) {
3559                         DHD_INFO(("%s: nextlen too large (%d) seq %d\n",
3560                                 __func__, bus->nextlen, seq));
3561                         bus->nextlen = 0;
3562                 }
3563                 doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
3564                 txmax = SDPCM_WINDOW_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
3565
3566                 errcode = 0;
3567                 if ((u16)~(sublen ^ check)) {
3568                         DHD_ERROR(("%s (superframe): HW hdr error: len/check "
3569                                 "0x%04x/0x%04x\n", __func__, sublen, check));
3570                         errcode = -1;
3571                 } else if (roundup(sublen, bus->blocksize) != dlen) {
3572                         DHD_ERROR(("%s (superframe): len 0x%04x, rounded "
3573                                 "0x%04x, expect 0x%04x\n",
3574                                 __func__, sublen,
3575                                 roundup(sublen, bus->blocksize), dlen));
3576                         errcode = -1;
3577                 } else if (SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]) !=
3578                            SDPCM_GLOM_CHANNEL) {
3579                         DHD_ERROR(("%s (superframe): bad channel %d\n",
3580                                    __func__,
3581                                    SDPCM_PACKET_CHANNEL(&dptr
3582                                                         [SDPCM_FRAMETAG_LEN])));
3583                         errcode = -1;
3584                 } else if (SDPCM_GLOMDESC(&dptr[SDPCM_FRAMETAG_LEN])) {
3585                         DHD_ERROR(("%s (superframe): got second descriptor?\n",
3586                                    __func__));
3587                         errcode = -1;
3588                 } else if ((doff < SDPCM_HDRLEN) ||
3589                            (doff > (pfirst->len - SDPCM_HDRLEN))) {
3590                         DHD_ERROR(("%s (superframe): Bad data offset %d: HW %d "
3591                                 "pkt %d min %d\n",
3592                                 __func__, doff, sublen,
3593                                 pfirst->len, SDPCM_HDRLEN));
3594                         errcode = -1;
3595                 }
3596
3597                 /* Check sequence number of superframe SW header */
3598                 if (rxseq != seq) {
3599                         DHD_INFO(("%s: (superframe) rx_seq %d, expected %d\n",
3600                                   __func__, seq, rxseq));
3601                         bus->rx_badseq++;
3602                         rxseq = seq;
3603                 }
3604
3605                 /* Check window for sanity */
3606                 if ((u8) (txmax - bus->tx_seq) > 0x40) {
3607                         DHD_ERROR(("%s: unlikely tx max %d with tx_seq %d\n",
3608                                 __func__, txmax, bus->tx_seq));
3609                         txmax = bus->tx_seq + 2;
3610                 }
3611                 bus->tx_max = txmax;
3612
3613                 /* Remove superframe header, remember offset */
3614                 skb_pull(pfirst, doff);
3615                 sfdoff = doff;
3616
3617                 /* Validate all the subframe headers */
3618                 for (num = 0, pnext = pfirst; pnext && !errcode;
3619                      num++, pnext = pnext->next) {
3620                         dptr = (u8 *) (pnext->data);
3621                         dlen = (u16) (pnext->len);
3622                         sublen = get_unaligned_le16(dptr);
3623                         check = get_unaligned_le16(dptr + sizeof(u16));
3624                         chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]);
3625                         doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
3626 #ifdef DHD_DEBUG
3627                         if (DHD_GLOM_ON()) {
3628                                 printk(KERN_DEBUG "subframe:\n");
3629                                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
3630                                                      dptr, 32);
3631                         }
3632 #endif
3633
3634                         if ((u16)~(sublen ^ check)) {
3635                                 DHD_ERROR(("%s (subframe %d): HW hdr error: "
3636                                            "len/check 0x%04x/0x%04x\n",
3637                                            __func__, num, sublen, check));
3638                                 errcode = -1;
3639                         } else if ((sublen > dlen) || (sublen < SDPCM_HDRLEN)) {
3640                                 DHD_ERROR(("%s (subframe %d): length mismatch: "
3641                                            "len 0x%04x, expect 0x%04x\n",
3642                                            __func__, num, sublen, dlen));
3643                                 errcode = -1;
3644                         } else if ((chan != SDPCM_DATA_CHANNEL) &&
3645                                    (chan != SDPCM_EVENT_CHANNEL)) {
3646                                 DHD_ERROR(("%s (subframe %d): bad channel %d\n",
3647                                            __func__, num, chan));
3648                                 errcode = -1;
3649                         } else if ((doff < SDPCM_HDRLEN) || (doff > sublen)) {
3650                                 DHD_ERROR(("%s (subframe %d): Bad data offset %d: HW %d min %d\n",
3651                                         __func__, num, doff, sublen,
3652                                         SDPCM_HDRLEN));
3653                                 errcode = -1;
3654                         }
3655                 }
3656
3657                 if (errcode) {
3658                         /* Terminate frame on error, request
3659                                  a couple retries */
3660                         if (bus->glomerr++ < 3) {
3661                                 /* Restore superframe header space */
3662                                 skb_push(pfirst, sfdoff);
3663                                 brcmf_sdbrcm_rxfail(bus, true, true);
3664                         } else {
3665                                 bus->glomerr = 0;
3666                                 brcmf_sdbrcm_rxfail(bus, true, false);
3667                                 brcmu_pkt_buf_free_skb(bus->glom);
3668                                 bus->rxglomfail++;
3669                                 bus->glom = NULL;
3670                         }
3671                         bus->nextlen = 0;
3672                         return 0;
3673                 }
3674
3675                 /* Basic SD framing looks ok - process each packet (header) */
3676                 save_pfirst = pfirst;
3677                 bus->glom = NULL;
3678                 plast = NULL;
3679
3680                 for (num = 0; pfirst; rxseq++, pfirst = pnext) {
3681                         pnext = pfirst->next;
3682                         pfirst->next = NULL;
3683
3684                         dptr = (u8 *) (pfirst->data);
3685                         sublen = get_unaligned_le16(dptr);
3686                         chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]);
3687                         seq = SDPCM_PACKET_SEQUENCE(&dptr[SDPCM_FRAMETAG_LEN]);
3688                         doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
3689
3690                         DHD_GLOM(("%s: Get subframe %d, %p(%p/%d), sublen %d "
3691                                 "chan %d seq %d\n",
3692                                 __func__, num, pfirst, pfirst->data,
3693                                 pfirst->len, sublen, chan, seq));
3694
3695                         ASSERT((chan == SDPCM_DATA_CHANNEL)
3696                                || (chan == SDPCM_EVENT_CHANNEL));
3697
3698                         if (rxseq != seq) {
3699                                 DHD_GLOM(("%s: rx_seq %d, expected %d\n",
3700                                           __func__, seq, rxseq));
3701                                 bus->rx_badseq++;
3702                                 rxseq = seq;
3703                         }
3704 #ifdef DHD_DEBUG
3705                         if (DHD_BYTES_ON() && DHD_DATA_ON()) {
3706                                 printk(KERN_DEBUG "Rx Subframe Data:\n");
3707                                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
3708                                                      dptr, dlen);
3709                         }
3710 #endif
3711
3712                         __skb_trim(pfirst, sublen);
3713                         skb_pull(pfirst, doff);
3714
3715                         if (pfirst->len == 0) {
3716                                 brcmu_pkt_buf_free_skb(pfirst);
3717                                 if (plast) {
3718                                         plast->next = pnext;
3719                                 } else {
3720                                         ASSERT(save_pfirst == pfirst);
3721                                         save_pfirst = pnext;
3722                                 }
3723                                 continue;
3724                         } else if (brcmf_proto_hdrpull(bus->dhd, &ifidx, pfirst)
3725                                         != 0) {
3726                                 DHD_ERROR(("%s: rx protocol error\n",
3727                                            __func__));
3728                                 bus->dhd->rx_errors++;
3729                                 brcmu_pkt_buf_free_skb(pfirst);
3730                                 if (plast) {
3731                                         plast->next = pnext;
3732                                 } else {
3733                                         ASSERT(save_pfirst == pfirst);
3734                                         save_pfirst = pnext;
3735                                 }
3736                                 continue;
3737                         }
3738
3739                         /* this packet will go up, link back into
3740                                  chain and count it */
3741                         pfirst->next = pnext;
3742                         plast = pfirst;
3743                         num++;
3744
3745 #ifdef DHD_DEBUG
3746                         if (DHD_GLOM_ON()) {
3747                                 DHD_GLOM(("%s subframe %d to stack, %p(%p/%d) "
3748                                 "nxt/lnk %p/%p\n",
3749                                 __func__, num, pfirst, pfirst->data,
3750                                 pfirst->len, pfirst->next,
3751                                 pfirst->prev));
3752                                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
3753                                                 pfirst->data,
3754                                                 min_t(int, pfirst->len, 32));
3755                         }
3756 #endif                          /* DHD_DEBUG */
3757                 }
3758                 if (num) {
3759                         brcmf_os_sdunlock(bus->dhd);
3760                         brcmf_rx_frame(bus->dhd, ifidx, save_pfirst, num);
3761                         brcmf_os_sdlock(bus->dhd);
3762                 }
3763
3764                 bus->rxglomframes++;
3765                 bus->rxglompkts += num;
3766         }
3767         return num;
3768 }
3769
3770 /* Return true if there may be more frames to read */
3771 static uint
3772 brcmf_sdbrcm_readframes(dhd_bus_t *bus, uint maxframes, bool *finished)
3773 {
3774         struct brcmf_sdio *sdh = bus->sdh;
3775
3776         u16 len, check; /* Extracted hardware header fields */
3777         u8 chan, seq, doff;     /* Extracted software header fields */
3778         u8 fcbits;              /* Extracted fcbits from software header */
3779
3780         struct sk_buff *pkt;            /* Packet for event or data frames */
3781         u16 pad;                /* Number of pad bytes to read */
3782         u16 rdlen;              /* Total number of bytes to read */
3783         u8 rxseq;               /* Next sequence number to expect */
3784         uint rxleft = 0;        /* Remaining number of frames allowed */
3785         int sdret;              /* Return code from bcmsdh calls */
3786         u8 txmax;               /* Maximum tx sequence offered */
3787         bool len_consistent;    /* Result of comparing readahead len and
3788                                          len from hw-hdr */
3789         u8 *rxbuf;
3790         int ifidx = 0;
3791         uint rxcount = 0;       /* Total frames read */
3792
3793 #if defined(DHD_DEBUG) || defined(SDTEST)
3794         bool sdtest = false;    /* To limit message spew from test mode */
3795 #endif
3796
3797         DHD_TRACE(("%s: Enter\n", __func__));
3798
3799         ASSERT(maxframes);
3800
3801 #ifdef SDTEST
3802         /* Allow pktgen to override maxframes */
3803         if (bus->pktgen_count && (bus->pktgen_mode == DHD_PKTGEN_RECV)) {
3804                 maxframes = bus->pktgen_count;
3805                 sdtest = true;
3806         }
3807 #endif
3808
3809         /* Not finished unless we encounter no more frames indication */
3810         *finished = false;
3811
3812         for (rxseq = bus->rx_seq, rxleft = maxframes;
3813              !bus->rxskip && rxleft && bus->dhd->busstate != DHD_BUS_DOWN;
3814              rxseq++, rxleft--) {
3815
3816                 /* Handle glomming separately */
3817                 if (bus->glom || bus->glomd) {
3818                         u8 cnt;
3819                         DHD_GLOM(("%s: calling rxglom: glomd %p, glom %p\n",
3820                                   __func__, bus->glomd, bus->glom));
3821                         cnt = brcmf_sdbrcm_rxglom(bus, rxseq);
3822                         DHD_GLOM(("%s: rxglom returned %d\n", __func__, cnt));
3823                         rxseq += cnt - 1;
3824                         rxleft = (rxleft > cnt) ? (rxleft - cnt) : 1;
3825                         continue;
3826                 }
3827
3828                 /* Try doing single read if we can */
3829                 if (dhd_readahead && bus->nextlen) {
3830                         u16 nextlen = bus->nextlen;
3831                         bus->nextlen = 0;
3832
3833                         if (bus->bus == SPI_BUS) {
3834                                 rdlen = len = nextlen;
3835                         } else {
3836                                 rdlen = len = nextlen << 4;
3837
3838                                 /* Pad read to blocksize for efficiency */
3839                                 if (bus->roundup && bus->blocksize
3840                                     && (rdlen > bus->blocksize)) {
3841                                         pad =
3842                                             bus->blocksize -
3843                                             (rdlen % bus->blocksize);
3844                                         if ((pad <= bus->roundup)
3845                                             && (pad < bus->blocksize)
3846                                             && ((rdlen + pad + firstread) <
3847                                                 MAX_RX_DATASZ))
3848                                                 rdlen += pad;
3849                                 } else if (rdlen % DHD_SDALIGN) {
3850                                         rdlen +=
3851                                             DHD_SDALIGN - (rdlen % DHD_SDALIGN);
3852                                 }
3853                         }
3854
3855                         /* We use bus->rxctl buffer in WinXP for initial
3856                          * control pkt receives.
3857                          * Later we use buffer-poll for data as well
3858                          * as control packets.
3859                          * This is required because dhd receives full
3860                          * frame in gSPI unlike SDIO.
3861                          * After the frame is received we have to
3862                          * distinguish whether it is data
3863                          * or non-data frame.
3864                          */
3865                         /* Allocate a packet buffer */
3866                         pkt = brcmu_pkt_buf_get_skb(rdlen + DHD_SDALIGN);
3867                         if (!pkt) {
3868                                 if (bus->bus == SPI_BUS) {
3869                                         bus->usebufpool = false;
3870                                         bus->rxctl = bus->rxbuf;
3871                                         if (dhd_alignctl) {
3872                                                 bus->rxctl += firstread;
3873                                                 pad = ((unsigned long)bus->rxctl %
3874                                                       DHD_SDALIGN);
3875                                                 if (pad)
3876                                                         bus->rxctl +=
3877                                                             (DHD_SDALIGN - pad);
3878                                                 bus->rxctl -= firstread;
3879                                         }
3880                                         ASSERT(bus->rxctl >= bus->rxbuf);
3881                                         rxbuf = bus->rxctl;
3882                                         /* Read the entire frame */
3883                                         sdret = brcmf_sdcard_recv_buf(sdh,
3884                                                     brcmf_sdcard_cur_sbwad(sdh),
3885                                                     SDIO_FUNC_2, F2SYNC,
3886                                                     rxbuf, rdlen,
3887                                                     NULL, NULL, NULL);
3888                                         bus->f2rxdata++;
3889                                         ASSERT(sdret != -BCME_PENDING);
3890
3891                                         /* Control frame failures need
3892                                          retransmission */
3893                                         if (sdret < 0) {
3894                                                 DHD_ERROR(("%s: read %d control bytes failed: %d\n",
3895                                                         __func__,
3896                                                         rdlen, sdret));
3897                                                 /* dhd.rx_ctlerrs is higher */
3898                                                 bus->rxc_errors++;
3899                                                 brcmf_sdbrcm_rxfail(bus, true,
3900                                                        (bus->bus ==
3901                                                         SPI_BUS) ? false
3902                                                        : true);
3903                                                 continue;
3904                                         }
3905                                 } else {
3906                                         /* Give up on data,
3907                                         request rtx of events */
3908                                         DHD_ERROR(("%s (nextlen): "
3909                                                    "brcmu_pkt_buf_get_skb "
3910                                                    "failed:"
3911                                                    " len %d rdlen %d expected"
3912                                                    " rxseq %d\n", __func__,
3913                                                    len, rdlen, rxseq));
3914                                         continue;
3915                                 }
3916                         } else {
3917                                 if (bus->bus == SPI_BUS)
3918                                         bus->usebufpool = true;
3919
3920                                 ASSERT(!(pkt->prev));
3921                                 PKTALIGN(pkt, rdlen, DHD_SDALIGN);
3922                                 rxbuf = (u8 *) (pkt->data);
3923                                 /* Read the entire frame */
3924                                 sdret = brcmf_sdcard_recv_buf(sdh,
3925                                                 brcmf_sdcard_cur_sbwad(sdh),
3926                                                 SDIO_FUNC_2, F2SYNC,
3927                                                 rxbuf, rdlen,
3928                                                 pkt, NULL, NULL);
3929                                 bus->f2rxdata++;
3930                                 ASSERT(sdret != -BCME_PENDING);
3931
3932                                 if (sdret < 0) {
3933                                         DHD_ERROR(("%s (nextlen): read %d bytes failed: %d\n",
3934                                                 __func__, rdlen, sdret));
3935                                         brcmu_pkt_buf_free_skb(pkt);
3936                                         bus->dhd->rx_errors++;
3937                                         /* Force retry w/normal header read.
3938                                          * Don't attempt NAK for
3939                                          * gSPI
3940                                          */
3941                                         brcmf_sdbrcm_rxfail(bus, true,
3942                                                        (bus->bus ==
3943                                                         SPI_BUS) ? false :
3944                                                        true);
3945                                         continue;
3946                                 }
3947                         }
3948
3949                         /* Now check the header */
3950                         memcpy(bus->rxhdr, rxbuf, SDPCM_HDRLEN);
3951
3952                         /* Extract hardware header fields */
3953                         len = get_unaligned_le16(bus->rxhdr);
3954                         check = get_unaligned_le16(bus->rxhdr + sizeof(u16));
3955
3956                         /* All zeros means readahead info was bad */
3957                         if (!(len | check)) {
3958                                 DHD_INFO(("%s (nextlen): read zeros in HW "
3959                                         "header???\n", __func__));
3960                                 brcmf_sdbrcm_pktfree2(bus, pkt);
3961                                 continue;
3962                         }
3963
3964                         /* Validate check bytes */
3965                         if ((u16)~(len ^ check)) {
3966                                 DHD_ERROR(("%s (nextlen): HW hdr error:"
3967                                         " nextlen/len/check"
3968                                         " 0x%04x/0x%04x/0x%04x\n",
3969                                         __func__, nextlen, len, check));
3970                                 bus->rx_badhdr++;
3971                                 brcmf_sdbrcm_rxfail(bus, false, false);
3972                                 brcmf_sdbrcm_pktfree2(bus, pkt);
3973                                 continue;
3974                         }
3975
3976                         /* Validate frame length */
3977                         if (len < SDPCM_HDRLEN) {
3978                                 DHD_ERROR(("%s (nextlen): HW hdr length "
3979                                         "invalid: %d\n", __func__, len));
3980                                 brcmf_sdbrcm_pktfree2(bus, pkt);
3981                                 continue;
3982                         }
3983
3984                         /* Check for consistency withreadahead info */
3985                         len_consistent = (nextlen != (roundup(len, 16) >> 4));
3986                         if (len_consistent) {
3987                                 /* Mismatch, force retry w/normal
3988                                         header (may be >4K) */
3989                                 DHD_ERROR(("%s (nextlen): mismatch, "
3990                                         "nextlen %d len %d rnd %d; "
3991                                         "expected rxseq %d\n",
3992                                         __func__, nextlen,
3993                                         len, roundup(len, 16), rxseq));
3994                                 brcmf_sdbrcm_rxfail(bus, true,
3995                                                   bus->bus != SPI_BUS);
3996                                 brcmf_sdbrcm_pktfree2(bus, pkt);
3997                                 continue;
3998                         }
3999
4000                         /* Extract software header fields */
4001                         chan = SDPCM_PACKET_CHANNEL(
4002                                         &bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4003                         seq = SDPCM_PACKET_SEQUENCE(
4004                                         &bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4005                         doff = SDPCM_DOFFSET_VALUE(
4006                                         &bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4007                         txmax = SDPCM_WINDOW_VALUE(
4008                                         &bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4009
4010                         bus->nextlen =
4011                             bus->rxhdr[SDPCM_FRAMETAG_LEN +
4012                                        SDPCM_NEXTLEN_OFFSET];
4013                         if ((bus->nextlen << 4) > MAX_RX_DATASZ) {
4014                                 DHD_INFO(("%s (nextlen): got frame w/nextlen too large" " (%d), seq %d\n",
4015                                         __func__, bus->nextlen, seq));
4016                                 bus->nextlen = 0;
4017                         }
4018
4019                         bus->dhd->rx_readahead_cnt++;
4020
4021                         /* Handle Flow Control */
4022                         fcbits = SDPCM_FCMASK_VALUE(
4023                                         &bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4024
4025                         if (bus->flowcontrol != fcbits) {
4026                                 if (~bus->flowcontrol & fcbits)
4027                                         bus->fc_xoff++;
4028
4029                                 if (bus->flowcontrol & ~fcbits)
4030                                         bus->fc_xon++;
4031
4032                                 bus->fc_rcvd++;
4033                                 bus->flowcontrol = fcbits;
4034                         }
4035
4036                         /* Check and update sequence number */
4037                         if (rxseq != seq) {
4038                                 DHD_INFO(("%s (nextlen): rx_seq %d, expected "
4039                                         "%d\n", __func__, seq, rxseq));
4040                                 bus->rx_badseq++;
4041                                 rxseq = seq;
4042                         }
4043
4044                         /* Check window for sanity */
4045                         if ((u8) (txmax - bus->tx_seq) > 0x40) {
4046                                 DHD_ERROR(("%s: got unlikely tx max %d with "
4047                                         "tx_seq %d\n",
4048                                         __func__, txmax, bus->tx_seq));
4049                                 txmax = bus->tx_seq + 2;
4050                         }
4051                         bus->tx_max = txmax;
4052
4053 #ifdef DHD_DEBUG
4054                         if (DHD_BYTES_ON() && DHD_DATA_ON()) {
4055                                 printk(KERN_DEBUG "Rx Data:\n");
4056                                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
4057                                                      rxbuf, len);
4058                         } else if (DHD_HDRS_ON()) {
4059                                 printk(KERN_DEBUG "RxHdr:\n");
4060                                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
4061                                                      bus->rxhdr, SDPCM_HDRLEN);
4062                         }
4063 #endif
4064
4065                         if (chan == SDPCM_CONTROL_CHANNEL) {
4066                                 if (bus->bus == SPI_BUS) {
4067                                         brcmf_sdbrcm_read_control(bus, rxbuf,
4068                                                                   len, doff);
4069                                 } else {
4070                                         DHD_ERROR(("%s (nextlen): readahead on control" " packet %d?\n",
4071                                                 __func__, seq));
4072                                         /* Force retry w/normal header read */
4073                                         bus->nextlen = 0;
4074                                         brcmf_sdbrcm_rxfail(bus, false, true);
4075                                 }
4076                                 brcmf_sdbrcm_pktfree2(bus, pkt);
4077                                 continue;
4078                         }
4079
4080                         if ((bus->bus == SPI_BUS) && !bus->usebufpool) {
4081                                 DHD_ERROR(("Received %d bytes on %d channel. Running out of " "rx pktbuf's or not yet malloced.\n",
4082                                         len, chan));
4083                                 continue;
4084                         }
4085
4086                         /* Validate data offset */
4087                         if ((doff < SDPCM_HDRLEN) || (doff > len)) {
4088                                 DHD_ERROR(("%s (nextlen): bad data offset %d: HW len %d min %d\n",
4089                                         __func__, doff, len, SDPCM_HDRLEN));
4090                                 brcmf_sdbrcm_rxfail(bus, false, false);
4091                                 brcmf_sdbrcm_pktfree2(bus, pkt);
4092                                 continue;
4093                         }
4094
4095                         /* All done with this one -- now deliver the packet */
4096                         goto deliver;
4097                 }
4098                 /* gSPI frames should not be handled in fractions */
4099                 if (bus->bus == SPI_BUS)
4100                         break;
4101
4102                 /* Read frame header (hardware and software) */
4103                 sdret = brcmf_sdcard_recv_buf(sdh, brcmf_sdcard_cur_sbwad(sdh),
4104                                 SDIO_FUNC_2, F2SYNC, bus->rxhdr, firstread,
4105                                 NULL, NULL, NULL);
4106                 bus->f2rxhdrs++;
4107                 ASSERT(sdret != -BCME_PENDING);
4108
4109                 if (sdret < 0) {
4110                         DHD_ERROR(("%s: RXHEADER FAILED: %d\n", __func__,
4111                                    sdret));
4112                         bus->rx_hdrfail++;
4113                         brcmf_sdbrcm_rxfail(bus, true, true);
4114                         continue;
4115                 }
4116 #ifdef DHD_DEBUG
4117                 if (DHD_BYTES_ON() || DHD_HDRS_ON()) {
4118                         printk(KERN_DEBUG "RxHdr:\n");
4119                         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
4120                                              bus->rxhdr, SDPCM_HDRLEN);
4121                 }
4122 #endif
4123
4124                 /* Extract hardware header fields */
4125                 len = get_unaligned_le16(bus->rxhdr);
4126                 check = get_unaligned_le16(bus->rxhdr + sizeof(u16));
4127
4128                 /* All zeros means no more frames */
4129                 if (!(len | check)) {
4130                         *finished = true;
4131                         break;
4132                 }
4133
4134                 /* Validate check bytes */
4135                 if ((u16) ~(len ^ check)) {
4136                         DHD_ERROR(("%s: HW hdr err: len/check 0x%04x/0x%04x\n",
4137                                 __func__, len, check));
4138                         bus->rx_badhdr++;
4139                         brcmf_sdbrcm_rxfail(bus, false, false);
4140                         continue;
4141                 }
4142
4143                 /* Validate frame length */
4144                 if (len < SDPCM_HDRLEN) {
4145                         DHD_ERROR(("%s: HW hdr length invalid: %d\n",
4146                                    __func__, len));
4147                         continue;
4148                 }
4149
4150                 /* Extract software header fields */
4151                 chan = SDPCM_PACKET_CHANNEL(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4152                 seq = SDPCM_PACKET_SEQUENCE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4153                 doff = SDPCM_DOFFSET_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4154                 txmax = SDPCM_WINDOW_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4155
4156                 /* Validate data offset */
4157                 if ((doff < SDPCM_HDRLEN) || (doff > len)) {
4158                         DHD_ERROR(("%s: Bad data offset %d: HW len %d, min %d "
4159                                 "seq %d\n",
4160                                 __func__, doff, len, SDPCM_HDRLEN, seq));
4161                         bus->rx_badhdr++;
4162                         ASSERT(0);
4163                         brcmf_sdbrcm_rxfail(bus, false, false);
4164                         continue;
4165                 }
4166
4167                 /* Save the readahead length if there is one */
4168                 bus->nextlen =
4169                     bus->rxhdr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET];
4170                 if ((bus->nextlen << 4) > MAX_RX_DATASZ) {
4171                         DHD_INFO(("%s (nextlen): got frame w/nextlen too large "
4172                                 "(%d), seq %d\n",
4173                                 __func__, bus->nextlen, seq));
4174                         bus->nextlen = 0;
4175                 }
4176
4177                 /* Handle Flow Control */
4178                 fcbits = SDPCM_FCMASK_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
4179
4180                 if (bus->flowcontrol != fcbits) {
4181                         if (~bus->flowcontrol & fcbits)
4182                                 bus->fc_xoff++;
4183
4184                         if (bus->flowcontrol & ~fcbits)
4185                                 bus->fc_xon++;
4186
4187                         bus->fc_rcvd++;
4188                         bus->flowcontrol = fcbits;
4189                 }
4190
4191                 /* Check and update sequence number */
4192                 if (rxseq != seq) {
4193                         DHD_INFO(("%s: rx_seq %d, expected %d\n", __func__,
4194                                   seq, rxseq));
4195                         bus->rx_badseq++;
4196                         rxseq = seq;
4197                 }
4198
4199                 /* Check window for sanity */
4200                 if ((u8) (txmax - bus->tx_seq) > 0x40) {
4201                         DHD_ERROR(("%s: unlikely tx max %d with tx_seq %d\n",
4202                                 __func__, txmax, bus->tx_seq));
4203                         txmax = bus->tx_seq + 2;
4204                 }
4205                 bus->tx_max = txmax;
4206
4207                 /* Call a separate function for control frames */
4208                 if (chan == SDPCM_CONTROL_CHANNEL) {
4209                         brcmf_sdbrcm_read_control(bus, bus->rxhdr, len, doff);
4210                         continue;
4211                 }
4212
4213                 ASSERT((chan == SDPCM_DATA_CHANNEL)
4214                        || (chan == SDPCM_EVENT_CHANNEL)
4215                        || (chan == SDPCM_TEST_CHANNEL)
4216                        || (chan == SDPCM_GLOM_CHANNEL));
4217
4218                 /* Length to read */
4219                 rdlen = (len > firstread) ? (len - firstread) : 0;
4220
4221                 /* May pad read to blocksize for efficiency */
4222                 if (bus->roundup && bus->blocksize &&
4223                         (rdlen > bus->blocksize)) {
4224                         pad = bus->blocksize - (rdlen % bus->blocksize);
4225                         if ((pad <= bus->roundup) && (pad < bus->blocksize) &&
4226                             ((rdlen + pad + firstread) < MAX_RX_DATASZ))
4227                                 rdlen += pad;
4228                 } else if (rdlen % DHD_SDALIGN) {
4229                         rdlen += DHD_SDALIGN - (rdlen % DHD_SDALIGN);
4230                 }
4231
4232                 /* Satisfy length-alignment requirements */
4233                 if (forcealign && (rdlen & (ALIGNMENT - 1)))
4234                         rdlen = roundup(rdlen, ALIGNMENT);
4235
4236                 if ((rdlen + firstread) > MAX_RX_DATASZ) {
4237                         /* Too long -- skip this frame */
4238                         DHD_ERROR(("%s: too long: len %d rdlen %d\n",
4239                                    __func__, len, rdlen));
4240                         bus->dhd->rx_errors++;
4241                         bus->rx_toolong++;
4242                         brcmf_sdbrcm_rxfail(bus, false, false);
4243                         continue;
4244                 }
4245
4246                 pkt = brcmu_pkt_buf_get_skb(rdlen + firstread + DHD_SDALIGN);
4247                 if (!pkt) {
4248                         /* Give up on data, request rtx of events */
4249                         DHD_ERROR(("%s: brcmu_pkt_buf_get_skb failed: rdlen %d"
4250                                    " chan %d\n", __func__, rdlen, chan));
4251                         bus->dhd->rx_dropped++;
4252                         brcmf_sdbrcm_rxfail(bus, false, RETRYCHAN(chan));
4253                         continue;
4254                 }
4255
4256                 ASSERT(!(pkt->prev));
4257
4258                 /* Leave room for what we already read, and align remainder */
4259                 ASSERT(firstread < pkt->len);
4260                 skb_pull(pkt, firstread);
4261                 PKTALIGN(pkt, rdlen, DHD_SDALIGN);
4262
4263                 /* Read the remaining frame data */
4264                 sdret = brcmf_sdcard_recv_buf(sdh, brcmf_sdcard_cur_sbwad(sdh),
4265                                 SDIO_FUNC_2, F2SYNC, ((u8 *) (pkt->data)),
4266                                 rdlen, pkt, NULL, NULL);
4267                 bus->f2rxdata++;
4268                 ASSERT(sdret != -BCME_PENDING);
4269
4270                 if (sdret < 0) {
4271                         DHD_ERROR(("%s: read %d %s bytes failed: %d\n",
4272                                    __func__, rdlen,
4273                                    ((chan ==
4274                                      SDPCM_EVENT_CHANNEL) ? "event" : ((chan ==
4275                                         SDPCM_DATA_CHANNEL)
4276                                        ? "data" : "test")),
4277                                    sdret));
4278                         brcmu_pkt_buf_free_skb(pkt);
4279                         bus->dhd->rx_errors++;
4280                         brcmf_sdbrcm_rxfail(bus, true, RETRYCHAN(chan));
4281                         continue;
4282                 }
4283
4284                 /* Copy the already-read portion */
4285                 skb_push(pkt, firstread);
4286                 memcpy(pkt->data, bus->rxhdr, firstread);
4287
4288 #ifdef DHD_DEBUG
4289                 if (DHD_BYTES_ON() && DHD_DATA_ON()) {
4290                         printk(KERN_DEBUG "Rx Data:\n");
4291                         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
4292                                              pkt->data, len);
4293                 }
4294 #endif
4295
4296 deliver:
4297                 /* Save superframe descriptor and allocate packet frame */
4298                 if (chan == SDPCM_GLOM_CHANNEL) {
4299                         if (SDPCM_GLOMDESC(&bus->rxhdr[SDPCM_FRAMETAG_LEN])) {
4300                                 DHD_GLOM(("%s: glom descriptor, %d bytes:\n",
4301                                         __func__, len));
4302 #ifdef DHD_DEBUG
4303                                 if (DHD_GLOM_ON()) {
4304                                         printk(KERN_DEBUG "Glom Data:\n");
4305                                         print_hex_dump_bytes("",
4306                                                              DUMP_PREFIX_OFFSET,
4307                                                              pkt->data, len);
4308                                 }
4309 #endif
4310                                 __skb_trim(pkt, len);
4311                                 ASSERT(doff == SDPCM_HDRLEN);
4312                                 skb_pull(pkt, SDPCM_HDRLEN);
4313                                 bus->glomd = pkt;
4314                         } else {
4315                                 DHD_ERROR(("%s: glom superframe w/o "
4316                                         "descriptor!\n", __func__));
4317                                 brcmf_sdbrcm_rxfail(bus, false, false);
4318                         }
4319                         continue;
4320                 }
4321
4322                 /* Fill in packet len and prio, deliver upward */
4323                 __skb_trim(pkt, len);
4324                 skb_pull(pkt, doff);
4325
4326 #ifdef SDTEST
4327                 /* Test channel packets are processed separately */
4328                 if (chan == SDPCM_TEST_CHANNEL) {
4329                         brcmf_sdbrcm_checkdied(bus, pkt, seq);
4330                         continue;
4331                 }
4332 #endif                          /* SDTEST */
4333
4334                 if (pkt->len == 0) {
4335                         brcmu_pkt_buf_free_skb(pkt);
4336                         continue;
4337                 } else if (brcmf_proto_hdrpull(bus->dhd, &ifidx, pkt) != 0) {
4338                         DHD_ERROR(("%s: rx protocol error\n", __func__));
4339                         brcmu_pkt_buf_free_skb(pkt);
4340                         bus->dhd->rx_errors++;
4341                         continue;
4342                 }
4343
4344                 /* Unlock during rx call */
4345                 brcmf_os_sdunlock(bus->dhd);
4346                 brcmf_rx_frame(bus->dhd, ifidx, pkt, 1);
4347                 brcmf_os_sdlock(bus->dhd);
4348         }
4349         rxcount = maxframes - rxleft;
4350 #ifdef DHD_DEBUG
4351         /* Message if we hit the limit */
4352         if (!rxleft && !sdtest)
4353                 DHD_DATA(("%s: hit rx limit of %d frames\n", __func__,
4354                           maxframes));
4355         else
4356 #endif                          /* DHD_DEBUG */
4357                 DHD_DATA(("%s: processed %d frames\n", __func__, rxcount));
4358         /* Back off rxseq if awaiting rtx, update rx_seq */
4359         if (bus->rxskip)
4360                 rxseq--;
4361         bus->rx_seq = rxseq;
4362
4363         return rxcount;
4364 }
4365
4366 static u32 brcmf_sdbrcm_hostmail(dhd_bus_t *bus)
4367 {
4368         struct sdpcmd_regs *regs = bus->regs;
4369         u32 intstatus = 0;
4370         u32 hmb_data;
4371         u8 fcbits;
4372         uint retries = 0;
4373
4374         DHD_TRACE(("%s: Enter\n", __func__));
4375
4376         /* Read mailbox data and ack that we did so */
4377         R_SDREG(hmb_data, &regs->tohostmailboxdata, retries);
4378         if (retries <= retry_limit)
4379                 W_SDREG(SMB_INT_ACK, &regs->tosbmailbox, retries);
4380         bus->f1regdata += 2;
4381
4382         /* Dongle recomposed rx frames, accept them again */
4383         if (hmb_data & HMB_DATA_NAKHANDLED) {
4384                 DHD_INFO(("Dongle reports NAK handled, expect rtx of %d\n",
4385                           bus->rx_seq));
4386                 if (!bus->rxskip)
4387                         DHD_ERROR(("%s: unexpected NAKHANDLED!\n", __func__));
4388
4389                 bus->rxskip = false;
4390                 intstatus |= I_HMB_FRAME_IND;
4391         }
4392
4393         /*
4394          * DEVREADY does not occur with gSPI.
4395          */
4396         if (hmb_data & (HMB_DATA_DEVREADY | HMB_DATA_FWREADY)) {
4397                 bus->sdpcm_ver =
4398                     (hmb_data & HMB_DATA_VERSION_MASK) >>
4399                     HMB_DATA_VERSION_SHIFT;
4400                 if (bus->sdpcm_ver != SDPCM_PROT_VERSION)
4401                         DHD_ERROR(("Version mismatch, dongle reports %d, "
4402                                 "expecting %d\n",
4403                                 bus->sdpcm_ver, SDPCM_PROT_VERSION));
4404                 else
4405                         DHD_INFO(("Dongle ready, protocol version %d\n",
4406                                   bus->sdpcm_ver));
4407         }
4408
4409         /*
4410          * Flow Control has been moved into the RX headers and this out of band
4411          * method isn't used any more.
4412          * remaining backward compatible with older dongles.
4413          */
4414         if (hmb_data & HMB_DATA_FC) {
4415                 fcbits = (hmb_data & HMB_DATA_FCDATA_MASK) >>
4416                                                         HMB_DATA_FCDATA_SHIFT;
4417
4418                 if (fcbits & ~bus->flowcontrol)
4419                         bus->fc_xoff++;
4420
4421                 if (bus->flowcontrol & ~fcbits)
4422                         bus->fc_xon++;
4423
4424                 bus->fc_rcvd++;
4425                 bus->flowcontrol = fcbits;
4426         }
4427
4428         /* Shouldn't be any others */
4429         if (hmb_data & ~(HMB_DATA_DEVREADY |
4430                          HMB_DATA_NAKHANDLED |
4431                          HMB_DATA_FC |
4432                          HMB_DATA_FWREADY |
4433                          HMB_DATA_FCDATA_MASK | HMB_DATA_VERSION_MASK)) {
4434                 DHD_ERROR(("Unknown mailbox data content: 0x%02x\n", hmb_data));
4435         }
4436
4437         return intstatus;
4438 }
4439
4440 bool brcmf_sdbrcm_dpc(dhd_bus_t *bus)
4441 {
4442         struct brcmf_sdio *sdh = bus->sdh;
4443         struct sdpcmd_regs *regs = bus->regs;
4444         u32 intstatus, newstatus = 0;
4445         uint retries = 0;
4446         uint rxlimit = brcmf_rxbound;   /* Rx frames to read before resched */
4447         uint txlimit = brcmf_txbound;   /* Tx frames to send before resched */
4448         uint framecnt = 0;      /* Temporary counter of tx/rx frames */
4449         bool rxdone = true;     /* Flag for no more read data */
4450         bool resched = false;   /* Flag indicating resched wanted */
4451
4452         DHD_TRACE(("%s: Enter\n", __func__));
4453
4454         /* Start with leftover status bits */
4455         intstatus = bus->intstatus;
4456
4457         brcmf_os_sdlock(bus->dhd);
4458
4459         /* If waiting for HTAVAIL, check status */
4460         if (bus->clkstate == CLK_PENDING) {
4461                 int err;
4462                 u8 clkctl, devctl = 0;
4463
4464 #ifdef DHD_DEBUG
4465                 /* Check for inconsistent device control */
4466                 devctl = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
4467                                                SBSDIO_DEVICE_CTL, &err);
4468                 if (err) {
4469                         DHD_ERROR(("%s: error reading DEVCTL: %d\n",
4470                                    __func__, err));
4471                         bus->dhd->busstate = DHD_BUS_DOWN;
4472                 } else {
4473                         ASSERT(devctl & SBSDIO_DEVCTL_CA_INT_ONLY);
4474                 }
4475 #endif                          /* DHD_DEBUG */
4476
4477                 /* Read CSR, if clock on switch to AVAIL, else ignore */
4478                 clkctl = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
4479                                                SBSDIO_FUNC1_CHIPCLKCSR, &err);
4480                 if (err) {
4481                         DHD_ERROR(("%s: error reading CSR: %d\n", __func__,
4482                                    err));
4483                         bus->dhd->busstate = DHD_BUS_DOWN;
4484                 }
4485
4486                 DHD_INFO(("DPC: PENDING, devctl 0x%02x clkctl 0x%02x\n", devctl,
4487                           clkctl));
4488
4489                 if (SBSDIO_HTAV(clkctl)) {
4490                         devctl = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
4491                                                        SBSDIO_DEVICE_CTL, &err);
4492                         if (err) {
4493                                 DHD_ERROR(("%s: error reading DEVCTL: %d\n",
4494                                            __func__, err));
4495                                 bus->dhd->busstate = DHD_BUS_DOWN;
4496                         }
4497                         devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
4498                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
4499                                 SBSDIO_DEVICE_CTL, devctl, &err);
4500                         if (err) {
4501                                 DHD_ERROR(("%s: error writing DEVCTL: %d\n",
4502                                            __func__, err));
4503                                 bus->dhd->busstate = DHD_BUS_DOWN;
4504                         }
4505                         bus->clkstate = CLK_AVAIL;
4506                 } else {
4507                         goto clkwait;
4508                 }
4509         }
4510
4511         BUS_WAKE(bus);
4512
4513         /* Make sure backplane clock is on */
4514         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, true);
4515         if (bus->clkstate == CLK_PENDING)
4516                 goto clkwait;
4517
4518         /* Pending interrupt indicates new device status */
4519         if (bus->ipend) {
4520                 bus->ipend = false;
4521                 R_SDREG(newstatus, &regs->intstatus, retries);
4522                 bus->f1regdata++;
4523                 if (brcmf_sdcard_regfail(bus->sdh))
4524                         newstatus = 0;
4525                 newstatus &= bus->hostintmask;
4526                 bus->fcstate = !!(newstatus & I_HMB_FC_STATE);
4527                 if (newstatus) {
4528                         W_SDREG(newstatus, &regs->intstatus, retries);
4529                         bus->f1regdata++;
4530                 }
4531         }
4532
4533         /* Merge new bits with previous */
4534         intstatus |= newstatus;
4535         bus->intstatus = 0;
4536
4537         /* Handle flow-control change: read new state in case our ack
4538          * crossed another change interrupt.  If change still set, assume
4539          * FC ON for safety, let next loop through do the debounce.
4540          */
4541         if (intstatus & I_HMB_FC_CHANGE) {
4542                 intstatus &= ~I_HMB_FC_CHANGE;
4543                 W_SDREG(I_HMB_FC_CHANGE, &regs->intstatus, retries);
4544                 R_SDREG(newstatus, &regs->intstatus, retries);
4545                 bus->f1regdata += 2;
4546                 bus->fcstate =
4547                     !!(newstatus & (I_HMB_FC_STATE | I_HMB_FC_CHANGE));
4548                 intstatus |= (newstatus & bus->hostintmask);
4549         }
4550
4551         /* Handle host mailbox indication */
4552         if (intstatus & I_HMB_HOST_INT) {
4553                 intstatus &= ~I_HMB_HOST_INT;
4554                 intstatus |= brcmf_sdbrcm_hostmail(bus);
4555         }
4556
4557         /* Generally don't ask for these, can get CRC errors... */
4558         if (intstatus & I_WR_OOSYNC) {
4559                 DHD_ERROR(("Dongle reports WR_OOSYNC\n"));
4560                 intstatus &= ~I_WR_OOSYNC;
4561         }
4562
4563         if (intstatus & I_RD_OOSYNC) {
4564                 DHD_ERROR(("Dongle reports RD_OOSYNC\n"));
4565                 intstatus &= ~I_RD_OOSYNC;
4566         }
4567
4568         if (intstatus & I_SBINT) {
4569                 DHD_ERROR(("Dongle reports SBINT\n"));
4570                 intstatus &= ~I_SBINT;
4571         }
4572
4573         /* Would be active due to wake-wlan in gSPI */
4574         if (intstatus & I_CHIPACTIVE) {
4575                 DHD_INFO(("Dongle reports CHIPACTIVE\n"));
4576                 intstatus &= ~I_CHIPACTIVE;
4577         }
4578
4579         /* Ignore frame indications if rxskip is set */
4580         if (bus->rxskip)
4581                 intstatus &= ~I_HMB_FRAME_IND;
4582
4583         /* On frame indication, read available frames */
4584         if (PKT_AVAILABLE()) {
4585                 framecnt = brcmf_sdbrcm_readframes(bus, rxlimit, &rxdone);
4586                 if (rxdone || bus->rxskip)
4587                         intstatus &= ~I_HMB_FRAME_IND;
4588                 rxlimit -= min(framecnt, rxlimit);
4589         }
4590
4591         /* Keep still-pending events for next scheduling */
4592         bus->intstatus = intstatus;
4593
4594 clkwait:
4595 #if defined(OOB_INTR_ONLY)
4596         brcmf_sdio_oob_intr_set(1);
4597 #endif                          /* (OOB_INTR_ONLY) */
4598         /* Re-enable interrupts to detect new device events (mailbox, rx frame)
4599          * or clock availability.  (Allows tx loop to check ipend if desired.)
4600          * (Unless register access seems hosed, as we may not be able to ACK...)
4601          */
4602         if (bus->intr && bus->intdis && !brcmf_sdcard_regfail(sdh)) {
4603                 DHD_INTR(("%s: enable SDIO interrupts, rxdone %d framecnt %d\n",
4604                           __func__, rxdone, framecnt));
4605                 bus->intdis = false;
4606                 brcmf_sdcard_intr_enable(sdh);
4607         }
4608
4609         if (DATAOK(bus) && bus->ctrl_frame_stat &&
4610                 (bus->clkstate == CLK_AVAIL)) {
4611                 int ret, i;
4612
4613                 ret = brcmf_sdbrcm_send_buf(bus, brcmf_sdcard_cur_sbwad(sdh),
4614                         SDIO_FUNC_2, F2SYNC, (u8 *) bus->ctrl_frame_buf,
4615                         (u32) bus->ctrl_frame_len, NULL, NULL, NULL);
4616                 ASSERT(ret != -BCME_PENDING);
4617
4618                 if (ret < 0) {
4619                         /* On failure, abort the command and
4620                                 terminate the frame */
4621                         DHD_INFO(("%s: sdio error %d, abort command and "
4622                                 "terminate frame.\n", __func__, ret));
4623                         bus->tx_sderrs++;
4624
4625                         brcmf_sdcard_abort(sdh, SDIO_FUNC_2);
4626
4627                         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1,
4628                                          SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM,
4629                                          NULL);
4630                         bus->f1regdata++;
4631
4632                         for (i = 0; i < 3; i++) {
4633                                 u8 hi, lo;
4634                                 hi = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
4635                                                      SBSDIO_FUNC1_WFRAMEBCHI,
4636                                                      NULL);
4637                                 lo = brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
4638                                                      SBSDIO_FUNC1_WFRAMEBCLO,
4639                                                      NULL);
4640                                 bus->f1regdata += 2;
4641                                 if ((hi == 0) && (lo == 0))
4642                                         break;
4643                         }
4644
4645                 }
4646                 if (ret == 0)
4647                         bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP;
4648
4649                 DHD_INFO(("Return_dpc value is : %d\n", ret));
4650                 bus->ctrl_frame_stat = false;
4651                 brcmf_wait_event_wakeup(bus->dhd);
4652         }
4653         /* Send queued frames (limit 1 if rx may still be pending) */
4654         else if ((bus->clkstate == CLK_AVAIL) && !bus->fcstate &&
4655                  brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol) && txlimit
4656                  && DATAOK(bus)) {
4657                 framecnt = rxdone ? txlimit : min(txlimit, dhd_txminmax);
4658                 framecnt = brcmf_sdbrcm_sendfromq(bus, framecnt);
4659                 txlimit -= framecnt;
4660         }
4661
4662         /* Resched if events or tx frames are pending,
4663                  else await next interrupt */
4664         /* On failed register access, all bets are off:
4665                  no resched or interrupts */
4666         if ((bus->dhd->busstate == DHD_BUS_DOWN) || brcmf_sdcard_regfail(sdh)) {
4667                 DHD_ERROR(("%s: failed backplane access over SDIO, halting "
4668                         "operation %d\n", __func__, brcmf_sdcard_regfail(sdh)));
4669                 bus->dhd->busstate = DHD_BUS_DOWN;
4670                 bus->intstatus = 0;
4671         } else if (bus->clkstate == CLK_PENDING) {
4672                 DHD_INFO(("%s: rescheduled due to CLK_PENDING awaiting "
4673                         "I_CHIPACTIVE interrupt\n", __func__));
4674                 resched = true;
4675         } else if (bus->intstatus || bus->ipend ||
4676                 (!bus->fcstate && brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol)
4677                  && DATAOK(bus)) || PKT_AVAILABLE()) {
4678                 resched = true;
4679         }
4680
4681         bus->dpc_sched = resched;
4682
4683         /* If we're done for now, turn off clock request. */
4684         if ((bus->clkstate != CLK_PENDING)
4685             && bus->idletime == DHD_IDLE_IMMEDIATE) {
4686                 bus->activity = false;
4687                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
4688         }
4689
4690         brcmf_os_sdunlock(bus->dhd);
4691
4692         return resched;
4693 }
4694
4695 bool dhd_bus_dpc(struct dhd_bus *bus)
4696 {
4697         bool resched;
4698
4699         /* Call the DPC directly. */
4700         DHD_TRACE(("Calling brcmf_sdbrcm_dpc() from %s\n", __func__));
4701         resched = brcmf_sdbrcm_dpc(bus);
4702
4703         return resched;
4704 }
4705
4706 void brcmf_sdbrcm_isr(void *arg)
4707 {
4708         dhd_bus_t *bus = (dhd_bus_t *) arg;
4709         struct brcmf_sdio *sdh;
4710
4711         DHD_TRACE(("%s: Enter\n", __func__));
4712
4713         if (!bus) {
4714                 DHD_ERROR(("%s : bus is null pointer , exit\n", __func__));
4715                 return;
4716         }
4717         sdh = bus->sdh;
4718
4719         if (bus->dhd->busstate == DHD_BUS_DOWN) {
4720                 DHD_ERROR(("%s : bus is down. we have nothing to do\n",
4721                            __func__));
4722                 return;
4723         }
4724         /* Count the interrupt call */
4725         bus->intrcount++;
4726         bus->ipend = true;
4727
4728         /* Shouldn't get this interrupt if we're sleeping? */
4729         if (bus->sleeping) {
4730                 DHD_ERROR(("INTERRUPT WHILE SLEEPING??\n"));
4731                 return;
4732         }
4733
4734         /* Disable additional interrupts (is this needed now)? */
4735         if (bus->intr)
4736                 DHD_INTR(("%s: disable SDIO interrupts\n", __func__));
4737         else
4738                 DHD_ERROR(("brcmf_sdbrcm_isr() w/o interrupt configured!\n"));
4739
4740         brcmf_sdcard_intr_disable(sdh);
4741         bus->intdis = true;
4742
4743 #if defined(SDIO_ISR_THREAD)
4744         DHD_TRACE(("Calling brcmf_sdbrcm_dpc() from %s\n", __func__));
4745         while (brcmf_sdbrcm_dpc(bus))
4746                 ;
4747 #else
4748         bus->dpc_sched = true;
4749         brcmf_sched_dpc(bus->dhd);
4750 #endif
4751
4752 }
4753
4754 #ifdef SDTEST
4755 static void brcmf_sdbrcm_pktgen_init(dhd_bus_t *bus)
4756 {
4757         /* Default to specified length, or full range */
4758         if (brcmf_pktgen_len) {
4759                 bus->pktgen_maxlen = min(brcmf_pktgen_len,
4760                                          BRCMF_MAX_PKTGEN_LEN);
4761                 bus->pktgen_minlen = bus->pktgen_maxlen;
4762         } else {
4763                 bus->pktgen_maxlen = BRCMF_MAX_PKTGEN_LEN;
4764                 bus->pktgen_minlen = 0;
4765         }
4766         bus->pktgen_len = (u16) bus->pktgen_minlen;
4767
4768         /* Default to per-watchdog burst with 10s print time */
4769         bus->pktgen_freq = 1;
4770         bus->pktgen_print = 10000 / brcmf_watchdog_ms;
4771         bus->pktgen_count = (brcmf_pktgen * brcmf_watchdog_ms + 999) / 1000;
4772
4773         /* Default to echo mode */
4774         bus->pktgen_mode = DHD_PKTGEN_ECHO;
4775         bus->pktgen_stop = 1;
4776 }
4777
4778 static void brcmf_sdbrcm_pktgen(dhd_bus_t *bus)
4779 {
4780         struct sk_buff *pkt;
4781         u8 *data;
4782         uint pktcount;
4783         uint fillbyte;
4784         u16 len;
4785
4786         /* Display current count if appropriate */
4787         if (bus->pktgen_print && (++bus->pktgen_ptick >= bus->pktgen_print)) {
4788                 bus->pktgen_ptick = 0;
4789                 printk(KERN_DEBUG "%s: send attempts %d rcvd %d\n",
4790                        __func__, bus->pktgen_sent, bus->pktgen_rcvd);
4791         }
4792
4793         /* For recv mode, just make sure dongle has started sending */
4794         if (bus->pktgen_mode == DHD_PKTGEN_RECV) {
4795                 if (!bus->pktgen_rcvd)
4796                         brcmf_sdbrcm_sdtest_set(bus, true);
4797                 return;
4798         }
4799
4800         /* Otherwise, generate or request the specified number of packets */
4801         for (pktcount = 0; pktcount < bus->pktgen_count; pktcount++) {
4802                 /* Stop if total has been reached */
4803                 if (bus->pktgen_total
4804                     && (bus->pktgen_sent >= bus->pktgen_total)) {
4805                         bus->pktgen_count = 0;
4806                         break;
4807                 }
4808
4809                 /* Allocate an appropriate-sized packet */
4810                 len = bus->pktgen_len;
4811                 pkt = brcmu_pkt_buf_get_skb(
4812                         (len + SDPCM_HDRLEN + SDPCM_TEST_HDRLEN + DHD_SDALIGN),
4813                         true);
4814                 if (!pkt) {
4815                         DHD_ERROR(("%s: brcmu_pkt_buf_get_skb failed!\n",
4816                                    __func__));
4817                         break;
4818                 }
4819                 PKTALIGN(pkt, (len + SDPCM_HDRLEN + SDPCM_TEST_HDRLEN),
4820                          DHD_SDALIGN);
4821                 data = (u8 *) (pkt->data) + SDPCM_HDRLEN;
4822
4823                 /* Write test header cmd and extra based on mode */
4824                 switch (bus->pktgen_mode) {
4825                 case DHD_PKTGEN_ECHO:
4826                         *data++ = SDPCM_TEST_ECHOREQ;
4827                         *data++ = (u8) bus->pktgen_sent;
4828                         break;
4829
4830                 case DHD_PKTGEN_SEND:
4831                         *data++ = SDPCM_TEST_DISCARD;
4832                         *data++ = (u8) bus->pktgen_sent;
4833                         break;
4834
4835                 case DHD_PKTGEN_RXBURST:
4836                         *data++ = SDPCM_TEST_BURST;
4837                         *data++ = (u8) bus->pktgen_count;
4838                         break;
4839
4840                 default:
4841                         DHD_ERROR(("Unrecognized pktgen mode %d\n",
4842                                    bus->pktgen_mode));
4843                         brcmu_pkt_buf_free_skb(pkt, true);
4844                         bus->pktgen_count = 0;
4845                         return;
4846                 }
4847
4848                 /* Write test header length field */
4849                 *data++ = (len >> 0);
4850                 *data++ = (len >> 8);
4851
4852                 /* Then fill in the remainder -- N/A for burst,
4853                          but who cares... */
4854                 for (fillbyte = 0; fillbyte < len; fillbyte++)
4855                         *data++ =
4856                             SDPCM_TEST_FILL(fillbyte, (u8) bus->pktgen_sent);
4857
4858 #ifdef DHD_DEBUG
4859                 if (DHD_BYTES_ON() && DHD_DATA_ON()) {
4860                         data = (u8 *) (pkt->data) + SDPCM_HDRLEN;
4861                         printk(KERN_DEBUG "brcmf_sdbrcm_pktgen: Tx Data:\n");
4862                         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, data,
4863                                              pkt->len - SDPCM_HDRLEN);
4864                 }
4865 #endif
4866
4867                 /* Send it */
4868                 if (brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_TEST_CHANNEL, true)) {
4869                         bus->pktgen_fail++;
4870                         if (bus->pktgen_stop
4871                             && bus->pktgen_stop == bus->pktgen_fail)
4872                                 bus->pktgen_count = 0;
4873                 }
4874                 bus->pktgen_sent++;
4875
4876                 /* Bump length if not fixed, wrap at max */
4877                 if (++bus->pktgen_len > bus->pktgen_maxlen)
4878                         bus->pktgen_len = (u16) bus->pktgen_minlen;
4879
4880                 /* Special case for burst mode: just send one request! */
4881                 if (bus->pktgen_mode == DHD_PKTGEN_RXBURST)
4882                         break;
4883         }
4884 }
4885
4886 static void brcmf_sdbrcm_sdtest_set(dhd_bus_t *bus, bool start)
4887 {
4888         struct sk_buff *pkt;
4889         u8 *data;
4890
4891         /* Allocate the packet */
4892         pkt = brcmu_pkt_buf_get_skb(SDPCM_HDRLEN + SDPCM_TEST_HDRLEN +
4893                 DHD_SDALIGN, true);
4894         if (!pkt) {
4895                 DHD_ERROR(("%s: brcmu_pkt_buf_get_skb failed!\n", __func__));
4896                 return;
4897         }
4898         PKTALIGN(pkt, (SDPCM_HDRLEN + SDPCM_TEST_HDRLEN), DHD_SDALIGN);
4899         data = (u8 *) (pkt->data) + SDPCM_HDRLEN;
4900
4901         /* Fill in the test header */
4902         *data++ = SDPCM_TEST_SEND;
4903         *data++ = start;
4904         *data++ = (bus->pktgen_maxlen >> 0);
4905         *data++ = (bus->pktgen_maxlen >> 8);
4906
4907         /* Send it */
4908         if (brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_TEST_CHANNEL, true))
4909                 bus->pktgen_fail++;
4910 }
4911
4912 static void
4913 brcmf_sdbrcm_checkdied(dhd_bus_t *bus, struct sk_buff *pkt, uint seq)
4914 {
4915         u8 *data;
4916         uint pktlen;
4917
4918         u8 cmd;
4919         u8 extra;
4920         u16 len;
4921         u16 offset;
4922
4923         /* Check for min length */
4924         pktlen = pkt->len;
4925         if (pktlen < SDPCM_TEST_HDRLEN) {
4926                 DHD_ERROR(("brcmf_sdbrcm_checkdied: toss runt frame, pktlen "
4927                            "%d\n", pktlen));
4928                 brcmu_pkt_buf_free_skb(pkt, false);
4929                 return;
4930         }
4931
4932         /* Extract header fields */
4933         data = pkt->data;
4934         cmd = *data++;
4935         extra = *data++;
4936         len = *data++;
4937         len += *data++ << 8;
4938
4939         /* Check length for relevant commands */
4940         if (cmd == SDPCM_TEST_DISCARD || cmd == SDPCM_TEST_ECHOREQ
4941             || cmd == SDPCM_TEST_ECHORSP) {
4942                 if (pktlen != len + SDPCM_TEST_HDRLEN) {
4943                         DHD_ERROR(("brcmf_sdbrcm_checkdied: frame length "
4944                                 "mismatch, pktlen %d seq %d" " cmd %d extra %d "
4945                                 "len %d\n",
4946                                 pktlen, seq, cmd, extra, len));
4947                         brcmu_pkt_buf_free_skb(pkt, false);
4948                         return;
4949                 }
4950         }
4951
4952         /* Process as per command */
4953         switch (cmd) {
4954         case SDPCM_TEST_ECHOREQ:
4955                 /* Rx->Tx turnaround ok (even on NDIS w/current
4956                          implementation) */
4957                 *(u8 *) (pkt->data) = SDPCM_TEST_ECHORSP;
4958                 if (brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_TEST_CHANNEL, true) == 0)
4959                         bus->pktgen_sent++;
4960                 else {
4961                         bus->pktgen_fail++;
4962                         brcmu_pkt_buf_free_skb(pkt, false);
4963                 }
4964                 bus->pktgen_rcvd++;
4965                 break;
4966
4967         case SDPCM_TEST_ECHORSP:
4968                 if (bus->ext_loop) {
4969                         brcmu_pkt_buf_free_skb(pkt, false);
4970                         bus->pktgen_rcvd++;
4971                         break;
4972                 }
4973
4974                 for (offset = 0; offset < len; offset++, data++) {
4975                         if (*data != SDPCM_TEST_FILL(offset, extra)) {
4976                                 DHD_ERROR(("brcmf_sdbrcm_checkdied: echo data "
4977                                            "mismatch: " "offset %d (len %d) "
4978                                            "expect 0x%02x rcvd 0x%02x\n",
4979                                            offset, len,
4980                                            SDPCM_TEST_FILL(offset, extra),
4981                                            *data));
4982                                 break;
4983                         }
4984                 }
4985                 brcmu_pkt_buf_free_skb(pkt, false);
4986                 bus->pktgen_rcvd++;
4987                 break;
4988
4989         case SDPCM_TEST_DISCARD:
4990                 brcmu_pkt_buf_free_skb(pkt, false);
4991                 bus->pktgen_rcvd++;
4992                 break;
4993
4994         case SDPCM_TEST_BURST:
4995         case SDPCM_TEST_SEND:
4996         default:
4997                 DHD_INFO(("brcmf_sdbrcm_checkdied: unsupported or unknown "
4998                         "command, pktlen %d seq %d" " cmd %d extra %d len %d\n",
4999                         pktlen, seq, cmd, extra, len));
5000                 brcmu_pkt_buf_free_skb(pkt, false);
5001                 break;
5002         }
5003
5004         /* For recv mode, stop at limie (and tell dongle to stop sending) */
5005         if (bus->pktgen_mode == DHD_PKTGEN_RECV) {
5006                 if (bus->pktgen_total
5007                     && (bus->pktgen_rcvd >= bus->pktgen_total)) {
5008                         bus->pktgen_count = 0;
5009                         brcmf_sdbrcm_sdtest_set(bus, false);
5010                 }
5011         }
5012 }
5013 #endif                          /* SDTEST */
5014
5015 extern bool brcmf_sdbrcm_bus_watchdog(dhd_pub_t *dhdp)
5016 {
5017         dhd_bus_t *bus;
5018
5019         DHD_TIMER(("%s: Enter\n", __func__));
5020
5021         bus = dhdp->bus;
5022
5023         if (bus->dhd->dongle_reset)
5024                 return false;
5025
5026         /* Ignore the timer if simulating bus down */
5027         if (bus->sleeping)
5028                 return false;
5029
5030         brcmf_os_sdlock(bus->dhd);
5031
5032         /* Poll period: check device if appropriate. */
5033         if (bus->poll && (++bus->polltick >= bus->pollrate)) {
5034                 u32 intstatus = 0;
5035
5036                 /* Reset poll tick */
5037                 bus->polltick = 0;
5038
5039                 /* Check device if no interrupts */
5040                 if (!bus->intr || (bus->intrcount == bus->lastintrs)) {
5041
5042                         if (!bus->dpc_sched) {
5043                                 u8 devpend;
5044                                 devpend = brcmf_sdcard_cfg_read(bus->sdh,
5045                                                 SDIO_FUNC_0, SDIO_CCCR_INTx,
5046                                                 NULL);
5047                                 intstatus =
5048                                     devpend & (INTR_STATUS_FUNC1 |
5049                                                INTR_STATUS_FUNC2);
5050                         }
5051
5052                         /* If there is something, make like the ISR and
5053                                  schedule the DPC */
5054                         if (intstatus) {
5055                                 bus->pollcnt++;
5056                                 bus->ipend = true;
5057                                 if (bus->intr)
5058                                         brcmf_sdcard_intr_disable(bus->sdh);
5059
5060                                 bus->dpc_sched = true;
5061                                 brcmf_sched_dpc(bus->dhd);
5062
5063                         }
5064                 }
5065
5066                 /* Update interrupt tracking */
5067                 bus->lastintrs = bus->intrcount;
5068         }
5069 #ifdef DHD_DEBUG
5070         /* Poll for console output periodically */
5071         if (dhdp->busstate == DHD_BUS_DATA && brcmf_console_ms != 0) {
5072                 bus->console.count += brcmf_watchdog_ms;
5073                 if (bus->console.count >= brcmf_console_ms) {
5074                         bus->console.count -= brcmf_console_ms;
5075                         /* Make sure backplane clock is on */
5076                         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
5077                         if (brcmf_sdbrcm_readconsole(bus) < 0)
5078                                 brcmf_console_ms = 0;   /* On error,
5079                                                          stop trying */
5080                 }
5081         }
5082 #endif                          /* DHD_DEBUG */
5083
5084 #ifdef SDTEST
5085         /* Generate packets if configured */
5086         if (bus->pktgen_count && (++bus->pktgen_tick >= bus->pktgen_freq)) {
5087                 /* Make sure backplane clock is on */
5088                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
5089                 bus->pktgen_tick = 0;
5090                 brcmf_sdbrcm_pktgen(bus);
5091         }
5092 #endif
5093
5094         /* On idle timeout clear activity flag and/or turn off clock */
5095         if ((bus->idletime > 0) && (bus->clkstate == CLK_AVAIL)) {
5096                 if (++bus->idlecount >= bus->idletime) {
5097                         bus->idlecount = 0;
5098                         if (bus->activity) {
5099                                 bus->activity = false;
5100                                 brcmf_os_wd_timer(bus->dhd, brcmf_watchdog_ms);
5101                         } else {
5102                                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
5103                         }
5104                 }
5105         }
5106
5107         brcmf_os_sdunlock(bus->dhd);
5108
5109         return bus->ipend;
5110 }
5111
5112 #ifdef DHD_DEBUG
5113 extern int brcmf_sdbrcm_bus_console_in(dhd_pub_t *dhdp, unsigned char *msg,
5114                                        uint msglen)
5115 {
5116         dhd_bus_t *bus = dhdp->bus;
5117         u32 addr, val;
5118         int rv;
5119         struct sk_buff *pkt;
5120
5121         /* Address could be zero if CONSOLE := 0 in dongle Makefile */
5122         if (bus->console_addr == 0)
5123                 return -ENOTSUPP;
5124
5125         /* Exclusive bus access */
5126         brcmf_os_sdlock(bus->dhd);
5127
5128         /* Don't allow input if dongle is in reset */
5129         if (bus->dhd->dongle_reset) {
5130                 brcmf_os_sdunlock(bus->dhd);
5131                 return -EPERM;
5132         }
5133
5134         /* Request clock to allow SDIO accesses */
5135         BUS_WAKE(bus);
5136         /* No pend allowed since txpkt is called later, ht clk has to be on */
5137         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
5138
5139         /* Zero cbuf_index */
5140         addr = bus->console_addr + offsetof(rte_cons_t, cbuf_idx);
5141         val = cpu_to_le32(0);
5142         rv = brcmf_sdbrcm_membytes(bus, true, addr, (u8 *)&val, sizeof(val));
5143         if (rv < 0)
5144                 goto done;
5145
5146         /* Write message into cbuf */
5147         addr = bus->console_addr + offsetof(rte_cons_t, cbuf);
5148         rv = brcmf_sdbrcm_membytes(bus, true, addr, (u8 *)msg, msglen);
5149         if (rv < 0)
5150                 goto done;
5151
5152         /* Write length into vcons_in */
5153         addr = bus->console_addr + offsetof(rte_cons_t, vcons_in);
5154         val = cpu_to_le32(msglen);
5155         rv = brcmf_sdbrcm_membytes(bus, true, addr, (u8 *)&val, sizeof(val));
5156         if (rv < 0)
5157                 goto done;
5158
5159         /* Bump dongle by sending an empty event pkt.
5160          * sdpcm_sendup (RX) checks for virtual console input.
5161          */
5162         pkt = brcmu_pkt_buf_get_skb(4 + SDPCM_RESERVE);
5163         if ((pkt != NULL) && bus->clkstate == CLK_AVAIL)
5164                 brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_EVENT_CHANNEL, true);
5165
5166 done:
5167         if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) {
5168                 bus->activity = false;
5169                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, true);
5170         }
5171
5172         brcmf_os_sdunlock(bus->dhd);
5173
5174         return rv;
5175 }
5176 #endif                          /* DHD_DEBUG */
5177
5178 static bool brcmf_sdbrcm_chipmatch(u16 chipid)
5179 {
5180         if (chipid == BCM4325_CHIP_ID)
5181                 return true;
5182         if (chipid == BCM4329_CHIP_ID)
5183                 return true;
5184         if (chipid == BCM4319_CHIP_ID)
5185                 return true;
5186         return false;
5187 }
5188
5189 static void *brcmf_sdbrcm_probe(u16 venid, u16 devid, u16 bus_no,
5190                            u16 slot, u16 func, uint bustype, void *regsva,
5191                            void *sdh)
5192 {
5193         int ret;
5194         dhd_bus_t *bus;
5195
5196         /* Init global variables at run-time, not as part of the declaration.
5197          * This is required to support init/de-init of the driver.
5198          * Initialization
5199          * of globals as part of the declaration results in non-deterministic
5200          * behavior since the value of the globals may be different on the
5201          * first time that the driver is initialized vs subsequent
5202          * initializations.
5203          */
5204         brcmf_txbound = DHD_TXBOUND;
5205         brcmf_rxbound = DHD_RXBOUND;
5206         dhd_alignctl = true;
5207         sd1idle = true;
5208         dhd_readahead = true;
5209         retrydata = false;
5210         brcmf_dongle_memsize = 0;
5211         dhd_txminmax = DHD_TXMINMAX;
5212
5213         forcealign = true;
5214
5215         brcmf_c_init();
5216
5217         DHD_TRACE(("%s: Enter\n", __func__));
5218         DHD_INFO(("%s: venid 0x%04x devid 0x%04x\n", __func__, venid, devid));
5219
5220         /* We make assumptions about address window mappings */
5221         ASSERT((unsigned long)regsva == SI_ENUM_BASE);
5222
5223         /* BCMSDH passes venid and devid based on CIS parsing -- but
5224          * low-power start
5225          * means early parse could fail, so here we should get either an ID
5226          * we recognize OR (-1) indicating we must request power first.
5227          */
5228         /* Check the Vendor ID */
5229         switch (venid) {
5230         case 0x0000:
5231         case PCI_VENDOR_ID_BROADCOM:
5232                 break;
5233         default:
5234                 DHD_ERROR(("%s: unknown vendor: 0x%04x\n", __func__, venid));
5235                 return NULL;
5236         }
5237
5238         /* Check the Device ID and make sure it's one that we support */
5239         switch (devid) {
5240         case BCM4325_D11DUAL_ID:        /* 4325 802.11a/g id */
5241         case BCM4325_D11G_ID:   /* 4325 802.11g 2.4Ghz band id */
5242         case BCM4325_D11A_ID:   /* 4325 802.11a 5Ghz band id */
5243                 DHD_INFO(("%s: found 4325 Dongle\n", __func__));
5244                 break;
5245         case BCM4329_D11NDUAL_ID:       /* 4329 802.11n dualband device */
5246         case BCM4329_D11N2G_ID: /* 4329 802.11n 2.4G device */
5247         case BCM4329_D11N5G_ID: /* 4329 802.11n 5G device */
5248         case 0x4329:
5249                 DHD_INFO(("%s: found 4329 Dongle\n", __func__));
5250                 break;
5251         case BCM4319_D11N_ID:   /* 4319 802.11n id */
5252         case BCM4319_D11N2G_ID: /* 4319 802.11n2g id */
5253         case BCM4319_D11N5G_ID: /* 4319 802.11n5g id */
5254                 DHD_INFO(("%s: found 4319 Dongle\n", __func__));
5255                 break;
5256         case 0:
5257                 DHD_INFO(("%s: allow device id 0, will check chip internals\n",
5258                           __func__));
5259                 break;
5260
5261         default:
5262                 DHD_ERROR(("%s: skipping 0x%04x/0x%04x, not a dongle\n",
5263                            __func__, venid, devid));
5264                 return NULL;
5265         }
5266
5267         /* Allocate private bus interface state */
5268         bus = kzalloc(sizeof(dhd_bus_t), GFP_ATOMIC);
5269         if (!bus) {
5270                 DHD_ERROR(("%s: kmalloc of dhd_bus_t failed\n", __func__));
5271                 goto fail;
5272         }
5273         bus->sdh = sdh;
5274         bus->cl_devid = (u16) devid;
5275         bus->bus = DHD_BUS;
5276         bus->tx_seq = SDPCM_SEQUENCE_WRAP - 1;
5277         bus->usebufpool = false;        /* Use bufpool if allocated,
5278                                          else use locally malloced rxbuf */
5279
5280         /* attempt to attach to the dongle */
5281         if (!(brcmf_sdbrcm_probe_attach(bus, sdh, regsva, devid))) {
5282                 DHD_ERROR(("%s: brcmf_sdbrcm_probe_attach failed\n", __func__));
5283                 goto fail;
5284         }
5285
5286         spin_lock_init(&bus->txqlock);
5287
5288         /* Attach to the dhd/OS/network interface */
5289         bus->dhd = brcmf_attach(bus, SDPCM_RESERVE);
5290         if (!bus->dhd) {
5291                 DHD_ERROR(("%s: dhd_attach failed\n", __func__));
5292                 goto fail;
5293         }
5294
5295         /* Allocate buffers */
5296         if (!(brcmf_sdbrcm_probe_malloc(bus, sdh))) {
5297                 DHD_ERROR(("%s: brcmf_sdbrcm_probe_malloc failed\n", __func__));
5298                 goto fail;
5299         }
5300
5301         if (!(brcmf_sdbrcm_probe_init(bus, sdh))) {
5302                 DHD_ERROR(("%s: brcmf_sdbrcm_probe_init failed\n", __func__));
5303                 goto fail;
5304         }
5305
5306         /* Register interrupt callback, but mask it (not operational yet). */
5307         DHD_INTR(("%s: disable SDIO interrupts (not interested yet)\n",
5308                   __func__));
5309         brcmf_sdcard_intr_disable(sdh);
5310         ret = brcmf_sdcard_intr_reg(sdh, brcmf_sdbrcm_isr, bus);
5311         if (ret != 0) {
5312                 DHD_ERROR(("%s: FAILED: bcmsdh_intr_reg returned %d\n",
5313                            __func__, ret));
5314                 goto fail;
5315         }
5316         DHD_INTR(("%s: registered SDIO interrupt function ok\n", __func__));
5317
5318         DHD_INFO(("%s: completed!!\n", __func__));
5319
5320         /* if firmware path present try to download and bring up bus */
5321         ret = brcmf_bus_start(bus->dhd);
5322         if (ret != 0) {
5323                 if (ret == -ENOLINK) {
5324                         DHD_ERROR(("%s: dongle is not responding\n", __func__));
5325                         goto fail;
5326                 }
5327         }
5328         /* Ok, have the per-port tell the stack we're open for business */
5329         if (brcmf_net_attach(bus->dhd, 0) != 0) {
5330                 DHD_ERROR(("%s: Net attach failed!!\n", __func__));
5331                 goto fail;
5332         }
5333
5334         return bus;
5335
5336 fail:
5337         brcmf_sdbrcm_release(bus);
5338         return NULL;
5339 }
5340
5341 static bool
5342 brcmf_sdbrcm_probe_attach(struct dhd_bus *bus, void *sdh, void *regsva,
5343                           u16 devid)
5344 {
5345         u8 clkctl = 0;
5346         int err = 0;
5347
5348         bus->alp_only = true;
5349
5350         /* Return the window to backplane enumeration space for core access */
5351         if (brcmf_sdbrcm_set_siaddr_window(bus, SI_ENUM_BASE))
5352                 DHD_ERROR(("%s: FAILED to return to SI_ENUM_BASE\n", __func__));
5353
5354 #ifdef DHD_DEBUG
5355         printk(KERN_DEBUG "F1 signature read @0x18000000=0x%4x\n",
5356                brcmf_sdcard_reg_read(bus->sdh, SI_ENUM_BASE, 4));
5357
5358 #endif                          /* DHD_DEBUG */
5359
5360         /*
5361          * Force PLL off until brcmf_sdbrcm_chip_attach()
5362          * programs PLL control regs
5363          */
5364
5365         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
5366                          DHD_INIT_CLKCTL1, &err);
5367         if (!err)
5368                 clkctl =
5369                     brcmf_sdcard_cfg_read(sdh, SDIO_FUNC_1,
5370                                           SBSDIO_FUNC1_CHIPCLKCSR, &err);
5371
5372         if (err || ((clkctl & ~SBSDIO_AVBITS) != DHD_INIT_CLKCTL1)) {
5373                 DHD_ERROR(("brcmf_sdbrcm_probe: ChipClkCSR access: err %d wrote"
5374                         " 0x%02x read 0x%02x\n",
5375                         err, DHD_INIT_CLKCTL1, clkctl));
5376                 goto fail;
5377         }
5378
5379         if (brcmf_sdbrcm_chip_attach(bus, regsva)) {
5380                 DHD_ERROR(("%s: brcmf_sdbrcm_chip_attach failed!\n", __func__));
5381                 goto fail;
5382         }
5383
5384         brcmf_sdcard_chipinfo(sdh, bus->ci->chip, bus->ci->chiprev);
5385
5386         if (!brcmf_sdbrcm_chipmatch((u16) bus->ci->chip)) {
5387                 DHD_ERROR(("%s: unsupported chip: 0x%04x\n",
5388                            __func__, bus->ci->chip));
5389                 goto fail;
5390         }
5391
5392         brcmf_sdbrcm_sdiod_drive_strength_init(bus, brcmf_sdiod_drive_strength);
5393
5394         /* Get info on the ARM and SOCRAM cores... */
5395         if (!DHD_NOPMU(bus)) {
5396                 bus->armrev = SBCOREREV(brcmf_sdcard_reg_read(bus->sdh,
5397                         CORE_SB(bus->ci->armcorebase, sbidhigh), 4));
5398                 bus->orig_ramsize = bus->ci->ramsize;
5399                 if (!(bus->orig_ramsize)) {
5400                         DHD_ERROR(("%s: failed to find SOCRAM memory!\n",
5401                                    __func__));
5402                         goto fail;
5403                 }
5404                 bus->ramsize = bus->orig_ramsize;
5405                 if (brcmf_dongle_memsize)
5406                         brcmf_sdbrcm_setmemsize(bus, brcmf_dongle_memsize);
5407
5408                 DHD_ERROR(("DHD: dongle ram size is set to %d(orig %d)\n",
5409                            bus->ramsize, bus->orig_ramsize));
5410         }
5411
5412         bus->regs = (void *)bus->ci->buscorebase;
5413
5414         /* Set core control so an SDIO reset does a backplane reset */
5415         OR_REG(&bus->regs->corecontrol, CC_BPRESEN);
5416
5417         brcmu_pktq_init(&bus->txq, (PRIOMASK + 1), TXQLEN);
5418
5419         /* Locate an appropriately-aligned portion of hdrbuf */
5420         bus->rxhdr = (u8 *) roundup((unsigned long)&bus->hdrbuf[0], DHD_SDALIGN);
5421
5422         /* Set the poll and/or interrupt flags */
5423         bus->intr = (bool) brcmf_intr;
5424         bus->poll = (bool) brcmf_poll;
5425         if (bus->poll)
5426                 bus->pollrate = 1;
5427
5428         return true;
5429
5430 fail:
5431         return false;
5432 }
5433
5434 static bool brcmf_sdbrcm_probe_malloc(dhd_bus_t *bus, void *sdh)
5435 {
5436         DHD_TRACE(("%s: Enter\n", __func__));
5437
5438         if (bus->dhd->maxctl) {
5439                 bus->rxblen =
5440                     roundup((bus->dhd->maxctl + SDPCM_HDRLEN),
5441                             ALIGNMENT) + DHD_SDALIGN;
5442                 bus->rxbuf = kmalloc(bus->rxblen, GFP_ATOMIC);
5443                 if (!(bus->rxbuf)) {
5444                         DHD_ERROR(("%s: kmalloc of %d-byte rxbuf failed\n",
5445                                    __func__, bus->rxblen));
5446                         goto fail;
5447                 }
5448         }
5449
5450         /* Allocate buffer to receive glomed packet */
5451         bus->databuf = kmalloc(MAX_DATA_BUF, GFP_ATOMIC);
5452         if (!(bus->databuf)) {
5453                 DHD_ERROR(("%s: kmalloc of %d-byte databuf failed\n",
5454                            __func__, MAX_DATA_BUF));
5455                 /* release rxbuf which was already located as above */
5456                 if (!bus->rxblen)
5457                         kfree(bus->rxbuf);
5458                 goto fail;
5459         }
5460
5461         /* Align the buffer */
5462         if ((unsigned long)bus->databuf % DHD_SDALIGN)
5463                 bus->dataptr =
5464                     bus->databuf + (DHD_SDALIGN -
5465                                     ((unsigned long)bus->databuf % DHD_SDALIGN));
5466         else
5467                 bus->dataptr = bus->databuf;
5468
5469         return true;
5470
5471 fail:
5472         return false;
5473 }
5474
5475 static bool brcmf_sdbrcm_probe_init(dhd_bus_t *bus, void *sdh)
5476 {
5477         s32 fnum;
5478
5479         DHD_TRACE(("%s: Enter\n", __func__));
5480
5481 #ifdef SDTEST
5482         brcmf_sdbrcm_pktgen_init(bus);
5483 #endif                          /* SDTEST */
5484
5485         /* Disable F2 to clear any intermediate frame state on the dongle */
5486         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_0, SDIO_CCCR_IOEx,
5487                                SDIO_FUNC_ENABLE_1, NULL);
5488
5489         bus->dhd->busstate = DHD_BUS_DOWN;
5490         bus->sleeping = false;
5491         bus->rxflow = false;
5492         bus->prev_rxlim_hit = 0;
5493
5494         /* Done with backplane-dependent accesses, can drop clock... */
5495         brcmf_sdcard_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, 0,
5496                                NULL);
5497
5498         /* ...and initialize clock/power states */
5499         bus->clkstate = CLK_SDONLY;
5500         bus->idletime = (s32) brcmf_idletime;
5501         bus->idleclock = DHD_IDLE_ACTIVE;
5502
5503         /* Query the F2 block size, set roundup accordingly */
5504         fnum = 2;
5505         if (brcmf_sdcard_iovar_op(sdh, "sd_blocksize", &fnum, sizeof(s32),
5506                             &bus->blocksize, sizeof(s32), false) != 0) {
5507                 bus->blocksize = 0;
5508                 DHD_ERROR(("%s: fail on %s get\n", __func__, "sd_blocksize"));
5509         } else {
5510                 DHD_INFO(("%s: Initial value for %s is %d\n",
5511                           __func__, "sd_blocksize", bus->blocksize));
5512         }
5513         bus->roundup = min(max_roundup, bus->blocksize);
5514
5515         /* Query if bus module supports packet chaining,
5516                  default to use if supported */
5517         if (brcmf_sdcard_iovar_op(sdh, "sd_rxchain", NULL, 0,
5518                             &bus->sd_rxchain, sizeof(s32),
5519                             false) != 0) {
5520                 bus->sd_rxchain = false;
5521         } else {
5522                 DHD_INFO(("%s: bus module (through bcmsdh API) %s chaining\n",
5523                           __func__,
5524                           (bus->sd_rxchain ? "supports" : "does not support")));
5525         }
5526         bus->use_rxchain = (bool) bus->sd_rxchain;
5527
5528         return true;
5529 }
5530
5531 bool
5532 dhd_bus_download_firmware(struct dhd_bus *bus, char *fw_path, char *nv_path)
5533 {
5534         bool ret;
5535         bus->fw_path = fw_path;
5536         bus->nv_path = nv_path;
5537
5538         ret = brcmf_sdbrcm_download_firmware(bus, bus->sdh);
5539
5540         return ret;
5541 }
5542
5543 static bool
5544 brcmf_sdbrcm_download_firmware(struct dhd_bus *bus, void *sdh)
5545 {
5546         bool ret;
5547
5548         /* Download the firmware */
5549         brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
5550
5551         ret = _brcmf_sdbrcm_download_firmware(bus) == 0;
5552
5553         brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
5554
5555         return ret;
5556 }
5557
5558 /* Detach and free everything */
5559 static void brcmf_sdbrcm_release(dhd_bus_t *bus)
5560 {
5561         DHD_TRACE(("%s: Enter\n", __func__));
5562
5563         if (bus) {
5564                 /* De-register interrupt handler */
5565                 brcmf_sdcard_intr_disable(bus->sdh);
5566                 brcmf_sdcard_intr_dereg(bus->sdh);
5567
5568                 if (bus->dhd) {
5569                         brcmf_detach(bus->dhd);
5570                         brcmf_sdbrcm_release_dongle(bus);
5571                         bus->dhd = NULL;
5572                 }
5573
5574                 brcmf_sdbrcm_release_malloc(bus);
5575
5576                 kfree(bus);
5577         }
5578
5579         DHD_TRACE(("%s: Disconnected\n", __func__));
5580 }
5581
5582 static void brcmf_sdbrcm_release_malloc(dhd_bus_t *bus)
5583 {
5584         DHD_TRACE(("%s: Enter\n", __func__));
5585
5586         if (bus->dhd && bus->dhd->dongle_reset)
5587                 return;
5588
5589         kfree(bus->rxbuf);
5590         bus->rxctl = bus->rxbuf = NULL;
5591         bus->rxlen = 0;
5592
5593         kfree(bus->databuf);
5594         bus->databuf = NULL;
5595 }
5596
5597 static void brcmf_sdbrcm_release_dongle(dhd_bus_t *bus)
5598 {
5599         DHD_TRACE(("%s: Enter\n", __func__));
5600
5601         if (bus->dhd && bus->dhd->dongle_reset)
5602                 return;
5603
5604         if (bus->ci) {
5605                 brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
5606                 brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
5607                 brcmf_sdbrcm_chip_detach(bus);
5608                 if (bus->vars && bus->varsz)
5609                         kfree(bus->vars);
5610                 bus->vars = NULL;
5611         }
5612
5613         DHD_TRACE(("%s: Disconnected\n", __func__));
5614 }
5615
5616 static void brcmf_sdbrcm_disconnect(void *ptr)
5617 {
5618         dhd_bus_t *bus = (dhd_bus_t *)ptr;
5619
5620         DHD_TRACE(("%s: Enter\n", __func__));
5621
5622         if (bus) {
5623                 ASSERT(bus->dhd);
5624                 brcmf_sdbrcm_release(bus);
5625         }
5626
5627         DHD_TRACE(("%s: Disconnected\n", __func__));
5628 }
5629
5630 /* Register/Unregister functions are called by the main DHD entry
5631  * point (e.g. module insertion) to link with the bus driver, in
5632  * order to look for or await the device.
5633  */
5634
5635 static bcmsdh_driver_t dhd_sdio = {
5636         brcmf_sdbrcm_probe,
5637         brcmf_sdbrcm_disconnect
5638 };
5639
5640 int dhd_bus_register(void)
5641 {
5642         DHD_TRACE(("%s: Enter\n", __func__));
5643
5644         return brcmf_sdio_register(&dhd_sdio);
5645 }
5646
5647 void dhd_bus_unregister(void)
5648 {
5649         DHD_TRACE(("%s: Enter\n", __func__));
5650
5651         brcmf_sdio_unregister();
5652 }
5653
5654 static int brcmf_sdbrcm_download_code_file(struct dhd_bus *bus, char *fw_path)
5655 {
5656         int bcmerror = -1;
5657         int offset = 0;
5658         uint len;
5659         void *image = NULL;
5660         u8 *memblock = NULL, *memptr;
5661
5662         DHD_INFO(("%s: download firmware %s\n", __func__, brcmf_fw_path));
5663
5664         image = brcmf_os_open_image(fw_path);
5665         if (image == NULL)
5666                 goto err;
5667
5668         memptr = memblock = kmalloc(MEMBLOCK + DHD_SDALIGN, GFP_ATOMIC);
5669         if (memblock == NULL) {
5670                 DHD_ERROR(("%s: Failed to allocate memory %d bytes\n",
5671                            __func__, MEMBLOCK));
5672                 goto err;
5673         }
5674         if ((u32)(unsigned long)memblock % DHD_SDALIGN)
5675                 memptr +=
5676                     (DHD_SDALIGN - ((u32)(unsigned long)memblock % DHD_SDALIGN));
5677
5678         /* Download image */
5679         while ((len =
5680                 brcmf_os_get_image_block((char *)memptr, MEMBLOCK, image))) {
5681                 bcmerror = brcmf_sdbrcm_membytes(bus, true, offset, memptr,
5682                                                  len);
5683                 if (bcmerror) {
5684                         DHD_ERROR(("%s: error %d on writing %d membytes at "
5685                         "0x%08x\n", __func__, bcmerror, MEMBLOCK, offset));
5686                         goto err;
5687                 }
5688
5689                 offset += MEMBLOCK;
5690         }
5691
5692 err:
5693         kfree(memblock);
5694
5695         if (image)
5696                 brcmf_os_close_image(image);
5697
5698         return bcmerror;
5699 }
5700
5701 /*
5702  * ProcessVars:Takes a buffer of "<var>=<value>\n" lines read from a file
5703  * and ending in a NUL.
5704  * Removes carriage returns, empty lines, comment lines, and converts
5705  * newlines to NULs.
5706  * Shortens buffer as needed and pads with NULs.  End of buffer is marked
5707  * by two NULs.
5708 */
5709
5710 static uint brcmf_process_nvram_vars(char *varbuf, uint len)
5711 {
5712         char *dp;
5713         bool findNewline;
5714         int column;
5715         uint buf_len, n;
5716
5717         dp = varbuf;
5718
5719         findNewline = false;
5720         column = 0;
5721
5722         for (n = 0; n < len; n++) {
5723                 if (varbuf[n] == 0)
5724                         break;
5725                 if (varbuf[n] == '\r')
5726                         continue;
5727                 if (findNewline && varbuf[n] != '\n')
5728                         continue;
5729                 findNewline = false;
5730                 if (varbuf[n] == '#') {
5731                         findNewline = true;
5732                         continue;
5733                 }
5734                 if (varbuf[n] == '\n') {
5735                         if (column == 0)
5736                                 continue;
5737                         *dp++ = 0;
5738                         column = 0;
5739                         continue;
5740                 }
5741                 *dp++ = varbuf[n];
5742                 column++;
5743         }
5744         buf_len = dp - varbuf;
5745
5746         while (dp < varbuf + n)
5747                 *dp++ = 0;
5748
5749         return buf_len;
5750 }
5751
5752 /*
5753         EXAMPLE: nvram_array
5754         nvram_arry format:
5755         name=value
5756         Use carriage return at the end of each assignment,
5757          and an empty string with
5758         carriage return at the end of array.
5759
5760         For example:
5761         unsigned char  nvram_array[] = {"name1=value1\n",
5762         "name2=value2\n", "\n"};
5763         Hex values start with 0x, and mac addr format: xx:xx:xx:xx:xx:xx.
5764
5765         Search "EXAMPLE: nvram_array" to see how the array is activated.
5766 */
5767
5768 void dhd_bus_set_nvram_params(struct dhd_bus *bus, const char *nvram_params)
5769 {
5770         bus->nvram_params = nvram_params;
5771 }
5772
5773 static int brcmf_sdbrcm_download_nvram(struct dhd_bus *bus)
5774 {
5775         int bcmerror = -1;
5776         uint len;
5777         void *image = NULL;
5778         char *memblock = NULL;
5779         char *bufp;
5780         char *nv_path;
5781         bool nvram_file_exists;
5782
5783         nv_path = bus->nv_path;
5784
5785         nvram_file_exists = ((nv_path != NULL) && (nv_path[0] != '\0'));
5786         if (!nvram_file_exists && (bus->nvram_params == NULL))
5787                 return 0;
5788
5789         if (nvram_file_exists) {
5790                 image = brcmf_os_open_image(nv_path);
5791                 if (image == NULL)
5792                         goto err;
5793         }
5794
5795         memblock = kmalloc(MEMBLOCK, GFP_ATOMIC);
5796         if (memblock == NULL) {
5797                 DHD_ERROR(("%s: Failed to allocate memory %d bytes\n",
5798                            __func__, MEMBLOCK));
5799                 goto err;
5800         }
5801
5802         /* Download variables */
5803         if (nvram_file_exists) {
5804                 len = brcmf_os_get_image_block(memblock, MEMBLOCK, image);
5805         } else {
5806                 len = strlen(bus->nvram_params);
5807                 ASSERT(len <= MEMBLOCK);
5808                 if (len > MEMBLOCK)
5809                         len = MEMBLOCK;
5810                 memcpy(memblock, bus->nvram_params, len);
5811         }
5812
5813         if (len > 0 && len < MEMBLOCK) {
5814                 bufp = (char *)memblock;
5815                 bufp[len] = 0;
5816                 len = brcmf_process_nvram_vars(bufp, len);
5817                 bufp += len;
5818                 *bufp++ = 0;
5819                 if (len)
5820                         bcmerror = brcmf_sdbrcm_downloadvars(bus, memblock,
5821                                                            len + 1);
5822                 if (bcmerror) {
5823                         DHD_ERROR(("%s: error downloading vars: %d\n",
5824                                    __func__, bcmerror));
5825                 }
5826         } else {
5827                 DHD_ERROR(("%s: error reading nvram file: %d\n",
5828                            __func__, len));
5829                 bcmerror = -EIO;
5830         }
5831
5832 err:
5833         kfree(memblock);
5834
5835         if (image)
5836                 brcmf_os_close_image(image);
5837
5838         return bcmerror;
5839 }
5840
5841 static int _brcmf_sdbrcm_download_firmware(struct dhd_bus *bus)
5842 {
5843         int bcmerror = -1;
5844
5845         bool embed = false;     /* download embedded firmware */
5846         bool dlok = false;      /* download firmware succeeded */
5847
5848         /* Out immediately if no image to download */
5849         if ((bus->fw_path == NULL) || (bus->fw_path[0] == '\0'))
5850                 return bcmerror;
5851
5852         /* Keep arm in reset */
5853         if (brcmf_sdbrcm_download_state(bus, true)) {
5854                 DHD_ERROR(("%s: error placing ARM core in reset\n", __func__));
5855                 goto err;
5856         }
5857
5858         /* External image takes precedence if specified */
5859         if ((bus->fw_path != NULL) && (bus->fw_path[0] != '\0')) {
5860                 if (brcmf_sdbrcm_download_code_file(bus, bus->fw_path)) {
5861                         DHD_ERROR(("%s: dongle image file download failed\n",
5862                                    __func__));
5863                         goto err;
5864                 } else {
5865                         embed = false;
5866                         dlok = true;
5867                 }
5868         }
5869         if (!dlok) {
5870                 DHD_ERROR(("%s: dongle image download failed\n", __func__));
5871                 goto err;
5872         }
5873
5874         /* EXAMPLE: nvram_array */
5875         /* If a valid nvram_arry is specified as above, it can be passed
5876                  down to dongle */
5877         /* dhd_bus_set_nvram_params(bus, (char *)&nvram_array); */
5878
5879         /* External nvram takes precedence if specified */
5880         if (brcmf_sdbrcm_download_nvram(bus)) {
5881                 DHD_ERROR(("%s: dongle nvram file download failed\n",
5882                            __func__));
5883         }
5884
5885         /* Take arm out of reset */
5886         if (brcmf_sdbrcm_download_state(bus, false)) {
5887                 DHD_ERROR(("%s: error getting out of ARM core reset\n",
5888                            __func__));
5889                 goto err;
5890         }
5891
5892         bcmerror = 0;
5893
5894 err:
5895         return bcmerror;
5896 }
5897
5898
5899 static int
5900 brcmf_sdbrcm_send_buf(dhd_bus_t *bus, u32 addr, uint fn, uint flags,
5901                     u8 *buf, uint nbytes, struct sk_buff *pkt,
5902                     bcmsdh_cmplt_fn_t complete, void *handle)
5903 {
5904         return brcmf_sdcard_send_buf
5905                 (bus->sdh, addr, fn, flags, buf, nbytes, pkt, complete,
5906                  handle);
5907 }
5908
5909 uint dhd_bus_chip(struct dhd_bus *bus)
5910 {
5911         ASSERT(bus->ci != NULL);
5912         return bus->ci->chip;
5913 }
5914
5915 void *dhd_bus_pub(struct dhd_bus *bus)
5916 {
5917         return bus->dhd;
5918 }
5919
5920 void *dhd_bus_txq(struct dhd_bus *bus)
5921 {
5922         return &bus->txq;
5923 }
5924
5925 uint dhd_bus_hdrlen(struct dhd_bus *bus)
5926 {
5927         return SDPCM_HDRLEN;
5928 }
5929
5930 int brcmf_bus_devreset(dhd_pub_t *dhdp, u8 flag)
5931 {
5932         int bcmerror = 0;
5933         dhd_bus_t *bus;
5934
5935         bus = dhdp->bus;
5936
5937         if (flag == true) {
5938                 if (!bus->dhd->dongle_reset) {
5939                         /* Expect app to have torn down any
5940                          connection before calling */
5941                         /* Stop the bus, disable F2 */
5942                         brcmf_sdbrcm_bus_stop(bus, false);
5943
5944                         /* Clean tx/rx buffer pointers,
5945                          detach from the dongle */
5946                         brcmf_sdbrcm_release_dongle(bus);
5947
5948                         bus->dhd->dongle_reset = true;
5949                         bus->dhd->up = false;
5950
5951                         DHD_TRACE(("%s:  WLAN OFF DONE\n", __func__));
5952                         /* App can now remove power from device */
5953                 } else
5954                         bcmerror = -EIO;
5955         } else {
5956                 /* App must have restored power to device before calling */
5957
5958                 DHD_TRACE(("\n\n%s: == WLAN ON ==\n", __func__));
5959
5960                 if (bus->dhd->dongle_reset) {
5961                         /* Turn on WLAN */
5962                         /* Reset SD client */
5963                         brcmf_sdcard_reset(bus->sdh);
5964
5965                         /* Attempt to re-attach & download */
5966                         if (brcmf_sdbrcm_probe_attach(bus, bus->sdh,
5967                                                  (u32 *) SI_ENUM_BASE,
5968                                                  bus->cl_devid)) {
5969                                 /* Attempt to download binary to the dongle */
5970                                 if (brcmf_sdbrcm_probe_init
5971                                     (bus, bus->sdh)
5972                                     && brcmf_sdbrcm_download_firmware(bus,
5973                                                                  bus->sdh)) {
5974
5975                                         /* Re-init bus, enable F2 transfer */
5976                                         brcmf_sdbrcm_bus_init(
5977                                                 (dhd_pub_t *) bus->dhd, false);
5978
5979 #if defined(OOB_INTR_ONLY)
5980                                         brcmf_sdbrcm_enable_oob_intr(bus, true);
5981 #endif                          /* defined(OOB_INTR_ONLY) */
5982
5983                                         bus->dhd->dongle_reset = false;
5984                                         bus->dhd->up = true;
5985
5986                                         DHD_TRACE(("%s: WLAN ON DONE\n",
5987                                                    __func__));
5988                                 } else
5989                                         bcmerror = -EIO;
5990                         } else
5991                                 bcmerror = -EIO;
5992                 } else {
5993                         bcmerror = -EISCONN;
5994                         DHD_ERROR(("%s: Set DEVRESET=false invoked when device "
5995                                 "is on\n", __func__));
5996                         bcmerror = -EIO;
5997                 }
5998         }
5999         return bcmerror;
6000 }
6001
6002 static int
6003 brcmf_sdbrcm_chip_recognition(struct brcmf_sdio *sdh, struct chip_info *ci,
6004                             void *regs)
6005 {
6006         u32 regdata;
6007
6008         /*
6009          * Get CC core rev
6010          * Chipid is assume to be at offset 0 from regs arg
6011          * For different chiptypes or old sdio hosts w/o chipcommon,
6012          * other ways of recognition should be added here.
6013          */
6014         ci->cccorebase = (u32)regs;
6015         regdata = brcmf_sdcard_reg_read(sdh,
6016                                 CORE_CC_REG(ci->cccorebase, chipid), 4);
6017         ci->chip = regdata & CID_ID_MASK;
6018         ci->chiprev = (regdata & CID_REV_MASK) >> CID_REV_SHIFT;
6019
6020         DHD_INFO(("%s: chipid=0x%x chiprev=%d\n",
6021                 __func__, ci->chip, ci->chiprev));
6022
6023         /* Address of cores for new chips should be added here */
6024         switch (ci->chip) {
6025         case BCM4329_CHIP_ID:
6026                 ci->buscorebase = BCM4329_CORE_BUS_BASE;
6027                 ci->ramcorebase = BCM4329_CORE_SOCRAM_BASE;
6028                 ci->armcorebase = BCM4329_CORE_ARM_BASE;
6029                 ci->ramsize = BCM4329_RAMSIZE;
6030                 break;
6031         default:
6032                 DHD_ERROR(("%s: chipid 0x%x is not supported\n",
6033                         __func__, ci->chip));
6034                 return -ENODEV;
6035         }
6036
6037         regdata = brcmf_sdcard_reg_read(sdh,
6038                 CORE_SB(ci->cccorebase, sbidhigh), 4);
6039         ci->ccrev = SBCOREREV(regdata);
6040
6041         regdata = brcmf_sdcard_reg_read(sdh,
6042                 CORE_CC_REG(ci->cccorebase, pmucapabilities), 4);
6043         ci->pmurev = regdata & PCAP_REV_MASK;
6044
6045         regdata = brcmf_sdcard_reg_read(sdh,
6046                                         CORE_SB(ci->buscorebase, sbidhigh), 4);
6047         ci->buscorerev = SBCOREREV(regdata);
6048         ci->buscoretype = (regdata & SBIDH_CC_MASK) >> SBIDH_CC_SHIFT;
6049
6050         DHD_INFO(("%s: ccrev=%d, pmurev=%d, buscore rev/type=%d/0x%x\n",
6051                 __func__, ci->ccrev, ci->pmurev,
6052                 ci->buscorerev, ci->buscoretype));
6053
6054         /* get chipcommon capabilites */
6055         ci->cccaps = brcmf_sdcard_reg_read(sdh,
6056                 CORE_CC_REG(ci->cccorebase, capabilities), 4);
6057
6058         return 0;
6059 }
6060
6061 static void
6062 brcmf_sdbrcm_chip_disablecore(struct brcmf_sdio *sdh, u32 corebase)
6063 {
6064         u32 regdata;
6065
6066         regdata = brcmf_sdcard_reg_read(sdh,
6067                 CORE_SB(corebase, sbtmstatelow), 4);
6068         if (regdata & SBTML_RESET)
6069                 return;
6070
6071         regdata = brcmf_sdcard_reg_read(sdh,
6072                 CORE_SB(corebase, sbtmstatelow), 4);
6073         if ((regdata & (SICF_CLOCK_EN << SBTML_SICF_SHIFT)) != 0) {
6074                 /*
6075                  * set target reject and spin until busy is clear
6076                  * (preserve core-specific bits)
6077                  */
6078                 regdata = brcmf_sdcard_reg_read(sdh,
6079                         CORE_SB(corebase, sbtmstatelow), 4);
6080                 brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbtmstatelow), 4,
6081                         regdata | SBTML_REJ);
6082
6083                 regdata = brcmf_sdcard_reg_read(sdh,
6084                         CORE_SB(corebase, sbtmstatelow), 4);
6085                 udelay(1);
6086                 SPINWAIT((brcmf_sdcard_reg_read(sdh,
6087                         CORE_SB(corebase, sbtmstatehigh), 4) &
6088                         SBTMH_BUSY), 100000);
6089
6090                 regdata = brcmf_sdcard_reg_read(sdh,
6091                         CORE_SB(corebase, sbtmstatehigh), 4);
6092                 if (regdata & SBTMH_BUSY)
6093                         DHD_ERROR(("%s: ARM core still busy\n", __func__));
6094
6095                 regdata = brcmf_sdcard_reg_read(sdh,
6096                         CORE_SB(corebase, sbidlow), 4);
6097                 if (regdata & SBIDL_INIT) {
6098                         regdata = brcmf_sdcard_reg_read(sdh,
6099                                 CORE_SB(corebase, sbimstate), 4) |
6100                                 SBIM_RJ;
6101                         brcmf_sdcard_reg_write(sdh,
6102                                 CORE_SB(corebase, sbimstate), 4,
6103                                 regdata);
6104                         regdata = brcmf_sdcard_reg_read(sdh,
6105                                 CORE_SB(corebase, sbimstate), 4);
6106                         udelay(1);
6107                         SPINWAIT((brcmf_sdcard_reg_read(sdh,
6108                                 CORE_SB(corebase, sbimstate), 4) &
6109                                 SBIM_BY), 100000);
6110                 }
6111
6112                 /* set reset and reject while enabling the clocks */
6113                 brcmf_sdcard_reg_write(sdh,
6114                         CORE_SB(corebase, sbtmstatelow), 4,
6115                         (((SICF_FGC | SICF_CLOCK_EN) << SBTML_SICF_SHIFT) |
6116                         SBTML_REJ | SBTML_RESET));
6117                 regdata = brcmf_sdcard_reg_read(sdh,
6118                         CORE_SB(corebase, sbtmstatelow), 4);
6119                 udelay(10);
6120
6121                 /* clear the initiator reject bit */
6122                 regdata = brcmf_sdcard_reg_read(sdh,
6123                         CORE_SB(corebase, sbidlow), 4);
6124                 if (regdata & SBIDL_INIT) {
6125                         regdata = brcmf_sdcard_reg_read(sdh,
6126                                 CORE_SB(corebase, sbimstate), 4) &
6127                                 ~SBIM_RJ;
6128                         brcmf_sdcard_reg_write(sdh,
6129                                 CORE_SB(corebase, sbimstate), 4,
6130                                 regdata);
6131                 }
6132         }
6133
6134         /* leave reset and reject asserted */
6135         brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbtmstatelow), 4,
6136                 (SBTML_REJ | SBTML_RESET));
6137         udelay(1);
6138 }
6139
6140 static int
6141 brcmf_sdbrcm_chip_attach(struct dhd_bus *bus, void *regs)
6142 {
6143         struct chip_info *ci;
6144         int err;
6145         u8 clkval, clkset;
6146
6147         DHD_TRACE(("%s: Enter\n", __func__));
6148
6149         /* alloc chip_info_t */
6150         ci = kmalloc(sizeof(struct chip_info), GFP_ATOMIC);
6151         if (NULL == ci) {
6152                 DHD_ERROR(("%s: malloc failed!\n", __func__));
6153                 return -ENOMEM;
6154         }
6155
6156         memset((unsigned char *)ci, 0, sizeof(struct chip_info));
6157
6158         /* bus/core/clk setup for register access */
6159         /* Try forcing SDIO core to do ALPAvail request only */
6160         clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
6161         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
6162                         clkset, &err);
6163         if (err) {
6164                 DHD_ERROR(("%s: error writing for HT off\n", __func__));
6165                 goto fail;
6166         }
6167
6168         /* If register supported, wait for ALPAvail and then force ALP */
6169         /* This may take up to 15 milliseconds */
6170         clkval = brcmf_sdcard_cfg_read(bus->sdh, SDIO_FUNC_1,
6171                         SBSDIO_FUNC1_CHIPCLKCSR, NULL);
6172         if ((clkval & ~SBSDIO_AVBITS) == clkset) {
6173                 SPINWAIT(((clkval =
6174                                 brcmf_sdcard_cfg_read(bus->sdh, SDIO_FUNC_1,
6175                                                 SBSDIO_FUNC1_CHIPCLKCSR,
6176                                                 NULL)),
6177                                 !SBSDIO_ALPAV(clkval)),
6178                                 PMU_MAX_TRANSITION_DLY);
6179                 if (!SBSDIO_ALPAV(clkval)) {
6180                         DHD_ERROR(("%s: timeout on ALPAV wait, clkval 0x%02x\n",
6181                                 __func__, clkval));
6182                         err = -EBUSY;
6183                         goto fail;
6184                 }
6185                 clkset = SBSDIO_FORCE_HW_CLKREQ_OFF |
6186                                 SBSDIO_FORCE_ALP;
6187                 brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1,
6188                                 SBSDIO_FUNC1_CHIPCLKCSR,
6189                                 clkset, &err);
6190                 udelay(65);
6191         } else {
6192                 DHD_ERROR(("%s: ChipClkCSR access: wrote 0x%02x read 0x%02x\n",
6193                         __func__, clkset, clkval));
6194                 err = -EACCES;
6195                 goto fail;
6196         }
6197
6198         /* Also, disable the extra SDIO pull-ups */
6199         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SDIOPULLUP,
6200                                0, NULL);
6201
6202         err = brcmf_sdbrcm_chip_recognition(bus->sdh, ci, regs);
6203         if (err)
6204                 goto fail;
6205
6206         /*
6207          * Make sure any on-chip ARM is off (in case strapping is wrong),
6208          * or downloaded code was already running.
6209          */
6210         brcmf_sdbrcm_chip_disablecore(bus->sdh, ci->armcorebase);
6211
6212         brcmf_sdcard_reg_write(bus->sdh,
6213                 CORE_CC_REG(ci->cccorebase, gpiopullup), 4, 0);
6214         brcmf_sdcard_reg_write(bus->sdh,
6215                 CORE_CC_REG(ci->cccorebase, gpiopulldown), 4, 0);
6216
6217         /* Disable F2 to clear any intermediate frame state on the dongle */
6218         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_0, SDIO_CCCR_IOEx,
6219                 SDIO_FUNC_ENABLE_1, NULL);
6220
6221         /* WAR: cmd52 backplane read so core HW will drop ALPReq */
6222         clkval = brcmf_sdcard_cfg_read(bus->sdh, SDIO_FUNC_1,
6223                         0, NULL);
6224
6225         /* Done with backplane-dependent accesses, can drop clock... */
6226         brcmf_sdcard_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
6227                                0, NULL);
6228
6229         bus->ci = ci;
6230         return 0;
6231 fail:
6232         bus->ci = NULL;
6233         kfree(ci);
6234         return err;
6235 }
6236
6237 static void
6238 brcmf_sdbrcm_chip_resetcore(struct brcmf_sdio *sdh, u32 corebase)
6239 {
6240         u32 regdata;
6241
6242         /*
6243          * Must do the disable sequence first to work for
6244          * arbitrary current core state.
6245          */
6246         brcmf_sdbrcm_chip_disablecore(sdh, corebase);
6247
6248         /*
6249          * Now do the initialization sequence.
6250          * set reset while enabling the clock and
6251          * forcing them on throughout the core
6252          */
6253         brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbtmstatelow), 4,
6254                 ((SICF_FGC | SICF_CLOCK_EN) << SBTML_SICF_SHIFT) |
6255                 SBTML_RESET);
6256         udelay(1);
6257
6258         regdata = brcmf_sdcard_reg_read(sdh, CORE_SB(corebase, sbtmstatehigh),
6259                                         4);
6260         if (regdata & SBTMH_SERR)
6261                 brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbtmstatehigh),
6262                                        4, 0);
6263
6264         regdata = brcmf_sdcard_reg_read(sdh, CORE_SB(corebase, sbimstate), 4);
6265         if (regdata & (SBIM_IBE | SBIM_TO))
6266                 brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbimstate), 4,
6267                         regdata & ~(SBIM_IBE | SBIM_TO));
6268
6269         /* clear reset and allow it to propagate throughout the core */
6270         brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbtmstatelow), 4,
6271                 (SICF_FGC << SBTML_SICF_SHIFT) |
6272                 (SICF_CLOCK_EN << SBTML_SICF_SHIFT));
6273         udelay(1);
6274
6275         /* leave clock enabled */
6276         brcmf_sdcard_reg_write(sdh, CORE_SB(corebase, sbtmstatelow), 4,
6277                 (SICF_CLOCK_EN << SBTML_SICF_SHIFT));
6278         udelay(1);
6279 }
6280
6281 /* SDIO Pad drive strength to select value mappings */
6282 struct sdiod_drive_str {
6283         u8 strength;    /* Pad Drive Strength in mA */
6284         u8 sel;         /* Chip-specific select value */
6285 };
6286
6287 /* SDIO Drive Strength to sel value table for PMU Rev 1 */
6288 static const struct sdiod_drive_str sdiod_drive_strength_tab1[] = {
6289         {
6290         4, 0x2}, {
6291         2, 0x3}, {
6292         1, 0x0}, {
6293         0, 0x0}
6294         };
6295
6296 /* SDIO Drive Strength to sel value table for PMU Rev 2, 3 */
6297 static const struct sdiod_drive_str sdiod_drive_strength_tab2[] = {
6298         {
6299         12, 0x7}, {
6300         10, 0x6}, {
6301         8, 0x5}, {
6302         6, 0x4}, {
6303         4, 0x2}, {
6304         2, 0x1}, {
6305         0, 0x0}
6306         };
6307
6308 /* SDIO Drive Strength to sel value table for PMU Rev 8 (1.8V) */
6309 static const struct sdiod_drive_str sdiod_drive_strength_tab3[] = {
6310         {
6311         32, 0x7}, {
6312         26, 0x6}, {
6313         22, 0x5}, {
6314         16, 0x4}, {
6315         12, 0x3}, {
6316         8, 0x2}, {
6317         4, 0x1}, {
6318         0, 0x0}
6319         };
6320
6321 #define SDIOD_DRVSTR_KEY(chip, pmu)     (((chip) << 16) | (pmu))
6322
6323 static void
6324 brcmf_sdbrcm_sdiod_drive_strength_init(struct dhd_bus *bus, u32 drivestrength) {
6325         struct sdiod_drive_str *str_tab = NULL;
6326         u32 str_mask = 0;
6327         u32 str_shift = 0;
6328         char chn[8];
6329
6330         if (!(bus->ci->cccaps & CC_CAP_PMU))
6331                 return;
6332
6333         switch (SDIOD_DRVSTR_KEY(bus->ci->chip, bus->ci->pmurev)) {
6334         case SDIOD_DRVSTR_KEY(BCM4325_CHIP_ID, 1):
6335                 str_tab = (struct sdiod_drive_str *)&sdiod_drive_strength_tab1;
6336                 str_mask = 0x30000000;
6337                 str_shift = 28;
6338                 break;
6339         case SDIOD_DRVSTR_KEY(BCM4325_CHIP_ID, 2):
6340         case SDIOD_DRVSTR_KEY(BCM4325_CHIP_ID, 3):
6341                 str_tab = (struct sdiod_drive_str *)&sdiod_drive_strength_tab2;
6342                 str_mask = 0x00003800;
6343                 str_shift = 11;
6344                 break;
6345         case SDIOD_DRVSTR_KEY(BCM4336_CHIP_ID, 8):
6346                 str_tab = (struct sdiod_drive_str *)&sdiod_drive_strength_tab3;
6347                 str_mask = 0x00003800;
6348                 str_shift = 11;
6349                 break;
6350         default:
6351                 DHD_ERROR(("No SDIO Drive strength init"
6352                         "done for chip %s rev %d pmurev %d\n",
6353                         brcmu_chipname(bus->ci->chip, chn, 8),
6354                         bus->ci->chiprev, bus->ci->pmurev));
6355                 break;
6356         }
6357
6358         if (str_tab != NULL) {
6359                 u32 drivestrength_sel = 0;
6360                 u32 cc_data_temp;
6361                 int i;
6362
6363                 for (i = 0; str_tab[i].strength != 0; i++) {
6364                         if (drivestrength >= str_tab[i].strength) {
6365                                 drivestrength_sel = str_tab[i].sel;
6366                                 break;
6367                         }
6368                 }
6369
6370                 brcmf_sdcard_reg_write(bus->sdh,
6371                         CORE_CC_REG(bus->ci->cccorebase, chipcontrol_addr),
6372                         4, 1);
6373                 cc_data_temp = brcmf_sdcard_reg_read(bus->sdh,
6374                         CORE_CC_REG(bus->ci->cccorebase, chipcontrol_addr), 4);
6375                 cc_data_temp &= ~str_mask;
6376                 drivestrength_sel <<= str_shift;
6377                 cc_data_temp |= drivestrength_sel;
6378                 brcmf_sdcard_reg_write(bus->sdh,
6379                         CORE_CC_REG(bus->ci->cccorebase, chipcontrol_addr),
6380                         4, cc_data_temp);
6381
6382                 DHD_INFO(("SDIO: %dmA drive strength selected, set to 0x%08x\n",
6383                         drivestrength, cc_data_temp));
6384         }
6385 }
6386
6387 static void
6388 brcmf_sdbrcm_chip_detach(struct dhd_bus *bus)
6389 {
6390         DHD_TRACE(("%s: Enter\n", __func__));
6391
6392         kfree(bus->ci);
6393         bus->ci = NULL;
6394 }