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