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