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