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 	if (seq)
3003 		seq_printf(seq,
3004 			   "dongle trap info: type 0x%x @ epc 0x%08x\n"
3005 			   "  cpsr 0x%08x spsr 0x%08x sp 0x%08x\n"
3006 			   "  lr   0x%08x pc   0x%08x offset 0x%x\n"
3007 			   "  r0   0x%08x r1   0x%08x r2 0x%08x r3 0x%08x\n"
3008 			   "  r4   0x%08x r5   0x%08x r6 0x%08x r7 0x%08x\n",
3009 			   le32_to_cpu(tr.type), le32_to_cpu(tr.epc),
3010 			   le32_to_cpu(tr.cpsr), le32_to_cpu(tr.spsr),
3011 			   le32_to_cpu(tr.r13), le32_to_cpu(tr.r14),
3012 			   le32_to_cpu(tr.pc), sh->trap_addr,
3013 			   le32_to_cpu(tr.r0), le32_to_cpu(tr.r1),
3014 			   le32_to_cpu(tr.r2), le32_to_cpu(tr.r3),
3015 			   le32_to_cpu(tr.r4), le32_to_cpu(tr.r5),
3016 			   le32_to_cpu(tr.r6), le32_to_cpu(tr.r7));
3017 	else
3018 		pr_debug("dongle trap info: type 0x%x @ epc 0x%08x\n"
3019 			 "  cpsr 0x%08x spsr 0x%08x sp 0x%08x\n"
3020 			 "  lr   0x%08x pc   0x%08x offset 0x%x\n"
3021 			 "  r0   0x%08x r1   0x%08x r2 0x%08x r3 0x%08x\n"
3022 			 "  r4   0x%08x r5   0x%08x r6 0x%08x r7 0x%08x\n",
3023 			 le32_to_cpu(tr.type), le32_to_cpu(tr.epc),
3024 			 le32_to_cpu(tr.cpsr), le32_to_cpu(tr.spsr),
3025 			 le32_to_cpu(tr.r13), le32_to_cpu(tr.r14),
3026 			 le32_to_cpu(tr.pc), sh->trap_addr,
3027 			 le32_to_cpu(tr.r0), le32_to_cpu(tr.r1),
3028 			 le32_to_cpu(tr.r2), le32_to_cpu(tr.r3),
3029 			 le32_to_cpu(tr.r4), le32_to_cpu(tr.r5),
3030 			 le32_to_cpu(tr.r6), le32_to_cpu(tr.r7));
3031 	return 0;
3032 }
3033 
3034 static int brcmf_sdio_assert_info(struct seq_file *seq, struct brcmf_sdio *bus,
3035 				  struct sdpcm_shared *sh)
3036 {
3037 	int error = 0;
3038 	char file[80] = "?";
3039 	char expr[80] = "<???>";
3040 
3041 	if ((sh->flags & SDPCM_SHARED_ASSERT_BUILT) == 0) {
3042 		brcmf_dbg(INFO, "firmware not built with -assert\n");
3043 		return 0;
3044 	} else if ((sh->flags & SDPCM_SHARED_ASSERT) == 0) {
3045 		brcmf_dbg(INFO, "no assert in dongle\n");
3046 		return 0;
3047 	}
3048 
3049 	sdio_claim_host(bus->sdiodev->func1);
3050 	if (sh->assert_file_addr != 0) {
3051 		error = brcmf_sdiod_ramrw(bus->sdiodev, false,
3052 					  sh->assert_file_addr, (u8 *)file, 80);
3053 		if (error < 0)
3054 			return error;
3055 	}
3056 	if (sh->assert_exp_addr != 0) {
3057 		error = brcmf_sdiod_ramrw(bus->sdiodev, false,
3058 					  sh->assert_exp_addr, (u8 *)expr, 80);
3059 		if (error < 0)
3060 			return error;
3061 	}
3062 	sdio_release_host(bus->sdiodev->func1);
3063 
3064 	seq_printf(seq, "dongle assert: %s:%d: assert(%s)\n",
3065 		   file, sh->assert_line, expr);
3066 	return 0;
3067 }
3068 
3069 static int brcmf_sdio_checkdied(struct brcmf_sdio *bus)
3070 {
3071 	int error;
3072 	struct sdpcm_shared sh;
3073 
3074 	error = brcmf_sdio_readshared(bus, &sh);
3075 
3076 	if (error < 0)
3077 		return error;
3078 
3079 	if ((sh.flags & SDPCM_SHARED_ASSERT_BUILT) == 0)
3080 		brcmf_dbg(INFO, "firmware not built with -assert\n");
3081 	else if (sh.flags & SDPCM_SHARED_ASSERT)
3082 		brcmf_err("assertion in dongle\n");
3083 
3084 	if (sh.flags & SDPCM_SHARED_TRAP) {
3085 		brcmf_err("firmware trap in dongle\n");
3086 		brcmf_sdio_trap_info(NULL, bus, &sh);
3087 	}
3088 
3089 	return 0;
3090 }
3091 
3092 static int brcmf_sdio_died_dump(struct seq_file *seq, struct brcmf_sdio *bus)
3093 {
3094 	int error = 0;
3095 	struct sdpcm_shared sh;
3096 
3097 	error = brcmf_sdio_readshared(bus, &sh);
3098 	if (error < 0)
3099 		goto done;
3100 
3101 	error = brcmf_sdio_assert_info(seq, bus, &sh);
3102 	if (error < 0)
3103 		goto done;
3104 
3105 	error = brcmf_sdio_trap_info(seq, bus, &sh);
3106 	if (error < 0)
3107 		goto done;
3108 
3109 	error = brcmf_sdio_dump_console(seq, bus, &sh);
3110 
3111 done:
3112 	return error;
3113 }
3114 
3115 static int brcmf_sdio_forensic_read(struct seq_file *seq, void *data)
3116 {
3117 	struct brcmf_bus *bus_if = dev_get_drvdata(seq->private);
3118 	struct brcmf_sdio *bus = bus_if->bus_priv.sdio->bus;
3119 
3120 	return brcmf_sdio_died_dump(seq, bus);
3121 }
3122 
3123 static int brcmf_debugfs_sdio_count_read(struct seq_file *seq, void *data)
3124 {
3125 	struct brcmf_bus *bus_if = dev_get_drvdata(seq->private);
3126 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3127 	struct brcmf_sdio_count *sdcnt = &sdiodev->bus->sdcnt;
3128 
3129 	seq_printf(seq,
3130 		   "intrcount:    %u\nlastintrs:    %u\n"
3131 		   "pollcnt:      %u\nregfails:     %u\n"
3132 		   "tx_sderrs:    %u\nfcqueued:     %u\n"
3133 		   "rxrtx:        %u\nrx_toolong:   %u\n"
3134 		   "rxc_errors:   %u\nrx_hdrfail:   %u\n"
3135 		   "rx_badhdr:    %u\nrx_badseq:    %u\n"
3136 		   "fc_rcvd:      %u\nfc_xoff:      %u\n"
3137 		   "fc_xon:       %u\nrxglomfail:   %u\n"
3138 		   "rxglomframes: %u\nrxglompkts:   %u\n"
3139 		   "f2rxhdrs:     %u\nf2rxdata:     %u\n"
3140 		   "f2txdata:     %u\nf1regdata:    %u\n"
3141 		   "tickcnt:      %u\ntx_ctlerrs:   %lu\n"
3142 		   "tx_ctlpkts:   %lu\nrx_ctlerrs:   %lu\n"
3143 		   "rx_ctlpkts:   %lu\nrx_readahead: %lu\n",
3144 		   sdcnt->intrcount, sdcnt->lastintrs,
3145 		   sdcnt->pollcnt, sdcnt->regfails,
3146 		   sdcnt->tx_sderrs, sdcnt->fcqueued,
3147 		   sdcnt->rxrtx, sdcnt->rx_toolong,
3148 		   sdcnt->rxc_errors, sdcnt->rx_hdrfail,
3149 		   sdcnt->rx_badhdr, sdcnt->rx_badseq,
3150 		   sdcnt->fc_rcvd, sdcnt->fc_xoff,
3151 		   sdcnt->fc_xon, sdcnt->rxglomfail,
3152 		   sdcnt->rxglomframes, sdcnt->rxglompkts,
3153 		   sdcnt->f2rxhdrs, sdcnt->f2rxdata,
3154 		   sdcnt->f2txdata, sdcnt->f1regdata,
3155 		   sdcnt->tickcnt, sdcnt->tx_ctlerrs,
3156 		   sdcnt->tx_ctlpkts, sdcnt->rx_ctlerrs,
3157 		   sdcnt->rx_ctlpkts, sdcnt->rx_readahead_cnt);
3158 
3159 	return 0;
3160 }
3161 
3162 static void brcmf_sdio_debugfs_create(struct device *dev)
3163 {
3164 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3165 	struct brcmf_pub *drvr = bus_if->drvr;
3166 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3167 	struct brcmf_sdio *bus = sdiodev->bus;
3168 	struct dentry *dentry = brcmf_debugfs_get_devdir(drvr);
3169 
3170 	if (IS_ERR_OR_NULL(dentry))
3171 		return;
3172 
3173 	bus->console_interval = BRCMF_CONSOLE;
3174 
3175 	brcmf_debugfs_add_entry(drvr, "forensics", brcmf_sdio_forensic_read);
3176 	brcmf_debugfs_add_entry(drvr, "counters",
3177 				brcmf_debugfs_sdio_count_read);
3178 	debugfs_create_u32("console_interval", 0644, dentry,
3179 			   &bus->console_interval);
3180 }
3181 #else
3182 static int brcmf_sdio_checkdied(struct brcmf_sdio *bus)
3183 {
3184 	return 0;
3185 }
3186 
3187 static void brcmf_sdio_debugfs_create(struct device *dev)
3188 {
3189 }
3190 #endif /* DEBUG */
3191 
3192 static int
3193 brcmf_sdio_bus_rxctl(struct device *dev, unsigned char *msg, uint msglen)
3194 {
3195 	int timeleft;
3196 	uint rxlen = 0;
3197 	bool pending;
3198 	u8 *buf;
3199 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3200 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3201 	struct brcmf_sdio *bus = sdiodev->bus;
3202 
3203 	brcmf_dbg(TRACE, "Enter\n");
3204 	if (sdiodev->state != BRCMF_SDIOD_DATA)
3205 		return -EIO;
3206 
3207 	/* Wait until control frame is available */
3208 	timeleft = brcmf_sdio_dcmd_resp_wait(bus, &bus->rxlen, &pending);
3209 
3210 	spin_lock_bh(&bus->rxctl_lock);
3211 	rxlen = bus->rxlen;
3212 	memcpy(msg, bus->rxctl, min(msglen, rxlen));
3213 	bus->rxctl = NULL;
3214 	buf = bus->rxctl_orig;
3215 	bus->rxctl_orig = NULL;
3216 	bus->rxlen = 0;
3217 	spin_unlock_bh(&bus->rxctl_lock);
3218 	vfree(buf);
3219 
3220 	if (rxlen) {
3221 		brcmf_dbg(CTL, "resumed on rxctl frame, got %d expected %d\n",
3222 			  rxlen, msglen);
3223 	} else if (timeleft == 0) {
3224 		brcmf_err("resumed on timeout\n");
3225 		brcmf_sdio_checkdied(bus);
3226 	} else if (pending) {
3227 		brcmf_dbg(CTL, "cancelled\n");
3228 		return -ERESTARTSYS;
3229 	} else {
3230 		brcmf_dbg(CTL, "resumed for unknown reason?\n");
3231 		brcmf_sdio_checkdied(bus);
3232 	}
3233 
3234 	if (rxlen)
3235 		bus->sdcnt.rx_ctlpkts++;
3236 	else
3237 		bus->sdcnt.rx_ctlerrs++;
3238 
3239 	return rxlen ? (int)rxlen : -ETIMEDOUT;
3240 }
3241 
3242 #ifdef DEBUG
3243 static bool
3244 brcmf_sdio_verifymemory(struct brcmf_sdio_dev *sdiodev, u32 ram_addr,
3245 			u8 *ram_data, uint ram_sz)
3246 {
3247 	char *ram_cmp;
3248 	int err;
3249 	bool ret = true;
3250 	int address;
3251 	int offset;
3252 	int len;
3253 
3254 	/* read back and verify */
3255 	brcmf_dbg(INFO, "Compare RAM dl & ul at 0x%08x; size=%d\n", ram_addr,
3256 		  ram_sz);
3257 	ram_cmp = kmalloc(MEMBLOCK, GFP_KERNEL);
3258 	/* do not proceed while no memory but  */
3259 	if (!ram_cmp)
3260 		return true;
3261 
3262 	address = ram_addr;
3263 	offset = 0;
3264 	while (offset < ram_sz) {
3265 		len = ((offset + MEMBLOCK) < ram_sz) ? MEMBLOCK :
3266 		      ram_sz - offset;
3267 		err = brcmf_sdiod_ramrw(sdiodev, false, address, ram_cmp, len);
3268 		if (err) {
3269 			brcmf_err("error %d on reading %d membytes at 0x%08x\n",
3270 				  err, len, address);
3271 			ret = false;
3272 			break;
3273 		} else if (memcmp(ram_cmp, &ram_data[offset], len)) {
3274 			brcmf_err("Downloaded RAM image is corrupted, block offset is %d, len is %d\n",
3275 				  offset, len);
3276 			ret = false;
3277 			break;
3278 		}
3279 		offset += len;
3280 		address += len;
3281 	}
3282 
3283 	kfree(ram_cmp);
3284 
3285 	return ret;
3286 }
3287 #else	/* DEBUG */
3288 static bool
3289 brcmf_sdio_verifymemory(struct brcmf_sdio_dev *sdiodev, u32 ram_addr,
3290 			u8 *ram_data, uint ram_sz)
3291 {
3292 	return true;
3293 }
3294 #endif	/* DEBUG */
3295 
3296 static int brcmf_sdio_download_code_file(struct brcmf_sdio *bus,
3297 					 const struct firmware *fw)
3298 {
3299 	int err;
3300 
3301 	brcmf_dbg(TRACE, "Enter\n");
3302 
3303 	err = brcmf_sdiod_ramrw(bus->sdiodev, true, bus->ci->rambase,
3304 				(u8 *)fw->data, fw->size);
3305 	if (err)
3306 		brcmf_err("error %d on writing %d membytes at 0x%08x\n",
3307 			  err, (int)fw->size, bus->ci->rambase);
3308 	else if (!brcmf_sdio_verifymemory(bus->sdiodev, bus->ci->rambase,
3309 					  (u8 *)fw->data, fw->size))
3310 		err = -EIO;
3311 
3312 	return err;
3313 }
3314 
3315 static int brcmf_sdio_download_nvram(struct brcmf_sdio *bus,
3316 				     void *vars, u32 varsz)
3317 {
3318 	int address;
3319 	int err;
3320 
3321 	brcmf_dbg(TRACE, "Enter\n");
3322 
3323 	address = bus->ci->ramsize - varsz + bus->ci->rambase;
3324 	err = brcmf_sdiod_ramrw(bus->sdiodev, true, address, vars, varsz);
3325 	if (err)
3326 		brcmf_err("error %d on writing %d nvram bytes at 0x%08x\n",
3327 			  err, varsz, address);
3328 	else if (!brcmf_sdio_verifymemory(bus->sdiodev, address, vars, varsz))
3329 		err = -EIO;
3330 
3331 	return err;
3332 }
3333 
3334 static int brcmf_sdio_download_firmware(struct brcmf_sdio *bus,
3335 					const struct firmware *fw,
3336 					void *nvram, u32 nvlen)
3337 {
3338 	int bcmerror;
3339 	u32 rstvec;
3340 
3341 	sdio_claim_host(bus->sdiodev->func1);
3342 	brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
3343 
3344 	rstvec = get_unaligned_le32(fw->data);
3345 	brcmf_dbg(SDIO, "firmware rstvec: %x\n", rstvec);
3346 
3347 	bcmerror = brcmf_sdio_download_code_file(bus, fw);
3348 	release_firmware(fw);
3349 	if (bcmerror) {
3350 		brcmf_err("dongle image file download failed\n");
3351 		brcmf_fw_nvram_free(nvram);
3352 		goto err;
3353 	}
3354 
3355 	bcmerror = brcmf_sdio_download_nvram(bus, nvram, nvlen);
3356 	brcmf_fw_nvram_free(nvram);
3357 	if (bcmerror) {
3358 		brcmf_err("dongle nvram file download failed\n");
3359 		goto err;
3360 	}
3361 
3362 	/* Take arm out of reset */
3363 	if (!brcmf_chip_set_active(bus->ci, rstvec)) {
3364 		brcmf_err("error getting out of ARM core reset\n");
3365 		goto err;
3366 	}
3367 
3368 err:
3369 	brcmf_sdio_clkctl(bus, CLK_SDONLY, false);
3370 	sdio_release_host(bus->sdiodev->func1);
3371 	return bcmerror;
3372 }
3373 
3374 static bool brcmf_sdio_aos_no_decode(struct brcmf_sdio *bus)
3375 {
3376 	if (bus->ci->chip == CY_CC_43012_CHIP_ID ||
3377 	    bus->ci->chip == CY_CC_4373_CHIP_ID ||
3378 	    bus->ci->chip == BRCM_CC_4339_CHIP_ID ||
3379 	    bus->ci->chip == BRCM_CC_4345_CHIP_ID ||
3380 	    bus->ci->chip == BRCM_CC_4354_CHIP_ID)
3381 		return true;
3382 	else
3383 		return false;
3384 }
3385 
3386 static void brcmf_sdio_sr_init(struct brcmf_sdio *bus)
3387 {
3388 	int err = 0;
3389 	u8 val;
3390 	u8 wakeupctrl;
3391 	u8 cardcap;
3392 	u8 chipclkcsr;
3393 
3394 	brcmf_dbg(TRACE, "Enter\n");
3395 
3396 	if (brcmf_chip_is_ulp(bus->ci)) {
3397 		wakeupctrl = SBSDIO_FUNC1_WCTRL_ALPWAIT_SHIFT;
3398 		chipclkcsr = SBSDIO_HT_AVAIL_REQ;
3399 	} else {
3400 		wakeupctrl = SBSDIO_FUNC1_WCTRL_HTWAIT_SHIFT;
3401 		chipclkcsr = SBSDIO_FORCE_HT;
3402 	}
3403 
3404 	if (brcmf_sdio_aos_no_decode(bus)) {
3405 		cardcap = SDIO_CCCR_BRCM_CARDCAP_CMD_NODEC;
3406 	} else {
3407 		cardcap = (SDIO_CCCR_BRCM_CARDCAP_CMD14_SUPPORT |
3408 			   SDIO_CCCR_BRCM_CARDCAP_CMD14_EXT);
3409 	}
3410 
3411 	val = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_WAKEUPCTRL, &err);
3412 	if (err) {
3413 		brcmf_err("error reading SBSDIO_FUNC1_WAKEUPCTRL\n");
3414 		return;
3415 	}
3416 	val |= 1 << wakeupctrl;
3417 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_WAKEUPCTRL, val, &err);
3418 	if (err) {
3419 		brcmf_err("error writing SBSDIO_FUNC1_WAKEUPCTRL\n");
3420 		return;
3421 	}
3422 
3423 	/* Add CMD14 Support */
3424 	brcmf_sdiod_func0_wb(bus->sdiodev, SDIO_CCCR_BRCM_CARDCAP,
3425 			     cardcap,
3426 			     &err);
3427 	if (err) {
3428 		brcmf_err("error writing SDIO_CCCR_BRCM_CARDCAP\n");
3429 		return;
3430 	}
3431 
3432 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3433 			   chipclkcsr, &err);
3434 	if (err) {
3435 		brcmf_err("error writing SBSDIO_FUNC1_CHIPCLKCSR\n");
3436 		return;
3437 	}
3438 
3439 	/* set flag */
3440 	bus->sr_enabled = true;
3441 	brcmf_dbg(INFO, "SR enabled\n");
3442 }
3443 
3444 /* enable KSO bit */
3445 static int brcmf_sdio_kso_init(struct brcmf_sdio *bus)
3446 {
3447 	struct brcmf_core *core = bus->sdio_core;
3448 	u8 val;
3449 	int err = 0;
3450 
3451 	brcmf_dbg(TRACE, "Enter\n");
3452 
3453 	/* KSO bit added in SDIO core rev 12 */
3454 	if (core->rev < 12)
3455 		return 0;
3456 
3457 	val = brcmf_sdiod_readb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR, &err);
3458 	if (err) {
3459 		brcmf_err("error reading SBSDIO_FUNC1_SLEEPCSR\n");
3460 		return err;
3461 	}
3462 
3463 	if (!(val & SBSDIO_FUNC1_SLEEPCSR_KSO_MASK)) {
3464 		val |= (SBSDIO_FUNC1_SLEEPCSR_KSO_EN <<
3465 			SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT);
3466 		brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_SLEEPCSR,
3467 				   val, &err);
3468 		if (err) {
3469 			brcmf_err("error writing SBSDIO_FUNC1_SLEEPCSR\n");
3470 			return err;
3471 		}
3472 	}
3473 
3474 	return 0;
3475 }
3476 
3477 
3478 static int brcmf_sdio_bus_preinit(struct device *dev)
3479 {
3480 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3481 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3482 	struct brcmf_sdio *bus = sdiodev->bus;
3483 	struct brcmf_core *core = bus->sdio_core;
3484 	u32 value;
3485 	int err;
3486 
3487 	/* maxctl provided by common layer */
3488 	if (WARN_ON(!bus_if->maxctl))
3489 		return -EINVAL;
3490 
3491 	/* Allocate control receive buffer */
3492 	bus_if->maxctl += bus->roundup;
3493 	value = roundup((bus_if->maxctl + SDPCM_HDRLEN), ALIGNMENT);
3494 	value += bus->head_align;
3495 	bus->rxbuf = kmalloc(value, GFP_ATOMIC);
3496 	if (bus->rxbuf)
3497 		bus->rxblen = value;
3498 
3499 	/* the commands below use the terms tx and rx from
3500 	 * a device perspective, ie. bus:txglom affects the
3501 	 * bus transfers from device to host.
3502 	 */
3503 	if (core->rev < 12) {
3504 		/* for sdio core rev < 12, disable txgloming */
3505 		value = 0;
3506 		err = brcmf_iovar_data_set(dev, "bus:txglom", &value,
3507 					   sizeof(u32));
3508 	} else {
3509 		/* otherwise, set txglomalign */
3510 		value = sdiodev->settings->bus.sdio.sd_sgentry_align;
3511 		/* SDIO ADMA requires at least 32 bit alignment */
3512 		value = max_t(u32, value, ALIGNMENT);
3513 		err = brcmf_iovar_data_set(dev, "bus:txglomalign", &value,
3514 					   sizeof(u32));
3515 	}
3516 
3517 	if (err < 0)
3518 		goto done;
3519 
3520 	bus->tx_hdrlen = SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN;
3521 	if (sdiodev->sg_support) {
3522 		bus->txglom = false;
3523 		value = 1;
3524 		err = brcmf_iovar_data_set(bus->sdiodev->dev, "bus:rxglom",
3525 					   &value, sizeof(u32));
3526 		if (err < 0) {
3527 			/* bus:rxglom is allowed to fail */
3528 			err = 0;
3529 		} else {
3530 			bus->txglom = true;
3531 			bus->tx_hdrlen += SDPCM_HWEXT_LEN;
3532 		}
3533 	}
3534 	brcmf_bus_add_txhdrlen(bus->sdiodev->dev, bus->tx_hdrlen);
3535 
3536 done:
3537 	return err;
3538 }
3539 
3540 static size_t brcmf_sdio_bus_get_ramsize(struct device *dev)
3541 {
3542 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3543 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3544 	struct brcmf_sdio *bus = sdiodev->bus;
3545 
3546 	return bus->ci->ramsize - bus->ci->srsize;
3547 }
3548 
3549 static int brcmf_sdio_bus_get_memdump(struct device *dev, void *data,
3550 				      size_t mem_size)
3551 {
3552 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
3553 	struct brcmf_sdio_dev *sdiodev = bus_if->bus_priv.sdio;
3554 	struct brcmf_sdio *bus = sdiodev->bus;
3555 	int err;
3556 	int address;
3557 	int offset;
3558 	int len;
3559 
3560 	brcmf_dbg(INFO, "dump at 0x%08x: size=%zu\n", bus->ci->rambase,
3561 		  mem_size);
3562 
3563 	address = bus->ci->rambase;
3564 	offset = err = 0;
3565 	sdio_claim_host(sdiodev->func1);
3566 	while (offset < mem_size) {
3567 		len = ((offset + MEMBLOCK) < mem_size) ? MEMBLOCK :
3568 		      mem_size - offset;
3569 		err = brcmf_sdiod_ramrw(sdiodev, false, address, data, len);
3570 		if (err) {
3571 			brcmf_err("error %d on reading %d membytes at 0x%08x\n",
3572 				  err, len, address);
3573 			goto done;
3574 		}
3575 		data += len;
3576 		offset += len;
3577 		address += len;
3578 	}
3579 
3580 done:
3581 	sdio_release_host(sdiodev->func1);
3582 	return err;
3583 }
3584 
3585 void brcmf_sdio_trigger_dpc(struct brcmf_sdio *bus)
3586 {
3587 	if (!bus->dpc_triggered) {
3588 		bus->dpc_triggered = true;
3589 		queue_work(bus->brcmf_wq, &bus->datawork);
3590 	}
3591 }
3592 
3593 void brcmf_sdio_isr(struct brcmf_sdio *bus)
3594 {
3595 	brcmf_dbg(TRACE, "Enter\n");
3596 
3597 	if (!bus) {
3598 		brcmf_err("bus is null pointer, exiting\n");
3599 		return;
3600 	}
3601 
3602 	/* Count the interrupt call */
3603 	bus->sdcnt.intrcount++;
3604 	if (in_interrupt())
3605 		atomic_set(&bus->ipend, 1);
3606 	else
3607 		if (brcmf_sdio_intr_rstatus(bus)) {
3608 			brcmf_err("failed backplane access\n");
3609 		}
3610 
3611 	/* Disable additional interrupts (is this needed now)? */
3612 	if (!bus->intr)
3613 		brcmf_err("isr w/o interrupt configured!\n");
3614 
3615 	bus->dpc_triggered = true;
3616 	queue_work(bus->brcmf_wq, &bus->datawork);
3617 }
3618 
3619 static void brcmf_sdio_bus_watchdog(struct brcmf_sdio *bus)
3620 {
3621 	brcmf_dbg(TIMER, "Enter\n");
3622 
3623 	/* Poll period: check device if appropriate. */
3624 	if (!bus->sr_enabled &&
3625 	    bus->poll && (++bus->polltick >= bus->pollrate)) {
3626 		u32 intstatus = 0;
3627 
3628 		/* Reset poll tick */
3629 		bus->polltick = 0;
3630 
3631 		/* Check device if no interrupts */
3632 		if (!bus->intr ||
3633 		    (bus->sdcnt.intrcount == bus->sdcnt.lastintrs)) {
3634 
3635 			if (!bus->dpc_triggered) {
3636 				u8 devpend;
3637 
3638 				sdio_claim_host(bus->sdiodev->func1);
3639 				devpend = brcmf_sdiod_func0_rb(bus->sdiodev,
3640 						  SDIO_CCCR_INTx, NULL);
3641 				sdio_release_host(bus->sdiodev->func1);
3642 				intstatus = devpend & (INTR_STATUS_FUNC1 |
3643 						       INTR_STATUS_FUNC2);
3644 			}
3645 
3646 			/* If there is something, make like the ISR and
3647 				 schedule the DPC */
3648 			if (intstatus) {
3649 				bus->sdcnt.pollcnt++;
3650 				atomic_set(&bus->ipend, 1);
3651 
3652 				bus->dpc_triggered = true;
3653 				queue_work(bus->brcmf_wq, &bus->datawork);
3654 			}
3655 		}
3656 
3657 		/* Update interrupt tracking */
3658 		bus->sdcnt.lastintrs = bus->sdcnt.intrcount;
3659 	}
3660 #ifdef DEBUG
3661 	/* Poll for console output periodically */
3662 	if (bus->sdiodev->state == BRCMF_SDIOD_DATA && BRCMF_FWCON_ON() &&
3663 	    bus->console_interval != 0) {
3664 		bus->console.count += jiffies_to_msecs(BRCMF_WD_POLL);
3665 		if (bus->console.count >= bus->console_interval) {
3666 			bus->console.count -= bus->console_interval;
3667 			sdio_claim_host(bus->sdiodev->func1);
3668 			/* Make sure backplane clock is on */
3669 			brcmf_sdio_bus_sleep(bus, false, false);
3670 			if (brcmf_sdio_readconsole(bus) < 0)
3671 				/* stop on error */
3672 				bus->console_interval = 0;
3673 			sdio_release_host(bus->sdiodev->func1);
3674 		}
3675 	}
3676 #endif				/* DEBUG */
3677 
3678 	/* On idle timeout clear activity flag and/or turn off clock */
3679 	if (!bus->dpc_triggered) {
3680 		rmb();
3681 		if ((!bus->dpc_running) && (bus->idletime > 0) &&
3682 		    (bus->clkstate == CLK_AVAIL)) {
3683 			bus->idlecount++;
3684 			if (bus->idlecount > bus->idletime) {
3685 				brcmf_dbg(SDIO, "idle\n");
3686 				sdio_claim_host(bus->sdiodev->func1);
3687 				brcmf_sdio_wd_timer(bus, false);
3688 				bus->idlecount = 0;
3689 				brcmf_sdio_bus_sleep(bus, true, false);
3690 				sdio_release_host(bus->sdiodev->func1);
3691 			}
3692 		} else {
3693 			bus->idlecount = 0;
3694 		}
3695 	} else {
3696 		bus->idlecount = 0;
3697 	}
3698 }
3699 
3700 static void brcmf_sdio_dataworker(struct work_struct *work)
3701 {
3702 	struct brcmf_sdio *bus = container_of(work, struct brcmf_sdio,
3703 					      datawork);
3704 
3705 	bus->dpc_running = true;
3706 	wmb();
3707 	while (READ_ONCE(bus->dpc_triggered)) {
3708 		bus->dpc_triggered = false;
3709 		brcmf_sdio_dpc(bus);
3710 		bus->idlecount = 0;
3711 	}
3712 	bus->dpc_running = false;
3713 	if (brcmf_sdiod_freezing(bus->sdiodev)) {
3714 		brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DOWN);
3715 		brcmf_sdiod_try_freeze(bus->sdiodev);
3716 		brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DATA);
3717 	}
3718 }
3719 
3720 static void
3721 brcmf_sdio_drivestrengthinit(struct brcmf_sdio_dev *sdiodev,
3722 			     struct brcmf_chip *ci, u32 drivestrength)
3723 {
3724 	const struct sdiod_drive_str *str_tab = NULL;
3725 	u32 str_mask;
3726 	u32 str_shift;
3727 	u32 i;
3728 	u32 drivestrength_sel = 0;
3729 	u32 cc_data_temp;
3730 	u32 addr;
3731 
3732 	if (!(ci->cc_caps & CC_CAP_PMU))
3733 		return;
3734 
3735 	switch (SDIOD_DRVSTR_KEY(ci->chip, ci->pmurev)) {
3736 	case SDIOD_DRVSTR_KEY(BRCM_CC_4330_CHIP_ID, 12):
3737 		str_tab = sdiod_drvstr_tab1_1v8;
3738 		str_mask = 0x00003800;
3739 		str_shift = 11;
3740 		break;
3741 	case SDIOD_DRVSTR_KEY(BRCM_CC_4334_CHIP_ID, 17):
3742 		str_tab = sdiod_drvstr_tab6_1v8;
3743 		str_mask = 0x00001800;
3744 		str_shift = 11;
3745 		break;
3746 	case SDIOD_DRVSTR_KEY(BRCM_CC_43143_CHIP_ID, 17):
3747 		/* note: 43143 does not support tristate */
3748 		i = ARRAY_SIZE(sdiod_drvstr_tab2_3v3) - 1;
3749 		if (drivestrength >= sdiod_drvstr_tab2_3v3[i].strength) {
3750 			str_tab = sdiod_drvstr_tab2_3v3;
3751 			str_mask = 0x00000007;
3752 			str_shift = 0;
3753 		} else
3754 			brcmf_err("Invalid SDIO Drive strength for chip %s, strength=%d\n",
3755 				  ci->name, drivestrength);
3756 		break;
3757 	case SDIOD_DRVSTR_KEY(BRCM_CC_43362_CHIP_ID, 13):
3758 		str_tab = sdiod_drive_strength_tab5_1v8;
3759 		str_mask = 0x00003800;
3760 		str_shift = 11;
3761 		break;
3762 	default:
3763 		brcmf_dbg(INFO, "No SDIO driver strength init needed for chip %s rev %d pmurev %d\n",
3764 			  ci->name, ci->chiprev, ci->pmurev);
3765 		break;
3766 	}
3767 
3768 	if (str_tab != NULL) {
3769 		struct brcmf_core *pmu = brcmf_chip_get_pmu(ci);
3770 
3771 		for (i = 0; str_tab[i].strength != 0; i++) {
3772 			if (drivestrength >= str_tab[i].strength) {
3773 				drivestrength_sel = str_tab[i].sel;
3774 				break;
3775 			}
3776 		}
3777 		addr = CORE_CC_REG(pmu->base, chipcontrol_addr);
3778 		brcmf_sdiod_writel(sdiodev, addr, 1, NULL);
3779 		cc_data_temp = brcmf_sdiod_readl(sdiodev, addr, NULL);
3780 		cc_data_temp &= ~str_mask;
3781 		drivestrength_sel <<= str_shift;
3782 		cc_data_temp |= drivestrength_sel;
3783 		brcmf_sdiod_writel(sdiodev, addr, cc_data_temp, NULL);
3784 
3785 		brcmf_dbg(INFO, "SDIO: %d mA (req=%d mA) drive strength selected, set to 0x%08x\n",
3786 			  str_tab[i].strength, drivestrength, cc_data_temp);
3787 	}
3788 }
3789 
3790 static int brcmf_sdio_buscoreprep(void *ctx)
3791 {
3792 	struct brcmf_sdio_dev *sdiodev = ctx;
3793 	int err = 0;
3794 	u8 clkval, clkset;
3795 
3796 	/* Try forcing SDIO core to do ALPAvail request only */
3797 	clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
3798 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
3799 	if (err) {
3800 		brcmf_err("error writing for HT off\n");
3801 		return err;
3802 	}
3803 
3804 	/* If register supported, wait for ALPAvail and then force ALP */
3805 	/* This may take up to 15 milliseconds */
3806 	clkval = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, NULL);
3807 
3808 	if ((clkval & ~SBSDIO_AVBITS) != clkset) {
3809 		brcmf_err("ChipClkCSR access: wrote 0x%02x read 0x%02x\n",
3810 			  clkset, clkval);
3811 		return -EACCES;
3812 	}
3813 
3814 	SPINWAIT(((clkval = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3815 					      NULL)),
3816 		 !SBSDIO_ALPAV(clkval)),
3817 		 PMU_MAX_TRANSITION_DLY);
3818 
3819 	if (!SBSDIO_ALPAV(clkval)) {
3820 		brcmf_err("timeout on ALPAV wait, clkval 0x%02x\n",
3821 			  clkval);
3822 		return -EBUSY;
3823 	}
3824 
3825 	clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP;
3826 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
3827 	udelay(65);
3828 
3829 	/* Also, disable the extra SDIO pull-ups */
3830 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_SDIOPULLUP, 0, NULL);
3831 
3832 	return 0;
3833 }
3834 
3835 static void brcmf_sdio_buscore_activate(void *ctx, struct brcmf_chip *chip,
3836 					u32 rstvec)
3837 {
3838 	struct brcmf_sdio_dev *sdiodev = ctx;
3839 	struct brcmf_core *core = sdiodev->bus->sdio_core;
3840 	u32 reg_addr;
3841 
3842 	/* clear all interrupts */
3843 	reg_addr = core->base + SD_REG(intstatus);
3844 	brcmf_sdiod_writel(sdiodev, reg_addr, 0xFFFFFFFF, NULL);
3845 
3846 	if (rstvec)
3847 		/* Write reset vector to address 0 */
3848 		brcmf_sdiod_ramrw(sdiodev, true, 0, (void *)&rstvec,
3849 				  sizeof(rstvec));
3850 }
3851 
3852 static u32 brcmf_sdio_buscore_read32(void *ctx, u32 addr)
3853 {
3854 	struct brcmf_sdio_dev *sdiodev = ctx;
3855 	u32 val, rev;
3856 
3857 	val = brcmf_sdiod_readl(sdiodev, addr, NULL);
3858 
3859 	/*
3860 	 * this is a bit of special handling if reading the chipcommon chipid
3861 	 * register. The 4339 is a next-gen of the 4335. It uses the same
3862 	 * SDIO device id as 4335 and the chipid register returns 4335 as well.
3863 	 * It can be identified as 4339 by looking at the chip revision. It
3864 	 * is corrected here so the chip.c module has the right info.
3865 	 */
3866 	if (addr == CORE_CC_REG(SI_ENUM_BASE, chipid) &&
3867 	    (sdiodev->func1->device == SDIO_DEVICE_ID_BROADCOM_4339 ||
3868 	     sdiodev->func1->device == SDIO_DEVICE_ID_BROADCOM_4335_4339)) {
3869 		rev = (val & CID_REV_MASK) >> CID_REV_SHIFT;
3870 		if (rev >= 2) {
3871 			val &= ~CID_ID_MASK;
3872 			val |= BRCM_CC_4339_CHIP_ID;
3873 		}
3874 	}
3875 
3876 	return val;
3877 }
3878 
3879 static void brcmf_sdio_buscore_write32(void *ctx, u32 addr, u32 val)
3880 {
3881 	struct brcmf_sdio_dev *sdiodev = ctx;
3882 
3883 	brcmf_sdiod_writel(sdiodev, addr, val, NULL);
3884 }
3885 
3886 static const struct brcmf_buscore_ops brcmf_sdio_buscore_ops = {
3887 	.prepare = brcmf_sdio_buscoreprep,
3888 	.activate = brcmf_sdio_buscore_activate,
3889 	.read32 = brcmf_sdio_buscore_read32,
3890 	.write32 = brcmf_sdio_buscore_write32,
3891 };
3892 
3893 static bool
3894 brcmf_sdio_probe_attach(struct brcmf_sdio *bus)
3895 {
3896 	struct brcmf_sdio_dev *sdiodev;
3897 	u8 clkctl = 0;
3898 	int err = 0;
3899 	int reg_addr;
3900 	u32 reg_val;
3901 	u32 drivestrength;
3902 
3903 	sdiodev = bus->sdiodev;
3904 	sdio_claim_host(sdiodev->func1);
3905 
3906 	pr_debug("F1 signature read @0x18000000=0x%4x\n",
3907 		 brcmf_sdiod_readl(sdiodev, SI_ENUM_BASE, NULL));
3908 
3909 	/*
3910 	 * Force PLL off until brcmf_chip_attach()
3911 	 * programs PLL control regs
3912 	 */
3913 
3914 	brcmf_sdiod_writeb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, BRCMF_INIT_CLKCTL1,
3915 			   &err);
3916 	if (!err)
3917 		clkctl = brcmf_sdiod_readb(sdiodev, SBSDIO_FUNC1_CHIPCLKCSR,
3918 					   &err);
3919 
3920 	if (err || ((clkctl & ~SBSDIO_AVBITS) != BRCMF_INIT_CLKCTL1)) {
3921 		brcmf_err("ChipClkCSR access: err %d wrote 0x%02x read 0x%02x\n",
3922 			  err, BRCMF_INIT_CLKCTL1, clkctl);
3923 		goto fail;
3924 	}
3925 
3926 	bus->ci = brcmf_chip_attach(sdiodev, &brcmf_sdio_buscore_ops);
3927 	if (IS_ERR(bus->ci)) {
3928 		brcmf_err("brcmf_chip_attach failed!\n");
3929 		bus->ci = NULL;
3930 		goto fail;
3931 	}
3932 
3933 	/* Pick up the SDIO core info struct from chip.c */
3934 	bus->sdio_core   = brcmf_chip_get_core(bus->ci, BCMA_CORE_SDIO_DEV);
3935 	if (!bus->sdio_core)
3936 		goto fail;
3937 
3938 	/* Pick up the CHIPCOMMON core info struct, for bulk IO in bcmsdh.c */
3939 	sdiodev->cc_core = brcmf_chip_get_core(bus->ci, BCMA_CORE_CHIPCOMMON);
3940 	if (!sdiodev->cc_core)
3941 		goto fail;
3942 
3943 	sdiodev->settings = brcmf_get_module_param(sdiodev->dev,
3944 						   BRCMF_BUSTYPE_SDIO,
3945 						   bus->ci->chip,
3946 						   bus->ci->chiprev);
3947 	if (!sdiodev->settings) {
3948 		brcmf_err("Failed to get device parameters\n");
3949 		goto fail;
3950 	}
3951 	/* platform specific configuration:
3952 	 *   alignments must be at least 4 bytes for ADMA
3953 	 */
3954 	bus->head_align = ALIGNMENT;
3955 	bus->sgentry_align = ALIGNMENT;
3956 	if (sdiodev->settings->bus.sdio.sd_head_align > ALIGNMENT)
3957 		bus->head_align = sdiodev->settings->bus.sdio.sd_head_align;
3958 	if (sdiodev->settings->bus.sdio.sd_sgentry_align > ALIGNMENT)
3959 		bus->sgentry_align =
3960 				sdiodev->settings->bus.sdio.sd_sgentry_align;
3961 
3962 	/* allocate scatter-gather table. sg support
3963 	 * will be disabled upon allocation failure.
3964 	 */
3965 	brcmf_sdiod_sgtable_alloc(sdiodev);
3966 
3967 #ifdef CONFIG_PM_SLEEP
3968 	/* wowl can be supported when KEEP_POWER is true and (WAKE_SDIO_IRQ
3969 	 * is true or when platform data OOB irq is true).
3970 	 */
3971 	if ((sdio_get_host_pm_caps(sdiodev->func1) & MMC_PM_KEEP_POWER) &&
3972 	    ((sdio_get_host_pm_caps(sdiodev->func1) & MMC_PM_WAKE_SDIO_IRQ) ||
3973 	     (sdiodev->settings->bus.sdio.oob_irq_supported)))
3974 		sdiodev->bus_if->wowl_supported = true;
3975 #endif
3976 
3977 	if (brcmf_sdio_kso_init(bus)) {
3978 		brcmf_err("error enabling KSO\n");
3979 		goto fail;
3980 	}
3981 
3982 	if (sdiodev->settings->bus.sdio.drive_strength)
3983 		drivestrength = sdiodev->settings->bus.sdio.drive_strength;
3984 	else
3985 		drivestrength = DEFAULT_SDIO_DRIVE_STRENGTH;
3986 	brcmf_sdio_drivestrengthinit(sdiodev, bus->ci, drivestrength);
3987 
3988 	/* Set card control so an SDIO card reset does a WLAN backplane reset */
3989 	reg_val = brcmf_sdiod_func0_rb(sdiodev, SDIO_CCCR_BRCM_CARDCTRL, &err);
3990 	if (err)
3991 		goto fail;
3992 
3993 	reg_val |= SDIO_CCCR_BRCM_CARDCTRL_WLANRESET;
3994 
3995 	brcmf_sdiod_func0_wb(sdiodev, SDIO_CCCR_BRCM_CARDCTRL, reg_val, &err);
3996 	if (err)
3997 		goto fail;
3998 
3999 	/* set PMUControl so a backplane reset does PMU state reload */
4000 	reg_addr = CORE_CC_REG(brcmf_chip_get_pmu(bus->ci)->base, pmucontrol);
4001 	reg_val = brcmf_sdiod_readl(sdiodev, reg_addr, &err);
4002 	if (err)
4003 		goto fail;
4004 
4005 	reg_val |= (BCMA_CC_PMU_CTL_RES_RELOAD << BCMA_CC_PMU_CTL_RES_SHIFT);
4006 
4007 	brcmf_sdiod_writel(sdiodev, reg_addr, reg_val, &err);
4008 	if (err)
4009 		goto fail;
4010 
4011 	sdio_release_host(sdiodev->func1);
4012 
4013 	brcmu_pktq_init(&bus->txq, (PRIOMASK + 1), TXQLEN);
4014 
4015 	/* allocate header buffer */
4016 	bus->hdrbuf = kzalloc(MAX_HDR_READ + bus->head_align, GFP_KERNEL);
4017 	if (!bus->hdrbuf)
4018 		return false;
4019 	/* Locate an appropriately-aligned portion of hdrbuf */
4020 	bus->rxhdr = (u8 *) roundup((unsigned long)&bus->hdrbuf[0],
4021 				    bus->head_align);
4022 
4023 	/* Set the poll and/or interrupt flags */
4024 	bus->intr = true;
4025 	bus->poll = false;
4026 	if (bus->poll)
4027 		bus->pollrate = 1;
4028 
4029 	return true;
4030 
4031 fail:
4032 	sdio_release_host(sdiodev->func1);
4033 	return false;
4034 }
4035 
4036 static int
4037 brcmf_sdio_watchdog_thread(void *data)
4038 {
4039 	struct brcmf_sdio *bus = (struct brcmf_sdio *)data;
4040 	int wait;
4041 
4042 	allow_signal(SIGTERM);
4043 	/* Run until signal received */
4044 	brcmf_sdiod_freezer_count(bus->sdiodev);
4045 	while (1) {
4046 		if (kthread_should_stop())
4047 			break;
4048 		brcmf_sdiod_freezer_uncount(bus->sdiodev);
4049 		wait = wait_for_completion_interruptible(&bus->watchdog_wait);
4050 		brcmf_sdiod_freezer_count(bus->sdiodev);
4051 		brcmf_sdiod_try_freeze(bus->sdiodev);
4052 		if (!wait) {
4053 			brcmf_sdio_bus_watchdog(bus);
4054 			/* Count the tick for reference */
4055 			bus->sdcnt.tickcnt++;
4056 			reinit_completion(&bus->watchdog_wait);
4057 		} else
4058 			break;
4059 	}
4060 	return 0;
4061 }
4062 
4063 static void
4064 brcmf_sdio_watchdog(struct timer_list *t)
4065 {
4066 	struct brcmf_sdio *bus = from_timer(bus, t, timer);
4067 
4068 	if (bus->watchdog_tsk) {
4069 		complete(&bus->watchdog_wait);
4070 		/* Reschedule the watchdog */
4071 		if (bus->wd_active)
4072 			mod_timer(&bus->timer,
4073 				  jiffies + BRCMF_WD_POLL);
4074 	}
4075 }
4076 
4077 static
4078 int brcmf_sdio_get_fwname(struct device *dev, const char *ext, u8 *fw_name)
4079 {
4080 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
4081 	struct brcmf_fw_request *fwreq;
4082 	struct brcmf_fw_name fwnames[] = {
4083 		{ ext, fw_name },
4084 	};
4085 
4086 	fwreq = brcmf_fw_alloc_request(bus_if->chip, bus_if->chiprev,
4087 				       brcmf_sdio_fwnames,
4088 				       ARRAY_SIZE(brcmf_sdio_fwnames),
4089 				       fwnames, ARRAY_SIZE(fwnames));
4090 	if (!fwreq)
4091 		return -ENOMEM;
4092 
4093 	kfree(fwreq);
4094 	return 0;
4095 }
4096 
4097 static const struct brcmf_bus_ops brcmf_sdio_bus_ops = {
4098 	.stop = brcmf_sdio_bus_stop,
4099 	.preinit = brcmf_sdio_bus_preinit,
4100 	.txdata = brcmf_sdio_bus_txdata,
4101 	.txctl = brcmf_sdio_bus_txctl,
4102 	.rxctl = brcmf_sdio_bus_rxctl,
4103 	.gettxq = brcmf_sdio_bus_gettxq,
4104 	.wowl_config = brcmf_sdio_wowl_config,
4105 	.get_ramsize = brcmf_sdio_bus_get_ramsize,
4106 	.get_memdump = brcmf_sdio_bus_get_memdump,
4107 	.get_fwname = brcmf_sdio_get_fwname,
4108 	.debugfs_create = brcmf_sdio_debugfs_create
4109 };
4110 
4111 #define BRCMF_SDIO_FW_CODE	0
4112 #define BRCMF_SDIO_FW_NVRAM	1
4113 
4114 static void brcmf_sdio_firmware_callback(struct device *dev, int err,
4115 					 struct brcmf_fw_request *fwreq)
4116 {
4117 	struct brcmf_bus *bus_if = dev_get_drvdata(dev);
4118 	struct brcmf_sdio_dev *sdiod = bus_if->bus_priv.sdio;
4119 	struct brcmf_sdio *bus = sdiod->bus;
4120 	struct brcmf_core *core = bus->sdio_core;
4121 	const struct firmware *code;
4122 	void *nvram;
4123 	u32 nvram_len;
4124 	u8 saveclk, bpreq;
4125 	u8 devctl;
4126 
4127 	brcmf_dbg(TRACE, "Enter: dev=%s, err=%d\n", dev_name(dev), err);
4128 
4129 	if (err)
4130 		goto fail;
4131 
4132 	code = fwreq->items[BRCMF_SDIO_FW_CODE].binary;
4133 	nvram = fwreq->items[BRCMF_SDIO_FW_NVRAM].nv_data.data;
4134 	nvram_len = fwreq->items[BRCMF_SDIO_FW_NVRAM].nv_data.len;
4135 	kfree(fwreq);
4136 
4137 	/* try to download image and nvram to the dongle */
4138 	bus->alp_only = true;
4139 	err = brcmf_sdio_download_firmware(bus, code, nvram, nvram_len);
4140 	if (err)
4141 		goto fail;
4142 	bus->alp_only = false;
4143 
4144 	/* Start the watchdog timer */
4145 	bus->sdcnt.tickcnt = 0;
4146 	brcmf_sdio_wd_timer(bus, true);
4147 
4148 	sdio_claim_host(sdiod->func1);
4149 
4150 	/* Make sure backplane clock is on, needed to generate F2 interrupt */
4151 	brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
4152 	if (bus->clkstate != CLK_AVAIL)
4153 		goto release;
4154 
4155 	/* Force clocks on backplane to be sure F2 interrupt propagates */
4156 	saveclk = brcmf_sdiod_readb(sdiod, SBSDIO_FUNC1_CHIPCLKCSR, &err);
4157 	if (!err) {
4158 		bpreq = saveclk;
4159 		bpreq |= brcmf_chip_is_ulp(bus->ci) ?
4160 			SBSDIO_HT_AVAIL_REQ : SBSDIO_FORCE_HT;
4161 		brcmf_sdiod_writeb(sdiod, SBSDIO_FUNC1_CHIPCLKCSR,
4162 				   bpreq, &err);
4163 	}
4164 	if (err) {
4165 		brcmf_err("Failed to force clock for F2: err %d\n", err);
4166 		goto release;
4167 	}
4168 
4169 	/* Enable function 2 (frame transfers) */
4170 	brcmf_sdiod_writel(sdiod, core->base + SD_REG(tosbmailboxdata),
4171 			   SDPCM_PROT_VERSION << SMB_DATA_VERSION_SHIFT, NULL);
4172 
4173 	err = sdio_enable_func(sdiod->func2);
4174 
4175 	brcmf_dbg(INFO, "enable F2: err=%d\n", err);
4176 
4177 	/* If F2 successfully enabled, set core and enable interrupts */
4178 	if (!err) {
4179 		/* Set up the interrupt mask and enable interrupts */
4180 		bus->hostintmask = HOSTINTMASK;
4181 		brcmf_sdiod_writel(sdiod, core->base + SD_REG(hostintmask),
4182 				   bus->hostintmask, NULL);
4183 
4184 		switch (sdiod->func1->device) {
4185 		case SDIO_DEVICE_ID_CYPRESS_4373:
4186 			brcmf_dbg(INFO, "set F2 watermark to 0x%x*4 bytes\n",
4187 				  CY_4373_F2_WATERMARK);
4188 			brcmf_sdiod_writeb(sdiod, SBSDIO_WATERMARK,
4189 					   CY_4373_F2_WATERMARK, &err);
4190 			devctl = brcmf_sdiod_readb(sdiod, SBSDIO_DEVICE_CTL,
4191 						   &err);
4192 			devctl |= SBSDIO_DEVCTL_F2WM_ENAB;
4193 			brcmf_sdiod_writeb(sdiod, SBSDIO_DEVICE_CTL, devctl,
4194 					   &err);
4195 			brcmf_sdiod_writeb(sdiod, SBSDIO_FUNC1_MESBUSYCTRL,
4196 					   CY_4373_F2_WATERMARK |
4197 					   SBSDIO_MESBUSYCTRL_ENAB, &err);
4198 			break;
4199 		case SDIO_DEVICE_ID_CYPRESS_43012:
4200 			brcmf_dbg(INFO, "set F2 watermark to 0x%x*4 bytes\n",
4201 				  CY_43012_F2_WATERMARK);
4202 			brcmf_sdiod_writeb(sdiod, SBSDIO_WATERMARK,
4203 					   CY_43012_F2_WATERMARK, &err);
4204 			devctl = brcmf_sdiod_readb(sdiod, SBSDIO_DEVICE_CTL,
4205 						   &err);
4206 			devctl |= SBSDIO_DEVCTL_F2WM_ENAB;
4207 			brcmf_sdiod_writeb(sdiod, SBSDIO_DEVICE_CTL, devctl,
4208 					   &err);
4209 			break;
4210 		default:
4211 			brcmf_sdiod_writeb(sdiod, SBSDIO_WATERMARK,
4212 					   DEFAULT_F2_WATERMARK, &err);
4213 			break;
4214 		}
4215 	} else {
4216 		/* Disable F2 again */
4217 		sdio_disable_func(sdiod->func2);
4218 		goto checkdied;
4219 	}
4220 
4221 	if (brcmf_chip_sr_capable(bus->ci)) {
4222 		brcmf_sdio_sr_init(bus);
4223 	} else {
4224 		/* Restore previous clock setting */
4225 		brcmf_sdiod_writeb(sdiod, SBSDIO_FUNC1_CHIPCLKCSR,
4226 				   saveclk, &err);
4227 	}
4228 
4229 	if (err == 0) {
4230 		/* Allow full data communication using DPC from now on. */
4231 		brcmf_sdiod_change_state(bus->sdiodev, BRCMF_SDIOD_DATA);
4232 
4233 		err = brcmf_sdiod_intr_register(sdiod);
4234 		if (err != 0)
4235 			brcmf_err("intr register failed:%d\n", err);
4236 	}
4237 
4238 	/* If we didn't come up, turn off backplane clock */
4239 	if (err != 0) {
4240 		brcmf_sdio_clkctl(bus, CLK_NONE, false);
4241 		goto checkdied;
4242 	}
4243 
4244 	sdio_release_host(sdiod->func1);
4245 
4246 	/* Assign bus interface call back */
4247 	sdiod->bus_if->dev = sdiod->dev;
4248 	sdiod->bus_if->ops = &brcmf_sdio_bus_ops;
4249 	sdiod->bus_if->chip = bus->ci->chip;
4250 	sdiod->bus_if->chiprev = bus->ci->chiprev;
4251 
4252 	/* Attach to the common layer, reserve hdr space */
4253 	err = brcmf_attach(sdiod->dev, sdiod->settings);
4254 	if (err != 0) {
4255 		brcmf_err("brcmf_attach failed\n");
4256 		sdio_claim_host(sdiod->func1);
4257 		goto checkdied;
4258 	}
4259 
4260 	/* ready */
4261 	return;
4262 
4263 checkdied:
4264 	brcmf_sdio_checkdied(bus);
4265 release:
4266 	sdio_release_host(sdiod->func1);
4267 fail:
4268 	brcmf_dbg(TRACE, "failed: dev=%s, err=%d\n", dev_name(dev), err);
4269 	device_release_driver(&sdiod->func2->dev);
4270 	device_release_driver(dev);
4271 }
4272 
4273 static struct brcmf_fw_request *
4274 brcmf_sdio_prepare_fw_request(struct brcmf_sdio *bus)
4275 {
4276 	struct brcmf_fw_request *fwreq;
4277 	struct brcmf_fw_name fwnames[] = {
4278 		{ ".bin", bus->sdiodev->fw_name },
4279 		{ ".txt", bus->sdiodev->nvram_name },
4280 	};
4281 
4282 	fwreq = brcmf_fw_alloc_request(bus->ci->chip, bus->ci->chiprev,
4283 				       brcmf_sdio_fwnames,
4284 				       ARRAY_SIZE(brcmf_sdio_fwnames),
4285 				       fwnames, ARRAY_SIZE(fwnames));
4286 	if (!fwreq)
4287 		return NULL;
4288 
4289 	fwreq->items[BRCMF_SDIO_FW_CODE].type = BRCMF_FW_TYPE_BINARY;
4290 	fwreq->items[BRCMF_SDIO_FW_NVRAM].type = BRCMF_FW_TYPE_NVRAM;
4291 	fwreq->board_type = bus->sdiodev->settings->board_type;
4292 
4293 	return fwreq;
4294 }
4295 
4296 struct brcmf_sdio *brcmf_sdio_probe(struct brcmf_sdio_dev *sdiodev)
4297 {
4298 	int ret;
4299 	struct brcmf_sdio *bus;
4300 	struct workqueue_struct *wq;
4301 	struct brcmf_fw_request *fwreq;
4302 
4303 	brcmf_dbg(TRACE, "Enter\n");
4304 
4305 	/* Allocate private bus interface state */
4306 	bus = kzalloc(sizeof(struct brcmf_sdio), GFP_ATOMIC);
4307 	if (!bus)
4308 		goto fail;
4309 
4310 	bus->sdiodev = sdiodev;
4311 	sdiodev->bus = bus;
4312 	skb_queue_head_init(&bus->glom);
4313 	bus->txbound = BRCMF_TXBOUND;
4314 	bus->rxbound = BRCMF_RXBOUND;
4315 	bus->txminmax = BRCMF_TXMINMAX;
4316 	bus->tx_seq = SDPCM_SEQ_WRAP - 1;
4317 
4318 	/* single-threaded workqueue */
4319 	wq = alloc_ordered_workqueue("brcmf_wq/%s", WQ_MEM_RECLAIM,
4320 				     dev_name(&sdiodev->func1->dev));
4321 	if (!wq) {
4322 		brcmf_err("insufficient memory to create txworkqueue\n");
4323 		goto fail;
4324 	}
4325 	brcmf_sdiod_freezer_count(sdiodev);
4326 	INIT_WORK(&bus->datawork, brcmf_sdio_dataworker);
4327 	bus->brcmf_wq = wq;
4328 
4329 	/* attempt to attach to the dongle */
4330 	if (!(brcmf_sdio_probe_attach(bus))) {
4331 		brcmf_err("brcmf_sdio_probe_attach failed\n");
4332 		goto fail;
4333 	}
4334 
4335 	spin_lock_init(&bus->rxctl_lock);
4336 	spin_lock_init(&bus->txq_lock);
4337 	init_waitqueue_head(&bus->ctrl_wait);
4338 	init_waitqueue_head(&bus->dcmd_resp_wait);
4339 
4340 	/* Set up the watchdog timer */
4341 	timer_setup(&bus->timer, brcmf_sdio_watchdog, 0);
4342 	/* Initialize watchdog thread */
4343 	init_completion(&bus->watchdog_wait);
4344 	bus->watchdog_tsk = kthread_run(brcmf_sdio_watchdog_thread,
4345 					bus, "brcmf_wdog/%s",
4346 					dev_name(&sdiodev->func1->dev));
4347 	if (IS_ERR(bus->watchdog_tsk)) {
4348 		pr_warn("brcmf_watchdog thread failed to start\n");
4349 		bus->watchdog_tsk = NULL;
4350 	}
4351 	/* Initialize DPC thread */
4352 	bus->dpc_triggered = false;
4353 	bus->dpc_running = false;
4354 
4355 	/* default sdio bus header length for tx packet */
4356 	bus->tx_hdrlen = SDPCM_HWHDR_LEN + SDPCM_SWHDR_LEN;
4357 
4358 	/* Query the F2 block size, set roundup accordingly */
4359 	bus->blocksize = bus->sdiodev->func2->cur_blksize;
4360 	bus->roundup = min(max_roundup, bus->blocksize);
4361 
4362 	sdio_claim_host(bus->sdiodev->func1);
4363 
4364 	/* Disable F2 to clear any intermediate frame state on the dongle */
4365 	sdio_disable_func(bus->sdiodev->func2);
4366 
4367 	bus->rxflow = false;
4368 
4369 	/* Done with backplane-dependent accesses, can drop clock... */
4370 	brcmf_sdiod_writeb(bus->sdiodev, SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL);
4371 
4372 	sdio_release_host(bus->sdiodev->func1);
4373 
4374 	/* ...and initialize clock/power states */
4375 	bus->clkstate = CLK_SDONLY;
4376 	bus->idletime = BRCMF_IDLE_INTERVAL;
4377 	bus->idleclock = BRCMF_IDLE_ACTIVE;
4378 
4379 	/* SR state */
4380 	bus->sr_enabled = false;
4381 
4382 	brcmf_dbg(INFO, "completed!!\n");
4383 
4384 	fwreq = brcmf_sdio_prepare_fw_request(bus);
4385 	if (!fwreq) {
4386 		ret = -ENOMEM;
4387 		goto fail;
4388 	}
4389 
4390 	ret = brcmf_fw_get_firmwares(sdiodev->dev, fwreq,
4391 				     brcmf_sdio_firmware_callback);
4392 	if (ret != 0) {
4393 		brcmf_err("async firmware request failed: %d\n", ret);
4394 		kfree(fwreq);
4395 		goto fail;
4396 	}
4397 
4398 	return bus;
4399 
4400 fail:
4401 	brcmf_sdio_remove(bus);
4402 	return NULL;
4403 }
4404 
4405 /* Detach and free everything */
4406 void brcmf_sdio_remove(struct brcmf_sdio *bus)
4407 {
4408 	brcmf_dbg(TRACE, "Enter\n");
4409 
4410 	if (bus) {
4411 		/* Stop watchdog task */
4412 		if (bus->watchdog_tsk) {
4413 			send_sig(SIGTERM, bus->watchdog_tsk, 1);
4414 			kthread_stop(bus->watchdog_tsk);
4415 			bus->watchdog_tsk = NULL;
4416 		}
4417 
4418 		/* De-register interrupt handler */
4419 		brcmf_sdiod_intr_unregister(bus->sdiodev);
4420 
4421 		brcmf_detach(bus->sdiodev->dev);
4422 
4423 		cancel_work_sync(&bus->datawork);
4424 		if (bus->brcmf_wq)
4425 			destroy_workqueue(bus->brcmf_wq);
4426 
4427 		if (bus->ci) {
4428 			if (bus->sdiodev->state != BRCMF_SDIOD_NOMEDIUM) {
4429 				sdio_claim_host(bus->sdiodev->func1);
4430 				brcmf_sdio_wd_timer(bus, false);
4431 				brcmf_sdio_clkctl(bus, CLK_AVAIL, false);
4432 				/* Leave the device in state where it is
4433 				 * 'passive'. This is done by resetting all
4434 				 * necessary cores.
4435 				 */
4436 				msleep(20);
4437 				brcmf_chip_set_passive(bus->ci);
4438 				brcmf_sdio_clkctl(bus, CLK_NONE, false);
4439 				sdio_release_host(bus->sdiodev->func1);
4440 			}
4441 			brcmf_chip_detach(bus->ci);
4442 		}
4443 		if (bus->sdiodev->settings)
4444 			brcmf_release_module_param(bus->sdiodev->settings);
4445 
4446 		kfree(bus->rxbuf);
4447 		kfree(bus->hdrbuf);
4448 		kfree(bus);
4449 	}
4450 
4451 	brcmf_dbg(TRACE, "Disconnected\n");
4452 }
4453 
4454 void brcmf_sdio_wd_timer(struct brcmf_sdio *bus, bool active)
4455 {
4456 	/* Totally stop the timer */
4457 	if (!active && bus->wd_active) {
4458 		del_timer_sync(&bus->timer);
4459 		bus->wd_active = false;
4460 		return;
4461 	}
4462 
4463 	/* don't start the wd until fw is loaded */
4464 	if (bus->sdiodev->state != BRCMF_SDIOD_DATA)
4465 		return;
4466 
4467 	if (active) {
4468 		if (!bus->wd_active) {
4469 			/* Create timer again when watchdog period is
4470 			   dynamically changed or in the first instance
4471 			 */
4472 			bus->timer.expires = jiffies + BRCMF_WD_POLL;
4473 			add_timer(&bus->timer);
4474 			bus->wd_active = true;
4475 		} else {
4476 			/* Re arm the timer, at last watchdog period */
4477 			mod_timer(&bus->timer, jiffies + BRCMF_WD_POLL);
4478 		}
4479 	}
4480 }
4481 
4482 int brcmf_sdio_sleep(struct brcmf_sdio *bus, bool sleep)
4483 {
4484 	int ret;
4485 
4486 	sdio_claim_host(bus->sdiodev->func1);
4487 	ret = brcmf_sdio_bus_sleep(bus, sleep, false);
4488 	sdio_release_host(bus->sdiodev->func1);
4489 
4490 	return ret;
4491 }
4492 
4493