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