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