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