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