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