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