1/*
2 *  linux/drivers/mmc/host/sdhci.c - Secure Digital Host Controller Interface driver
3 *
4 *  Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or (at
9 * your option) any later version.
10 *
11 * Thanks to the following companies for their support:
12 *
13 *     - JMicron (hardware and technical support)
14 */
15
16#include <linux/delay.h>
17#include <linux/highmem.h>
18#include <linux/io.h>
19#include <linux/module.h>
20#include <linux/dma-mapping.h>
21#include <linux/slab.h>
22#include <linux/scatterlist.h>
23#include <linux/regulator/consumer.h>
24#include <linux/pm_runtime.h>
25
26#include <linux/leds.h>
27
28#include <linux/mmc/mmc.h>
29#include <linux/mmc/host.h>
30#include <linux/mmc/card.h>
31#include <linux/mmc/sdio.h>
32#include <linux/mmc/slot-gpio.h>
33
34#include "sdhci.h"
35
36#define DRIVER_NAME "sdhci"
37
38#define DBG(f, x...) \
39	pr_debug(DRIVER_NAME " [%s()]: " f, __func__,## x)
40
41#if defined(CONFIG_LEDS_CLASS) || (defined(CONFIG_LEDS_CLASS_MODULE) && \
42	defined(CONFIG_MMC_SDHCI_MODULE))
43#define SDHCI_USE_LEDS_CLASS
44#endif
45
46#define MAX_TUNING_LOOP 40
47
48static unsigned int debug_quirks = 0;
49static unsigned int debug_quirks2;
50
51static void sdhci_finish_data(struct sdhci_host *);
52
53static void sdhci_finish_command(struct sdhci_host *);
54static int sdhci_execute_tuning(struct mmc_host *mmc, u32 opcode);
55static void sdhci_tuning_timer(unsigned long data);
56static void sdhci_enable_preset_value(struct sdhci_host *host, bool enable);
57static int sdhci_pre_dma_transfer(struct sdhci_host *host,
58					struct mmc_data *data);
59static int sdhci_do_get_cd(struct sdhci_host *host);
60
61#ifdef CONFIG_PM
62static int sdhci_runtime_pm_get(struct sdhci_host *host);
63static int sdhci_runtime_pm_put(struct sdhci_host *host);
64static void sdhci_runtime_pm_bus_on(struct sdhci_host *host);
65static void sdhci_runtime_pm_bus_off(struct sdhci_host *host);
66#else
67static inline int sdhci_runtime_pm_get(struct sdhci_host *host)
68{
69	return 0;
70}
71static inline int sdhci_runtime_pm_put(struct sdhci_host *host)
72{
73	return 0;
74}
75static void sdhci_runtime_pm_bus_on(struct sdhci_host *host)
76{
77}
78static void sdhci_runtime_pm_bus_off(struct sdhci_host *host)
79{
80}
81#endif
82
83static void sdhci_dumpregs(struct sdhci_host *host)
84{
85	pr_debug(DRIVER_NAME ": =========== REGISTER DUMP (%s)===========\n",
86		mmc_hostname(host->mmc));
87
88	pr_debug(DRIVER_NAME ": Sys addr: 0x%08x | Version:  0x%08x\n",
89		sdhci_readl(host, SDHCI_DMA_ADDRESS),
90		sdhci_readw(host, SDHCI_HOST_VERSION));
91	pr_debug(DRIVER_NAME ": Blk size: 0x%08x | Blk cnt:  0x%08x\n",
92		sdhci_readw(host, SDHCI_BLOCK_SIZE),
93		sdhci_readw(host, SDHCI_BLOCK_COUNT));
94	pr_debug(DRIVER_NAME ": Argument: 0x%08x | Trn mode: 0x%08x\n",
95		sdhci_readl(host, SDHCI_ARGUMENT),
96		sdhci_readw(host, SDHCI_TRANSFER_MODE));
97	pr_debug(DRIVER_NAME ": Present:  0x%08x | Host ctl: 0x%08x\n",
98		sdhci_readl(host, SDHCI_PRESENT_STATE),
99		sdhci_readb(host, SDHCI_HOST_CONTROL));
100	pr_debug(DRIVER_NAME ": Power:    0x%08x | Blk gap:  0x%08x\n",
101		sdhci_readb(host, SDHCI_POWER_CONTROL),
102		sdhci_readb(host, SDHCI_BLOCK_GAP_CONTROL));
103	pr_debug(DRIVER_NAME ": Wake-up:  0x%08x | Clock:    0x%08x\n",
104		sdhci_readb(host, SDHCI_WAKE_UP_CONTROL),
105		sdhci_readw(host, SDHCI_CLOCK_CONTROL));
106	pr_debug(DRIVER_NAME ": Timeout:  0x%08x | Int stat: 0x%08x\n",
107		sdhci_readb(host, SDHCI_TIMEOUT_CONTROL),
108		sdhci_readl(host, SDHCI_INT_STATUS));
109	pr_debug(DRIVER_NAME ": Int enab: 0x%08x | Sig enab: 0x%08x\n",
110		sdhci_readl(host, SDHCI_INT_ENABLE),
111		sdhci_readl(host, SDHCI_SIGNAL_ENABLE));
112	pr_debug(DRIVER_NAME ": AC12 err: 0x%08x | Slot int: 0x%08x\n",
113		sdhci_readw(host, SDHCI_ACMD12_ERR),
114		sdhci_readw(host, SDHCI_SLOT_INT_STATUS));
115	pr_debug(DRIVER_NAME ": Caps:     0x%08x | Caps_1:   0x%08x\n",
116		sdhci_readl(host, SDHCI_CAPABILITIES),
117		sdhci_readl(host, SDHCI_CAPABILITIES_1));
118	pr_debug(DRIVER_NAME ": Cmd:      0x%08x | Max curr: 0x%08x\n",
119		sdhci_readw(host, SDHCI_COMMAND),
120		sdhci_readl(host, SDHCI_MAX_CURRENT));
121	pr_debug(DRIVER_NAME ": Host ctl2: 0x%08x\n",
122		sdhci_readw(host, SDHCI_HOST_CONTROL2));
123
124	if (host->flags & SDHCI_USE_ADMA) {
125		if (host->flags & SDHCI_USE_64_BIT_DMA)
126			pr_debug(DRIVER_NAME ": ADMA Err: 0x%08x | ADMA Ptr: 0x%08x%08x\n",
127				 readl(host->ioaddr + SDHCI_ADMA_ERROR),
128				 readl(host->ioaddr + SDHCI_ADMA_ADDRESS_HI),
129				 readl(host->ioaddr + SDHCI_ADMA_ADDRESS));
130		else
131			pr_debug(DRIVER_NAME ": ADMA Err: 0x%08x | ADMA Ptr: 0x%08x\n",
132				 readl(host->ioaddr + SDHCI_ADMA_ERROR),
133				 readl(host->ioaddr + SDHCI_ADMA_ADDRESS));
134	}
135
136	pr_debug(DRIVER_NAME ": ===========================================\n");
137}
138
139/*****************************************************************************\
140 *                                                                           *
141 * Low level functions                                                       *
142 *                                                                           *
143\*****************************************************************************/
144
145static void sdhci_set_card_detection(struct sdhci_host *host, bool enable)
146{
147	u32 present;
148
149	if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) ||
150	    (host->mmc->caps & MMC_CAP_NONREMOVABLE))
151		return;
152
153	if (enable) {
154		present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
155				      SDHCI_CARD_PRESENT;
156
157		host->ier |= present ? SDHCI_INT_CARD_REMOVE :
158				       SDHCI_INT_CARD_INSERT;
159	} else {
160		host->ier &= ~(SDHCI_INT_CARD_REMOVE | SDHCI_INT_CARD_INSERT);
161	}
162
163	sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
164	sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
165}
166
167static void sdhci_enable_card_detection(struct sdhci_host *host)
168{
169	sdhci_set_card_detection(host, true);
170}
171
172static void sdhci_disable_card_detection(struct sdhci_host *host)
173{
174	sdhci_set_card_detection(host, false);
175}
176
177void sdhci_reset(struct sdhci_host *host, u8 mask)
178{
179	unsigned long timeout;
180
181	sdhci_writeb(host, mask, SDHCI_SOFTWARE_RESET);
182
183	if (mask & SDHCI_RESET_ALL) {
184		host->clock = 0;
185		/* Reset-all turns off SD Bus Power */
186		if (host->quirks2 & SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON)
187			sdhci_runtime_pm_bus_off(host);
188	}
189
190	/* Wait max 100 ms */
191	timeout = 100;
192
193	/* hw clears the bit when it's done */
194	while (sdhci_readb(host, SDHCI_SOFTWARE_RESET) & mask) {
195		if (timeout == 0) {
196			pr_err("%s: Reset 0x%x never completed.\n",
197				mmc_hostname(host->mmc), (int)mask);
198			sdhci_dumpregs(host);
199			return;
200		}
201		timeout--;
202		mdelay(1);
203	}
204}
205EXPORT_SYMBOL_GPL(sdhci_reset);
206
207static void sdhci_do_reset(struct sdhci_host *host, u8 mask)
208{
209	if (host->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
210		if (!(sdhci_readl(host, SDHCI_PRESENT_STATE) &
211			SDHCI_CARD_PRESENT))
212			return;
213	}
214
215	host->ops->reset(host, mask);
216
217	if (mask & SDHCI_RESET_ALL) {
218		if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
219			if (host->ops->enable_dma)
220				host->ops->enable_dma(host);
221		}
222
223		/* Resetting the controller clears many */
224		host->preset_enabled = false;
225	}
226}
227
228static void sdhci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios);
229
230static void sdhci_init(struct sdhci_host *host, int soft)
231{
232	if (soft)
233		sdhci_do_reset(host, SDHCI_RESET_CMD|SDHCI_RESET_DATA);
234	else
235		sdhci_do_reset(host, SDHCI_RESET_ALL);
236
237	host->ier = SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
238		    SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT |
239		    SDHCI_INT_INDEX | SDHCI_INT_END_BIT | SDHCI_INT_CRC |
240		    SDHCI_INT_TIMEOUT | SDHCI_INT_DATA_END |
241		    SDHCI_INT_RESPONSE;
242
243	sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
244	sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
245
246	if (soft) {
247		/* force clock reconfiguration */
248		host->clock = 0;
249		sdhci_set_ios(host->mmc, &host->mmc->ios);
250	}
251}
252
253static void sdhci_reinit(struct sdhci_host *host)
254{
255	sdhci_init(host, 0);
256	/*
257	 * Retuning stuffs are affected by different cards inserted and only
258	 * applicable to UHS-I cards. So reset these fields to their initial
259	 * value when card is removed.
260	 */
261	if (host->flags & SDHCI_USING_RETUNING_TIMER) {
262		host->flags &= ~SDHCI_USING_RETUNING_TIMER;
263
264		del_timer_sync(&host->tuning_timer);
265		host->flags &= ~SDHCI_NEEDS_RETUNING;
266	}
267	sdhci_enable_card_detection(host);
268}
269
270static void sdhci_activate_led(struct sdhci_host *host)
271{
272	u8 ctrl;
273
274	ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
275	ctrl |= SDHCI_CTRL_LED;
276	sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
277}
278
279static void sdhci_deactivate_led(struct sdhci_host *host)
280{
281	u8 ctrl;
282
283	ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
284	ctrl &= ~SDHCI_CTRL_LED;
285	sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
286}
287
288#ifdef SDHCI_USE_LEDS_CLASS
289static void sdhci_led_control(struct led_classdev *led,
290	enum led_brightness brightness)
291{
292	struct sdhci_host *host = container_of(led, struct sdhci_host, led);
293	unsigned long flags;
294
295	spin_lock_irqsave(&host->lock, flags);
296
297	if (host->runtime_suspended)
298		goto out;
299
300	if (brightness == LED_OFF)
301		sdhci_deactivate_led(host);
302	else
303		sdhci_activate_led(host);
304out:
305	spin_unlock_irqrestore(&host->lock, flags);
306}
307#endif
308
309/*****************************************************************************\
310 *                                                                           *
311 * Core functions                                                            *
312 *                                                                           *
313\*****************************************************************************/
314
315static void sdhci_read_block_pio(struct sdhci_host *host)
316{
317	unsigned long flags;
318	size_t blksize, len, chunk;
319	u32 uninitialized_var(scratch);
320	u8 *buf;
321
322	DBG("PIO reading\n");
323
324	blksize = host->data->blksz;
325	chunk = 0;
326
327	local_irq_save(flags);
328
329	while (blksize) {
330		if (!sg_miter_next(&host->sg_miter))
331			BUG();
332
333		len = min(host->sg_miter.length, blksize);
334
335		blksize -= len;
336		host->sg_miter.consumed = len;
337
338		buf = host->sg_miter.addr;
339
340		while (len) {
341			if (chunk == 0) {
342				scratch = sdhci_readl(host, SDHCI_BUFFER);
343				chunk = 4;
344			}
345
346			*buf = scratch & 0xFF;
347
348			buf++;
349			scratch >>= 8;
350			chunk--;
351			len--;
352		}
353	}
354
355	sg_miter_stop(&host->sg_miter);
356
357	local_irq_restore(flags);
358}
359
360static void sdhci_write_block_pio(struct sdhci_host *host)
361{
362	unsigned long flags;
363	size_t blksize, len, chunk;
364	u32 scratch;
365	u8 *buf;
366
367	DBG("PIO writing\n");
368
369	blksize = host->data->blksz;
370	chunk = 0;
371	scratch = 0;
372
373	local_irq_save(flags);
374
375	while (blksize) {
376		if (!sg_miter_next(&host->sg_miter))
377			BUG();
378
379		len = min(host->sg_miter.length, blksize);
380
381		blksize -= len;
382		host->sg_miter.consumed = len;
383
384		buf = host->sg_miter.addr;
385
386		while (len) {
387			scratch |= (u32)*buf << (chunk * 8);
388
389			buf++;
390			chunk++;
391			len--;
392
393			if ((chunk == 4) || ((len == 0) && (blksize == 0))) {
394				sdhci_writel(host, scratch, SDHCI_BUFFER);
395				chunk = 0;
396				scratch = 0;
397			}
398		}
399	}
400
401	sg_miter_stop(&host->sg_miter);
402
403	local_irq_restore(flags);
404}
405
406static void sdhci_transfer_pio(struct sdhci_host *host)
407{
408	u32 mask;
409
410	BUG_ON(!host->data);
411
412	if (host->blocks == 0)
413		return;
414
415	if (host->data->flags & MMC_DATA_READ)
416		mask = SDHCI_DATA_AVAILABLE;
417	else
418		mask = SDHCI_SPACE_AVAILABLE;
419
420	/*
421	 * Some controllers (JMicron JMB38x) mess up the buffer bits
422	 * for transfers < 4 bytes. As long as it is just one block,
423	 * we can ignore the bits.
424	 */
425	if ((host->quirks & SDHCI_QUIRK_BROKEN_SMALL_PIO) &&
426		(host->data->blocks == 1))
427		mask = ~0;
428
429	while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
430		if (host->quirks & SDHCI_QUIRK_PIO_NEEDS_DELAY)
431			udelay(100);
432
433		if (host->data->flags & MMC_DATA_READ)
434			sdhci_read_block_pio(host);
435		else
436			sdhci_write_block_pio(host);
437
438		host->blocks--;
439		if (host->blocks == 0)
440			break;
441	}
442
443	DBG("PIO transfer complete.\n");
444}
445
446static char *sdhci_kmap_atomic(struct scatterlist *sg, unsigned long *flags)
447{
448	local_irq_save(*flags);
449	return kmap_atomic(sg_page(sg)) + sg->offset;
450}
451
452static void sdhci_kunmap_atomic(void *buffer, unsigned long *flags)
453{
454	kunmap_atomic(buffer);
455	local_irq_restore(*flags);
456}
457
458static void sdhci_adma_write_desc(struct sdhci_host *host, void *desc,
459				  dma_addr_t addr, int len, unsigned cmd)
460{
461	struct sdhci_adma2_64_desc *dma_desc = desc;
462
463	/* 32-bit and 64-bit descriptors have these members in same position */
464	dma_desc->cmd = cpu_to_le16(cmd);
465	dma_desc->len = cpu_to_le16(len);
466	dma_desc->addr_lo = cpu_to_le32((u32)addr);
467
468	if (host->flags & SDHCI_USE_64_BIT_DMA)
469		dma_desc->addr_hi = cpu_to_le32((u64)addr >> 32);
470}
471
472static void sdhci_adma_mark_end(void *desc)
473{
474	struct sdhci_adma2_64_desc *dma_desc = desc;
475
476	/* 32-bit and 64-bit descriptors have 'cmd' in same position */
477	dma_desc->cmd |= cpu_to_le16(ADMA2_END);
478}
479
480static int sdhci_adma_table_pre(struct sdhci_host *host,
481	struct mmc_data *data)
482{
483	int direction;
484
485	void *desc;
486	void *align;
487	dma_addr_t addr;
488	dma_addr_t align_addr;
489	int len, offset;
490
491	struct scatterlist *sg;
492	int i;
493	char *buffer;
494	unsigned long flags;
495
496	/*
497	 * The spec does not specify endianness of descriptor table.
498	 * We currently guess that it is LE.
499	 */
500
501	if (data->flags & MMC_DATA_READ)
502		direction = DMA_FROM_DEVICE;
503	else
504		direction = DMA_TO_DEVICE;
505
506	host->align_addr = dma_map_single(mmc_dev(host->mmc),
507		host->align_buffer, host->align_buffer_sz, direction);
508	if (dma_mapping_error(mmc_dev(host->mmc), host->align_addr))
509		goto fail;
510	BUG_ON(host->align_addr & host->align_mask);
511
512	host->sg_count = sdhci_pre_dma_transfer(host, data);
513	if (host->sg_count < 0)
514		goto unmap_align;
515
516	desc = host->adma_table;
517	align = host->align_buffer;
518
519	align_addr = host->align_addr;
520
521	for_each_sg(data->sg, sg, host->sg_count, i) {
522		addr = sg_dma_address(sg);
523		len = sg_dma_len(sg);
524
525		/*
526		 * The SDHCI specification states that ADMA
527		 * addresses must be 32-bit aligned. If they
528		 * aren't, then we use a bounce buffer for
529		 * the (up to three) bytes that screw up the
530		 * alignment.
531		 */
532		offset = (host->align_sz - (addr & host->align_mask)) &
533			 host->align_mask;
534		if (offset) {
535			if (data->flags & MMC_DATA_WRITE) {
536				buffer = sdhci_kmap_atomic(sg, &flags);
537				memcpy(align, buffer, offset);
538				sdhci_kunmap_atomic(buffer, &flags);
539			}
540
541			/* tran, valid */
542			sdhci_adma_write_desc(host, desc, align_addr, offset,
543					      ADMA2_TRAN_VALID);
544
545			BUG_ON(offset > 65536);
546
547			align += host->align_sz;
548			align_addr += host->align_sz;
549
550			desc += host->desc_sz;
551
552			addr += offset;
553			len -= offset;
554		}
555
556		BUG_ON(len > 65536);
557
558		if (len) {
559			/* tran, valid */
560			sdhci_adma_write_desc(host, desc, addr, len,
561					      ADMA2_TRAN_VALID);
562			desc += host->desc_sz;
563		}
564
565		/*
566		 * If this triggers then we have a calculation bug
567		 * somewhere. :/
568		 */
569		WARN_ON((desc - host->adma_table) >= host->adma_table_sz);
570	}
571
572	if (host->quirks & SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC) {
573		/*
574		* Mark the last descriptor as the terminating descriptor
575		*/
576		if (desc != host->adma_table) {
577			desc -= host->desc_sz;
578			sdhci_adma_mark_end(desc);
579		}
580	} else {
581		/*
582		* Add a terminating entry.
583		*/
584
585		/* nop, end, valid */
586		sdhci_adma_write_desc(host, desc, 0, 0, ADMA2_NOP_END_VALID);
587	}
588
589	/*
590	 * Resync align buffer as we might have changed it.
591	 */
592	if (data->flags & MMC_DATA_WRITE) {
593		dma_sync_single_for_device(mmc_dev(host->mmc),
594			host->align_addr, host->align_buffer_sz, direction);
595	}
596
597	return 0;
598
599unmap_align:
600	dma_unmap_single(mmc_dev(host->mmc), host->align_addr,
601		host->align_buffer_sz, direction);
602fail:
603	return -EINVAL;
604}
605
606static void sdhci_adma_table_post(struct sdhci_host *host,
607	struct mmc_data *data)
608{
609	int direction;
610
611	struct scatterlist *sg;
612	int i, size;
613	void *align;
614	char *buffer;
615	unsigned long flags;
616	bool has_unaligned;
617
618	if (data->flags & MMC_DATA_READ)
619		direction = DMA_FROM_DEVICE;
620	else
621		direction = DMA_TO_DEVICE;
622
623	dma_unmap_single(mmc_dev(host->mmc), host->align_addr,
624		host->align_buffer_sz, direction);
625
626	/* Do a quick scan of the SG list for any unaligned mappings */
627	has_unaligned = false;
628	for_each_sg(data->sg, sg, host->sg_count, i)
629		if (sg_dma_address(sg) & host->align_mask) {
630			has_unaligned = true;
631			break;
632		}
633
634	if (has_unaligned && data->flags & MMC_DATA_READ) {
635		dma_sync_sg_for_cpu(mmc_dev(host->mmc), data->sg,
636			data->sg_len, direction);
637
638		align = host->align_buffer;
639
640		for_each_sg(data->sg, sg, host->sg_count, i) {
641			if (sg_dma_address(sg) & host->align_mask) {
642				size = host->align_sz -
643				       (sg_dma_address(sg) & host->align_mask);
644
645				buffer = sdhci_kmap_atomic(sg, &flags);
646				memcpy(buffer, align, size);
647				sdhci_kunmap_atomic(buffer, &flags);
648
649				align += host->align_sz;
650			}
651		}
652	}
653
654	if (data->host_cookie == COOKIE_MAPPED) {
655		dma_unmap_sg(mmc_dev(host->mmc), data->sg,
656			data->sg_len, direction);
657		data->host_cookie = COOKIE_UNMAPPED;
658	}
659}
660
661static u8 sdhci_calc_timeout(struct sdhci_host *host, struct mmc_command *cmd)
662{
663	u8 count;
664	struct mmc_data *data = cmd->data;
665	unsigned target_timeout, current_timeout;
666
667	/*
668	 * If the host controller provides us with an incorrect timeout
669	 * value, just skip the check and use 0xE.  The hardware may take
670	 * longer to time out, but that's much better than having a too-short
671	 * timeout value.
672	 */
673	if (host->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL)
674		return 0xE;
675
676	/* Unspecified timeout, assume max */
677	if (!data && !cmd->busy_timeout)
678		return 0xE;
679
680	/* timeout in us */
681	if (!data)
682		target_timeout = cmd->busy_timeout * 1000;
683	else {
684		target_timeout = DIV_ROUND_UP(data->timeout_ns, 1000);
685		if (host->clock && data->timeout_clks) {
686			unsigned long long val;
687
688			/*
689			 * data->timeout_clks is in units of clock cycles.
690			 * host->clock is in Hz.  target_timeout is in us.
691			 * Hence, us = 1000000 * cycles / Hz.  Round up.
692			 */
693			val = 1000000 * data->timeout_clks;
694			if (do_div(val, host->clock))
695				target_timeout++;
696			target_timeout += val;
697		}
698	}
699
700	/*
701	 * Figure out needed cycles.
702	 * We do this in steps in order to fit inside a 32 bit int.
703	 * The first step is the minimum timeout, which will have a
704	 * minimum resolution of 6 bits:
705	 * (1) 2^13*1000 > 2^22,
706	 * (2) host->timeout_clk < 2^16
707	 *     =>
708	 *     (1) / (2) > 2^6
709	 */
710	count = 0;
711	current_timeout = (1 << 13) * 1000 / host->timeout_clk;
712	while (current_timeout < target_timeout) {
713		count++;
714		current_timeout <<= 1;
715		if (count >= 0xF)
716			break;
717	}
718
719	if (count >= 0xF) {
720		DBG("%s: Too large timeout 0x%x requested for CMD%d!\n",
721		    mmc_hostname(host->mmc), count, cmd->opcode);
722		count = 0xE;
723	}
724
725	return count;
726}
727
728static void sdhci_set_transfer_irqs(struct sdhci_host *host)
729{
730	u32 pio_irqs = SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL;
731	u32 dma_irqs = SDHCI_INT_DMA_END | SDHCI_INT_ADMA_ERROR;
732
733	if (host->flags & SDHCI_REQ_USE_DMA)
734		host->ier = (host->ier & ~pio_irqs) | dma_irqs;
735	else
736		host->ier = (host->ier & ~dma_irqs) | pio_irqs;
737
738	sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
739	sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
740}
741
742static void sdhci_set_timeout(struct sdhci_host *host, struct mmc_command *cmd)
743{
744	u8 count;
745
746	if (host->ops->set_timeout) {
747		host->ops->set_timeout(host, cmd);
748	} else {
749		count = sdhci_calc_timeout(host, cmd);
750		sdhci_writeb(host, count, SDHCI_TIMEOUT_CONTROL);
751	}
752}
753
754static void sdhci_prepare_data(struct sdhci_host *host, struct mmc_command *cmd)
755{
756	u8 ctrl;
757	struct mmc_data *data = cmd->data;
758	int ret;
759
760	WARN_ON(host->data);
761
762	if (data || (cmd->flags & MMC_RSP_BUSY))
763		sdhci_set_timeout(host, cmd);
764
765	if (!data)
766		return;
767
768	/* Sanity checks */
769	BUG_ON(data->blksz * data->blocks > 524288);
770	BUG_ON(data->blksz > host->mmc->max_blk_size);
771	BUG_ON(data->blocks > 65535);
772
773	host->data = data;
774	host->data_early = 0;
775	host->data->bytes_xfered = 0;
776
777	if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA))
778		host->flags |= SDHCI_REQ_USE_DMA;
779
780	/*
781	 * FIXME: This doesn't account for merging when mapping the
782	 * scatterlist.
783	 */
784	if (host->flags & SDHCI_REQ_USE_DMA) {
785		int broken, i;
786		struct scatterlist *sg;
787
788		broken = 0;
789		if (host->flags & SDHCI_USE_ADMA) {
790			if (host->quirks & SDHCI_QUIRK_32BIT_ADMA_SIZE)
791				broken = 1;
792		} else {
793			if (host->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE)
794				broken = 1;
795		}
796
797		if (unlikely(broken)) {
798			for_each_sg(data->sg, sg, data->sg_len, i) {
799				if (sg->length & 0x3) {
800					DBG("Reverting to PIO because of "
801						"transfer size (%d)\n",
802						sg->length);
803					host->flags &= ~SDHCI_REQ_USE_DMA;
804					break;
805				}
806			}
807		}
808	}
809
810	/*
811	 * The assumption here being that alignment is the same after
812	 * translation to device address space.
813	 */
814	if (host->flags & SDHCI_REQ_USE_DMA) {
815		int broken, i;
816		struct scatterlist *sg;
817
818		broken = 0;
819		if (host->flags & SDHCI_USE_ADMA) {
820			/*
821			 * As we use 3 byte chunks to work around
822			 * alignment problems, we need to check this
823			 * quirk.
824			 */
825			if (host->quirks & SDHCI_QUIRK_32BIT_ADMA_SIZE)
826				broken = 1;
827		} else {
828			if (host->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR)
829				broken = 1;
830		}
831
832		if (unlikely(broken)) {
833			for_each_sg(data->sg, sg, data->sg_len, i) {
834				if (sg->offset & 0x3) {
835					DBG("Reverting to PIO because of "
836						"bad alignment\n");
837					host->flags &= ~SDHCI_REQ_USE_DMA;
838					break;
839				}
840			}
841		}
842	}
843
844	if (host->flags & SDHCI_REQ_USE_DMA) {
845		if (host->flags & SDHCI_USE_ADMA) {
846			ret = sdhci_adma_table_pre(host, data);
847			if (ret) {
848				/*
849				 * This only happens when someone fed
850				 * us an invalid request.
851				 */
852				WARN_ON(1);
853				host->flags &= ~SDHCI_REQ_USE_DMA;
854			} else {
855				sdhci_writel(host, host->adma_addr,
856					SDHCI_ADMA_ADDRESS);
857				if (host->flags & SDHCI_USE_64_BIT_DMA)
858					sdhci_writel(host,
859						     (u64)host->adma_addr >> 32,
860						     SDHCI_ADMA_ADDRESS_HI);
861			}
862		} else {
863			int sg_cnt;
864
865			sg_cnt = sdhci_pre_dma_transfer(host, data);
866			if (sg_cnt <= 0) {
867				/*
868				 * This only happens when someone fed
869				 * us an invalid request.
870				 */
871				WARN_ON(1);
872				host->flags &= ~SDHCI_REQ_USE_DMA;
873			} else {
874				WARN_ON(sg_cnt != 1);
875				sdhci_writel(host, sg_dma_address(data->sg),
876					SDHCI_DMA_ADDRESS);
877			}
878		}
879	}
880
881	/*
882	 * Always adjust the DMA selection as some controllers
883	 * (e.g. JMicron) can't do PIO properly when the selection
884	 * is ADMA.
885	 */
886	if (host->version >= SDHCI_SPEC_200) {
887		ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
888		ctrl &= ~SDHCI_CTRL_DMA_MASK;
889		if ((host->flags & SDHCI_REQ_USE_DMA) &&
890			(host->flags & SDHCI_USE_ADMA)) {
891			if (host->flags & SDHCI_USE_64_BIT_DMA)
892				ctrl |= SDHCI_CTRL_ADMA64;
893			else
894				ctrl |= SDHCI_CTRL_ADMA32;
895		} else {
896			ctrl |= SDHCI_CTRL_SDMA;
897		}
898		sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
899	}
900
901	if (!(host->flags & SDHCI_REQ_USE_DMA)) {
902		int flags;
903
904		flags = SG_MITER_ATOMIC;
905		if (host->data->flags & MMC_DATA_READ)
906			flags |= SG_MITER_TO_SG;
907		else
908			flags |= SG_MITER_FROM_SG;
909		sg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags);
910		host->blocks = data->blocks;
911	}
912
913	sdhci_set_transfer_irqs(host);
914
915	/* Set the DMA boundary value and block size */
916	sdhci_writew(host, SDHCI_MAKE_BLKSZ(SDHCI_DEFAULT_BOUNDARY_ARG,
917		data->blksz), SDHCI_BLOCK_SIZE);
918	sdhci_writew(host, data->blocks, SDHCI_BLOCK_COUNT);
919}
920
921static void sdhci_set_transfer_mode(struct sdhci_host *host,
922	struct mmc_command *cmd)
923{
924	u16 mode = 0;
925	struct mmc_data *data = cmd->data;
926
927	if (data == NULL) {
928		if (host->quirks2 &
929			SDHCI_QUIRK2_CLEAR_TRANSFERMODE_REG_BEFORE_CMD) {
930			sdhci_writew(host, 0x0, SDHCI_TRANSFER_MODE);
931		} else {
932		/* clear Auto CMD settings for no data CMDs */
933			mode = sdhci_readw(host, SDHCI_TRANSFER_MODE);
934			sdhci_writew(host, mode & ~(SDHCI_TRNS_AUTO_CMD12 |
935				SDHCI_TRNS_AUTO_CMD23), SDHCI_TRANSFER_MODE);
936		}
937		return;
938	}
939
940	WARN_ON(!host->data);
941
942	if (!(host->quirks2 & SDHCI_QUIRK2_SUPPORT_SINGLE))
943		mode = SDHCI_TRNS_BLK_CNT_EN;
944
945	if (mmc_op_multi(cmd->opcode) || data->blocks > 1) {
946		mode = SDHCI_TRNS_BLK_CNT_EN | SDHCI_TRNS_MULTI;
947		/*
948		 * If we are sending CMD23, CMD12 never gets sent
949		 * on successful completion (so no Auto-CMD12).
950		 */
951		if (!host->mrq->sbc && (host->flags & SDHCI_AUTO_CMD12) &&
952		    (cmd->opcode != SD_IO_RW_EXTENDED))
953			mode |= SDHCI_TRNS_AUTO_CMD12;
954		else if (host->mrq->sbc && (host->flags & SDHCI_AUTO_CMD23)) {
955			mode |= SDHCI_TRNS_AUTO_CMD23;
956			sdhci_writel(host, host->mrq->sbc->arg, SDHCI_ARGUMENT2);
957		}
958	}
959
960	if (data->flags & MMC_DATA_READ)
961		mode |= SDHCI_TRNS_READ;
962	if (host->flags & SDHCI_REQ_USE_DMA)
963		mode |= SDHCI_TRNS_DMA;
964
965	sdhci_writew(host, mode, SDHCI_TRANSFER_MODE);
966}
967
968static void sdhci_finish_data(struct sdhci_host *host)
969{
970	struct mmc_data *data;
971
972	BUG_ON(!host->data);
973
974	data = host->data;
975	host->data = NULL;
976
977	if (host->flags & SDHCI_REQ_USE_DMA) {
978		if (host->flags & SDHCI_USE_ADMA)
979			sdhci_adma_table_post(host, data);
980		else {
981			if (data->host_cookie == COOKIE_MAPPED) {
982				dma_unmap_sg(mmc_dev(host->mmc),
983					data->sg, data->sg_len,
984					(data->flags & MMC_DATA_READ) ?
985					DMA_FROM_DEVICE : DMA_TO_DEVICE);
986				data->host_cookie = COOKIE_UNMAPPED;
987			}
988		}
989	}
990
991	/*
992	 * The specification states that the block count register must
993	 * be updated, but it does not specify at what point in the
994	 * data flow. That makes the register entirely useless to read
995	 * back so we have to assume that nothing made it to the card
996	 * in the event of an error.
997	 */
998	if (data->error)
999		data->bytes_xfered = 0;
1000	else
1001		data->bytes_xfered = data->blksz * data->blocks;
1002
1003	/*
1004	 * Need to send CMD12 if -
1005	 * a) open-ended multiblock transfer (no CMD23)
1006	 * b) error in multiblock transfer
1007	 */
1008	if (data->stop &&
1009	    (data->error ||
1010	     !host->mrq->sbc)) {
1011
1012		/*
1013		 * The controller needs a reset of internal state machines
1014		 * upon error conditions.
1015		 */
1016		if (data->error) {
1017			sdhci_do_reset(host, SDHCI_RESET_CMD);
1018			sdhci_do_reset(host, SDHCI_RESET_DATA);
1019		}
1020
1021		sdhci_send_command(host, data->stop);
1022	} else
1023		tasklet_schedule(&host->finish_tasklet);
1024}
1025
1026void sdhci_send_command(struct sdhci_host *host, struct mmc_command *cmd)
1027{
1028	int flags;
1029	u32 mask;
1030	unsigned long timeout;
1031
1032	WARN_ON(host->cmd);
1033
1034	/* Wait max 10 ms */
1035	timeout = 10;
1036
1037	mask = SDHCI_CMD_INHIBIT;
1038	if ((cmd->data != NULL) || (cmd->flags & MMC_RSP_BUSY))
1039		mask |= SDHCI_DATA_INHIBIT;
1040
1041	/* We shouldn't wait for data inihibit for stop commands, even
1042	   though they might use busy signaling */
1043	if (host->mrq->data && (cmd == host->mrq->data->stop))
1044		mask &= ~SDHCI_DATA_INHIBIT;
1045
1046	while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
1047		if (timeout == 0) {
1048			pr_err("%s: Controller never released "
1049				"inhibit bit(s).\n", mmc_hostname(host->mmc));
1050			sdhci_dumpregs(host);
1051			cmd->error = -EIO;
1052			tasklet_schedule(&host->finish_tasklet);
1053			return;
1054		}
1055		timeout--;
1056		mdelay(1);
1057	}
1058
1059	timeout = jiffies;
1060	if (!cmd->data && cmd->busy_timeout > 9000)
1061		timeout += DIV_ROUND_UP(cmd->busy_timeout, 1000) * HZ + HZ;
1062	else
1063		timeout += 10 * HZ;
1064	mod_timer(&host->timer, timeout);
1065
1066	host->cmd = cmd;
1067	host->busy_handle = 0;
1068
1069	sdhci_prepare_data(host, cmd);
1070
1071	sdhci_writel(host, cmd->arg, SDHCI_ARGUMENT);
1072
1073	sdhci_set_transfer_mode(host, cmd);
1074
1075	if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
1076		pr_err("%s: Unsupported response type!\n",
1077			mmc_hostname(host->mmc));
1078		cmd->error = -EINVAL;
1079		tasklet_schedule(&host->finish_tasklet);
1080		return;
1081	}
1082
1083	if (!(cmd->flags & MMC_RSP_PRESENT))
1084		flags = SDHCI_CMD_RESP_NONE;
1085	else if (cmd->flags & MMC_RSP_136)
1086		flags = SDHCI_CMD_RESP_LONG;
1087	else if (cmd->flags & MMC_RSP_BUSY)
1088		flags = SDHCI_CMD_RESP_SHORT_BUSY;
1089	else
1090		flags = SDHCI_CMD_RESP_SHORT;
1091
1092	if (cmd->flags & MMC_RSP_CRC)
1093		flags |= SDHCI_CMD_CRC;
1094	if (cmd->flags & MMC_RSP_OPCODE)
1095		flags |= SDHCI_CMD_INDEX;
1096
1097	/* CMD19 is special in that the Data Present Select should be set */
1098	if (cmd->data || cmd->opcode == MMC_SEND_TUNING_BLOCK ||
1099	    cmd->opcode == MMC_SEND_TUNING_BLOCK_HS200)
1100		flags |= SDHCI_CMD_DATA;
1101
1102	sdhci_writew(host, SDHCI_MAKE_CMD(cmd->opcode, flags), SDHCI_COMMAND);
1103}
1104EXPORT_SYMBOL_GPL(sdhci_send_command);
1105
1106static void sdhci_finish_command(struct sdhci_host *host)
1107{
1108	int i;
1109
1110	BUG_ON(host->cmd == NULL);
1111
1112	if (host->cmd->flags & MMC_RSP_PRESENT) {
1113		if (host->cmd->flags & MMC_RSP_136) {
1114			/* CRC is stripped so we need to do some shifting. */
1115			for (i = 0;i < 4;i++) {
1116				host->cmd->resp[i] = sdhci_readl(host,
1117					SDHCI_RESPONSE + (3-i)*4) << 8;
1118				if (i != 3)
1119					host->cmd->resp[i] |=
1120						sdhci_readb(host,
1121						SDHCI_RESPONSE + (3-i)*4-1);
1122			}
1123		} else {
1124			host->cmd->resp[0] = sdhci_readl(host, SDHCI_RESPONSE);
1125		}
1126	}
1127
1128	host->cmd->error = 0;
1129
1130	/* Finished CMD23, now send actual command. */
1131	if (host->cmd == host->mrq->sbc) {
1132		host->cmd = NULL;
1133		sdhci_send_command(host, host->mrq->cmd);
1134	} else {
1135
1136		/* Processed actual command. */
1137		if (host->data && host->data_early)
1138			sdhci_finish_data(host);
1139
1140		if (!host->cmd->data)
1141			tasklet_schedule(&host->finish_tasklet);
1142
1143		host->cmd = NULL;
1144	}
1145}
1146
1147static u16 sdhci_get_preset_value(struct sdhci_host *host)
1148{
1149	u16 preset = 0;
1150
1151	switch (host->timing) {
1152	case MMC_TIMING_UHS_SDR12:
1153		preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR12);
1154		break;
1155	case MMC_TIMING_UHS_SDR25:
1156		preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR25);
1157		break;
1158	case MMC_TIMING_UHS_SDR50:
1159		preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR50);
1160		break;
1161	case MMC_TIMING_UHS_SDR104:
1162	case MMC_TIMING_MMC_HS200:
1163		preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR104);
1164		break;
1165	case MMC_TIMING_UHS_DDR50:
1166	case MMC_TIMING_MMC_DDR52:
1167		preset = sdhci_readw(host, SDHCI_PRESET_FOR_DDR50);
1168		break;
1169	case MMC_TIMING_MMC_HS400:
1170		preset = sdhci_readw(host, SDHCI_PRESET_FOR_HS400);
1171		break;
1172	default:
1173		pr_warn("%s: Invalid UHS-I mode selected\n",
1174			mmc_hostname(host->mmc));
1175		preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR12);
1176		break;
1177	}
1178	return preset;
1179}
1180
1181void sdhci_set_clock(struct sdhci_host *host, unsigned int clock)
1182{
1183	int div = 0; /* Initialized for compiler warning */
1184	int real_div = div, clk_mul = 1;
1185	u16 clk = 0;
1186	unsigned long timeout;
1187
1188	host->mmc->actual_clock = 0;
1189
1190	sdhci_writew(host, 0, SDHCI_CLOCK_CONTROL);
1191
1192	if (clock == 0)
1193		return;
1194
1195	if (host->version >= SDHCI_SPEC_300) {
1196		if (host->preset_enabled) {
1197			u16 pre_val;
1198
1199			clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1200			pre_val = sdhci_get_preset_value(host);
1201			div = (pre_val & SDHCI_PRESET_SDCLK_FREQ_MASK)
1202				>> SDHCI_PRESET_SDCLK_FREQ_SHIFT;
1203			if (host->clk_mul &&
1204				(pre_val & SDHCI_PRESET_CLKGEN_SEL_MASK)) {
1205				clk = SDHCI_PROG_CLOCK_MODE;
1206				real_div = div + 1;
1207				clk_mul = host->clk_mul;
1208			} else {
1209				real_div = max_t(int, 1, div << 1);
1210			}
1211			goto clock_set;
1212		}
1213
1214		/*
1215		 * Check if the Host Controller supports Programmable Clock
1216		 * Mode.
1217		 */
1218		if (host->clk_mul) {
1219			for (div = 1; div <= 1024; div++) {
1220				if ((host->max_clk * host->clk_mul / div)
1221					<= clock)
1222					break;
1223			}
1224			/*
1225			 * Set Programmable Clock Mode in the Clock
1226			 * Control register.
1227			 */
1228			clk = SDHCI_PROG_CLOCK_MODE;
1229			real_div = div;
1230			clk_mul = host->clk_mul;
1231			div--;
1232		} else {
1233			/* Version 3.00 divisors must be a multiple of 2. */
1234			if (host->max_clk <= clock)
1235				div = 1;
1236			else {
1237				for (div = 2; div < SDHCI_MAX_DIV_SPEC_300;
1238				     div += 2) {
1239					if ((host->max_clk / div) <= clock)
1240						break;
1241				}
1242			}
1243			real_div = div;
1244			div >>= 1;
1245		}
1246	} else {
1247		/* Version 2.00 divisors must be a power of 2. */
1248		for (div = 1; div < SDHCI_MAX_DIV_SPEC_200; div *= 2) {
1249			if ((host->max_clk / div) <= clock)
1250				break;
1251		}
1252		real_div = div;
1253		div >>= 1;
1254	}
1255
1256clock_set:
1257	if (real_div)
1258		host->mmc->actual_clock = (host->max_clk * clk_mul) / real_div;
1259	clk |= (div & SDHCI_DIV_MASK) << SDHCI_DIVIDER_SHIFT;
1260	clk |= ((div & SDHCI_DIV_HI_MASK) >> SDHCI_DIV_MASK_LEN)
1261		<< SDHCI_DIVIDER_HI_SHIFT;
1262	clk |= SDHCI_CLOCK_INT_EN;
1263	sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1264
1265	/* Wait max 20 ms */
1266	timeout = 20;
1267	while (!((clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL))
1268		& SDHCI_CLOCK_INT_STABLE)) {
1269		if (timeout == 0) {
1270			pr_err("%s: Internal clock never "
1271				"stabilised.\n", mmc_hostname(host->mmc));
1272			sdhci_dumpregs(host);
1273			return;
1274		}
1275		timeout--;
1276		mdelay(1);
1277	}
1278
1279	clk |= SDHCI_CLOCK_CARD_EN;
1280	sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1281}
1282EXPORT_SYMBOL_GPL(sdhci_set_clock);
1283
1284static void sdhci_set_power(struct sdhci_host *host, unsigned char mode,
1285			    unsigned short vdd)
1286{
1287	struct mmc_host *mmc = host->mmc;
1288	u8 pwr = 0;
1289
1290	if (!IS_ERR(mmc->supply.vmmc)) {
1291		spin_unlock_irq(&host->lock);
1292		mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, vdd);
1293		spin_lock_irq(&host->lock);
1294
1295		if (mode != MMC_POWER_OFF)
1296			sdhci_writeb(host, SDHCI_POWER_ON, SDHCI_POWER_CONTROL);
1297		else
1298			sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
1299
1300		return;
1301	}
1302
1303	if (mode != MMC_POWER_OFF) {
1304		switch (1 << vdd) {
1305		case MMC_VDD_165_195:
1306			pwr = SDHCI_POWER_180;
1307			break;
1308		case MMC_VDD_29_30:
1309		case MMC_VDD_30_31:
1310			pwr = SDHCI_POWER_300;
1311			break;
1312		case MMC_VDD_32_33:
1313		case MMC_VDD_33_34:
1314			pwr = SDHCI_POWER_330;
1315			break;
1316		default:
1317			BUG();
1318		}
1319	}
1320
1321	if (host->pwr == pwr)
1322		return;
1323
1324	host->pwr = pwr;
1325
1326	if (pwr == 0) {
1327		sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
1328		if (host->quirks2 & SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON)
1329			sdhci_runtime_pm_bus_off(host);
1330		vdd = 0;
1331	} else {
1332		/*
1333		 * Spec says that we should clear the power reg before setting
1334		 * a new value. Some controllers don't seem to like this though.
1335		 */
1336		if (!(host->quirks & SDHCI_QUIRK_SINGLE_POWER_WRITE))
1337			sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
1338
1339		/*
1340		 * At least the Marvell CaFe chip gets confused if we set the
1341		 * voltage and set turn on power at the same time, so set the
1342		 * voltage first.
1343		 */
1344		if (host->quirks & SDHCI_QUIRK_NO_SIMULT_VDD_AND_POWER)
1345			sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
1346
1347		pwr |= SDHCI_POWER_ON;
1348
1349		sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
1350
1351		if (host->quirks2 & SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON)
1352			sdhci_runtime_pm_bus_on(host);
1353
1354		/*
1355		 * Some controllers need an extra 10ms delay of 10ms before
1356		 * they can apply clock after applying power
1357		 */
1358		if (host->quirks & SDHCI_QUIRK_DELAY_AFTER_POWER)
1359			mdelay(10);
1360	}
1361}
1362
1363/*****************************************************************************\
1364 *                                                                           *
1365 * MMC callbacks                                                             *
1366 *                                                                           *
1367\*****************************************************************************/
1368
1369static void sdhci_request(struct mmc_host *mmc, struct mmc_request *mrq)
1370{
1371	struct sdhci_host *host;
1372	int present;
1373	unsigned long flags;
1374	u32 tuning_opcode;
1375
1376	host = mmc_priv(mmc);
1377
1378	sdhci_runtime_pm_get(host);
1379
1380	/* Firstly check card presence */
1381	present = sdhci_do_get_cd(host);
1382
1383	spin_lock_irqsave(&host->lock, flags);
1384
1385	WARN_ON(host->mrq != NULL);
1386
1387#ifndef SDHCI_USE_LEDS_CLASS
1388	sdhci_activate_led(host);
1389#endif
1390
1391	/*
1392	 * Ensure we don't send the STOP for non-SET_BLOCK_COUNTED
1393	 * requests if Auto-CMD12 is enabled.
1394	 */
1395	if (!mrq->sbc && (host->flags & SDHCI_AUTO_CMD12)) {
1396		if (mrq->stop) {
1397			mrq->data->stop = NULL;
1398			mrq->stop = NULL;
1399		}
1400	}
1401
1402	host->mrq = mrq;
1403
1404	if (!present || host->flags & SDHCI_DEVICE_DEAD) {
1405		host->mrq->cmd->error = -ENOMEDIUM;
1406		tasklet_schedule(&host->finish_tasklet);
1407	} else {
1408		u32 present_state;
1409
1410		present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
1411		/*
1412		 * Check if the re-tuning timer has already expired and there
1413		 * is no on-going data transfer and DAT0 is not busy. If so,
1414		 * we need to execute tuning procedure before sending command.
1415		 */
1416		if ((host->flags & SDHCI_NEEDS_RETUNING) &&
1417		    !(present_state & (SDHCI_DOING_WRITE | SDHCI_DOING_READ)) &&
1418		    (present_state & SDHCI_DATA_0_LVL_MASK)) {
1419			if (mmc->card) {
1420				/* eMMC uses cmd21 but sd and sdio use cmd19 */
1421				tuning_opcode =
1422					mmc->card->type == MMC_TYPE_MMC ?
1423					MMC_SEND_TUNING_BLOCK_HS200 :
1424					MMC_SEND_TUNING_BLOCK;
1425
1426				/* Here we need to set the host->mrq to NULL,
1427				 * in case the pending finish_tasklet
1428				 * finishes it incorrectly.
1429				 */
1430				host->mrq = NULL;
1431
1432				spin_unlock_irqrestore(&host->lock, flags);
1433				sdhci_execute_tuning(mmc, tuning_opcode);
1434				spin_lock_irqsave(&host->lock, flags);
1435
1436				/* Restore original mmc_request structure */
1437				host->mrq = mrq;
1438			}
1439		}
1440
1441		if (mrq->sbc && !(host->flags & SDHCI_AUTO_CMD23))
1442			sdhci_send_command(host, mrq->sbc);
1443		else
1444			sdhci_send_command(host, mrq->cmd);
1445	}
1446
1447	mmiowb();
1448	spin_unlock_irqrestore(&host->lock, flags);
1449}
1450
1451void sdhci_set_bus_width(struct sdhci_host *host, int width)
1452{
1453	u8 ctrl;
1454
1455	ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
1456	if (width == MMC_BUS_WIDTH_8) {
1457		ctrl &= ~SDHCI_CTRL_4BITBUS;
1458		if (host->version >= SDHCI_SPEC_300)
1459			ctrl |= SDHCI_CTRL_8BITBUS;
1460	} else {
1461		if (host->version >= SDHCI_SPEC_300)
1462			ctrl &= ~SDHCI_CTRL_8BITBUS;
1463		if (width == MMC_BUS_WIDTH_4)
1464			ctrl |= SDHCI_CTRL_4BITBUS;
1465		else
1466			ctrl &= ~SDHCI_CTRL_4BITBUS;
1467	}
1468	sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1469}
1470EXPORT_SYMBOL_GPL(sdhci_set_bus_width);
1471
1472void sdhci_set_uhs_signaling(struct sdhci_host *host, unsigned timing)
1473{
1474	u16 ctrl_2;
1475
1476	ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1477	/* Select Bus Speed Mode for host */
1478	ctrl_2 &= ~SDHCI_CTRL_UHS_MASK;
1479	if ((timing == MMC_TIMING_MMC_HS200) ||
1480	    (timing == MMC_TIMING_UHS_SDR104))
1481		ctrl_2 |= SDHCI_CTRL_UHS_SDR104;
1482	else if (timing == MMC_TIMING_UHS_SDR12)
1483		ctrl_2 |= SDHCI_CTRL_UHS_SDR12;
1484	else if (timing == MMC_TIMING_UHS_SDR25)
1485		ctrl_2 |= SDHCI_CTRL_UHS_SDR25;
1486	else if (timing == MMC_TIMING_UHS_SDR50)
1487		ctrl_2 |= SDHCI_CTRL_UHS_SDR50;
1488	else if ((timing == MMC_TIMING_UHS_DDR50) ||
1489		 (timing == MMC_TIMING_MMC_DDR52))
1490		ctrl_2 |= SDHCI_CTRL_UHS_DDR50;
1491	else if (timing == MMC_TIMING_MMC_HS400)
1492		ctrl_2 |= SDHCI_CTRL_HS400; /* Non-standard */
1493	sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
1494}
1495EXPORT_SYMBOL_GPL(sdhci_set_uhs_signaling);
1496
1497static void sdhci_do_set_ios(struct sdhci_host *host, struct mmc_ios *ios)
1498{
1499	unsigned long flags;
1500	u8 ctrl;
1501	struct mmc_host *mmc = host->mmc;
1502
1503	spin_lock_irqsave(&host->lock, flags);
1504
1505	if (host->flags & SDHCI_DEVICE_DEAD) {
1506		spin_unlock_irqrestore(&host->lock, flags);
1507		if (!IS_ERR(mmc->supply.vmmc) &&
1508		    ios->power_mode == MMC_POWER_OFF)
1509			mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0);
1510		return;
1511	}
1512
1513	/*
1514	 * Reset the chip on each power off.
1515	 * Should clear out any weird states.
1516	 */
1517	if (ios->power_mode == MMC_POWER_OFF) {
1518		sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
1519		sdhci_reinit(host);
1520	}
1521
1522	if (host->version >= SDHCI_SPEC_300 &&
1523		(ios->power_mode == MMC_POWER_UP) &&
1524		!(host->quirks2 & SDHCI_QUIRK2_PRESET_VALUE_BROKEN))
1525		sdhci_enable_preset_value(host, false);
1526
1527	if (!ios->clock || ios->clock != host->clock) {
1528		host->ops->set_clock(host, ios->clock);
1529		host->clock = ios->clock;
1530
1531		if (host->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK &&
1532		    host->clock) {
1533			host->timeout_clk = host->mmc->actual_clock ?
1534						host->mmc->actual_clock / 1000 :
1535						host->clock / 1000;
1536			host->mmc->max_busy_timeout =
1537				host->ops->get_max_timeout_count ?
1538				host->ops->get_max_timeout_count(host) :
1539				1 << 27;
1540			host->mmc->max_busy_timeout /= host->timeout_clk;
1541		}
1542	}
1543
1544	sdhci_set_power(host, ios->power_mode, ios->vdd);
1545
1546	if (host->ops->platform_send_init_74_clocks)
1547		host->ops->platform_send_init_74_clocks(host, ios->power_mode);
1548
1549	host->ops->set_bus_width(host, ios->bus_width);
1550
1551	ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
1552
1553	if ((ios->timing == MMC_TIMING_SD_HS ||
1554	     ios->timing == MMC_TIMING_MMC_HS)
1555	    && !(host->quirks & SDHCI_QUIRK_NO_HISPD_BIT))
1556		ctrl |= SDHCI_CTRL_HISPD;
1557	else
1558		ctrl &= ~SDHCI_CTRL_HISPD;
1559
1560	if (host->version >= SDHCI_SPEC_300) {
1561		u16 clk, ctrl_2;
1562
1563		/* In case of UHS-I modes, set High Speed Enable */
1564		if ((ios->timing == MMC_TIMING_MMC_HS400) ||
1565		    (ios->timing == MMC_TIMING_MMC_HS200) ||
1566		    (ios->timing == MMC_TIMING_MMC_DDR52) ||
1567		    (ios->timing == MMC_TIMING_UHS_SDR50) ||
1568		    (ios->timing == MMC_TIMING_UHS_SDR104) ||
1569		    (ios->timing == MMC_TIMING_UHS_DDR50) ||
1570		    (ios->timing == MMC_TIMING_UHS_SDR25))
1571			ctrl |= SDHCI_CTRL_HISPD;
1572
1573		if (!host->preset_enabled) {
1574			sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1575			/*
1576			 * We only need to set Driver Strength if the
1577			 * preset value enable is not set.
1578			 */
1579			ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1580			ctrl_2 &= ~SDHCI_CTRL_DRV_TYPE_MASK;
1581			if (ios->drv_type == MMC_SET_DRIVER_TYPE_A)
1582				ctrl_2 |= SDHCI_CTRL_DRV_TYPE_A;
1583			else if (ios->drv_type == MMC_SET_DRIVER_TYPE_C)
1584				ctrl_2 |= SDHCI_CTRL_DRV_TYPE_C;
1585
1586			sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
1587		} else {
1588			/*
1589			 * According to SDHC Spec v3.00, if the Preset Value
1590			 * Enable in the Host Control 2 register is set, we
1591			 * need to reset SD Clock Enable before changing High
1592			 * Speed Enable to avoid generating clock gliches.
1593			 */
1594
1595			/* Reset SD Clock Enable */
1596			clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1597			clk &= ~SDHCI_CLOCK_CARD_EN;
1598			sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1599
1600			sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1601
1602			/* Re-enable SD Clock */
1603			host->ops->set_clock(host, host->clock);
1604		}
1605
1606		/* Reset SD Clock Enable */
1607		clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1608		clk &= ~SDHCI_CLOCK_CARD_EN;
1609		sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1610
1611		host->ops->set_uhs_signaling(host, ios->timing);
1612		host->timing = ios->timing;
1613
1614		if (!(host->quirks2 & SDHCI_QUIRK2_PRESET_VALUE_BROKEN) &&
1615				((ios->timing == MMC_TIMING_UHS_SDR12) ||
1616				 (ios->timing == MMC_TIMING_UHS_SDR25) ||
1617				 (ios->timing == MMC_TIMING_UHS_SDR50) ||
1618				 (ios->timing == MMC_TIMING_UHS_SDR104) ||
1619				 (ios->timing == MMC_TIMING_UHS_DDR50) ||
1620				 (ios->timing == MMC_TIMING_MMC_DDR52))) {
1621			u16 preset;
1622
1623			sdhci_enable_preset_value(host, true);
1624			preset = sdhci_get_preset_value(host);
1625			ios->drv_type = (preset & SDHCI_PRESET_DRV_MASK)
1626				>> SDHCI_PRESET_DRV_SHIFT;
1627		}
1628
1629		/* Re-enable SD Clock */
1630		host->ops->set_clock(host, host->clock);
1631	} else
1632		sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1633
1634	/*
1635	 * Some (ENE) controllers go apeshit on some ios operation,
1636	 * signalling timeout and CRC errors even on CMD0. Resetting
1637	 * it on each ios seems to solve the problem.
1638	 */
1639	if (host->quirks & SDHCI_QUIRK_RESET_CMD_DATA_ON_IOS)
1640		sdhci_do_reset(host, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1641
1642	mmiowb();
1643	spin_unlock_irqrestore(&host->lock, flags);
1644}
1645
1646static void sdhci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
1647{
1648	struct sdhci_host *host = mmc_priv(mmc);
1649
1650	sdhci_runtime_pm_get(host);
1651	sdhci_do_set_ios(host, ios);
1652	sdhci_runtime_pm_put(host);
1653}
1654
1655static int sdhci_do_get_cd(struct sdhci_host *host)
1656{
1657	int gpio_cd = mmc_gpio_get_cd(host->mmc);
1658
1659	if (host->flags & SDHCI_DEVICE_DEAD)
1660		return 0;
1661
1662	/* If polling/nonremovable, assume that the card is always present. */
1663	if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) ||
1664	    (host->mmc->caps & MMC_CAP_NONREMOVABLE))
1665		return 1;
1666
1667	/* Try slot gpio detect */
1668	if (!IS_ERR_VALUE(gpio_cd))
1669		return !!gpio_cd;
1670
1671	/* Host native card detect */
1672	return !!(sdhci_readl(host, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
1673}
1674
1675static int sdhci_get_cd(struct mmc_host *mmc)
1676{
1677	struct sdhci_host *host = mmc_priv(mmc);
1678	int ret;
1679
1680	sdhci_runtime_pm_get(host);
1681	ret = sdhci_do_get_cd(host);
1682	sdhci_runtime_pm_put(host);
1683	return ret;
1684}
1685
1686static int sdhci_check_ro(struct sdhci_host *host)
1687{
1688	unsigned long flags;
1689	int is_readonly;
1690
1691	spin_lock_irqsave(&host->lock, flags);
1692
1693	if (host->flags & SDHCI_DEVICE_DEAD)
1694		is_readonly = 0;
1695	else if (host->ops->get_ro)
1696		is_readonly = host->ops->get_ro(host);
1697	else
1698		is_readonly = !(sdhci_readl(host, SDHCI_PRESENT_STATE)
1699				& SDHCI_WRITE_PROTECT);
1700
1701	spin_unlock_irqrestore(&host->lock, flags);
1702
1703	/* This quirk needs to be replaced by a callback-function later */
1704	return host->quirks & SDHCI_QUIRK_INVERTED_WRITE_PROTECT ?
1705		!is_readonly : is_readonly;
1706}
1707
1708#define SAMPLE_COUNT	5
1709
1710static int sdhci_do_get_ro(struct sdhci_host *host)
1711{
1712	int i, ro_count;
1713
1714	if (!(host->quirks & SDHCI_QUIRK_UNSTABLE_RO_DETECT))
1715		return sdhci_check_ro(host);
1716
1717	ro_count = 0;
1718	for (i = 0; i < SAMPLE_COUNT; i++) {
1719		if (sdhci_check_ro(host)) {
1720			if (++ro_count > SAMPLE_COUNT / 2)
1721				return 1;
1722		}
1723		msleep(30);
1724	}
1725	return 0;
1726}
1727
1728static void sdhci_hw_reset(struct mmc_host *mmc)
1729{
1730	struct sdhci_host *host = mmc_priv(mmc);
1731
1732	if (host->ops && host->ops->hw_reset)
1733		host->ops->hw_reset(host);
1734}
1735
1736static int sdhci_get_ro(struct mmc_host *mmc)
1737{
1738	struct sdhci_host *host = mmc_priv(mmc);
1739	int ret;
1740
1741	sdhci_runtime_pm_get(host);
1742	ret = sdhci_do_get_ro(host);
1743	sdhci_runtime_pm_put(host);
1744	return ret;
1745}
1746
1747static void sdhci_enable_sdio_irq_nolock(struct sdhci_host *host, int enable)
1748{
1749	if (!(host->flags & SDHCI_DEVICE_DEAD)) {
1750		if (enable)
1751			host->ier |= SDHCI_INT_CARD_INT;
1752		else
1753			host->ier &= ~SDHCI_INT_CARD_INT;
1754
1755		sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
1756		sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
1757		mmiowb();
1758	}
1759}
1760
1761static void sdhci_enable_sdio_irq(struct mmc_host *mmc, int enable)
1762{
1763	struct sdhci_host *host = mmc_priv(mmc);
1764	unsigned long flags;
1765
1766	sdhci_runtime_pm_get(host);
1767
1768	spin_lock_irqsave(&host->lock, flags);
1769	if (enable)
1770		host->flags |= SDHCI_SDIO_IRQ_ENABLED;
1771	else
1772		host->flags &= ~SDHCI_SDIO_IRQ_ENABLED;
1773
1774	sdhci_enable_sdio_irq_nolock(host, enable);
1775	spin_unlock_irqrestore(&host->lock, flags);
1776
1777	sdhci_runtime_pm_put(host);
1778}
1779
1780static int sdhci_do_start_signal_voltage_switch(struct sdhci_host *host,
1781						struct mmc_ios *ios)
1782{
1783	struct mmc_host *mmc = host->mmc;
1784	u16 ctrl;
1785	int ret;
1786
1787	/*
1788	 * Signal Voltage Switching is only applicable for Host Controllers
1789	 * v3.00 and above.
1790	 */
1791	if (host->version < SDHCI_SPEC_300)
1792		return 0;
1793
1794	ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1795
1796	switch (ios->signal_voltage) {
1797	case MMC_SIGNAL_VOLTAGE_330:
1798		/* Set 1.8V Signal Enable in the Host Control2 register to 0 */
1799		ctrl &= ~SDHCI_CTRL_VDD_180;
1800		sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
1801
1802		if (!IS_ERR(mmc->supply.vqmmc)) {
1803			ret = regulator_set_voltage(mmc->supply.vqmmc, 2700000,
1804						    3600000);
1805			if (ret) {
1806				pr_warn("%s: Switching to 3.3V signalling voltage failed\n",
1807					mmc_hostname(mmc));
1808				return -EIO;
1809			}
1810		}
1811		/* Wait for 5ms */
1812		usleep_range(5000, 5500);
1813
1814		/* 3.3V regulator output should be stable within 5 ms */
1815		ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1816		if (!(ctrl & SDHCI_CTRL_VDD_180))
1817			return 0;
1818
1819		pr_warn("%s: 3.3V regulator output did not became stable\n",
1820			mmc_hostname(mmc));
1821
1822		return -EAGAIN;
1823	case MMC_SIGNAL_VOLTAGE_180:
1824		if (!IS_ERR(mmc->supply.vqmmc)) {
1825			ret = regulator_set_voltage(mmc->supply.vqmmc,
1826					1700000, 1950000);
1827			if (ret) {
1828				pr_warn("%s: Switching to 1.8V signalling voltage failed\n",
1829					mmc_hostname(mmc));
1830				return -EIO;
1831			}
1832		}
1833
1834		/*
1835		 * Enable 1.8V Signal Enable in the Host Control2
1836		 * register
1837		 */
1838		ctrl |= SDHCI_CTRL_VDD_180;
1839		sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
1840
1841		/* Some controller need to do more when switching */
1842		if (host->ops->voltage_switch)
1843			host->ops->voltage_switch(host);
1844
1845		/* 1.8V regulator output should be stable within 5 ms */
1846		ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1847		if (ctrl & SDHCI_CTRL_VDD_180)
1848			return 0;
1849
1850		pr_warn("%s: 1.8V regulator output did not became stable\n",
1851			mmc_hostname(mmc));
1852
1853		return -EAGAIN;
1854	case MMC_SIGNAL_VOLTAGE_120:
1855		if (!IS_ERR(mmc->supply.vqmmc)) {
1856			ret = regulator_set_voltage(mmc->supply.vqmmc, 1100000,
1857						    1300000);
1858			if (ret) {
1859				pr_warn("%s: Switching to 1.2V signalling voltage failed\n",
1860					mmc_hostname(mmc));
1861				return -EIO;
1862			}
1863		}
1864		return 0;
1865	default:
1866		/* No signal voltage switch required */
1867		return 0;
1868	}
1869}
1870
1871static int sdhci_start_signal_voltage_switch(struct mmc_host *mmc,
1872	struct mmc_ios *ios)
1873{
1874	struct sdhci_host *host = mmc_priv(mmc);
1875	int err;
1876
1877	if (host->version < SDHCI_SPEC_300)
1878		return 0;
1879	sdhci_runtime_pm_get(host);
1880	err = sdhci_do_start_signal_voltage_switch(host, ios);
1881	sdhci_runtime_pm_put(host);
1882	return err;
1883}
1884
1885static int sdhci_card_busy(struct mmc_host *mmc)
1886{
1887	struct sdhci_host *host = mmc_priv(mmc);
1888	u32 present_state;
1889
1890	sdhci_runtime_pm_get(host);
1891	/* Check whether DAT[3:0] is 0000 */
1892	present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
1893	sdhci_runtime_pm_put(host);
1894
1895	return !(present_state & SDHCI_DATA_LVL_MASK);
1896}
1897
1898static int sdhci_prepare_hs400_tuning(struct mmc_host *mmc, struct mmc_ios *ios)
1899{
1900	struct sdhci_host *host = mmc_priv(mmc);
1901	unsigned long flags;
1902
1903	spin_lock_irqsave(&host->lock, flags);
1904	host->flags |= SDHCI_HS400_TUNING;
1905	spin_unlock_irqrestore(&host->lock, flags);
1906
1907	return 0;
1908}
1909
1910static int sdhci_execute_tuning(struct mmc_host *mmc, u32 opcode)
1911{
1912	struct sdhci_host *host = mmc_priv(mmc);
1913	u16 ctrl;
1914	int tuning_loop_counter = MAX_TUNING_LOOP;
1915	int err = 0;
1916	unsigned long flags;
1917	unsigned int tuning_count = 0;
1918	bool hs400_tuning;
1919
1920	sdhci_runtime_pm_get(host);
1921	spin_lock_irqsave(&host->lock, flags);
1922
1923	hs400_tuning = host->flags & SDHCI_HS400_TUNING;
1924	host->flags &= ~SDHCI_HS400_TUNING;
1925
1926	if (host->tuning_mode == SDHCI_TUNING_MODE_1)
1927		tuning_count = host->tuning_count;
1928
1929	/*
1930	 * The Host Controller needs tuning only in case of SDR104 mode
1931	 * and for SDR50 mode when Use Tuning for SDR50 is set in the
1932	 * Capabilities register.
1933	 * If the Host Controller supports the HS200 mode then the
1934	 * tuning function has to be executed.
1935	 */
1936	switch (host->timing) {
1937	/* HS400 tuning is done in HS200 mode */
1938	case MMC_TIMING_MMC_HS400:
1939		err = -EINVAL;
1940		goto out_unlock;
1941
1942	case MMC_TIMING_MMC_HS200:
1943		/*
1944		 * Periodic re-tuning for HS400 is not expected to be needed, so
1945		 * disable it here.
1946		 */
1947		if (hs400_tuning)
1948			tuning_count = 0;
1949		break;
1950
1951	case MMC_TIMING_UHS_SDR104:
1952		break;
1953
1954	case MMC_TIMING_UHS_SDR50:
1955		if (host->flags & SDHCI_SDR50_NEEDS_TUNING ||
1956		    host->flags & SDHCI_SDR104_NEEDS_TUNING)
1957			break;
1958		/* FALLTHROUGH */
1959
1960	default:
1961		goto out_unlock;
1962	}
1963
1964	if (host->ops->platform_execute_tuning) {
1965		spin_unlock_irqrestore(&host->lock, flags);
1966		err = host->ops->platform_execute_tuning(host, opcode);
1967		sdhci_runtime_pm_put(host);
1968		return err;
1969	}
1970
1971	ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1972	ctrl |= SDHCI_CTRL_EXEC_TUNING;
1973	if (host->quirks2 & SDHCI_QUIRK2_TUNING_WORK_AROUND)
1974		ctrl |= SDHCI_CTRL_TUNED_CLK;
1975	sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
1976
1977	/*
1978	 * As per the Host Controller spec v3.00, tuning command
1979	 * generates Buffer Read Ready interrupt, so enable that.
1980	 *
1981	 * Note: The spec clearly says that when tuning sequence
1982	 * is being performed, the controller does not generate
1983	 * interrupts other than Buffer Read Ready interrupt. But
1984	 * to make sure we don't hit a controller bug, we _only_
1985	 * enable Buffer Read Ready interrupt here.
1986	 */
1987	sdhci_writel(host, SDHCI_INT_DATA_AVAIL, SDHCI_INT_ENABLE);
1988	sdhci_writel(host, SDHCI_INT_DATA_AVAIL, SDHCI_SIGNAL_ENABLE);
1989
1990	/*
1991	 * Issue CMD19 repeatedly till Execute Tuning is set to 0 or the number
1992	 * of loops reaches 40 times or a timeout of 150ms occurs.
1993	 */
1994	do {
1995		struct mmc_command cmd = {0};
1996		struct mmc_request mrq = {NULL};
1997
1998		cmd.opcode = opcode;
1999		cmd.arg = 0;
2000		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
2001		cmd.retries = 0;
2002		cmd.data = NULL;
2003		cmd.error = 0;
2004
2005		if (tuning_loop_counter-- == 0)
2006			break;
2007
2008		mrq.cmd = &cmd;
2009		host->mrq = &mrq;
2010
2011		/*
2012		 * In response to CMD19, the card sends 64 bytes of tuning
2013		 * block to the Host Controller. So we set the block size
2014		 * to 64 here.
2015		 */
2016		if (cmd.opcode == MMC_SEND_TUNING_BLOCK_HS200) {
2017			if (mmc->ios.bus_width == MMC_BUS_WIDTH_8)
2018				sdhci_writew(host, SDHCI_MAKE_BLKSZ(7, 128),
2019					     SDHCI_BLOCK_SIZE);
2020			else if (mmc->ios.bus_width == MMC_BUS_WIDTH_4)
2021				sdhci_writew(host, SDHCI_MAKE_BLKSZ(7, 64),
2022					     SDHCI_BLOCK_SIZE);
2023		} else {
2024			sdhci_writew(host, SDHCI_MAKE_BLKSZ(7, 64),
2025				     SDHCI_BLOCK_SIZE);
2026		}
2027
2028		/*
2029		 * The tuning block is sent by the card to the host controller.
2030		 * So we set the TRNS_READ bit in the Transfer Mode register.
2031		 * This also takes care of setting DMA Enable and Multi Block
2032		 * Select in the same register to 0.
2033		 */
2034		sdhci_writew(host, SDHCI_TRNS_READ, SDHCI_TRANSFER_MODE);
2035
2036		sdhci_send_command(host, &cmd);
2037
2038		host->cmd = NULL;
2039		host->mrq = NULL;
2040
2041		spin_unlock_irqrestore(&host->lock, flags);
2042		/* Wait for Buffer Read Ready interrupt */
2043		wait_event_interruptible_timeout(host->buf_ready_int,
2044					(host->tuning_done == 1),
2045					msecs_to_jiffies(50));
2046		spin_lock_irqsave(&host->lock, flags);
2047
2048		if (!host->tuning_done) {
2049			pr_info(DRIVER_NAME ": Timeout waiting for "
2050				"Buffer Read Ready interrupt during tuning "
2051				"procedure, falling back to fixed sampling "
2052				"clock\n");
2053			ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2054			ctrl &= ~SDHCI_CTRL_TUNED_CLK;
2055			ctrl &= ~SDHCI_CTRL_EXEC_TUNING;
2056			sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2057
2058			err = -EIO;
2059			goto out;
2060		}
2061
2062		host->tuning_done = 0;
2063
2064		ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2065
2066		/* eMMC spec does not require a delay between tuning cycles */
2067		if (opcode == MMC_SEND_TUNING_BLOCK)
2068			mdelay(1);
2069	} while (ctrl & SDHCI_CTRL_EXEC_TUNING);
2070
2071	/*
2072	 * The Host Driver has exhausted the maximum number of loops allowed,
2073	 * so use fixed sampling frequency.
2074	 */
2075	if (tuning_loop_counter < 0) {
2076		ctrl &= ~SDHCI_CTRL_TUNED_CLK;
2077		sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2078	}
2079	if (!(ctrl & SDHCI_CTRL_TUNED_CLK)) {
2080		pr_info(DRIVER_NAME ": Tuning procedure"
2081			" failed, falling back to fixed sampling"
2082			" clock\n");
2083		err = -EIO;
2084	}
2085
2086out:
2087	host->flags &= ~SDHCI_NEEDS_RETUNING;
2088
2089	if (tuning_count) {
2090		host->flags |= SDHCI_USING_RETUNING_TIMER;
2091		mod_timer(&host->tuning_timer, jiffies + tuning_count * HZ);
2092	}
2093
2094	/*
2095	 * In case tuning fails, host controllers which support re-tuning can
2096	 * try tuning again at a later time, when the re-tuning timer expires.
2097	 * So for these controllers, we return 0. Since there might be other
2098	 * controllers who do not have this capability, we return error for
2099	 * them. SDHCI_USING_RETUNING_TIMER means the host is currently using
2100	 * a retuning timer to do the retuning for the card.
2101	 */
2102	if (err && (host->flags & SDHCI_USING_RETUNING_TIMER))
2103		err = 0;
2104
2105	sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
2106	sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
2107out_unlock:
2108	spin_unlock_irqrestore(&host->lock, flags);
2109	sdhci_runtime_pm_put(host);
2110
2111	return err;
2112}
2113
2114
2115static void sdhci_enable_preset_value(struct sdhci_host *host, bool enable)
2116{
2117	/* Host Controller v3.00 defines preset value registers */
2118	if (host->version < SDHCI_SPEC_300)
2119		return;
2120
2121	/*
2122	 * We only enable or disable Preset Value if they are not already
2123	 * enabled or disabled respectively. Otherwise, we bail out.
2124	 */
2125	if (host->preset_enabled != enable) {
2126		u16 ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2127
2128		if (enable)
2129			ctrl |= SDHCI_CTRL_PRESET_VAL_ENABLE;
2130		else
2131			ctrl &= ~SDHCI_CTRL_PRESET_VAL_ENABLE;
2132
2133		sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2134
2135		if (enable)
2136			host->flags |= SDHCI_PV_ENABLED;
2137		else
2138			host->flags &= ~SDHCI_PV_ENABLED;
2139
2140		host->preset_enabled = enable;
2141	}
2142}
2143
2144static void sdhci_post_req(struct mmc_host *mmc, struct mmc_request *mrq,
2145				int err)
2146{
2147	struct sdhci_host *host = mmc_priv(mmc);
2148	struct mmc_data *data = mrq->data;
2149
2150	if (host->flags & SDHCI_REQ_USE_DMA) {
2151		if (data->host_cookie == COOKIE_GIVEN ||
2152				data->host_cookie == COOKIE_MAPPED)
2153			dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
2154					 data->flags & MMC_DATA_WRITE ?
2155					 DMA_TO_DEVICE : DMA_FROM_DEVICE);
2156		data->host_cookie = COOKIE_UNMAPPED;
2157	}
2158}
2159
2160static int sdhci_pre_dma_transfer(struct sdhci_host *host,
2161				       struct mmc_data *data)
2162{
2163	int sg_count;
2164
2165	if (data->host_cookie == COOKIE_MAPPED) {
2166		data->host_cookie = COOKIE_GIVEN;
2167		return data->sg_count;
2168	}
2169
2170	WARN_ON(data->host_cookie == COOKIE_GIVEN);
2171
2172	sg_count = dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
2173				data->flags & MMC_DATA_WRITE ?
2174				DMA_TO_DEVICE : DMA_FROM_DEVICE);
2175
2176	if (sg_count == 0)
2177		return -ENOSPC;
2178
2179	data->sg_count = sg_count;
2180	data->host_cookie = COOKIE_MAPPED;
2181
2182	return sg_count;
2183}
2184
2185static void sdhci_pre_req(struct mmc_host *mmc, struct mmc_request *mrq,
2186			       bool is_first_req)
2187{
2188	struct sdhci_host *host = mmc_priv(mmc);
2189
2190	mrq->data->host_cookie = COOKIE_UNMAPPED;
2191
2192	if (host->flags & SDHCI_REQ_USE_DMA)
2193		sdhci_pre_dma_transfer(host, mrq->data);
2194}
2195
2196static void sdhci_card_event(struct mmc_host *mmc)
2197{
2198	struct sdhci_host *host = mmc_priv(mmc);
2199	unsigned long flags;
2200	int present;
2201
2202	/* First check if client has provided their own card event */
2203	if (host->ops->card_event)
2204		host->ops->card_event(host);
2205
2206	present = sdhci_do_get_cd(host);
2207
2208	spin_lock_irqsave(&host->lock, flags);
2209
2210	/* Check host->mrq first in case we are runtime suspended */
2211	if (host->mrq && !present) {
2212		pr_err("%s: Card removed during transfer!\n",
2213			mmc_hostname(host->mmc));
2214		pr_err("%s: Resetting controller.\n",
2215			mmc_hostname(host->mmc));
2216
2217		sdhci_do_reset(host, SDHCI_RESET_CMD);
2218		sdhci_do_reset(host, SDHCI_RESET_DATA);
2219
2220		host->mrq->cmd->error = -ENOMEDIUM;
2221		tasklet_schedule(&host->finish_tasklet);
2222	}
2223
2224	spin_unlock_irqrestore(&host->lock, flags);
2225}
2226
2227static const struct mmc_host_ops sdhci_ops = {
2228	.request	= sdhci_request,
2229	.post_req	= sdhci_post_req,
2230	.pre_req	= sdhci_pre_req,
2231	.set_ios	= sdhci_set_ios,
2232	.get_cd		= sdhci_get_cd,
2233	.get_ro		= sdhci_get_ro,
2234	.hw_reset	= sdhci_hw_reset,
2235	.enable_sdio_irq = sdhci_enable_sdio_irq,
2236	.start_signal_voltage_switch	= sdhci_start_signal_voltage_switch,
2237	.prepare_hs400_tuning		= sdhci_prepare_hs400_tuning,
2238	.execute_tuning			= sdhci_execute_tuning,
2239	.card_event			= sdhci_card_event,
2240	.card_busy	= sdhci_card_busy,
2241};
2242
2243/*****************************************************************************\
2244 *                                                                           *
2245 * Tasklets                                                                  *
2246 *                                                                           *
2247\*****************************************************************************/
2248
2249static void sdhci_tasklet_finish(unsigned long param)
2250{
2251	struct sdhci_host *host;
2252	unsigned long flags;
2253	struct mmc_request *mrq;
2254
2255	host = (struct sdhci_host*)param;
2256
2257	spin_lock_irqsave(&host->lock, flags);
2258
2259        /*
2260         * If this tasklet gets rescheduled while running, it will
2261         * be run again afterwards but without any active request.
2262         */
2263	if (!host->mrq) {
2264		spin_unlock_irqrestore(&host->lock, flags);
2265		return;
2266	}
2267
2268	del_timer(&host->timer);
2269
2270	mrq = host->mrq;
2271
2272	/*
2273	 * The controller needs a reset of internal state machines
2274	 * upon error conditions.
2275	 */
2276	if (!(host->flags & SDHCI_DEVICE_DEAD) &&
2277	    ((mrq->cmd && mrq->cmd->error) ||
2278	     (mrq->sbc && mrq->sbc->error) ||
2279	     (mrq->data && ((mrq->data->error && !mrq->data->stop) ||
2280			    (mrq->data->stop && mrq->data->stop->error))) ||
2281	     (host->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST))) {
2282
2283		/* Some controllers need this kick or reset won't work here */
2284		if (host->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET)
2285			/* This is to force an update */
2286			host->ops->set_clock(host, host->clock);
2287
2288		/* Spec says we should do both at the same time, but Ricoh
2289		   controllers do not like that. */
2290		sdhci_do_reset(host, SDHCI_RESET_CMD);
2291		sdhci_do_reset(host, SDHCI_RESET_DATA);
2292	}
2293
2294	host->mrq = NULL;
2295	host->cmd = NULL;
2296	host->data = NULL;
2297
2298#ifndef SDHCI_USE_LEDS_CLASS
2299	sdhci_deactivate_led(host);
2300#endif
2301
2302	mmiowb();
2303	spin_unlock_irqrestore(&host->lock, flags);
2304
2305	mmc_request_done(host->mmc, mrq);
2306	sdhci_runtime_pm_put(host);
2307}
2308
2309static void sdhci_timeout_timer(unsigned long data)
2310{
2311	struct sdhci_host *host;
2312	unsigned long flags;
2313
2314	host = (struct sdhci_host*)data;
2315
2316	spin_lock_irqsave(&host->lock, flags);
2317
2318	if (host->mrq) {
2319		pr_err("%s: Timeout waiting for hardware "
2320			"interrupt.\n", mmc_hostname(host->mmc));
2321		sdhci_dumpregs(host);
2322
2323		if (host->data) {
2324			host->data->error = -ETIMEDOUT;
2325			sdhci_finish_data(host);
2326		} else {
2327			if (host->cmd)
2328				host->cmd->error = -ETIMEDOUT;
2329			else
2330				host->mrq->cmd->error = -ETIMEDOUT;
2331
2332			tasklet_schedule(&host->finish_tasklet);
2333		}
2334	}
2335
2336	mmiowb();
2337	spin_unlock_irqrestore(&host->lock, flags);
2338}
2339
2340static void sdhci_tuning_timer(unsigned long data)
2341{
2342	struct sdhci_host *host;
2343	unsigned long flags;
2344
2345	host = (struct sdhci_host *)data;
2346
2347	spin_lock_irqsave(&host->lock, flags);
2348
2349	host->flags |= SDHCI_NEEDS_RETUNING;
2350
2351	spin_unlock_irqrestore(&host->lock, flags);
2352}
2353
2354/*****************************************************************************\
2355 *                                                                           *
2356 * Interrupt handling                                                        *
2357 *                                                                           *
2358\*****************************************************************************/
2359
2360static void sdhci_cmd_irq(struct sdhci_host *host, u32 intmask, u32 *mask)
2361{
2362	BUG_ON(intmask == 0);
2363
2364	if (!host->cmd) {
2365		pr_err("%s: Got command interrupt 0x%08x even "
2366			"though no command operation was in progress.\n",
2367			mmc_hostname(host->mmc), (unsigned)intmask);
2368		sdhci_dumpregs(host);
2369		return;
2370	}
2371
2372	if (intmask & SDHCI_INT_TIMEOUT)
2373		host->cmd->error = -ETIMEDOUT;
2374	else if (intmask & (SDHCI_INT_CRC | SDHCI_INT_END_BIT |
2375			SDHCI_INT_INDEX))
2376		host->cmd->error = -EILSEQ;
2377
2378	if (host->cmd->error) {
2379		tasklet_schedule(&host->finish_tasklet);
2380		return;
2381	}
2382
2383	/*
2384	 * The host can send and interrupt when the busy state has
2385	 * ended, allowing us to wait without wasting CPU cycles.
2386	 * Unfortunately this is overloaded on the "data complete"
2387	 * interrupt, so we need to take some care when handling
2388	 * it.
2389	 *
2390	 * Note: The 1.0 specification is a bit ambiguous about this
2391	 *       feature so there might be some problems with older
2392	 *       controllers.
2393	 */
2394	if (host->cmd->flags & MMC_RSP_BUSY) {
2395		if (host->cmd->data)
2396			DBG("Cannot wait for busy signal when also "
2397				"doing a data transfer");
2398		else if (!(host->quirks & SDHCI_QUIRK_NO_BUSY_IRQ)
2399				&& !host->busy_handle) {
2400			/* Mark that command complete before busy is ended */
2401			host->busy_handle = 1;
2402			return;
2403		}
2404
2405		/* The controller does not support the end-of-busy IRQ,
2406		 * fall through and take the SDHCI_INT_RESPONSE */
2407	} else if ((host->quirks2 & SDHCI_QUIRK2_STOP_WITH_TC) &&
2408		   host->cmd->opcode == MMC_STOP_TRANSMISSION && !host->data) {
2409		*mask &= ~SDHCI_INT_DATA_END;
2410	}
2411
2412	if (intmask & SDHCI_INT_RESPONSE)
2413		sdhci_finish_command(host);
2414}
2415
2416#ifdef CONFIG_MMC_DEBUG
2417static void sdhci_adma_show_error(struct sdhci_host *host)
2418{
2419	const char *name = mmc_hostname(host->mmc);
2420	void *desc = host->adma_table;
2421
2422	sdhci_dumpregs(host);
2423
2424	while (true) {
2425		struct sdhci_adma2_64_desc *dma_desc = desc;
2426
2427		if (host->flags & SDHCI_USE_64_BIT_DMA)
2428			DBG("%s: %p: DMA 0x%08x%08x, LEN 0x%04x, Attr=0x%02x\n",
2429			    name, desc, le32_to_cpu(dma_desc->addr_hi),
2430			    le32_to_cpu(dma_desc->addr_lo),
2431			    le16_to_cpu(dma_desc->len),
2432			    le16_to_cpu(dma_desc->cmd));
2433		else
2434			DBG("%s: %p: DMA 0x%08x, LEN 0x%04x, Attr=0x%02x\n",
2435			    name, desc, le32_to_cpu(dma_desc->addr_lo),
2436			    le16_to_cpu(dma_desc->len),
2437			    le16_to_cpu(dma_desc->cmd));
2438
2439		desc += host->desc_sz;
2440
2441		if (dma_desc->cmd & cpu_to_le16(ADMA2_END))
2442			break;
2443	}
2444}
2445#else
2446static void sdhci_adma_show_error(struct sdhci_host *host) { }
2447#endif
2448
2449static void sdhci_data_irq(struct sdhci_host *host, u32 intmask)
2450{
2451	u32 command;
2452	BUG_ON(intmask == 0);
2453
2454	/* CMD19 generates _only_ Buffer Read Ready interrupt */
2455	if (intmask & SDHCI_INT_DATA_AVAIL) {
2456		command = SDHCI_GET_CMD(sdhci_readw(host, SDHCI_COMMAND));
2457		if (command == MMC_SEND_TUNING_BLOCK ||
2458		    command == MMC_SEND_TUNING_BLOCK_HS200) {
2459			host->tuning_done = 1;
2460			wake_up(&host->buf_ready_int);
2461			return;
2462		}
2463	}
2464
2465	if (!host->data) {
2466		/*
2467		 * The "data complete" interrupt is also used to
2468		 * indicate that a busy state has ended. See comment
2469		 * above in sdhci_cmd_irq().
2470		 */
2471		if (host->cmd && (host->cmd->flags & MMC_RSP_BUSY)) {
2472			if (intmask & SDHCI_INT_DATA_TIMEOUT) {
2473				host->cmd->error = -ETIMEDOUT;
2474				tasklet_schedule(&host->finish_tasklet);
2475				return;
2476			}
2477			if (intmask & SDHCI_INT_DATA_END) {
2478				/*
2479				 * Some cards handle busy-end interrupt
2480				 * before the command completed, so make
2481				 * sure we do things in the proper order.
2482				 */
2483				if (host->busy_handle)
2484					sdhci_finish_command(host);
2485				else
2486					host->busy_handle = 1;
2487				return;
2488			}
2489		}
2490
2491		pr_err("%s: Got data interrupt 0x%08x even "
2492			"though no data operation was in progress.\n",
2493			mmc_hostname(host->mmc), (unsigned)intmask);
2494		sdhci_dumpregs(host);
2495
2496		return;
2497	}
2498
2499	if (intmask & SDHCI_INT_DATA_TIMEOUT)
2500		host->data->error = -ETIMEDOUT;
2501	else if (intmask & SDHCI_INT_DATA_END_BIT)
2502		host->data->error = -EILSEQ;
2503	else if ((intmask & SDHCI_INT_DATA_CRC) &&
2504		SDHCI_GET_CMD(sdhci_readw(host, SDHCI_COMMAND))
2505			!= MMC_BUS_TEST_R)
2506		host->data->error = -EILSEQ;
2507	else if (intmask & SDHCI_INT_ADMA_ERROR) {
2508		pr_err("%s: ADMA error\n", mmc_hostname(host->mmc));
2509		sdhci_adma_show_error(host);
2510		host->data->error = -EIO;
2511		if (host->ops->adma_workaround)
2512			host->ops->adma_workaround(host, intmask);
2513	}
2514
2515	if (host->data->error)
2516		sdhci_finish_data(host);
2517	else {
2518		if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL))
2519			sdhci_transfer_pio(host);
2520
2521		/*
2522		 * We currently don't do anything fancy with DMA
2523		 * boundaries, but as we can't disable the feature
2524		 * we need to at least restart the transfer.
2525		 *
2526		 * According to the spec sdhci_readl(host, SDHCI_DMA_ADDRESS)
2527		 * should return a valid address to continue from, but as
2528		 * some controllers are faulty, don't trust them.
2529		 */
2530		if (intmask & SDHCI_INT_DMA_END) {
2531			u32 dmastart, dmanow;
2532			dmastart = sg_dma_address(host->data->sg);
2533			dmanow = dmastart + host->data->bytes_xfered;
2534			/*
2535			 * Force update to the next DMA block boundary.
2536			 */
2537			dmanow = (dmanow &
2538				~(SDHCI_DEFAULT_BOUNDARY_SIZE - 1)) +
2539				SDHCI_DEFAULT_BOUNDARY_SIZE;
2540			host->data->bytes_xfered = dmanow - dmastart;
2541			DBG("%s: DMA base 0x%08x, transferred 0x%06x bytes,"
2542				" next 0x%08x\n",
2543				mmc_hostname(host->mmc), dmastart,
2544				host->data->bytes_xfered, dmanow);
2545			sdhci_writel(host, dmanow, SDHCI_DMA_ADDRESS);
2546		}
2547
2548		if (intmask & SDHCI_INT_DATA_END) {
2549			if (host->cmd) {
2550				/*
2551				 * Data managed to finish before the
2552				 * command completed. Make sure we do
2553				 * things in the proper order.
2554				 */
2555				host->data_early = 1;
2556			} else {
2557				sdhci_finish_data(host);
2558			}
2559		}
2560	}
2561}
2562
2563static irqreturn_t sdhci_irq(int irq, void *dev_id)
2564{
2565	irqreturn_t result = IRQ_NONE;
2566	struct sdhci_host *host = dev_id;
2567	u32 intmask, mask, unexpected = 0;
2568	int max_loops = 16;
2569
2570	spin_lock(&host->lock);
2571
2572	if (host->runtime_suspended && !sdhci_sdio_irq_enabled(host)) {
2573		spin_unlock(&host->lock);
2574		return IRQ_NONE;
2575	}
2576
2577	intmask = sdhci_readl(host, SDHCI_INT_STATUS);
2578	if (!intmask || intmask == 0xffffffff) {
2579		result = IRQ_NONE;
2580		goto out;
2581	}
2582
2583	do {
2584		/* Clear selected interrupts. */
2585		mask = intmask & (SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK |
2586				  SDHCI_INT_BUS_POWER);
2587		sdhci_writel(host, mask, SDHCI_INT_STATUS);
2588
2589		DBG("*** %s got interrupt: 0x%08x\n",
2590			mmc_hostname(host->mmc), intmask);
2591
2592		if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
2593			u32 present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
2594				      SDHCI_CARD_PRESENT;
2595
2596			/*
2597			 * There is a observation on i.mx esdhc.  INSERT
2598			 * bit will be immediately set again when it gets
2599			 * cleared, if a card is inserted.  We have to mask
2600			 * the irq to prevent interrupt storm which will
2601			 * freeze the system.  And the REMOVE gets the
2602			 * same situation.
2603			 *
2604			 * More testing are needed here to ensure it works
2605			 * for other platforms though.
2606			 */
2607			host->ier &= ~(SDHCI_INT_CARD_INSERT |
2608				       SDHCI_INT_CARD_REMOVE);
2609			host->ier |= present ? SDHCI_INT_CARD_REMOVE :
2610					       SDHCI_INT_CARD_INSERT;
2611			sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
2612			sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
2613
2614			sdhci_writel(host, intmask & (SDHCI_INT_CARD_INSERT |
2615				     SDHCI_INT_CARD_REMOVE), SDHCI_INT_STATUS);
2616
2617			host->thread_isr |= intmask & (SDHCI_INT_CARD_INSERT |
2618						       SDHCI_INT_CARD_REMOVE);
2619			result = IRQ_WAKE_THREAD;
2620		}
2621
2622		if (intmask & SDHCI_INT_CMD_MASK)
2623			sdhci_cmd_irq(host, intmask & SDHCI_INT_CMD_MASK,
2624				      &intmask);
2625
2626		if (intmask & SDHCI_INT_DATA_MASK)
2627			sdhci_data_irq(host, intmask & SDHCI_INT_DATA_MASK);
2628
2629		if (intmask & SDHCI_INT_BUS_POWER)
2630			pr_err("%s: Card is consuming too much power!\n",
2631				mmc_hostname(host->mmc));
2632
2633		if (intmask & SDHCI_INT_CARD_INT) {
2634			sdhci_enable_sdio_irq_nolock(host, false);
2635			host->thread_isr |= SDHCI_INT_CARD_INT;
2636			result = IRQ_WAKE_THREAD;
2637		}
2638
2639		intmask &= ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE |
2640			     SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK |
2641			     SDHCI_INT_ERROR | SDHCI_INT_BUS_POWER |
2642			     SDHCI_INT_CARD_INT);
2643
2644		if (intmask) {
2645			unexpected |= intmask;
2646			sdhci_writel(host, intmask, SDHCI_INT_STATUS);
2647		}
2648
2649		if (result == IRQ_NONE)
2650			result = IRQ_HANDLED;
2651
2652		intmask = sdhci_readl(host, SDHCI_INT_STATUS);
2653	} while (intmask && --max_loops);
2654out:
2655	spin_unlock(&host->lock);
2656
2657	if (unexpected) {
2658		pr_err("%s: Unexpected interrupt 0x%08x.\n",
2659			   mmc_hostname(host->mmc), unexpected);
2660		sdhci_dumpregs(host);
2661	}
2662
2663	return result;
2664}
2665
2666static irqreturn_t sdhci_thread_irq(int irq, void *dev_id)
2667{
2668	struct sdhci_host *host = dev_id;
2669	unsigned long flags;
2670	u32 isr;
2671
2672	spin_lock_irqsave(&host->lock, flags);
2673	isr = host->thread_isr;
2674	host->thread_isr = 0;
2675	spin_unlock_irqrestore(&host->lock, flags);
2676
2677	if (isr & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
2678		sdhci_card_event(host->mmc);
2679		mmc_detect_change(host->mmc, msecs_to_jiffies(200));
2680	}
2681
2682	if (isr & SDHCI_INT_CARD_INT) {
2683		sdio_run_irqs(host->mmc);
2684
2685		spin_lock_irqsave(&host->lock, flags);
2686		if (host->flags & SDHCI_SDIO_IRQ_ENABLED)
2687			sdhci_enable_sdio_irq_nolock(host, true);
2688		spin_unlock_irqrestore(&host->lock, flags);
2689	}
2690
2691	return isr ? IRQ_HANDLED : IRQ_NONE;
2692}
2693
2694/*****************************************************************************\
2695 *                                                                           *
2696 * Suspend/resume                                                            *
2697 *                                                                           *
2698\*****************************************************************************/
2699
2700#ifdef CONFIG_PM
2701void sdhci_enable_irq_wakeups(struct sdhci_host *host)
2702{
2703	u8 val;
2704	u8 mask = SDHCI_WAKE_ON_INSERT | SDHCI_WAKE_ON_REMOVE
2705			| SDHCI_WAKE_ON_INT;
2706
2707	val = sdhci_readb(host, SDHCI_WAKE_UP_CONTROL);
2708	val |= mask ;
2709	/* Avoid fake wake up */
2710	if (host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION)
2711		val &= ~(SDHCI_WAKE_ON_INSERT | SDHCI_WAKE_ON_REMOVE);
2712	sdhci_writeb(host, val, SDHCI_WAKE_UP_CONTROL);
2713}
2714EXPORT_SYMBOL_GPL(sdhci_enable_irq_wakeups);
2715
2716static void sdhci_disable_irq_wakeups(struct sdhci_host *host)
2717{
2718	u8 val;
2719	u8 mask = SDHCI_WAKE_ON_INSERT | SDHCI_WAKE_ON_REMOVE
2720			| SDHCI_WAKE_ON_INT;
2721
2722	val = sdhci_readb(host, SDHCI_WAKE_UP_CONTROL);
2723	val &= ~mask;
2724	sdhci_writeb(host, val, SDHCI_WAKE_UP_CONTROL);
2725}
2726
2727int sdhci_suspend_host(struct sdhci_host *host)
2728{
2729	sdhci_disable_card_detection(host);
2730
2731	/* Disable tuning since we are suspending */
2732	if (host->flags & SDHCI_USING_RETUNING_TIMER) {
2733		del_timer_sync(&host->tuning_timer);
2734		host->flags &= ~SDHCI_NEEDS_RETUNING;
2735	}
2736
2737	if (!device_may_wakeup(mmc_dev(host->mmc))) {
2738		host->ier = 0;
2739		sdhci_writel(host, 0, SDHCI_INT_ENABLE);
2740		sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
2741		free_irq(host->irq, host);
2742	} else {
2743		sdhci_enable_irq_wakeups(host);
2744		enable_irq_wake(host->irq);
2745	}
2746	return 0;
2747}
2748
2749EXPORT_SYMBOL_GPL(sdhci_suspend_host);
2750
2751int sdhci_resume_host(struct sdhci_host *host)
2752{
2753	int ret = 0;
2754
2755	if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
2756		if (host->ops->enable_dma)
2757			host->ops->enable_dma(host);
2758	}
2759
2760	if (!device_may_wakeup(mmc_dev(host->mmc))) {
2761		ret = request_threaded_irq(host->irq, sdhci_irq,
2762					   sdhci_thread_irq, IRQF_SHARED,
2763					   mmc_hostname(host->mmc), host);
2764		if (ret)
2765			return ret;
2766	} else {
2767		sdhci_disable_irq_wakeups(host);
2768		disable_irq_wake(host->irq);
2769	}
2770
2771	if ((host->mmc->pm_flags & MMC_PM_KEEP_POWER) &&
2772	    (host->quirks2 & SDHCI_QUIRK2_HOST_OFF_CARD_ON)) {
2773		/* Card keeps power but host controller does not */
2774		sdhci_init(host, 0);
2775		host->pwr = 0;
2776		host->clock = 0;
2777		sdhci_do_set_ios(host, &host->mmc->ios);
2778	} else {
2779		sdhci_init(host, (host->mmc->pm_flags & MMC_PM_KEEP_POWER));
2780		mmiowb();
2781	}
2782
2783	sdhci_enable_card_detection(host);
2784
2785	/* Set the re-tuning expiration flag */
2786	if (host->flags & SDHCI_USING_RETUNING_TIMER)
2787		host->flags |= SDHCI_NEEDS_RETUNING;
2788
2789	return ret;
2790}
2791
2792EXPORT_SYMBOL_GPL(sdhci_resume_host);
2793
2794static int sdhci_runtime_pm_get(struct sdhci_host *host)
2795{
2796	return pm_runtime_get_sync(host->mmc->parent);
2797}
2798
2799static int sdhci_runtime_pm_put(struct sdhci_host *host)
2800{
2801	pm_runtime_mark_last_busy(host->mmc->parent);
2802	return pm_runtime_put_autosuspend(host->mmc->parent);
2803}
2804
2805static void sdhci_runtime_pm_bus_on(struct sdhci_host *host)
2806{
2807	if (host->bus_on)
2808		return;
2809	host->bus_on = true;
2810	pm_runtime_get_noresume(host->mmc->parent);
2811}
2812
2813static void sdhci_runtime_pm_bus_off(struct sdhci_host *host)
2814{
2815	if (!host->bus_on)
2816		return;
2817	host->bus_on = false;
2818	pm_runtime_put_noidle(host->mmc->parent);
2819}
2820
2821int sdhci_runtime_suspend_host(struct sdhci_host *host)
2822{
2823	unsigned long flags;
2824
2825	/* Disable tuning since we are suspending */
2826	if (host->flags & SDHCI_USING_RETUNING_TIMER) {
2827		del_timer_sync(&host->tuning_timer);
2828		host->flags &= ~SDHCI_NEEDS_RETUNING;
2829	}
2830
2831	spin_lock_irqsave(&host->lock, flags);
2832	host->ier &= SDHCI_INT_CARD_INT;
2833	sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
2834	sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
2835	spin_unlock_irqrestore(&host->lock, flags);
2836
2837	synchronize_hardirq(host->irq);
2838
2839	spin_lock_irqsave(&host->lock, flags);
2840	host->runtime_suspended = true;
2841	spin_unlock_irqrestore(&host->lock, flags);
2842
2843	return 0;
2844}
2845EXPORT_SYMBOL_GPL(sdhci_runtime_suspend_host);
2846
2847int sdhci_runtime_resume_host(struct sdhci_host *host)
2848{
2849	unsigned long flags;
2850	int host_flags = host->flags;
2851
2852	if (host_flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
2853		if (host->ops->enable_dma)
2854			host->ops->enable_dma(host);
2855	}
2856
2857	sdhci_init(host, 0);
2858
2859	/* Force clock and power re-program */
2860	host->pwr = 0;
2861	host->clock = 0;
2862	sdhci_do_start_signal_voltage_switch(host, &host->mmc->ios);
2863	sdhci_do_set_ios(host, &host->mmc->ios);
2864
2865	if ((host_flags & SDHCI_PV_ENABLED) &&
2866		!(host->quirks2 & SDHCI_QUIRK2_PRESET_VALUE_BROKEN)) {
2867		spin_lock_irqsave(&host->lock, flags);
2868		sdhci_enable_preset_value(host, true);
2869		spin_unlock_irqrestore(&host->lock, flags);
2870	}
2871
2872	/* Set the re-tuning expiration flag */
2873	if (host->flags & SDHCI_USING_RETUNING_TIMER)
2874		host->flags |= SDHCI_NEEDS_RETUNING;
2875
2876	spin_lock_irqsave(&host->lock, flags);
2877
2878	host->runtime_suspended = false;
2879
2880	/* Enable SDIO IRQ */
2881	if (host->flags & SDHCI_SDIO_IRQ_ENABLED)
2882		sdhci_enable_sdio_irq_nolock(host, true);
2883
2884	/* Enable Card Detection */
2885	sdhci_enable_card_detection(host);
2886
2887	spin_unlock_irqrestore(&host->lock, flags);
2888
2889	return 0;
2890}
2891EXPORT_SYMBOL_GPL(sdhci_runtime_resume_host);
2892
2893#endif /* CONFIG_PM */
2894
2895/*****************************************************************************\
2896 *                                                                           *
2897 * Device allocation/registration                                            *
2898 *                                                                           *
2899\*****************************************************************************/
2900
2901struct sdhci_host *sdhci_alloc_host(struct device *dev,
2902	size_t priv_size)
2903{
2904	struct mmc_host *mmc;
2905	struct sdhci_host *host;
2906
2907	WARN_ON(dev == NULL);
2908
2909	mmc = mmc_alloc_host(sizeof(struct sdhci_host) + priv_size, dev);
2910	if (!mmc)
2911		return ERR_PTR(-ENOMEM);
2912
2913	host = mmc_priv(mmc);
2914	host->mmc = mmc;
2915
2916	return host;
2917}
2918
2919EXPORT_SYMBOL_GPL(sdhci_alloc_host);
2920
2921int sdhci_add_host(struct sdhci_host *host)
2922{
2923	struct mmc_host *mmc;
2924	u32 caps[2] = {0, 0};
2925	u32 max_current_caps;
2926	unsigned int ocr_avail;
2927	unsigned int override_timeout_clk;
2928	int ret;
2929
2930	WARN_ON(host == NULL);
2931	if (host == NULL)
2932		return -EINVAL;
2933
2934	mmc = host->mmc;
2935
2936	if (debug_quirks)
2937		host->quirks = debug_quirks;
2938	if (debug_quirks2)
2939		host->quirks2 = debug_quirks2;
2940
2941	override_timeout_clk = host->timeout_clk;
2942
2943	sdhci_do_reset(host, SDHCI_RESET_ALL);
2944
2945	host->version = sdhci_readw(host, SDHCI_HOST_VERSION);
2946	host->version = (host->version & SDHCI_SPEC_VER_MASK)
2947				>> SDHCI_SPEC_VER_SHIFT;
2948	if (host->version > SDHCI_SPEC_300) {
2949		pr_err("%s: Unknown controller version (%d). "
2950			"You may experience problems.\n", mmc_hostname(mmc),
2951			host->version);
2952	}
2953
2954	caps[0] = (host->quirks & SDHCI_QUIRK_MISSING_CAPS) ? host->caps :
2955		sdhci_readl(host, SDHCI_CAPABILITIES);
2956
2957	if (host->version >= SDHCI_SPEC_300)
2958		caps[1] = (host->quirks & SDHCI_QUIRK_MISSING_CAPS) ?
2959			host->caps1 :
2960			sdhci_readl(host, SDHCI_CAPABILITIES_1);
2961
2962	if (host->quirks & SDHCI_QUIRK_FORCE_DMA)
2963		host->flags |= SDHCI_USE_SDMA;
2964	else if (!(caps[0] & SDHCI_CAN_DO_SDMA))
2965		DBG("Controller doesn't have SDMA capability\n");
2966	else
2967		host->flags |= SDHCI_USE_SDMA;
2968
2969	if ((host->quirks & SDHCI_QUIRK_BROKEN_DMA) &&
2970		(host->flags & SDHCI_USE_SDMA)) {
2971		DBG("Disabling DMA as it is marked broken\n");
2972		host->flags &= ~SDHCI_USE_SDMA;
2973	}
2974
2975	if ((host->version >= SDHCI_SPEC_200) &&
2976		(caps[0] & SDHCI_CAN_DO_ADMA2))
2977		host->flags |= SDHCI_USE_ADMA;
2978
2979	if ((host->quirks & SDHCI_QUIRK_BROKEN_ADMA) &&
2980		(host->flags & SDHCI_USE_ADMA)) {
2981		DBG("Disabling ADMA as it is marked broken\n");
2982		host->flags &= ~SDHCI_USE_ADMA;
2983	}
2984
2985	/*
2986	 * It is assumed that a 64-bit capable device has set a 64-bit DMA mask
2987	 * and *must* do 64-bit DMA.  A driver has the opportunity to change
2988	 * that during the first call to ->enable_dma().  Similarly
2989	 * SDHCI_QUIRK2_BROKEN_64_BIT_DMA must be left to the drivers to
2990	 * implement.
2991	 */
2992	if (sdhci_readl(host, SDHCI_CAPABILITIES) & SDHCI_CAN_64BIT)
2993		host->flags |= SDHCI_USE_64_BIT_DMA;
2994
2995	if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
2996		if (host->ops->enable_dma) {
2997			if (host->ops->enable_dma(host)) {
2998				pr_warn("%s: No suitable DMA available - falling back to PIO\n",
2999					mmc_hostname(mmc));
3000				host->flags &=
3001					~(SDHCI_USE_SDMA | SDHCI_USE_ADMA);
3002			}
3003		}
3004	}
3005
3006	/* SDMA does not support 64-bit DMA */
3007	if (host->flags & SDHCI_USE_64_BIT_DMA)
3008		host->flags &= ~SDHCI_USE_SDMA;
3009
3010	if (host->flags & SDHCI_USE_ADMA) {
3011		/*
3012		 * The DMA descriptor table size is calculated as the maximum
3013		 * number of segments times 2, to allow for an alignment
3014		 * descriptor for each segment, plus 1 for a nop end descriptor,
3015		 * all multipled by the descriptor size.
3016		 */
3017		if (host->flags & SDHCI_USE_64_BIT_DMA) {
3018			host->adma_table_sz = (SDHCI_MAX_SEGS * 2 + 1) *
3019					      SDHCI_ADMA2_64_DESC_SZ;
3020			host->align_buffer_sz = SDHCI_MAX_SEGS *
3021						SDHCI_ADMA2_64_ALIGN;
3022			host->desc_sz = SDHCI_ADMA2_64_DESC_SZ;
3023			host->align_sz = SDHCI_ADMA2_64_ALIGN;
3024			host->align_mask = SDHCI_ADMA2_64_ALIGN - 1;
3025		} else {
3026			host->adma_table_sz = (SDHCI_MAX_SEGS * 2 + 1) *
3027					      SDHCI_ADMA2_32_DESC_SZ;
3028			host->align_buffer_sz = SDHCI_MAX_SEGS *
3029						SDHCI_ADMA2_32_ALIGN;
3030			host->desc_sz = SDHCI_ADMA2_32_DESC_SZ;
3031			host->align_sz = SDHCI_ADMA2_32_ALIGN;
3032			host->align_mask = SDHCI_ADMA2_32_ALIGN - 1;
3033		}
3034		host->adma_table = dma_alloc_coherent(mmc_dev(mmc),
3035						      host->adma_table_sz,
3036						      &host->adma_addr,
3037						      GFP_KERNEL);
3038		host->align_buffer = kmalloc(host->align_buffer_sz, GFP_KERNEL);
3039		if (!host->adma_table || !host->align_buffer) {
3040			if (host->adma_table)
3041				dma_free_coherent(mmc_dev(mmc),
3042						  host->adma_table_sz,
3043						  host->adma_table,
3044						  host->adma_addr);
3045			kfree(host->align_buffer);
3046			pr_warn("%s: Unable to allocate ADMA buffers - falling back to standard DMA\n",
3047				mmc_hostname(mmc));
3048			host->flags &= ~SDHCI_USE_ADMA;
3049			host->adma_table = NULL;
3050			host->align_buffer = NULL;
3051		} else if (host->adma_addr & host->align_mask) {
3052			pr_warn("%s: unable to allocate aligned ADMA descriptor\n",
3053				mmc_hostname(mmc));
3054			host->flags &= ~SDHCI_USE_ADMA;
3055			dma_free_coherent(mmc_dev(mmc), host->adma_table_sz,
3056					  host->adma_table, host->adma_addr);
3057			kfree(host->align_buffer);
3058			host->adma_table = NULL;
3059			host->align_buffer = NULL;
3060		}
3061	}
3062
3063	/*
3064	 * If we use DMA, then it's up to the caller to set the DMA
3065	 * mask, but PIO does not need the hw shim so we set a new
3066	 * mask here in that case.
3067	 */
3068	if (!(host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA))) {
3069		host->dma_mask = DMA_BIT_MASK(64);
3070		mmc_dev(mmc)->dma_mask = &host->dma_mask;
3071	}
3072
3073	if (host->version >= SDHCI_SPEC_300)
3074		host->max_clk = (caps[0] & SDHCI_CLOCK_V3_BASE_MASK)
3075			>> SDHCI_CLOCK_BASE_SHIFT;
3076	else
3077		host->max_clk = (caps[0] & SDHCI_CLOCK_BASE_MASK)
3078			>> SDHCI_CLOCK_BASE_SHIFT;
3079
3080	host->max_clk *= 1000000;
3081	if (host->max_clk == 0 || host->quirks &
3082			SDHCI_QUIRK_CAP_CLOCK_BASE_BROKEN) {
3083		if (!host->ops->get_max_clock) {
3084			pr_err("%s: Hardware doesn't specify base clock "
3085			       "frequency.\n", mmc_hostname(mmc));
3086			return -ENODEV;
3087		}
3088		host->max_clk = host->ops->get_max_clock(host);
3089	}
3090
3091	/*
3092	 * In case of Host Controller v3.00, find out whether clock
3093	 * multiplier is supported.
3094	 */
3095	host->clk_mul = (caps[1] & SDHCI_CLOCK_MUL_MASK) >>
3096			SDHCI_CLOCK_MUL_SHIFT;
3097
3098	/*
3099	 * In case the value in Clock Multiplier is 0, then programmable
3100	 * clock mode is not supported, otherwise the actual clock
3101	 * multiplier is one more than the value of Clock Multiplier
3102	 * in the Capabilities Register.
3103	 */
3104	if (host->clk_mul)
3105		host->clk_mul += 1;
3106
3107	/*
3108	 * Set host parameters.
3109	 */
3110	mmc->ops = &sdhci_ops;
3111	mmc->f_max = host->max_clk;
3112	if (host->ops->get_min_clock)
3113		mmc->f_min = host->ops->get_min_clock(host);
3114	else if (host->version >= SDHCI_SPEC_300) {
3115		if (host->clk_mul) {
3116			mmc->f_min = (host->max_clk * host->clk_mul) / 1024;
3117			mmc->f_max = host->max_clk * host->clk_mul;
3118		} else
3119			mmc->f_min = host->max_clk / SDHCI_MAX_DIV_SPEC_300;
3120	} else
3121		mmc->f_min = host->max_clk / SDHCI_MAX_DIV_SPEC_200;
3122
3123	if (!(host->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)) {
3124		host->timeout_clk = (caps[0] & SDHCI_TIMEOUT_CLK_MASK) >>
3125					SDHCI_TIMEOUT_CLK_SHIFT;
3126		if (host->timeout_clk == 0) {
3127			if (host->ops->get_timeout_clock) {
3128				host->timeout_clk =
3129					host->ops->get_timeout_clock(host);
3130			} else {
3131				pr_err("%s: Hardware doesn't specify timeout clock frequency.\n",
3132					mmc_hostname(mmc));
3133				return -ENODEV;
3134			}
3135		}
3136
3137		if (caps[0] & SDHCI_TIMEOUT_CLK_UNIT)
3138			host->timeout_clk *= 1000;
3139
3140		if (override_timeout_clk)
3141			host->timeout_clk = override_timeout_clk;
3142
3143		mmc->max_busy_timeout = host->ops->get_max_timeout_count ?
3144			host->ops->get_max_timeout_count(host) : 1 << 27;
3145		mmc->max_busy_timeout /= host->timeout_clk;
3146	}
3147
3148	mmc->caps |= MMC_CAP_SDIO_IRQ | MMC_CAP_ERASE | MMC_CAP_CMD23;
3149	mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD;
3150
3151	if (host->quirks & SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12)
3152		host->flags |= SDHCI_AUTO_CMD12;
3153
3154	/* Auto-CMD23 stuff only works in ADMA or PIO. */
3155	if ((host->version >= SDHCI_SPEC_300) &&
3156	    ((host->flags & SDHCI_USE_ADMA) ||
3157	     !(host->flags & SDHCI_USE_SDMA)) &&
3158	     !(host->quirks2 & SDHCI_QUIRK2_ACMD23_BROKEN)) {
3159		host->flags |= SDHCI_AUTO_CMD23;
3160		DBG("%s: Auto-CMD23 available\n", mmc_hostname(mmc));
3161	} else {
3162		DBG("%s: Auto-CMD23 unavailable\n", mmc_hostname(mmc));
3163	}
3164
3165	/*
3166	 * A controller may support 8-bit width, but the board itself
3167	 * might not have the pins brought out.  Boards that support
3168	 * 8-bit width must set "mmc->caps |= MMC_CAP_8_BIT_DATA;" in
3169	 * their platform code before calling sdhci_add_host(), and we
3170	 * won't assume 8-bit width for hosts without that CAP.
3171	 */
3172	if (!(host->quirks & SDHCI_QUIRK_FORCE_1_BIT_DATA))
3173		mmc->caps |= MMC_CAP_4_BIT_DATA;
3174
3175	if (host->quirks2 & SDHCI_QUIRK2_HOST_NO_CMD23)
3176		mmc->caps &= ~MMC_CAP_CMD23;
3177
3178	if (caps[0] & SDHCI_CAN_DO_HISPD)
3179		mmc->caps |= MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED;
3180
3181	if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) &&
3182	    !(mmc->caps & MMC_CAP_NONREMOVABLE))
3183		mmc->caps |= MMC_CAP_NEEDS_POLL;
3184
3185	/* If there are external regulators, get them */
3186	if (mmc_regulator_get_supply(mmc) == -EPROBE_DEFER)
3187		return -EPROBE_DEFER;
3188
3189	/* If vqmmc regulator and no 1.8V signalling, then there's no UHS */
3190	if (!IS_ERR(mmc->supply.vqmmc)) {
3191		ret = regulator_enable(mmc->supply.vqmmc);
3192		if (!regulator_is_supported_voltage(mmc->supply.vqmmc, 1700000,
3193						    1950000))
3194			caps[1] &= ~(SDHCI_SUPPORT_SDR104 |
3195					SDHCI_SUPPORT_SDR50 |
3196					SDHCI_SUPPORT_DDR50);
3197		if (ret) {
3198			pr_warn("%s: Failed to enable vqmmc regulator: %d\n",
3199				mmc_hostname(mmc), ret);
3200			mmc->supply.vqmmc = ERR_PTR(-EINVAL);
3201		}
3202	}
3203
3204	if (host->quirks2 & SDHCI_QUIRK2_NO_1_8_V)
3205		caps[1] &= ~(SDHCI_SUPPORT_SDR104 | SDHCI_SUPPORT_SDR50 |
3206		       SDHCI_SUPPORT_DDR50);
3207
3208	/* Any UHS-I mode in caps implies SDR12 and SDR25 support. */
3209	if (caps[1] & (SDHCI_SUPPORT_SDR104 | SDHCI_SUPPORT_SDR50 |
3210		       SDHCI_SUPPORT_DDR50))
3211		mmc->caps |= MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
3212
3213	/* SDR104 supports also implies SDR50 support */
3214	if (caps[1] & SDHCI_SUPPORT_SDR104) {
3215		mmc->caps |= MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_SDR50;
3216		/* SD3.0: SDR104 is supported so (for eMMC) the caps2
3217		 * field can be promoted to support HS200.
3218		 */
3219		if (!(host->quirks2 & SDHCI_QUIRK2_BROKEN_HS200))
3220			mmc->caps2 |= MMC_CAP2_HS200;
3221	} else if (caps[1] & SDHCI_SUPPORT_SDR50)
3222		mmc->caps |= MMC_CAP_UHS_SDR50;
3223
3224	if (host->quirks2 & SDHCI_QUIRK2_CAPS_BIT63_FOR_HS400 &&
3225	    (caps[1] & SDHCI_SUPPORT_HS400))
3226		mmc->caps2 |= MMC_CAP2_HS400;
3227
3228	if ((mmc->caps2 & MMC_CAP2_HSX00_1_2V) &&
3229	    (IS_ERR(mmc->supply.vqmmc) ||
3230	     !regulator_is_supported_voltage(mmc->supply.vqmmc, 1100000,
3231					     1300000)))
3232		mmc->caps2 &= ~MMC_CAP2_HSX00_1_2V;
3233
3234	if ((caps[1] & SDHCI_SUPPORT_DDR50) &&
3235		!(host->quirks2 & SDHCI_QUIRK2_BROKEN_DDR50))
3236		mmc->caps |= MMC_CAP_UHS_DDR50;
3237
3238	/* Does the host need tuning for SDR50? */
3239	if (caps[1] & SDHCI_USE_SDR50_TUNING)
3240		host->flags |= SDHCI_SDR50_NEEDS_TUNING;
3241
3242	/* Does the host need tuning for SDR104 / HS200? */
3243	if (mmc->caps2 & MMC_CAP2_HS200)
3244		host->flags |= SDHCI_SDR104_NEEDS_TUNING;
3245
3246	/* Driver Type(s) (A, C, D) supported by the host */
3247	if (caps[1] & SDHCI_DRIVER_TYPE_A)
3248		mmc->caps |= MMC_CAP_DRIVER_TYPE_A;
3249	if (caps[1] & SDHCI_DRIVER_TYPE_C)
3250		mmc->caps |= MMC_CAP_DRIVER_TYPE_C;
3251	if (caps[1] & SDHCI_DRIVER_TYPE_D)
3252		mmc->caps |= MMC_CAP_DRIVER_TYPE_D;
3253
3254	/* Initial value for re-tuning timer count */
3255	host->tuning_count = (caps[1] & SDHCI_RETUNING_TIMER_COUNT_MASK) >>
3256			      SDHCI_RETUNING_TIMER_COUNT_SHIFT;
3257
3258	/*
3259	 * In case Re-tuning Timer is not disabled, the actual value of
3260	 * re-tuning timer will be 2 ^ (n - 1).
3261	 */
3262	if (host->tuning_count)
3263		host->tuning_count = 1 << (host->tuning_count - 1);
3264
3265	/* Re-tuning mode supported by the Host Controller */
3266	host->tuning_mode = (caps[1] & SDHCI_RETUNING_MODE_MASK) >>
3267			     SDHCI_RETUNING_MODE_SHIFT;
3268
3269	ocr_avail = 0;
3270
3271	/*
3272	 * According to SD Host Controller spec v3.00, if the Host System
3273	 * can afford more than 150mA, Host Driver should set XPC to 1. Also
3274	 * the value is meaningful only if Voltage Support in the Capabilities
3275	 * register is set. The actual current value is 4 times the register
3276	 * value.
3277	 */
3278	max_current_caps = sdhci_readl(host, SDHCI_MAX_CURRENT);
3279	if (!max_current_caps && !IS_ERR(mmc->supply.vmmc)) {
3280		int curr = regulator_get_current_limit(mmc->supply.vmmc);
3281		if (curr > 0) {
3282
3283			/* convert to SDHCI_MAX_CURRENT format */
3284			curr = curr/1000;  /* convert to mA */
3285			curr = curr/SDHCI_MAX_CURRENT_MULTIPLIER;
3286
3287			curr = min_t(u32, curr, SDHCI_MAX_CURRENT_LIMIT);
3288			max_current_caps =
3289				(curr << SDHCI_MAX_CURRENT_330_SHIFT) |
3290				(curr << SDHCI_MAX_CURRENT_300_SHIFT) |
3291				(curr << SDHCI_MAX_CURRENT_180_SHIFT);
3292		}
3293	}
3294
3295	if (caps[0] & SDHCI_CAN_VDD_330) {
3296		ocr_avail |= MMC_VDD_32_33 | MMC_VDD_33_34;
3297
3298		mmc->max_current_330 = ((max_current_caps &
3299				   SDHCI_MAX_CURRENT_330_MASK) >>
3300				   SDHCI_MAX_CURRENT_330_SHIFT) *
3301				   SDHCI_MAX_CURRENT_MULTIPLIER;
3302	}
3303	if (caps[0] & SDHCI_CAN_VDD_300) {
3304		ocr_avail |= MMC_VDD_29_30 | MMC_VDD_30_31;
3305
3306		mmc->max_current_300 = ((max_current_caps &
3307				   SDHCI_MAX_CURRENT_300_MASK) >>
3308				   SDHCI_MAX_CURRENT_300_SHIFT) *
3309				   SDHCI_MAX_CURRENT_MULTIPLIER;
3310	}
3311	if (caps[0] & SDHCI_CAN_VDD_180) {
3312		ocr_avail |= MMC_VDD_165_195;
3313
3314		mmc->max_current_180 = ((max_current_caps &
3315				   SDHCI_MAX_CURRENT_180_MASK) >>
3316				   SDHCI_MAX_CURRENT_180_SHIFT) *
3317				   SDHCI_MAX_CURRENT_MULTIPLIER;
3318	}
3319
3320	/* If OCR set by host, use it instead. */
3321	if (host->ocr_mask)
3322		ocr_avail = host->ocr_mask;
3323
3324	/* If OCR set by external regulators, give it highest prio. */
3325	if (mmc->ocr_avail)
3326		ocr_avail = mmc->ocr_avail;
3327
3328	mmc->ocr_avail = ocr_avail;
3329	mmc->ocr_avail_sdio = ocr_avail;
3330	if (host->ocr_avail_sdio)
3331		mmc->ocr_avail_sdio &= host->ocr_avail_sdio;
3332	mmc->ocr_avail_sd = ocr_avail;
3333	if (host->ocr_avail_sd)
3334		mmc->ocr_avail_sd &= host->ocr_avail_sd;
3335	else /* normal SD controllers don't support 1.8V */
3336		mmc->ocr_avail_sd &= ~MMC_VDD_165_195;
3337	mmc->ocr_avail_mmc = ocr_avail;
3338	if (host->ocr_avail_mmc)
3339		mmc->ocr_avail_mmc &= host->ocr_avail_mmc;
3340
3341	if (mmc->ocr_avail == 0) {
3342		pr_err("%s: Hardware doesn't report any "
3343			"support voltages.\n", mmc_hostname(mmc));
3344		return -ENODEV;
3345	}
3346
3347	spin_lock_init(&host->lock);
3348
3349	/*
3350	 * Maximum number of segments. Depends on if the hardware
3351	 * can do scatter/gather or not.
3352	 */
3353	if (host->flags & SDHCI_USE_ADMA)
3354		mmc->max_segs = SDHCI_MAX_SEGS;
3355	else if (host->flags & SDHCI_USE_SDMA)
3356		mmc->max_segs = 1;
3357	else /* PIO */
3358		mmc->max_segs = SDHCI_MAX_SEGS;
3359
3360	/*
3361	 * Maximum number of sectors in one transfer. Limited by SDMA boundary
3362	 * size (512KiB). Note some tuning modes impose a 4MiB limit, but this
3363	 * is less anyway.
3364	 */
3365	mmc->max_req_size = 524288;
3366
3367	/*
3368	 * Maximum segment size. Could be one segment with the maximum number
3369	 * of bytes. When doing hardware scatter/gather, each entry cannot
3370	 * be larger than 64 KiB though.
3371	 */
3372	if (host->flags & SDHCI_USE_ADMA) {
3373		if (host->quirks & SDHCI_QUIRK_BROKEN_ADMA_ZEROLEN_DESC)
3374			mmc->max_seg_size = 65535;
3375		else
3376			mmc->max_seg_size = 65536;
3377	} else {
3378		mmc->max_seg_size = mmc->max_req_size;
3379	}
3380
3381	/*
3382	 * Maximum block size. This varies from controller to controller and
3383	 * is specified in the capabilities register.
3384	 */
3385	if (host->quirks & SDHCI_QUIRK_FORCE_BLK_SZ_2048) {
3386		mmc->max_blk_size = 2;
3387	} else {
3388		mmc->max_blk_size = (caps[0] & SDHCI_MAX_BLOCK_MASK) >>
3389				SDHCI_MAX_BLOCK_SHIFT;
3390		if (mmc->max_blk_size >= 3) {
3391			pr_warn("%s: Invalid maximum block size, assuming 512 bytes\n",
3392				mmc_hostname(mmc));
3393			mmc->max_blk_size = 0;
3394		}
3395	}
3396
3397	mmc->max_blk_size = 512 << mmc->max_blk_size;
3398
3399	/*
3400	 * Maximum block count.
3401	 */
3402	mmc->max_blk_count = (host->quirks & SDHCI_QUIRK_NO_MULTIBLOCK) ? 1 : 65535;
3403
3404	/*
3405	 * Init tasklets.
3406	 */
3407	tasklet_init(&host->finish_tasklet,
3408		sdhci_tasklet_finish, (unsigned long)host);
3409
3410	setup_timer(&host->timer, sdhci_timeout_timer, (unsigned long)host);
3411
3412	init_waitqueue_head(&host->buf_ready_int);
3413
3414	if (host->version >= SDHCI_SPEC_300) {
3415		/* Initialize re-tuning timer */
3416		init_timer(&host->tuning_timer);
3417		host->tuning_timer.data = (unsigned long)host;
3418		host->tuning_timer.function = sdhci_tuning_timer;
3419	}
3420
3421	sdhci_init(host, 0);
3422
3423	ret = request_threaded_irq(host->irq, sdhci_irq, sdhci_thread_irq,
3424				   IRQF_SHARED,	mmc_hostname(mmc), host);
3425	if (ret) {
3426		pr_err("%s: Failed to request IRQ %d: %d\n",
3427		       mmc_hostname(mmc), host->irq, ret);
3428		goto untasklet;
3429	}
3430
3431#ifdef CONFIG_MMC_DEBUG
3432	sdhci_dumpregs(host);
3433#endif
3434
3435#ifdef SDHCI_USE_LEDS_CLASS
3436	snprintf(host->led_name, sizeof(host->led_name),
3437		"%s::", mmc_hostname(mmc));
3438	host->led.name = host->led_name;
3439	host->led.brightness = LED_OFF;
3440	host->led.default_trigger = mmc_hostname(mmc);
3441	host->led.brightness_set = sdhci_led_control;
3442
3443	ret = led_classdev_register(mmc_dev(mmc), &host->led);
3444	if (ret) {
3445		pr_err("%s: Failed to register LED device: %d\n",
3446		       mmc_hostname(mmc), ret);
3447		goto reset;
3448	}
3449#endif
3450
3451	mmiowb();
3452
3453	mmc_add_host(mmc);
3454
3455	pr_info("%s: SDHCI controller on %s [%s] using %s\n",
3456		mmc_hostname(mmc), host->hw_name, dev_name(mmc_dev(mmc)),
3457		(host->flags & SDHCI_USE_ADMA) ?
3458		(host->flags & SDHCI_USE_64_BIT_DMA) ? "ADMA 64-bit" : "ADMA" :
3459		(host->flags & SDHCI_USE_SDMA) ? "DMA" : "PIO");
3460
3461	sdhci_enable_card_detection(host);
3462
3463	return 0;
3464
3465#ifdef SDHCI_USE_LEDS_CLASS
3466reset:
3467	sdhci_do_reset(host, SDHCI_RESET_ALL);
3468	sdhci_writel(host, 0, SDHCI_INT_ENABLE);
3469	sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
3470	free_irq(host->irq, host);
3471#endif
3472untasklet:
3473	tasklet_kill(&host->finish_tasklet);
3474
3475	return ret;
3476}
3477
3478EXPORT_SYMBOL_GPL(sdhci_add_host);
3479
3480void sdhci_remove_host(struct sdhci_host *host, int dead)
3481{
3482	struct mmc_host *mmc = host->mmc;
3483	unsigned long flags;
3484
3485	if (dead) {
3486		spin_lock_irqsave(&host->lock, flags);
3487
3488		host->flags |= SDHCI_DEVICE_DEAD;
3489
3490		if (host->mrq) {
3491			pr_err("%s: Controller removed during "
3492				" transfer!\n", mmc_hostname(mmc));
3493
3494			host->mrq->cmd->error = -ENOMEDIUM;
3495			tasklet_schedule(&host->finish_tasklet);
3496		}
3497
3498		spin_unlock_irqrestore(&host->lock, flags);
3499	}
3500
3501	sdhci_disable_card_detection(host);
3502
3503	mmc_remove_host(mmc);
3504
3505#ifdef SDHCI_USE_LEDS_CLASS
3506	led_classdev_unregister(&host->led);
3507#endif
3508
3509	if (!dead)
3510		sdhci_do_reset(host, SDHCI_RESET_ALL);
3511
3512	sdhci_writel(host, 0, SDHCI_INT_ENABLE);
3513	sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
3514	free_irq(host->irq, host);
3515
3516	del_timer_sync(&host->timer);
3517
3518	tasklet_kill(&host->finish_tasklet);
3519
3520	if (!IS_ERR(mmc->supply.vqmmc))
3521		regulator_disable(mmc->supply.vqmmc);
3522
3523	if (host->adma_table)
3524		dma_free_coherent(mmc_dev(mmc), host->adma_table_sz,
3525				  host->adma_table, host->adma_addr);
3526	kfree(host->align_buffer);
3527
3528	host->adma_table = NULL;
3529	host->align_buffer = NULL;
3530}
3531
3532EXPORT_SYMBOL_GPL(sdhci_remove_host);
3533
3534void sdhci_free_host(struct sdhci_host *host)
3535{
3536	mmc_free_host(host->mmc);
3537}
3538
3539EXPORT_SYMBOL_GPL(sdhci_free_host);
3540
3541/*****************************************************************************\
3542 *                                                                           *
3543 * Driver init/exit                                                          *
3544 *                                                                           *
3545\*****************************************************************************/
3546
3547static int __init sdhci_drv_init(void)
3548{
3549	pr_info(DRIVER_NAME
3550		": Secure Digital Host Controller Interface driver\n");
3551	pr_info(DRIVER_NAME ": Copyright(c) Pierre Ossman\n");
3552
3553	return 0;
3554}
3555
3556static void __exit sdhci_drv_exit(void)
3557{
3558}
3559
3560module_init(sdhci_drv_init);
3561module_exit(sdhci_drv_exit);
3562
3563module_param(debug_quirks, uint, 0444);
3564module_param(debug_quirks2, uint, 0444);
3565
3566MODULE_AUTHOR("Pierre Ossman <pierre@ossman.eu>");
3567MODULE_DESCRIPTION("Secure Digital Host Controller Interface core driver");
3568MODULE_LICENSE("GPL");
3569
3570MODULE_PARM_DESC(debug_quirks, "Force certain quirks.");
3571MODULE_PARM_DESC(debug_quirks2, "Force certain other quirks.");
3572