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