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