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