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