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