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