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