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