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/atomic.h>
19 #include <linux/kernel.h>
20 #include <linux/kthread.h>
21 #include <linux/printk.h>
22 #include <linux/pci_ids.h>
23 #include <linux/netdevice.h>
24 #include <linux/interrupt.h>
25 #include <linux/sched/signal.h>
26 #include <linux/mmc/sdio.h>
27 #include <linux/mmc/sdio_ids.h>
28 #include <linux/mmc/sdio_func.h>
29 #include <linux/mmc/card.h>
30 #include <linux/semaphore.h>
31 #include <linux/firmware.h>
32 #include <linux/module.h>
33 #include <linux/bcma/bcma.h>
34 #include <linux/debugfs.h>
35 #include <linux/vmalloc.h>
36 #include <asm/unaligned.h>
37 #include <defs.h>
38 #include <brcmu_wifi.h>
39 #include <brcmu_utils.h>
40 #include <brcm_hw_ids.h>
41 #include <soc.h>
42 #include "sdio.h"
43 #include "chip.h"
44 #include "firmware.h"
45 #include "core.h"
46 #include "common.h"
47 #include "bcdc.h"
48 
49 #define DCMD_RESP_TIMEOUT	msecs_to_jiffies(2500)
50 #define CTL_DONE_TIMEOUT	msecs_to_jiffies(2500)
51 
52 #ifdef DEBUG
53 
54 #define BRCMF_TRAP_INFO_SIZE	80
55 
56 #define CBUF_LEN	(128)
57 
58 /* Device console log buffer state */
59 #define CONSOLE_BUFFER_MAX	2024
60 
61 struct rte_log_le {
62 	__le32 buf;		/* Can't be pointer on (64-bit) hosts */
63 	__le32 buf_size;
64 	__le32 idx;
65 	char *_buf_compat;	/* Redundant pointer for backward compat. */
66 };
67 
68 struct rte_console {
69 	/* Virtual UART
70 	 * When there is no UART (e.g. Quickturn),
71 	 * the host should write a complete
72 	 * input line directly into cbuf and then write
73 	 * the length into vcons_in.
74 	 * This may also be used when there is a real UART
75 	 * (at risk of conflicting with
76 	 * the real UART).  vcons_out is currently unused.
77 	 */
78 	uint vcons_in;
79 	uint vcons_out;
80 
81 	/* Output (logging) buffer
82 	 * Console output is written to a ring buffer log_buf at index log_idx.
83 	 * The host may read the output when it sees log_idx advance.
84 	 * Output will be lost if the output wraps around faster than the host
85 	 * polls.
86 	 */
87 	struct rte_log_le log_le;
88 
89 	/* Console input line buffer
90 	 * Characters are read one at a time into cbuf
91 	 * until <CR> is received, then
92 	 * the buffer is processed as a command line.
93 	 * Also used for virtual UART.
94 	 */
95 	uint cbuf_idx;
96 	char cbuf[CBUF_LEN];
97 };
98 
99 #endif				/* DEBUG */
100 #include <chipcommon.h>
101 
102 #include "bus.h"
103 #include "debug.h"
104 #include "tracepoint.h"
105 
106 #define TXQLEN		2048	/* bulk tx queue length */
107 #define TXHI		(TXQLEN - 256)	/* turn on flow control above TXHI */
108 #define TXLOW		(TXHI - 256)	/* turn off flow control below TXLOW */
109 #define PRIOMASK	7
110 
111 #define TXRETRIES	2	/* # of retries for tx frames */
112 
113 #define BRCMF_RXBOUND	50	/* Default for max rx frames in
114 				 one scheduling */
115 
116 #define BRCMF_TXBOUND	20	/* Default for max tx frames in
117 				 one scheduling */
118 
119 #define BRCMF_TXMINMAX	1	/* Max tx frames if rx still pending */
120 
121 #define MEMBLOCK	2048	/* Block size used for downloading
122 				 of dongle image */
123 #define MAX_DATA_BUF	(32 * 1024)	/* Must be large enough to hold
124 				 biggest possible glom */
125 
126 #define BRCMF_FIRSTREAD	(1 << 6)
127 
128 #define BRCMF_CONSOLE	10	/* watchdog interval to poll console */
129 
130 /* SBSDIO_DEVICE_CTL */
131 
132 /* 1: device will assert busy signal when receiving CMD53 */
133 #define SBSDIO_DEVCTL_SETBUSY		0x01
134 /* 1: assertion of sdio interrupt is synchronous to the sdio clock */
135 #define SBSDIO_DEVCTL_SPI_INTR_SYNC	0x02
136 /* 1: mask all interrupts to host except the chipActive (rev 8) */
137 #define SBSDIO_DEVCTL_CA_INT_ONLY	0x04
138 /* 1: isolate internal sdio signals, put external pads in tri-state; requires
139  * sdio bus power cycle to clear (rev 9) */
140 #define SBSDIO_DEVCTL_PADS_ISO		0x08
141 /* Force SD->SB reset mapping (rev 11) */
142 #define SBSDIO_DEVCTL_SB_RST_CTL	0x30
143 /*   Determined by CoreControl bit */
144 #define SBSDIO_DEVCTL_RST_CORECTL	0x00
145 /*   Force backplane reset */
146 #define SBSDIO_DEVCTL_RST_BPRESET	0x10
147 /*   Force no backplane reset */
148 #define SBSDIO_DEVCTL_RST_NOBPRESET	0x20
149 
150 /* direct(mapped) cis space */
151 
152 /* MAPPED common CIS address */
153 #define SBSDIO_CIS_BASE_COMMON		0x1000
154 /* maximum bytes in one CIS */
155 #define SBSDIO_CIS_SIZE_LIMIT		0x200
156 /* cis offset addr is < 17 bits */
157 #define SBSDIO_CIS_OFT_ADDR_MASK	0x1FFFF
158 
159 /* manfid tuple length, include tuple, link bytes */
160 #define SBSDIO_CIS_MANFID_TUPLE_LEN	6
161 
162 #define SD_REG(field) \
163 		(offsetof(struct sdpcmd_regs, field))
164 
165 /* SDIO function 1 register CHIPCLKCSR */
166 /* Force ALP request to backplane */
167 #define SBSDIO_FORCE_ALP		0x01
168 /* Force HT request to backplane */
169 #define SBSDIO_FORCE_HT			0x02
170 /* Force ILP request to backplane */
171 #define SBSDIO_FORCE_ILP		0x04
172 /* Make ALP ready (power up xtal) */
173 #define SBSDIO_ALP_AVAIL_REQ		0x08
174 /* Make HT ready (power up PLL) */
175 #define SBSDIO_HT_AVAIL_REQ		0x10
176 /* Squelch clock requests from HW */
177 #define SBSDIO_FORCE_HW_CLKREQ_OFF	0x20
178 /* Status: ALP is ready */
179 #define SBSDIO_ALP_AVAIL		0x40
180 /* Status: HT is ready */
181 #define SBSDIO_HT_AVAIL			0x80
182 #define SBSDIO_CSR_MASK			0x1F
183 #define SBSDIO_AVBITS		(SBSDIO_HT_AVAIL | SBSDIO_ALP_AVAIL)
184 #define SBSDIO_ALPAV(regval)	((regval) & SBSDIO_AVBITS)
185 #define SBSDIO_HTAV(regval)	(((regval) & SBSDIO_AVBITS) == SBSDIO_AVBITS)
186 #define SBSDIO_ALPONLY(regval)	(SBSDIO_ALPAV(regval) && !SBSDIO_HTAV(regval))
187 #define SBSDIO_CLKAV(regval, alponly) \
188 	(SBSDIO_ALPAV(regval) && (alponly ? 1 : SBSDIO_HTAV(regval)))
189 
190 /* intstatus */
191 #define I_SMB_SW0	(1 << 0)	/* To SB Mail S/W interrupt 0 */
192 #define I_SMB_SW1	(1 << 1)	/* To SB Mail S/W interrupt 1 */
193 #define I_SMB_SW2	(1 << 2)	/* To SB Mail S/W interrupt 2 */
194 #define I_SMB_SW3	(1 << 3)	/* To SB Mail S/W interrupt 3 */
195 #define I_SMB_SW_MASK	0x0000000f	/* To SB Mail S/W interrupts mask */
196 #define I_SMB_SW_SHIFT	0	/* To SB Mail S/W interrupts shift */
197 #define I_HMB_SW0	(1 << 4)	/* To Host Mail S/W interrupt 0 */
198 #define I_HMB_SW1	(1 << 5)	/* To Host Mail S/W interrupt 1 */
199 #define I_HMB_SW2	(1 << 6)	/* To Host Mail S/W interrupt 2 */
200 #define I_HMB_SW3	(1 << 7)	/* To Host Mail S/W interrupt 3 */
201 #define I_HMB_SW_MASK	0x000000f0	/* To Host Mail S/W interrupts mask */
202 #define I_HMB_SW_SHIFT	4	/* To Host Mail S/W interrupts shift */
203 #define I_WR_OOSYNC	(1 << 8)	/* Write Frame Out Of Sync */
204 #define I_RD_OOSYNC	(1 << 9)	/* Read Frame Out Of Sync */
205 #define	I_PC		(1 << 10)	/* descriptor error */
206 #define	I_PD		(1 << 11)	/* data error */
207 #define	I_DE		(1 << 12)	/* Descriptor protocol Error */
208 #define	I_RU		(1 << 13)	/* Receive descriptor Underflow */
209 #define	I_RO		(1 << 14)	/* Receive fifo Overflow */
210 #define	I_XU		(1 << 15)	/* Transmit fifo Underflow */
211 #define	I_RI		(1 << 16)	/* Receive Interrupt */
212 #define I_BUSPWR	(1 << 17)	/* SDIO Bus Power Change (rev 9) */
213 #define I_XMTDATA_AVAIL (1 << 23)	/* bits in fifo */
214 #define	I_XI		(1 << 24)	/* Transmit Interrupt */
215 #define I_RF_TERM	(1 << 25)	/* Read Frame Terminate */
216 #define I_WF_TERM	(1 << 26)	/* Write Frame Terminate */
217 #define I_PCMCIA_XU	(1 << 27)	/* PCMCIA Transmit FIFO Underflow */
218 #define I_SBINT		(1 << 28)	/* sbintstatus Interrupt */
219 #define I_CHIPACTIVE	(1 << 29)	/* chip from doze to active state */
220 #define I_SRESET	(1 << 30)	/* CCCR RES interrupt */
221 #define I_IOE2		(1U << 31)	/* CCCR IOE2 Bit Changed */
222 #define	I_ERRORS	(I_PC | I_PD | I_DE | I_RU | I_RO | I_XU)
223 #define I_DMA		(I_RI | I_XI | I_ERRORS)
224 
225 /* corecontrol */
226 #define CC_CISRDY		(1 << 0)	/* CIS Ready */
227 #define CC_BPRESEN		(1 << 1)	/* CCCR RES signal */
228 #define CC_F2RDY		(1 << 2)	/* set CCCR IOR2 bit */
229 #define CC_CLRPADSISO		(1 << 3)	/* clear SDIO pads isolation */
230 #define CC_XMTDATAAVAIL_MODE	(1 << 4)
231 #define CC_XMTDATAAVAIL_CTRL	(1 << 5)
232 
233 /* SDA_FRAMECTRL */
234 #define SFC_RF_TERM	(1 << 0)	/* Read Frame Terminate */
235 #define SFC_WF_TERM	(1 << 1)	/* Write Frame Terminate */
236 #define SFC_CRC4WOOS	(1 << 2)	/* CRC error for write out of sync */
237 #define SFC_ABORTALL	(1 << 3)	/* Abort all in-progress frames */
238 
239 /*
240  * Software allocation of To SB Mailbox resources
241  */
242 
243 /* tosbmailbox bits corresponding to intstatus bits */
244 #define SMB_NAK		(1 << 0)	/* Frame NAK */
245 #define SMB_INT_ACK	(1 << 1)	/* Host Interrupt ACK */
246 #define SMB_USE_OOB	(1 << 2)	/* Use OOB Wakeup */
247 #define SMB_DEV_INT	(1 << 3)	/* Miscellaneous Interrupt */
248 
249 /* tosbmailboxdata */
250 #define SMB_DATA_VERSION_SHIFT	16	/* host protocol version */
251 
252 /*
253  * Software allocation of To Host Mailbox resources
254  */
255 
256 /* intstatus bits */
257 #define I_HMB_FC_STATE	I_HMB_SW0	/* Flow Control State */
258 #define I_HMB_FC_CHANGE	I_HMB_SW1	/* Flow Control State Changed */
259 #define I_HMB_FRAME_IND	I_HMB_SW2	/* Frame Indication */
260 #define I_HMB_HOST_INT	I_HMB_SW3	/* Miscellaneous Interrupt */
261 
262 /* tohostmailboxdata */
263 #define HMB_DATA_NAKHANDLED	0x0001	/* retransmit NAK'd frame */
264 #define HMB_DATA_DEVREADY	0x0002	/* talk to host after enable */
265 #define HMB_DATA_FC		0x0004	/* per prio flowcontrol update flag */
266 #define HMB_DATA_FWREADY	0x0008	/* fw ready for protocol activity */
267 #define HMB_DATA_FWHALT		0x0010	/* firmware halted */
268 
269 #define HMB_DATA_FCDATA_MASK	0xff000000
270 #define HMB_DATA_FCDATA_SHIFT	24
271 
272 #define HMB_DATA_VERSION_MASK	0x00ff0000
273 #define HMB_DATA_VERSION_SHIFT	16
274 
275 /*
276  * Software-defined protocol header
277  */
278 
279 /* Current protocol version */
280 #define SDPCM_PROT_VERSION	4
281 
282 /*
283  * Shared structure between dongle and the host.
284  * The structure contains pointers to trap or assert information.
285  */
286 #define SDPCM_SHARED_VERSION       0x0003
287 #define SDPCM_SHARED_VERSION_MASK  0x00FF
288 #define SDPCM_SHARED_ASSERT_BUILT  0x0100
289 #define SDPCM_SHARED_ASSERT        0x0200
290 #define SDPCM_SHARED_TRAP          0x0400
291 
292 /* Space for header read, limit for data packets */
293 #define MAX_HDR_READ	(1 << 6)
294 #define MAX_RX_DATASZ	2048
295 
296 /* Bump up limit on waiting for HT to account for first startup;
297  * if the image is doing a CRC calculation before programming the PMU
298  * for HT availability, it could take a couple hundred ms more, so
299  * max out at a 1 second (1000000us).
300  */
301 #undef PMU_MAX_TRANSITION_DLY
302 #define PMU_MAX_TRANSITION_DLY 1000000
303 
304 /* Value for ChipClockCSR during initial setup */
305 #define BRCMF_INIT_CLKCTL1	(SBSDIO_FORCE_HW_CLKREQ_OFF |	\
306 					SBSDIO_ALP_AVAIL_REQ)
307 
308 /* Flags for SDH calls */
309 #define F2SYNC	(SDIO_REQ_4BYTE | SDIO_REQ_FIXED)
310 
311 #define BRCMF_IDLE_ACTIVE	0	/* Do not request any SD clock change
312 					 * when idle
313 					 */
314 #define BRCMF_IDLE_INTERVAL	1
315 
316 #define KSO_WAIT_US 50
317 #define MAX_KSO_ATTEMPTS (PMU_MAX_TRANSITION_DLY/KSO_WAIT_US)
318 #define BRCMF_SDIO_MAX_ACCESS_ERRORS	5
319 
320 /*
321  * Conversion of 802.1D priority to precedence level
322  */
323 static uint prio2prec(u32 prio)
324 {
325 	return (prio == PRIO_8021D_NONE || prio == PRIO_8021D_BE) ?
326 	       (prio^2) : prio;
327 }
328 
329 #ifdef DEBUG
330 /* Device console log buffer state */
331 struct brcmf_console {
332 	uint count;		/* Poll interval msec counter */
333 	uint log_addr;		/* Log struct address (fixed) */
334 	struct rte_log_le log_le;	/* Log struct (host copy) */
335 	uint bufsize;		/* Size of log buffer */
336 	u8 *buf;		/* Log buffer (host copy) */
337 	uint last;		/* Last buffer read index */
338 };
339 
340 struct brcmf_trap_info {
341 	__le32		type;
342 	__le32		epc;
343 	__le32		cpsr;
344 	__le32		spsr;
345 	__le32		r0;	/* a1 */
346 	__le32		r1;	/* a2 */
347 	__le32		r2;	/* a3 */
348 	__le32		r3;	/* a4 */
349 	__le32		r4;	/* v1 */
350 	__le32		r5;	/* v2 */
351 	__le32		r6;	/* v3 */
352 	__le32		r7;	/* v4 */
353 	__le32		r8;	/* v5 */
354 	__le32		r9;	/* sb/v6 */
355 	__le32		r10;	/* sl/v7 */
356 	__le32		r11;	/* fp/v8 */
357 	__le32		r12;	/* ip */
358 	__le32		r13;	/* sp */
359 	__le32		r14;	/* lr */
360 	__le32		pc;	/* r15 */
361 };
362 #endif				/* DEBUG */
363 
364 struct sdpcm_shared {
365 	u32 flags;
366 	u32 trap_addr;
367 	u32 assert_exp_addr;
368 	u32 assert_file_addr;
369 	u32 assert_line;
370 	u32 console_addr;	/* Address of struct rte_console */
371 	u32 msgtrace_addr;
372 	u8 tag[32];
373 	u32 brpt_addr;
374 };
375 
376 struct sdpcm_shared_le {
377 	__le32 flags;
378 	__le32 trap_addr;
379 	__le32 assert_exp_addr;
380 	__le32 assert_file_addr;
381 	__le32 assert_line;
382 	__le32 console_addr;	/* Address of struct rte_console */
383 	__le32 msgtrace_addr;
384 	u8 tag[32];
385 	__le32 brpt_addr;
386 };
387 
388 /* dongle SDIO bus specific header info */
389 struct brcmf_sdio_hdrinfo {
390 	u8 seq_num;
391 	u8 channel;
392 	u16 len;
393 	u16 len_left;
394 	u16 len_nxtfrm;
395 	u8 dat_offset;
396 	bool lastfrm;
397 	u16 tail_pad;
398 };
399 
400 /*
401  * hold counter variables
402  */
403 struct brcmf_sdio_count {
404 	uint intrcount;		/* Count of device interrupt callbacks */
405 	uint lastintrs;		/* Count as of last watchdog timer */
406 	uint pollcnt;		/* Count of active polls */
407 	uint regfails;		/* Count of R_REG failures */
408 	uint tx_sderrs;		/* Count of tx attempts with sd errors */
409 	uint fcqueued;		/* Tx packets that got queued */
410 	uint rxrtx;		/* Count of rtx requests (NAK to dongle) */
411 	uint rx_toolong;	/* Receive frames too long to receive */
412 	uint rxc_errors;	/* SDIO errors when reading control frames */
413 	uint rx_hdrfail;	/* SDIO errors on header reads */
414 	uint rx_badhdr;		/* Bad received headers (roosync?) */
415 	uint rx_badseq;		/* Mismatched rx sequence number */
416 	uint fc_rcvd;		/* Number of flow-control events received */
417 	uint fc_xoff;		/* Number which turned on flow-control */
418 	uint fc_xon;		/* Number which turned off flow-control */
419 	uint rxglomfail;	/* Failed deglom attempts */
420 	uint rxglomframes;	/* Number of glom frames (superframes) */
421 	uint rxglompkts;	/* Number of packets from glom frames */
422 	uint f2rxhdrs;		/* Number of header reads */
423 	uint f2rxdata;		/* Number of frame data reads */
424 	uint f2txdata;		/* Number of f2 frame writes */
425 	uint f1regdata;		/* Number of f1 register accesses */
426 	uint tickcnt;		/* Number of watchdog been schedule */
427 	ulong tx_ctlerrs;	/* Err of sending ctrl frames */
428 	ulong tx_ctlpkts;	/* Ctrl frames sent to dongle */
429 	ulong rx_ctlerrs;	/* Err of processing rx ctrl frames */
430 	ulong rx_ctlpkts;	/* Ctrl frames processed from dongle */
431 	ulong rx_readahead_cnt;	/* packets where header read-ahead was used */
432 };
433 
434 /* misc chip info needed by some of the routines */
435 /* Private data for SDIO bus interaction */
436 struct brcmf_sdio {
437 	struct brcmf_sdio_dev *sdiodev;	/* sdio device handler */
438 	struct brcmf_chip *ci;	/* Chip info struct */
439 	struct brcmf_core *sdio_core; /* sdio core info struct */
440 
441 	u32 hostintmask;	/* Copy of Host Interrupt Mask */
442 	atomic_t intstatus;	/* Intstatus bits (events) pending */
443 	atomic_t fcstate;	/* State of dongle flow-control */
444 
445 	uint blocksize;		/* Block size of SDIO transfers */
446 	uint roundup;		/* Max roundup limit */
447 
448 	struct pktq txq;	/* Queue length used for flow-control */
449 	u8 flowcontrol;	/* per prio flow control bitmask */
450 	u8 tx_seq;		/* Transmit sequence number (next) */
451 	u8 tx_max;		/* Maximum transmit sequence allowed */
452 
453 	u8 *hdrbuf;		/* buffer for handling rx frame */
454 	u8 *rxhdr;		/* Header of current rx frame (in hdrbuf) */
455 	u8 rx_seq;		/* Receive sequence number (expected) */
456 	struct brcmf_sdio_hdrinfo cur_read;
457 				/* info of current read frame */
458 	bool rxskip;		/* Skip receive (awaiting NAK ACK) */
459 	bool rxpending;		/* Data frame pending in dongle */
460 
461 	uint rxbound;		/* Rx frames to read before resched */
462 	uint txbound;		/* Tx frames to send before resched */
463 	uint txminmax;
464 
465 	struct sk_buff *glomd;	/* Packet containing glomming descriptor */
466 	struct sk_buff_head glom; /* Packet list for glommed superframe */
467 
468 	u8 *rxbuf;		/* Buffer for receiving control packets */
469 	uint rxblen;		/* Allocated length of rxbuf */
470 	u8 *rxctl;		/* Aligned pointer into rxbuf */
471 	u8 *rxctl_orig;		/* pointer for freeing rxctl */
472 	uint rxlen;		/* Length of valid data in buffer */
473 	spinlock_t rxctl_lock;	/* protection lock for ctrl frame resources */
474 
475 	u8 sdpcm_ver;	/* Bus protocol reported by dongle */
476 
477 	bool intr;		/* Use interrupts */
478 	bool poll;		/* Use polling */
479 	atomic_t ipend;		/* Device interrupt is pending */
480 	uint spurious;		/* Count of spurious interrupts */
481 	uint pollrate;		/* Ticks between device polls */
482 	uint polltick;		/* Tick counter */
483 
484 #ifdef DEBUG
485 	uint console_interval;
486 	struct brcmf_console console;	/* Console output polling support */
487 	uint console_addr;	/* Console address from shared struct */
488 #endif				/* DEBUG */
489 
490 	uint clkstate;		/* State of sd and backplane clock(s) */
491 	s32 idletime;		/* Control for activity timeout */
492 	s32 idlecount;		/* Activity timeout counter */
493 	s32 idleclock;		/* How to set bus driver when idle */
494 	bool rxflow_mode;	/* Rx flow control mode */
495 	bool rxflow;		/* Is rx flow control on */
496 	bool alp_only;		/* Don't use HT clock (ALP only) */
497 
498 	u8 *ctrl_frame_buf;
499 	u16 ctrl_frame_len;
500 	bool ctrl_frame_stat;
501 	int ctrl_frame_err;
502 
503 	spinlock_t txq_lock;		/* protect bus->txq */
504 	wait_queue_head_t ctrl_wait;
505 	wait_queue_head_t dcmd_resp_wait;
506 
507 	struct timer_list timer;
508 	struct completion watchdog_wait;
509 	struct task_struct *watchdog_tsk;
510 	bool wd_active;
511 
512 	struct workqueue_struct *brcmf_wq;
513 	struct work_struct datawork;
514 	bool dpc_triggered;
515 	bool dpc_running;
516 
517 	bool txoff;		/* Transmit flow-controlled */
518 	struct brcmf_sdio_count sdcnt;
519 	bool sr_enabled; /* SaveRestore enabled */
520 	bool sleeping;
521 
522 	u8 tx_hdrlen;		/* sdio bus header length for tx packet */
523 	bool txglom;		/* host tx glomming enable flag */
524 	u16 head_align;		/* buffer pointer alignment */
525 	u16 sgentry_align;	/* scatter-gather buffer alignment */
526 };
527 
528 /* clkstate */
529 #define CLK_NONE	0
530 #define CLK_SDONLY	1
531 #define CLK_PENDING	2
532 #define CLK_AVAIL	3
533 
534 #ifdef DEBUG
535 static int qcount[NUMPRIO];
536 #endif				/* DEBUG */
537 
538 #define DEFAULT_SDIO_DRIVE_STRENGTH	6	/* in milliamps */
539 
540 #define RETRYCHAN(chan) ((chan) == SDPCM_EVENT_CHANNEL)
541 
542 /* Limit on rounding up frames */
543 static const uint max_roundup = 512;
544 
545 #ifdef CONFIG_ARCH_DMA_ADDR_T_64BIT
546 #define ALIGNMENT  8
547 #else
548 #define ALIGNMENT  4
549 #endif
550 
551 enum brcmf_sdio_frmtype {
552 	BRCMF_SDIO_FT_NORMAL,
553 	BRCMF_SDIO_FT_SUPER,
554 	BRCMF_SDIO_FT_SUB,
555 };
556 
557 #define SDIOD_DRVSTR_KEY(chip, pmu)     (((chip) << 16) | (pmu))
558 
559 /* SDIO Pad drive strength to select value mappings */
560 struct sdiod_drive_str {
561 	u8 strength;	/* Pad Drive Strength in mA */
562 	u8 sel;		/* Chip-specific select value */
563 };
564 
565 /* SDIO Drive Strength to sel value table for PMU Rev 11 (1.8V) */
566 static const struct sdiod_drive_str sdiod_drvstr_tab1_1v8[] = {
567 	{32, 0x6},
568 	{26, 0x7},
569 	{22, 0x4},
570 	{16, 0x5},
571 	{12, 0x2},
572 	{8, 0x3},
573 	{4, 0x0},
574 	{0, 0x1}
575 };
576 
577 /* SDIO Drive Strength to sel value table for PMU Rev 13 (1.8v) */
578 static const struct sdiod_drive_str sdiod_drive_strength_tab5_1v8[] = {
579 	{6, 0x7},
580 	{5, 0x6},
581 	{4, 0x5},
582 	{3, 0x4},
583 	{2, 0x2},
584 	{1, 0x1},
585 	{0, 0x0}
586 };
587 
588 /* SDIO Drive Strength to sel value table for PMU Rev 17 (1.8v) */
589 static const struct sdiod_drive_str sdiod_drvstr_tab6_1v8[] = {
590 	{3, 0x3},
591 	{2, 0x2},
592 	{1, 0x1},
593 	{0, 0x0} };
594 
595 /* SDIO Drive Strength to sel value table for 43143 PMU Rev 17 (3.3V) */
596 static const struct sdiod_drive_str sdiod_drvstr_tab2_3v3[] = {
597 	{16, 0x7},
598 	{12, 0x5},
599 	{8,  0x3},
600 	{4,  0x1}
601 };
602 
603 BRCMF_FW_DEF(43143, "brcmfmac43143-sdio");
604 BRCMF_FW_DEF(43241B0, "brcmfmac43241b0-sdio");
605 BRCMF_FW_DEF(43241B4, "brcmfmac43241b4-sdio");
606 BRCMF_FW_DEF(43241B5, "brcmfmac43241b5-sdio");
607 BRCMF_FW_DEF(4329, "brcmfmac4329-sdio");
608 BRCMF_FW_DEF(4330, "brcmfmac4330-sdio");
609 BRCMF_FW_DEF(4334, "brcmfmac4334-sdio");
610 BRCMF_FW_DEF(43340, "brcmfmac43340-sdio");
611 BRCMF_FW_DEF(4335, "brcmfmac4335-sdio");
612 BRCMF_FW_DEF(43362, "brcmfmac43362-sdio");
613 BRCMF_FW_DEF(4339, "brcmfmac4339-sdio");
614 BRCMF_FW_DEF(43430A0, "brcmfmac43430a0-sdio");
615 /* Note the names are not postfixed with a1 for backward compatibility */
616 BRCMF_FW_DEF(43430A1, "brcmfmac43430-sdio");
617 BRCMF_FW_DEF(43455, "brcmfmac43455-sdio");
618 BRCMF_FW_DEF(4354, "brcmfmac4354-sdio");
619 BRCMF_FW_DEF(4356, "brcmfmac4356-sdio");
620 BRCMF_FW_DEF(4373, "brcmfmac4373-sdio");
621 
622 static const struct brcmf_firmware_mapping brcmf_sdio_fwnames[] = {
623 	BRCMF_FW_ENTRY(BRCM_CC_43143_CHIP_ID, 0xFFFFFFFF, 43143),
624 	BRCMF_FW_ENTRY(BRCM_CC_43241_CHIP_ID, 0x0000001F, 43241B0),
625 	BRCMF_FW_ENTRY(BRCM_CC_43241_CHIP_ID, 0x00000020, 43241B4),
626 	BRCMF_FW_ENTRY(BRCM_CC_43241_CHIP_ID, 0xFFFFFFC0, 43241B5),
627 	BRCMF_FW_ENTRY(BRCM_CC_4329_CHIP_ID, 0xFFFFFFFF, 4329),
628 	BRCMF_FW_ENTRY(BRCM_CC_4330_CHIP_ID, 0xFFFFFFFF, 4330),
629 	BRCMF_FW_ENTRY(BRCM_CC_4334_CHIP_ID, 0xFFFFFFFF, 4334),
630 	BRCMF_FW_ENTRY(BRCM_CC_43340_CHIP_ID, 0xFFFFFFFF, 43340),
631 	BRCMF_FW_ENTRY(BRCM_CC_43341_CHIP_ID, 0xFFFFFFFF, 43340),
632 	BRCMF_FW_ENTRY(BRCM_CC_4335_CHIP_ID, 0xFFFFFFFF, 4335),
633 	BRCMF_FW_ENTRY(BRCM_CC_43362_CHIP_ID, 0xFFFFFFFE, 43362),
634 	BRCMF_FW_ENTRY(BRCM_CC_4339_CHIP_ID, 0xFFFFFFFF, 4339),
635 	BRCMF_FW_ENTRY(BRCM_CC_43430_CHIP_ID, 0x00000001, 43430A0),
636 	BRCMF_FW_ENTRY(BRCM_CC_43430_CHIP_ID, 0xFFFFFFFE, 43430A1),
637 	BRCMF_FW_ENTRY(BRCM_CC_4345_CHIP_ID, 0xFFFFFFC0, 43455),
638 	BRCMF_FW_ENTRY(BRCM_CC_4354_CHIP_ID, 0xFFFFFFFF, 4354),
639 	BRCMF_FW_ENTRY(BRCM_CC_4356_CHIP_ID, 0xFFFFFFFF, 4356),
640 	BRCMF_FW_ENTRY(CY_CC_4373_CHIP_ID, 0xFFFFFFFF, 4373)
641 };
642 
643 static void pkt_align(struct sk_buff *p, int len, int align)
644 {
645 	uint datalign;
646 	datalign = (unsigned long)(p->data);
647 	datalign = roundup(datalign, (align)) - datalign;
648 	if (datalign)
649 		skb_pull(p, datalign);
650 	__skb_trim(p, len);
651 }
652 
653 /* To check if there's window offered */
654 static bool data_ok(struct brcmf_sdio *bus)
655 {
656 	return (u8)(bus->tx_max - bus->tx_seq) != 0 &&
657 	       ((u8)(bus->tx_max - bus->tx_seq) & 0x80) == 0;
658 }
659 
660 static int
661 brcmf_sdio_kso_control(struct brcmf_sdio *bus, bool on)
662 {
663 	u8 wr_val = 0, rd_val, cmp_val, bmask;
664 	int err = 0;
665 	int err_cnt = 0;
666 	int try_cnt = 0;
667 
668 	brcmf_dbg(TRACE, "Enter: on=%d\n", on);
669 
670 	wr_val = (on << SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT);
671 	/* 1st KSO write goes to AOS wake up core if device is asleep  */
672 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR, wr_val, &err);
673 
674 	if (on) {
675 		/* device WAKEUP through KSO:
676 		 * write bit 0 & read back until
677 		 * both bits 0 (kso bit) & 1 (dev on status) are set
678 		 */
679 		cmp_val = SBSDIO_FUNC1_SLEEPCSR_KSO_MASK |
680 			  SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK;
681 		bmask = cmp_val;
682 		usleep_range(2000, 3000);
683 	} else {
684 		/* Put device to sleep, turn off KSO */
685 		cmp_val = 0;
686 		/* only check for bit0, bit1(dev on status) may not
687 		 * get cleared right away
688 		 */
689 		bmask = SBSDIO_FUNC1_SLEEPCSR_KSO_MASK;
690 	}
691 
692 	do {
693 		/* reliable KSO bit set/clr:
694 		 * the sdiod sleep write access is synced to PMU 32khz clk
695 		 * just one write attempt may fail,
696 		 * read it back until it matches written value
697 		 */
698 		rd_val = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
699 					   &err);
700 		if (!err) {
701 			if ((rd_val & bmask) == cmp_val)
702 				break;
703 			err_cnt = 0;
704 		}
705 		/* bail out upon subsequent access errors */
706 		if (err && (err_cnt++ > BRCMF_SDIO_MAX_ACCESS_ERRORS))
707 			break;
708 
709 		udelay(KSO_WAIT_US);
710 		brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR, wr_val,
711 				   &err);
712 
713 	} while (try_cnt++ < MAX_KSO_ATTEMPTS);
714 
715 	if (try_cnt > 2)
716 		brcmf_dbg(SDIO, "try_cnt=%d rd_val=0x%x err=%d\n", try_cnt,
717 			  rd_val, err);
718 
719 	if (try_cnt > MAX_KSO_ATTEMPTS)
720 		brcmf_err("max tries: rd_val=0x%x err=%d\n", rd_val, err);
721 
722 	return err;
723 }
724 
725 #define HOSTINTMASK		(I_HMB_SW_MASK | I_CHIPACTIVE)
726 
727 /* Turn backplane clock on or off */
728 static int brcmf_sdio_htclk(struct brcmf_sdio *bus, bool on, bool pendok)
729 {
730 	int err;
731 	u8 clkctl, clkreq, devctl;
732 	unsigned long timeout;
733 
734 	brcmf_dbg(SDIO, "Enter\n");
735 
736 	clkctl = 0;
737 
738 	if (bus->sr_enabled) {
739 		bus->clkstate = (on ? CLK_AVAIL : CLK_SDONLY);
740 		return 0;
741 	}
742 
743 	if (on) {
744 		/* Request HT Avail */
745 		clkreq =
746 		    bus->alp_only ? SBSDIO_ALP_AVAIL_REQ : SBSDIO_HT_AVAIL_REQ;
747 
748 		brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
749 				   clkreq, &err);
750 		if (err) {
751 			brcmf_err("HT Avail request error: %d\n", err);
752 			return -EBADE;
753 		}
754 
755 		/* Check current status */
756 		clkctl = brcmf_sdiod_readb(bus->sdiodev,
757 					   SBSDIO_FUNC1_CHIPCLKCSR, &err);
758 		if (err) {
759 			brcmf_err("HT Avail read error: %d\n", err);
760 			return -EBADE;
761 		}
762 
763 		/* Go to pending and await interrupt if appropriate */
764 		if (!SBSDIO_CLKAV(clkctl, bus->alp_only) && pendok) {
765 			/* Allow only clock-available interrupt */
766 			devctl = brcmf_sdiod_readb(bus->sdiodev,
767 						   SBSDIO_DEVICE_CTL, &err);
768 			if (err) {
769 				brcmf_err("Devctl error setting CA: %d\n", err);
770 				return -EBADE;
771 			}
772 
773 			devctl |= SBSDIO_DEVCTL_CA_INT_ONLY;
774 			brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_DEVICE_CTL,
775 					   devctl, &err);
776 			brcmf_dbg(SDIO, "CLKCTL: set PENDING\n");
777 			bus->clkstate = CLK_PENDING;
778 
779 			return 0;
780 		} else if (bus->clkstate == CLK_PENDING) {
781 			/* Cancel CA-only interrupt filter */
782 			devctl = brcmf_sdiod_readb(bus->sdiodev,
783 						   SBSDIO_DEVICE_CTL, &err);
784 			devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
785 			brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_DEVICE_CTL,
786 					   devctl, &err);
787 		}
788 
789 		/* Otherwise, wait here (polling) for HT Avail */
790 		timeout = jiffies +
791 			  msecs_to_jiffies(PMU_MAX_TRANSITION_DLY/1000);
792 		while (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
793 			clkctl = brcmf_sdiod_readb(bus->sdiodev,
794 						   SBSDIO_FUNC1_CHIPCLKCSR,
795 						   &err);
796 			if (time_after(jiffies, timeout))
797 				break;
798 			else
799 				usleep_range(5000, 10000);
800 		}
801 		if (err) {
802 			brcmf_err("HT Avail request error: %d\n", err);
803 			return -EBADE;
804 		}
805 		if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) {
806 			brcmf_err("HT Avail timeout (%d): clkctl 0x%02x\n",
807 				  PMU_MAX_TRANSITION_DLY, clkctl);
808 			return -EBADE;
809 		}
810 
811 		/* Mark clock available */
812 		bus->clkstate = CLK_AVAIL;
813 		brcmf_dbg(SDIO, "CLKCTL: turned ON\n");
814 
815 #if defined(DEBUG)
816 		if (!bus->alp_only) {
817 			if (SBSDIO_ALPONLY(clkctl))
818 				brcmf_err("HT Clock should be on\n");
819 		}
820 #endif				/* defined (DEBUG) */
821 
822 	} else {
823 		clkreq = 0;
824 
825 		if (bus->clkstate == CLK_PENDING) {
826 			/* Cancel CA-only interrupt filter */
827 			devctl = brcmf_sdiod_readb(bus->sdiodev,
828 						   SBSDIO_DEVICE_CTL, &err);
829 			devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
830 			brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_DEVICE_CTL,
831 					   devctl, &err);
832 		}
833 
834 		bus->clkstate = CLK_SDONLY;
835 		brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
836 				   clkreq, &err);
837 		brcmf_dbg(SDIO, "CLKCTL: turned OFF\n");
838 		if (err) {
839 			brcmf_err("Failed access turning clock off: %d\n",
840 				  err);
841 			return -EBADE;
842 		}
843 	}
844 	return 0;
845 }
846 
847 /* Change idle/active SD state */
848 static int brcmf_sdio_sdclk(struct brcmf_sdio *bus, bool on)
849 {
850 	brcmf_dbg(SDIO, "Enter\n");
851 
852 	if (on)
853 		bus->clkstate = CLK_SDONLY;
854 	else
855 		bus->clkstate = CLK_NONE;
856 
857 	return 0;
858 }
859 
860 /* Transition SD and backplane clock readiness */
861 static int brcmf_sdio_clkctl(struct brcmf_sdio *bus, uint target, bool pendok)
862 {
863 #ifdef DEBUG
864 	uint oldstate = bus->clkstate;
865 #endif				/* DEBUG */
866 
867 	brcmf_dbg(SDIO, "Enter\n");
868 
869 	/* Early exit if we're already there */
870 	if (bus->clkstate == target)
871 		return 0;
872 
873 	switch (target) {
874 	case CLK_AVAIL:
875 		/* Make sure SD clock is available */
876 		if (bus->clkstate == CLK_NONE)
877 			brcmf_sdio_sdclk(bus, true);
878 		/* Now request HT Avail on the backplane */
879 		brcmf_sdio_htclk(bus, true, pendok);
880 		break;
881 
882 	case CLK_SDONLY:
883 		/* Remove HT request, or bring up SD clock */
884 		if (bus->clkstate == CLK_NONE)
885 			brcmf_sdio_sdclk(bus, true);
886 		else if (bus->clkstate == CLK_AVAIL)
887 			brcmf_sdio_htclk(bus, false, false);
888 		else
889 			brcmf_err("request for %d -> %d\n",
890 				  bus->clkstate, target);
891 		break;
892 
893 	case CLK_NONE:
894 		/* Make sure to remove HT request */
895 		if (bus->clkstate == CLK_AVAIL)
896 			brcmf_sdio_htclk(bus, false, false);
897 		/* Now remove the SD clock */
898 		brcmf_sdio_sdclk(bus, false);
899 		break;
900 	}
901 #ifdef DEBUG
902 	brcmf_dbg(SDIO, "%d -> %d\n", oldstate, bus->clkstate);
903 #endif				/* DEBUG */
904 
905 	return 0;
906 }
907 
908 static int
909 brcmf_sdio_bus_sleep(struct brcmf_sdio *bus, bool sleep, bool pendok)
910 {
911 	int err = 0;
912 	u8 clkcsr;
913 
914 	brcmf_dbg(SDIO, "Enter: request %s currently %s\n",
915 		  (sleep ? "SLEEP" : "WAKE"),
916 		  (bus->sleeping ? "SLEEP" : "WAKE"));
917 
918 	/* If SR is enabled control bus state with KSO */
919 	if (bus->sr_enabled) {
920 		/* Done if we're already in the requested state */
921 		if (sleep == bus->sleeping)
922 			goto end;
923 
924 		/* Going to sleep */
925 		if (sleep) {
926 			clkcsr = brcmf_sdiod_readb(bus->sdiodev,
927 						   SBSDIO_FUNC1_CHIPCLKCSR,
928 						   &err);
929 			if ((clkcsr & SBSDIO_CSR_MASK) == 0) {
930 				brcmf_dbg(SDIO, "no clock, set ALP\n");
931 				brcmf_sdiod_writeb(bus->sdiodev,
932 						   SBSDIO_FUNC1_CHIPCLKCSR,
933 						   SBSDIO_ALP_AVAIL_REQ, &err);
934 			}
935 			err = brcmf_sdio_kso_control(bus, false);
936 		} else {
937 			err = brcmf_sdio_kso_control(bus, true);
938 		}
939 		if (err) {
940 			brcmf_err("error while changing bus sleep state %d\n",
941 				  err);
942 			goto done;
943 		}
944 	}
945 
946 end:
947 	/* control clocks */
948 	if (sleep) {
949 		if (!bus->sr_enabled)
950 			brcmf_sdio_clkctl(bus, CLK_NONE, pendok);
951 	} else {
952 		brcmf_sdio_clkctl(bus, CLK_AVAIL, pendok);
953 		brcmf_sdio_wd_timer(bus, true);
954 	}
955 	bus->sleeping = sleep;
956 	brcmf_dbg(SDIO, "new state %s\n",
957 		  (sleep ? "SLEEP" : "WAKE"));
958 done:
959 	brcmf_dbg(SDIO, "Exit: err=%d\n", err);
960 	return err;
961 
962 }
963 
964 #ifdef DEBUG
965 static inline bool brcmf_sdio_valid_shared_address(u32 addr)
966 {
967 	return !(addr == 0 || ((~addr >> 16) & 0xffff) == (addr & 0xffff));
968 }
969 
970 static int brcmf_sdio_readshared(struct brcmf_sdio *bus,
971 				 struct sdpcm_shared *sh)
972 {
973 	u32 addr = 0;
974 	int rv;
975 	u32 shaddr = 0;
976 	struct sdpcm_shared_le sh_le;
977 	__le32 addr_le;
978 
979 	sdio_claim_host(bus->sdiodev->func1);
980 	brcmf_sdio_bus_sleep(bus, false, false);
981 
982 	/*
983 	 * Read last word in socram to determine
984 	 * address of sdpcm_shared structure
985 	 */
986 	shaddr = bus->ci->rambase + bus->ci->ramsize - 4;
987 	if (!bus->ci->rambase && brcmf_chip_sr_capable(bus->ci))
988 		shaddr -= bus->ci->srsize;
989 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, shaddr,
990 			       (u8 *)&addr_le, 4);
991 	if (rv < 0)
992 		goto fail;
993 
994 	/*
995 	 * Check if addr is valid.
996 	 * NVRAM length at the end of memory should have been overwritten.
997 	 */
998 	addr = le32_to_cpu(addr_le);
999 	if (!brcmf_sdio_valid_shared_address(addr)) {
1000 		brcmf_err("invalid sdpcm_shared address 0x%08X\n", addr);
1001 		rv = -EINVAL;
1002 		goto fail;
1003 	}
1004 
1005 	brcmf_dbg(INFO, "sdpcm_shared address 0x%08X\n", addr);
1006 
1007 	/* Read hndrte_shared structure */
1008 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr, (u8 *)&sh_le,
1009 			       sizeof(struct sdpcm_shared_le));
1010 	if (rv < 0)
1011 		goto fail;
1012 
1013 	sdio_release_host(bus->sdiodev->func1);
1014 
1015 	/* Endianness */
1016 	sh->flags = le32_to_cpu(sh_le.flags);
1017 	sh->trap_addr = le32_to_cpu(sh_le.trap_addr);
1018 	sh->assert_exp_addr = le32_to_cpu(sh_le.assert_exp_addr);
1019 	sh->assert_file_addr = le32_to_cpu(sh_le.assert_file_addr);
1020 	sh->assert_line = le32_to_cpu(sh_le.assert_line);
1021 	sh->console_addr = le32_to_cpu(sh_le.console_addr);
1022 	sh->msgtrace_addr = le32_to_cpu(sh_le.msgtrace_addr);
1023 
1024 	if ((sh->flags & SDPCM_SHARED_VERSION_MASK) > SDPCM_SHARED_VERSION) {
1025 		brcmf_err("sdpcm shared version unsupported: dhd %d dongle %d\n",
1026 			  SDPCM_SHARED_VERSION,
1027 			  sh->flags & SDPCM_SHARED_VERSION_MASK);
1028 		return -EPROTO;
1029 	}
1030 	return 0;
1031 
1032 fail:
1033 	brcmf_err("unable to obtain sdpcm_shared info: rv=%d (addr=0x%x)\n",
1034 		  rv, addr);
1035 	sdio_release_host(bus->sdiodev->func1);
1036 	return rv;
1037 }
1038 
1039 static void brcmf_sdio_get_console_addr(struct brcmf_sdio *bus)
1040 {
1041 	struct sdpcm_shared sh;
1042 
1043 	if (brcmf_sdio_readshared(bus, &sh) == 0)
1044 		bus->console_addr = sh.console_addr;
1045 }
1046 #else
1047 static void brcmf_sdio_get_console_addr(struct brcmf_sdio *bus)
1048 {
1049 }
1050 #endif /* DEBUG */
1051 
1052 static u32 brcmf_sdio_hostmail(struct brcmf_sdio *bus)
1053 {
1054 	struct brcmf_sdio_dev *sdiod = bus->sdiodev;
1055 	struct brcmf_core *core = bus->sdio_core;
1056 	u32 intstatus = 0;
1057 	u32 hmb_data;
1058 	u8 fcbits;
1059 	int ret;
1060 
1061 	brcmf_dbg(SDIO, "Enter\n");
1062 
1063 	/* Read mailbox data and ack that we did so */
1064 	hmb_data = brcmf_sdiod_readl(sdiod,
1065 				     core->base + SD_REG(tohostmailboxdata),
1066 				     &ret);
1067 
1068 	if (!ret)
1069 		brcmf_sdiod_writel(sdiod, core->base + SD_REG(tosbmailbox),
1070 				   SMB_INT_ACK, &ret);
1071 
1072 	bus->sdcnt.f1regdata += 2;
1073 
1074 	/* dongle indicates the firmware has halted/crashed */
1075 	if (hmb_data & HMB_DATA_FWHALT) {
1076 		brcmf_err("mailbox indicates firmware halted\n");
1077 		brcmf_dev_coredump(&sdiod->func1->dev);
1078 	}
1079 
1080 	/* Dongle recomposed rx frames, accept them again */
1081 	if (hmb_data & HMB_DATA_NAKHANDLED) {
1082 		brcmf_dbg(SDIO, "Dongle reports NAK handled, expect rtx of %d\n",
1083 			  bus->rx_seq);
1084 		if (!bus->rxskip)
1085 			brcmf_err("unexpected NAKHANDLED!\n");
1086 
1087 		bus->rxskip = false;
1088 		intstatus |= I_HMB_FRAME_IND;
1089 	}
1090 
1091 	/*
1092 	 * DEVREADY does not occur with gSPI.
1093 	 */
1094 	if (hmb_data & (HMB_DATA_DEVREADY | HMB_DATA_FWREADY)) {
1095 		bus->sdpcm_ver =
1096 		    (hmb_data & HMB_DATA_VERSION_MASK) >>
1097 		    HMB_DATA_VERSION_SHIFT;
1098 		if (bus->sdpcm_ver != SDPCM_PROT_VERSION)
1099 			brcmf_err("Version mismatch, dongle reports %d, "
1100 				  "expecting %d\n",
1101 				  bus->sdpcm_ver, SDPCM_PROT_VERSION);
1102 		else
1103 			brcmf_dbg(SDIO, "Dongle ready, protocol version %d\n",
1104 				  bus->sdpcm_ver);
1105 
1106 		/*
1107 		 * Retrieve console state address now that firmware should have
1108 		 * updated it.
1109 		 */
1110 		brcmf_sdio_get_console_addr(bus);
1111 	}
1112 
1113 	/*
1114 	 * Flow Control has been moved into the RX headers and this out of band
1115 	 * method isn't used any more.
1116 	 * remaining backward compatible with older dongles.
1117 	 */
1118 	if (hmb_data & HMB_DATA_FC) {
1119 		fcbits = (hmb_data & HMB_DATA_FCDATA_MASK) >>
1120 							HMB_DATA_FCDATA_SHIFT;
1121 
1122 		if (fcbits & ~bus->flowcontrol)
1123 			bus->sdcnt.fc_xoff++;
1124 
1125 		if (bus->flowcontrol & ~fcbits)
1126 			bus->sdcnt.fc_xon++;
1127 
1128 		bus->sdcnt.fc_rcvd++;
1129 		bus->flowcontrol = fcbits;
1130 	}
1131 
1132 	/* Shouldn't be any others */
1133 	if (hmb_data & ~(HMB_DATA_DEVREADY |
1134 			 HMB_DATA_NAKHANDLED |
1135 			 HMB_DATA_FC |
1136 			 HMB_DATA_FWREADY |
1137 			 HMB_DATA_FWHALT |
1138 			 HMB_DATA_FCDATA_MASK | HMB_DATA_VERSION_MASK))
1139 		brcmf_err("Unknown mailbox data content: 0x%02x\n",
1140 			  hmb_data);
1141 
1142 	return intstatus;
1143 }
1144 
1145 static void brcmf_sdio_rxfail(struct brcmf_sdio *bus, bool abort, bool rtx)
1146 {
1147 	struct brcmf_sdio_dev *sdiod = bus->sdiodev;
1148 	struct brcmf_core *core = bus->sdio_core;
1149 	uint retries = 0;
1150 	u16 lastrbc;
1151 	u8 hi, lo;
1152 	int err;
1153 
1154 	brcmf_err("%sterminate frame%s\n",
1155 		  abort ? "abort command, " : "",
1156 		  rtx ? ", send NAK" : "");
1157 
1158 	if (abort)
1159 		brcmf_sdiod_abort(bus->sdiodev, bus->sdiodev->func2);
1160 
1161 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_FRAMECTRL, SFC_RF_TERM,
1162 			   &err);
1163 	bus->sdcnt.f1regdata++;
1164 
1165 	/* Wait until the packet has been flushed (device/FIFO stable) */
1166 	for (lastrbc = retries = 0xffff; retries > 0; retries--) {
1167 		hi = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_RFRAMEBCHI,
1168 				       &err);
1169 		lo = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_RFRAMEBCLO,
1170 				       &err);
1171 		bus->sdcnt.f1regdata += 2;
1172 
1173 		if ((hi == 0) && (lo == 0))
1174 			break;
1175 
1176 		if ((hi > (lastrbc >> 8)) && (lo > (lastrbc & 0x00ff))) {
1177 			brcmf_err("count growing: last 0x%04x now 0x%04x\n",
1178 				  lastrbc, (hi << 8) + lo);
1179 		}
1180 		lastrbc = (hi << 8) + lo;
1181 	}
1182 
1183 	if (!retries)
1184 		brcmf_err("count never zeroed: last 0x%04x\n", lastrbc);
1185 	else
1186 		brcmf_dbg(SDIO, "flush took %d iterations\n", 0xffff - retries);
1187 
1188 	if (rtx) {
1189 		bus->sdcnt.rxrtx++;
1190 		brcmf_sdiod_writel(sdiod, core->base + SD_REG(tosbmailbox),
1191 				   SMB_NAK, &err);
1192 
1193 		bus->sdcnt.f1regdata++;
1194 		if (err == 0)
1195 			bus->rxskip = true;
1196 	}
1197 
1198 	/* Clear partial in any case */
1199 	bus->cur_read.len = 0;
1200 }
1201 
1202 static void brcmf_sdio_txfail(struct brcmf_sdio *bus)
1203 {
1204 	struct brcmf_sdio_dev *sdiodev = bus->sdiodev;
1205 	u8 i, hi, lo;
1206 
1207 	/* On failure, abort the command and terminate the frame */
1208 	brcmf_err("sdio error, abort command and terminate frame\n");
1209 	bus->sdcnt.tx_sderrs++;
1210 
1211 	brcmf_sdiod_abort(sdiodev, sdiodev->func2);
1212 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM, NULL);
1213 	bus->sdcnt.f1regdata++;
1214 
1215 	for (i = 0; i < 3; i++) {
1216 		hi = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_WFRAMEBCHI, NULL);
1217 		lo = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_WFRAMEBCLO, NULL);
1218 		bus->sdcnt.f1regdata += 2;
1219 		if ((hi == 0) && (lo == 0))
1220 			break;
1221 	}
1222 }
1223 
1224 /* return total length of buffer chain */
1225 static uint brcmf_sdio_glom_len(struct brcmf_sdio *bus)
1226 {
1227 	struct sk_buff *p;
1228 	uint total;
1229 
1230 	total = 0;
1231 	skb_queue_walk(&bus->glom, p)
1232 		total += p->len;
1233 	return total;
1234 }
1235 
1236 static void brcmf_sdio_free_glom(struct brcmf_sdio *bus)
1237 {
1238 	struct sk_buff *cur, *next;
1239 
1240 	skb_queue_walk_safe(&bus->glom, cur, next) {
1241 		skb_unlink(cur, &bus->glom);
1242 		brcmu_pkt_buf_free_skb(cur);
1243 	}
1244 }
1245 
1246 /**
1247  * brcmfmac sdio bus specific header
1248  * This is the lowest layer header wrapped on the packets transmitted between
1249  * host and WiFi dongle which contains information needed for SDIO core and
1250  * firmware
1251  *
1252  * It consists of 3 parts: hardware header, hardware extension header and
1253  * software header
1254  * hardware header (frame tag) - 4 bytes
1255  * Byte 0~1: Frame length
1256  * Byte 2~3: Checksum, bit-wise inverse of frame length
1257  * hardware extension header - 8 bytes
1258  * Tx glom mode only, N/A for Rx or normal Tx
1259  * Byte 0~1: Packet length excluding hw frame tag
1260  * Byte 2: Reserved
1261  * Byte 3: Frame flags, bit 0: last frame indication
1262  * Byte 4~5: Reserved
1263  * Byte 6~7: Tail padding length
1264  * software header - 8 bytes
1265  * Byte 0: Rx/Tx sequence number
1266  * Byte 1: 4 MSB Channel number, 4 LSB arbitrary flag
1267  * Byte 2: Length of next data frame, reserved for Tx
1268  * Byte 3: Data offset
1269  * Byte 4: Flow control bits, reserved for Tx
1270  * Byte 5: Maximum Sequence number allowed by firmware for Tx, N/A for Tx packet
1271  * Byte 6~7: Reserved
1272  */
1273 #define SDPCM_HWHDR_LEN			4
1274 #define SDPCM_HWEXT_LEN			8
1275 #define SDPCM_SWHDR_LEN			8
1276 #define SDPCM_HDRLEN			(SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN)
1277 /* software header */
1278 #define SDPCM_SEQ_MASK			0x000000ff
1279 #define SDPCM_SEQ_WRAP			256
1280 #define SDPCM_CHANNEL_MASK		0x00000f00
1281 #define SDPCM_CHANNEL_SHIFT		8
1282 #define SDPCM_CONTROL_CHANNEL		0	/* Control */
1283 #define SDPCM_EVENT_CHANNEL		1	/* Asyc Event Indication */
1284 #define SDPCM_DATA_CHANNEL		2	/* Data Xmit/Recv */
1285 #define SDPCM_GLOM_CHANNEL		3	/* Coalesced packets */
1286 #define SDPCM_TEST_CHANNEL		15	/* Test/debug packets */
1287 #define SDPCM_GLOMDESC(p)		(((u8 *)p)[1] & 0x80)
1288 #define SDPCM_NEXTLEN_MASK		0x00ff0000
1289 #define SDPCM_NEXTLEN_SHIFT		16
1290 #define SDPCM_DOFFSET_MASK		0xff000000
1291 #define SDPCM_DOFFSET_SHIFT		24
1292 #define SDPCM_FCMASK_MASK		0x000000ff
1293 #define SDPCM_WINDOW_MASK		0x0000ff00
1294 #define SDPCM_WINDOW_SHIFT		8
1295 
1296 static inline u8 brcmf_sdio_getdatoffset(u8 *swheader)
1297 {
1298 	u32 hdrvalue;
1299 	hdrvalue = *(u32 *)swheader;
1300 	return (u8)((hdrvalue & SDPCM_DOFFSET_MASK) >> SDPCM_DOFFSET_SHIFT);
1301 }
1302 
1303 static inline bool brcmf_sdio_fromevntchan(u8 *swheader)
1304 {
1305 	u32 hdrvalue;
1306 	u8 ret;
1307 
1308 	hdrvalue = *(u32 *)swheader;
1309 	ret = (u8)((hdrvalue & SDPCM_CHANNEL_MASK) >> SDPCM_CHANNEL_SHIFT);
1310 
1311 	return (ret == SDPCM_EVENT_CHANNEL);
1312 }
1313 
1314 static int brcmf_sdio_hdparse(struct brcmf_sdio *bus, u8 *header,
1315 			      struct brcmf_sdio_hdrinfo *rd,
1316 			      enum brcmf_sdio_frmtype type)
1317 {
1318 	u16 len, checksum;
1319 	u8 rx_seq, fc, tx_seq_max;
1320 	u32 swheader;
1321 
1322 	trace_brcmf_sdpcm_hdr(SDPCM_RX, header);
1323 
1324 	/* hw header */
1325 	len = get_unaligned_le16(header);
1326 	checksum = get_unaligned_le16(header + sizeof(u16));
1327 	/* All zero means no more to read */
1328 	if (!(len | checksum)) {
1329 		bus->rxpending = false;
1330 		return -ENODATA;
1331 	}
1332 	if ((u16)(~(len ^ checksum))) {
1333 		brcmf_err("HW header checksum error\n");
1334 		bus->sdcnt.rx_badhdr++;
1335 		brcmf_sdio_rxfail(bus, false, false);
1336 		return -EIO;
1337 	}
1338 	if (len < SDPCM_HDRLEN) {
1339 		brcmf_err("HW header length error\n");
1340 		return -EPROTO;
1341 	}
1342 	if (type == BRCMF_SDIO_FT_SUPER &&
1343 	    (roundup(len, bus->blocksize) != rd->len)) {
1344 		brcmf_err("HW superframe header length error\n");
1345 		return -EPROTO;
1346 	}
1347 	if (type == BRCMF_SDIO_FT_SUB && len > rd->len) {
1348 		brcmf_err("HW subframe header length error\n");
1349 		return -EPROTO;
1350 	}
1351 	rd->len = len;
1352 
1353 	/* software header */
1354 	header += SDPCM_HWHDR_LEN;
1355 	swheader = le32_to_cpu(*(__le32 *)header);
1356 	if (type == BRCMF_SDIO_FT_SUPER && SDPCM_GLOMDESC(header)) {
1357 		brcmf_err("Glom descriptor found in superframe head\n");
1358 		rd->len = 0;
1359 		return -EINVAL;
1360 	}
1361 	rx_seq = (u8)(swheader & SDPCM_SEQ_MASK);
1362 	rd->channel = (swheader & SDPCM_CHANNEL_MASK) >> SDPCM_CHANNEL_SHIFT;
1363 	if (len > MAX_RX_DATASZ && rd->channel != SDPCM_CONTROL_CHANNEL &&
1364 	    type != BRCMF_SDIO_FT_SUPER) {
1365 		brcmf_err("HW header length too long\n");
1366 		bus->sdcnt.rx_toolong++;
1367 		brcmf_sdio_rxfail(bus, false, false);
1368 		rd->len = 0;
1369 		return -EPROTO;
1370 	}
1371 	if (type == BRCMF_SDIO_FT_SUPER && rd->channel != SDPCM_GLOM_CHANNEL) {
1372 		brcmf_err("Wrong channel for superframe\n");
1373 		rd->len = 0;
1374 		return -EINVAL;
1375 	}
1376 	if (type == BRCMF_SDIO_FT_SUB && rd->channel != SDPCM_DATA_CHANNEL &&
1377 	    rd->channel != SDPCM_EVENT_CHANNEL) {
1378 		brcmf_err("Wrong channel for subframe\n");
1379 		rd->len = 0;
1380 		return -EINVAL;
1381 	}
1382 	rd->dat_offset = brcmf_sdio_getdatoffset(header);
1383 	if (rd->dat_offset < SDPCM_HDRLEN || rd->dat_offset > rd->len) {
1384 		brcmf_err("seq %d: bad data offset\n", rx_seq);
1385 		bus->sdcnt.rx_badhdr++;
1386 		brcmf_sdio_rxfail(bus, false, false);
1387 		rd->len = 0;
1388 		return -ENXIO;
1389 	}
1390 	if (rd->seq_num != rx_seq) {
1391 		brcmf_dbg(SDIO, "seq %d, expected %d\n", rx_seq, rd->seq_num);
1392 		bus->sdcnt.rx_badseq++;
1393 		rd->seq_num = rx_seq;
1394 	}
1395 	/* no need to check the reset for subframe */
1396 	if (type == BRCMF_SDIO_FT_SUB)
1397 		return 0;
1398 	rd->len_nxtfrm = (swheader & SDPCM_NEXTLEN_MASK) >> SDPCM_NEXTLEN_SHIFT;
1399 	if (rd->len_nxtfrm << 4 > MAX_RX_DATASZ) {
1400 		/* only warm for NON glom packet */
1401 		if (rd->channel != SDPCM_GLOM_CHANNEL)
1402 			brcmf_err("seq %d: next length error\n", rx_seq);
1403 		rd->len_nxtfrm = 0;
1404 	}
1405 	swheader = le32_to_cpu(*(__le32 *)(header + 4));
1406 	fc = swheader & SDPCM_FCMASK_MASK;
1407 	if (bus->flowcontrol != fc) {
1408 		if (~bus->flowcontrol & fc)
1409 			bus->sdcnt.fc_xoff++;
1410 		if (bus->flowcontrol & ~fc)
1411 			bus->sdcnt.fc_xon++;
1412 		bus->sdcnt.fc_rcvd++;
1413 		bus->flowcontrol = fc;
1414 	}
1415 	tx_seq_max = (swheader & SDPCM_WINDOW_MASK) >> SDPCM_WINDOW_SHIFT;
1416 	if ((u8)(tx_seq_max - bus->tx_seq) > 0x40) {
1417 		brcmf_err("seq %d: max tx seq number error\n", rx_seq);
1418 		tx_seq_max = bus->tx_seq + 2;
1419 	}
1420 	bus->tx_max = tx_seq_max;
1421 
1422 	return 0;
1423 }
1424 
1425 static inline void brcmf_sdio_update_hwhdr(u8 *header, u16 frm_length)
1426 {
1427 	*(__le16 *)header = cpu_to_le16(frm_length);
1428 	*(((__le16 *)header) + 1) = cpu_to_le16(~frm_length);
1429 }
1430 
1431 static void brcmf_sdio_hdpack(struct brcmf_sdio *bus, u8 *header,
1432 			      struct brcmf_sdio_hdrinfo *hd_info)
1433 {
1434 	u32 hdrval;
1435 	u8 hdr_offset;
1436 
1437 	brcmf_sdio_update_hwhdr(header, hd_info->len);
1438 	hdr_offset = SDPCM_HWHDR_LEN;
1439 
1440 	if (bus->txglom) {
1441 		hdrval = (hd_info->len - hdr_offset) | (hd_info->lastfrm << 24);
1442 		*((__le32 *)(header + hdr_offset)) = cpu_to_le32(hdrval);
1443 		hdrval = (u16)hd_info->tail_pad << 16;
1444 		*(((__le32 *)(header + hdr_offset)) + 1) = cpu_to_le32(hdrval);
1445 		hdr_offset += SDPCM_HWEXT_LEN;
1446 	}
1447 
1448 	hdrval = hd_info->seq_num;
1449 	hdrval |= (hd_info->channel << SDPCM_CHANNEL_SHIFT) &
1450 		  SDPCM_CHANNEL_MASK;
1451 	hdrval |= (hd_info->dat_offset << SDPCM_DOFFSET_SHIFT) &
1452 		  SDPCM_DOFFSET_MASK;
1453 	*((__le32 *)(header + hdr_offset)) = cpu_to_le32(hdrval);
1454 	*(((__le32 *)(header + hdr_offset)) + 1) = 0;
1455 	trace_brcmf_sdpcm_hdr(SDPCM_TX + !!(bus->txglom), header);
1456 }
1457 
1458 static u8 brcmf_sdio_rxglom(struct brcmf_sdio *bus, u8 rxseq)
1459 {
1460 	u16 dlen, totlen;
1461 	u8 *dptr, num = 0;
1462 	u16 sublen;
1463 	struct sk_buff *pfirst, *pnext;
1464 
1465 	int errcode;
1466 	u8 doff, sfdoff;
1467 
1468 	struct brcmf_sdio_hdrinfo rd_new;
1469 
1470 	/* If packets, issue read(s) and send up packet chain */
1471 	/* Return sequence numbers consumed? */
1472 
1473 	brcmf_dbg(SDIO, "start: glomd %p glom %p\n",
1474 		  bus->glomd, skb_peek(&bus->glom));
1475 
1476 	/* If there's a descriptor, generate the packet chain */
1477 	if (bus->glomd) {
1478 		pfirst = pnext = NULL;
1479 		dlen = (u16) (bus->glomd->len);
1480 		dptr = bus->glomd->data;
1481 		if (!dlen || (dlen & 1)) {
1482 			brcmf_err("bad glomd len(%d), ignore descriptor\n",
1483 				  dlen);
1484 			dlen = 0;
1485 		}
1486 
1487 		for (totlen = num = 0; dlen; num++) {
1488 			/* Get (and move past) next length */
1489 			sublen = get_unaligned_le16(dptr);
1490 			dlen -= sizeof(u16);
1491 			dptr += sizeof(u16);
1492 			if ((sublen < SDPCM_HDRLEN) ||
1493 			    ((num == 0) && (sublen < (2 * SDPCM_HDRLEN)))) {
1494 				brcmf_err("descriptor len %d bad: %d\n",
1495 					  num, sublen);
1496 				pnext = NULL;
1497 				break;
1498 			}
1499 			if (sublen % bus->sgentry_align) {
1500 				brcmf_err("sublen %d not multiple of %d\n",
1501 					  sublen, bus->sgentry_align);
1502 			}
1503 			totlen += sublen;
1504 
1505 			/* For last frame, adjust read len so total
1506 				 is a block multiple */
1507 			if (!dlen) {
1508 				sublen +=
1509 				    (roundup(totlen, bus->blocksize) - totlen);
1510 				totlen = roundup(totlen, bus->blocksize);
1511 			}
1512 
1513 			/* Allocate/chain packet for next subframe */
1514 			pnext = brcmu_pkt_buf_get_skb(sublen + bus->sgentry_align);
1515 			if (pnext == NULL) {
1516 				brcmf_err("bcm_pkt_buf_get_skb failed, num %d len %d\n",
1517 					  num, sublen);
1518 				break;
1519 			}
1520 			skb_queue_tail(&bus->glom, pnext);
1521 
1522 			/* Adhere to start alignment requirements */
1523 			pkt_align(pnext, sublen, bus->sgentry_align);
1524 		}
1525 
1526 		/* If all allocations succeeded, save packet chain
1527 			 in bus structure */
1528 		if (pnext) {
1529 			brcmf_dbg(GLOM, "allocated %d-byte packet chain for %d subframes\n",
1530 				  totlen, num);
1531 			if (BRCMF_GLOM_ON() && bus->cur_read.len &&
1532 			    totlen != bus->cur_read.len) {
1533 				brcmf_dbg(GLOM, "glomdesc mismatch: nextlen %d glomdesc %d rxseq %d\n",
1534 					  bus->cur_read.len, totlen, rxseq);
1535 			}
1536 			pfirst = pnext = NULL;
1537 		} else {
1538 			brcmf_sdio_free_glom(bus);
1539 			num = 0;
1540 		}
1541 
1542 		/* Done with descriptor packet */
1543 		brcmu_pkt_buf_free_skb(bus->glomd);
1544 		bus->glomd = NULL;
1545 		bus->cur_read.len = 0;
1546 	}
1547 
1548 	/* Ok -- either we just generated a packet chain,
1549 		 or had one from before */
1550 	if (!skb_queue_empty(&bus->glom)) {
1551 		if (BRCMF_GLOM_ON()) {
1552 			brcmf_dbg(GLOM, "try superframe read, packet chain:\n");
1553 			skb_queue_walk(&bus->glom, pnext) {
1554 				brcmf_dbg(GLOM, "    %p: %p len 0x%04x (%d)\n",
1555 					  pnext, (u8 *) (pnext->data),
1556 					  pnext->len, pnext->len);
1557 			}
1558 		}
1559 
1560 		pfirst = skb_peek(&bus->glom);
1561 		dlen = (u16) brcmf_sdio_glom_len(bus);
1562 
1563 		/* Do an SDIO read for the superframe.  Configurable iovar to
1564 		 * read directly into the chained packet, or allocate a large
1565 		 * packet and and copy into the chain.
1566 		 */
1567 		sdio_claim_host(bus->sdiodev->func1);
1568 		errcode = brcmf_sdiod_recv_chain(bus->sdiodev,
1569 						 &bus->glom, dlen);
1570 		sdio_release_host(bus->sdiodev->func1);
1571 		bus->sdcnt.f2rxdata++;
1572 
1573 		/* On failure, kill the superframe */
1574 		if (errcode < 0) {
1575 			brcmf_err("glom read of %d bytes failed: %d\n",
1576 				  dlen, errcode);
1577 
1578 			sdio_claim_host(bus->sdiodev->func1);
1579 			brcmf_sdio_rxfail(bus, true, false);
1580 			bus->sdcnt.rxglomfail++;
1581 			brcmf_sdio_free_glom(bus);
1582 			sdio_release_host(bus->sdiodev->func1);
1583 			return 0;
1584 		}
1585 
1586 		brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1587 				   pfirst->data, min_t(int, pfirst->len, 48),
1588 				   "SUPERFRAME:\n");
1589 
1590 		rd_new.seq_num = rxseq;
1591 		rd_new.len = dlen;
1592 		sdio_claim_host(bus->sdiodev->func1);
1593 		errcode = brcmf_sdio_hdparse(bus, pfirst->data, &rd_new,
1594 					     BRCMF_SDIO_FT_SUPER);
1595 		sdio_release_host(bus->sdiodev->func1);
1596 		bus->cur_read.len = rd_new.len_nxtfrm << 4;
1597 
1598 		/* Remove superframe header, remember offset */
1599 		skb_pull(pfirst, rd_new.dat_offset);
1600 		sfdoff = rd_new.dat_offset;
1601 		num = 0;
1602 
1603 		/* Validate all the subframe headers */
1604 		skb_queue_walk(&bus->glom, pnext) {
1605 			/* leave when invalid subframe is found */
1606 			if (errcode)
1607 				break;
1608 
1609 			rd_new.len = pnext->len;
1610 			rd_new.seq_num = rxseq++;
1611 			sdio_claim_host(bus->sdiodev->func1);
1612 			errcode = brcmf_sdio_hdparse(bus, pnext->data, &rd_new,
1613 						     BRCMF_SDIO_FT_SUB);
1614 			sdio_release_host(bus->sdiodev->func1);
1615 			brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1616 					   pnext->data, 32, "subframe:\n");
1617 
1618 			num++;
1619 		}
1620 
1621 		if (errcode) {
1622 			/* Terminate frame on error */
1623 			sdio_claim_host(bus->sdiodev->func1);
1624 			brcmf_sdio_rxfail(bus, true, false);
1625 			bus->sdcnt.rxglomfail++;
1626 			brcmf_sdio_free_glom(bus);
1627 			sdio_release_host(bus->sdiodev->func1);
1628 			bus->cur_read.len = 0;
1629 			return 0;
1630 		}
1631 
1632 		/* Basic SD framing looks ok - process each packet (header) */
1633 
1634 		skb_queue_walk_safe(&bus->glom, pfirst, pnext) {
1635 			dptr = (u8 *) (pfirst->data);
1636 			sublen = get_unaligned_le16(dptr);
1637 			doff = brcmf_sdio_getdatoffset(&dptr[SDPCM_HWHDR_LEN]);
1638 
1639 			brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
1640 					   dptr, pfirst->len,
1641 					   "Rx Subframe Data:\n");
1642 
1643 			__skb_trim(pfirst, sublen);
1644 			skb_pull(pfirst, doff);
1645 
1646 			if (pfirst->len == 0) {
1647 				skb_unlink(pfirst, &bus->glom);
1648 				brcmu_pkt_buf_free_skb(pfirst);
1649 				continue;
1650 			}
1651 
1652 			brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1653 					   pfirst->data,
1654 					   min_t(int, pfirst->len, 32),
1655 					   "subframe %d to stack, %p (%p/%d) nxt/lnk %p/%p\n",
1656 					   bus->glom.qlen, pfirst, pfirst->data,
1657 					   pfirst->len, pfirst->next,
1658 					   pfirst->prev);
1659 			skb_unlink(pfirst, &bus->glom);
1660 			if (brcmf_sdio_fromevntchan(&dptr[SDPCM_HWHDR_LEN]))
1661 				brcmf_rx_event(bus->sdiodev->dev, pfirst);
1662 			else
1663 				brcmf_rx_frame(bus->sdiodev->dev, pfirst,
1664 					       false);
1665 			bus->sdcnt.rxglompkts++;
1666 		}
1667 
1668 		bus->sdcnt.rxglomframes++;
1669 	}
1670 	return num;
1671 }
1672 
1673 static int brcmf_sdio_dcmd_resp_wait(struct brcmf_sdio *bus, uint *condition,
1674 				     bool *pending)
1675 {
1676 	DECLARE_WAITQUEUE(wait, current);
1677 	int timeout = DCMD_RESP_TIMEOUT;
1678 
1679 	/* Wait until control frame is available */
1680 	add_wait_queue(&bus->dcmd_resp_wait, &wait);
1681 	set_current_state(TASK_INTERRUPTIBLE);
1682 
1683 	while (!(*condition) && (!signal_pending(current) && timeout))
1684 		timeout = schedule_timeout(timeout);
1685 
1686 	if (signal_pending(current))
1687 		*pending = true;
1688 
1689 	set_current_state(TASK_RUNNING);
1690 	remove_wait_queue(&bus->dcmd_resp_wait, &wait);
1691 
1692 	return timeout;
1693 }
1694 
1695 static int brcmf_sdio_dcmd_resp_wake(struct brcmf_sdio *bus)
1696 {
1697 	wake_up_interruptible(&bus->dcmd_resp_wait);
1698 
1699 	return 0;
1700 }
1701 static void
1702 brcmf_sdio_read_control(struct brcmf_sdio *bus, u8 *hdr, uint len, uint doff)
1703 {
1704 	uint rdlen, pad;
1705 	u8 *buf = NULL, *rbuf;
1706 	int sdret;
1707 
1708 	brcmf_dbg(SDIO, "Enter\n");
1709 	if (bus->rxblen)
1710 		buf = vzalloc(bus->rxblen);
1711 	if (!buf)
1712 		goto done;
1713 
1714 	rbuf = bus->rxbuf;
1715 	pad = ((unsigned long)rbuf % bus->head_align);
1716 	if (pad)
1717 		rbuf += (bus->head_align - pad);
1718 
1719 	/* Copy the already-read portion over */
1720 	memcpy(buf, hdr, BRCMF_FIRSTREAD);
1721 	if (len <= BRCMF_FIRSTREAD)
1722 		goto gotpkt;
1723 
1724 	/* Raise rdlen to next SDIO block to avoid tail command */
1725 	rdlen = len - BRCMF_FIRSTREAD;
1726 	if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) {
1727 		pad = bus->blocksize - (rdlen % bus->blocksize);
1728 		if ((pad <= bus->roundup) && (pad < bus->blocksize) &&
1729 		    ((len + pad) < bus->sdiodev->bus_if->maxctl))
1730 			rdlen += pad;
1731 	} else if (rdlen % bus->head_align) {
1732 		rdlen += bus->head_align - (rdlen % bus->head_align);
1733 	}
1734 
1735 	/* Drop if the read is too big or it exceeds our maximum */
1736 	if ((rdlen + BRCMF_FIRSTREAD) > bus->sdiodev->bus_if->maxctl) {
1737 		brcmf_err("%d-byte control read exceeds %d-byte buffer\n",
1738 			  rdlen, bus->sdiodev->bus_if->maxctl);
1739 		brcmf_sdio_rxfail(bus, false, false);
1740 		goto done;
1741 	}
1742 
1743 	if ((len - doff) > bus->sdiodev->bus_if->maxctl) {
1744 		brcmf_err("%d-byte ctl frame (%d-byte ctl data) exceeds %d-byte limit\n",
1745 			  len, len - doff, bus->sdiodev->bus_if->maxctl);
1746 		bus->sdcnt.rx_toolong++;
1747 		brcmf_sdio_rxfail(bus, false, false);
1748 		goto done;
1749 	}
1750 
1751 	/* Read remain of frame body */
1752 	sdret = brcmf_sdiod_recv_buf(bus->sdiodev, rbuf, rdlen);
1753 	bus->sdcnt.f2rxdata++;
1754 
1755 	/* Control frame failures need retransmission */
1756 	if (sdret < 0) {
1757 		brcmf_err("read %d control bytes failed: %d\n",
1758 			  rdlen, sdret);
1759 		bus->sdcnt.rxc_errors++;
1760 		brcmf_sdio_rxfail(bus, true, true);
1761 		goto done;
1762 	} else
1763 		memcpy(buf + BRCMF_FIRSTREAD, rbuf, rdlen);
1764 
1765 gotpkt:
1766 
1767 	brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_CTL_ON(),
1768 			   buf, len, "RxCtrl:\n");
1769 
1770 	/* Point to valid data and indicate its length */
1771 	spin_lock_bh(&bus->rxctl_lock);
1772 	if (bus->rxctl) {
1773 		brcmf_err("last control frame is being processed.\n");
1774 		spin_unlock_bh(&bus->rxctl_lock);
1775 		vfree(buf);
1776 		goto done;
1777 	}
1778 	bus->rxctl = buf + doff;
1779 	bus->rxctl_orig = buf;
1780 	bus->rxlen = len - doff;
1781 	spin_unlock_bh(&bus->rxctl_lock);
1782 
1783 done:
1784 	/* Awake any waiters */
1785 	brcmf_sdio_dcmd_resp_wake(bus);
1786 }
1787 
1788 /* Pad read to blocksize for efficiency */
1789 static void brcmf_sdio_pad(struct brcmf_sdio *bus, u16 *pad, u16 *rdlen)
1790 {
1791 	if (bus->roundup && bus->blocksize && *rdlen > bus->blocksize) {
1792 		*pad = bus->blocksize - (*rdlen % bus->blocksize);
1793 		if (*pad <= bus->roundup && *pad < bus->blocksize &&
1794 		    *rdlen + *pad + BRCMF_FIRSTREAD < MAX_RX_DATASZ)
1795 			*rdlen += *pad;
1796 	} else if (*rdlen % bus->head_align) {
1797 		*rdlen += bus->head_align - (*rdlen % bus->head_align);
1798 	}
1799 }
1800 
1801 static uint brcmf_sdio_readframes(struct brcmf_sdio *bus, uint maxframes)
1802 {
1803 	struct sk_buff *pkt;		/* Packet for event or data frames */
1804 	u16 pad;		/* Number of pad bytes to read */
1805 	uint rxleft = 0;	/* Remaining number of frames allowed */
1806 	int ret;		/* Return code from calls */
1807 	uint rxcount = 0;	/* Total frames read */
1808 	struct brcmf_sdio_hdrinfo *rd = &bus->cur_read, rd_new;
1809 	u8 head_read = 0;
1810 
1811 	brcmf_dbg(SDIO, "Enter\n");
1812 
1813 	/* Not finished unless we encounter no more frames indication */
1814 	bus->rxpending = true;
1815 
1816 	for (rd->seq_num = bus->rx_seq, rxleft = maxframes;
1817 	     !bus->rxskip && rxleft && bus->sdiodev->state == BRCMF_SDIOD_DATA;
1818 	     rd->seq_num++, rxleft--) {
1819 
1820 		/* Handle glomming separately */
1821 		if (bus->glomd || !skb_queue_empty(&bus->glom)) {
1822 			u8 cnt;
1823 			brcmf_dbg(GLOM, "calling rxglom: glomd %p, glom %p\n",
1824 				  bus->glomd, skb_peek(&bus->glom));
1825 			cnt = brcmf_sdio_rxglom(bus, rd->seq_num);
1826 			brcmf_dbg(GLOM, "rxglom returned %d\n", cnt);
1827 			rd->seq_num += cnt - 1;
1828 			rxleft = (rxleft > cnt) ? (rxleft - cnt) : 1;
1829 			continue;
1830 		}
1831 
1832 		rd->len_left = rd->len;
1833 		/* read header first for unknow frame length */
1834 		sdio_claim_host(bus->sdiodev->func1);
1835 		if (!rd->len) {
1836 			ret = brcmf_sdiod_recv_buf(bus->sdiodev,
1837 						   bus->rxhdr, BRCMF_FIRSTREAD);
1838 			bus->sdcnt.f2rxhdrs++;
1839 			if (ret < 0) {
1840 				brcmf_err("RXHEADER FAILED: %d\n",
1841 					  ret);
1842 				bus->sdcnt.rx_hdrfail++;
1843 				brcmf_sdio_rxfail(bus, true, true);
1844 				sdio_release_host(bus->sdiodev->func1);
1845 				continue;
1846 			}
1847 
1848 			brcmf_dbg_hex_dump(BRCMF_BYTES_ON() || BRCMF_HDRS_ON(),
1849 					   bus->rxhdr, SDPCM_HDRLEN,
1850 					   "RxHdr:\n");
1851 
1852 			if (brcmf_sdio_hdparse(bus, bus->rxhdr, rd,
1853 					       BRCMF_SDIO_FT_NORMAL)) {
1854 				sdio_release_host(bus->sdiodev->func1);
1855 				if (!bus->rxpending)
1856 					break;
1857 				else
1858 					continue;
1859 			}
1860 
1861 			if (rd->channel == SDPCM_CONTROL_CHANNEL) {
1862 				brcmf_sdio_read_control(bus, bus->rxhdr,
1863 							rd->len,
1864 							rd->dat_offset);
1865 				/* prepare the descriptor for the next read */
1866 				rd->len = rd->len_nxtfrm << 4;
1867 				rd->len_nxtfrm = 0;
1868 				/* treat all packet as event if we don't know */
1869 				rd->channel = SDPCM_EVENT_CHANNEL;
1870 				sdio_release_host(bus->sdiodev->func1);
1871 				continue;
1872 			}
1873 			rd->len_left = rd->len > BRCMF_FIRSTREAD ?
1874 				       rd->len - BRCMF_FIRSTREAD : 0;
1875 			head_read = BRCMF_FIRSTREAD;
1876 		}
1877 
1878 		brcmf_sdio_pad(bus, &pad, &rd->len_left);
1879 
1880 		pkt = brcmu_pkt_buf_get_skb(rd->len_left + head_read +
1881 					    bus->head_align);
1882 		if (!pkt) {
1883 			/* Give up on data, request rtx of events */
1884 			brcmf_err("brcmu_pkt_buf_get_skb failed\n");
1885 			brcmf_sdio_rxfail(bus, false,
1886 					    RETRYCHAN(rd->channel));
1887 			sdio_release_host(bus->sdiodev->func1);
1888 			continue;
1889 		}
1890 		skb_pull(pkt, head_read);
1891 		pkt_align(pkt, rd->len_left, bus->head_align);
1892 
1893 		ret = brcmf_sdiod_recv_pkt(bus->sdiodev, pkt);
1894 		bus->sdcnt.f2rxdata++;
1895 		sdio_release_host(bus->sdiodev->func1);
1896 
1897 		if (ret < 0) {
1898 			brcmf_err("read %d bytes from channel %d failed: %d\n",
1899 				  rd->len, rd->channel, ret);
1900 			brcmu_pkt_buf_free_skb(pkt);
1901 			sdio_claim_host(bus->sdiodev->func1);
1902 			brcmf_sdio_rxfail(bus, true,
1903 					    RETRYCHAN(rd->channel));
1904 			sdio_release_host(bus->sdiodev->func1);
1905 			continue;
1906 		}
1907 
1908 		if (head_read) {
1909 			skb_push(pkt, head_read);
1910 			memcpy(pkt->data, bus->rxhdr, head_read);
1911 			head_read = 0;
1912 		} else {
1913 			memcpy(bus->rxhdr, pkt->data, SDPCM_HDRLEN);
1914 			rd_new.seq_num = rd->seq_num;
1915 			sdio_claim_host(bus->sdiodev->func1);
1916 			if (brcmf_sdio_hdparse(bus, bus->rxhdr, &rd_new,
1917 					       BRCMF_SDIO_FT_NORMAL)) {
1918 				rd->len = 0;
1919 				brcmu_pkt_buf_free_skb(pkt);
1920 			}
1921 			bus->sdcnt.rx_readahead_cnt++;
1922 			if (rd->len != roundup(rd_new.len, 16)) {
1923 				brcmf_err("frame length mismatch:read %d, should be %d\n",
1924 					  rd->len,
1925 					  roundup(rd_new.len, 16) >> 4);
1926 				rd->len = 0;
1927 				brcmf_sdio_rxfail(bus, true, true);
1928 				sdio_release_host(bus->sdiodev->func1);
1929 				brcmu_pkt_buf_free_skb(pkt);
1930 				continue;
1931 			}
1932 			sdio_release_host(bus->sdiodev->func1);
1933 			rd->len_nxtfrm = rd_new.len_nxtfrm;
1934 			rd->channel = rd_new.channel;
1935 			rd->dat_offset = rd_new.dat_offset;
1936 
1937 			brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() &&
1938 					     BRCMF_DATA_ON()) &&
1939 					   BRCMF_HDRS_ON(),
1940 					   bus->rxhdr, SDPCM_HDRLEN,
1941 					   "RxHdr:\n");
1942 
1943 			if (rd_new.channel == SDPCM_CONTROL_CHANNEL) {
1944 				brcmf_err("readahead on control packet %d?\n",
1945 					  rd_new.seq_num);
1946 				/* Force retry w/normal header read */
1947 				rd->len = 0;
1948 				sdio_claim_host(bus->sdiodev->func1);
1949 				brcmf_sdio_rxfail(bus, false, true);
1950 				sdio_release_host(bus->sdiodev->func1);
1951 				brcmu_pkt_buf_free_skb(pkt);
1952 				continue;
1953 			}
1954 		}
1955 
1956 		brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_DATA_ON(),
1957 				   pkt->data, rd->len, "Rx Data:\n");
1958 
1959 		/* Save superframe descriptor and allocate packet frame */
1960 		if (rd->channel == SDPCM_GLOM_CHANNEL) {
1961 			if (SDPCM_GLOMDESC(&bus->rxhdr[SDPCM_HWHDR_LEN])) {
1962 				brcmf_dbg(GLOM, "glom descriptor, %d bytes:\n",
1963 					  rd->len);
1964 				brcmf_dbg_hex_dump(BRCMF_GLOM_ON(),
1965 						   pkt->data, rd->len,
1966 						   "Glom Data:\n");
1967 				__skb_trim(pkt, rd->len);
1968 				skb_pull(pkt, SDPCM_HDRLEN);
1969 				bus->glomd = pkt;
1970 			} else {
1971 				brcmf_err("%s: glom superframe w/o "
1972 					  "descriptor!\n", __func__);
1973 				sdio_claim_host(bus->sdiodev->func1);
1974 				brcmf_sdio_rxfail(bus, false, false);
1975 				sdio_release_host(bus->sdiodev->func1);
1976 			}
1977 			/* prepare the descriptor for the next read */
1978 			rd->len = rd->len_nxtfrm << 4;
1979 			rd->len_nxtfrm = 0;
1980 			/* treat all packet as event if we don't know */
1981 			rd->channel = SDPCM_EVENT_CHANNEL;
1982 			continue;
1983 		}
1984 
1985 		/* Fill in packet len and prio, deliver upward */
1986 		__skb_trim(pkt, rd->len);
1987 		skb_pull(pkt, rd->dat_offset);
1988 
1989 		if (pkt->len == 0)
1990 			brcmu_pkt_buf_free_skb(pkt);
1991 		else if (rd->channel == SDPCM_EVENT_CHANNEL)
1992 			brcmf_rx_event(bus->sdiodev->dev, pkt);
1993 		else
1994 			brcmf_rx_frame(bus->sdiodev->dev, pkt,
1995 				       false);
1996 
1997 		/* prepare the descriptor for the next read */
1998 		rd->len = rd->len_nxtfrm << 4;
1999 		rd->len_nxtfrm = 0;
2000 		/* treat all packet as event if we don't know */
2001 		rd->channel = SDPCM_EVENT_CHANNEL;
2002 	}
2003 
2004 	rxcount = maxframes - rxleft;
2005 	/* Message if we hit the limit */
2006 	if (!rxleft)
2007 		brcmf_dbg(DATA, "hit rx limit of %d frames\n", maxframes);
2008 	else
2009 		brcmf_dbg(DATA, "processed %d frames\n", rxcount);
2010 	/* Back off rxseq if awaiting rtx, update rx_seq */
2011 	if (bus->rxskip)
2012 		rd->seq_num--;
2013 	bus->rx_seq = rd->seq_num;
2014 
2015 	return rxcount;
2016 }
2017 
2018 static void
2019 brcmf_sdio_wait_event_wakeup(struct brcmf_sdio *bus)
2020 {
2021 	wake_up_interruptible(&bus->ctrl_wait);
2022 	return;
2023 }
2024 
2025 static int brcmf_sdio_txpkt_hdalign(struct brcmf_sdio *bus, struct sk_buff *pkt)
2026 {
2027 	struct brcmf_bus_stats *stats;
2028 	u16 head_pad;
2029 	u8 *dat_buf;
2030 
2031 	dat_buf = (u8 *)(pkt->data);
2032 
2033 	/* Check head padding */
2034 	head_pad = ((unsigned long)dat_buf % bus->head_align);
2035 	if (head_pad) {
2036 		if (skb_headroom(pkt) < head_pad) {
2037 			stats = &bus->sdiodev->bus_if->stats;
2038 			atomic_inc(&stats->pktcowed);
2039 			if (skb_cow_head(pkt, head_pad)) {
2040 				atomic_inc(&stats->pktcow_failed);
2041 				return -ENOMEM;
2042 			}
2043 			head_pad = 0;
2044 		}
2045 		skb_push(pkt, head_pad);
2046 		dat_buf = (u8 *)(pkt->data);
2047 	}
2048 	memset(dat_buf, 0, head_pad + bus->tx_hdrlen);
2049 	return head_pad;
2050 }
2051 
2052 /*
2053  * struct brcmf_skbuff_cb reserves first two bytes in sk_buff::cb for
2054  * bus layer usage.
2055  */
2056 /* flag marking a dummy skb added for DMA alignment requirement */
2057 #define ALIGN_SKB_FLAG		0x8000
2058 /* bit mask of data length chopped from the previous packet */
2059 #define ALIGN_SKB_CHOP_LEN_MASK	0x7fff
2060 
2061 static int brcmf_sdio_txpkt_prep_sg(struct brcmf_sdio *bus,
2062 				    struct sk_buff_head *pktq,
2063 				    struct sk_buff *pkt, u16 total_len)
2064 {
2065 	struct brcmf_sdio_dev *sdiodev;
2066 	struct sk_buff *pkt_pad;
2067 	u16 tail_pad, tail_chop, chain_pad;
2068 	unsigned int blksize;
2069 	bool lastfrm;
2070 	int ntail, ret;
2071 
2072 	sdiodev = bus->sdiodev;
2073 	blksize = sdiodev->func2->cur_blksize;
2074 	/* sg entry alignment should be a divisor of block size */
2075 	WARN_ON(blksize % bus->sgentry_align);
2076 
2077 	/* Check tail padding */
2078 	lastfrm = skb_queue_is_last(pktq, pkt);
2079 	tail_pad = 0;
2080 	tail_chop = pkt->len % bus->sgentry_align;
2081 	if (tail_chop)
2082 		tail_pad = bus->sgentry_align - tail_chop;
2083 	chain_pad = (total_len + tail_pad) % blksize;
2084 	if (lastfrm && chain_pad)
2085 		tail_pad += blksize - chain_pad;
2086 	if (skb_tailroom(pkt) < tail_pad && pkt->len > blksize) {
2087 		pkt_pad = brcmu_pkt_buf_get_skb(tail_pad + tail_chop +
2088 						bus->head_align);
2089 		if (pkt_pad == NULL)
2090 			return -ENOMEM;
2091 		ret = brcmf_sdio_txpkt_hdalign(bus, pkt_pad);
2092 		if (unlikely(ret < 0)) {
2093 			kfree_skb(pkt_pad);
2094 			return ret;
2095 		}
2096 		memcpy(pkt_pad->data,
2097 		       pkt->data + pkt->len - tail_chop,
2098 		       tail_chop);
2099 		*(u16 *)(pkt_pad->cb) = ALIGN_SKB_FLAG + tail_chop;
2100 		skb_trim(pkt, pkt->len - tail_chop);
2101 		skb_trim(pkt_pad, tail_pad + tail_chop);
2102 		__skb_queue_after(pktq, pkt, pkt_pad);
2103 	} else {
2104 		ntail = pkt->data_len + tail_pad -
2105 			(pkt->end - pkt->tail);
2106 		if (skb_cloned(pkt) || ntail > 0)
2107 			if (pskb_expand_head(pkt, 0, ntail, GFP_ATOMIC))
2108 				return -ENOMEM;
2109 		if (skb_linearize(pkt))
2110 			return -ENOMEM;
2111 		__skb_put(pkt, tail_pad);
2112 	}
2113 
2114 	return tail_pad;
2115 }
2116 
2117 /**
2118  * brcmf_sdio_txpkt_prep - packet preparation for transmit
2119  * @bus: brcmf_sdio structure pointer
2120  * @pktq: packet list pointer
2121  * @chan: virtual channel to transmit the packet
2122  *
2123  * Processes to be applied to the packet
2124  *	- Align data buffer pointer
2125  *	- Align data buffer length
2126  *	- Prepare header
2127  * Return: negative value if there is error
2128  */
2129 static int
2130 brcmf_sdio_txpkt_prep(struct brcmf_sdio *bus, struct sk_buff_head *pktq,
2131 		      uint chan)
2132 {
2133 	u16 head_pad, total_len;
2134 	struct sk_buff *pkt_next;
2135 	u8 txseq;
2136 	int ret;
2137 	struct brcmf_sdio_hdrinfo hd_info = {0};
2138 
2139 	txseq = bus->tx_seq;
2140 	total_len = 0;
2141 	skb_queue_walk(pktq, pkt_next) {
2142 		/* alignment packet inserted in previous
2143 		 * loop cycle can be skipped as it is
2144 		 * already properly aligned and does not
2145 		 * need an sdpcm header.
2146 		 */
2147 		if (*(u16 *)(pkt_next->cb) & ALIGN_SKB_FLAG)
2148 			continue;
2149 
2150 		/* align packet data pointer */
2151 		ret = brcmf_sdio_txpkt_hdalign(bus, pkt_next);
2152 		if (ret < 0)
2153 			return ret;
2154 		head_pad = (u16)ret;
2155 		if (head_pad)
2156 			memset(pkt_next->data + bus->tx_hdrlen, 0, head_pad);
2157 
2158 		total_len += pkt_next->len;
2159 
2160 		hd_info.len = pkt_next->len;
2161 		hd_info.lastfrm = skb_queue_is_last(pktq, pkt_next);
2162 		if (bus->txglom && pktq->qlen > 1) {
2163 			ret = brcmf_sdio_txpkt_prep_sg(bus, pktq,
2164 						       pkt_next, total_len);
2165 			if (ret < 0)
2166 				return ret;
2167 			hd_info.tail_pad = (u16)ret;
2168 			total_len += (u16)ret;
2169 		}
2170 
2171 		hd_info.channel = chan;
2172 		hd_info.dat_offset = head_pad + bus->tx_hdrlen;
2173 		hd_info.seq_num = txseq++;
2174 
2175 		/* Now fill the header */
2176 		brcmf_sdio_hdpack(bus, pkt_next->data, &hd_info);
2177 
2178 		if (BRCMF_BYTES_ON() &&
2179 		    ((BRCMF_CTL_ON() && chan == SDPCM_CONTROL_CHANNEL) ||
2180 		     (BRCMF_DATA_ON() && chan != SDPCM_CONTROL_CHANNEL)))
2181 			brcmf_dbg_hex_dump(true, pkt_next->data, hd_info.len,
2182 					   "Tx Frame:\n");
2183 		else if (BRCMF_HDRS_ON())
2184 			brcmf_dbg_hex_dump(true, pkt_next->data,
2185 					   head_pad + bus->tx_hdrlen,
2186 					   "Tx Header:\n");
2187 	}
2188 	/* Hardware length tag of the first packet should be total
2189 	 * length of the chain (including padding)
2190 	 */
2191 	if (bus->txglom)
2192 		brcmf_sdio_update_hwhdr(pktq->next->data, total_len);
2193 	return 0;
2194 }
2195 
2196 /**
2197  * brcmf_sdio_txpkt_postp - packet post processing for transmit
2198  * @bus: brcmf_sdio structure pointer
2199  * @pktq: packet list pointer
2200  *
2201  * Processes to be applied to the packet
2202  *	- Remove head padding
2203  *	- Remove tail padding
2204  */
2205 static void
2206 brcmf_sdio_txpkt_postp(struct brcmf_sdio *bus, struct sk_buff_head *pktq)
2207 {
2208 	u8 *hdr;
2209 	u32 dat_offset;
2210 	u16 tail_pad;
2211 	u16 dummy_flags, chop_len;
2212 	struct sk_buff *pkt_next, *tmp, *pkt_prev;
2213 
2214 	skb_queue_walk_safe(pktq, pkt_next, tmp) {
2215 		dummy_flags = *(u16 *)(pkt_next->cb);
2216 		if (dummy_flags & ALIGN_SKB_FLAG) {
2217 			chop_len = dummy_flags & ALIGN_SKB_CHOP_LEN_MASK;
2218 			if (chop_len) {
2219 				pkt_prev = pkt_next->prev;
2220 				skb_put(pkt_prev, chop_len);
2221 			}
2222 			__skb_unlink(pkt_next, pktq);
2223 			brcmu_pkt_buf_free_skb(pkt_next);
2224 		} else {
2225 			hdr = pkt_next->data + bus->tx_hdrlen - SDPCM_SWHDR_LEN;
2226 			dat_offset = le32_to_cpu(*(__le32 *)hdr);
2227 			dat_offset = (dat_offset & SDPCM_DOFFSET_MASK) >>
2228 				     SDPCM_DOFFSET_SHIFT;
2229 			skb_pull(pkt_next, dat_offset);
2230 			if (bus->txglom) {
2231 				tail_pad = le16_to_cpu(*(__le16 *)(hdr - 2));
2232 				skb_trim(pkt_next, pkt_next->len - tail_pad);
2233 			}
2234 		}
2235 	}
2236 }
2237 
2238 /* Writes a HW/SW header into the packet and sends it. */
2239 /* Assumes: (a) header space already there, (b) caller holds lock */
2240 static int brcmf_sdio_txpkt(struct brcmf_sdio *bus, struct sk_buff_head *pktq,
2241 			    uint chan)
2242 {
2243 	int ret;
2244 	struct sk_buff *pkt_next, *tmp;
2245 
2246 	brcmf_dbg(TRACE, "Enter\n");
2247 
2248 	ret = brcmf_sdio_txpkt_prep(bus, pktq, chan);
2249 	if (ret)
2250 		goto done;
2251 
2252 	sdio_claim_host(bus->sdiodev->func1);
2253 	ret = brcmf_sdiod_send_pkt(bus->sdiodev, pktq);
2254 	bus->sdcnt.f2txdata++;
2255 
2256 	if (ret < 0)
2257 		brcmf_sdio_txfail(bus);
2258 
2259 	sdio_release_host(bus->sdiodev->func1);
2260 
2261 done:
2262 	brcmf_sdio_txpkt_postp(bus, pktq);
2263 	if (ret == 0)
2264 		bus->tx_seq = (bus->tx_seq + pktq->qlen) % SDPCM_SEQ_WRAP;
2265 	skb_queue_walk_safe(pktq, pkt_next, tmp) {
2266 		__skb_unlink(pkt_next, pktq);
2267 		brcmf_proto_bcdc_txcomplete(bus->sdiodev->dev, pkt_next,
2268 					    ret == 0);
2269 	}
2270 	return ret;
2271 }
2272 
2273 static uint brcmf_sdio_sendfromq(struct brcmf_sdio *bus, uint maxframes)
2274 {
2275 	struct sk_buff *pkt;
2276 	struct sk_buff_head pktq;
2277 	u32 intstat_addr = bus->sdio_core->base + SD_REG(intstatus);
2278 	u32 intstatus = 0;
2279 	int ret = 0, prec_out, i;
2280 	uint cnt = 0;
2281 	u8 tx_prec_map, pkt_num;
2282 
2283 	brcmf_dbg(TRACE, "Enter\n");
2284 
2285 	tx_prec_map = ~bus->flowcontrol;
2286 
2287 	/* Send frames until the limit or some other event */
2288 	for (cnt = 0; (cnt < maxframes) && data_ok(bus);) {
2289 		pkt_num = 1;
2290 		if (bus->txglom)
2291 			pkt_num = min_t(u8, bus->tx_max - bus->tx_seq,
2292 					bus->sdiodev->txglomsz);
2293 		pkt_num = min_t(u32, pkt_num,
2294 				brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol));
2295 		__skb_queue_head_init(&pktq);
2296 		spin_lock_bh(&bus->txq_lock);
2297 		for (i = 0; i < pkt_num; i++) {
2298 			pkt = brcmu_pktq_mdeq(&bus->txq, tx_prec_map,
2299 					      &prec_out);
2300 			if (pkt == NULL)
2301 				break;
2302 			__skb_queue_tail(&pktq, pkt);
2303 		}
2304 		spin_unlock_bh(&bus->txq_lock);
2305 		if (i == 0)
2306 			break;
2307 
2308 		ret = brcmf_sdio_txpkt(bus, &pktq, SDPCM_DATA_CHANNEL);
2309 
2310 		cnt += i;
2311 
2312 		/* In poll mode, need to check for other events */
2313 		if (!bus->intr) {
2314 			/* Check device status, signal pending interrupt */
2315 			sdio_claim_host(bus->sdiodev->func1);
2316 			intstatus = brcmf_sdiod_readl(bus->sdiodev,
2317 						      intstat_addr, &ret);
2318 			sdio_release_host(bus->sdiodev->func1);
2319 
2320 			bus->sdcnt.f2txdata++;
2321 			if (ret != 0)
2322 				break;
2323 			if (intstatus & bus->hostintmask)
2324 				atomic_set(&bus->ipend, 1);
2325 		}
2326 	}
2327 
2328 	/* Deflow-control stack if needed */
2329 	if ((bus->sdiodev->state == BRCMF_SDIOD_DATA) &&
2330 	    bus->txoff && (pktq_len(&bus->txq) < TXLOW)) {
2331 		bus->txoff = false;
2332 		brcmf_proto_bcdc_txflowblock(bus->sdiodev->dev, false);
2333 	}
2334 
2335 	return cnt;
2336 }
2337 
2338 static int brcmf_sdio_tx_ctrlframe(struct brcmf_sdio *bus, u8 *frame, u16 len)
2339 {
2340 	u8 doff;
2341 	u16 pad;
2342 	uint retries = 0;
2343 	struct brcmf_sdio_hdrinfo hd_info = {0};
2344 	int ret;
2345 
2346 	brcmf_dbg(SDIO, "Enter\n");
2347 
2348 	/* Back the pointer to make room for bus header */
2349 	frame -= bus->tx_hdrlen;
2350 	len += bus->tx_hdrlen;
2351 
2352 	/* Add alignment padding (optional for ctl frames) */
2353 	doff = ((unsigned long)frame % bus->head_align);
2354 	if (doff) {
2355 		frame -= doff;
2356 		len += doff;
2357 		memset(frame + bus->tx_hdrlen, 0, doff);
2358 	}
2359 
2360 	/* Round send length to next SDIO block */
2361 	pad = 0;
2362 	if (bus->roundup && bus->blocksize && (len > bus->blocksize)) {
2363 		pad = bus->blocksize - (len % bus->blocksize);
2364 		if ((pad > bus->roundup) || (pad >= bus->blocksize))
2365 			pad = 0;
2366 	} else if (len % bus->head_align) {
2367 		pad = bus->head_align - (len % bus->head_align);
2368 	}
2369 	len += pad;
2370 
2371 	hd_info.len = len - pad;
2372 	hd_info.channel = SDPCM_CONTROL_CHANNEL;
2373 	hd_info.dat_offset = doff + bus->tx_hdrlen;
2374 	hd_info.seq_num = bus->tx_seq;
2375 	hd_info.lastfrm = true;
2376 	hd_info.tail_pad = pad;
2377 	brcmf_sdio_hdpack(bus, frame, &hd_info);
2378 
2379 	if (bus->txglom)
2380 		brcmf_sdio_update_hwhdr(frame, len);
2381 
2382 	brcmf_dbg_hex_dump(BRCMF_BYTES_ON() && BRCMF_CTL_ON(),
2383 			   frame, len, "Tx Frame:\n");
2384 	brcmf_dbg_hex_dump(!(BRCMF_BYTES_ON() && BRCMF_CTL_ON()) &&
2385 			   BRCMF_HDRS_ON(),
2386 			   frame, min_t(u16, len, 16), "TxHdr:\n");
2387 
2388 	do {
2389 		ret = brcmf_sdiod_send_buf(bus->sdiodev, frame, len);
2390 
2391 		if (ret < 0)
2392 			brcmf_sdio_txfail(bus);
2393 		else
2394 			bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQ_WRAP;
2395 	} while (ret < 0 && retries++ < TXRETRIES);
2396 
2397 	return ret;
2398 }
2399 
2400 static void brcmf_sdio_bus_stop(struct device *dev)
2401 {
2402 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2403 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2404 	struct brcmf_sdio *bus = sdiodev->bus;
2405 	struct brcmf_core *core = bus->sdio_core;
2406 	u32 local_hostintmask;
2407 	u8 saveclk;
2408 	int err;
2409 
2410 	brcmf_dbg(TRACE, "Enter\n");
2411 
2412 	if (bus->watchdog_tsk) {
2413 		send_sig(SIGTERM, bus->watchdog_tsk, 1);
2414 		kthread_stop(bus->watchdog_tsk);
2415 		bus->watchdog_tsk = NULL;
2416 	}
2417 
2418 	if (sdiodev->state != BRCMF_SDIOD_NOMEDIUM) {
2419 		sdio_claim_host(sdiodev->func1);
2420 
2421 		/* Enable clock for device interrupts */
2422 		brcmf_sdio_bus_sleep(bus, false, false);
2423 
2424 		/* Disable and clear interrupts at the chip level also */
2425 		brcmf_sdiod_writel(sdiodev, core->base + SD_REG(hostintmask),
2426 				   0, NULL);
2427 
2428 		local_hostintmask = bus->hostintmask;
2429 		bus->hostintmask = 0;
2430 
2431 		/* Force backplane clocks to assure F2 interrupt propagates */
2432 		saveclk = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
2433 					    &err);
2434 		if (!err)
2435 			brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
2436 					   (saveclk | SBSDIO_FORCE_HT), &err);
2437 		if (err)
2438 			brcmf_err("Failed to force clock for F2: err %d\n",
2439 				  err);
2440 
2441 		/* Turn off the bus (F2), free any pending packets */
2442 		brcmf_dbg(INTR, "disable SDIO interrupts\n");
2443 		sdio_disable_func(sdiodev->func2);
2444 
2445 		/* Clear any pending interrupts now that F2 is disabled */
2446 		brcmf_sdiod_writel(sdiodev, core->base + SD_REG(intstatus),
2447 				   local_hostintmask, NULL);
2448 
2449 		sdio_release_host(sdiodev->func1);
2450 	}
2451 	/* Clear the data packet queues */
2452 	brcmu_pktq_flush(&bus->txq, true, NULL, NULL);
2453 
2454 	/* Clear any held glomming stuff */
2455 	brcmu_pkt_buf_free_skb(bus->glomd);
2456 	brcmf_sdio_free_glom(bus);
2457 
2458 	/* Clear rx control and wake any waiters */
2459 	spin_lock_bh(&bus->rxctl_lock);
2460 	bus->rxlen = 0;
2461 	spin_unlock_bh(&bus->rxctl_lock);
2462 	brcmf_sdio_dcmd_resp_wake(bus);
2463 
2464 	/* Reset some F2 state stuff */
2465 	bus->rxskip = false;
2466 	bus->tx_seq = bus->rx_seq = 0;
2467 }
2468 
2469 static inline void brcmf_sdio_clrintr(struct brcmf_sdio *bus)
2470 {
2471 	struct brcmf_sdio_dev *sdiodev;
2472 	unsigned long flags;
2473 
2474 	sdiodev = bus->sdiodev;
2475 	if (sdiodev->oob_irq_requested) {
2476 		spin_lock_irqsave(&sdiodev->irq_en_lock, flags);
2477 		if (!sdiodev->irq_en && !atomic_read(&bus->ipend)) {
2478 			enable_irq(sdiodev->settings->bus.sdio.oob_irq_nr);
2479 			sdiodev->irq_en = true;
2480 		}
2481 		spin_unlock_irqrestore(&sdiodev->irq_en_lock, flags);
2482 	}
2483 }
2484 
2485 static int brcmf_sdio_intr_rstatus(struct brcmf_sdio *bus)
2486 {
2487 	struct brcmf_core *core = bus->sdio_core;
2488 	u32 addr;
2489 	unsigned long val;
2490 	int ret;
2491 
2492 	addr = core->base + SD_REG(intstatus);
2493 
2494 	val = brcmf_sdiod_readl(bus->sdiodev, addr, &ret);
2495 	bus->sdcnt.f1regdata++;
2496 	if (ret != 0)
2497 		return ret;
2498 
2499 	val &= bus->hostintmask;
2500 	atomic_set(&bus->fcstate, !!(val & I_HMB_FC_STATE));
2501 
2502 	/* Clear interrupts */
2503 	if (val) {
2504 		brcmf_sdiod_writel(bus->sdiodev, addr, val, &ret);
2505 		bus->sdcnt.f1regdata++;
2506 		atomic_or(val, &bus->intstatus);
2507 	}
2508 
2509 	return ret;
2510 }
2511 
2512 static void brcmf_sdio_dpc(struct brcmf_sdio *bus)
2513 {
2514 	struct brcmf_sdio_dev *sdiod = bus->sdiodev;
2515 	u32 newstatus = 0;
2516 	u32 intstat_addr = bus->sdio_core->base + SD_REG(intstatus);
2517 	unsigned long intstatus;
2518 	uint txlimit = bus->txbound;	/* Tx frames to send before resched */
2519 	uint framecnt;			/* Temporary counter of tx/rx frames */
2520 	int err = 0;
2521 
2522 	brcmf_dbg(SDIO, "Enter\n");
2523 
2524 	sdio_claim_host(bus->sdiodev->func1);
2525 
2526 	/* If waiting for HTAVAIL, check status */
2527 	if (!bus->sr_enabled && bus->clkstate == CLK_PENDING) {
2528 		u8 clkctl, devctl = 0;
2529 
2530 #ifdef DEBUG
2531 		/* Check for inconsistent device control */
2532 		devctl = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_DEVICE_CTL,
2533 					   &err);
2534 #endif				/* DEBUG */
2535 
2536 		/* Read CSR, if clock on switch to AVAIL, else ignore */
2537 		clkctl = brcmf_sdiod_readb(bus->sdiodev,
2538 					   SBSDIO_FUNC1_CHIPCLKCSR, &err);
2539 
2540 		brcmf_dbg(SDIO, "DPC: PENDING, devctl 0x%02x clkctl 0x%02x\n",
2541 			  devctl, clkctl);
2542 
2543 		if (SBSDIO_HTAV(clkctl)) {
2544 			devctl = brcmf_sdiod_readb(bus->sdiodev,
2545 						   SBSDIO_DEVICE_CTL, &err);
2546 			devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY;
2547 			brcmf_sdiod_writeb(bus->sdiodev,
2548 					   SBSDIO_DEVICE_CTL, devctl, &err);
2549 			bus->clkstate = CLK_AVAIL;
2550 		}
2551 	}
2552 
2553 	/* Make sure backplane clock is on */
2554 	brcmf_sdio_bus_sleep(bus, false, true);
2555 
2556 	/* Pending interrupt indicates new device status */
2557 	if (atomic_read(&bus->ipend) > 0) {
2558 		atomic_set(&bus->ipend, 0);
2559 		err = brcmf_sdio_intr_rstatus(bus);
2560 	}
2561 
2562 	/* Start with leftover status bits */
2563 	intstatus = atomic_xchg(&bus->intstatus, 0);
2564 
2565 	/* Handle flow-control change: read new state in case our ack
2566 	 * crossed another change interrupt.  If change still set, assume
2567 	 * FC ON for safety, let next loop through do the debounce.
2568 	 */
2569 	if (intstatus & I_HMB_FC_CHANGE) {
2570 		intstatus &= ~I_HMB_FC_CHANGE;
2571 		brcmf_sdiod_writel(sdiod, intstat_addr, I_HMB_FC_CHANGE, &err);
2572 
2573 		newstatus = brcmf_sdiod_readl(sdiod, intstat_addr, &err);
2574 
2575 		bus->sdcnt.f1regdata += 2;
2576 		atomic_set(&bus->fcstate,
2577 			   !!(newstatus & (I_HMB_FC_STATE | I_HMB_FC_CHANGE)));
2578 		intstatus |= (newstatus & bus->hostintmask);
2579 	}
2580 
2581 	/* Handle host mailbox indication */
2582 	if (intstatus & I_HMB_HOST_INT) {
2583 		intstatus &= ~I_HMB_HOST_INT;
2584 		intstatus |= brcmf_sdio_hostmail(bus);
2585 	}
2586 
2587 	sdio_release_host(bus->sdiodev->func1);
2588 
2589 	/* Generally don't ask for these, can get CRC errors... */
2590 	if (intstatus & I_WR_OOSYNC) {
2591 		brcmf_err("Dongle reports WR_OOSYNC\n");
2592 		intstatus &= ~I_WR_OOSYNC;
2593 	}
2594 
2595 	if (intstatus & I_RD_OOSYNC) {
2596 		brcmf_err("Dongle reports RD_OOSYNC\n");
2597 		intstatus &= ~I_RD_OOSYNC;
2598 	}
2599 
2600 	if (intstatus & I_SBINT) {
2601 		brcmf_err("Dongle reports SBINT\n");
2602 		intstatus &= ~I_SBINT;
2603 	}
2604 
2605 	/* Would be active due to wake-wlan in gSPI */
2606 	if (intstatus & I_CHIPACTIVE) {
2607 		brcmf_dbg(SDIO, "Dongle reports CHIPACTIVE\n");
2608 		intstatus &= ~I_CHIPACTIVE;
2609 	}
2610 
2611 	/* Ignore frame indications if rxskip is set */
2612 	if (bus->rxskip)
2613 		intstatus &= ~I_HMB_FRAME_IND;
2614 
2615 	/* On frame indication, read available frames */
2616 	if ((intstatus & I_HMB_FRAME_IND) && (bus->clkstate == CLK_AVAIL)) {
2617 		brcmf_sdio_readframes(bus, bus->rxbound);
2618 		if (!bus->rxpending)
2619 			intstatus &= ~I_HMB_FRAME_IND;
2620 	}
2621 
2622 	/* Keep still-pending events for next scheduling */
2623 	if (intstatus)
2624 		atomic_or(intstatus, &bus->intstatus);
2625 
2626 	brcmf_sdio_clrintr(bus);
2627 
2628 	if (bus->ctrl_frame_stat && (bus->clkstate == CLK_AVAIL) &&
2629 	    data_ok(bus)) {
2630 		sdio_claim_host(bus->sdiodev->func1);
2631 		if (bus->ctrl_frame_stat) {
2632 			err = brcmf_sdio_tx_ctrlframe(bus,  bus->ctrl_frame_buf,
2633 						      bus->ctrl_frame_len);
2634 			bus->ctrl_frame_err = err;
2635 			wmb();
2636 			bus->ctrl_frame_stat = false;
2637 		}
2638 		sdio_release_host(bus->sdiodev->func1);
2639 		brcmf_sdio_wait_event_wakeup(bus);
2640 	}
2641 	/* Send queued frames (limit 1 if rx may still be pending) */
2642 	if ((bus->clkstate == CLK_AVAIL) && !atomic_read(&bus->fcstate) &&
2643 	    brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol) && txlimit &&
2644 	    data_ok(bus)) {
2645 		framecnt = bus->rxpending ? min(txlimit, bus->txminmax) :
2646 					    txlimit;
2647 		brcmf_sdio_sendfromq(bus, framecnt);
2648 	}
2649 
2650 	if ((bus->sdiodev->state != BRCMF_SDIOD_DATA) || (err != 0)) {
2651 		brcmf_err("failed backplane access over SDIO, halting operation\n");
2652 		atomic_set(&bus->intstatus, 0);
2653 		if (bus->ctrl_frame_stat) {
2654 			sdio_claim_host(bus->sdiodev->func1);
2655 			if (bus->ctrl_frame_stat) {
2656 				bus->ctrl_frame_err = -ENODEV;
2657 				wmb();
2658 				bus->ctrl_frame_stat = false;
2659 				brcmf_sdio_wait_event_wakeup(bus);
2660 			}
2661 			sdio_release_host(bus->sdiodev->func1);
2662 		}
2663 	} else if (atomic_read(&bus->intstatus) ||
2664 		   atomic_read(&bus->ipend) > 0 ||
2665 		   (!atomic_read(&bus->fcstate) &&
2666 		    brcmu_pktq_mlen(&bus->txq, ~bus->flowcontrol) &&
2667 		    data_ok(bus))) {
2668 		bus->dpc_triggered = true;
2669 	}
2670 }
2671 
2672 static struct pktq *brcmf_sdio_bus_gettxq(struct device *dev)
2673 {
2674 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2675 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2676 	struct brcmf_sdio *bus = sdiodev->bus;
2677 
2678 	return &bus->txq;
2679 }
2680 
2681 static bool brcmf_sdio_prec_enq(struct pktq *q, struct sk_buff *pkt, int prec)
2682 {
2683 	struct sk_buff *p;
2684 	int eprec = -1;		/* precedence to evict from */
2685 
2686 	/* Fast case, precedence queue is not full and we are also not
2687 	 * exceeding total queue length
2688 	 */
2689 	if (!pktq_pfull(q, prec) && !pktq_full(q)) {
2690 		brcmu_pktq_penq(q, prec, pkt);
2691 		return true;
2692 	}
2693 
2694 	/* Determine precedence from which to evict packet, if any */
2695 	if (pktq_pfull(q, prec)) {
2696 		eprec = prec;
2697 	} else if (pktq_full(q)) {
2698 		p = brcmu_pktq_peek_tail(q, &eprec);
2699 		if (eprec > prec)
2700 			return false;
2701 	}
2702 
2703 	/* Evict if needed */
2704 	if (eprec >= 0) {
2705 		/* Detect queueing to unconfigured precedence */
2706 		if (eprec == prec)
2707 			return false;	/* refuse newer (incoming) packet */
2708 		/* Evict packet according to discard policy */
2709 		p = brcmu_pktq_pdeq_tail(q, eprec);
2710 		if (p == NULL)
2711 			brcmf_err("brcmu_pktq_pdeq_tail() failed\n");
2712 		brcmu_pkt_buf_free_skb(p);
2713 	}
2714 
2715 	/* Enqueue */
2716 	p = brcmu_pktq_penq(q, prec, pkt);
2717 	if (p == NULL)
2718 		brcmf_err("brcmu_pktq_penq() failed\n");
2719 
2720 	return p != NULL;
2721 }
2722 
2723 static int brcmf_sdio_bus_txdata(struct device *dev, struct sk_buff *pkt)
2724 {
2725 	int ret = -EBADE;
2726 	uint prec;
2727 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2728 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2729 	struct brcmf_sdio *bus = sdiodev->bus;
2730 
2731 	brcmf_dbg(TRACE, "Enter: pkt: data %p len %d\n", pkt->data, pkt->len);
2732 	if (sdiodev->state != BRCMF_SDIOD_DATA)
2733 		return -EIO;
2734 
2735 	/* Add space for the header */
2736 	skb_push(pkt, bus->tx_hdrlen);
2737 	/* precondition: IS_ALIGNED((unsigned long)(pkt->data), 2) */
2738 
2739 	prec = prio2prec((pkt->priority & PRIOMASK));
2740 
2741 	/* Check for existing queue, current flow-control,
2742 			 pending event, or pending clock */
2743 	brcmf_dbg(TRACE, "deferring pktq len %d\n", pktq_len(&bus->txq));
2744 	bus->sdcnt.fcqueued++;
2745 
2746 	/* Priority based enq */
2747 	spin_lock_bh(&bus->txq_lock);
2748 	/* reset bus_flags in packet cb */
2749 	*(u16 *)(pkt->cb) = 0;
2750 	if (!brcmf_sdio_prec_enq(&bus->txq, pkt, prec)) {
2751 		skb_pull(pkt, bus->tx_hdrlen);
2752 		brcmf_err("out of bus->txq !!!\n");
2753 		ret = -ENOSR;
2754 	} else {
2755 		ret = 0;
2756 	}
2757 
2758 	if (pktq_len(&bus->txq) >= TXHI) {
2759 		bus->txoff = true;
2760 		brcmf_proto_bcdc_txflowblock(dev, true);
2761 	}
2762 	spin_unlock_bh(&bus->txq_lock);
2763 
2764 #ifdef DEBUG
2765 	if (pktq_plen(&bus->txq, prec) > qcount[prec])
2766 		qcount[prec] = pktq_plen(&bus->txq, prec);
2767 #endif
2768 
2769 	brcmf_sdio_trigger_dpc(bus);
2770 	return ret;
2771 }
2772 
2773 #ifdef DEBUG
2774 #define CONSOLE_LINE_MAX	192
2775 
2776 static int brcmf_sdio_readconsole(struct brcmf_sdio *bus)
2777 {
2778 	struct brcmf_console *c = &bus->console;
2779 	u8 line[CONSOLE_LINE_MAX], ch;
2780 	u32 n, idx, addr;
2781 	int rv;
2782 
2783 	/* Don't do anything until FWREADY updates console address */
2784 	if (bus->console_addr == 0)
2785 		return 0;
2786 
2787 	/* Read console log struct */
2788 	addr = bus->console_addr + offsetof(struct rte_console, log_le);
2789 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr, (u8 *)&c->log_le,
2790 			       sizeof(c->log_le));
2791 	if (rv < 0)
2792 		return rv;
2793 
2794 	/* Allocate console buffer (one time only) */
2795 	if (c->buf == NULL) {
2796 		c->bufsize = le32_to_cpu(c->log_le.buf_size);
2797 		c->buf = kmalloc(c->bufsize, GFP_ATOMIC);
2798 		if (c->buf == NULL)
2799 			return -ENOMEM;
2800 	}
2801 
2802 	idx = le32_to_cpu(c->log_le.idx);
2803 
2804 	/* Protect against corrupt value */
2805 	if (idx > c->bufsize)
2806 		return -EBADE;
2807 
2808 	/* Skip reading the console buffer if the index pointer
2809 	 has not moved */
2810 	if (idx == c->last)
2811 		return 0;
2812 
2813 	/* Read the console buffer */
2814 	addr = le32_to_cpu(c->log_le.buf);
2815 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr, c->buf, c->bufsize);
2816 	if (rv < 0)
2817 		return rv;
2818 
2819 	while (c->last != idx) {
2820 		for (n = 0; n < CONSOLE_LINE_MAX - 2; n++) {
2821 			if (c->last == idx) {
2822 				/* This would output a partial line.
2823 				 * Instead, back up
2824 				 * the buffer pointer and output this
2825 				 * line next time around.
2826 				 */
2827 				if (c->last >= n)
2828 					c->last -= n;
2829 				else
2830 					c->last = c->bufsize - n;
2831 				goto break2;
2832 			}
2833 			ch = c->buf[c->last];
2834 			c->last = (c->last + 1) % c->bufsize;
2835 			if (ch == '\n')
2836 				break;
2837 			line[n] = ch;
2838 		}
2839 
2840 		if (n > 0) {
2841 			if (line[n - 1] == '\r')
2842 				n--;
2843 			line[n] = 0;
2844 			pr_debug("CONSOLE: %s\n", line);
2845 		}
2846 	}
2847 break2:
2848 
2849 	return 0;
2850 }
2851 #endif				/* DEBUG */
2852 
2853 static int
2854 brcmf_sdio_bus_txctl(struct device *dev, unsigned char *msg, uint msglen)
2855 {
2856 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
2857 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
2858 	struct brcmf_sdio *bus = sdiodev->bus;
2859 	int ret;
2860 
2861 	brcmf_dbg(TRACE, "Enter\n");
2862 	if (sdiodev->state != BRCMF_SDIOD_DATA)
2863 		return -EIO;
2864 
2865 	/* Send from dpc */
2866 	bus->ctrl_frame_buf = msg;
2867 	bus->ctrl_frame_len = msglen;
2868 	wmb();
2869 	bus->ctrl_frame_stat = true;
2870 
2871 	brcmf_sdio_trigger_dpc(bus);
2872 	wait_event_interruptible_timeout(bus->ctrl_wait, !bus->ctrl_frame_stat,
2873 					 CTL_DONE_TIMEOUT);
2874 	ret = 0;
2875 	if (bus->ctrl_frame_stat) {
2876 		sdio_claim_host(bus->sdiodev->func1);
2877 		if (bus->ctrl_frame_stat) {
2878 			brcmf_dbg(SDIO, "ctrl_frame timeout\n");
2879 			bus->ctrl_frame_stat = false;
2880 			ret = -ETIMEDOUT;
2881 		}
2882 		sdio_release_host(bus->sdiodev->func1);
2883 	}
2884 	if (!ret) {
2885 		brcmf_dbg(SDIO, "ctrl_frame complete, err=%d\n",
2886 			  bus->ctrl_frame_err);
2887 		rmb();
2888 		ret = bus->ctrl_frame_err;
2889 	}
2890 
2891 	if (ret)
2892 		bus->sdcnt.tx_ctlerrs++;
2893 	else
2894 		bus->sdcnt.tx_ctlpkts++;
2895 
2896 	return ret;
2897 }
2898 
2899 #ifdef DEBUG
2900 static int brcmf_sdio_dump_console(struct seq_file *seq, struct brcmf_sdio *bus,
2901 				   struct sdpcm_shared *sh)
2902 {
2903 	u32 addr, console_ptr, console_size, console_index;
2904 	char *conbuf = NULL;
2905 	__le32 sh_val;
2906 	int rv;
2907 
2908 	/* obtain console information from device memory */
2909 	addr = sh->console_addr + offsetof(struct rte_console, log_le);
2910 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr,
2911 			       (u8 *)&sh_val, sizeof(u32));
2912 	if (rv < 0)
2913 		return rv;
2914 	console_ptr = le32_to_cpu(sh_val);
2915 
2916 	addr = sh->console_addr + offsetof(struct rte_console, log_le.buf_size);
2917 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr,
2918 			       (u8 *)&sh_val, sizeof(u32));
2919 	if (rv < 0)
2920 		return rv;
2921 	console_size = le32_to_cpu(sh_val);
2922 
2923 	addr = sh->console_addr + offsetof(struct rte_console, log_le.idx);
2924 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, addr,
2925 			       (u8 *)&sh_val, sizeof(u32));
2926 	if (rv < 0)
2927 		return rv;
2928 	console_index = le32_to_cpu(sh_val);
2929 
2930 	/* allocate buffer for console data */
2931 	if (console_size <= CONSOLE_BUFFER_MAX)
2932 		conbuf = vzalloc(console_size+1);
2933 
2934 	if (!conbuf)
2935 		return -ENOMEM;
2936 
2937 	/* obtain the console data from device */
2938 	conbuf[console_size] = '\0';
2939 	rv = brcmf_sdiod_ramrw(bus->sdiodev, false, console_ptr, (u8 *)conbuf,
2940 			       console_size);
2941 	if (rv < 0)
2942 		goto done;
2943 
2944 	rv = seq_write(seq, conbuf + console_index,
2945 		       console_size - console_index);
2946 	if (rv < 0)
2947 		goto done;
2948 
2949 	if (console_index > 0)
2950 		rv = seq_write(seq, conbuf, console_index - 1);
2951 
2952 done:
2953 	vfree(conbuf);
2954 	return rv;
2955 }
2956 
2957 static int brcmf_sdio_trap_info(struct seq_file *seq, struct brcmf_sdio *bus,
2958 				struct sdpcm_shared *sh)
2959 {
2960 	int error;
2961 	struct brcmf_trap_info tr;
2962 
2963 	if ((sh->flags & SDPCM_SHARED_TRAP) == 0) {
2964 		brcmf_dbg(INFO, "no trap in firmware\n");
2965 		return 0;
2966 	}
2967 
2968 	error = brcmf_sdiod_ramrw(bus->sdiodev, false, sh->trap_addr, (u8 *)&tr,
2969 				  sizeof(struct brcmf_trap_info));
2970 	if (error < 0)
2971 		return error;
2972 
2973 	seq_printf(seq,
2974 		   "dongle trap info: type 0x%x @ epc 0x%08x\n"
2975 		   "  cpsr 0x%08x spsr 0x%08x sp 0x%08x\n"
2976 		   "  lr   0x%08x pc   0x%08x offset 0x%x\n"
2977 		   "  r0   0x%08x r1   0x%08x r2 0x%08x r3 0x%08x\n"
2978 		   "  r4   0x%08x r5   0x%08x r6 0x%08x r7 0x%08x\n",
2979 		   le32_to_cpu(tr.type), le32_to_cpu(tr.epc),
2980 		   le32_to_cpu(tr.cpsr), le32_to_cpu(tr.spsr),
2981 		   le32_to_cpu(tr.r13), le32_to_cpu(tr.r14),
2982 		   le32_to_cpu(tr.pc), sh->trap_addr,
2983 		   le32_to_cpu(tr.r0), le32_to_cpu(tr.r1),
2984 		   le32_to_cpu(tr.r2), le32_to_cpu(tr.r3),
2985 		   le32_to_cpu(tr.r4), le32_to_cpu(tr.r5),
2986 		   le32_to_cpu(tr.r6), le32_to_cpu(tr.r7));
2987 
2988 	return 0;
2989 }
2990 
2991 static int brcmf_sdio_assert_info(struct seq_file *seq, struct brcmf_sdio *bus,
2992 				  struct sdpcm_shared *sh)
2993 {
2994 	int error = 0;
2995 	char file[80] = "?";
2996 	char expr[80] = "<???>";
2997 
2998 	if ((sh->flags & SDPCM_SHARED_ASSERT_BUILT) == 0) {
2999 		brcmf_dbg(INFO, "firmware not built with -assert\n");
3000 		return 0;
3001 	} else if ((sh->flags & SDPCM_SHARED_ASSERT) == 0) {
3002 		brcmf_dbg(INFO, "no assert in dongle\n");
3003 		return 0;
3004 	}
3005 
3006 	sdio_claim_host(bus->sdiodev->func1);
3007 	if (sh->assert_file_addr != 0) {
3008 		error = brcmf_sdiod_ramrw(bus->sdiodev, false,
3009 					  sh->assert_file_addr, (u8 *)file, 80);
3010 		if (error < 0)
3011 			return error;
3012 	}
3013 	if (sh->assert_exp_addr != 0) {
3014 		error = brcmf_sdiod_ramrw(bus->sdiodev, false,
3015 					  sh->assert_exp_addr, (u8 *)expr, 80);
3016 		if (error < 0)
3017 			return error;
3018 	}
3019 	sdio_release_host(bus->sdiodev->func1);
3020 
3021 	seq_printf(seq, "dongle assert: %s:%d: assert(%s)\n",
3022 		   file, sh->assert_line, expr);
3023 	return 0;
3024 }
3025 
3026 static int brcmf_sdio_checkdied(struct brcmf_sdio *bus)
3027 {
3028 	int error;
3029 	struct sdpcm_shared sh;
3030 
3031 	error = brcmf_sdio_readshared(bus, &sh);
3032 
3033 	if (error < 0)
3034 		return error;
3035 
3036 	if ((sh.flags & SDPCM_SHARED_ASSERT_BUILT) == 0)
3037 		brcmf_dbg(INFO, "firmware not built with -assert\n");
3038 	else if (sh.flags & SDPCM_SHARED_ASSERT)
3039 		brcmf_err("assertion in dongle\n");
3040 
3041 	if (sh.flags & SDPCM_SHARED_TRAP)
3042 		brcmf_err("firmware trap in dongle\n");
3043 
3044 	return 0;
3045 }
3046 
3047 static int brcmf_sdio_died_dump(struct seq_file *seq, struct brcmf_sdio *bus)
3048 {
3049 	int error = 0;
3050 	struct sdpcm_shared sh;
3051 
3052 	error = brcmf_sdio_readshared(bus, &sh);
3053 	if (error < 0)
3054 		goto done;
3055 
3056 	error = brcmf_sdio_assert_info(seq, bus, &sh);
3057 	if (error < 0)
3058 		goto done;
3059 
3060 	error = brcmf_sdio_trap_info(seq, bus, &sh);
3061 	if (error < 0)
3062 		goto done;
3063 
3064 	error = brcmf_sdio_dump_console(seq, bus, &sh);
3065 
3066 done:
3067 	return error;
3068 }
3069 
3070 static int brcmf_sdio_forensic_read(struct seq_file *seq, void *data)
3071 {
3072 	struct brcmf_bus *bus_if = dev_get_drvdata(seq->private);
3073 	struct brcmf_sdio *bus = bus_if->bus_priv.sdio->bus;
3074 
3075 	return brcmf_sdio_died_dump(seq, bus);
3076 }
3077 
3078 static int brcmf_debugfs_sdio_count_read(struct seq_file *seq, void *data)
3079 {
3080 	struct brcmf_bus *bus_if = dev_get_drvdata(seq->private);
3081 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3082 	struct brcmf_sdio_count *sdcnt = &sdiodev->bus->sdcnt;
3083 
3084 	seq_printf(seq,
3085 		   "intrcount:    %u\nlastintrs:    %u\n"
3086 		   "pollcnt:      %u\nregfails:     %u\n"
3087 		   "tx_sderrs:    %u\nfcqueued:     %u\n"
3088 		   "rxrtx:        %u\nrx_toolong:   %u\n"
3089 		   "rxc_errors:   %u\nrx_hdrfail:   %u\n"
3090 		   "rx_badhdr:    %u\nrx_badseq:    %u\n"
3091 		   "fc_rcvd:      %u\nfc_xoff:      %u\n"
3092 		   "fc_xon:       %u\nrxglomfail:   %u\n"
3093 		   "rxglomframes: %u\nrxglompkts:   %u\n"
3094 		   "f2rxhdrs:     %u\nf2rxdata:     %u\n"
3095 		   "f2txdata:     %u\nf1regdata:    %u\n"
3096 		   "tickcnt:      %u\ntx_ctlerrs:   %lu\n"
3097 		   "tx_ctlpkts:   %lu\nrx_ctlerrs:   %lu\n"
3098 		   "rx_ctlpkts:   %lu\nrx_readahead: %lu\n",
3099 		   sdcnt->intrcount, sdcnt->lastintrs,
3100 		   sdcnt->pollcnt, sdcnt->regfails,
3101 		   sdcnt->tx_sderrs, sdcnt->fcqueued,
3102 		   sdcnt->rxrtx, sdcnt->rx_toolong,
3103 		   sdcnt->rxc_errors, sdcnt->rx_hdrfail,
3104 		   sdcnt->rx_badhdr, sdcnt->rx_badseq,
3105 		   sdcnt->fc_rcvd, sdcnt->fc_xoff,
3106 		   sdcnt->fc_xon, sdcnt->rxglomfail,
3107 		   sdcnt->rxglomframes, sdcnt->rxglompkts,
3108 		   sdcnt->f2rxhdrs, sdcnt->f2rxdata,
3109 		   sdcnt->f2txdata, sdcnt->f1regdata,
3110 		   sdcnt->tickcnt, sdcnt->tx_ctlerrs,
3111 		   sdcnt->tx_ctlpkts, sdcnt->rx_ctlerrs,
3112 		   sdcnt->rx_ctlpkts, sdcnt->rx_readahead_cnt);
3113 
3114 	return 0;
3115 }
3116 
3117 static void brcmf_sdio_debugfs_create(struct brcmf_sdio *bus)
3118 {
3119 	struct brcmf_pub *drvr = bus->sdiodev->bus_if->drvr;
3120 	struct dentry *dentry = brcmf_debugfs_get_devdir(drvr);
3121 
3122 	if (IS_ERR_OR_NULL(dentry))
3123 		return;
3124 
3125 	bus->console_interval = BRCMF_CONSOLE;
3126 
3127 	brcmf_debugfs_add_entry(drvr, "forensics", brcmf_sdio_forensic_read);
3128 	brcmf_debugfs_add_entry(drvr, "counters",
3129 				brcmf_debugfs_sdio_count_read);
3130 	debugfs_create_u32("console_interval", 0644, dentry,
3131 			   &bus->console_interval);
3132 }
3133 #else
3134 static int brcmf_sdio_checkdied(struct brcmf_sdio *bus)
3135 {
3136 	return 0;
3137 }
3138 
3139 static void brcmf_sdio_debugfs_create(struct brcmf_sdio *bus)
3140 {
3141 }
3142 #endif /* DEBUG */
3143 
3144 static int
3145 brcmf_sdio_bus_rxctl(struct device *dev, unsigned char *msg, uint msglen)
3146 {
3147 	int timeleft;
3148 	uint rxlen = 0;
3149 	bool pending;
3150 	u8 *buf;
3151 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3152 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3153 	struct brcmf_sdio *bus = sdiodev->bus;
3154 
3155 	brcmf_dbg(TRACE, "Enter\n");
3156 	if (sdiodev->state != BRCMF_SDIOD_DATA)
3157 		return -EIO;
3158 
3159 	/* Wait until control frame is available */
3160 	timeleft = brcmf_sdio_dcmd_resp_wait(bus, &bus->rxlen, &pending);
3161 
3162 	spin_lock_bh(&bus->rxctl_lock);
3163 	rxlen = bus->rxlen;
3164 	memcpy(msg, bus->rxctl, min(msglen, rxlen));
3165 	bus->rxctl = NULL;
3166 	buf = bus->rxctl_orig;
3167 	bus->rxctl_orig = NULL;
3168 	bus->rxlen = 0;
3169 	spin_unlock_bh(&bus->rxctl_lock);
3170 	vfree(buf);
3171 
3172 	if (rxlen) {
3173 		brcmf_dbg(CTL, "resumed on rxctl frame, got %d expected %d\n",
3174 			  rxlen, msglen);
3175 	} else if (timeleft == 0) {
3176 		brcmf_err("resumed on timeout\n");
3177 		brcmf_sdio_checkdied(bus);
3178 	} else if (pending) {
3179 		brcmf_dbg(CTL, "cancelled\n");
3180 		return -ERESTARTSYS;
3181 	} else {
3182 		brcmf_dbg(CTL, "resumed for unknown reason?\n");
3183 		brcmf_sdio_checkdied(bus);
3184 	}
3185 
3186 	if (rxlen)
3187 		bus->sdcnt.rx_ctlpkts++;
3188 	else
3189 		bus->sdcnt.rx_ctlerrs++;
3190 
3191 	return rxlen ? (int)rxlen : -ETIMEDOUT;
3192 }
3193 
3194 #ifdef DEBUG
3195 static bool
3196 brcmf_sdio_verifymemory(struct brcmf_sdio_dev *sdiodev, u32 ram_addr,
3197 			u8 *ram_data, uint ram_sz)
3198 {
3199 	char *ram_cmp;
3200 	int err;
3201 	bool ret = true;
3202 	int address;
3203 	int offset;
3204 	int len;
3205 
3206 	/* read back and verify */
3207 	brcmf_dbg(INFO, "Compare RAM dl & ul at 0x%08x; size=%d\n", ram_addr,
3208 		  ram_sz);
3209 	ram_cmp = kmalloc(MEMBLOCK, GFP_KERNEL);
3210 	/* do not proceed while no memory but  */
3211 	if (!ram_cmp)
3212 		return true;
3213 
3214 	address = ram_addr;
3215 	offset = 0;
3216 	while (offset < ram_sz) {
3217 		len = ((offset + MEMBLOCK) < ram_sz) ? MEMBLOCK :
3218 		      ram_sz - offset;
3219 		err = brcmf_sdiod_ramrw(sdiodev, false, address, ram_cmp, len);
3220 		if (err) {
3221 			brcmf_err("error %d on reading %d membytes at 0x%08x\n",
3222 				  err, len, address);
3223 			ret = false;
3224 			break;
3225 		} else if (memcmp(ram_cmp, &ram_data[offset], len)) {
3226 			brcmf_err("Downloaded RAM image is corrupted, block offset is %d, len is %d\n",
3227 				  offset, len);
3228 			ret = false;
3229 			break;
3230 		}
3231 		offset += len;
3232 		address += len;
3233 	}
3234 
3235 	kfree(ram_cmp);
3236 
3237 	return ret;
3238 }
3239 #else	/* DEBUG */
3240 static bool
3241 brcmf_sdio_verifymemory(struct brcmf_sdio_dev *sdiodev, u32 ram_addr,
3242 			u8 *ram_data, uint ram_sz)
3243 {
3244 	return true;
3245 }
3246 #endif	/* DEBUG */
3247 
3248 static int brcmf_sdio_download_code_file(struct brcmf_sdio *bus,
3249 					 const struct firmware *fw)
3250 {
3251 	int err;
3252 
3253 	brcmf_dbg(TRACE, "Enter\n");
3254 
3255 	err = brcmf_sdiod_ramrw(bus->sdiodev, true, bus->ci->rambase,
3256 				(u8 *)fw->data, fw->size);
3257 	if (err)
3258 		brcmf_err("error %d on writing %d membytes at 0x%08x\n",
3259 			  err, (int)fw->size, bus->ci->rambase);
3260 	else if (!brcmf_sdio_verifymemory(bus->sdiodev, bus->ci->rambase,
3261 					  (u8 *)fw->data, fw->size))
3262 		err = -EIO;
3263 
3264 	return err;
3265 }
3266 
3267 static int brcmf_sdio_download_nvram(struct brcmf_sdio *bus,
3268 				     void *vars, u32 varsz)
3269 {
3270 	int address;
3271 	int err;
3272 
3273 	brcmf_dbg(TRACE, "Enter\n");
3274 
3275 	address = bus->ci->ramsize - varsz + bus->ci->rambase;
3276 	err = brcmf_sdiod_ramrw(bus->sdiodev, true, address, vars, varsz);
3277 	if (err)
3278 		brcmf_err("error %d on writing %d nvram bytes at 0x%08x\n",
3279 			  err, varsz, address);
3280 	else if (!brcmf_sdio_verifymemory(bus->sdiodev, address, vars, varsz))
3281 		err = -EIO;
3282 
3283 	return err;
3284 }
3285 
3286 static int brcmf_sdio_download_firmware(struct brcmf_sdio *bus,
3287 					const struct firmware *fw,
3288 					void *nvram, u32 nvlen)
3289 {
3290 	int bcmerror;
3291 	u32 rstvec;
3292 
3293 	sdio_claim_host(bus->sdiodev->func1);
3294 	brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
3295 
3296 	rstvec = get_unaligned_le32(fw->data);
3297 	brcmf_dbg(SDIO, "firmware rstvec: %x\n", rstvec);
3298 
3299 	bcmerror = brcmf_sdio_download_code_file(bus, fw);
3300 	release_firmware(fw);
3301 	if (bcmerror) {
3302 		brcmf_err("dongle image file download failed\n");
3303 		brcmf_fw_nvram_free(nvram);
3304 		goto err;
3305 	}
3306 
3307 	bcmerror = brcmf_sdio_download_nvram(bus, nvram, nvlen);
3308 	brcmf_fw_nvram_free(nvram);
3309 	if (bcmerror) {
3310 		brcmf_err("dongle nvram file download failed\n");
3311 		goto err;
3312 	}
3313 
3314 	/* Take arm out of reset */
3315 	if (!brcmf_chip_set_active(bus->ci, rstvec)) {
3316 		brcmf_err("error getting out of ARM core reset\n");
3317 		goto err;
3318 	}
3319 
3320 err:
3321 	brcmf_sdio_clkctl(bus, CLK_SDONLY, false);
3322 	sdio_release_host(bus->sdiodev->func1);
3323 	return bcmerror;
3324 }
3325 
3326 static void brcmf_sdio_sr_init(struct brcmf_sdio *bus)
3327 {
3328 	int err = 0;
3329 	u8 val;
3330 
3331 	brcmf_dbg(TRACE, "Enter\n");
3332 
3333 	val = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_WAKEUPCTRL, &err);
3334 	if (err) {
3335 		brcmf_err("error reading SBSDIO_FUNC1_WAKEUPCTRL\n");
3336 		return;
3337 	}
3338 
3339 	val |= 1 << SBSDIO_FUNC1_WCTRL_HTWAIT_SHIFT;
3340 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_WAKEUPCTRL, val, &err);
3341 	if (err) {
3342 		brcmf_err("error writing SBSDIO_FUNC1_WAKEUPCTRL\n");
3343 		return;
3344 	}
3345 
3346 	/* Add CMD14 Support */
3347 	brcmf_sdiod_func0_wb(bus->sdiodev, SDIO_CCCR_BRCM_CARDCAP,
3348 			     (SDIO_CCCR_BRCM_CARDCAP_CMD14_SUPPORT |
3349 			      SDIO_CCCR_BRCM_CARDCAP_CMD14_EXT),
3350 			     &err);
3351 	if (err) {
3352 		brcmf_err("error writing SDIO_CCCR_BRCM_CARDCAP\n");
3353 		return;
3354 	}
3355 
3356 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3357 			   SBSDIO_FORCE_HT, &err);
3358 	if (err) {
3359 		brcmf_err("error writing SBSDIO_FUNC1_CHIPCLKCSR\n");
3360 		return;
3361 	}
3362 
3363 	/* set flag */
3364 	bus->sr_enabled = true;
3365 	brcmf_dbg(INFO, "SR enabled\n");
3366 }
3367 
3368 /* enable KSO bit */
3369 static int brcmf_sdio_kso_init(struct brcmf_sdio *bus)
3370 {
3371 	struct brcmf_core *core = bus->sdio_core;
3372 	u8 val;
3373 	int err = 0;
3374 
3375 	brcmf_dbg(TRACE, "Enter\n");
3376 
3377 	/* KSO bit added in SDIO core rev 12 */
3378 	if (core->rev < 12)
3379 		return 0;
3380 
3381 	val = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR, &err);
3382 	if (err) {
3383 		brcmf_err("error reading SBSDIO_FUNC1_SLEEPCSR\n");
3384 		return err;
3385 	}
3386 
3387 	if (!(val & SBSDIO_FUNC1_SLEEPCSR_KSO_MASK)) {
3388 		val |= (SBSDIO_FUNC1_SLEEPCSR_KSO_EN <<
3389 			SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT);
3390 		brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
3391 				   val, &err);
3392 		if (err) {
3393 			brcmf_err("error writing SBSDIO_FUNC1_SLEEPCSR\n");
3394 			return err;
3395 		}
3396 	}
3397 
3398 	return 0;
3399 }
3400 
3401 
3402 static int brcmf_sdio_bus_preinit(struct device *dev)
3403 {
3404 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3405 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3406 	struct brcmf_sdio *bus = sdiodev->bus;
3407 	struct brcmf_core *core = bus->sdio_core;
3408 	uint pad_size;
3409 	u32 value;
3410 	int err;
3411 
3412 	/* maxctl provided by common layer */
3413 	if (WARN_ON(!bus_if->maxctl))
3414 		return -EINVAL;
3415 
3416 	/* Allocate control receive buffer */
3417 	bus_if->maxctl += bus->roundup;
3418 	value = roundup((bus_if->maxctl + SDPCM_HDRLEN), ALIGNMENT);
3419 	value += bus->head_align;
3420 	bus->rxbuf = kmalloc(value, GFP_ATOMIC);
3421 	if (bus->rxbuf)
3422 		bus->rxblen = value;
3423 
3424 	brcmf_sdio_debugfs_create(bus);
3425 
3426 	/* the commands below use the terms tx and rx from
3427 	 * a device perspective, ie. bus:txglom affects the
3428 	 * bus transfers from device to host.
3429 	 */
3430 	if (core->rev < 12) {
3431 		/* for sdio core rev < 12, disable txgloming */
3432 		value = 0;
3433 		err = brcmf_iovar_data_set(dev, "bus:txglom", &value,
3434 					   sizeof(u32));
3435 	} else {
3436 		/* otherwise, set txglomalign */
3437 		value = sdiodev->settings->bus.sdio.sd_sgentry_align;
3438 		/* SDIO ADMA requires at least 32 bit alignment */
3439 		value = max_t(u32, value, ALIGNMENT);
3440 		err = brcmf_iovar_data_set(dev, "bus:txglomalign", &value,
3441 					   sizeof(u32));
3442 	}
3443 
3444 	if (err < 0)
3445 		goto done;
3446 
3447 	bus->tx_hdrlen = SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN;
3448 	if (sdiodev->sg_support) {
3449 		bus->txglom = false;
3450 		value = 1;
3451 		pad_size = bus->sdiodev->func2->cur_blksize << 1;
3452 		err = brcmf_iovar_data_set(bus->sdiodev->dev, "bus:rxglom",
3453 					   &value, sizeof(u32));
3454 		if (err < 0) {
3455 			/* bus:rxglom is allowed to fail */
3456 			err = 0;
3457 		} else {
3458 			bus->txglom = true;
3459 			bus->tx_hdrlen += SDPCM_HWEXT_LEN;
3460 		}
3461 	}
3462 	brcmf_bus_add_txhdrlen(bus->sdiodev->dev, bus->tx_hdrlen);
3463 
3464 done:
3465 	return err;
3466 }
3467 
3468 static size_t brcmf_sdio_bus_get_ramsize(struct device *dev)
3469 {
3470 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3471 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3472 	struct brcmf_sdio *bus = sdiodev->bus;
3473 
3474 	return bus->ci->ramsize - bus->ci->srsize;
3475 }
3476 
3477 static int brcmf_sdio_bus_get_memdump(struct device *dev, void *data,
3478 				      size_t mem_size)
3479 {
3480 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3481 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3482 	struct brcmf_sdio *bus = sdiodev->bus;
3483 	int err;
3484 	int address;
3485 	int offset;
3486 	int len;
3487 
3488 	brcmf_dbg(INFO, "dump at 0x%08x: size=%zu\n", bus->ci->rambase,
3489 		  mem_size);
3490 
3491 	address = bus->ci->rambase;
3492 	offset = err = 0;
3493 	sdio_claim_host(sdiodev->func1);
3494 	while (offset < mem_size) {
3495 		len = ((offset + MEMBLOCK) < mem_size) ? MEMBLOCK :
3496 		      mem_size - offset;
3497 		err = brcmf_sdiod_ramrw(sdiodev, false, address, data, len);
3498 		if (err) {
3499 			brcmf_err("error %d on reading %d membytes at 0x%08x\n",
3500 				  err, len, address);
3501 			goto done;
3502 		}
3503 		data += len;
3504 		offset += len;
3505 		address += len;
3506 	}
3507 
3508 done:
3509 	sdio_release_host(sdiodev->func1);
3510 	return err;
3511 }
3512 
3513 void brcmf_sdio_trigger_dpc(struct brcmf_sdio *bus)
3514 {
3515 	if (!bus->dpc_triggered) {
3516 		bus->dpc_triggered = true;
3517 		queue_work(bus->brcmf_wq, &bus->datawork);
3518 	}
3519 }
3520 
3521 void brcmf_sdio_isr(struct brcmf_sdio *bus)
3522 {
3523 	brcmf_dbg(TRACE, "Enter\n");
3524 
3525 	if (!bus) {
3526 		brcmf_err("bus is null pointer, exiting\n");
3527 		return;
3528 	}
3529 
3530 	/* Count the interrupt call */
3531 	bus->sdcnt.intrcount++;
3532 	if (in_interrupt())
3533 		atomic_set(&bus->ipend, 1);
3534 	else
3535 		if (brcmf_sdio_intr_rstatus(bus)) {
3536 			brcmf_err("failed backplane access\n");
3537 		}
3538 
3539 	/* Disable additional interrupts (is this needed now)? */
3540 	if (!bus->intr)
3541 		brcmf_err("isr w/o interrupt configured!\n");
3542 
3543 	bus->dpc_triggered = true;
3544 	queue_work(bus->brcmf_wq, &bus->datawork);
3545 }
3546 
3547 static void brcmf_sdio_bus_watchdog(struct brcmf_sdio *bus)
3548 {
3549 	brcmf_dbg(TIMER, "Enter\n");
3550 
3551 	/* Poll period: check device if appropriate. */
3552 	if (!bus->sr_enabled &&
3553 	    bus->poll && (++bus->polltick >= bus->pollrate)) {
3554 		u32 intstatus = 0;
3555 
3556 		/* Reset poll tick */
3557 		bus->polltick = 0;
3558 
3559 		/* Check device if no interrupts */
3560 		if (!bus->intr ||
3561 		    (bus->sdcnt.intrcount == bus->sdcnt.lastintrs)) {
3562 
3563 			if (!bus->dpc_triggered) {
3564 				u8 devpend;
3565 
3566 				sdio_claim_host(bus->sdiodev->func1);
3567 				devpend = brcmf_sdiod_func0_rb(bus->sdiodev,
3568 						  SDIO_CCCR_INTx, NULL);
3569 				sdio_release_host(bus->sdiodev->func1);
3570 				intstatus = devpend & (INTR_STATUS_FUNC1 |
3571 						       INTR_STATUS_FUNC2);
3572 			}
3573 
3574 			/* If there is something, make like the ISR and
3575 				 schedule the DPC */
3576 			if (intstatus) {
3577 				bus->sdcnt.pollcnt++;
3578 				atomic_set(&bus->ipend, 1);
3579 
3580 				bus->dpc_triggered = true;
3581 				queue_work(bus->brcmf_wq, &bus->datawork);
3582 			}
3583 		}
3584 
3585 		/* Update interrupt tracking */
3586 		bus->sdcnt.lastintrs = bus->sdcnt.intrcount;
3587 	}
3588 #ifdef DEBUG
3589 	/* Poll for console output periodically */
3590 	if (bus->sdiodev->state == BRCMF_SDIOD_DATA && BRCMF_FWCON_ON() &&
3591 	    bus->console_interval != 0) {
3592 		bus->console.count += jiffies_to_msecs(BRCMF_WD_POLL);
3593 		if (bus->console.count >= bus->console_interval) {
3594 			bus->console.count -= bus->console_interval;
3595 			sdio_claim_host(bus->sdiodev->func1);
3596 			/* Make sure backplane clock is on */
3597 			brcmf_sdio_bus_sleep(bus, false, false);
3598 			if (brcmf_sdio_readconsole(bus) < 0)
3599 				/* stop on error */
3600 				bus->console_interval = 0;
3601 			sdio_release_host(bus->sdiodev->func1);
3602 		}
3603 	}
3604 #endif				/* DEBUG */
3605 
3606 	/* On idle timeout clear activity flag and/or turn off clock */
3607 	if (!bus->dpc_triggered) {
3608 		rmb();
3609 		if ((!bus->dpc_running) && (bus->idletime > 0) &&
3610 		    (bus->clkstate == CLK_AVAIL)) {
3611 			bus->idlecount++;
3612 			if (bus->idlecount > bus->idletime) {
3613 				brcmf_dbg(SDIO, "idle\n");
3614 				sdio_claim_host(bus->sdiodev->func1);
3615 				brcmf_sdio_wd_timer(bus, false);
3616 				bus->idlecount = 0;
3617 				brcmf_sdio_bus_sleep(bus, true, false);
3618 				sdio_release_host(bus->sdiodev->func1);
3619 			}
3620 		} else {
3621 			bus->idlecount = 0;
3622 		}
3623 	} else {
3624 		bus->idlecount = 0;
3625 	}
3626 }
3627 
3628 static void brcmf_sdio_dataworker(struct work_struct *work)
3629 {
3630 	struct brcmf_sdio *bus = container_of(work, struct brcmf_sdio,
3631 					      datawork);
3632 
3633 	bus->dpc_running = true;
3634 	wmb();
3635 	while (READ_ONCE(bus->dpc_triggered)) {
3636 		bus->dpc_triggered = false;
3637 		brcmf_sdio_dpc(bus);
3638 		bus->idlecount = 0;
3639 	}
3640 	bus->dpc_running = false;
3641 	if (brcmf_sdiod_freezing(bus->sdiodev)) {
3642 		brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DOWN);
3643 		brcmf_sdiod_try_freeze(bus->sdiodev);
3644 		brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DATA);
3645 	}
3646 }
3647 
3648 static void
3649 brcmf_sdio_drivestrengthinit(struct brcmf_sdio_dev *sdiodev,
3650 			     struct brcmf_chip *ci, u32 drivestrength)
3651 {
3652 	const struct sdiod_drive_str *str_tab = NULL;
3653 	u32 str_mask;
3654 	u32 str_shift;
3655 	u32 i;
3656 	u32 drivestrength_sel = 0;
3657 	u32 cc_data_temp;
3658 	u32 addr;
3659 
3660 	if (!(ci->cc_caps & CC_CAP_PMU))
3661 		return;
3662 
3663 	switch (SDIOD_DRVSTR_KEY(ci->chip, ci->pmurev)) {
3664 	case SDIOD_DRVSTR_KEY(BRCM_CC_4330_CHIP_ID, 12):
3665 		str_tab = sdiod_drvstr_tab1_1v8;
3666 		str_mask = 0x00003800;
3667 		str_shift = 11;
3668 		break;
3669 	case SDIOD_DRVSTR_KEY(BRCM_CC_4334_CHIP_ID, 17):
3670 		str_tab = sdiod_drvstr_tab6_1v8;
3671 		str_mask = 0x00001800;
3672 		str_shift = 11;
3673 		break;
3674 	case SDIOD_DRVSTR_KEY(BRCM_CC_43143_CHIP_ID, 17):
3675 		/* note: 43143 does not support tristate */
3676 		i = ARRAY_SIZE(sdiod_drvstr_tab2_3v3) - 1;
3677 		if (drivestrength >= sdiod_drvstr_tab2_3v3[i].strength) {
3678 			str_tab = sdiod_drvstr_tab2_3v3;
3679 			str_mask = 0x00000007;
3680 			str_shift = 0;
3681 		} else
3682 			brcmf_err("Invalid SDIO Drive strength for chip %s, strength=%d\n",
3683 				  ci->name, drivestrength);
3684 		break;
3685 	case SDIOD_DRVSTR_KEY(BRCM_CC_43362_CHIP_ID, 13):
3686 		str_tab = sdiod_drive_strength_tab5_1v8;
3687 		str_mask = 0x00003800;
3688 		str_shift = 11;
3689 		break;
3690 	default:
3691 		brcmf_dbg(INFO, "No SDIO driver strength init needed for chip %s rev %d pmurev %d\n",
3692 			  ci->name, ci->chiprev, ci->pmurev);
3693 		break;
3694 	}
3695 
3696 	if (str_tab != NULL) {
3697 		struct brcmf_core *pmu = brcmf_chip_get_pmu(ci);
3698 
3699 		for (i = 0; str_tab[i].strength != 0; i++) {
3700 			if (drivestrength >= str_tab[i].strength) {
3701 				drivestrength_sel = str_tab[i].sel;
3702 				break;
3703 			}
3704 		}
3705 		addr = CORE_CC_REG(pmu->base, chipcontrol_addr);
3706 		brcmf_sdiod_writel(sdiodev, addr, 1, NULL);
3707 		cc_data_temp = brcmf_sdiod_readl(sdiodev, addr, NULL);
3708 		cc_data_temp &= ~str_mask;
3709 		drivestrength_sel <<= str_shift;
3710 		cc_data_temp |= drivestrength_sel;
3711 		brcmf_sdiod_writel(sdiodev, addr, cc_data_temp, NULL);
3712 
3713 		brcmf_dbg(INFO, "SDIO: %d mA (req=%d mA) drive strength selected, set to 0x%08x\n",
3714 			  str_tab[i].strength, drivestrength, cc_data_temp);
3715 	}
3716 }
3717 
3718 static int brcmf_sdio_buscoreprep(void *ctx)
3719 {
3720 	struct brcmf_sdio_dev *sdiodev = ctx;
3721 	int err = 0;
3722 	u8 clkval, clkset;
3723 
3724 	/* Try forcing SDIO core to do ALPAvail request only */
3725 	clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
3726 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
3727 	if (err) {
3728 		brcmf_err("error writing for HT off\n");
3729 		return err;
3730 	}
3731 
3732 	/* If register supported, wait for ALPAvail and then force ALP */
3733 	/* This may take up to 15 milliseconds */
3734 	clkval = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, NULL);
3735 
3736 	if ((clkval & ~SBSDIO_AVBITS) != clkset) {
3737 		brcmf_err("ChipClkCSR access: wrote 0x%02x read 0x%02x\n",
3738 			  clkset, clkval);
3739 		return -EACCES;
3740 	}
3741 
3742 	SPINWAIT(((clkval = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3743 					      NULL)),
3744 		 !SBSDIO_ALPAV(clkval)),
3745 		 PMU_MAX_TRANSITION_DLY);
3746 
3747 	if (!SBSDIO_ALPAV(clkval)) {
3748 		brcmf_err("timeout on ALPAV wait, clkval 0x%02x\n",
3749 			  clkval);
3750 		return -EBUSY;
3751 	}
3752 
3753 	clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP;
3754 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
3755 	udelay(65);
3756 
3757 	/* Also, disable the extra SDIO pull-ups */
3758 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_SDIOPULLUP, 0, NULL);
3759 
3760 	return 0;
3761 }
3762 
3763 static void brcmf_sdio_buscore_activate(void *ctx, struct brcmf_chip *chip,
3764 					u32 rstvec)
3765 {
3766 	struct brcmf_sdio_dev *sdiodev = ctx;
3767 	struct brcmf_core *core = sdiodev->bus->sdio_core;
3768 	u32 reg_addr;
3769 
3770 	/* clear all interrupts */
3771 	reg_addr = core->base + SD_REG(intstatus);
3772 	brcmf_sdiod_writel(sdiodev, reg_addr, 0xFFFFFFFF, NULL);
3773 
3774 	if (rstvec)
3775 		/* Write reset vector to address 0 */
3776 		brcmf_sdiod_ramrw(sdiodev, true, 0, (void *)&rstvec,
3777 				  sizeof(rstvec));
3778 }
3779 
3780 static u32 brcmf_sdio_buscore_read32(void *ctx, u32 addr)
3781 {
3782 	struct brcmf_sdio_dev *sdiodev = ctx;
3783 	u32 val, rev;
3784 
3785 	val = brcmf_sdiod_readl(sdiodev, addr, NULL);
3786 
3787 	/*
3788 	 * this is a bit of special handling if reading the chipcommon chipid
3789 	 * register. The 4339 is a next-gen of the 4335. It uses the same
3790 	 * SDIO device id as 4335 and the chipid register returns 4335 as well.
3791 	 * It can be identified as 4339 by looking at the chip revision. It
3792 	 * is corrected here so the chip.c module has the right info.
3793 	 */
3794 	if (addr == CORE_CC_REG(SI_ENUM_BASE, chipid) &&
3795 	    (sdiodev->func1->device == SDIO_DEVICE_ID_BROADCOM_4339 ||
3796 	     sdiodev->func1->device == SDIO_DEVICE_ID_BROADCOM_4335_4339)) {
3797 		rev = (val & CID_REV_MASK) >> CID_REV_SHIFT;
3798 		if (rev >= 2) {
3799 			val &= ~CID_ID_MASK;
3800 			val |= BRCM_CC_4339_CHIP_ID;
3801 		}
3802 	}
3803 
3804 	return val;
3805 }
3806 
3807 static void brcmf_sdio_buscore_write32(void *ctx, u32 addr, u32 val)
3808 {
3809 	struct brcmf_sdio_dev *sdiodev = ctx;
3810 
3811 	brcmf_sdiod_writel(sdiodev, addr, val, NULL);
3812 }
3813 
3814 static const struct brcmf_buscore_ops brcmf_sdio_buscore_ops = {
3815 	.prepare = brcmf_sdio_buscoreprep,
3816 	.activate = brcmf_sdio_buscore_activate,
3817 	.read32 = brcmf_sdio_buscore_read32,
3818 	.write32 = brcmf_sdio_buscore_write32,
3819 };
3820 
3821 static bool
3822 brcmf_sdio_probe_attach(struct brcmf_sdio *bus)
3823 {
3824 	struct brcmf_sdio_dev *sdiodev;
3825 	u8 clkctl = 0;
3826 	int err = 0;
3827 	int reg_addr;
3828 	u32 reg_val;
3829 	u32 drivestrength;
3830 
3831 	sdiodev = bus->sdiodev;
3832 	sdio_claim_host(sdiodev->func1);
3833 
3834 	pr_debug("F1 signature read @0x18000000=0x%4x\n",
3835 		 brcmf_sdiod_readl(sdiodev, SI_ENUM_BASE, NULL));
3836 
3837 	/*
3838 	 * Force PLL off until brcmf_chip_attach()
3839 	 * programs PLL control regs
3840 	 */
3841 
3842 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, BRCMF_INIT_CLKCTL1,
3843 			   &err);
3844 	if (!err)
3845 		clkctl = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3846 					   &err);
3847 
3848 	if (err || ((clkctl & ~SBSDIO_AVBITS) != BRCMF_INIT_CLKCTL1)) {
3849 		brcmf_err("ChipClkCSR access: err %d wrote 0x%02x read 0x%02x\n",
3850 			  err, BRCMF_INIT_CLKCTL1, clkctl);
3851 		goto fail;
3852 	}
3853 
3854 	bus->ci = brcmf_chip_attach(sdiodev, &brcmf_sdio_buscore_ops);
3855 	if (IS_ERR(bus->ci)) {
3856 		brcmf_err("brcmf_chip_attach failed!\n");
3857 		bus->ci = NULL;
3858 		goto fail;
3859 	}
3860 
3861 	/* Pick up the SDIO core info struct from chip.c */
3862 	bus->sdio_core   = brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV);
3863 	if (!bus->sdio_core)
3864 		goto fail;
3865 
3866 	/* Pick up the CHIPCOMMON core info struct, for bulk IO in bcmsdh.c */
3867 	sdiodev->cc_core = brcmf_chip_get_core(bus->ci, BCMA_CORE_CHIPCOMMON);
3868 	if (!sdiodev->cc_core)
3869 		goto fail;
3870 
3871 	sdiodev->settings = brcmf_get_module_param(sdiodev->dev,
3872 						   BRCMF_BUSTYPE_SDIO,
3873 						   bus->ci->chip,
3874 						   bus->ci->chiprev);
3875 	if (!sdiodev->settings) {
3876 		brcmf_err("Failed to get device parameters\n");
3877 		goto fail;
3878 	}
3879 	/* platform specific configuration:
3880 	 *   alignments must be at least 4 bytes for ADMA
3881 	 */
3882 	bus->head_align = ALIGNMENT;
3883 	bus->sgentry_align = ALIGNMENT;
3884 	if (sdiodev->settings->bus.sdio.sd_head_align > ALIGNMENT)
3885 		bus->head_align = sdiodev->settings->bus.sdio.sd_head_align;
3886 	if (sdiodev->settings->bus.sdio.sd_sgentry_align > ALIGNMENT)
3887 		bus->sgentry_align =
3888 				sdiodev->settings->bus.sdio.sd_sgentry_align;
3889 
3890 	/* allocate scatter-gather table. sg support
3891 	 * will be disabled upon allocation failure.
3892 	 */
3893 	brcmf_sdiod_sgtable_alloc(sdiodev);
3894 
3895 #ifdef CONFIG_PM_SLEEP
3896 	/* wowl can be supported when KEEP_POWER is true and (WAKE_SDIO_IRQ
3897 	 * is true or when platform data OOB irq is true).
3898 	 */
3899 	if ((sdio_get_host_pm_caps(sdiodev->func1) & MMC_PM_KEEP_POWER) &&
3900 	    ((sdio_get_host_pm_caps(sdiodev->func1) & MMC_PM_WAKE_SDIO_IRQ) ||
3901 	     (sdiodev->settings->bus.sdio.oob_irq_supported)))
3902 		sdiodev->bus_if->wowl_supported = true;
3903 #endif
3904 
3905 	if (brcmf_sdio_kso_init(bus)) {
3906 		brcmf_err("error enabling KSO\n");
3907 		goto fail;
3908 	}
3909 
3910 	if (sdiodev->settings->bus.sdio.drive_strength)
3911 		drivestrength = sdiodev->settings->bus.sdio.drive_strength;
3912 	else
3913 		drivestrength = DEFAULT_SDIO_DRIVE_STRENGTH;
3914 	brcmf_sdio_drivestrengthinit(sdiodev, bus->ci, drivestrength);
3915 
3916 	/* Set card control so an SDIO card reset does a WLAN backplane reset */
3917 	reg_val = brcmf_sdiod_func0_rb(sdiodev, SDIO_CCCR_BRCM_CARDCTRL, &err);
3918 	if (err)
3919 		goto fail;
3920 
3921 	reg_val |= SDIO_CCCR_BRCM_CARDCTRL_WLANRESET;
3922 
3923 	brcmf_sdiod_func0_wb(sdiodev, SDIO_CCCR_BRCM_CARDCTRL, reg_val, &err);
3924 	if (err)
3925 		goto fail;
3926 
3927 	/* set PMUControl so a backplane reset does PMU state reload */
3928 	reg_addr = CORE_CC_REG(brcmf_chip_get_pmu(bus->ci)->base, pmucontrol);
3929 	reg_val = brcmf_sdiod_readl(sdiodev, reg_addr, &err);
3930 	if (err)
3931 		goto fail;
3932 
3933 	reg_val |= (BCMA_CC_PMU_CTL_RES_RELOAD << BCMA_CC_PMU_CTL_RES_SHIFT);
3934 
3935 	brcmf_sdiod_writel(sdiodev, reg_addr, reg_val, &err);
3936 	if (err)
3937 		goto fail;
3938 
3939 	sdio_release_host(sdiodev->func1);
3940 
3941 	brcmu_pktq_init(&bus->txq, (PRIOMASK + 1), TXQLEN);
3942 
3943 	/* allocate header buffer */
3944 	bus->hdrbuf = kzalloc(MAX_HDR_READ + bus->head_align, GFP_KERNEL);
3945 	if (!bus->hdrbuf)
3946 		return false;
3947 	/* Locate an appropriately-aligned portion of hdrbuf */
3948 	bus->rxhdr = (u8 *) roundup((unsigned long)&bus->hdrbuf[0],
3949 				    bus->head_align);
3950 
3951 	/* Set the poll and/or interrupt flags */
3952 	bus->intr = true;
3953 	bus->poll = false;
3954 	if (bus->poll)
3955 		bus->pollrate = 1;
3956 
3957 	return true;
3958 
3959 fail:
3960 	sdio_release_host(sdiodev->func1);
3961 	return false;
3962 }
3963 
3964 static int
3965 brcmf_sdio_watchdog_thread(void *data)
3966 {
3967 	struct brcmf_sdio *bus = (struct brcmf_sdio *)data;
3968 	int wait;
3969 
3970 	allow_signal(SIGTERM);
3971 	/* Run until signal received */
3972 	brcmf_sdiod_freezer_count(bus->sdiodev);
3973 	while (1) {
3974 		if (kthread_should_stop())
3975 			break;
3976 		brcmf_sdiod_freezer_uncount(bus->sdiodev);
3977 		wait = wait_for_completion_interruptible(&bus->watchdog_wait);
3978 		brcmf_sdiod_freezer_count(bus->sdiodev);
3979 		brcmf_sdiod_try_freeze(bus->sdiodev);
3980 		if (!wait) {
3981 			brcmf_sdio_bus_watchdog(bus);
3982 			/* Count the tick for reference */
3983 			bus->sdcnt.tickcnt++;
3984 			reinit_completion(&bus->watchdog_wait);
3985 		} else
3986 			break;
3987 	}
3988 	return 0;
3989 }
3990 
3991 static void
3992 brcmf_sdio_watchdog(struct timer_list *t)
3993 {
3994 	struct brcmf_sdio *bus = from_timer(bus, t, timer);
3995 
3996 	if (bus->watchdog_tsk) {
3997 		complete(&bus->watchdog_wait);
3998 		/* Reschedule the watchdog */
3999 		if (bus->wd_active)
4000 			mod_timer(&bus->timer,
4001 				  jiffies + BRCMF_WD_POLL);
4002 	}
4003 }
4004 
4005 static
4006 int brcmf_sdio_get_fwname(struct device *dev, const char *ext, u8 *fw_name)
4007 {
4008 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
4009 	struct brcmf_fw_request *fwreq;
4010 	struct brcmf_fw_name fwnames[] = {
4011 		{ ext, fw_name },
4012 	};
4013 
4014 	fwreq = brcmf_fw_alloc_request(bus_if->chip, bus_if->chiprev,
4015 				       brcmf_sdio_fwnames,
4016 				       ARRAY_SIZE(brcmf_sdio_fwnames),
4017 				       fwnames, ARRAY_SIZE(fwnames));
4018 	if (!fwreq)
4019 		return -ENOMEM;
4020 
4021 	kfree(fwreq);
4022 	return 0;
4023 }
4024 
4025 static const struct brcmf_bus_ops brcmf_sdio_bus_ops = {
4026 	.stop = brcmf_sdio_bus_stop,
4027 	.preinit = brcmf_sdio_bus_preinit,
4028 	.txdata = brcmf_sdio_bus_txdata,
4029 	.txctl = brcmf_sdio_bus_txctl,
4030 	.rxctl = brcmf_sdio_bus_rxctl,
4031 	.gettxq = brcmf_sdio_bus_gettxq,
4032 	.wowl_config = brcmf_sdio_wowl_config,
4033 	.get_ramsize = brcmf_sdio_bus_get_ramsize,
4034 	.get_memdump = brcmf_sdio_bus_get_memdump,
4035 	.get_fwname = brcmf_sdio_get_fwname,
4036 };
4037 
4038 #define BRCMF_SDIO_FW_CODE	0
4039 #define BRCMF_SDIO_FW_NVRAM	1
4040 
4041 static void brcmf_sdio_firmware_callback(struct device *dev, int err,
4042 					 struct brcmf_fw_request *fwreq)
4043 {
4044 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
4045 	struct brcmf_sdio_dev *sdiod = bus_if->bus_priv.sdio;
4046 	struct brcmf_sdio *bus = sdiod->bus;
4047 	struct brcmf_core *core = bus->sdio_core;
4048 	const struct firmware *code;
4049 	void *nvram;
4050 	u32 nvram_len;
4051 	u8 saveclk;
4052 
4053 	brcmf_dbg(TRACE, "Enter: dev=%s, err=%d\n", dev_name(dev), err);
4054 
4055 	if (err)
4056 		goto fail;
4057 
4058 	code = fwreq->items[BRCMF_SDIO_FW_CODE].binary;
4059 	nvram = fwreq->items[BRCMF_SDIO_FW_NVRAM].nv_data.data;
4060 	nvram_len = fwreq->items[BRCMF_SDIO_FW_NVRAM].nv_data.len;
4061 	kfree(fwreq);
4062 
4063 	/* try to download image and nvram to the dongle */
4064 	bus->alp_only = true;
4065 	err = brcmf_sdio_download_firmware(bus, code, nvram, nvram_len);
4066 	if (err)
4067 		goto fail;
4068 	bus->alp_only = false;
4069 
4070 	/* Start the watchdog timer */
4071 	bus->sdcnt.tickcnt = 0;
4072 	brcmf_sdio_wd_timer(bus, true);
4073 
4074 	sdio_claim_host(sdiod->func1);
4075 
4076 	/* Make sure backplane clock is on, needed to generate F2 interrupt */
4077 	brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
4078 	if (bus->clkstate != CLK_AVAIL)
4079 		goto release;
4080 
4081 	/* Force clocks on backplane to be sure F2 interrupt propagates */
4082 	saveclk = brcmf_sdiod_readb(sdiod, SBSDIO_FUNC1_CHIPCLKCSR, &err);
4083 	if (!err) {
4084 		brcmf_sdiod_writeb(sdiod, SBSDIO_FUNC1_CHIPCLKCSR,
4085 				   (saveclk | SBSDIO_FORCE_HT), &err);
4086 	}
4087 	if (err) {
4088 		brcmf_err("Failed to force clock for F2: err %d\n", err);
4089 		goto release;
4090 	}
4091 
4092 	/* Enable function 2 (frame transfers) */
4093 	brcmf_sdiod_writel(sdiod, core->base + SD_REG(tosbmailboxdata),
4094 			   SDPCM_PROT_VERSION << SMB_DATA_VERSION_SHIFT, NULL);
4095 
4096 	err = sdio_enable_func(sdiod->func2);
4097 
4098 	brcmf_dbg(INFO, "enable F2: err=%d\n", err);
4099 
4100 	/* If F2 successfully enabled, set core and enable interrupts */
4101 	if (!err) {
4102 		/* Set up the interrupt mask and enable interrupts */
4103 		bus->hostintmask = HOSTINTMASK;
4104 		brcmf_sdiod_writel(sdiod, core->base + SD_REG(hostintmask),
4105 				   bus->hostintmask, NULL);
4106 
4107 
4108 		brcmf_sdiod_writeb(sdiod, SBSDIO_WATERMARK, 8, &err);
4109 	} else {
4110 		/* Disable F2 again */
4111 		sdio_disable_func(sdiod->func2);
4112 		goto release;
4113 	}
4114 
4115 	if (brcmf_chip_sr_capable(bus->ci)) {
4116 		brcmf_sdio_sr_init(bus);
4117 	} else {
4118 		/* Restore previous clock setting */
4119 		brcmf_sdiod_writeb(sdiod, SBSDIO_FUNC1_CHIPCLKCSR,
4120 				   saveclk, &err);
4121 	}
4122 
4123 	if (err == 0) {
4124 		/* Allow full data communication using DPC from now on. */
4125 		brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DATA);
4126 
4127 		err = brcmf_sdiod_intr_register(sdiod);
4128 		if (err != 0)
4129 			brcmf_err("intr register failed:%d\n", err);
4130 	}
4131 
4132 	/* If we didn't come up, turn off backplane clock */
4133 	if (err != 0)
4134 		brcmf_sdio_clkctl(bus, CLK_NONE, false);
4135 
4136 	sdio_release_host(sdiod->func1);
4137 
4138 	/* Assign bus interface call back */
4139 	sdiod->bus_if->dev = sdiod->dev;
4140 	sdiod->bus_if->ops = &brcmf_sdio_bus_ops;
4141 	sdiod->bus_if->chip = bus->ci->chip;
4142 	sdiod->bus_if->chiprev = bus->ci->chiprev;
4143 
4144 	/* Attach to the common layer, reserve hdr space */
4145 	err = brcmf_attach(sdiod->dev, sdiod->settings);
4146 	if (err != 0) {
4147 		brcmf_err("brcmf_attach failed\n");
4148 		goto fail;
4149 	}
4150 
4151 	/* ready */
4152 	return;
4153 
4154 release:
4155 	sdio_release_host(sdiod->func1);
4156 fail:
4157 	brcmf_dbg(TRACE, "failed: dev=%s, err=%d\n", dev_name(dev), err);
4158 	device_release_driver(&sdiod->func2->dev);
4159 	device_release_driver(dev);
4160 }
4161 
4162 static struct brcmf_fw_request *
4163 brcmf_sdio_prepare_fw_request(struct brcmf_sdio *bus)
4164 {
4165 	struct brcmf_fw_request *fwreq;
4166 	struct brcmf_fw_name fwnames[] = {
4167 		{ ".bin", bus->sdiodev->fw_name },
4168 		{ ".txt", bus->sdiodev->nvram_name },
4169 	};
4170 
4171 	fwreq = brcmf_fw_alloc_request(bus->ci->chip, bus->ci->chiprev,
4172 				       brcmf_sdio_fwnames,
4173 				       ARRAY_SIZE(brcmf_sdio_fwnames),
4174 				       fwnames, ARRAY_SIZE(fwnames));
4175 	if (!fwreq)
4176 		return NULL;
4177 
4178 	fwreq->items[BRCMF_SDIO_FW_CODE].type = BRCMF_FW_TYPE_BINARY;
4179 	fwreq->items[BRCMF_SDIO_FW_NVRAM].type = BRCMF_FW_TYPE_NVRAM;
4180 
4181 	return fwreq;
4182 }
4183 
4184 struct brcmf_sdio *brcmf_sdio_probe(struct brcmf_sdio_dev *sdiodev)
4185 {
4186 	int ret;
4187 	struct brcmf_sdio *bus;
4188 	struct workqueue_struct *wq;
4189 	struct brcmf_fw_request *fwreq;
4190 
4191 	brcmf_dbg(TRACE, "Enter\n");
4192 
4193 	/* Allocate private bus interface state */
4194 	bus = kzalloc(sizeof(struct brcmf_sdio), GFP_ATOMIC);
4195 	if (!bus)
4196 		goto fail;
4197 
4198 	bus->sdiodev = sdiodev;
4199 	sdiodev->bus = bus;
4200 	skb_queue_head_init(&bus->glom);
4201 	bus->txbound = BRCMF_TXBOUND;
4202 	bus->rxbound = BRCMF_RXBOUND;
4203 	bus->txminmax = BRCMF_TXMINMAX;
4204 	bus->tx_seq = SDPCM_SEQ_WRAP - 1;
4205 
4206 	/* single-threaded workqueue */
4207 	wq = alloc_ordered_workqueue("brcmf_wq/%s", WQ_MEM_RECLAIM,
4208 				     dev_name(&sdiodev->func1->dev));
4209 	if (!wq) {
4210 		brcmf_err("insufficient memory to create txworkqueue\n");
4211 		goto fail;
4212 	}
4213 	brcmf_sdiod_freezer_count(sdiodev);
4214 	INIT_WORK(&bus->datawork, brcmf_sdio_dataworker);
4215 	bus->brcmf_wq = wq;
4216 
4217 	/* attempt to attach to the dongle */
4218 	if (!(brcmf_sdio_probe_attach(bus))) {
4219 		brcmf_err("brcmf_sdio_probe_attach failed\n");
4220 		goto fail;
4221 	}
4222 
4223 	spin_lock_init(&bus->rxctl_lock);
4224 	spin_lock_init(&bus->txq_lock);
4225 	init_waitqueue_head(&bus->ctrl_wait);
4226 	init_waitqueue_head(&bus->dcmd_resp_wait);
4227 
4228 	/* Set up the watchdog timer */
4229 	timer_setup(&bus->timer, brcmf_sdio_watchdog, 0);
4230 	/* Initialize watchdog thread */
4231 	init_completion(&bus->watchdog_wait);
4232 	bus->watchdog_tsk = kthread_run(brcmf_sdio_watchdog_thread,
4233 					bus, "brcmf_wdog/%s",
4234 					dev_name(&sdiodev->func1->dev));
4235 	if (IS_ERR(bus->watchdog_tsk)) {
4236 		pr_warn("brcmf_watchdog thread failed to start\n");
4237 		bus->watchdog_tsk = NULL;
4238 	}
4239 	/* Initialize DPC thread */
4240 	bus->dpc_triggered = false;
4241 	bus->dpc_running = false;
4242 
4243 	/* default sdio bus header length for tx packet */
4244 	bus->tx_hdrlen = SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN;
4245 
4246 	/* Query the F2 block size, set roundup accordingly */
4247 	bus->blocksize = bus->sdiodev->func2->cur_blksize;
4248 	bus->roundup = min(max_roundup, bus->blocksize);
4249 
4250 	sdio_claim_host(bus->sdiodev->func1);
4251 
4252 	/* Disable F2 to clear any intermediate frame state on the dongle */
4253 	sdio_disable_func(bus->sdiodev->func2);
4254 
4255 	bus->rxflow = false;
4256 
4257 	/* Done with backplane-dependent accesses, can drop clock... */
4258 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL);
4259 
4260 	sdio_release_host(bus->sdiodev->func1);
4261 
4262 	/* ...and initialize clock/power states */
4263 	bus->clkstate = CLK_SDONLY;
4264 	bus->idletime = BRCMF_IDLE_INTERVAL;
4265 	bus->idleclock = BRCMF_IDLE_ACTIVE;
4266 
4267 	/* SR state */
4268 	bus->sr_enabled = false;
4269 
4270 	brcmf_dbg(INFO, "completed!!\n");
4271 
4272 	fwreq = brcmf_sdio_prepare_fw_request(bus);
4273 	if (!fwreq) {
4274 		ret = -ENOMEM;
4275 		goto fail;
4276 	}
4277 
4278 	ret = brcmf_fw_get_firmwares(sdiodev->dev, fwreq,
4279 				     brcmf_sdio_firmware_callback);
4280 	if (ret != 0) {
4281 		brcmf_err("async firmware request failed: %d\n", ret);
4282 		kfree(fwreq);
4283 		goto fail;
4284 	}
4285 
4286 	return bus;
4287 
4288 fail:
4289 	brcmf_sdio_remove(bus);
4290 	return NULL;
4291 }
4292 
4293 /* Detach and free everything */
4294 void brcmf_sdio_remove(struct brcmf_sdio *bus)
4295 {
4296 	brcmf_dbg(TRACE, "Enter\n");
4297 
4298 	if (bus) {
4299 		/* Stop watchdog task */
4300 		if (bus->watchdog_tsk) {
4301 			send_sig(SIGTERM, bus->watchdog_tsk, 1);
4302 			kthread_stop(bus->watchdog_tsk);
4303 			bus->watchdog_tsk = NULL;
4304 		}
4305 
4306 		/* De-register interrupt handler */
4307 		brcmf_sdiod_intr_unregister(bus->sdiodev);
4308 
4309 		brcmf_detach(bus->sdiodev->dev);
4310 
4311 		cancel_work_sync(&bus->datawork);
4312 		if (bus->brcmf_wq)
4313 			destroy_workqueue(bus->brcmf_wq);
4314 
4315 		if (bus->ci) {
4316 			if (bus->sdiodev->state != BRCMF_SDIOD_NOMEDIUM) {
4317 				sdio_claim_host(bus->sdiodev->func1);
4318 				brcmf_sdio_wd_timer(bus, false);
4319 				brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
4320 				/* Leave the device in state where it is
4321 				 * 'passive'. This is done by resetting all
4322 				 * necessary cores.
4323 				 */
4324 				msleep(20);
4325 				brcmf_chip_set_passive(bus->ci);
4326 				brcmf_sdio_clkctl(bus, CLK_NONE, false);
4327 				sdio_release_host(bus->sdiodev->func1);
4328 			}
4329 			brcmf_chip_detach(bus->ci);
4330 		}
4331 		if (bus->sdiodev->settings)
4332 			brcmf_release_module_param(bus->sdiodev->settings);
4333 
4334 		kfree(bus->rxbuf);
4335 		kfree(bus->hdrbuf);
4336 		kfree(bus);
4337 	}
4338 
4339 	brcmf_dbg(TRACE, "Disconnected\n");
4340 }
4341 
4342 void brcmf_sdio_wd_timer(struct brcmf_sdio *bus, bool active)
4343 {
4344 	/* Totally stop the timer */
4345 	if (!active && bus->wd_active) {
4346 		del_timer_sync(&bus->timer);
4347 		bus->wd_active = false;
4348 		return;
4349 	}
4350 
4351 	/* don't start the wd until fw is loaded */
4352 	if (bus->sdiodev->state != BRCMF_SDIOD_DATA)
4353 		return;
4354 
4355 	if (active) {
4356 		if (!bus->wd_active) {
4357 			/* Create timer again when watchdog period is
4358 			   dynamically changed or in the first instance
4359 			 */
4360 			bus->timer.expires = jiffies + BRCMF_WD_POLL;
4361 			add_timer(&bus->timer);
4362 			bus->wd_active = true;
4363 		} else {
4364 			/* Re arm the timer, at last watchdog period */
4365 			mod_timer(&bus->timer, jiffies + BRCMF_WD_POLL);
4366 		}
4367 	}
4368 }
4369 
4370 int brcmf_sdio_sleep(struct brcmf_sdio *bus, bool sleep)
4371 {
4372 	int ret;
4373 
4374 	sdio_claim_host(bus->sdiodev->func1);
4375 	ret = brcmf_sdio_bus_sleep(bus, sleep, false);
4376 	sdio_release_host(bus->sdiodev->func1);
4377 
4378 	return ret;
4379 }
4380 
4381