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