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