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