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