dhd_sdio.c revision 23677ce3172fcb93522a1df077d21019e73ee1e3
1/*
2 * Copyright (c) 2010 Broadcom Corporation
3 *
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
11 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
13 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18
19#include <linux/types.h>
20#include <linux/kernel.h>
21#include <linux/kthread.h>
22#include <linux/printk.h>
23#include <linux/pci_ids.h>
24#include <linux/netdevice.h>
25#include <linux/interrupt.h>
26#include <linux/sched.h>
27#include <linux/mmc/sdio.h>
28#include <linux/mmc/sdio_func.h>
29#include <linux/mmc/card.h>
30#include <linux/semaphore.h>
31#include <linux/firmware.h>
32#include <linux/module.h>
33#include <linux/bcma/bcma.h>
34#include <asm/unaligned.h>
35#include <defs.h>
36#include <brcmu_wifi.h>
37#include <brcmu_utils.h>
38#include <brcm_hw_ids.h>
39#include <soc.h>
40#include "sdio_host.h"
41#include "sdio_chip.h"
42
43#define DCMD_RESP_TIMEOUT  2000	/* In milli second */
44
45#ifdef DEBUG
46
47#define BRCMF_TRAP_INFO_SIZE	80
48
49#define CBUF_LEN	(128)
50
51struct rte_log_le {
52	__le32 buf;		/* Can't be pointer on (64-bit) hosts */
53	__le32 buf_size;
54	__le32 idx;
55	char *_buf_compat;	/* Redundant pointer for backward compat. */
56};
57
58struct rte_console {
59	/* Virtual UART
60	 * When there is no UART (e.g. Quickturn),
61	 * the host should write a complete
62	 * input line directly into cbuf and then write
63	 * the length into vcons_in.
64	 * This may also be used when there is a real UART
65	 * (at risk of conflicting with
66	 * the real UART).  vcons_out is currently unused.
67	 */
68	uint vcons_in;
69	uint vcons_out;
70
71	/* Output (logging) buffer
72	 * Console output is written to a ring buffer log_buf at index log_idx.
73	 * The host may read the output when it sees log_idx advance.
74	 * Output will be lost if the output wraps around faster than the host
75	 * polls.
76	 */
77	struct rte_log_le log_le;
78
79	/* Console input line buffer
80	 * Characters are read one at a time into cbuf
81	 * until <CR> is received, then
82	 * the buffer is processed as a command line.
83	 * Also used for virtual UART.
84	 */
85	uint cbuf_idx;
86	char cbuf[CBUF_LEN];
87};
88
89#endif				/* DEBUG */
90#include <chipcommon.h>
91
92#include "dhd_bus.h"
93#include "dhd_dbg.h"
94
95#define TXQLEN		2048	/* bulk tx queue length */
96#define TXHI		(TXQLEN - 256)	/* turn on flow control above TXHI */
97#define TXLOW		(TXHI - 256)	/* turn off flow control below TXLOW */
98#define PRIOMASK	7
99
100#define TXRETRIES	2	/* # of retries for tx frames */
101
102#define BRCMF_RXBOUND	50	/* Default for max rx frames in
103				 one scheduling */
104
105#define BRCMF_TXBOUND	20	/* Default for max tx frames in
106				 one scheduling */
107
108#define BRCMF_TXMINMAX	1	/* Max tx frames if rx still pending */
109
110#define MEMBLOCK	2048	/* Block size used for downloading
111				 of dongle image */
112#define MAX_DATA_BUF	(32 * 1024)	/* Must be large enough to hold
113				 biggest possible glom */
114
115#define BRCMF_FIRSTREAD	(1 << 6)
116
117
118/* SBSDIO_DEVICE_CTL */
119
120/* 1: device will assert busy signal when receiving CMD53 */
121#define SBSDIO_DEVCTL_SETBUSY		0x01
122/* 1: assertion of sdio interrupt is synchronous to the sdio clock */
123#define SBSDIO_DEVCTL_SPI_INTR_SYNC	0x02
124/* 1: mask all interrupts to host except the chipActive (rev 8) */
125#define SBSDIO_DEVCTL_CA_INT_ONLY	0x04
126/* 1: isolate internal sdio signals, put external pads in tri-state; requires
127 * sdio bus power cycle to clear (rev 9) */
128#define SBSDIO_DEVCTL_PADS_ISO		0x08
129/* Force SD->SB reset mapping (rev 11) */
130#define SBSDIO_DEVCTL_SB_RST_CTL	0x30
131/*   Determined by CoreControl bit */
132#define SBSDIO_DEVCTL_RST_CORECTL	0x00
133/*   Force backplane reset */
134#define SBSDIO_DEVCTL_RST_BPRESET	0x10
135/*   Force no backplane reset */
136#define SBSDIO_DEVCTL_RST_NOBPRESET	0x20
137
138/* direct(mapped) cis space */
139
140/* MAPPED common CIS address */
141#define SBSDIO_CIS_BASE_COMMON		0x1000
142/* maximum bytes in one CIS */
143#define SBSDIO_CIS_SIZE_LIMIT		0x200
144/* cis offset addr is < 17 bits */
145#define SBSDIO_CIS_OFT_ADDR_MASK	0x1FFFF
146
147/* manfid tuple length, include tuple, link bytes */
148#define SBSDIO_CIS_MANFID_TUPLE_LEN	6
149
150/* intstatus */
151#define I_SMB_SW0	(1 << 0)	/* To SB Mail S/W interrupt 0 */
152#define I_SMB_SW1	(1 << 1)	/* To SB Mail S/W interrupt 1 */
153#define I_SMB_SW2	(1 << 2)	/* To SB Mail S/W interrupt 2 */
154#define I_SMB_SW3	(1 << 3)	/* To SB Mail S/W interrupt 3 */
155#define I_SMB_SW_MASK	0x0000000f	/* To SB Mail S/W interrupts mask */
156#define I_SMB_SW_SHIFT	0	/* To SB Mail S/W interrupts shift */
157#define I_HMB_SW0	(1 << 4)	/* To Host Mail S/W interrupt 0 */
158#define I_HMB_SW1	(1 << 5)	/* To Host Mail S/W interrupt 1 */
159#define I_HMB_SW2	(1 << 6)	/* To Host Mail S/W interrupt 2 */
160#define I_HMB_SW3	(1 << 7)	/* To Host Mail S/W interrupt 3 */
161#define I_HMB_SW_MASK	0x000000f0	/* To Host Mail S/W interrupts mask */
162#define I_HMB_SW_SHIFT	4	/* To Host Mail S/W interrupts shift */
163#define I_WR_OOSYNC	(1 << 8)	/* Write Frame Out Of Sync */
164#define I_RD_OOSYNC	(1 << 9)	/* Read Frame Out Of Sync */
165#define	I_PC		(1 << 10)	/* descriptor error */
166#define	I_PD		(1 << 11)	/* data error */
167#define	I_DE		(1 << 12)	/* Descriptor protocol Error */
168#define	I_RU		(1 << 13)	/* Receive descriptor Underflow */
169#define	I_RO		(1 << 14)	/* Receive fifo Overflow */
170#define	I_XU		(1 << 15)	/* Transmit fifo Underflow */
171#define	I_RI		(1 << 16)	/* Receive Interrupt */
172#define I_BUSPWR	(1 << 17)	/* SDIO Bus Power Change (rev 9) */
173#define I_XMTDATA_AVAIL (1 << 23)	/* bits in fifo */
174#define	I_XI		(1 << 24)	/* Transmit Interrupt */
175#define I_RF_TERM	(1 << 25)	/* Read Frame Terminate */
176#define I_WF_TERM	(1 << 26)	/* Write Frame Terminate */
177#define I_PCMCIA_XU	(1 << 27)	/* PCMCIA Transmit FIFO Underflow */
178#define I_SBINT		(1 << 28)	/* sbintstatus Interrupt */
179#define I_CHIPACTIVE	(1 << 29)	/* chip from doze to active state */
180#define I_SRESET	(1 << 30)	/* CCCR RES interrupt */
181#define I_IOE2		(1U << 31)	/* CCCR IOE2 Bit Changed */
182#define	I_ERRORS	(I_PC | I_PD | I_DE | I_RU | I_RO | I_XU)
183#define I_DMA		(I_RI | I_XI | I_ERRORS)
184
185/* corecontrol */
186#define CC_CISRDY		(1 << 0)	/* CIS Ready */
187#define CC_BPRESEN		(1 << 1)	/* CCCR RES signal */
188#define CC_F2RDY		(1 << 2)	/* set CCCR IOR2 bit */
189#define CC_CLRPADSISO		(1 << 3)	/* clear SDIO pads isolation */
190#define CC_XMTDATAAVAIL_MODE	(1 << 4)
191#define CC_XMTDATAAVAIL_CTRL	(1 << 5)
192
193/* SDA_FRAMECTRL */
194#define SFC_RF_TERM	(1 << 0)	/* Read Frame Terminate */
195#define SFC_WF_TERM	(1 << 1)	/* Write Frame Terminate */
196#define SFC_CRC4WOOS	(1 << 2)	/* CRC error for write out of sync */
197#define SFC_ABORTALL	(1 << 3)	/* Abort all in-progress frames */
198
199/* HW frame tag */
200#define SDPCM_FRAMETAG_LEN	4	/* 2 bytes len, 2 bytes check val */
201
202/* Total length of frame header for dongle protocol */
203#define SDPCM_HDRLEN	(SDPCM_FRAMETAG_LEN + SDPCM_SWHEADER_LEN)
204#define SDPCM_RESERVE	(SDPCM_HDRLEN + BRCMF_SDALIGN)
205
206/*
207 * Software allocation of To SB Mailbox resources
208 */
209
210/* tosbmailbox bits corresponding to intstatus bits */
211#define SMB_NAK		(1 << 0)	/* Frame NAK */
212#define SMB_INT_ACK	(1 << 1)	/* Host Interrupt ACK */
213#define SMB_USE_OOB	(1 << 2)	/* Use OOB Wakeup */
214#define SMB_DEV_INT	(1 << 3)	/* Miscellaneous Interrupt */
215
216/* tosbmailboxdata */
217#define SMB_DATA_VERSION_SHIFT	16	/* host protocol version */
218
219/*
220 * Software allocation of To Host Mailbox resources
221 */
222
223/* intstatus bits */
224#define I_HMB_FC_STATE	I_HMB_SW0	/* Flow Control State */
225#define I_HMB_FC_CHANGE	I_HMB_SW1	/* Flow Control State Changed */
226#define I_HMB_FRAME_IND	I_HMB_SW2	/* Frame Indication */
227#define I_HMB_HOST_INT	I_HMB_SW3	/* Miscellaneous Interrupt */
228
229/* tohostmailboxdata */
230#define HMB_DATA_NAKHANDLED	1	/* retransmit NAK'd frame */
231#define HMB_DATA_DEVREADY	2	/* talk to host after enable */
232#define HMB_DATA_FC		4	/* per prio flowcontrol update flag */
233#define HMB_DATA_FWREADY	8	/* fw ready for protocol activity */
234
235#define HMB_DATA_FCDATA_MASK	0xff000000
236#define HMB_DATA_FCDATA_SHIFT	24
237
238#define HMB_DATA_VERSION_MASK	0x00ff0000
239#define HMB_DATA_VERSION_SHIFT	16
240
241/*
242 * Software-defined protocol header
243 */
244
245/* Current protocol version */
246#define SDPCM_PROT_VERSION	4
247
248/* SW frame header */
249#define SDPCM_PACKET_SEQUENCE(p)	(((u8 *)p)[0] & 0xff)
250
251#define SDPCM_CHANNEL_MASK		0x00000f00
252#define SDPCM_CHANNEL_SHIFT		8
253#define SDPCM_PACKET_CHANNEL(p)		(((u8 *)p)[1] & 0x0f)
254
255#define SDPCM_NEXTLEN_OFFSET		2
256
257/* Data Offset from SOF (HW Tag, SW Tag, Pad) */
258#define SDPCM_DOFFSET_OFFSET		3	/* Data Offset */
259#define SDPCM_DOFFSET_VALUE(p)		(((u8 *)p)[SDPCM_DOFFSET_OFFSET] & 0xff)
260#define SDPCM_DOFFSET_MASK		0xff000000
261#define SDPCM_DOFFSET_SHIFT		24
262#define SDPCM_FCMASK_OFFSET		4	/* Flow control */
263#define SDPCM_FCMASK_VALUE(p)		(((u8 *)p)[SDPCM_FCMASK_OFFSET] & 0xff)
264#define SDPCM_WINDOW_OFFSET		5	/* Credit based fc */
265#define SDPCM_WINDOW_VALUE(p)		(((u8 *)p)[SDPCM_WINDOW_OFFSET] & 0xff)
266
267#define SDPCM_SWHEADER_LEN	8	/* SW header is 64 bits */
268
269/* logical channel numbers */
270#define SDPCM_CONTROL_CHANNEL	0	/* Control channel Id */
271#define SDPCM_EVENT_CHANNEL	1	/* Asyc Event Indication Channel Id */
272#define SDPCM_DATA_CHANNEL	2	/* Data Xmit/Recv Channel Id */
273#define SDPCM_GLOM_CHANNEL	3	/* For coalesced packets */
274#define SDPCM_TEST_CHANNEL	15	/* Reserved for test/debug packets */
275
276#define SDPCM_SEQUENCE_WRAP	256	/* wrap-around val for 8bit frame seq */
277
278#define SDPCM_GLOMDESC(p)	(((u8 *)p)[1] & 0x80)
279
280/*
281 * Shared structure between dongle and the host.
282 * The structure contains pointers to trap or assert information.
283 */
284#define SDPCM_SHARED_VERSION       0x0002
285#define SDPCM_SHARED_VERSION_MASK  0x00FF
286#define SDPCM_SHARED_ASSERT_BUILT  0x0100
287#define SDPCM_SHARED_ASSERT        0x0200
288#define SDPCM_SHARED_TRAP          0x0400
289
290/* Space for header read, limit for data packets */
291#define MAX_HDR_READ	(1 << 6)
292#define MAX_RX_DATASZ	2048
293
294/* Maximum milliseconds to wait for F2 to come up */
295#define BRCMF_WAIT_F2RDY	3000
296
297/* Bump up limit on waiting for HT to account for first startup;
298 * if the image is doing a CRC calculation before programming the PMU
299 * for HT availability, it could take a couple hundred ms more, so
300 * max out at a 1 second (1000000us).
301 */
302#undef PMU_MAX_TRANSITION_DLY
303#define PMU_MAX_TRANSITION_DLY 1000000
304
305/* Value for ChipClockCSR during initial setup */
306#define BRCMF_INIT_CLKCTL1	(SBSDIO_FORCE_HW_CLKREQ_OFF |	\
307					SBSDIO_ALP_AVAIL_REQ)
308
309/* Flags for SDH calls */
310#define F2SYNC	(SDIO_REQ_4BYTE | SDIO_REQ_FIXED)
311
312#define BRCMFMAC_FW_NAME	"brcm/brcmfmac.bin"
313#define BRCMFMAC_NV_NAME	"brcm/brcmfmac.txt"
314MODULE_FIRMWARE(BRCMFMAC_FW_NAME);
315MODULE_FIRMWARE(BRCMFMAC_NV_NAME);
316
317#define BRCMF_IDLE_IMMEDIATE	(-1)	/* Enter idle immediately */
318#define BRCMF_IDLE_ACTIVE	0	/* Do not request any SD clock change
319					 * when idle
320					 */
321#define BRCMF_IDLE_INTERVAL	1
322
323/*
324 * Conversion of 802.1D priority to precedence level
325 */
326static uint prio2prec(u32 prio)
327{
328	return (prio == PRIO_8021D_NONE || prio == PRIO_8021D_BE) ?
329	       (prio^2) : prio;
330}
331
332/* core registers */
333struct sdpcmd_regs {
334	u32 corecontrol;		/* 0x00, rev8 */
335	u32 corestatus;			/* rev8 */
336	u32 PAD[1];
337	u32 biststatus;			/* rev8 */
338
339	/* PCMCIA access */
340	u16 pcmciamesportaladdr;	/* 0x010, rev8 */
341	u16 PAD[1];
342	u16 pcmciamesportalmask;	/* rev8 */
343	u16 PAD[1];
344	u16 pcmciawrframebc;		/* rev8 */
345	u16 PAD[1];
346	u16 pcmciaunderflowtimer;	/* rev8 */
347	u16 PAD[1];
348
349	/* interrupt */
350	u32 intstatus;			/* 0x020, rev8 */
351	u32 hostintmask;		/* rev8 */
352	u32 intmask;			/* rev8 */
353	u32 sbintstatus;		/* rev8 */
354	u32 sbintmask;			/* rev8 */
355	u32 funcintmask;		/* rev4 */
356	u32 PAD[2];
357	u32 tosbmailbox;		/* 0x040, rev8 */
358	u32 tohostmailbox;		/* rev8 */
359	u32 tosbmailboxdata;		/* rev8 */
360	u32 tohostmailboxdata;		/* rev8 */
361
362	/* synchronized access to registers in SDIO clock domain */
363	u32 sdioaccess;			/* 0x050, rev8 */
364	u32 PAD[3];
365
366	/* PCMCIA frame control */
367	u8 pcmciaframectrl;		/* 0x060, rev8 */
368	u8 PAD[3];
369	u8 pcmciawatermark;		/* rev8 */
370	u8 PAD[155];
371
372	/* interrupt batching control */
373	u32 intrcvlazy;			/* 0x100, rev8 */
374	u32 PAD[3];
375
376	/* counters */
377	u32 cmd52rd;			/* 0x110, rev8 */
378	u32 cmd52wr;			/* rev8 */
379	u32 cmd53rd;			/* rev8 */
380	u32 cmd53wr;			/* rev8 */
381	u32 abort;			/* rev8 */
382	u32 datacrcerror;		/* rev8 */
383	u32 rdoutofsync;		/* rev8 */
384	u32 wroutofsync;		/* rev8 */
385	u32 writebusy;			/* rev8 */
386	u32 readwait;			/* rev8 */
387	u32 readterm;			/* rev8 */
388	u32 writeterm;			/* rev8 */
389	u32 PAD[40];
390	u32 clockctlstatus;		/* rev8 */
391	u32 PAD[7];
392
393	u32 PAD[128];			/* DMA engines */
394
395	/* SDIO/PCMCIA CIS region */
396	char cis[512];			/* 0x400-0x5ff, rev6 */
397
398	/* PCMCIA function control registers */
399	char pcmciafcr[256];		/* 0x600-6ff, rev6 */
400	u16 PAD[55];
401
402	/* PCMCIA backplane access */
403	u16 backplanecsr;		/* 0x76E, rev6 */
404	u16 backplaneaddr0;		/* rev6 */
405	u16 backplaneaddr1;		/* rev6 */
406	u16 backplaneaddr2;		/* rev6 */
407	u16 backplaneaddr3;		/* rev6 */
408	u16 backplanedata0;		/* rev6 */
409	u16 backplanedata1;		/* rev6 */
410	u16 backplanedata2;		/* rev6 */
411	u16 backplanedata3;		/* rev6 */
412	u16 PAD[31];
413
414	/* sprom "size" & "blank" info */
415	u16 spromstatus;		/* 0x7BE, rev2 */
416	u32 PAD[464];
417
418	u16 PAD[0x80];
419};
420
421#ifdef DEBUG
422/* Device console log buffer state */
423struct brcmf_console {
424	uint count;		/* Poll interval msec counter */
425	uint log_addr;		/* Log struct address (fixed) */
426	struct rte_log_le log_le;	/* Log struct (host copy) */
427	uint bufsize;		/* Size of log buffer */
428	u8 *buf;		/* Log buffer (host copy) */
429	uint last;		/* Last buffer read index */
430};
431#endif				/* DEBUG */
432
433struct sdpcm_shared {
434	u32 flags;
435	u32 trap_addr;
436	u32 assert_exp_addr;
437	u32 assert_file_addr;
438	u32 assert_line;
439	u32 console_addr;	/* Address of struct rte_console */
440	u32 msgtrace_addr;
441	u8 tag[32];
442};
443
444struct sdpcm_shared_le {
445	__le32 flags;
446	__le32 trap_addr;
447	__le32 assert_exp_addr;
448	__le32 assert_file_addr;
449	__le32 assert_line;
450	__le32 console_addr;	/* Address of struct rte_console */
451	__le32 msgtrace_addr;
452	u8 tag[32];
453};
454
455
456/* misc chip info needed by some of the routines */
457/* Private data for SDIO bus interaction */
458struct brcmf_sdio {
459	struct brcmf_sdio_dev *sdiodev;	/* sdio device handler */
460	struct chip_info *ci;	/* Chip info struct */
461	char *vars;		/* Variables (from CIS and/or other) */
462	uint varsz;		/* Size of variables buffer */
463
464	u32 ramsize;		/* Size of RAM in SOCRAM (bytes) */
465
466	u32 hostintmask;	/* Copy of Host Interrupt Mask */
467	u32 intstatus;	/* Intstatus bits (events) pending */
468	bool dpc_sched;		/* Indicates DPC schedule (intrpt rcvd) */
469	bool fcstate;		/* State of dongle flow-control */
470
471	uint blocksize;		/* Block size of SDIO transfers */
472	uint roundup;		/* Max roundup limit */
473
474	struct pktq txq;	/* Queue length used for flow-control */
475	u8 flowcontrol;	/* per prio flow control bitmask */
476	u8 tx_seq;		/* Transmit sequence number (next) */
477	u8 tx_max;		/* Maximum transmit sequence allowed */
478
479	u8 hdrbuf[MAX_HDR_READ + BRCMF_SDALIGN];
480	u8 *rxhdr;		/* Header of current rx frame (in hdrbuf) */
481	u16 nextlen;		/* Next Read Len from last header */
482	u8 rx_seq;		/* Receive sequence number (expected) */
483	bool rxskip;		/* Skip receive (awaiting NAK ACK) */
484
485	uint rxbound;		/* Rx frames to read before resched */
486	uint txbound;		/* Tx frames to send before resched */
487	uint txminmax;
488
489	struct sk_buff *glomd;	/* Packet containing glomming descriptor */
490	struct sk_buff_head glom; /* Packet list for glommed superframe */
491	uint glomerr;		/* Glom packet read errors */
492
493	u8 *rxbuf;		/* Buffer for receiving control packets */
494	uint rxblen;		/* Allocated length of rxbuf */
495	u8 *rxctl;		/* Aligned pointer into rxbuf */
496	u8 *databuf;		/* Buffer for receiving big glom packet */
497	u8 *dataptr;		/* Aligned pointer into databuf */
498	uint rxlen;		/* Length of valid data in buffer */
499
500	u8 sdpcm_ver;	/* Bus protocol reported by dongle */
501
502	bool intr;		/* Use interrupts */
503	bool poll;		/* Use polling */
504	bool ipend;		/* Device interrupt is pending */
505	uint intrcount;		/* Count of device interrupt callbacks */
506	uint lastintrs;		/* Count as of last watchdog timer */
507	uint spurious;		/* Count of spurious interrupts */
508	uint pollrate;		/* Ticks between device polls */
509	uint polltick;		/* Tick counter */
510	uint pollcnt;		/* Count of active polls */
511
512#ifdef DEBUG
513	uint console_interval;
514	struct brcmf_console console;	/* Console output polling support */
515	uint console_addr;	/* Console address from shared struct */
516#endif				/* DEBUG */
517
518	uint regfails;		/* Count of R_REG failures */
519
520	uint clkstate;		/* State of sd and backplane clock(s) */
521	bool activity;		/* Activity flag for clock down */
522	s32 idletime;		/* Control for activity timeout */
523	s32 idlecount;	/* Activity timeout counter */
524	s32 idleclock;	/* How to set bus driver when idle */
525	s32 sd_rxchain;
526	bool use_rxchain;	/* If brcmf should use PKT chains */
527	bool sleeping;		/* Is SDIO bus sleeping? */
528	bool rxflow_mode;	/* Rx flow control mode */
529	bool rxflow;		/* Is rx flow control on */
530	bool alp_only;		/* Don't use HT clock (ALP only) */
531/* Field to decide if rx of control frames happen in rxbuf or lb-pool */
532	bool usebufpool;
533
534	/* Some additional counters */
535	uint tx_sderrs;		/* Count of tx attempts with sd errors */
536	uint fcqueued;		/* Tx packets that got queued */
537	uint rxrtx;		/* Count of rtx requests (NAK to dongle) */
538	uint rx_toolong;	/* Receive frames too long to receive */
539	uint rxc_errors;	/* SDIO errors when reading control frames */
540	uint rx_hdrfail;	/* SDIO errors on header reads */
541	uint rx_badhdr;		/* Bad received headers (roosync?) */
542	uint rx_badseq;		/* Mismatched rx sequence number */
543	uint fc_rcvd;		/* Number of flow-control events received */
544	uint fc_xoff;		/* Number which turned on flow-control */
545	uint fc_xon;		/* Number which turned off flow-control */
546	uint rxglomfail;	/* Failed deglom attempts */
547	uint rxglomframes;	/* Number of glom frames (superframes) */
548	uint rxglompkts;	/* Number of packets from glom frames */
549	uint f2rxhdrs;		/* Number of header reads */
550	uint f2rxdata;		/* Number of frame data reads */
551	uint f2txdata;		/* Number of f2 frame writes */
552	uint f1regdata;		/* Number of f1 register accesses */
553	uint tickcnt;		/* Number of watchdog been schedule */
554	unsigned long tx_ctlerrs;	/* Err of sending ctrl frames */
555	unsigned long tx_ctlpkts;	/* Ctrl frames sent to dongle */
556	unsigned long rx_ctlerrs;	/* Err of processing rx ctrl frames */
557	unsigned long rx_ctlpkts;	/* Ctrl frames processed from dongle */
558	unsigned long rx_readahead_cnt;	/* Number of packets where header
559					 * read-ahead was used. */
560
561	u8 *ctrl_frame_buf;
562	u32 ctrl_frame_len;
563	bool ctrl_frame_stat;
564
565	spinlock_t txqlock;
566	wait_queue_head_t ctrl_wait;
567	wait_queue_head_t dcmd_resp_wait;
568
569	struct timer_list timer;
570	struct completion watchdog_wait;
571	struct task_struct *watchdog_tsk;
572	bool wd_timer_valid;
573	uint save_ms;
574
575	struct task_struct *dpc_tsk;
576	struct completion dpc_wait;
577
578	struct semaphore sdsem;
579
580	const struct firmware *firmware;
581	u32 fw_ptr;
582
583	bool txoff;		/* Transmit flow-controlled */
584};
585
586/* clkstate */
587#define CLK_NONE	0
588#define CLK_SDONLY	1
589#define CLK_PENDING	2	/* Not used yet */
590#define CLK_AVAIL	3
591
592#ifdef DEBUG
593static int qcount[NUMPRIO];
594static int tx_packets[NUMPRIO];
595#endif				/* DEBUG */
596
597#define SDIO_DRIVE_STRENGTH	6	/* in milliamps */
598
599#define RETRYCHAN(chan) ((chan) == SDPCM_EVENT_CHANNEL)
600
601/* Retry count for register access failures */
602static const uint retry_limit = 2;
603
604/* Limit on rounding up frames */
605static const uint max_roundup = 512;
606
607#define ALIGNMENT  4
608
609static void pkt_align(struct sk_buff *p, int len, int align)
610{
611	uint datalign;
612	datalign = (unsigned long)(p->data);
613	datalign = roundup(datalign, (align)) - datalign;
614	if (datalign)
615		skb_pull(p, datalign);
616	__skb_trim(p, len);
617}
618
619/* To check if there's window offered */
620static bool data_ok(struct brcmf_sdio *bus)
621{
622	return (u8)(bus->tx_max - bus->tx_seq) != 0 &&
623	       ((u8)(bus->tx_max - bus->tx_seq) & 0x80) == 0;
624}
625
626/*
627 * Reads a register in the SDIO hardware block. This block occupies a series of
628 * adresses on the 32 bit backplane bus.
629 */
630static void
631r_sdreg32(struct brcmf_sdio *bus, u32 *regvar, u32 reg_offset, u32 *retryvar)
632{
633	u8 idx = brcmf_sdio_chip_getinfidx(bus->ci, BCMA_CORE_SDIO_DEV);
634	*retryvar = 0;
635	do {
636		*regvar = brcmf_sdcard_reg_read(bus->sdiodev,
637				bus->ci->c_inf[idx].base + reg_offset,
638				sizeof(u32));
639	} while (brcmf_sdcard_regfail(bus->sdiodev) &&
640		 (++(*retryvar) <= retry_limit));
641	if (*retryvar) {
642		bus->regfails += (*retryvar-1);
643		if (*retryvar > retry_limit) {
644			brcmf_dbg(ERROR, "FAILED READ %Xh\n", reg_offset);
645			*regvar = 0;
646		}
647	}
648}
649
650static void
651w_sdreg32(struct brcmf_sdio *bus, u32 regval, u32 reg_offset, u32 *retryvar)
652{
653	u8 idx = brcmf_sdio_chip_getinfidx(bus->ci, BCMA_CORE_SDIO_DEV);
654	*retryvar = 0;
655	do {
656		brcmf_sdcard_reg_write(bus->sdiodev,
657				       bus->ci->c_inf[idx].base + reg_offset,
658				       sizeof(u32), regval);
659	} while (brcmf_sdcard_regfail(bus->sdiodev) &&
660		 (++(*retryvar) <= retry_limit));
661	if (*retryvar) {
662		bus->regfails += (*retryvar-1);
663		if (*retryvar > retry_limit)
664			brcmf_dbg(ERROR, "FAILED REGISTER WRITE %Xh\n",
665				  reg_offset);
666	}
667}
668
669#define PKT_AVAILABLE()		(intstatus & I_HMB_FRAME_IND)
670
671#define HOSTINTMASK		(I_HMB_SW_MASK | I_CHIPACTIVE)
672
673/* Packet free applicable unconditionally for sdio and sdspi.
674 * Conditional if bufpool was present for gspi bus.
675 */
676static void brcmf_sdbrcm_pktfree2(struct brcmf_sdio *bus, struct sk_buff *pkt)
677{
678	if (bus->usebufpool)
679		brcmu_pkt_buf_free_skb(pkt);
680}
681
682/* Turn backplane clock on or off */
683static int brcmf_sdbrcm_htclk(struct brcmf_sdio *bus, bool on, bool pendok)
684{
685	int err;
686	u8 clkctl, clkreq, devctl;
687	unsigned long timeout;
688
689	brcmf_dbg(TRACE, "Enter\n");
690
691	clkctl = 0;
692
693	if (on) {
694		/* Request HT Avail */
695		clkreq =
696		    bus->alp_only ? SBSDIO_ALP_AVAIL_REQ : SBSDIO_HT_AVAIL_REQ;
697
698		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
699				       SBSDIO_FUNC1_CHIPCLKCSR, clkreq, &err);
700		if (err) {
701			brcmf_dbg(ERROR, "HT Avail request error: %d\n", err);
702			return -EBADE;
703		}
704
705		/* Check current status */
706		clkctl = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
707					       SBSDIO_FUNC1_CHIPCLKCSR, &err);
708		if (err) {
709			brcmf_dbg(ERROR, "HT Avail read error: %d\n", err);
710			return -EBADE;
711		}
712
713		/* Go to pending and await interrupt if appropriate */
714		if (!SBSDIO_CLKAV(clkctl, bus->alp_only) && pendok) {
715			/* Allow only clock-available interrupt */
716			devctl = brcmf_sdcard_cfg_read(bus->sdiodev,
717					SDIO_FUNC_1,
718					SBSDIO_DEVICE_CTL, &err);
719			if (err) {
720				brcmf_dbg(ERROR, "Devctl error setting CA: %d\n",
721					  err);
722				return -EBADE;
723			}
724
725			devctl |= SBSDIO_DEVCTL_CA_INT_ONLY;
726			brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
727					       SBSDIO_DEVICE_CTL, devctl, &err);
728			brcmf_dbg(INFO, "CLKCTL: set PENDING\n");
729			bus->clkstate = CLK_PENDING;
730
731			return 0;
732		} else if (bus->clkstate == CLK_PENDING) {
733			/* Cancel CA-only interrupt filter */
734			devctl =
735			    brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
736						  SBSDIO_DEVICE_CTL, &err);
737			devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
738			brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
739				SBSDIO_DEVICE_CTL, devctl, &err);
740		}
741
742		/* Otherwise, wait here (polling) for HT Avail */
743		timeout = jiffies +
744			  msecs_to_jiffies(PMU_MAX_TRANSITION_DLY/1000);
745		while (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
746			clkctl = brcmf_sdcard_cfg_read(bus->sdiodev,
747						       SDIO_FUNC_1,
748						       SBSDIO_FUNC1_CHIPCLKCSR,
749						       &err);
750			if (time_after(jiffies, timeout))
751				break;
752			else
753				usleep_range(5000, 10000);
754		}
755		if (err) {
756			brcmf_dbg(ERROR, "HT Avail request error: %d\n", err);
757			return -EBADE;
758		}
759		if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
760			brcmf_dbg(ERROR, "HT Avail timeout (%d): clkctl 0x%02x\n",
761				  PMU_MAX_TRANSITION_DLY, clkctl);
762			return -EBADE;
763		}
764
765		/* Mark clock available */
766		bus->clkstate = CLK_AVAIL;
767		brcmf_dbg(INFO, "CLKCTL: turned ON\n");
768
769#if defined(DEBUG)
770		if (!bus->alp_only) {
771			if (SBSDIO_ALPONLY(clkctl))
772				brcmf_dbg(ERROR, "HT Clock should be on\n");
773		}
774#endif				/* defined (DEBUG) */
775
776		bus->activity = true;
777	} else {
778		clkreq = 0;
779
780		if (bus->clkstate == CLK_PENDING) {
781			/* Cancel CA-only interrupt filter */
782			devctl = brcmf_sdcard_cfg_read(bus->sdiodev,
783					SDIO_FUNC_1,
784					SBSDIO_DEVICE_CTL, &err);
785			devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
786			brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
787				SBSDIO_DEVICE_CTL, devctl, &err);
788		}
789
790		bus->clkstate = CLK_SDONLY;
791		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
792			SBSDIO_FUNC1_CHIPCLKCSR, clkreq, &err);
793		brcmf_dbg(INFO, "CLKCTL: turned OFF\n");
794		if (err) {
795			brcmf_dbg(ERROR, "Failed access turning clock off: %d\n",
796				  err);
797			return -EBADE;
798		}
799	}
800	return 0;
801}
802
803/* Change idle/active SD state */
804static int brcmf_sdbrcm_sdclk(struct brcmf_sdio *bus, bool on)
805{
806	brcmf_dbg(TRACE, "Enter\n");
807
808	if (on)
809		bus->clkstate = CLK_SDONLY;
810	else
811		bus->clkstate = CLK_NONE;
812
813	return 0;
814}
815
816/* Transition SD and backplane clock readiness */
817static int brcmf_sdbrcm_clkctl(struct brcmf_sdio *bus, uint target, bool pendok)
818{
819#ifdef DEBUG
820	uint oldstate = bus->clkstate;
821#endif				/* DEBUG */
822
823	brcmf_dbg(TRACE, "Enter\n");
824
825	/* Early exit if we're already there */
826	if (bus->clkstate == target) {
827		if (target == CLK_AVAIL) {
828			brcmf_sdbrcm_wd_timer(bus, BRCMF_WD_POLL_MS);
829			bus->activity = true;
830		}
831		return 0;
832	}
833
834	switch (target) {
835	case CLK_AVAIL:
836		/* Make sure SD clock is available */
837		if (bus->clkstate == CLK_NONE)
838			brcmf_sdbrcm_sdclk(bus, true);
839		/* Now request HT Avail on the backplane */
840		brcmf_sdbrcm_htclk(bus, true, pendok);
841		brcmf_sdbrcm_wd_timer(bus, BRCMF_WD_POLL_MS);
842		bus->activity = true;
843		break;
844
845	case CLK_SDONLY:
846		/* Remove HT request, or bring up SD clock */
847		if (bus->clkstate == CLK_NONE)
848			brcmf_sdbrcm_sdclk(bus, true);
849		else if (bus->clkstate == CLK_AVAIL)
850			brcmf_sdbrcm_htclk(bus, false, false);
851		else
852			brcmf_dbg(ERROR, "request for %d -> %d\n",
853				  bus->clkstate, target);
854		brcmf_sdbrcm_wd_timer(bus, BRCMF_WD_POLL_MS);
855		break;
856
857	case CLK_NONE:
858		/* Make sure to remove HT request */
859		if (bus->clkstate == CLK_AVAIL)
860			brcmf_sdbrcm_htclk(bus, false, false);
861		/* Now remove the SD clock */
862		brcmf_sdbrcm_sdclk(bus, false);
863		brcmf_sdbrcm_wd_timer(bus, 0);
864		break;
865	}
866#ifdef DEBUG
867	brcmf_dbg(INFO, "%d -> %d\n", oldstate, bus->clkstate);
868#endif				/* DEBUG */
869
870	return 0;
871}
872
873static int brcmf_sdbrcm_bussleep(struct brcmf_sdio *bus, bool sleep)
874{
875	uint retries = 0;
876
877	brcmf_dbg(INFO, "request %s (currently %s)\n",
878		  sleep ? "SLEEP" : "WAKE",
879		  bus->sleeping ? "SLEEP" : "WAKE");
880
881	/* Done if we're already in the requested state */
882	if (sleep == bus->sleeping)
883		return 0;
884
885	/* Going to sleep: set the alarm and turn off the lights... */
886	if (sleep) {
887		/* Don't sleep if something is pending */
888		if (bus->dpc_sched || bus->rxskip || pktq_len(&bus->txq))
889			return -EBUSY;
890
891		/* Make sure the controller has the bus up */
892		brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
893
894		/* Tell device to start using OOB wakeup */
895		w_sdreg32(bus, SMB_USE_OOB,
896			  offsetof(struct sdpcmd_regs, tosbmailbox), &retries);
897		if (retries > retry_limit)
898			brcmf_dbg(ERROR, "CANNOT SIGNAL CHIP, WILL NOT WAKE UP!!\n");
899
900		/* Turn off our contribution to the HT clock request */
901		brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
902
903		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
904			SBSDIO_FUNC1_CHIPCLKCSR,
905			SBSDIO_FORCE_HW_CLKREQ_OFF, NULL);
906
907		/* Isolate the bus */
908		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
909			SBSDIO_DEVICE_CTL,
910			SBSDIO_DEVCTL_PADS_ISO, NULL);
911
912		/* Change state */
913		bus->sleeping = true;
914
915	} else {
916		/* Waking up: bus power up is ok, set local state */
917
918		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
919			SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL);
920
921		/* Make sure the controller has the bus up */
922		brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
923
924		/* Send misc interrupt to indicate OOB not needed */
925		w_sdreg32(bus, 0, offsetof(struct sdpcmd_regs, tosbmailboxdata),
926			  &retries);
927		if (retries <= retry_limit)
928			w_sdreg32(bus, SMB_DEV_INT,
929				  offsetof(struct sdpcmd_regs, tosbmailbox),
930				  &retries);
931
932		if (retries > retry_limit)
933			brcmf_dbg(ERROR, "CANNOT SIGNAL CHIP TO CLEAR OOB!!\n");
934
935		/* Make sure we have SD bus access */
936		brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
937
938		/* Change state */
939		bus->sleeping = false;
940	}
941
942	return 0;
943}
944
945static void bus_wake(struct brcmf_sdio *bus)
946{
947	if (bus->sleeping)
948		brcmf_sdbrcm_bussleep(bus, false);
949}
950
951static u32 brcmf_sdbrcm_hostmail(struct brcmf_sdio *bus)
952{
953	u32 intstatus = 0;
954	u32 hmb_data;
955	u8 fcbits;
956	uint retries = 0;
957
958	brcmf_dbg(TRACE, "Enter\n");
959
960	/* Read mailbox data and ack that we did so */
961	r_sdreg32(bus, &hmb_data,
962		  offsetof(struct sdpcmd_regs, tohostmailboxdata), &retries);
963
964	if (retries <= retry_limit)
965		w_sdreg32(bus, SMB_INT_ACK,
966			  offsetof(struct sdpcmd_regs, tosbmailbox), &retries);
967	bus->f1regdata += 2;
968
969	/* Dongle recomposed rx frames, accept them again */
970	if (hmb_data & HMB_DATA_NAKHANDLED) {
971		brcmf_dbg(INFO, "Dongle reports NAK handled, expect rtx of %d\n",
972			  bus->rx_seq);
973		if (!bus->rxskip)
974			brcmf_dbg(ERROR, "unexpected NAKHANDLED!\n");
975
976		bus->rxskip = false;
977		intstatus |= I_HMB_FRAME_IND;
978	}
979
980	/*
981	 * DEVREADY does not occur with gSPI.
982	 */
983	if (hmb_data & (HMB_DATA_DEVREADY | HMB_DATA_FWREADY)) {
984		bus->sdpcm_ver =
985		    (hmb_data & HMB_DATA_VERSION_MASK) >>
986		    HMB_DATA_VERSION_SHIFT;
987		if (bus->sdpcm_ver != SDPCM_PROT_VERSION)
988			brcmf_dbg(ERROR, "Version mismatch, dongle reports %d, "
989				  "expecting %d\n",
990				  bus->sdpcm_ver, SDPCM_PROT_VERSION);
991		else
992			brcmf_dbg(INFO, "Dongle ready, protocol version %d\n",
993				  bus->sdpcm_ver);
994	}
995
996	/*
997	 * Flow Control has been moved into the RX headers and this out of band
998	 * method isn't used any more.
999	 * remaining backward compatible with older dongles.
1000	 */
1001	if (hmb_data & HMB_DATA_FC) {
1002		fcbits = (hmb_data & HMB_DATA_FCDATA_MASK) >>
1003							HMB_DATA_FCDATA_SHIFT;
1004
1005		if (fcbits & ~bus->flowcontrol)
1006			bus->fc_xoff++;
1007
1008		if (bus->flowcontrol & ~fcbits)
1009			bus->fc_xon++;
1010
1011		bus->fc_rcvd++;
1012		bus->flowcontrol = fcbits;
1013	}
1014
1015	/* Shouldn't be any others */
1016	if (hmb_data & ~(HMB_DATA_DEVREADY |
1017			 HMB_DATA_NAKHANDLED |
1018			 HMB_DATA_FC |
1019			 HMB_DATA_FWREADY |
1020			 HMB_DATA_FCDATA_MASK | HMB_DATA_VERSION_MASK))
1021		brcmf_dbg(ERROR, "Unknown mailbox data content: 0x%02x\n",
1022			  hmb_data);
1023
1024	return intstatus;
1025}
1026
1027static void brcmf_sdbrcm_rxfail(struct brcmf_sdio *bus, bool abort, bool rtx)
1028{
1029	uint retries = 0;
1030	u16 lastrbc;
1031	u8 hi, lo;
1032	int err;
1033
1034	brcmf_dbg(ERROR, "%sterminate frame%s\n",
1035		  abort ? "abort command, " : "",
1036		  rtx ? ", send NAK" : "");
1037
1038	if (abort)
1039		brcmf_sdcard_abort(bus->sdiodev, SDIO_FUNC_2);
1040
1041	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
1042			       SBSDIO_FUNC1_FRAMECTRL,
1043			       SFC_RF_TERM, &err);
1044	bus->f1regdata++;
1045
1046	/* Wait until the packet has been flushed (device/FIFO stable) */
1047	for (lastrbc = retries = 0xffff; retries > 0; retries--) {
1048		hi = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
1049					   SBSDIO_FUNC1_RFRAMEBCHI, NULL);
1050		lo = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
1051					   SBSDIO_FUNC1_RFRAMEBCLO, NULL);
1052		bus->f1regdata += 2;
1053
1054		if ((hi == 0) && (lo == 0))
1055			break;
1056
1057		if ((hi > (lastrbc >> 8)) && (lo > (lastrbc & 0x00ff))) {
1058			brcmf_dbg(ERROR, "count growing: last 0x%04x now 0x%04x\n",
1059				  lastrbc, (hi << 8) + lo);
1060		}
1061		lastrbc = (hi << 8) + lo;
1062	}
1063
1064	if (!retries)
1065		brcmf_dbg(ERROR, "count never zeroed: last 0x%04x\n", lastrbc);
1066	else
1067		brcmf_dbg(INFO, "flush took %d iterations\n", 0xffff - retries);
1068
1069	if (rtx) {
1070		bus->rxrtx++;
1071		w_sdreg32(bus, SMB_NAK,
1072			  offsetof(struct sdpcmd_regs, tosbmailbox), &retries);
1073
1074		bus->f1regdata++;
1075		if (retries <= retry_limit)
1076			bus->rxskip = true;
1077	}
1078
1079	/* Clear partial in any case */
1080	bus->nextlen = 0;
1081
1082	/* If we can't reach the device, signal failure */
1083	if (err || brcmf_sdcard_regfail(bus->sdiodev))
1084		bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
1085}
1086
1087/* copy a buffer into a pkt buffer chain */
1088static uint brcmf_sdbrcm_glom_from_buf(struct brcmf_sdio *bus, uint len)
1089{
1090	uint n, ret = 0;
1091	struct sk_buff *p;
1092	u8 *buf;
1093
1094	buf = bus->dataptr;
1095
1096	/* copy the data */
1097	skb_queue_walk(&bus->glom, p) {
1098		n = min_t(uint, p->len, len);
1099		memcpy(p->data, buf, n);
1100		buf += n;
1101		len -= n;
1102		ret += n;
1103		if (!len)
1104			break;
1105	}
1106
1107	return ret;
1108}
1109
1110/* return total length of buffer chain */
1111static uint brcmf_sdbrcm_glom_len(struct brcmf_sdio *bus)
1112{
1113	struct sk_buff *p;
1114	uint total;
1115
1116	total = 0;
1117	skb_queue_walk(&bus->glom, p)
1118		total += p->len;
1119	return total;
1120}
1121
1122static void brcmf_sdbrcm_free_glom(struct brcmf_sdio *bus)
1123{
1124	struct sk_buff *cur, *next;
1125
1126	skb_queue_walk_safe(&bus->glom, cur, next) {
1127		skb_unlink(cur, &bus->glom);
1128		brcmu_pkt_buf_free_skb(cur);
1129	}
1130}
1131
1132static u8 brcmf_sdbrcm_rxglom(struct brcmf_sdio *bus, u8 rxseq)
1133{
1134	u16 dlen, totlen;
1135	u8 *dptr, num = 0;
1136
1137	u16 sublen, check;
1138	struct sk_buff *pfirst, *pnext;
1139
1140	int errcode;
1141	u8 chan, seq, doff, sfdoff;
1142	u8 txmax;
1143
1144	int ifidx = 0;
1145	bool usechain = bus->use_rxchain;
1146
1147	/* If packets, issue read(s) and send up packet chain */
1148	/* Return sequence numbers consumed? */
1149
1150	brcmf_dbg(TRACE, "start: glomd %p glom %p\n",
1151		  bus->glomd, skb_peek(&bus->glom));
1152
1153	/* If there's a descriptor, generate the packet chain */
1154	if (bus->glomd) {
1155		pfirst = pnext = NULL;
1156		dlen = (u16) (bus->glomd->len);
1157		dptr = bus->glomd->data;
1158		if (!dlen || (dlen & 1)) {
1159			brcmf_dbg(ERROR, "bad glomd len(%d), ignore descriptor\n",
1160				  dlen);
1161			dlen = 0;
1162		}
1163
1164		for (totlen = num = 0; dlen; num++) {
1165			/* Get (and move past) next length */
1166			sublen = get_unaligned_le16(dptr);
1167			dlen -= sizeof(u16);
1168			dptr += sizeof(u16);
1169			if ((sublen < SDPCM_HDRLEN) ||
1170			    ((num == 0) && (sublen < (2 * SDPCM_HDRLEN)))) {
1171				brcmf_dbg(ERROR, "descriptor len %d bad: %d\n",
1172					  num, sublen);
1173				pnext = NULL;
1174				break;
1175			}
1176			if (sublen % BRCMF_SDALIGN) {
1177				brcmf_dbg(ERROR, "sublen %d not multiple of %d\n",
1178					  sublen, BRCMF_SDALIGN);
1179				usechain = false;
1180			}
1181			totlen += sublen;
1182
1183			/* For last frame, adjust read len so total
1184				 is a block multiple */
1185			if (!dlen) {
1186				sublen +=
1187				    (roundup(totlen, bus->blocksize) - totlen);
1188				totlen = roundup(totlen, bus->blocksize);
1189			}
1190
1191			/* Allocate/chain packet for next subframe */
1192			pnext = brcmu_pkt_buf_get_skb(sublen + BRCMF_SDALIGN);
1193			if (pnext == NULL) {
1194				brcmf_dbg(ERROR, "bcm_pkt_buf_get_skb failed, num %d len %d\n",
1195					  num, sublen);
1196				break;
1197			}
1198			skb_queue_tail(&bus->glom, pnext);
1199
1200			/* Adhere to start alignment requirements */
1201			pkt_align(pnext, sublen, BRCMF_SDALIGN);
1202		}
1203
1204		/* If all allocations succeeded, save packet chain
1205			 in bus structure */
1206		if (pnext) {
1207			brcmf_dbg(GLOM, "allocated %d-byte packet chain for %d subframes\n",
1208				  totlen, num);
1209			if (BRCMF_GLOM_ON() && bus->nextlen &&
1210			    totlen != bus->nextlen) {
1211				brcmf_dbg(GLOM, "glomdesc mismatch: nextlen %d glomdesc %d rxseq %d\n",
1212					  bus->nextlen, totlen, rxseq);
1213			}
1214			pfirst = pnext = NULL;
1215		} else {
1216			brcmf_sdbrcm_free_glom(bus);
1217			num = 0;
1218		}
1219
1220		/* Done with descriptor packet */
1221		brcmu_pkt_buf_free_skb(bus->glomd);
1222		bus->glomd = NULL;
1223		bus->nextlen = 0;
1224	}
1225
1226	/* Ok -- either we just generated a packet chain,
1227		 or had one from before */
1228	if (!skb_queue_empty(&bus->glom)) {
1229		if (BRCMF_GLOM_ON()) {
1230			brcmf_dbg(GLOM, "try superframe read, packet chain:\n");
1231			skb_queue_walk(&bus->glom, pnext) {
1232				brcmf_dbg(GLOM, "    %p: %p len 0x%04x (%d)\n",
1233					  pnext, (u8 *) (pnext->data),
1234					  pnext->len, pnext->len);
1235			}
1236		}
1237
1238		pfirst = skb_peek(&bus->glom);
1239		dlen = (u16) brcmf_sdbrcm_glom_len(bus);
1240
1241		/* Do an SDIO read for the superframe.  Configurable iovar to
1242		 * read directly into the chained packet, or allocate a large
1243		 * packet and and copy into the chain.
1244		 */
1245		if (usechain) {
1246			errcode = brcmf_sdcard_recv_chain(bus->sdiodev,
1247					bus->sdiodev->sbwad,
1248					SDIO_FUNC_2, F2SYNC, &bus->glom);
1249		} else if (bus->dataptr) {
1250			errcode = brcmf_sdcard_recv_buf(bus->sdiodev,
1251					bus->sdiodev->sbwad,
1252					SDIO_FUNC_2, F2SYNC,
1253					bus->dataptr, dlen);
1254			sublen = (u16) brcmf_sdbrcm_glom_from_buf(bus, dlen);
1255			if (sublen != dlen) {
1256				brcmf_dbg(ERROR, "FAILED TO COPY, dlen %d sublen %d\n",
1257					  dlen, sublen);
1258				errcode = -1;
1259			}
1260			pnext = NULL;
1261		} else {
1262			brcmf_dbg(ERROR, "COULDN'T ALLOC %d-BYTE GLOM, FORCE FAILURE\n",
1263				  dlen);
1264			errcode = -1;
1265		}
1266		bus->f2rxdata++;
1267
1268		/* On failure, kill the superframe, allow a couple retries */
1269		if (errcode < 0) {
1270			brcmf_dbg(ERROR, "glom read of %d bytes failed: %d\n",
1271				  dlen, errcode);
1272			bus->sdiodev->bus_if->dstats.rx_errors++;
1273
1274			if (bus->glomerr++ < 3) {
1275				brcmf_sdbrcm_rxfail(bus, true, true);
1276			} else {
1277				bus->glomerr = 0;
1278				brcmf_sdbrcm_rxfail(bus, true, false);
1279				bus->rxglomfail++;
1280				brcmf_sdbrcm_free_glom(bus);
1281			}
1282			return 0;
1283		}
1284
1285		brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1286				   pfirst->data, min_t(int, pfirst->len, 48),
1287				   "SUPERFRAME:\n");
1288
1289		/* Validate the superframe header */
1290		dptr = (u8 *) (pfirst->data);
1291		sublen = get_unaligned_le16(dptr);
1292		check = get_unaligned_le16(dptr + sizeof(u16));
1293
1294		chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]);
1295		seq = SDPCM_PACKET_SEQUENCE(&dptr[SDPCM_FRAMETAG_LEN]);
1296		bus->nextlen = dptr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET];
1297		if ((bus->nextlen << 4) > MAX_RX_DATASZ) {
1298			brcmf_dbg(INFO, "nextlen too large (%d) seq %d\n",
1299				  bus->nextlen, seq);
1300			bus->nextlen = 0;
1301		}
1302		doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
1303		txmax = SDPCM_WINDOW_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
1304
1305		errcode = 0;
1306		if ((u16)~(sublen ^ check)) {
1307			brcmf_dbg(ERROR, "(superframe): HW hdr error: len/check 0x%04x/0x%04x\n",
1308				  sublen, check);
1309			errcode = -1;
1310		} else if (roundup(sublen, bus->blocksize) != dlen) {
1311			brcmf_dbg(ERROR, "(superframe): len 0x%04x, rounded 0x%04x, expect 0x%04x\n",
1312				  sublen, roundup(sublen, bus->blocksize),
1313				  dlen);
1314			errcode = -1;
1315		} else if (SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]) !=
1316			   SDPCM_GLOM_CHANNEL) {
1317			brcmf_dbg(ERROR, "(superframe): bad channel %d\n",
1318				  SDPCM_PACKET_CHANNEL(
1319					  &dptr[SDPCM_FRAMETAG_LEN]));
1320			errcode = -1;
1321		} else if (SDPCM_GLOMDESC(&dptr[SDPCM_FRAMETAG_LEN])) {
1322			brcmf_dbg(ERROR, "(superframe): got 2nd descriptor?\n");
1323			errcode = -1;
1324		} else if ((doff < SDPCM_HDRLEN) ||
1325			   (doff > (pfirst->len - SDPCM_HDRLEN))) {
1326			brcmf_dbg(ERROR, "(superframe): Bad data offset %d: HW %d pkt %d min %d\n",
1327				  doff, sublen, pfirst->len, SDPCM_HDRLEN);
1328			errcode = -1;
1329		}
1330
1331		/* Check sequence number of superframe SW header */
1332		if (rxseq != seq) {
1333			brcmf_dbg(INFO, "(superframe) rx_seq %d, expected %d\n",
1334				  seq, rxseq);
1335			bus->rx_badseq++;
1336			rxseq = seq;
1337		}
1338
1339		/* Check window for sanity */
1340		if ((u8) (txmax - bus->tx_seq) > 0x40) {
1341			brcmf_dbg(ERROR, "unlikely tx max %d with tx_seq %d\n",
1342				  txmax, bus->tx_seq);
1343			txmax = bus->tx_seq + 2;
1344		}
1345		bus->tx_max = txmax;
1346
1347		/* Remove superframe header, remember offset */
1348		skb_pull(pfirst, doff);
1349		sfdoff = doff;
1350		num = 0;
1351
1352		/* Validate all the subframe headers */
1353		skb_queue_walk(&bus->glom, pnext) {
1354			/* leave when invalid subframe is found */
1355			if (errcode)
1356				break;
1357
1358			dptr = (u8 *) (pnext->data);
1359			dlen = (u16) (pnext->len);
1360			sublen = get_unaligned_le16(dptr);
1361			check = get_unaligned_le16(dptr + sizeof(u16));
1362			chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]);
1363			doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
1364			brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1365					   dptr, 32, "subframe:\n");
1366
1367			if ((u16)~(sublen ^ check)) {
1368				brcmf_dbg(ERROR, "(subframe %d): HW hdr error: len/check 0x%04x/0x%04x\n",
1369					  num, sublen, check);
1370				errcode = -1;
1371			} else if ((sublen > dlen) || (sublen < SDPCM_HDRLEN)) {
1372				brcmf_dbg(ERROR, "(subframe %d): length mismatch: len 0x%04x, expect 0x%04x\n",
1373					  num, sublen, dlen);
1374				errcode = -1;
1375			} else if ((chan != SDPCM_DATA_CHANNEL) &&
1376				   (chan != SDPCM_EVENT_CHANNEL)) {
1377				brcmf_dbg(ERROR, "(subframe %d): bad channel %d\n",
1378					  num, chan);
1379				errcode = -1;
1380			} else if ((doff < SDPCM_HDRLEN) || (doff > sublen)) {
1381				brcmf_dbg(ERROR, "(subframe %d): Bad data offset %d: HW %d min %d\n",
1382					  num, doff, sublen, SDPCM_HDRLEN);
1383				errcode = -1;
1384			}
1385			/* increase the subframe count */
1386			num++;
1387		}
1388
1389		if (errcode) {
1390			/* Terminate frame on error, request
1391				 a couple retries */
1392			if (bus->glomerr++ < 3) {
1393				/* Restore superframe header space */
1394				skb_push(pfirst, sfdoff);
1395				brcmf_sdbrcm_rxfail(bus, true, true);
1396			} else {
1397				bus->glomerr = 0;
1398				brcmf_sdbrcm_rxfail(bus, true, false);
1399				bus->rxglomfail++;
1400				brcmf_sdbrcm_free_glom(bus);
1401			}
1402			bus->nextlen = 0;
1403			return 0;
1404		}
1405
1406		/* Basic SD framing looks ok - process each packet (header) */
1407
1408		skb_queue_walk_safe(&bus->glom, pfirst, pnext) {
1409			dptr = (u8 *) (pfirst->data);
1410			sublen = get_unaligned_le16(dptr);
1411			chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]);
1412			seq = SDPCM_PACKET_SEQUENCE(&dptr[SDPCM_FRAMETAG_LEN]);
1413			doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]);
1414
1415			brcmf_dbg(GLOM, "Get subframe %d, %p(%p/%d), sublen %d chan %d seq %d\n",
1416				  num, pfirst, pfirst->data,
1417				  pfirst->len, sublen, chan, seq);
1418
1419			/* precondition: chan == SDPCM_DATA_CHANNEL ||
1420					 chan == SDPCM_EVENT_CHANNEL */
1421
1422			if (rxseq != seq) {
1423				brcmf_dbg(GLOM, "rx_seq %d, expected %d\n",
1424					  seq, rxseq);
1425				bus->rx_badseq++;
1426				rxseq = seq;
1427			}
1428			rxseq++;
1429
1430			brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
1431					   dptr, dlen, "Rx Subframe Data:\n");
1432
1433			__skb_trim(pfirst, sublen);
1434			skb_pull(pfirst, doff);
1435
1436			if (pfirst->len == 0) {
1437				skb_unlink(pfirst, &bus->glom);
1438				brcmu_pkt_buf_free_skb(pfirst);
1439				continue;
1440			} else if (brcmf_proto_hdrpull(bus->sdiodev->dev,
1441						       &ifidx, pfirst) != 0) {
1442				brcmf_dbg(ERROR, "rx protocol error\n");
1443				bus->sdiodev->bus_if->dstats.rx_errors++;
1444				skb_unlink(pfirst, &bus->glom);
1445				brcmu_pkt_buf_free_skb(pfirst);
1446				continue;
1447			}
1448
1449			brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1450					   pfirst->data,
1451					   min_t(int, pfirst->len, 32),
1452					   "subframe %d to stack, %p (%p/%d) nxt/lnk %p/%p\n",
1453					   bus->glom.qlen, pfirst, pfirst->data,
1454					   pfirst->len, pfirst->next,
1455					   pfirst->prev);
1456		}
1457		/* sent any remaining packets up */
1458		if (bus->glom.qlen) {
1459			up(&bus->sdsem);
1460			brcmf_rx_frame(bus->sdiodev->dev, ifidx, &bus->glom);
1461			down(&bus->sdsem);
1462		}
1463
1464		bus->rxglomframes++;
1465		bus->rxglompkts += bus->glom.qlen;
1466	}
1467	return num;
1468}
1469
1470static int brcmf_sdbrcm_dcmd_resp_wait(struct brcmf_sdio *bus, uint *condition,
1471					bool *pending)
1472{
1473	DECLARE_WAITQUEUE(wait, current);
1474	int timeout = msecs_to_jiffies(DCMD_RESP_TIMEOUT);
1475
1476	/* Wait until control frame is available */
1477	add_wait_queue(&bus->dcmd_resp_wait, &wait);
1478	set_current_state(TASK_INTERRUPTIBLE);
1479
1480	while (!(*condition) && (!signal_pending(current) && timeout))
1481		timeout = schedule_timeout(timeout);
1482
1483	if (signal_pending(current))
1484		*pending = true;
1485
1486	set_current_state(TASK_RUNNING);
1487	remove_wait_queue(&bus->dcmd_resp_wait, &wait);
1488
1489	return timeout;
1490}
1491
1492static int brcmf_sdbrcm_dcmd_resp_wake(struct brcmf_sdio *bus)
1493{
1494	if (waitqueue_active(&bus->dcmd_resp_wait))
1495		wake_up_interruptible(&bus->dcmd_resp_wait);
1496
1497	return 0;
1498}
1499static void
1500brcmf_sdbrcm_read_control(struct brcmf_sdio *bus, u8 *hdr, uint len, uint doff)
1501{
1502	uint rdlen, pad;
1503
1504	int sdret;
1505
1506	brcmf_dbg(TRACE, "Enter\n");
1507
1508	/* Set rxctl for frame (w/optional alignment) */
1509	bus->rxctl = bus->rxbuf;
1510	bus->rxctl += BRCMF_FIRSTREAD;
1511	pad = ((unsigned long)bus->rxctl % BRCMF_SDALIGN);
1512	if (pad)
1513		bus->rxctl += (BRCMF_SDALIGN - pad);
1514	bus->rxctl -= BRCMF_FIRSTREAD;
1515
1516	/* Copy the already-read portion over */
1517	memcpy(bus->rxctl, hdr, BRCMF_FIRSTREAD);
1518	if (len <= BRCMF_FIRSTREAD)
1519		goto gotpkt;
1520
1521	/* Raise rdlen to next SDIO block to avoid tail command */
1522	rdlen = len - BRCMF_FIRSTREAD;
1523	if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) {
1524		pad = bus->blocksize - (rdlen % bus->blocksize);
1525		if ((pad <= bus->roundup) && (pad < bus->blocksize) &&
1526		    ((len + pad) < bus->sdiodev->bus_if->maxctl))
1527			rdlen += pad;
1528	} else if (rdlen % BRCMF_SDALIGN) {
1529		rdlen += BRCMF_SDALIGN - (rdlen % BRCMF_SDALIGN);
1530	}
1531
1532	/* Satisfy length-alignment requirements */
1533	if (rdlen & (ALIGNMENT - 1))
1534		rdlen = roundup(rdlen, ALIGNMENT);
1535
1536	/* Drop if the read is too big or it exceeds our maximum */
1537	if ((rdlen + BRCMF_FIRSTREAD) > bus->sdiodev->bus_if->maxctl) {
1538		brcmf_dbg(ERROR, "%d-byte control read exceeds %d-byte buffer\n",
1539			  rdlen, bus->sdiodev->bus_if->maxctl);
1540		bus->sdiodev->bus_if->dstats.rx_errors++;
1541		brcmf_sdbrcm_rxfail(bus, false, false);
1542		goto done;
1543	}
1544
1545	if ((len - doff) > bus->sdiodev->bus_if->maxctl) {
1546		brcmf_dbg(ERROR, "%d-byte ctl frame (%d-byte ctl data) exceeds %d-byte limit\n",
1547			  len, len - doff, bus->sdiodev->bus_if->maxctl);
1548		bus->sdiodev->bus_if->dstats.rx_errors++;
1549		bus->rx_toolong++;
1550		brcmf_sdbrcm_rxfail(bus, false, false);
1551		goto done;
1552	}
1553
1554	/* Read remainder of frame body into the rxctl buffer */
1555	sdret = brcmf_sdcard_recv_buf(bus->sdiodev,
1556				bus->sdiodev->sbwad,
1557				SDIO_FUNC_2,
1558				F2SYNC, (bus->rxctl + BRCMF_FIRSTREAD), rdlen);
1559	bus->f2rxdata++;
1560
1561	/* Control frame failures need retransmission */
1562	if (sdret < 0) {
1563		brcmf_dbg(ERROR, "read %d control bytes failed: %d\n",
1564			  rdlen, sdret);
1565		bus->rxc_errors++;
1566		brcmf_sdbrcm_rxfail(bus, true, true);
1567		goto done;
1568	}
1569
1570gotpkt:
1571
1572	brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_CTL_ON(),
1573			   bus->rxctl, len, "RxCtrl:\n");
1574
1575	/* Point to valid data and indicate its length */
1576	bus->rxctl += doff;
1577	bus->rxlen = len - doff;
1578
1579done:
1580	/* Awake any waiters */
1581	brcmf_sdbrcm_dcmd_resp_wake(bus);
1582}
1583
1584/* Pad read to blocksize for efficiency */
1585static void brcmf_pad(struct brcmf_sdio *bus, u16 *pad, u16 *rdlen)
1586{
1587	if (bus->roundup && bus->blocksize && *rdlen > bus->blocksize) {
1588		*pad = bus->blocksize - (*rdlen % bus->blocksize);
1589		if (*pad <= bus->roundup && *pad < bus->blocksize &&
1590		    *rdlen + *pad + BRCMF_FIRSTREAD < MAX_RX_DATASZ)
1591			*rdlen += *pad;
1592	} else if (*rdlen % BRCMF_SDALIGN) {
1593		*rdlen += BRCMF_SDALIGN - (*rdlen % BRCMF_SDALIGN);
1594	}
1595}
1596
1597static void
1598brcmf_alloc_pkt_and_read(struct brcmf_sdio *bus, u16 rdlen,
1599			 struct sk_buff **pkt, u8 **rxbuf)
1600{
1601	int sdret;		/* Return code from calls */
1602
1603	*pkt = brcmu_pkt_buf_get_skb(rdlen + BRCMF_SDALIGN);
1604	if (*pkt == NULL)
1605		return;
1606
1607	pkt_align(*pkt, rdlen, BRCMF_SDALIGN);
1608	*rxbuf = (u8 *) ((*pkt)->data);
1609	/* Read the entire frame */
1610	sdret = brcmf_sdcard_recv_pkt(bus->sdiodev, bus->sdiodev->sbwad,
1611				      SDIO_FUNC_2, F2SYNC, *pkt);
1612	bus->f2rxdata++;
1613
1614	if (sdret < 0) {
1615		brcmf_dbg(ERROR, "(nextlen): read %d bytes failed: %d\n",
1616			  rdlen, sdret);
1617		brcmu_pkt_buf_free_skb(*pkt);
1618		bus->sdiodev->bus_if->dstats.rx_errors++;
1619		/* Force retry w/normal header read.
1620		 * Don't attempt NAK for
1621		 * gSPI
1622		 */
1623		brcmf_sdbrcm_rxfail(bus, true, true);
1624		*pkt = NULL;
1625	}
1626}
1627
1628/* Checks the header */
1629static int
1630brcmf_check_rxbuf(struct brcmf_sdio *bus, struct sk_buff *pkt, u8 *rxbuf,
1631		  u8 rxseq, u16 nextlen, u16 *len)
1632{
1633	u16 check;
1634	bool len_consistent;	/* Result of comparing readahead len and
1635				   len from hw-hdr */
1636
1637	memcpy(bus->rxhdr, rxbuf, SDPCM_HDRLEN);
1638
1639	/* Extract hardware header fields */
1640	*len = get_unaligned_le16(bus->rxhdr);
1641	check = get_unaligned_le16(bus->rxhdr + sizeof(u16));
1642
1643	/* All zeros means readahead info was bad */
1644	if (!(*len | check)) {
1645		brcmf_dbg(INFO, "(nextlen): read zeros in HW header???\n");
1646		goto fail;
1647	}
1648
1649	/* Validate check bytes */
1650	if ((u16)~(*len ^ check)) {
1651		brcmf_dbg(ERROR, "(nextlen): HW hdr error: nextlen/len/check 0x%04x/0x%04x/0x%04x\n",
1652			  nextlen, *len, check);
1653		bus->rx_badhdr++;
1654		brcmf_sdbrcm_rxfail(bus, false, false);
1655		goto fail;
1656	}
1657
1658	/* Validate frame length */
1659	if (*len < SDPCM_HDRLEN) {
1660		brcmf_dbg(ERROR, "(nextlen): HW hdr length invalid: %d\n",
1661			  *len);
1662		goto fail;
1663	}
1664
1665	/* Check for consistency with readahead info */
1666	len_consistent = (nextlen != (roundup(*len, 16) >> 4));
1667	if (len_consistent) {
1668		/* Mismatch, force retry w/normal
1669			header (may be >4K) */
1670		brcmf_dbg(ERROR, "(nextlen): mismatch, nextlen %d len %d rnd %d; expected rxseq %d\n",
1671			  nextlen, *len, roundup(*len, 16),
1672			  rxseq);
1673		brcmf_sdbrcm_rxfail(bus, true, true);
1674		goto fail;
1675	}
1676
1677	return 0;
1678
1679fail:
1680	brcmf_sdbrcm_pktfree2(bus, pkt);
1681	return -EINVAL;
1682}
1683
1684/* Return true if there may be more frames to read */
1685static uint
1686brcmf_sdbrcm_readframes(struct brcmf_sdio *bus, uint maxframes, bool *finished)
1687{
1688	u16 len, check;	/* Extracted hardware header fields */
1689	u8 chan, seq, doff;	/* Extracted software header fields */
1690	u8 fcbits;		/* Extracted fcbits from software header */
1691
1692	struct sk_buff *pkt;		/* Packet for event or data frames */
1693	u16 pad;		/* Number of pad bytes to read */
1694	u16 rdlen;		/* Total number of bytes to read */
1695	u8 rxseq;		/* Next sequence number to expect */
1696	uint rxleft = 0;	/* Remaining number of frames allowed */
1697	int sdret;		/* Return code from calls */
1698	u8 txmax;		/* Maximum tx sequence offered */
1699	u8 *rxbuf;
1700	int ifidx = 0;
1701	uint rxcount = 0;	/* Total frames read */
1702
1703	brcmf_dbg(TRACE, "Enter\n");
1704
1705	/* Not finished unless we encounter no more frames indication */
1706	*finished = false;
1707
1708	for (rxseq = bus->rx_seq, rxleft = maxframes;
1709	     !bus->rxskip && rxleft &&
1710	     bus->sdiodev->bus_if->state != BRCMF_BUS_DOWN;
1711	     rxseq++, rxleft--) {
1712
1713		/* Handle glomming separately */
1714		if (bus->glomd || !skb_queue_empty(&bus->glom)) {
1715			u8 cnt;
1716			brcmf_dbg(GLOM, "calling rxglom: glomd %p, glom %p\n",
1717				  bus->glomd, skb_peek(&bus->glom));
1718			cnt = brcmf_sdbrcm_rxglom(bus, rxseq);
1719			brcmf_dbg(GLOM, "rxglom returned %d\n", cnt);
1720			rxseq += cnt - 1;
1721			rxleft = (rxleft > cnt) ? (rxleft - cnt) : 1;
1722			continue;
1723		}
1724
1725		/* Try doing single read if we can */
1726		if (bus->nextlen) {
1727			u16 nextlen = bus->nextlen;
1728			bus->nextlen = 0;
1729
1730			rdlen = len = nextlen << 4;
1731			brcmf_pad(bus, &pad, &rdlen);
1732
1733			/*
1734			 * After the frame is received we have to
1735			 * distinguish whether it is data
1736			 * or non-data frame.
1737			 */
1738			brcmf_alloc_pkt_and_read(bus, rdlen, &pkt, &rxbuf);
1739			if (pkt == NULL) {
1740				/* Give up on data, request rtx of events */
1741				brcmf_dbg(ERROR, "(nextlen): brcmf_alloc_pkt_and_read failed: len %d rdlen %d expected rxseq %d\n",
1742					  len, rdlen, rxseq);
1743				continue;
1744			}
1745
1746			if (brcmf_check_rxbuf(bus, pkt, rxbuf, rxseq, nextlen,
1747					      &len) < 0)
1748				continue;
1749
1750			/* Extract software header fields */
1751			chan = SDPCM_PACKET_CHANNEL(
1752					&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1753			seq = SDPCM_PACKET_SEQUENCE(
1754					&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1755			doff = SDPCM_DOFFSET_VALUE(
1756					&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1757			txmax = SDPCM_WINDOW_VALUE(
1758					&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1759
1760			bus->nextlen =
1761			    bus->rxhdr[SDPCM_FRAMETAG_LEN +
1762				       SDPCM_NEXTLEN_OFFSET];
1763			if ((bus->nextlen << 4) > MAX_RX_DATASZ) {
1764				brcmf_dbg(INFO, "(nextlen): got frame w/nextlen too large (%d), seq %d\n",
1765					  bus->nextlen, seq);
1766				bus->nextlen = 0;
1767			}
1768
1769			bus->rx_readahead_cnt++;
1770
1771			/* Handle Flow Control */
1772			fcbits = SDPCM_FCMASK_VALUE(
1773					&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1774
1775			if (bus->flowcontrol != fcbits) {
1776				if (~bus->flowcontrol & fcbits)
1777					bus->fc_xoff++;
1778
1779				if (bus->flowcontrol & ~fcbits)
1780					bus->fc_xon++;
1781
1782				bus->fc_rcvd++;
1783				bus->flowcontrol = fcbits;
1784			}
1785
1786			/* Check and update sequence number */
1787			if (rxseq != seq) {
1788				brcmf_dbg(INFO, "(nextlen): rx_seq %d, expected %d\n",
1789					  seq, rxseq);
1790				bus->rx_badseq++;
1791				rxseq = seq;
1792			}
1793
1794			/* Check window for sanity */
1795			if ((u8) (txmax - bus->tx_seq) > 0x40) {
1796				brcmf_dbg(ERROR, "got unlikely tx max %d with tx_seq %d\n",
1797					  txmax, bus->tx_seq);
1798				txmax = bus->tx_seq + 2;
1799			}
1800			bus->tx_max = txmax;
1801
1802			brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
1803					   rxbuf, len, "Rx Data:\n");
1804			brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() &&
1805					     BRCMF_DATA_ON()) &&
1806					   BRCMF_HDRS_ON(),
1807					   bus->rxhdr, SDPCM_HDRLEN,
1808					   "RxHdr:\n");
1809
1810			if (chan == SDPCM_CONTROL_CHANNEL) {
1811				brcmf_dbg(ERROR, "(nextlen): readahead on control packet %d?\n",
1812					  seq);
1813				/* Force retry w/normal header read */
1814				bus->nextlen = 0;
1815				brcmf_sdbrcm_rxfail(bus, false, true);
1816				brcmf_sdbrcm_pktfree2(bus, pkt);
1817				continue;
1818			}
1819
1820			/* Validate data offset */
1821			if ((doff < SDPCM_HDRLEN) || (doff > len)) {
1822				brcmf_dbg(ERROR, "(nextlen): bad data offset %d: HW len %d min %d\n",
1823					  doff, len, SDPCM_HDRLEN);
1824				brcmf_sdbrcm_rxfail(bus, false, false);
1825				brcmf_sdbrcm_pktfree2(bus, pkt);
1826				continue;
1827			}
1828
1829			/* All done with this one -- now deliver the packet */
1830			goto deliver;
1831		}
1832
1833		/* Read frame header (hardware and software) */
1834		sdret = brcmf_sdcard_recv_buf(bus->sdiodev, bus->sdiodev->sbwad,
1835					      SDIO_FUNC_2, F2SYNC, bus->rxhdr,
1836					      BRCMF_FIRSTREAD);
1837		bus->f2rxhdrs++;
1838
1839		if (sdret < 0) {
1840			brcmf_dbg(ERROR, "RXHEADER FAILED: %d\n", sdret);
1841			bus->rx_hdrfail++;
1842			brcmf_sdbrcm_rxfail(bus, true, true);
1843			continue;
1844		}
1845		brcmf_dbg_hex_dump(BRCMF_BYTES_ON() || BRCMF_HDRS_ON(),
1846				   bus->rxhdr, SDPCM_HDRLEN, "RxHdr:\n");
1847
1848
1849		/* Extract hardware header fields */
1850		len = get_unaligned_le16(bus->rxhdr);
1851		check = get_unaligned_le16(bus->rxhdr + sizeof(u16));
1852
1853		/* All zeros means no more frames */
1854		if (!(len | check)) {
1855			*finished = true;
1856			break;
1857		}
1858
1859		/* Validate check bytes */
1860		if ((u16) ~(len ^ check)) {
1861			brcmf_dbg(ERROR, "HW hdr err: len/check 0x%04x/0x%04x\n",
1862				  len, check);
1863			bus->rx_badhdr++;
1864			brcmf_sdbrcm_rxfail(bus, false, false);
1865			continue;
1866		}
1867
1868		/* Validate frame length */
1869		if (len < SDPCM_HDRLEN) {
1870			brcmf_dbg(ERROR, "HW hdr length invalid: %d\n", len);
1871			continue;
1872		}
1873
1874		/* Extract software header fields */
1875		chan = SDPCM_PACKET_CHANNEL(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1876		seq = SDPCM_PACKET_SEQUENCE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1877		doff = SDPCM_DOFFSET_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1878		txmax = SDPCM_WINDOW_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1879
1880		/* Validate data offset */
1881		if ((doff < SDPCM_HDRLEN) || (doff > len)) {
1882			brcmf_dbg(ERROR, "Bad data offset %d: HW len %d, min %d seq %d\n",
1883				  doff, len, SDPCM_HDRLEN, seq);
1884			bus->rx_badhdr++;
1885			brcmf_sdbrcm_rxfail(bus, false, false);
1886			continue;
1887		}
1888
1889		/* Save the readahead length if there is one */
1890		bus->nextlen =
1891		    bus->rxhdr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET];
1892		if ((bus->nextlen << 4) > MAX_RX_DATASZ) {
1893			brcmf_dbg(INFO, "(nextlen): got frame w/nextlen too large (%d), seq %d\n",
1894				  bus->nextlen, seq);
1895			bus->nextlen = 0;
1896		}
1897
1898		/* Handle Flow Control */
1899		fcbits = SDPCM_FCMASK_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]);
1900
1901		if (bus->flowcontrol != fcbits) {
1902			if (~bus->flowcontrol & fcbits)
1903				bus->fc_xoff++;
1904
1905			if (bus->flowcontrol & ~fcbits)
1906				bus->fc_xon++;
1907
1908			bus->fc_rcvd++;
1909			bus->flowcontrol = fcbits;
1910		}
1911
1912		/* Check and update sequence number */
1913		if (rxseq != seq) {
1914			brcmf_dbg(INFO, "rx_seq %d, expected %d\n", seq, rxseq);
1915			bus->rx_badseq++;
1916			rxseq = seq;
1917		}
1918
1919		/* Check window for sanity */
1920		if ((u8) (txmax - bus->tx_seq) > 0x40) {
1921			brcmf_dbg(ERROR, "unlikely tx max %d with tx_seq %d\n",
1922				  txmax, bus->tx_seq);
1923			txmax = bus->tx_seq + 2;
1924		}
1925		bus->tx_max = txmax;
1926
1927		/* Call a separate function for control frames */
1928		if (chan == SDPCM_CONTROL_CHANNEL) {
1929			brcmf_sdbrcm_read_control(bus, bus->rxhdr, len, doff);
1930			continue;
1931		}
1932
1933		/* precondition: chan is either SDPCM_DATA_CHANNEL,
1934		   SDPCM_EVENT_CHANNEL, SDPCM_TEST_CHANNEL or
1935		   SDPCM_GLOM_CHANNEL */
1936
1937		/* Length to read */
1938		rdlen = (len > BRCMF_FIRSTREAD) ? (len - BRCMF_FIRSTREAD) : 0;
1939
1940		/* May pad read to blocksize for efficiency */
1941		if (bus->roundup && bus->blocksize &&
1942			(rdlen > bus->blocksize)) {
1943			pad = bus->blocksize - (rdlen % bus->blocksize);
1944			if ((pad <= bus->roundup) && (pad < bus->blocksize) &&
1945			    ((rdlen + pad + BRCMF_FIRSTREAD) < MAX_RX_DATASZ))
1946				rdlen += pad;
1947		} else if (rdlen % BRCMF_SDALIGN) {
1948			rdlen += BRCMF_SDALIGN - (rdlen % BRCMF_SDALIGN);
1949		}
1950
1951		/* Satisfy length-alignment requirements */
1952		if (rdlen & (ALIGNMENT - 1))
1953			rdlen = roundup(rdlen, ALIGNMENT);
1954
1955		if ((rdlen + BRCMF_FIRSTREAD) > MAX_RX_DATASZ) {
1956			/* Too long -- skip this frame */
1957			brcmf_dbg(ERROR, "too long: len %d rdlen %d\n",
1958				  len, rdlen);
1959			bus->sdiodev->bus_if->dstats.rx_errors++;
1960			bus->rx_toolong++;
1961			brcmf_sdbrcm_rxfail(bus, false, false);
1962			continue;
1963		}
1964
1965		pkt = brcmu_pkt_buf_get_skb(rdlen +
1966					    BRCMF_FIRSTREAD + BRCMF_SDALIGN);
1967		if (!pkt) {
1968			/* Give up on data, request rtx of events */
1969			brcmf_dbg(ERROR, "brcmu_pkt_buf_get_skb failed: rdlen %d chan %d\n",
1970				  rdlen, chan);
1971			bus->sdiodev->bus_if->dstats.rx_dropped++;
1972			brcmf_sdbrcm_rxfail(bus, false, RETRYCHAN(chan));
1973			continue;
1974		}
1975
1976		/* Leave room for what we already read, and align remainder */
1977		skb_pull(pkt, BRCMF_FIRSTREAD);
1978		pkt_align(pkt, rdlen, BRCMF_SDALIGN);
1979
1980		/* Read the remaining frame data */
1981		sdret = brcmf_sdcard_recv_pkt(bus->sdiodev, bus->sdiodev->sbwad,
1982					      SDIO_FUNC_2, F2SYNC, pkt);
1983		bus->f2rxdata++;
1984
1985		if (sdret < 0) {
1986			brcmf_dbg(ERROR, "read %d %s bytes failed: %d\n", rdlen,
1987				  ((chan == SDPCM_EVENT_CHANNEL) ? "event"
1988				   : ((chan == SDPCM_DATA_CHANNEL) ? "data"
1989				      : "test")), sdret);
1990			brcmu_pkt_buf_free_skb(pkt);
1991			bus->sdiodev->bus_if->dstats.rx_errors++;
1992			brcmf_sdbrcm_rxfail(bus, true, RETRYCHAN(chan));
1993			continue;
1994		}
1995
1996		/* Copy the already-read portion */
1997		skb_push(pkt, BRCMF_FIRSTREAD);
1998		memcpy(pkt->data, bus->rxhdr, BRCMF_FIRSTREAD);
1999
2000		brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
2001				   pkt->data, len, "Rx Data:\n");
2002
2003deliver:
2004		/* Save superframe descriptor and allocate packet frame */
2005		if (chan == SDPCM_GLOM_CHANNEL) {
2006			if (SDPCM_GLOMDESC(&bus->rxhdr[SDPCM_FRAMETAG_LEN])) {
2007				brcmf_dbg(GLOM, "glom descriptor, %d bytes:\n",
2008					  len);
2009				brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
2010						   pkt->data, len,
2011						   "Glom Data:\n");
2012				__skb_trim(pkt, len);
2013				skb_pull(pkt, SDPCM_HDRLEN);
2014				bus->glomd = pkt;
2015			} else {
2016				brcmf_dbg(ERROR, "%s: glom superframe w/o "
2017					  "descriptor!\n", __func__);
2018				brcmf_sdbrcm_rxfail(bus, false, false);
2019			}
2020			continue;
2021		}
2022
2023		/* Fill in packet len and prio, deliver upward */
2024		__skb_trim(pkt, len);
2025		skb_pull(pkt, doff);
2026
2027		if (pkt->len == 0) {
2028			brcmu_pkt_buf_free_skb(pkt);
2029			continue;
2030		} else if (brcmf_proto_hdrpull(bus->sdiodev->dev, &ifidx,
2031			   pkt) != 0) {
2032			brcmf_dbg(ERROR, "rx protocol error\n");
2033			brcmu_pkt_buf_free_skb(pkt);
2034			bus->sdiodev->bus_if->dstats.rx_errors++;
2035			continue;
2036		}
2037
2038		/* Unlock during rx call */
2039		up(&bus->sdsem);
2040		brcmf_rx_packet(bus->sdiodev->dev, ifidx, pkt);
2041		down(&bus->sdsem);
2042	}
2043	rxcount = maxframes - rxleft;
2044	/* Message if we hit the limit */
2045	if (!rxleft)
2046		brcmf_dbg(DATA, "hit rx limit of %d frames\n",
2047			  maxframes);
2048	else
2049		brcmf_dbg(DATA, "processed %d frames\n", rxcount);
2050	/* Back off rxseq if awaiting rtx, update rx_seq */
2051	if (bus->rxskip)
2052		rxseq--;
2053	bus->rx_seq = rxseq;
2054
2055	return rxcount;
2056}
2057
2058static void
2059brcmf_sdbrcm_wait_for_event(struct brcmf_sdio *bus, bool *lockvar)
2060{
2061	up(&bus->sdsem);
2062	wait_event_interruptible_timeout(bus->ctrl_wait, !*lockvar, HZ * 2);
2063	down(&bus->sdsem);
2064	return;
2065}
2066
2067static void
2068brcmf_sdbrcm_wait_event_wakeup(struct brcmf_sdio *bus)
2069{
2070	if (waitqueue_active(&bus->ctrl_wait))
2071		wake_up_interruptible(&bus->ctrl_wait);
2072	return;
2073}
2074
2075/* Writes a HW/SW header into the packet and sends it. */
2076/* Assumes: (a) header space already there, (b) caller holds lock */
2077static int brcmf_sdbrcm_txpkt(struct brcmf_sdio *bus, struct sk_buff *pkt,
2078			      uint chan, bool free_pkt)
2079{
2080	int ret;
2081	u8 *frame;
2082	u16 len, pad = 0;
2083	u32 swheader;
2084	struct sk_buff *new;
2085	int i;
2086
2087	brcmf_dbg(TRACE, "Enter\n");
2088
2089	frame = (u8 *) (pkt->data);
2090
2091	/* Add alignment padding, allocate new packet if needed */
2092	pad = ((unsigned long)frame % BRCMF_SDALIGN);
2093	if (pad) {
2094		if (skb_headroom(pkt) < pad) {
2095			brcmf_dbg(INFO, "insufficient headroom %d for %d pad\n",
2096				  skb_headroom(pkt), pad);
2097			bus->sdiodev->bus_if->tx_realloc++;
2098			new = brcmu_pkt_buf_get_skb(pkt->len + BRCMF_SDALIGN);
2099			if (!new) {
2100				brcmf_dbg(ERROR, "couldn't allocate new %d-byte packet\n",
2101					  pkt->len + BRCMF_SDALIGN);
2102				ret = -ENOMEM;
2103				goto done;
2104			}
2105
2106			pkt_align(new, pkt->len, BRCMF_SDALIGN);
2107			memcpy(new->data, pkt->data, pkt->len);
2108			if (free_pkt)
2109				brcmu_pkt_buf_free_skb(pkt);
2110			/* free the pkt if canned one is not used */
2111			free_pkt = true;
2112			pkt = new;
2113			frame = (u8 *) (pkt->data);
2114			/* precondition: (frame % BRCMF_SDALIGN) == 0) */
2115			pad = 0;
2116		} else {
2117			skb_push(pkt, pad);
2118			frame = (u8 *) (pkt->data);
2119			/* precondition: pad + SDPCM_HDRLEN <= pkt->len */
2120			memset(frame, 0, pad + SDPCM_HDRLEN);
2121		}
2122	}
2123	/* precondition: pad < BRCMF_SDALIGN */
2124
2125	/* Hardware tag: 2 byte len followed by 2 byte ~len check (all LE) */
2126	len = (u16) (pkt->len);
2127	*(__le16 *) frame = cpu_to_le16(len);
2128	*(((__le16 *) frame) + 1) = cpu_to_le16(~len);
2129
2130	/* Software tag: channel, sequence number, data offset */
2131	swheader =
2132	    ((chan << SDPCM_CHANNEL_SHIFT) & SDPCM_CHANNEL_MASK) | bus->tx_seq |
2133	    (((pad +
2134	       SDPCM_HDRLEN) << SDPCM_DOFFSET_SHIFT) & SDPCM_DOFFSET_MASK);
2135
2136	put_unaligned_le32(swheader, frame + SDPCM_FRAMETAG_LEN);
2137	put_unaligned_le32(0, frame + SDPCM_FRAMETAG_LEN + sizeof(swheader));
2138
2139#ifdef DEBUG
2140	tx_packets[pkt->priority]++;
2141#endif
2142
2143	brcmf_dbg_hex_dump(BRCMF_BYTES_ON() &&
2144			   ((BRCMF_CTL_ON() && chan == SDPCM_CONTROL_CHANNEL) ||
2145			    (BRCMF_DATA_ON() && chan != SDPCM_CONTROL_CHANNEL)),
2146			   frame, len, "Tx Frame:\n");
2147	brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() &&
2148			     ((BRCMF_CTL_ON() &&
2149			       chan == SDPCM_CONTROL_CHANNEL) ||
2150			      (BRCMF_DATA_ON() &&
2151			       chan != SDPCM_CONTROL_CHANNEL))) &&
2152			   BRCMF_HDRS_ON(),
2153			   frame, min_t(u16, len, 16), "TxHdr:\n");
2154
2155	/* Raise len to next SDIO block to eliminate tail command */
2156	if (bus->roundup && bus->blocksize && (len > bus->blocksize)) {
2157		u16 pad = bus->blocksize - (len % bus->blocksize);
2158		if ((pad <= bus->roundup) && (pad < bus->blocksize))
2159				len += pad;
2160	} else if (len % BRCMF_SDALIGN) {
2161		len += BRCMF_SDALIGN - (len % BRCMF_SDALIGN);
2162	}
2163
2164	/* Some controllers have trouble with odd bytes -- round to even */
2165	if (len & (ALIGNMENT - 1))
2166			len = roundup(len, ALIGNMENT);
2167
2168	ret = brcmf_sdcard_send_pkt(bus->sdiodev, bus->sdiodev->sbwad,
2169				    SDIO_FUNC_2, F2SYNC, pkt);
2170	bus->f2txdata++;
2171
2172	if (ret < 0) {
2173		/* On failure, abort the command and terminate the frame */
2174		brcmf_dbg(INFO, "sdio error %d, abort command and terminate frame\n",
2175			  ret);
2176		bus->tx_sderrs++;
2177
2178		brcmf_sdcard_abort(bus->sdiodev, SDIO_FUNC_2);
2179		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
2180				 SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM,
2181				 NULL);
2182		bus->f1regdata++;
2183
2184		for (i = 0; i < 3; i++) {
2185			u8 hi, lo;
2186			hi = brcmf_sdcard_cfg_read(bus->sdiodev,
2187					     SDIO_FUNC_1,
2188					     SBSDIO_FUNC1_WFRAMEBCHI,
2189					     NULL);
2190			lo = brcmf_sdcard_cfg_read(bus->sdiodev,
2191					     SDIO_FUNC_1,
2192					     SBSDIO_FUNC1_WFRAMEBCLO,
2193					     NULL);
2194			bus->f1regdata += 2;
2195			if ((hi == 0) && (lo == 0))
2196				break;
2197		}
2198
2199	}
2200	if (ret == 0)
2201		bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP;
2202
2203done:
2204	/* restore pkt buffer pointer before calling tx complete routine */
2205	skb_pull(pkt, SDPCM_HDRLEN + pad);
2206	up(&bus->sdsem);
2207	brcmf_txcomplete(bus->sdiodev->dev, pkt, ret != 0);
2208	down(&bus->sdsem);
2209
2210	if (free_pkt)
2211		brcmu_pkt_buf_free_skb(pkt);
2212
2213	return ret;
2214}
2215
2216static uint brcmf_sdbrcm_sendfromq(struct brcmf_sdio *bus, uint maxframes)
2217{
2218	struct sk_buff *pkt;
2219	u32 intstatus = 0;
2220	uint retries = 0;
2221	int ret = 0, prec_out;
2222	uint cnt = 0;
2223	uint datalen;
2224	u8 tx_prec_map;
2225
2226	brcmf_dbg(TRACE, "Enter\n");
2227
2228	tx_prec_map = ~bus->flowcontrol;
2229
2230	/* Send frames until the limit or some other event */
2231	for (cnt = 0; (cnt < maxframes) && data_ok(bus); cnt++) {
2232		spin_lock_bh(&bus->txqlock);
2233		pkt = brcmu_pktq_mdeq(&bus->txq, tx_prec_map, &prec_out);
2234		if (pkt == NULL) {
2235			spin_unlock_bh(&bus->txqlock);
2236			break;
2237		}
2238		spin_unlock_bh(&bus->txqlock);
2239		datalen = pkt->len - SDPCM_HDRLEN;
2240
2241		ret = brcmf_sdbrcm_txpkt(bus, pkt, SDPCM_DATA_CHANNEL, true);
2242		if (ret)
2243			bus->sdiodev->bus_if->dstats.tx_errors++;
2244		else
2245			bus->sdiodev->bus_if->dstats.tx_bytes += datalen;
2246
2247		/* In poll mode, need to check for other events */
2248		if (!bus->intr && cnt) {
2249			/* Check device status, signal pending interrupt */
2250			r_sdreg32(bus, &intstatus,
2251				  offsetof(struct sdpcmd_regs, intstatus),
2252				  &retries);
2253			bus->f2txdata++;
2254			if (brcmf_sdcard_regfail(bus->sdiodev))
2255				break;
2256			if (intstatus & bus->hostintmask)
2257				bus->ipend = true;
2258		}
2259	}
2260
2261	/* Deflow-control stack if needed */
2262	if (bus->sdiodev->bus_if->drvr_up &&
2263	    (bus->sdiodev->bus_if->state == BRCMF_BUS_DATA) &&
2264	    bus->txoff && (pktq_len(&bus->txq) < TXLOW)) {
2265		bus->txoff = OFF;
2266		brcmf_txflowcontrol(bus->sdiodev->dev, 0, OFF);
2267	}
2268
2269	return cnt;
2270}
2271
2272static void brcmf_sdbrcm_bus_stop(struct device *dev)
2273{
2274	u32 local_hostintmask;
2275	u8 saveclk;
2276	uint retries;
2277	int err;
2278	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2279	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv;
2280	struct brcmf_sdio *bus = sdiodev->bus;
2281
2282	brcmf_dbg(TRACE, "Enter\n");
2283
2284	if (bus->watchdog_tsk) {
2285		send_sig(SIGTERM, bus->watchdog_tsk, 1);
2286		kthread_stop(bus->watchdog_tsk);
2287		bus->watchdog_tsk = NULL;
2288	}
2289
2290	if (bus->dpc_tsk && bus->dpc_tsk != current) {
2291		send_sig(SIGTERM, bus->dpc_tsk, 1);
2292		kthread_stop(bus->dpc_tsk);
2293		bus->dpc_tsk = NULL;
2294	}
2295
2296	down(&bus->sdsem);
2297
2298	bus_wake(bus);
2299
2300	/* Enable clock for device interrupts */
2301	brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
2302
2303	/* Disable and clear interrupts at the chip level also */
2304	w_sdreg32(bus, 0, offsetof(struct sdpcmd_regs, hostintmask), &retries);
2305	local_hostintmask = bus->hostintmask;
2306	bus->hostintmask = 0;
2307
2308	/* Change our idea of bus state */
2309	bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
2310
2311	/* Force clocks on backplane to be sure F2 interrupt propagates */
2312	saveclk = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
2313					SBSDIO_FUNC1_CHIPCLKCSR, &err);
2314	if (!err) {
2315		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
2316				       SBSDIO_FUNC1_CHIPCLKCSR,
2317				       (saveclk | SBSDIO_FORCE_HT), &err);
2318	}
2319	if (err)
2320		brcmf_dbg(ERROR, "Failed to force clock for F2: err %d\n", err);
2321
2322	/* Turn off the bus (F2), free any pending packets */
2323	brcmf_dbg(INTR, "disable SDIO interrupts\n");
2324	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_0, SDIO_CCCR_IOEx,
2325			 SDIO_FUNC_ENABLE_1, NULL);
2326
2327	/* Clear any pending interrupts now that F2 is disabled */
2328	w_sdreg32(bus, local_hostintmask,
2329		  offsetof(struct sdpcmd_regs, intstatus), &retries);
2330
2331	/* Turn off the backplane clock (only) */
2332	brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
2333
2334	/* Clear the data packet queues */
2335	brcmu_pktq_flush(&bus->txq, true, NULL, NULL);
2336
2337	/* Clear any held glomming stuff */
2338	if (bus->glomd)
2339		brcmu_pkt_buf_free_skb(bus->glomd);
2340	brcmf_sdbrcm_free_glom(bus);
2341
2342	/* Clear rx control and wake any waiters */
2343	bus->rxlen = 0;
2344	brcmf_sdbrcm_dcmd_resp_wake(bus);
2345
2346	/* Reset some F2 state stuff */
2347	bus->rxskip = false;
2348	bus->tx_seq = bus->rx_seq = 0;
2349
2350	up(&bus->sdsem);
2351}
2352
2353static bool brcmf_sdbrcm_dpc(struct brcmf_sdio *bus)
2354{
2355	u32 intstatus, newstatus = 0;
2356	uint retries = 0;
2357	uint rxlimit = bus->rxbound;	/* Rx frames to read before resched */
2358	uint txlimit = bus->txbound;	/* Tx frames to send before resched */
2359	uint framecnt = 0;	/* Temporary counter of tx/rx frames */
2360	bool rxdone = true;	/* Flag for no more read data */
2361	bool resched = false;	/* Flag indicating resched wanted */
2362
2363	brcmf_dbg(TRACE, "Enter\n");
2364
2365	/* Start with leftover status bits */
2366	intstatus = bus->intstatus;
2367
2368	down(&bus->sdsem);
2369
2370	/* If waiting for HTAVAIL, check status */
2371	if (bus->clkstate == CLK_PENDING) {
2372		int err;
2373		u8 clkctl, devctl = 0;
2374
2375#ifdef DEBUG
2376		/* Check for inconsistent device control */
2377		devctl = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
2378					       SBSDIO_DEVICE_CTL, &err);
2379		if (err) {
2380			brcmf_dbg(ERROR, "error reading DEVCTL: %d\n", err);
2381			bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
2382		}
2383#endif				/* DEBUG */
2384
2385		/* Read CSR, if clock on switch to AVAIL, else ignore */
2386		clkctl = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
2387					       SBSDIO_FUNC1_CHIPCLKCSR, &err);
2388		if (err) {
2389			brcmf_dbg(ERROR, "error reading CSR: %d\n",
2390				  err);
2391			bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
2392		}
2393
2394		brcmf_dbg(INFO, "DPC: PENDING, devctl 0x%02x clkctl 0x%02x\n",
2395			  devctl, clkctl);
2396
2397		if (SBSDIO_HTAV(clkctl)) {
2398			devctl = brcmf_sdcard_cfg_read(bus->sdiodev,
2399						       SDIO_FUNC_1,
2400						       SBSDIO_DEVICE_CTL, &err);
2401			if (err) {
2402				brcmf_dbg(ERROR, "error reading DEVCTL: %d\n",
2403					  err);
2404				bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
2405			}
2406			devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
2407			brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
2408				SBSDIO_DEVICE_CTL, devctl, &err);
2409			if (err) {
2410				brcmf_dbg(ERROR, "error writing DEVCTL: %d\n",
2411					  err);
2412				bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
2413			}
2414			bus->clkstate = CLK_AVAIL;
2415		} else {
2416			goto clkwait;
2417		}
2418	}
2419
2420	bus_wake(bus);
2421
2422	/* Make sure backplane clock is on */
2423	brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, true);
2424	if (bus->clkstate == CLK_PENDING)
2425		goto clkwait;
2426
2427	/* Pending interrupt indicates new device status */
2428	if (bus->ipend) {
2429		bus->ipend = false;
2430		r_sdreg32(bus, &newstatus,
2431			  offsetof(struct sdpcmd_regs, intstatus), &retries);
2432		bus->f1regdata++;
2433		if (brcmf_sdcard_regfail(bus->sdiodev))
2434			newstatus = 0;
2435		newstatus &= bus->hostintmask;
2436		bus->fcstate = !!(newstatus & I_HMB_FC_STATE);
2437		if (newstatus) {
2438			w_sdreg32(bus, newstatus,
2439				  offsetof(struct sdpcmd_regs, intstatus),
2440				  &retries);
2441			bus->f1regdata++;
2442		}
2443	}
2444
2445	/* Merge new bits with previous */
2446	intstatus |= newstatus;
2447	bus->intstatus = 0;
2448
2449	/* Handle flow-control change: read new state in case our ack
2450	 * crossed another change interrupt.  If change still set, assume
2451	 * FC ON for safety, let next loop through do the debounce.
2452	 */
2453	if (intstatus & I_HMB_FC_CHANGE) {
2454		intstatus &= ~I_HMB_FC_CHANGE;
2455		w_sdreg32(bus, I_HMB_FC_CHANGE,
2456			  offsetof(struct sdpcmd_regs, intstatus), &retries);
2457
2458		r_sdreg32(bus, &newstatus,
2459			  offsetof(struct sdpcmd_regs, intstatus), &retries);
2460		bus->f1regdata += 2;
2461		bus->fcstate =
2462		    !!(newstatus & (I_HMB_FC_STATE | I_HMB_FC_CHANGE));
2463		intstatus |= (newstatus & bus->hostintmask);
2464	}
2465
2466	/* Handle host mailbox indication */
2467	if (intstatus & I_HMB_HOST_INT) {
2468		intstatus &= ~I_HMB_HOST_INT;
2469		intstatus |= brcmf_sdbrcm_hostmail(bus);
2470	}
2471
2472	/* Generally don't ask for these, can get CRC errors... */
2473	if (intstatus & I_WR_OOSYNC) {
2474		brcmf_dbg(ERROR, "Dongle reports WR_OOSYNC\n");
2475		intstatus &= ~I_WR_OOSYNC;
2476	}
2477
2478	if (intstatus & I_RD_OOSYNC) {
2479		brcmf_dbg(ERROR, "Dongle reports RD_OOSYNC\n");
2480		intstatus &= ~I_RD_OOSYNC;
2481	}
2482
2483	if (intstatus & I_SBINT) {
2484		brcmf_dbg(ERROR, "Dongle reports SBINT\n");
2485		intstatus &= ~I_SBINT;
2486	}
2487
2488	/* Would be active due to wake-wlan in gSPI */
2489	if (intstatus & I_CHIPACTIVE) {
2490		brcmf_dbg(INFO, "Dongle reports CHIPACTIVE\n");
2491		intstatus &= ~I_CHIPACTIVE;
2492	}
2493
2494	/* Ignore frame indications if rxskip is set */
2495	if (bus->rxskip)
2496		intstatus &= ~I_HMB_FRAME_IND;
2497
2498	/* On frame indication, read available frames */
2499	if (PKT_AVAILABLE()) {
2500		framecnt = brcmf_sdbrcm_readframes(bus, rxlimit, &rxdone);
2501		if (rxdone || bus->rxskip)
2502			intstatus &= ~I_HMB_FRAME_IND;
2503		rxlimit -= min(framecnt, rxlimit);
2504	}
2505
2506	/* Keep still-pending events for next scheduling */
2507	bus->intstatus = intstatus;
2508
2509clkwait:
2510	if (data_ok(bus) && bus->ctrl_frame_stat &&
2511		(bus->clkstate == CLK_AVAIL)) {
2512		int ret, i;
2513
2514		ret = brcmf_sdcard_send_buf(bus->sdiodev, bus->sdiodev->sbwad,
2515			SDIO_FUNC_2, F2SYNC, (u8 *) bus->ctrl_frame_buf,
2516			(u32) bus->ctrl_frame_len);
2517
2518		if (ret < 0) {
2519			/* On failure, abort the command and
2520				terminate the frame */
2521			brcmf_dbg(INFO, "sdio error %d, abort command and terminate frame\n",
2522				  ret);
2523			bus->tx_sderrs++;
2524
2525			brcmf_sdcard_abort(bus->sdiodev, SDIO_FUNC_2);
2526
2527			brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
2528					 SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM,
2529					 NULL);
2530			bus->f1regdata++;
2531
2532			for (i = 0; i < 3; i++) {
2533				u8 hi, lo;
2534				hi = brcmf_sdcard_cfg_read(bus->sdiodev,
2535						     SDIO_FUNC_1,
2536						     SBSDIO_FUNC1_WFRAMEBCHI,
2537						     NULL);
2538				lo = brcmf_sdcard_cfg_read(bus->sdiodev,
2539						     SDIO_FUNC_1,
2540						     SBSDIO_FUNC1_WFRAMEBCLO,
2541						     NULL);
2542				bus->f1regdata += 2;
2543				if ((hi == 0) && (lo == 0))
2544					break;
2545			}
2546
2547		}
2548		if (ret == 0)
2549			bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP;
2550
2551		brcmf_dbg(INFO, "Return_dpc value is : %d\n", ret);
2552		bus->ctrl_frame_stat = false;
2553		brcmf_sdbrcm_wait_event_wakeup(bus);
2554	}
2555	/* Send queued frames (limit 1 if rx may still be pending) */
2556	else if ((bus->clkstate == CLK_AVAIL) && !bus->fcstate &&
2557		 brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol) && txlimit
2558		 && data_ok(bus)) {
2559		framecnt = rxdone ? txlimit : min(txlimit, bus->txminmax);
2560		framecnt = brcmf_sdbrcm_sendfromq(bus, framecnt);
2561		txlimit -= framecnt;
2562	}
2563
2564	/* Resched if events or tx frames are pending,
2565		 else await next interrupt */
2566	/* On failed register access, all bets are off:
2567		 no resched or interrupts */
2568	if ((bus->sdiodev->bus_if->state == BRCMF_BUS_DOWN) ||
2569	    brcmf_sdcard_regfail(bus->sdiodev)) {
2570		brcmf_dbg(ERROR, "failed backplane access over SDIO, halting operation %d\n",
2571			  brcmf_sdcard_regfail(bus->sdiodev));
2572		bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
2573		bus->intstatus = 0;
2574	} else if (bus->clkstate == CLK_PENDING) {
2575		brcmf_dbg(INFO, "rescheduled due to CLK_PENDING awaiting I_CHIPACTIVE interrupt\n");
2576		resched = true;
2577	} else if (bus->intstatus || bus->ipend ||
2578		(!bus->fcstate && brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol)
2579		 && data_ok(bus)) || PKT_AVAILABLE()) {
2580		resched = true;
2581	}
2582
2583	bus->dpc_sched = resched;
2584
2585	/* If we're done for now, turn off clock request. */
2586	if ((bus->clkstate != CLK_PENDING)
2587	    && bus->idletime == BRCMF_IDLE_IMMEDIATE) {
2588		bus->activity = false;
2589		brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
2590	}
2591
2592	up(&bus->sdsem);
2593
2594	return resched;
2595}
2596
2597static int brcmf_sdbrcm_dpc_thread(void *data)
2598{
2599	struct brcmf_sdio *bus = (struct brcmf_sdio *) data;
2600
2601	allow_signal(SIGTERM);
2602	/* Run until signal received */
2603	while (1) {
2604		if (kthread_should_stop())
2605			break;
2606		if (!wait_for_completion_interruptible(&bus->dpc_wait)) {
2607			/* Call bus dpc unless it indicated down
2608			(then clean stop) */
2609			if (bus->sdiodev->bus_if->state != BRCMF_BUS_DOWN) {
2610				if (brcmf_sdbrcm_dpc(bus))
2611					complete(&bus->dpc_wait);
2612			} else {
2613				/* after stopping the bus, exit thread */
2614				brcmf_sdbrcm_bus_stop(bus->sdiodev->dev);
2615				bus->dpc_tsk = NULL;
2616				break;
2617			}
2618		} else
2619			break;
2620	}
2621	return 0;
2622}
2623
2624static int brcmf_sdbrcm_bus_txdata(struct device *dev, struct sk_buff *pkt)
2625{
2626	int ret = -EBADE;
2627	uint datalen, prec;
2628	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2629	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv;
2630	struct brcmf_sdio *bus = sdiodev->bus;
2631
2632	brcmf_dbg(TRACE, "Enter\n");
2633
2634	datalen = pkt->len;
2635
2636	/* Add space for the header */
2637	skb_push(pkt, SDPCM_HDRLEN);
2638	/* precondition: IS_ALIGNED((unsigned long)(pkt->data), 2) */
2639
2640	prec = prio2prec((pkt->priority & PRIOMASK));
2641
2642	/* Check for existing queue, current flow-control,
2643			 pending event, or pending clock */
2644	brcmf_dbg(TRACE, "deferring pktq len %d\n", pktq_len(&bus->txq));
2645	bus->fcqueued++;
2646
2647	/* Priority based enq */
2648	spin_lock_bh(&bus->txqlock);
2649	if (!brcmf_c_prec_enq(bus->sdiodev->dev, &bus->txq, pkt, prec)) {
2650		skb_pull(pkt, SDPCM_HDRLEN);
2651		brcmf_txcomplete(bus->sdiodev->dev, pkt, false);
2652		brcmu_pkt_buf_free_skb(pkt);
2653		brcmf_dbg(ERROR, "out of bus->txq !!!\n");
2654		ret = -ENOSR;
2655	} else {
2656		ret = 0;
2657	}
2658	spin_unlock_bh(&bus->txqlock);
2659
2660	if (pktq_len(&bus->txq) >= TXHI) {
2661		bus->txoff = ON;
2662		brcmf_txflowcontrol(bus->sdiodev->dev, 0, ON);
2663	}
2664
2665#ifdef DEBUG
2666	if (pktq_plen(&bus->txq, prec) > qcount[prec])
2667		qcount[prec] = pktq_plen(&bus->txq, prec);
2668#endif
2669	/* Schedule DPC if needed to send queued packet(s) */
2670	if (!bus->dpc_sched) {
2671		bus->dpc_sched = true;
2672		if (bus->dpc_tsk)
2673			complete(&bus->dpc_wait);
2674	}
2675
2676	return ret;
2677}
2678
2679static int
2680brcmf_sdbrcm_membytes(struct brcmf_sdio *bus, bool write, u32 address, u8 *data,
2681		 uint size)
2682{
2683	int bcmerror = 0;
2684	u32 sdaddr;
2685	uint dsize;
2686
2687	/* Determine initial transfer parameters */
2688	sdaddr = address & SBSDIO_SB_OFT_ADDR_MASK;
2689	if ((sdaddr + size) & SBSDIO_SBWINDOW_MASK)
2690		dsize = (SBSDIO_SB_OFT_ADDR_LIMIT - sdaddr);
2691	else
2692		dsize = size;
2693
2694	/* Set the backplane window to include the start address */
2695	bcmerror = brcmf_sdcard_set_sbaddr_window(bus->sdiodev, address);
2696	if (bcmerror) {
2697		brcmf_dbg(ERROR, "window change failed\n");
2698		goto xfer_done;
2699	}
2700
2701	/* Do the transfer(s) */
2702	while (size) {
2703		brcmf_dbg(INFO, "%s %d bytes at offset 0x%08x in window 0x%08x\n",
2704			  write ? "write" : "read", dsize,
2705			  sdaddr, address & SBSDIO_SBWINDOW_MASK);
2706		bcmerror = brcmf_sdcard_rwdata(bus->sdiodev, write,
2707					       sdaddr, data, dsize);
2708		if (bcmerror) {
2709			brcmf_dbg(ERROR, "membytes transfer failed\n");
2710			break;
2711		}
2712
2713		/* Adjust for next transfer (if any) */
2714		size -= dsize;
2715		if (size) {
2716			data += dsize;
2717			address += dsize;
2718			bcmerror = brcmf_sdcard_set_sbaddr_window(bus->sdiodev,
2719								  address);
2720			if (bcmerror) {
2721				brcmf_dbg(ERROR, "window change failed\n");
2722				break;
2723			}
2724			sdaddr = 0;
2725			dsize = min_t(uint, SBSDIO_SB_OFT_ADDR_LIMIT, size);
2726		}
2727	}
2728
2729xfer_done:
2730	/* Return the window to backplane enumeration space for core access */
2731	if (brcmf_sdcard_set_sbaddr_window(bus->sdiodev, bus->sdiodev->sbwad))
2732		brcmf_dbg(ERROR, "FAILED to set window back to 0x%x\n",
2733			  bus->sdiodev->sbwad);
2734
2735	return bcmerror;
2736}
2737
2738#ifdef DEBUG
2739#define CONSOLE_LINE_MAX	192
2740
2741static int brcmf_sdbrcm_readconsole(struct brcmf_sdio *bus)
2742{
2743	struct brcmf_console *c = &bus->console;
2744	u8 line[CONSOLE_LINE_MAX], ch;
2745	u32 n, idx, addr;
2746	int rv;
2747
2748	/* Don't do anything until FWREADY updates console address */
2749	if (bus->console_addr == 0)
2750		return 0;
2751
2752	/* Read console log struct */
2753	addr = bus->console_addr + offsetof(struct rte_console, log_le);
2754	rv = brcmf_sdbrcm_membytes(bus, false, addr, (u8 *)&c->log_le,
2755				   sizeof(c->log_le));
2756	if (rv < 0)
2757		return rv;
2758
2759	/* Allocate console buffer (one time only) */
2760	if (c->buf == NULL) {
2761		c->bufsize = le32_to_cpu(c->log_le.buf_size);
2762		c->buf = kmalloc(c->bufsize, GFP_ATOMIC);
2763		if (c->buf == NULL)
2764			return -ENOMEM;
2765	}
2766
2767	idx = le32_to_cpu(c->log_le.idx);
2768
2769	/* Protect against corrupt value */
2770	if (idx > c->bufsize)
2771		return -EBADE;
2772
2773	/* Skip reading the console buffer if the index pointer
2774	 has not moved */
2775	if (idx == c->last)
2776		return 0;
2777
2778	/* Read the console buffer */
2779	addr = le32_to_cpu(c->log_le.buf);
2780	rv = brcmf_sdbrcm_membytes(bus, false, addr, c->buf, c->bufsize);
2781	if (rv < 0)
2782		return rv;
2783
2784	while (c->last != idx) {
2785		for (n = 0; n < CONSOLE_LINE_MAX - 2; n++) {
2786			if (c->last == idx) {
2787				/* This would output a partial line.
2788				 * Instead, back up
2789				 * the buffer pointer and output this
2790				 * line next time around.
2791				 */
2792				if (c->last >= n)
2793					c->last -= n;
2794				else
2795					c->last = c->bufsize - n;
2796				goto break2;
2797			}
2798			ch = c->buf[c->last];
2799			c->last = (c->last + 1) % c->bufsize;
2800			if (ch == '\n')
2801				break;
2802			line[n] = ch;
2803		}
2804
2805		if (n > 0) {
2806			if (line[n - 1] == '\r')
2807				n--;
2808			line[n] = 0;
2809			pr_debug("CONSOLE: %s\n", line);
2810		}
2811	}
2812break2:
2813
2814	return 0;
2815}
2816#endif				/* DEBUG */
2817
2818static int brcmf_tx_frame(struct brcmf_sdio *bus, u8 *frame, u16 len)
2819{
2820	int i;
2821	int ret;
2822
2823	bus->ctrl_frame_stat = false;
2824	ret = brcmf_sdcard_send_buf(bus->sdiodev, bus->sdiodev->sbwad,
2825				    SDIO_FUNC_2, F2SYNC, frame, len);
2826
2827	if (ret < 0) {
2828		/* On failure, abort the command and terminate the frame */
2829		brcmf_dbg(INFO, "sdio error %d, abort command and terminate frame\n",
2830			  ret);
2831		bus->tx_sderrs++;
2832
2833		brcmf_sdcard_abort(bus->sdiodev, SDIO_FUNC_2);
2834
2835		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
2836				       SBSDIO_FUNC1_FRAMECTRL,
2837				       SFC_WF_TERM, NULL);
2838		bus->f1regdata++;
2839
2840		for (i = 0; i < 3; i++) {
2841			u8 hi, lo;
2842			hi = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
2843						   SBSDIO_FUNC1_WFRAMEBCHI,
2844						   NULL);
2845			lo = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
2846						   SBSDIO_FUNC1_WFRAMEBCLO,
2847						   NULL);
2848			bus->f1regdata += 2;
2849			if (hi == 0 && lo == 0)
2850				break;
2851		}
2852		return ret;
2853	}
2854
2855	bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP;
2856
2857	return ret;
2858}
2859
2860static int
2861brcmf_sdbrcm_bus_txctl(struct device *dev, unsigned char *msg, uint msglen)
2862{
2863	u8 *frame;
2864	u16 len;
2865	u32 swheader;
2866	uint retries = 0;
2867	u8 doff = 0;
2868	int ret = -1;
2869	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2870	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv;
2871	struct brcmf_sdio *bus = sdiodev->bus;
2872
2873	brcmf_dbg(TRACE, "Enter\n");
2874
2875	/* Back the pointer to make a room for bus header */
2876	frame = msg - SDPCM_HDRLEN;
2877	len = (msglen += SDPCM_HDRLEN);
2878
2879	/* Add alignment padding (optional for ctl frames) */
2880	doff = ((unsigned long)frame % BRCMF_SDALIGN);
2881	if (doff) {
2882		frame -= doff;
2883		len += doff;
2884		msglen += doff;
2885		memset(frame, 0, doff + SDPCM_HDRLEN);
2886	}
2887	/* precondition: doff < BRCMF_SDALIGN */
2888	doff += SDPCM_HDRLEN;
2889
2890	/* Round send length to next SDIO block */
2891	if (bus->roundup && bus->blocksize && (len > bus->blocksize)) {
2892		u16 pad = bus->blocksize - (len % bus->blocksize);
2893		if ((pad <= bus->roundup) && (pad < bus->blocksize))
2894			len += pad;
2895	} else if (len % BRCMF_SDALIGN) {
2896		len += BRCMF_SDALIGN - (len % BRCMF_SDALIGN);
2897	}
2898
2899	/* Satisfy length-alignment requirements */
2900	if (len & (ALIGNMENT - 1))
2901		len = roundup(len, ALIGNMENT);
2902
2903	/* precondition: IS_ALIGNED((unsigned long)frame, 2) */
2904
2905	/* Need to lock here to protect txseq and SDIO tx calls */
2906	down(&bus->sdsem);
2907
2908	bus_wake(bus);
2909
2910	/* Make sure backplane clock is on */
2911	brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
2912
2913	/* Hardware tag: 2 byte len followed by 2 byte ~len check (all LE) */
2914	*(__le16 *) frame = cpu_to_le16((u16) msglen);
2915	*(((__le16 *) frame) + 1) = cpu_to_le16(~msglen);
2916
2917	/* Software tag: channel, sequence number, data offset */
2918	swheader =
2919	    ((SDPCM_CONTROL_CHANNEL << SDPCM_CHANNEL_SHIFT) &
2920	     SDPCM_CHANNEL_MASK)
2921	    | bus->tx_seq | ((doff << SDPCM_DOFFSET_SHIFT) &
2922			     SDPCM_DOFFSET_MASK);
2923	put_unaligned_le32(swheader, frame + SDPCM_FRAMETAG_LEN);
2924	put_unaligned_le32(0, frame + SDPCM_FRAMETAG_LEN + sizeof(swheader));
2925
2926	if (!data_ok(bus)) {
2927		brcmf_dbg(INFO, "No bus credit bus->tx_max %d, bus->tx_seq %d\n",
2928			  bus->tx_max, bus->tx_seq);
2929		bus->ctrl_frame_stat = true;
2930		/* Send from dpc */
2931		bus->ctrl_frame_buf = frame;
2932		bus->ctrl_frame_len = len;
2933
2934		brcmf_sdbrcm_wait_for_event(bus, &bus->ctrl_frame_stat);
2935
2936		if (!bus->ctrl_frame_stat) {
2937			brcmf_dbg(INFO, "ctrl_frame_stat == false\n");
2938			ret = 0;
2939		} else {
2940			brcmf_dbg(INFO, "ctrl_frame_stat == true\n");
2941			ret = -1;
2942		}
2943	}
2944
2945	if (ret == -1) {
2946		brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_CTL_ON(),
2947				   frame, len, "Tx Frame:\n");
2948		brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() && BRCMF_CTL_ON()) &&
2949				   BRCMF_HDRS_ON(),
2950				   frame, min_t(u16, len, 16), "TxHdr:\n");
2951
2952		do {
2953			ret = brcmf_tx_frame(bus, frame, len);
2954		} while (ret < 0 && retries++ < TXRETRIES);
2955	}
2956
2957	if ((bus->idletime == BRCMF_IDLE_IMMEDIATE) && !bus->dpc_sched) {
2958		bus->activity = false;
2959		brcmf_sdbrcm_clkctl(bus, CLK_NONE, true);
2960	}
2961
2962	up(&bus->sdsem);
2963
2964	if (ret)
2965		bus->tx_ctlerrs++;
2966	else
2967		bus->tx_ctlpkts++;
2968
2969	return ret ? -EIO : 0;
2970}
2971
2972static int
2973brcmf_sdbrcm_bus_rxctl(struct device *dev, unsigned char *msg, uint msglen)
2974{
2975	int timeleft;
2976	uint rxlen = 0;
2977	bool pending;
2978	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2979	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv;
2980	struct brcmf_sdio *bus = sdiodev->bus;
2981
2982	brcmf_dbg(TRACE, "Enter\n");
2983
2984	/* Wait until control frame is available */
2985	timeleft = brcmf_sdbrcm_dcmd_resp_wait(bus, &bus->rxlen, &pending);
2986
2987	down(&bus->sdsem);
2988	rxlen = bus->rxlen;
2989	memcpy(msg, bus->rxctl, min(msglen, rxlen));
2990	bus->rxlen = 0;
2991	up(&bus->sdsem);
2992
2993	if (rxlen) {
2994		brcmf_dbg(CTL, "resumed on rxctl frame, got %d expected %d\n",
2995			  rxlen, msglen);
2996	} else if (timeleft == 0) {
2997		brcmf_dbg(ERROR, "resumed on timeout\n");
2998	} else if (pending) {
2999		brcmf_dbg(CTL, "cancelled\n");
3000		return -ERESTARTSYS;
3001	} else {
3002		brcmf_dbg(CTL, "resumed for unknown reason?\n");
3003	}
3004
3005	if (rxlen)
3006		bus->rx_ctlpkts++;
3007	else
3008		bus->rx_ctlerrs++;
3009
3010	return rxlen ? (int)rxlen : -ETIMEDOUT;
3011}
3012
3013static int brcmf_sdbrcm_downloadvars(struct brcmf_sdio *bus, void *arg, int len)
3014{
3015	int bcmerror = 0;
3016
3017	brcmf_dbg(TRACE, "Enter\n");
3018
3019	/* Basic sanity checks */
3020	if (bus->sdiodev->bus_if->drvr_up) {
3021		bcmerror = -EISCONN;
3022		goto err;
3023	}
3024	if (!len) {
3025		bcmerror = -EOVERFLOW;
3026		goto err;
3027	}
3028
3029	/* Free the old ones and replace with passed variables */
3030	kfree(bus->vars);
3031
3032	bus->vars = kmalloc(len, GFP_ATOMIC);
3033	bus->varsz = bus->vars ? len : 0;
3034	if (bus->vars == NULL) {
3035		bcmerror = -ENOMEM;
3036		goto err;
3037	}
3038
3039	/* Copy the passed variables, which should include the
3040		 terminating double-null */
3041	memcpy(bus->vars, arg, bus->varsz);
3042err:
3043	return bcmerror;
3044}
3045
3046static int brcmf_sdbrcm_write_vars(struct brcmf_sdio *bus)
3047{
3048	int bcmerror = 0;
3049	u32 varsize;
3050	u32 varaddr;
3051	u8 *vbuffer;
3052	u32 varsizew;
3053	__le32 varsizew_le;
3054#ifdef DEBUG
3055	char *nvram_ularray;
3056#endif				/* DEBUG */
3057
3058	/* Even if there are no vars are to be written, we still
3059		 need to set the ramsize. */
3060	varsize = bus->varsz ? roundup(bus->varsz, 4) : 0;
3061	varaddr = (bus->ramsize - 4) - varsize;
3062
3063	if (bus->vars) {
3064		vbuffer = kzalloc(varsize, GFP_ATOMIC);
3065		if (!vbuffer)
3066			return -ENOMEM;
3067
3068		memcpy(vbuffer, bus->vars, bus->varsz);
3069
3070		/* Write the vars list */
3071		bcmerror =
3072		    brcmf_sdbrcm_membytes(bus, true, varaddr, vbuffer, varsize);
3073#ifdef DEBUG
3074		/* Verify NVRAM bytes */
3075		brcmf_dbg(INFO, "Compare NVRAM dl & ul; varsize=%d\n", varsize);
3076		nvram_ularray = kmalloc(varsize, GFP_ATOMIC);
3077		if (!nvram_ularray) {
3078			kfree(vbuffer);
3079			return -ENOMEM;
3080		}
3081
3082		/* Upload image to verify downloaded contents. */
3083		memset(nvram_ularray, 0xaa, varsize);
3084
3085		/* Read the vars list to temp buffer for comparison */
3086		bcmerror =
3087		    brcmf_sdbrcm_membytes(bus, false, varaddr, nvram_ularray,
3088				     varsize);
3089		if (bcmerror) {
3090			brcmf_dbg(ERROR, "error %d on reading %d nvram bytes at 0x%08x\n",
3091				  bcmerror, varsize, varaddr);
3092		}
3093		/* Compare the org NVRAM with the one read from RAM */
3094		if (memcmp(vbuffer, nvram_ularray, varsize))
3095			brcmf_dbg(ERROR, "Downloaded NVRAM image is corrupted\n");
3096		else
3097			brcmf_dbg(ERROR, "Download/Upload/Compare of NVRAM ok\n");
3098
3099		kfree(nvram_ularray);
3100#endif				/* DEBUG */
3101
3102		kfree(vbuffer);
3103	}
3104
3105	/* adjust to the user specified RAM */
3106	brcmf_dbg(INFO, "Physical memory size: %d\n", bus->ramsize);
3107	brcmf_dbg(INFO, "Vars are at %d, orig varsize is %d\n",
3108		  varaddr, varsize);
3109	varsize = ((bus->ramsize - 4) - varaddr);
3110
3111	/*
3112	 * Determine the length token:
3113	 * Varsize, converted to words, in lower 16-bits, checksum
3114	 * in upper 16-bits.
3115	 */
3116	if (bcmerror) {
3117		varsizew = 0;
3118		varsizew_le = cpu_to_le32(0);
3119	} else {
3120		varsizew = varsize / 4;
3121		varsizew = (~varsizew << 16) | (varsizew & 0x0000FFFF);
3122		varsizew_le = cpu_to_le32(varsizew);
3123	}
3124
3125	brcmf_dbg(INFO, "New varsize is %d, length token=0x%08x\n",
3126		  varsize, varsizew);
3127
3128	/* Write the length token to the last word */
3129	bcmerror = brcmf_sdbrcm_membytes(bus, true, (bus->ramsize - 4),
3130					 (u8 *)&varsizew_le, 4);
3131
3132	return bcmerror;
3133}
3134
3135static int brcmf_sdbrcm_download_state(struct brcmf_sdio *bus, bool enter)
3136{
3137	uint retries;
3138	int bcmerror = 0;
3139	struct chip_info *ci = bus->ci;
3140
3141	/* To enter download state, disable ARM and reset SOCRAM.
3142	 * To exit download state, simply reset ARM (default is RAM boot).
3143	 */
3144	if (enter) {
3145		bus->alp_only = true;
3146
3147		ci->coredisable(bus->sdiodev, ci, BCMA_CORE_ARM_CM3);
3148
3149		ci->resetcore(bus->sdiodev, ci, BCMA_CORE_INTERNAL_MEM);
3150
3151		/* Clear the top bit of memory */
3152		if (bus->ramsize) {
3153			u32 zeros = 0;
3154			brcmf_sdbrcm_membytes(bus, true, bus->ramsize - 4,
3155					 (u8 *)&zeros, 4);
3156		}
3157	} else {
3158		if (!ci->iscoreup(bus->sdiodev, ci, BCMA_CORE_INTERNAL_MEM)) {
3159			brcmf_dbg(ERROR, "SOCRAM core is down after reset?\n");
3160			bcmerror = -EBADE;
3161			goto fail;
3162		}
3163
3164		bcmerror = brcmf_sdbrcm_write_vars(bus);
3165		if (bcmerror) {
3166			brcmf_dbg(ERROR, "no vars written to RAM\n");
3167			bcmerror = 0;
3168		}
3169
3170		w_sdreg32(bus, 0xFFFFFFFF,
3171			  offsetof(struct sdpcmd_regs, intstatus), &retries);
3172
3173		ci->resetcore(bus->sdiodev, ci, BCMA_CORE_ARM_CM3);
3174
3175		/* Allow HT Clock now that the ARM is running. */
3176		bus->alp_only = false;
3177
3178		bus->sdiodev->bus_if->state = BRCMF_BUS_LOAD;
3179	}
3180fail:
3181	return bcmerror;
3182}
3183
3184static int brcmf_sdbrcm_get_image(char *buf, int len, struct brcmf_sdio *bus)
3185{
3186	if (bus->firmware->size < bus->fw_ptr + len)
3187		len = bus->firmware->size - bus->fw_ptr;
3188
3189	memcpy(buf, &bus->firmware->data[bus->fw_ptr], len);
3190	bus->fw_ptr += len;
3191	return len;
3192}
3193
3194static int brcmf_sdbrcm_download_code_file(struct brcmf_sdio *bus)
3195{
3196	int offset = 0;
3197	uint len;
3198	u8 *memblock = NULL, *memptr;
3199	int ret;
3200
3201	brcmf_dbg(INFO, "Enter\n");
3202
3203	ret = request_firmware(&bus->firmware, BRCMFMAC_FW_NAME,
3204			       &bus->sdiodev->func[2]->dev);
3205	if (ret) {
3206		brcmf_dbg(ERROR, "Fail to request firmware %d\n", ret);
3207		return ret;
3208	}
3209	bus->fw_ptr = 0;
3210
3211	memptr = memblock = kmalloc(MEMBLOCK + BRCMF_SDALIGN, GFP_ATOMIC);
3212	if (memblock == NULL) {
3213		ret = -ENOMEM;
3214		goto err;
3215	}
3216	if ((u32)(unsigned long)memblock % BRCMF_SDALIGN)
3217		memptr += (BRCMF_SDALIGN -
3218			   ((u32)(unsigned long)memblock % BRCMF_SDALIGN));
3219
3220	/* Download image */
3221	while ((len =
3222		brcmf_sdbrcm_get_image((char *)memptr, MEMBLOCK, bus))) {
3223		ret = brcmf_sdbrcm_membytes(bus, true, offset, memptr, len);
3224		if (ret) {
3225			brcmf_dbg(ERROR, "error %d on writing %d membytes at 0x%08x\n",
3226				  ret, MEMBLOCK, offset);
3227			goto err;
3228		}
3229
3230		offset += MEMBLOCK;
3231	}
3232
3233err:
3234	kfree(memblock);
3235
3236	release_firmware(bus->firmware);
3237	bus->fw_ptr = 0;
3238
3239	return ret;
3240}
3241
3242/*
3243 * ProcessVars:Takes a buffer of "<var>=<value>\n" lines read from a file
3244 * and ending in a NUL.
3245 * Removes carriage returns, empty lines, comment lines, and converts
3246 * newlines to NULs.
3247 * Shortens buffer as needed and pads with NULs.  End of buffer is marked
3248 * by two NULs.
3249*/
3250
3251static uint brcmf_process_nvram_vars(char *varbuf, uint len)
3252{
3253	char *dp;
3254	bool findNewline;
3255	int column;
3256	uint buf_len, n;
3257
3258	dp = varbuf;
3259
3260	findNewline = false;
3261	column = 0;
3262
3263	for (n = 0; n < len; n++) {
3264		if (varbuf[n] == 0)
3265			break;
3266		if (varbuf[n] == '\r')
3267			continue;
3268		if (findNewline && varbuf[n] != '\n')
3269			continue;
3270		findNewline = false;
3271		if (varbuf[n] == '#') {
3272			findNewline = true;
3273			continue;
3274		}
3275		if (varbuf[n] == '\n') {
3276			if (column == 0)
3277				continue;
3278			*dp++ = 0;
3279			column = 0;
3280			continue;
3281		}
3282		*dp++ = varbuf[n];
3283		column++;
3284	}
3285	buf_len = dp - varbuf;
3286
3287	while (dp < varbuf + n)
3288		*dp++ = 0;
3289
3290	return buf_len;
3291}
3292
3293static int brcmf_sdbrcm_download_nvram(struct brcmf_sdio *bus)
3294{
3295	uint len;
3296	char *memblock = NULL;
3297	char *bufp;
3298	int ret;
3299
3300	ret = request_firmware(&bus->firmware, BRCMFMAC_NV_NAME,
3301			       &bus->sdiodev->func[2]->dev);
3302	if (ret) {
3303		brcmf_dbg(ERROR, "Fail to request nvram %d\n", ret);
3304		return ret;
3305	}
3306	bus->fw_ptr = 0;
3307
3308	memblock = kmalloc(MEMBLOCK, GFP_ATOMIC);
3309	if (memblock == NULL) {
3310		ret = -ENOMEM;
3311		goto err;
3312	}
3313
3314	len = brcmf_sdbrcm_get_image(memblock, MEMBLOCK, bus);
3315
3316	if (len > 0 && len < MEMBLOCK) {
3317		bufp = (char *)memblock;
3318		bufp[len] = 0;
3319		len = brcmf_process_nvram_vars(bufp, len);
3320		bufp += len;
3321		*bufp++ = 0;
3322		if (len)
3323			ret = brcmf_sdbrcm_downloadvars(bus, memblock, len + 1);
3324		if (ret)
3325			brcmf_dbg(ERROR, "error downloading vars: %d\n", ret);
3326	} else {
3327		brcmf_dbg(ERROR, "error reading nvram file: %d\n", len);
3328		ret = -EIO;
3329	}
3330
3331err:
3332	kfree(memblock);
3333
3334	release_firmware(bus->firmware);
3335	bus->fw_ptr = 0;
3336
3337	return ret;
3338}
3339
3340static int _brcmf_sdbrcm_download_firmware(struct brcmf_sdio *bus)
3341{
3342	int bcmerror = -1;
3343
3344	/* Keep arm in reset */
3345	if (brcmf_sdbrcm_download_state(bus, true)) {
3346		brcmf_dbg(ERROR, "error placing ARM core in reset\n");
3347		goto err;
3348	}
3349
3350	/* External image takes precedence if specified */
3351	if (brcmf_sdbrcm_download_code_file(bus)) {
3352		brcmf_dbg(ERROR, "dongle image file download failed\n");
3353		goto err;
3354	}
3355
3356	/* External nvram takes precedence if specified */
3357	if (brcmf_sdbrcm_download_nvram(bus))
3358		brcmf_dbg(ERROR, "dongle nvram file download failed\n");
3359
3360	/* Take arm out of reset */
3361	if (brcmf_sdbrcm_download_state(bus, false)) {
3362		brcmf_dbg(ERROR, "error getting out of ARM core reset\n");
3363		goto err;
3364	}
3365
3366	bcmerror = 0;
3367
3368err:
3369	return bcmerror;
3370}
3371
3372static bool
3373brcmf_sdbrcm_download_firmware(struct brcmf_sdio *bus)
3374{
3375	bool ret;
3376
3377	/* Download the firmware */
3378	brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
3379
3380	ret = _brcmf_sdbrcm_download_firmware(bus) == 0;
3381
3382	brcmf_sdbrcm_clkctl(bus, CLK_SDONLY, false);
3383
3384	return ret;
3385}
3386
3387static int brcmf_sdbrcm_bus_init(struct device *dev)
3388{
3389	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3390	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv;
3391	struct brcmf_sdio *bus = sdiodev->bus;
3392	unsigned long timeout;
3393	uint retries = 0;
3394	u8 ready, enable;
3395	int err, ret = 0;
3396	u8 saveclk;
3397
3398	brcmf_dbg(TRACE, "Enter\n");
3399
3400	/* try to download image and nvram to the dongle */
3401	if (bus_if->state == BRCMF_BUS_DOWN) {
3402		if (!(brcmf_sdbrcm_download_firmware(bus)))
3403			return -1;
3404	}
3405
3406	if (!bus->sdiodev->bus_if->drvr)
3407		return 0;
3408
3409	/* Start the watchdog timer */
3410	bus->tickcnt = 0;
3411	brcmf_sdbrcm_wd_timer(bus, BRCMF_WD_POLL_MS);
3412
3413	down(&bus->sdsem);
3414
3415	/* Make sure backplane clock is on, needed to generate F2 interrupt */
3416	brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
3417	if (bus->clkstate != CLK_AVAIL)
3418		goto exit;
3419
3420	/* Force clocks on backplane to be sure F2 interrupt propagates */
3421	saveclk =
3422	    brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
3423				  SBSDIO_FUNC1_CHIPCLKCSR, &err);
3424	if (!err) {
3425		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
3426				       SBSDIO_FUNC1_CHIPCLKCSR,
3427				       (saveclk | SBSDIO_FORCE_HT), &err);
3428	}
3429	if (err) {
3430		brcmf_dbg(ERROR, "Failed to force clock for F2: err %d\n", err);
3431		goto exit;
3432	}
3433
3434	/* Enable function 2 (frame transfers) */
3435	w_sdreg32(bus, SDPCM_PROT_VERSION << SMB_DATA_VERSION_SHIFT,
3436		  offsetof(struct sdpcmd_regs, tosbmailboxdata), &retries);
3437	enable = (SDIO_FUNC_ENABLE_1 | SDIO_FUNC_ENABLE_2);
3438
3439	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_0, SDIO_CCCR_IOEx,
3440			       enable, NULL);
3441
3442	timeout = jiffies + msecs_to_jiffies(BRCMF_WAIT_F2RDY);
3443	ready = 0;
3444	while (enable != ready) {
3445		ready = brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_0,
3446					      SDIO_CCCR_IORx, NULL);
3447		if (time_after(jiffies, timeout))
3448			break;
3449		else if (time_after(jiffies, timeout - BRCMF_WAIT_F2RDY + 50))
3450			/* prevent busy waiting if it takes too long */
3451			msleep_interruptible(20);
3452	}
3453
3454	brcmf_dbg(INFO, "enable 0x%02x, ready 0x%02x\n", enable, ready);
3455
3456	/* If F2 successfully enabled, set core and enable interrupts */
3457	if (ready == enable) {
3458		/* Set up the interrupt mask and enable interrupts */
3459		bus->hostintmask = HOSTINTMASK;
3460		w_sdreg32(bus, bus->hostintmask,
3461			  offsetof(struct sdpcmd_regs, hostintmask), &retries);
3462
3463		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
3464				       SBSDIO_WATERMARK, 8, &err);
3465
3466		/* Set bus state according to enable result */
3467		bus_if->state = BRCMF_BUS_DATA;
3468	}
3469
3470	else {
3471		/* Disable F2 again */
3472		enable = SDIO_FUNC_ENABLE_1;
3473		brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_0,
3474				       SDIO_CCCR_IOEx, enable, NULL);
3475	}
3476
3477	/* Restore previous clock setting */
3478	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
3479			       SBSDIO_FUNC1_CHIPCLKCSR, saveclk, &err);
3480
3481	/* If we didn't come up, turn off backplane clock */
3482	if (bus_if->state != BRCMF_BUS_DATA)
3483		brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
3484
3485exit:
3486	up(&bus->sdsem);
3487
3488	return ret;
3489}
3490
3491void brcmf_sdbrcm_isr(void *arg)
3492{
3493	struct brcmf_sdio *bus = (struct brcmf_sdio *) arg;
3494
3495	brcmf_dbg(TRACE, "Enter\n");
3496
3497	if (!bus) {
3498		brcmf_dbg(ERROR, "bus is null pointer, exiting\n");
3499		return;
3500	}
3501
3502	if (bus->sdiodev->bus_if->state == BRCMF_BUS_DOWN) {
3503		brcmf_dbg(ERROR, "bus is down. we have nothing to do\n");
3504		return;
3505	}
3506	/* Count the interrupt call */
3507	bus->intrcount++;
3508	bus->ipend = true;
3509
3510	/* Shouldn't get this interrupt if we're sleeping? */
3511	if (bus->sleeping) {
3512		brcmf_dbg(ERROR, "INTERRUPT WHILE SLEEPING??\n");
3513		return;
3514	}
3515
3516	/* Disable additional interrupts (is this needed now)? */
3517	if (!bus->intr)
3518		brcmf_dbg(ERROR, "isr w/o interrupt configured!\n");
3519
3520	bus->dpc_sched = true;
3521	if (bus->dpc_tsk)
3522		complete(&bus->dpc_wait);
3523}
3524
3525static bool brcmf_sdbrcm_bus_watchdog(struct brcmf_sdio *bus)
3526{
3527#ifdef DEBUG
3528	struct brcmf_bus *bus_if = dev_get_drvdata(bus->sdiodev->dev);
3529#endif	/* DEBUG */
3530
3531	brcmf_dbg(TIMER, "Enter\n");
3532
3533	/* Ignore the timer if simulating bus down */
3534	if (bus->sleeping)
3535		return false;
3536
3537	down(&bus->sdsem);
3538
3539	/* Poll period: check device if appropriate. */
3540	if (bus->poll && (++bus->polltick >= bus->pollrate)) {
3541		u32 intstatus = 0;
3542
3543		/* Reset poll tick */
3544		bus->polltick = 0;
3545
3546		/* Check device if no interrupts */
3547		if (!bus->intr || (bus->intrcount == bus->lastintrs)) {
3548
3549			if (!bus->dpc_sched) {
3550				u8 devpend;
3551				devpend = brcmf_sdcard_cfg_read(bus->sdiodev,
3552						SDIO_FUNC_0, SDIO_CCCR_INTx,
3553						NULL);
3554				intstatus =
3555				    devpend & (INTR_STATUS_FUNC1 |
3556					       INTR_STATUS_FUNC2);
3557			}
3558
3559			/* If there is something, make like the ISR and
3560				 schedule the DPC */
3561			if (intstatus) {
3562				bus->pollcnt++;
3563				bus->ipend = true;
3564
3565				bus->dpc_sched = true;
3566				if (bus->dpc_tsk)
3567					complete(&bus->dpc_wait);
3568			}
3569		}
3570
3571		/* Update interrupt tracking */
3572		bus->lastintrs = bus->intrcount;
3573	}
3574#ifdef DEBUG
3575	/* Poll for console output periodically */
3576	if (bus_if->state == BRCMF_BUS_DATA &&
3577	    bus->console_interval != 0) {
3578		bus->console.count += BRCMF_WD_POLL_MS;
3579		if (bus->console.count >= bus->console_interval) {
3580			bus->console.count -= bus->console_interval;
3581			/* Make sure backplane clock is on */
3582			brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
3583			if (brcmf_sdbrcm_readconsole(bus) < 0)
3584				/* stop on error */
3585				bus->console_interval = 0;
3586		}
3587	}
3588#endif				/* DEBUG */
3589
3590	/* On idle timeout clear activity flag and/or turn off clock */
3591	if ((bus->idletime > 0) && (bus->clkstate == CLK_AVAIL)) {
3592		if (++bus->idlecount >= bus->idletime) {
3593			bus->idlecount = 0;
3594			if (bus->activity) {
3595				bus->activity = false;
3596				brcmf_sdbrcm_wd_timer(bus, BRCMF_WD_POLL_MS);
3597			} else {
3598				brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
3599			}
3600		}
3601	}
3602
3603	up(&bus->sdsem);
3604
3605	return bus->ipend;
3606}
3607
3608static bool brcmf_sdbrcm_chipmatch(u16 chipid)
3609{
3610	if (chipid == BCM4329_CHIP_ID)
3611		return true;
3612	if (chipid == BCM4330_CHIP_ID)
3613		return true;
3614	return false;
3615}
3616
3617static void brcmf_sdbrcm_release_malloc(struct brcmf_sdio *bus)
3618{
3619	brcmf_dbg(TRACE, "Enter\n");
3620
3621	kfree(bus->rxbuf);
3622	bus->rxctl = bus->rxbuf = NULL;
3623	bus->rxlen = 0;
3624
3625	kfree(bus->databuf);
3626	bus->databuf = NULL;
3627}
3628
3629static bool brcmf_sdbrcm_probe_malloc(struct brcmf_sdio *bus)
3630{
3631	brcmf_dbg(TRACE, "Enter\n");
3632
3633	if (bus->sdiodev->bus_if->maxctl) {
3634		bus->rxblen =
3635		    roundup((bus->sdiodev->bus_if->maxctl + SDPCM_HDRLEN),
3636			    ALIGNMENT) + BRCMF_SDALIGN;
3637		bus->rxbuf = kmalloc(bus->rxblen, GFP_ATOMIC);
3638		if (!(bus->rxbuf))
3639			goto fail;
3640	}
3641
3642	/* Allocate buffer to receive glomed packet */
3643	bus->databuf = kmalloc(MAX_DATA_BUF, GFP_ATOMIC);
3644	if (!(bus->databuf)) {
3645		/* release rxbuf which was already located as above */
3646		if (!bus->rxblen)
3647			kfree(bus->rxbuf);
3648		goto fail;
3649	}
3650
3651	/* Align the buffer */
3652	if ((unsigned long)bus->databuf % BRCMF_SDALIGN)
3653		bus->dataptr = bus->databuf + (BRCMF_SDALIGN -
3654			       ((unsigned long)bus->databuf % BRCMF_SDALIGN));
3655	else
3656		bus->dataptr = bus->databuf;
3657
3658	return true;
3659
3660fail:
3661	return false;
3662}
3663
3664static bool
3665brcmf_sdbrcm_probe_attach(struct brcmf_sdio *bus, u32 regsva)
3666{
3667	u8 clkctl = 0;
3668	int err = 0;
3669	int reg_addr;
3670	u32 reg_val;
3671	u8 idx;
3672
3673	bus->alp_only = true;
3674
3675	/* Return the window to backplane enumeration space for core access */
3676	if (brcmf_sdcard_set_sbaddr_window(bus->sdiodev, SI_ENUM_BASE))
3677		brcmf_dbg(ERROR, "FAILED to return to SI_ENUM_BASE\n");
3678
3679	pr_debug("F1 signature read @0x18000000=0x%4x\n",
3680		 brcmf_sdcard_reg_read(bus->sdiodev, SI_ENUM_BASE, 4));
3681
3682	/*
3683	 * Force PLL off until brcmf_sdio_chip_attach()
3684	 * programs PLL control regs
3685	 */
3686
3687	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
3688			       SBSDIO_FUNC1_CHIPCLKCSR,
3689			       BRCMF_INIT_CLKCTL1, &err);
3690	if (!err)
3691		clkctl =
3692		    brcmf_sdcard_cfg_read(bus->sdiodev, SDIO_FUNC_1,
3693					  SBSDIO_FUNC1_CHIPCLKCSR, &err);
3694
3695	if (err || ((clkctl & ~SBSDIO_AVBITS) != BRCMF_INIT_CLKCTL1)) {
3696		brcmf_dbg(ERROR, "ChipClkCSR access: err %d wrote 0x%02x read 0x%02x\n",
3697			  err, BRCMF_INIT_CLKCTL1, clkctl);
3698		goto fail;
3699	}
3700
3701	if (brcmf_sdio_chip_attach(bus->sdiodev, &bus->ci, regsva)) {
3702		brcmf_dbg(ERROR, "brcmf_sdio_chip_attach failed!\n");
3703		goto fail;
3704	}
3705
3706	if (!brcmf_sdbrcm_chipmatch((u16) bus->ci->chip)) {
3707		brcmf_dbg(ERROR, "unsupported chip: 0x%04x\n", bus->ci->chip);
3708		goto fail;
3709	}
3710
3711	brcmf_sdio_chip_drivestrengthinit(bus->sdiodev, bus->ci,
3712					  SDIO_DRIVE_STRENGTH);
3713
3714	/* Get info on the SOCRAM cores... */
3715	bus->ramsize = bus->ci->ramsize;
3716	if (!(bus->ramsize)) {
3717		brcmf_dbg(ERROR, "failed to find SOCRAM memory!\n");
3718		goto fail;
3719	}
3720
3721	/* Set core control so an SDIO reset does a backplane reset */
3722	idx = brcmf_sdio_chip_getinfidx(bus->ci, BCMA_CORE_SDIO_DEV);
3723	reg_addr = bus->ci->c_inf[idx].base +
3724		   offsetof(struct sdpcmd_regs, corecontrol);
3725	reg_val = brcmf_sdcard_reg_read(bus->sdiodev, reg_addr, sizeof(u32));
3726	brcmf_sdcard_reg_write(bus->sdiodev, reg_addr, sizeof(u32),
3727			       reg_val | CC_BPRESEN);
3728
3729	brcmu_pktq_init(&bus->txq, (PRIOMASK + 1), TXQLEN);
3730
3731	/* Locate an appropriately-aligned portion of hdrbuf */
3732	bus->rxhdr = (u8 *) roundup((unsigned long)&bus->hdrbuf[0],
3733				    BRCMF_SDALIGN);
3734
3735	/* Set the poll and/or interrupt flags */
3736	bus->intr = true;
3737	bus->poll = false;
3738	if (bus->poll)
3739		bus->pollrate = 1;
3740
3741	return true;
3742
3743fail:
3744	return false;
3745}
3746
3747static bool brcmf_sdbrcm_probe_init(struct brcmf_sdio *bus)
3748{
3749	brcmf_dbg(TRACE, "Enter\n");
3750
3751	/* Disable F2 to clear any intermediate frame state on the dongle */
3752	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_0, SDIO_CCCR_IOEx,
3753			       SDIO_FUNC_ENABLE_1, NULL);
3754
3755	bus->sdiodev->bus_if->state = BRCMF_BUS_DOWN;
3756	bus->sleeping = false;
3757	bus->rxflow = false;
3758
3759	/* Done with backplane-dependent accesses, can drop clock... */
3760	brcmf_sdcard_cfg_write(bus->sdiodev, SDIO_FUNC_1,
3761			       SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL);
3762
3763	/* ...and initialize clock/power states */
3764	bus->clkstate = CLK_SDONLY;
3765	bus->idletime = BRCMF_IDLE_INTERVAL;
3766	bus->idleclock = BRCMF_IDLE_ACTIVE;
3767
3768	/* Query the F2 block size, set roundup accordingly */
3769	bus->blocksize = bus->sdiodev->func[2]->cur_blksize;
3770	bus->roundup = min(max_roundup, bus->blocksize);
3771
3772	/* bus module does not support packet chaining */
3773	bus->use_rxchain = false;
3774	bus->sd_rxchain = false;
3775
3776	return true;
3777}
3778
3779static int
3780brcmf_sdbrcm_watchdog_thread(void *data)
3781{
3782	struct brcmf_sdio *bus = (struct brcmf_sdio *)data;
3783
3784	allow_signal(SIGTERM);
3785	/* Run until signal received */
3786	while (1) {
3787		if (kthread_should_stop())
3788			break;
3789		if (!wait_for_completion_interruptible(&bus->watchdog_wait)) {
3790			brcmf_sdbrcm_bus_watchdog(bus);
3791			/* Count the tick for reference */
3792			bus->tickcnt++;
3793		} else
3794			break;
3795	}
3796	return 0;
3797}
3798
3799static void
3800brcmf_sdbrcm_watchdog(unsigned long data)
3801{
3802	struct brcmf_sdio *bus = (struct brcmf_sdio *)data;
3803
3804	if (bus->watchdog_tsk) {
3805		complete(&bus->watchdog_wait);
3806		/* Reschedule the watchdog */
3807		if (bus->wd_timer_valid)
3808			mod_timer(&bus->timer,
3809				  jiffies + BRCMF_WD_POLL_MS * HZ / 1000);
3810	}
3811}
3812
3813static void brcmf_sdbrcm_release_dongle(struct brcmf_sdio *bus)
3814{
3815	brcmf_dbg(TRACE, "Enter\n");
3816
3817	if (bus->ci) {
3818		brcmf_sdbrcm_clkctl(bus, CLK_AVAIL, false);
3819		brcmf_sdbrcm_clkctl(bus, CLK_NONE, false);
3820		brcmf_sdio_chip_detach(&bus->ci);
3821		if (bus->vars && bus->varsz)
3822			kfree(bus->vars);
3823		bus->vars = NULL;
3824	}
3825
3826	brcmf_dbg(TRACE, "Disconnected\n");
3827}
3828
3829/* Detach and free everything */
3830static void brcmf_sdbrcm_release(struct brcmf_sdio *bus)
3831{
3832	brcmf_dbg(TRACE, "Enter\n");
3833
3834	if (bus) {
3835		/* De-register interrupt handler */
3836		brcmf_sdcard_intr_dereg(bus->sdiodev);
3837
3838		if (bus->sdiodev->bus_if->drvr) {
3839			brcmf_detach(bus->sdiodev->dev);
3840			brcmf_sdbrcm_release_dongle(bus);
3841		}
3842
3843		brcmf_sdbrcm_release_malloc(bus);
3844
3845		kfree(bus);
3846	}
3847
3848	brcmf_dbg(TRACE, "Disconnected\n");
3849}
3850
3851void *brcmf_sdbrcm_probe(u32 regsva, struct brcmf_sdio_dev *sdiodev)
3852{
3853	int ret;
3854	struct brcmf_sdio *bus;
3855
3856	brcmf_dbg(TRACE, "Enter\n");
3857
3858	/* We make an assumption about address window mappings:
3859	 * regsva == SI_ENUM_BASE*/
3860
3861	/* Allocate private bus interface state */
3862	bus = kzalloc(sizeof(struct brcmf_sdio), GFP_ATOMIC);
3863	if (!bus)
3864		goto fail;
3865
3866	bus->sdiodev = sdiodev;
3867	sdiodev->bus = bus;
3868	skb_queue_head_init(&bus->glom);
3869	bus->txbound = BRCMF_TXBOUND;
3870	bus->rxbound = BRCMF_RXBOUND;
3871	bus->txminmax = BRCMF_TXMINMAX;
3872	bus->tx_seq = SDPCM_SEQUENCE_WRAP - 1;
3873	bus->usebufpool = false;	/* Use bufpool if allocated,
3874					 else use locally malloced rxbuf */
3875
3876	/* attempt to attach to the dongle */
3877	if (!(brcmf_sdbrcm_probe_attach(bus, regsva))) {
3878		brcmf_dbg(ERROR, "brcmf_sdbrcm_probe_attach failed\n");
3879		goto fail;
3880	}
3881
3882	spin_lock_init(&bus->txqlock);
3883	init_waitqueue_head(&bus->ctrl_wait);
3884	init_waitqueue_head(&bus->dcmd_resp_wait);
3885
3886	/* Set up the watchdog timer */
3887	init_timer(&bus->timer);
3888	bus->timer.data = (unsigned long)bus;
3889	bus->timer.function = brcmf_sdbrcm_watchdog;
3890
3891	/* Initialize thread based operation and lock */
3892	sema_init(&bus->sdsem, 1);
3893
3894	/* Initialize watchdog thread */
3895	init_completion(&bus->watchdog_wait);
3896	bus->watchdog_tsk = kthread_run(brcmf_sdbrcm_watchdog_thread,
3897					bus, "brcmf_watchdog");
3898	if (IS_ERR(bus->watchdog_tsk)) {
3899		pr_warn("brcmf_watchdog thread failed to start\n");
3900		bus->watchdog_tsk = NULL;
3901	}
3902	/* Initialize DPC thread */
3903	init_completion(&bus->dpc_wait);
3904	bus->dpc_tsk = kthread_run(brcmf_sdbrcm_dpc_thread,
3905				   bus, "brcmf_dpc");
3906	if (IS_ERR(bus->dpc_tsk)) {
3907		pr_warn("brcmf_dpc thread failed to start\n");
3908		bus->dpc_tsk = NULL;
3909	}
3910
3911	/* Assign bus interface call back */
3912	bus->sdiodev->bus_if->brcmf_bus_stop = brcmf_sdbrcm_bus_stop;
3913	bus->sdiodev->bus_if->brcmf_bus_init = brcmf_sdbrcm_bus_init;
3914	bus->sdiodev->bus_if->brcmf_bus_txdata = brcmf_sdbrcm_bus_txdata;
3915	bus->sdiodev->bus_if->brcmf_bus_txctl = brcmf_sdbrcm_bus_txctl;
3916	bus->sdiodev->bus_if->brcmf_bus_rxctl = brcmf_sdbrcm_bus_rxctl;
3917	/* Attach to the brcmf/OS/network interface */
3918	ret = brcmf_attach(SDPCM_RESERVE, bus->sdiodev->dev);
3919	if (ret != 0) {
3920		brcmf_dbg(ERROR, "brcmf_attach failed\n");
3921		goto fail;
3922	}
3923
3924	/* Allocate buffers */
3925	if (!(brcmf_sdbrcm_probe_malloc(bus))) {
3926		brcmf_dbg(ERROR, "brcmf_sdbrcm_probe_malloc failed\n");
3927		goto fail;
3928	}
3929
3930	if (!(brcmf_sdbrcm_probe_init(bus))) {
3931		brcmf_dbg(ERROR, "brcmf_sdbrcm_probe_init failed\n");
3932		goto fail;
3933	}
3934
3935	/* Register interrupt callback, but mask it (not operational yet). */
3936	brcmf_dbg(INTR, "disable SDIO interrupts (not interested yet)\n");
3937	ret = brcmf_sdcard_intr_reg(bus->sdiodev);
3938	if (ret != 0) {
3939		brcmf_dbg(ERROR, "FAILED: sdcard_intr_reg returned %d\n", ret);
3940		goto fail;
3941	}
3942	brcmf_dbg(INTR, "registered SDIO interrupt function ok\n");
3943
3944	brcmf_dbg(INFO, "completed!!\n");
3945
3946	/* if firmware path present try to download and bring up bus */
3947	ret = brcmf_bus_start(bus->sdiodev->dev);
3948	if (ret != 0) {
3949		if (ret == -ENOLINK) {
3950			brcmf_dbg(ERROR, "dongle is not responding\n");
3951			goto fail;
3952		}
3953	}
3954
3955	/* add interface and open for business */
3956	if (brcmf_add_if(bus->sdiodev->dev, 0, "wlan%d", NULL)) {
3957		brcmf_dbg(ERROR, "Add primary net device interface failed!!\n");
3958		goto fail;
3959	}
3960
3961	return bus;
3962
3963fail:
3964	brcmf_sdbrcm_release(bus);
3965	return NULL;
3966}
3967
3968void brcmf_sdbrcm_disconnect(void *ptr)
3969{
3970	struct brcmf_sdio *bus = (struct brcmf_sdio *)ptr;
3971
3972	brcmf_dbg(TRACE, "Enter\n");
3973
3974	if (bus)
3975		brcmf_sdbrcm_release(bus);
3976
3977	brcmf_dbg(TRACE, "Disconnected\n");
3978}
3979
3980void
3981brcmf_sdbrcm_wd_timer(struct brcmf_sdio *bus, uint wdtick)
3982{
3983	/* Totally stop the timer */
3984	if (!wdtick && bus->wd_timer_valid) {
3985		del_timer_sync(&bus->timer);
3986		bus->wd_timer_valid = false;
3987		bus->save_ms = wdtick;
3988		return;
3989	}
3990
3991	/* don't start the wd until fw is loaded */
3992	if (bus->sdiodev->bus_if->state == BRCMF_BUS_DOWN)
3993		return;
3994
3995	if (wdtick) {
3996		if (bus->save_ms != BRCMF_WD_POLL_MS) {
3997			if (bus->wd_timer_valid)
3998				/* Stop timer and restart at new value */
3999				del_timer_sync(&bus->timer);
4000
4001			/* Create timer again when watchdog period is
4002			   dynamically changed or in the first instance
4003			 */
4004			bus->timer.expires =
4005				jiffies + BRCMF_WD_POLL_MS * HZ / 1000;
4006			add_timer(&bus->timer);
4007
4008		} else {
4009			/* Re arm the timer, at last watchdog period */
4010			mod_timer(&bus->timer,
4011				jiffies + BRCMF_WD_POLL_MS * HZ / 1000);
4012		}
4013
4014		bus->wd_timer_valid = true;
4015		bus->save_ms = wdtick;
4016	}
4017}
4018