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