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