Linux-libre 5.3.12-gnu
[librecmc/linux-libre.git] / drivers / mmc / host / sdhci.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  linux/drivers/mmc/host/sdhci.c - Secure Digital Host Controller Interface driver
4  *
5  *  Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved.
6  *
7  * Thanks to the following companies for their support:
8  *
9  *     - JMicron (hardware and technical support)
10  */
11
12 #include <linux/delay.h>
13 #include <linux/ktime.h>
14 #include <linux/highmem.h>
15 #include <linux/io.h>
16 #include <linux/module.h>
17 #include <linux/dma-mapping.h>
18 #include <linux/slab.h>
19 #include <linux/scatterlist.h>
20 #include <linux/sizes.h>
21 #include <linux/swiotlb.h>
22 #include <linux/regulator/consumer.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/of.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("%s: " DRIVER_NAME ": " f, mmc_hostname(host->mmc), ## x)
40
41 #define SDHCI_DUMP(f, x...) \
42         pr_err("%s: " DRIVER_NAME ": " f, mmc_hostname(host->mmc), ## x)
43
44 #define MAX_TUNING_LOOP 40
45
46 static unsigned int debug_quirks = 0;
47 static unsigned int debug_quirks2;
48
49 static void sdhci_finish_data(struct sdhci_host *);
50
51 static void sdhci_enable_preset_value(struct sdhci_host *host, bool enable);
52
53 void sdhci_dumpregs(struct sdhci_host *host)
54 {
55         SDHCI_DUMP("============ SDHCI REGISTER DUMP ===========\n");
56
57         SDHCI_DUMP("Sys addr:  0x%08x | Version:  0x%08x\n",
58                    sdhci_readl(host, SDHCI_DMA_ADDRESS),
59                    sdhci_readw(host, SDHCI_HOST_VERSION));
60         SDHCI_DUMP("Blk size:  0x%08x | Blk cnt:  0x%08x\n",
61                    sdhci_readw(host, SDHCI_BLOCK_SIZE),
62                    sdhci_readw(host, SDHCI_BLOCK_COUNT));
63         SDHCI_DUMP("Argument:  0x%08x | Trn mode: 0x%08x\n",
64                    sdhci_readl(host, SDHCI_ARGUMENT),
65                    sdhci_readw(host, SDHCI_TRANSFER_MODE));
66         SDHCI_DUMP("Present:   0x%08x | Host ctl: 0x%08x\n",
67                    sdhci_readl(host, SDHCI_PRESENT_STATE),
68                    sdhci_readb(host, SDHCI_HOST_CONTROL));
69         SDHCI_DUMP("Power:     0x%08x | Blk gap:  0x%08x\n",
70                    sdhci_readb(host, SDHCI_POWER_CONTROL),
71                    sdhci_readb(host, SDHCI_BLOCK_GAP_CONTROL));
72         SDHCI_DUMP("Wake-up:   0x%08x | Clock:    0x%08x\n",
73                    sdhci_readb(host, SDHCI_WAKE_UP_CONTROL),
74                    sdhci_readw(host, SDHCI_CLOCK_CONTROL));
75         SDHCI_DUMP("Timeout:   0x%08x | Int stat: 0x%08x\n",
76                    sdhci_readb(host, SDHCI_TIMEOUT_CONTROL),
77                    sdhci_readl(host, SDHCI_INT_STATUS));
78         SDHCI_DUMP("Int enab:  0x%08x | Sig enab: 0x%08x\n",
79                    sdhci_readl(host, SDHCI_INT_ENABLE),
80                    sdhci_readl(host, SDHCI_SIGNAL_ENABLE));
81         SDHCI_DUMP("ACmd stat: 0x%08x | Slot int: 0x%08x\n",
82                    sdhci_readw(host, SDHCI_AUTO_CMD_STATUS),
83                    sdhci_readw(host, SDHCI_SLOT_INT_STATUS));
84         SDHCI_DUMP("Caps:      0x%08x | Caps_1:   0x%08x\n",
85                    sdhci_readl(host, SDHCI_CAPABILITIES),
86                    sdhci_readl(host, SDHCI_CAPABILITIES_1));
87         SDHCI_DUMP("Cmd:       0x%08x | Max curr: 0x%08x\n",
88                    sdhci_readw(host, SDHCI_COMMAND),
89                    sdhci_readl(host, SDHCI_MAX_CURRENT));
90         SDHCI_DUMP("Resp[0]:   0x%08x | Resp[1]:  0x%08x\n",
91                    sdhci_readl(host, SDHCI_RESPONSE),
92                    sdhci_readl(host, SDHCI_RESPONSE + 4));
93         SDHCI_DUMP("Resp[2]:   0x%08x | Resp[3]:  0x%08x\n",
94                    sdhci_readl(host, SDHCI_RESPONSE + 8),
95                    sdhci_readl(host, SDHCI_RESPONSE + 12));
96         SDHCI_DUMP("Host ctl2: 0x%08x\n",
97                    sdhci_readw(host, SDHCI_HOST_CONTROL2));
98
99         if (host->flags & SDHCI_USE_ADMA) {
100                 if (host->flags & SDHCI_USE_64_BIT_DMA) {
101                         SDHCI_DUMP("ADMA Err:  0x%08x | ADMA Ptr: 0x%08x%08x\n",
102                                    sdhci_readl(host, SDHCI_ADMA_ERROR),
103                                    sdhci_readl(host, SDHCI_ADMA_ADDRESS_HI),
104                                    sdhci_readl(host, SDHCI_ADMA_ADDRESS));
105                 } else {
106                         SDHCI_DUMP("ADMA Err:  0x%08x | ADMA Ptr: 0x%08x\n",
107                                    sdhci_readl(host, SDHCI_ADMA_ERROR),
108                                    sdhci_readl(host, SDHCI_ADMA_ADDRESS));
109                 }
110         }
111
112         SDHCI_DUMP("============================================\n");
113 }
114 EXPORT_SYMBOL_GPL(sdhci_dumpregs);
115
116 /*****************************************************************************\
117  *                                                                           *
118  * Low level functions                                                       *
119  *                                                                           *
120 \*****************************************************************************/
121
122 static void sdhci_do_enable_v4_mode(struct sdhci_host *host)
123 {
124         u16 ctrl2;
125
126         ctrl2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
127         if (ctrl2 & SDHCI_CTRL_V4_MODE)
128                 return;
129
130         ctrl2 |= SDHCI_CTRL_V4_MODE;
131         sdhci_writew(host, ctrl2, SDHCI_HOST_CONTROL2);
132 }
133
134 /*
135  * This can be called before sdhci_add_host() by Vendor's host controller
136  * driver to enable v4 mode if supported.
137  */
138 void sdhci_enable_v4_mode(struct sdhci_host *host)
139 {
140         host->v4_mode = true;
141         sdhci_do_enable_v4_mode(host);
142 }
143 EXPORT_SYMBOL_GPL(sdhci_enable_v4_mode);
144
145 static inline bool sdhci_data_line_cmd(struct mmc_command *cmd)
146 {
147         return cmd->data || cmd->flags & MMC_RSP_BUSY;
148 }
149
150 static void sdhci_set_card_detection(struct sdhci_host *host, bool enable)
151 {
152         u32 present;
153
154         if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) ||
155             !mmc_card_is_removable(host->mmc))
156                 return;
157
158         if (enable) {
159                 present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
160                                       SDHCI_CARD_PRESENT;
161
162                 host->ier |= present ? SDHCI_INT_CARD_REMOVE :
163                                        SDHCI_INT_CARD_INSERT;
164         } else {
165                 host->ier &= ~(SDHCI_INT_CARD_REMOVE | SDHCI_INT_CARD_INSERT);
166         }
167
168         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
169         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
170 }
171
172 static void sdhci_enable_card_detection(struct sdhci_host *host)
173 {
174         sdhci_set_card_detection(host, true);
175 }
176
177 static void sdhci_disable_card_detection(struct sdhci_host *host)
178 {
179         sdhci_set_card_detection(host, false);
180 }
181
182 static void sdhci_runtime_pm_bus_on(struct sdhci_host *host)
183 {
184         if (host->bus_on)
185                 return;
186         host->bus_on = true;
187         pm_runtime_get_noresume(host->mmc->parent);
188 }
189
190 static void sdhci_runtime_pm_bus_off(struct sdhci_host *host)
191 {
192         if (!host->bus_on)
193                 return;
194         host->bus_on = false;
195         pm_runtime_put_noidle(host->mmc->parent);
196 }
197
198 void sdhci_reset(struct sdhci_host *host, u8 mask)
199 {
200         ktime_t timeout;
201
202         sdhci_writeb(host, mask, SDHCI_SOFTWARE_RESET);
203
204         if (mask & SDHCI_RESET_ALL) {
205                 host->clock = 0;
206                 /* Reset-all turns off SD Bus Power */
207                 if (host->quirks2 & SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON)
208                         sdhci_runtime_pm_bus_off(host);
209         }
210
211         /* Wait max 100 ms */
212         timeout = ktime_add_ms(ktime_get(), 100);
213
214         /* hw clears the bit when it's done */
215         while (1) {
216                 bool timedout = ktime_after(ktime_get(), timeout);
217
218                 if (!(sdhci_readb(host, SDHCI_SOFTWARE_RESET) & mask))
219                         break;
220                 if (timedout) {
221                         pr_err("%s: Reset 0x%x never completed.\n",
222                                 mmc_hostname(host->mmc), (int)mask);
223                         sdhci_dumpregs(host);
224                         return;
225                 }
226                 udelay(10);
227         }
228 }
229 EXPORT_SYMBOL_GPL(sdhci_reset);
230
231 static void sdhci_do_reset(struct sdhci_host *host, u8 mask)
232 {
233         if (host->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
234                 struct mmc_host *mmc = host->mmc;
235
236                 if (!mmc->ops->get_cd(mmc))
237                         return;
238         }
239
240         host->ops->reset(host, mask);
241
242         if (mask & SDHCI_RESET_ALL) {
243                 if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
244                         if (host->ops->enable_dma)
245                                 host->ops->enable_dma(host);
246                 }
247
248                 /* Resetting the controller clears many */
249                 host->preset_enabled = false;
250         }
251 }
252
253 static void sdhci_set_default_irqs(struct sdhci_host *host)
254 {
255         host->ier = SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
256                     SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT |
257                     SDHCI_INT_INDEX | SDHCI_INT_END_BIT | SDHCI_INT_CRC |
258                     SDHCI_INT_TIMEOUT | SDHCI_INT_DATA_END |
259                     SDHCI_INT_RESPONSE;
260
261         if (host->tuning_mode == SDHCI_TUNING_MODE_2 ||
262             host->tuning_mode == SDHCI_TUNING_MODE_3)
263                 host->ier |= SDHCI_INT_RETUNE;
264
265         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
266         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
267 }
268
269 static void sdhci_config_dma(struct sdhci_host *host)
270 {
271         u8 ctrl;
272         u16 ctrl2;
273
274         if (host->version < SDHCI_SPEC_200)
275                 return;
276
277         ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
278
279         /*
280          * Always adjust the DMA selection as some controllers
281          * (e.g. JMicron) can't do PIO properly when the selection
282          * is ADMA.
283          */
284         ctrl &= ~SDHCI_CTRL_DMA_MASK;
285         if (!(host->flags & SDHCI_REQ_USE_DMA))
286                 goto out;
287
288         /* Note if DMA Select is zero then SDMA is selected */
289         if (host->flags & SDHCI_USE_ADMA)
290                 ctrl |= SDHCI_CTRL_ADMA32;
291
292         if (host->flags & SDHCI_USE_64_BIT_DMA) {
293                 /*
294                  * If v4 mode, all supported DMA can be 64-bit addressing if
295                  * controller supports 64-bit system address, otherwise only
296                  * ADMA can support 64-bit addressing.
297                  */
298                 if (host->v4_mode) {
299                         ctrl2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
300                         ctrl2 |= SDHCI_CTRL_64BIT_ADDR;
301                         sdhci_writew(host, ctrl2, SDHCI_HOST_CONTROL2);
302                 } else if (host->flags & SDHCI_USE_ADMA) {
303                         /*
304                          * Don't need to undo SDHCI_CTRL_ADMA32 in order to
305                          * set SDHCI_CTRL_ADMA64.
306                          */
307                         ctrl |= SDHCI_CTRL_ADMA64;
308                 }
309         }
310
311 out:
312         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
313 }
314
315 static void sdhci_init(struct sdhci_host *host, int soft)
316 {
317         struct mmc_host *mmc = host->mmc;
318
319         if (soft)
320                 sdhci_do_reset(host, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
321         else
322                 sdhci_do_reset(host, SDHCI_RESET_ALL);
323
324         if (host->v4_mode)
325                 sdhci_do_enable_v4_mode(host);
326
327         sdhci_set_default_irqs(host);
328
329         host->cqe_on = false;
330
331         if (soft) {
332                 /* force clock reconfiguration */
333                 host->clock = 0;
334                 mmc->ops->set_ios(mmc, &mmc->ios);
335         }
336 }
337
338 static void sdhci_reinit(struct sdhci_host *host)
339 {
340         sdhci_init(host, 0);
341         sdhci_enable_card_detection(host);
342 }
343
344 static void __sdhci_led_activate(struct sdhci_host *host)
345 {
346         u8 ctrl;
347
348         if (host->quirks & SDHCI_QUIRK_NO_LED)
349                 return;
350
351         ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
352         ctrl |= SDHCI_CTRL_LED;
353         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
354 }
355
356 static void __sdhci_led_deactivate(struct sdhci_host *host)
357 {
358         u8 ctrl;
359
360         if (host->quirks & SDHCI_QUIRK_NO_LED)
361                 return;
362
363         ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
364         ctrl &= ~SDHCI_CTRL_LED;
365         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
366 }
367
368 #if IS_REACHABLE(CONFIG_LEDS_CLASS)
369 static void sdhci_led_control(struct led_classdev *led,
370                               enum led_brightness brightness)
371 {
372         struct sdhci_host *host = container_of(led, struct sdhci_host, led);
373         unsigned long flags;
374
375         spin_lock_irqsave(&host->lock, flags);
376
377         if (host->runtime_suspended)
378                 goto out;
379
380         if (brightness == LED_OFF)
381                 __sdhci_led_deactivate(host);
382         else
383                 __sdhci_led_activate(host);
384 out:
385         spin_unlock_irqrestore(&host->lock, flags);
386 }
387
388 static int sdhci_led_register(struct sdhci_host *host)
389 {
390         struct mmc_host *mmc = host->mmc;
391
392         if (host->quirks & SDHCI_QUIRK_NO_LED)
393                 return 0;
394
395         snprintf(host->led_name, sizeof(host->led_name),
396                  "%s::", mmc_hostname(mmc));
397
398         host->led.name = host->led_name;
399         host->led.brightness = LED_OFF;
400         host->led.default_trigger = mmc_hostname(mmc);
401         host->led.brightness_set = sdhci_led_control;
402
403         return led_classdev_register(mmc_dev(mmc), &host->led);
404 }
405
406 static void sdhci_led_unregister(struct sdhci_host *host)
407 {
408         if (host->quirks & SDHCI_QUIRK_NO_LED)
409                 return;
410
411         led_classdev_unregister(&host->led);
412 }
413
414 static inline void sdhci_led_activate(struct sdhci_host *host)
415 {
416 }
417
418 static inline void sdhci_led_deactivate(struct sdhci_host *host)
419 {
420 }
421
422 #else
423
424 static inline int sdhci_led_register(struct sdhci_host *host)
425 {
426         return 0;
427 }
428
429 static inline void sdhci_led_unregister(struct sdhci_host *host)
430 {
431 }
432
433 static inline void sdhci_led_activate(struct sdhci_host *host)
434 {
435         __sdhci_led_activate(host);
436 }
437
438 static inline void sdhci_led_deactivate(struct sdhci_host *host)
439 {
440         __sdhci_led_deactivate(host);
441 }
442
443 #endif
444
445 static void sdhci_mod_timer(struct sdhci_host *host, struct mmc_request *mrq,
446                             unsigned long timeout)
447 {
448         if (sdhci_data_line_cmd(mrq->cmd))
449                 mod_timer(&host->data_timer, timeout);
450         else
451                 mod_timer(&host->timer, timeout);
452 }
453
454 static void sdhci_del_timer(struct sdhci_host *host, struct mmc_request *mrq)
455 {
456         if (sdhci_data_line_cmd(mrq->cmd))
457                 del_timer(&host->data_timer);
458         else
459                 del_timer(&host->timer);
460 }
461
462 static inline bool sdhci_has_requests(struct sdhci_host *host)
463 {
464         return host->cmd || host->data_cmd;
465 }
466
467 /*****************************************************************************\
468  *                                                                           *
469  * Core functions                                                            *
470  *                                                                           *
471 \*****************************************************************************/
472
473 static void sdhci_read_block_pio(struct sdhci_host *host)
474 {
475         unsigned long flags;
476         size_t blksize, len, chunk;
477         u32 uninitialized_var(scratch);
478         u8 *buf;
479
480         DBG("PIO reading\n");
481
482         blksize = host->data->blksz;
483         chunk = 0;
484
485         local_irq_save(flags);
486
487         while (blksize) {
488                 BUG_ON(!sg_miter_next(&host->sg_miter));
489
490                 len = min(host->sg_miter.length, blksize);
491
492                 blksize -= len;
493                 host->sg_miter.consumed = len;
494
495                 buf = host->sg_miter.addr;
496
497                 while (len) {
498                         if (chunk == 0) {
499                                 scratch = sdhci_readl(host, SDHCI_BUFFER);
500                                 chunk = 4;
501                         }
502
503                         *buf = scratch & 0xFF;
504
505                         buf++;
506                         scratch >>= 8;
507                         chunk--;
508                         len--;
509                 }
510         }
511
512         sg_miter_stop(&host->sg_miter);
513
514         local_irq_restore(flags);
515 }
516
517 static void sdhci_write_block_pio(struct sdhci_host *host)
518 {
519         unsigned long flags;
520         size_t blksize, len, chunk;
521         u32 scratch;
522         u8 *buf;
523
524         DBG("PIO writing\n");
525
526         blksize = host->data->blksz;
527         chunk = 0;
528         scratch = 0;
529
530         local_irq_save(flags);
531
532         while (blksize) {
533                 BUG_ON(!sg_miter_next(&host->sg_miter));
534
535                 len = min(host->sg_miter.length, blksize);
536
537                 blksize -= len;
538                 host->sg_miter.consumed = len;
539
540                 buf = host->sg_miter.addr;
541
542                 while (len) {
543                         scratch |= (u32)*buf << (chunk * 8);
544
545                         buf++;
546                         chunk++;
547                         len--;
548
549                         if ((chunk == 4) || ((len == 0) && (blksize == 0))) {
550                                 sdhci_writel(host, scratch, SDHCI_BUFFER);
551                                 chunk = 0;
552                                 scratch = 0;
553                         }
554                 }
555         }
556
557         sg_miter_stop(&host->sg_miter);
558
559         local_irq_restore(flags);
560 }
561
562 static void sdhci_transfer_pio(struct sdhci_host *host)
563 {
564         u32 mask;
565
566         if (host->blocks == 0)
567                 return;
568
569         if (host->data->flags & MMC_DATA_READ)
570                 mask = SDHCI_DATA_AVAILABLE;
571         else
572                 mask = SDHCI_SPACE_AVAILABLE;
573
574         /*
575          * Some controllers (JMicron JMB38x) mess up the buffer bits
576          * for transfers < 4 bytes. As long as it is just one block,
577          * we can ignore the bits.
578          */
579         if ((host->quirks & SDHCI_QUIRK_BROKEN_SMALL_PIO) &&
580                 (host->data->blocks == 1))
581                 mask = ~0;
582
583         while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
584                 if (host->quirks & SDHCI_QUIRK_PIO_NEEDS_DELAY)
585                         udelay(100);
586
587                 if (host->data->flags & MMC_DATA_READ)
588                         sdhci_read_block_pio(host);
589                 else
590                         sdhci_write_block_pio(host);
591
592                 host->blocks--;
593                 if (host->blocks == 0)
594                         break;
595         }
596
597         DBG("PIO transfer complete.\n");
598 }
599
600 static int sdhci_pre_dma_transfer(struct sdhci_host *host,
601                                   struct mmc_data *data, int cookie)
602 {
603         int sg_count;
604
605         /*
606          * If the data buffers are already mapped, return the previous
607          * dma_map_sg() result.
608          */
609         if (data->host_cookie == COOKIE_PRE_MAPPED)
610                 return data->sg_count;
611
612         /* Bounce write requests to the bounce buffer */
613         if (host->bounce_buffer) {
614                 unsigned int length = data->blksz * data->blocks;
615
616                 if (length > host->bounce_buffer_size) {
617                         pr_err("%s: asked for transfer of %u bytes exceeds bounce buffer %u bytes\n",
618                                mmc_hostname(host->mmc), length,
619                                host->bounce_buffer_size);
620                         return -EIO;
621                 }
622                 if (mmc_get_dma_dir(data) == DMA_TO_DEVICE) {
623                         /* Copy the data to the bounce buffer */
624                         sg_copy_to_buffer(data->sg, data->sg_len,
625                                           host->bounce_buffer,
626                                           length);
627                 }
628                 /* Switch ownership to the DMA */
629                 dma_sync_single_for_device(host->mmc->parent,
630                                            host->bounce_addr,
631                                            host->bounce_buffer_size,
632                                            mmc_get_dma_dir(data));
633                 /* Just a dummy value */
634                 sg_count = 1;
635         } else {
636                 /* Just access the data directly from memory */
637                 sg_count = dma_map_sg(mmc_dev(host->mmc),
638                                       data->sg, data->sg_len,
639                                       mmc_get_dma_dir(data));
640         }
641
642         if (sg_count == 0)
643                 return -ENOSPC;
644
645         data->sg_count = sg_count;
646         data->host_cookie = cookie;
647
648         return sg_count;
649 }
650
651 static char *sdhci_kmap_atomic(struct scatterlist *sg, unsigned long *flags)
652 {
653         local_irq_save(*flags);
654         return kmap_atomic(sg_page(sg)) + sg->offset;
655 }
656
657 static void sdhci_kunmap_atomic(void *buffer, unsigned long *flags)
658 {
659         kunmap_atomic(buffer);
660         local_irq_restore(*flags);
661 }
662
663 void sdhci_adma_write_desc(struct sdhci_host *host, void **desc,
664                            dma_addr_t addr, int len, unsigned int cmd)
665 {
666         struct sdhci_adma2_64_desc *dma_desc = *desc;
667
668         /* 32-bit and 64-bit descriptors have these members in same position */
669         dma_desc->cmd = cpu_to_le16(cmd);
670         dma_desc->len = cpu_to_le16(len);
671         dma_desc->addr_lo = cpu_to_le32((u32)addr);
672
673         if (host->flags & SDHCI_USE_64_BIT_DMA)
674                 dma_desc->addr_hi = cpu_to_le32((u64)addr >> 32);
675
676         *desc += host->desc_sz;
677 }
678 EXPORT_SYMBOL_GPL(sdhci_adma_write_desc);
679
680 static inline void __sdhci_adma_write_desc(struct sdhci_host *host,
681                                            void **desc, dma_addr_t addr,
682                                            int len, unsigned int cmd)
683 {
684         if (host->ops->adma_write_desc)
685                 host->ops->adma_write_desc(host, desc, addr, len, cmd);
686         else
687                 sdhci_adma_write_desc(host, desc, addr, len, cmd);
688 }
689
690 static void sdhci_adma_mark_end(void *desc)
691 {
692         struct sdhci_adma2_64_desc *dma_desc = desc;
693
694         /* 32-bit and 64-bit descriptors have 'cmd' in same position */
695         dma_desc->cmd |= cpu_to_le16(ADMA2_END);
696 }
697
698 static void sdhci_adma_table_pre(struct sdhci_host *host,
699         struct mmc_data *data, int sg_count)
700 {
701         struct scatterlist *sg;
702         unsigned long flags;
703         dma_addr_t addr, align_addr;
704         void *desc, *align;
705         char *buffer;
706         int len, offset, i;
707
708         /*
709          * The spec does not specify endianness of descriptor table.
710          * We currently guess that it is LE.
711          */
712
713         host->sg_count = sg_count;
714
715         desc = host->adma_table;
716         align = host->align_buffer;
717
718         align_addr = host->align_addr;
719
720         for_each_sg(data->sg, sg, host->sg_count, i) {
721                 addr = sg_dma_address(sg);
722                 len = sg_dma_len(sg);
723
724                 /*
725                  * The SDHCI specification states that ADMA addresses must
726                  * be 32-bit aligned. If they aren't, then we use a bounce
727                  * buffer for the (up to three) bytes that screw up the
728                  * alignment.
729                  */
730                 offset = (SDHCI_ADMA2_ALIGN - (addr & SDHCI_ADMA2_MASK)) &
731                          SDHCI_ADMA2_MASK;
732                 if (offset) {
733                         if (data->flags & MMC_DATA_WRITE) {
734                                 buffer = sdhci_kmap_atomic(sg, &flags);
735                                 memcpy(align, buffer, offset);
736                                 sdhci_kunmap_atomic(buffer, &flags);
737                         }
738
739                         /* tran, valid */
740                         __sdhci_adma_write_desc(host, &desc, align_addr,
741                                                 offset, ADMA2_TRAN_VALID);
742
743                         BUG_ON(offset > 65536);
744
745                         align += SDHCI_ADMA2_ALIGN;
746                         align_addr += SDHCI_ADMA2_ALIGN;
747
748                         addr += offset;
749                         len -= offset;
750                 }
751
752                 BUG_ON(len > 65536);
753
754                 /* tran, valid */
755                 if (len)
756                         __sdhci_adma_write_desc(host, &desc, addr, len,
757                                                 ADMA2_TRAN_VALID);
758
759                 /*
760                  * If this triggers then we have a calculation bug
761                  * somewhere. :/
762                  */
763                 WARN_ON((desc - host->adma_table) >= host->adma_table_sz);
764         }
765
766         if (host->quirks & SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC) {
767                 /* Mark the last descriptor as the terminating descriptor */
768                 if (desc != host->adma_table) {
769                         desc -= host->desc_sz;
770                         sdhci_adma_mark_end(desc);
771                 }
772         } else {
773                 /* Add a terminating entry - nop, end, valid */
774                 __sdhci_adma_write_desc(host, &desc, 0, 0, ADMA2_NOP_END_VALID);
775         }
776 }
777
778 static void sdhci_adma_table_post(struct sdhci_host *host,
779         struct mmc_data *data)
780 {
781         struct scatterlist *sg;
782         int i, size;
783         void *align;
784         char *buffer;
785         unsigned long flags;
786
787         if (data->flags & MMC_DATA_READ) {
788                 bool has_unaligned = false;
789
790                 /* Do a quick scan of the SG list for any unaligned mappings */
791                 for_each_sg(data->sg, sg, host->sg_count, i)
792                         if (sg_dma_address(sg) & SDHCI_ADMA2_MASK) {
793                                 has_unaligned = true;
794                                 break;
795                         }
796
797                 if (has_unaligned) {
798                         dma_sync_sg_for_cpu(mmc_dev(host->mmc), data->sg,
799                                             data->sg_len, DMA_FROM_DEVICE);
800
801                         align = host->align_buffer;
802
803                         for_each_sg(data->sg, sg, host->sg_count, i) {
804                                 if (sg_dma_address(sg) & SDHCI_ADMA2_MASK) {
805                                         size = SDHCI_ADMA2_ALIGN -
806                                                (sg_dma_address(sg) & SDHCI_ADMA2_MASK);
807
808                                         buffer = sdhci_kmap_atomic(sg, &flags);
809                                         memcpy(buffer, align, size);
810                                         sdhci_kunmap_atomic(buffer, &flags);
811
812                                         align += SDHCI_ADMA2_ALIGN;
813                                 }
814                         }
815                 }
816         }
817 }
818
819 static dma_addr_t sdhci_sdma_address(struct sdhci_host *host)
820 {
821         if (host->bounce_buffer)
822                 return host->bounce_addr;
823         else
824                 return sg_dma_address(host->data->sg);
825 }
826
827 static void sdhci_set_sdma_addr(struct sdhci_host *host, dma_addr_t addr)
828 {
829         if (host->v4_mode) {
830                 sdhci_writel(host, addr, SDHCI_ADMA_ADDRESS);
831                 if (host->flags & SDHCI_USE_64_BIT_DMA)
832                         sdhci_writel(host, (u64)addr >> 32, SDHCI_ADMA_ADDRESS_HI);
833         } else {
834                 sdhci_writel(host, addr, SDHCI_DMA_ADDRESS);
835         }
836 }
837
838 static unsigned int sdhci_target_timeout(struct sdhci_host *host,
839                                          struct mmc_command *cmd,
840                                          struct mmc_data *data)
841 {
842         unsigned int target_timeout;
843
844         /* timeout in us */
845         if (!data) {
846                 target_timeout = cmd->busy_timeout * 1000;
847         } else {
848                 target_timeout = DIV_ROUND_UP(data->timeout_ns, 1000);
849                 if (host->clock && data->timeout_clks) {
850                         unsigned long long val;
851
852                         /*
853                          * data->timeout_clks is in units of clock cycles.
854                          * host->clock is in Hz.  target_timeout is in us.
855                          * Hence, us = 1000000 * cycles / Hz.  Round up.
856                          */
857                         val = 1000000ULL * data->timeout_clks;
858                         if (do_div(val, host->clock))
859                                 target_timeout++;
860                         target_timeout += val;
861                 }
862         }
863
864         return target_timeout;
865 }
866
867 static void sdhci_calc_sw_timeout(struct sdhci_host *host,
868                                   struct mmc_command *cmd)
869 {
870         struct mmc_data *data = cmd->data;
871         struct mmc_host *mmc = host->mmc;
872         struct mmc_ios *ios = &mmc->ios;
873         unsigned char bus_width = 1 << ios->bus_width;
874         unsigned int blksz;
875         unsigned int freq;
876         u64 target_timeout;
877         u64 transfer_time;
878
879         target_timeout = sdhci_target_timeout(host, cmd, data);
880         target_timeout *= NSEC_PER_USEC;
881
882         if (data) {
883                 blksz = data->blksz;
884                 freq = host->mmc->actual_clock ? : host->clock;
885                 transfer_time = (u64)blksz * NSEC_PER_SEC * (8 / bus_width);
886                 do_div(transfer_time, freq);
887                 /* multiply by '2' to account for any unknowns */
888                 transfer_time = transfer_time * 2;
889                 /* calculate timeout for the entire data */
890                 host->data_timeout = data->blocks * target_timeout +
891                                      transfer_time;
892         } else {
893                 host->data_timeout = target_timeout;
894         }
895
896         if (host->data_timeout)
897                 host->data_timeout += MMC_CMD_TRANSFER_TIME;
898 }
899
900 static u8 sdhci_calc_timeout(struct sdhci_host *host, struct mmc_command *cmd,
901                              bool *too_big)
902 {
903         u8 count;
904         struct mmc_data *data;
905         unsigned target_timeout, current_timeout;
906
907         *too_big = true;
908
909         /*
910          * If the host controller provides us with an incorrect timeout
911          * value, just skip the check and use 0xE.  The hardware may take
912          * longer to time out, but that's much better than having a too-short
913          * timeout value.
914          */
915         if (host->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL)
916                 return 0xE;
917
918         /* Unspecified command, asume max */
919         if (cmd == NULL)
920                 return 0xE;
921
922         data = cmd->data;
923         /* Unspecified timeout, assume max */
924         if (!data && !cmd->busy_timeout)
925                 return 0xE;
926
927         /* timeout in us */
928         target_timeout = sdhci_target_timeout(host, cmd, data);
929
930         /*
931          * Figure out needed cycles.
932          * We do this in steps in order to fit inside a 32 bit int.
933          * The first step is the minimum timeout, which will have a
934          * minimum resolution of 6 bits:
935          * (1) 2^13*1000 > 2^22,
936          * (2) host->timeout_clk < 2^16
937          *     =>
938          *     (1) / (2) > 2^6
939          */
940         count = 0;
941         current_timeout = (1 << 13) * 1000 / host->timeout_clk;
942         while (current_timeout < target_timeout) {
943                 count++;
944                 current_timeout <<= 1;
945                 if (count >= 0xF)
946                         break;
947         }
948
949         if (count >= 0xF) {
950                 if (!(host->quirks2 & SDHCI_QUIRK2_DISABLE_HW_TIMEOUT))
951                         DBG("Too large timeout 0x%x requested for CMD%d!\n",
952                             count, cmd->opcode);
953                 count = 0xE;
954         } else {
955                 *too_big = false;
956         }
957
958         return count;
959 }
960
961 static void sdhci_set_transfer_irqs(struct sdhci_host *host)
962 {
963         u32 pio_irqs = SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL;
964         u32 dma_irqs = SDHCI_INT_DMA_END | SDHCI_INT_ADMA_ERROR;
965
966         if (host->flags & SDHCI_REQ_USE_DMA)
967                 host->ier = (host->ier & ~pio_irqs) | dma_irqs;
968         else
969                 host->ier = (host->ier & ~dma_irqs) | pio_irqs;
970
971         if (host->flags & (SDHCI_AUTO_CMD23 | SDHCI_AUTO_CMD12))
972                 host->ier |= SDHCI_INT_AUTO_CMD_ERR;
973         else
974                 host->ier &= ~SDHCI_INT_AUTO_CMD_ERR;
975
976         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
977         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
978 }
979
980 static void sdhci_set_data_timeout_irq(struct sdhci_host *host, bool enable)
981 {
982         if (enable)
983                 host->ier |= SDHCI_INT_DATA_TIMEOUT;
984         else
985                 host->ier &= ~SDHCI_INT_DATA_TIMEOUT;
986         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
987         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
988 }
989
990 static void sdhci_set_timeout(struct sdhci_host *host, struct mmc_command *cmd)
991 {
992         u8 count;
993
994         if (host->ops->set_timeout) {
995                 host->ops->set_timeout(host, cmd);
996         } else {
997                 bool too_big = false;
998
999                 count = sdhci_calc_timeout(host, cmd, &too_big);
1000
1001                 if (too_big &&
1002                     host->quirks2 & SDHCI_QUIRK2_DISABLE_HW_TIMEOUT) {
1003                         sdhci_calc_sw_timeout(host, cmd);
1004                         sdhci_set_data_timeout_irq(host, false);
1005                 } else if (!(host->ier & SDHCI_INT_DATA_TIMEOUT)) {
1006                         sdhci_set_data_timeout_irq(host, true);
1007                 }
1008
1009                 sdhci_writeb(host, count, SDHCI_TIMEOUT_CONTROL);
1010         }
1011 }
1012
1013 static void sdhci_prepare_data(struct sdhci_host *host, struct mmc_command *cmd)
1014 {
1015         struct mmc_data *data = cmd->data;
1016
1017         host->data_timeout = 0;
1018
1019         if (sdhci_data_line_cmd(cmd))
1020                 sdhci_set_timeout(host, cmd);
1021
1022         if (!data)
1023                 return;
1024
1025         WARN_ON(host->data);
1026
1027         /* Sanity checks */
1028         BUG_ON(data->blksz * data->blocks > 524288);
1029         BUG_ON(data->blksz > host->mmc->max_blk_size);
1030         BUG_ON(data->blocks > 65535);
1031
1032         host->data = data;
1033         host->data_early = 0;
1034         host->data->bytes_xfered = 0;
1035
1036         if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
1037                 struct scatterlist *sg;
1038                 unsigned int length_mask, offset_mask;
1039                 int i;
1040
1041                 host->flags |= SDHCI_REQ_USE_DMA;
1042
1043                 /*
1044                  * FIXME: This doesn't account for merging when mapping the
1045                  * scatterlist.
1046                  *
1047                  * The assumption here being that alignment and lengths are
1048                  * the same after DMA mapping to device address space.
1049                  */
1050                 length_mask = 0;
1051                 offset_mask = 0;
1052                 if (host->flags & SDHCI_USE_ADMA) {
1053                         if (host->quirks & SDHCI_QUIRK_32BIT_ADMA_SIZE) {
1054                                 length_mask = 3;
1055                                 /*
1056                                  * As we use up to 3 byte chunks to work
1057                                  * around alignment problems, we need to
1058                                  * check the offset as well.
1059                                  */
1060                                 offset_mask = 3;
1061                         }
1062                 } else {
1063                         if (host->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE)
1064                                 length_mask = 3;
1065                         if (host->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR)
1066                                 offset_mask = 3;
1067                 }
1068
1069                 if (unlikely(length_mask | offset_mask)) {
1070                         for_each_sg(data->sg, sg, data->sg_len, i) {
1071                                 if (sg->length & length_mask) {
1072                                         DBG("Reverting to PIO because of transfer size (%d)\n",
1073                                             sg->length);
1074                                         host->flags &= ~SDHCI_REQ_USE_DMA;
1075                                         break;
1076                                 }
1077                                 if (sg->offset & offset_mask) {
1078                                         DBG("Reverting to PIO because of bad alignment\n");
1079                                         host->flags &= ~SDHCI_REQ_USE_DMA;
1080                                         break;
1081                                 }
1082                         }
1083                 }
1084         }
1085
1086         if (host->flags & SDHCI_REQ_USE_DMA) {
1087                 int sg_cnt = sdhci_pre_dma_transfer(host, data, COOKIE_MAPPED);
1088
1089                 if (sg_cnt <= 0) {
1090                         /*
1091                          * This only happens when someone fed
1092                          * us an invalid request.
1093                          */
1094                         WARN_ON(1);
1095                         host->flags &= ~SDHCI_REQ_USE_DMA;
1096                 } else if (host->flags & SDHCI_USE_ADMA) {
1097                         sdhci_adma_table_pre(host, data, sg_cnt);
1098
1099                         sdhci_writel(host, host->adma_addr, SDHCI_ADMA_ADDRESS);
1100                         if (host->flags & SDHCI_USE_64_BIT_DMA)
1101                                 sdhci_writel(host,
1102                                              (u64)host->adma_addr >> 32,
1103                                              SDHCI_ADMA_ADDRESS_HI);
1104                 } else {
1105                         WARN_ON(sg_cnt != 1);
1106                         sdhci_set_sdma_addr(host, sdhci_sdma_address(host));
1107                 }
1108         }
1109
1110         sdhci_config_dma(host);
1111
1112         if (!(host->flags & SDHCI_REQ_USE_DMA)) {
1113                 int flags;
1114
1115                 flags = SG_MITER_ATOMIC;
1116                 if (host->data->flags & MMC_DATA_READ)
1117                         flags |= SG_MITER_TO_SG;
1118                 else
1119                         flags |= SG_MITER_FROM_SG;
1120                 sg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags);
1121                 host->blocks = data->blocks;
1122         }
1123
1124         sdhci_set_transfer_irqs(host);
1125
1126         /* Set the DMA boundary value and block size */
1127         sdhci_writew(host, SDHCI_MAKE_BLKSZ(host->sdma_boundary, data->blksz),
1128                      SDHCI_BLOCK_SIZE);
1129
1130         /*
1131          * For Version 4.10 onwards, if v4 mode is enabled, 32-bit Block Count
1132          * can be supported, in that case 16-bit block count register must be 0.
1133          */
1134         if (host->version >= SDHCI_SPEC_410 && host->v4_mode &&
1135             (host->quirks2 & SDHCI_QUIRK2_USE_32BIT_BLK_CNT)) {
1136                 if (sdhci_readw(host, SDHCI_BLOCK_COUNT))
1137                         sdhci_writew(host, 0, SDHCI_BLOCK_COUNT);
1138                 sdhci_writew(host, data->blocks, SDHCI_32BIT_BLK_CNT);
1139         } else {
1140                 sdhci_writew(host, data->blocks, SDHCI_BLOCK_COUNT);
1141         }
1142 }
1143
1144 static inline bool sdhci_auto_cmd12(struct sdhci_host *host,
1145                                     struct mmc_request *mrq)
1146 {
1147         return !mrq->sbc && (host->flags & SDHCI_AUTO_CMD12) &&
1148                !mrq->cap_cmd_during_tfr;
1149 }
1150
1151 static inline void sdhci_auto_cmd_select(struct sdhci_host *host,
1152                                          struct mmc_command *cmd,
1153                                          u16 *mode)
1154 {
1155         bool use_cmd12 = sdhci_auto_cmd12(host, cmd->mrq) &&
1156                          (cmd->opcode != SD_IO_RW_EXTENDED);
1157         bool use_cmd23 = cmd->mrq->sbc && (host->flags & SDHCI_AUTO_CMD23);
1158         u16 ctrl2;
1159
1160         /*
1161          * In case of Version 4.10 or later, use of 'Auto CMD Auto
1162          * Select' is recommended rather than use of 'Auto CMD12
1163          * Enable' or 'Auto CMD23 Enable'.
1164          */
1165         if (host->version >= SDHCI_SPEC_410 && (use_cmd12 || use_cmd23)) {
1166                 *mode |= SDHCI_TRNS_AUTO_SEL;
1167
1168                 ctrl2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1169                 if (use_cmd23)
1170                         ctrl2 |= SDHCI_CMD23_ENABLE;
1171                 else
1172                         ctrl2 &= ~SDHCI_CMD23_ENABLE;
1173                 sdhci_writew(host, ctrl2, SDHCI_HOST_CONTROL2);
1174
1175                 return;
1176         }
1177
1178         /*
1179          * If we are sending CMD23, CMD12 never gets sent
1180          * on successful completion (so no Auto-CMD12).
1181          */
1182         if (use_cmd12)
1183                 *mode |= SDHCI_TRNS_AUTO_CMD12;
1184         else if (use_cmd23)
1185                 *mode |= SDHCI_TRNS_AUTO_CMD23;
1186 }
1187
1188 static void sdhci_set_transfer_mode(struct sdhci_host *host,
1189         struct mmc_command *cmd)
1190 {
1191         u16 mode = 0;
1192         struct mmc_data *data = cmd->data;
1193
1194         if (data == NULL) {
1195                 if (host->quirks2 &
1196                         SDHCI_QUIRK2_CLEAR_TRANSFERMODE_REG_BEFORE_CMD) {
1197                         /* must not clear SDHCI_TRANSFER_MODE when tuning */
1198                         if (cmd->opcode != MMC_SEND_TUNING_BLOCK_HS200)
1199                                 sdhci_writew(host, 0x0, SDHCI_TRANSFER_MODE);
1200                 } else {
1201                 /* clear Auto CMD settings for no data CMDs */
1202                         mode = sdhci_readw(host, SDHCI_TRANSFER_MODE);
1203                         sdhci_writew(host, mode & ~(SDHCI_TRNS_AUTO_CMD12 |
1204                                 SDHCI_TRNS_AUTO_CMD23), SDHCI_TRANSFER_MODE);
1205                 }
1206                 return;
1207         }
1208
1209         WARN_ON(!host->data);
1210
1211         if (!(host->quirks2 & SDHCI_QUIRK2_SUPPORT_SINGLE))
1212                 mode = SDHCI_TRNS_BLK_CNT_EN;
1213
1214         if (mmc_op_multi(cmd->opcode) || data->blocks > 1) {
1215                 mode = SDHCI_TRNS_BLK_CNT_EN | SDHCI_TRNS_MULTI;
1216                 sdhci_auto_cmd_select(host, cmd, &mode);
1217                 if (cmd->mrq->sbc && (host->flags & SDHCI_AUTO_CMD23))
1218                         sdhci_writel(host, cmd->mrq->sbc->arg, SDHCI_ARGUMENT2);
1219         }
1220
1221         if (data->flags & MMC_DATA_READ)
1222                 mode |= SDHCI_TRNS_READ;
1223         if (host->flags & SDHCI_REQ_USE_DMA)
1224                 mode |= SDHCI_TRNS_DMA;
1225
1226         sdhci_writew(host, mode, SDHCI_TRANSFER_MODE);
1227 }
1228
1229 static bool sdhci_needs_reset(struct sdhci_host *host, struct mmc_request *mrq)
1230 {
1231         return (!(host->flags & SDHCI_DEVICE_DEAD) &&
1232                 ((mrq->cmd && mrq->cmd->error) ||
1233                  (mrq->sbc && mrq->sbc->error) ||
1234                  (mrq->data && mrq->data->stop && mrq->data->stop->error) ||
1235                  (host->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)));
1236 }
1237
1238 static void __sdhci_finish_mrq(struct sdhci_host *host, struct mmc_request *mrq)
1239 {
1240         int i;
1241
1242         if (host->cmd && host->cmd->mrq == mrq)
1243                 host->cmd = NULL;
1244
1245         if (host->data_cmd && host->data_cmd->mrq == mrq)
1246                 host->data_cmd = NULL;
1247
1248         if (host->data && host->data->mrq == mrq)
1249                 host->data = NULL;
1250
1251         if (sdhci_needs_reset(host, mrq))
1252                 host->pending_reset = true;
1253
1254         for (i = 0; i < SDHCI_MAX_MRQS; i++) {
1255                 if (host->mrqs_done[i] == mrq) {
1256                         WARN_ON(1);
1257                         return;
1258                 }
1259         }
1260
1261         for (i = 0; i < SDHCI_MAX_MRQS; i++) {
1262                 if (!host->mrqs_done[i]) {
1263                         host->mrqs_done[i] = mrq;
1264                         break;
1265                 }
1266         }
1267
1268         WARN_ON(i >= SDHCI_MAX_MRQS);
1269
1270         sdhci_del_timer(host, mrq);
1271
1272         if (!sdhci_has_requests(host))
1273                 sdhci_led_deactivate(host);
1274 }
1275
1276 static void sdhci_finish_mrq(struct sdhci_host *host, struct mmc_request *mrq)
1277 {
1278         __sdhci_finish_mrq(host, mrq);
1279
1280         queue_work(host->complete_wq, &host->complete_work);
1281 }
1282
1283 static void sdhci_finish_data(struct sdhci_host *host)
1284 {
1285         struct mmc_command *data_cmd = host->data_cmd;
1286         struct mmc_data *data = host->data;
1287
1288         host->data = NULL;
1289         host->data_cmd = NULL;
1290
1291         /*
1292          * The controller needs a reset of internal state machines upon error
1293          * conditions.
1294          */
1295         if (data->error) {
1296                 if (!host->cmd || host->cmd == data_cmd)
1297                         sdhci_do_reset(host, SDHCI_RESET_CMD);
1298                 sdhci_do_reset(host, SDHCI_RESET_DATA);
1299         }
1300
1301         if ((host->flags & (SDHCI_REQ_USE_DMA | SDHCI_USE_ADMA)) ==
1302             (SDHCI_REQ_USE_DMA | SDHCI_USE_ADMA))
1303                 sdhci_adma_table_post(host, data);
1304
1305         /*
1306          * The specification states that the block count register must
1307          * be updated, but it does not specify at what point in the
1308          * data flow. That makes the register entirely useless to read
1309          * back so we have to assume that nothing made it to the card
1310          * in the event of an error.
1311          */
1312         if (data->error)
1313                 data->bytes_xfered = 0;
1314         else
1315                 data->bytes_xfered = data->blksz * data->blocks;
1316
1317         /*
1318          * Need to send CMD12 if -
1319          * a) open-ended multiblock transfer (no CMD23)
1320          * b) error in multiblock transfer
1321          */
1322         if (data->stop &&
1323             (data->error ||
1324              !data->mrq->sbc)) {
1325                 /*
1326                  * 'cap_cmd_during_tfr' request must not use the command line
1327                  * after mmc_command_done() has been called. It is upper layer's
1328                  * responsibility to send the stop command if required.
1329                  */
1330                 if (data->mrq->cap_cmd_during_tfr) {
1331                         __sdhci_finish_mrq(host, data->mrq);
1332                 } else {
1333                         /* Avoid triggering warning in sdhci_send_command() */
1334                         host->cmd = NULL;
1335                         sdhci_send_command(host, data->stop);
1336                 }
1337         } else {
1338                 __sdhci_finish_mrq(host, data->mrq);
1339         }
1340 }
1341
1342 void sdhci_send_command(struct sdhci_host *host, struct mmc_command *cmd)
1343 {
1344         int flags;
1345         u32 mask;
1346         unsigned long timeout;
1347
1348         WARN_ON(host->cmd);
1349
1350         /* Initially, a command has no error */
1351         cmd->error = 0;
1352
1353         if ((host->quirks2 & SDHCI_QUIRK2_STOP_WITH_TC) &&
1354             cmd->opcode == MMC_STOP_TRANSMISSION)
1355                 cmd->flags |= MMC_RSP_BUSY;
1356
1357         /* Wait max 10 ms */
1358         timeout = 10;
1359
1360         mask = SDHCI_CMD_INHIBIT;
1361         if (sdhci_data_line_cmd(cmd))
1362                 mask |= SDHCI_DATA_INHIBIT;
1363
1364         /* We shouldn't wait for data inihibit for stop commands, even
1365            though they might use busy signaling */
1366         if (cmd->mrq->data && (cmd == cmd->mrq->data->stop))
1367                 mask &= ~SDHCI_DATA_INHIBIT;
1368
1369         while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
1370                 if (timeout == 0) {
1371                         pr_err("%s: Controller never released inhibit bit(s).\n",
1372                                mmc_hostname(host->mmc));
1373                         sdhci_dumpregs(host);
1374                         cmd->error = -EIO;
1375                         sdhci_finish_mrq(host, cmd->mrq);
1376                         return;
1377                 }
1378                 timeout--;
1379                 mdelay(1);
1380         }
1381
1382         host->cmd = cmd;
1383         if (sdhci_data_line_cmd(cmd)) {
1384                 WARN_ON(host->data_cmd);
1385                 host->data_cmd = cmd;
1386         }
1387
1388         sdhci_prepare_data(host, cmd);
1389
1390         sdhci_writel(host, cmd->arg, SDHCI_ARGUMENT);
1391
1392         sdhci_set_transfer_mode(host, cmd);
1393
1394         if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
1395                 pr_err("%s: Unsupported response type!\n",
1396                         mmc_hostname(host->mmc));
1397                 cmd->error = -EINVAL;
1398                 sdhci_finish_mrq(host, cmd->mrq);
1399                 return;
1400         }
1401
1402         if (!(cmd->flags & MMC_RSP_PRESENT))
1403                 flags = SDHCI_CMD_RESP_NONE;
1404         else if (cmd->flags & MMC_RSP_136)
1405                 flags = SDHCI_CMD_RESP_LONG;
1406         else if (cmd->flags & MMC_RSP_BUSY)
1407                 flags = SDHCI_CMD_RESP_SHORT_BUSY;
1408         else
1409                 flags = SDHCI_CMD_RESP_SHORT;
1410
1411         if (cmd->flags & MMC_RSP_CRC)
1412                 flags |= SDHCI_CMD_CRC;
1413         if (cmd->flags & MMC_RSP_OPCODE)
1414                 flags |= SDHCI_CMD_INDEX;
1415
1416         /* CMD19 is special in that the Data Present Select should be set */
1417         if (cmd->data || cmd->opcode == MMC_SEND_TUNING_BLOCK ||
1418             cmd->opcode == MMC_SEND_TUNING_BLOCK_HS200)
1419                 flags |= SDHCI_CMD_DATA;
1420
1421         timeout = jiffies;
1422         if (host->data_timeout)
1423                 timeout += nsecs_to_jiffies(host->data_timeout);
1424         else if (!cmd->data && cmd->busy_timeout > 9000)
1425                 timeout += DIV_ROUND_UP(cmd->busy_timeout, 1000) * HZ + HZ;
1426         else
1427                 timeout += 10 * HZ;
1428         sdhci_mod_timer(host, cmd->mrq, timeout);
1429
1430         sdhci_writew(host, SDHCI_MAKE_CMD(cmd->opcode, flags), SDHCI_COMMAND);
1431 }
1432 EXPORT_SYMBOL_GPL(sdhci_send_command);
1433
1434 static void sdhci_read_rsp_136(struct sdhci_host *host, struct mmc_command *cmd)
1435 {
1436         int i, reg;
1437
1438         for (i = 0; i < 4; i++) {
1439                 reg = SDHCI_RESPONSE + (3 - i) * 4;
1440                 cmd->resp[i] = sdhci_readl(host, reg);
1441         }
1442
1443         if (host->quirks2 & SDHCI_QUIRK2_RSP_136_HAS_CRC)
1444                 return;
1445
1446         /* CRC is stripped so we need to do some shifting */
1447         for (i = 0; i < 4; i++) {
1448                 cmd->resp[i] <<= 8;
1449                 if (i != 3)
1450                         cmd->resp[i] |= cmd->resp[i + 1] >> 24;
1451         }
1452 }
1453
1454 static void sdhci_finish_command(struct sdhci_host *host)
1455 {
1456         struct mmc_command *cmd = host->cmd;
1457
1458         host->cmd = NULL;
1459
1460         if (cmd->flags & MMC_RSP_PRESENT) {
1461                 if (cmd->flags & MMC_RSP_136) {
1462                         sdhci_read_rsp_136(host, cmd);
1463                 } else {
1464                         cmd->resp[0] = sdhci_readl(host, SDHCI_RESPONSE);
1465                 }
1466         }
1467
1468         if (cmd->mrq->cap_cmd_during_tfr && cmd == cmd->mrq->cmd)
1469                 mmc_command_done(host->mmc, cmd->mrq);
1470
1471         /*
1472          * The host can send and interrupt when the busy state has
1473          * ended, allowing us to wait without wasting CPU cycles.
1474          * The busy signal uses DAT0 so this is similar to waiting
1475          * for data to complete.
1476          *
1477          * Note: The 1.0 specification is a bit ambiguous about this
1478          *       feature so there might be some problems with older
1479          *       controllers.
1480          */
1481         if (cmd->flags & MMC_RSP_BUSY) {
1482                 if (cmd->data) {
1483                         DBG("Cannot wait for busy signal when also doing a data transfer");
1484                 } else if (!(host->quirks & SDHCI_QUIRK_NO_BUSY_IRQ) &&
1485                            cmd == host->data_cmd) {
1486                         /* Command complete before busy is ended */
1487                         return;
1488                 }
1489         }
1490
1491         /* Finished CMD23, now send actual command. */
1492         if (cmd == cmd->mrq->sbc) {
1493                 sdhci_send_command(host, cmd->mrq->cmd);
1494         } else {
1495
1496                 /* Processed actual command. */
1497                 if (host->data && host->data_early)
1498                         sdhci_finish_data(host);
1499
1500                 if (!cmd->data)
1501                         __sdhci_finish_mrq(host, cmd->mrq);
1502         }
1503 }
1504
1505 static u16 sdhci_get_preset_value(struct sdhci_host *host)
1506 {
1507         u16 preset = 0;
1508
1509         switch (host->timing) {
1510         case MMC_TIMING_UHS_SDR12:
1511                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR12);
1512                 break;
1513         case MMC_TIMING_UHS_SDR25:
1514                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR25);
1515                 break;
1516         case MMC_TIMING_UHS_SDR50:
1517                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR50);
1518                 break;
1519         case MMC_TIMING_UHS_SDR104:
1520         case MMC_TIMING_MMC_HS200:
1521                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR104);
1522                 break;
1523         case MMC_TIMING_UHS_DDR50:
1524         case MMC_TIMING_MMC_DDR52:
1525                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_DDR50);
1526                 break;
1527         case MMC_TIMING_MMC_HS400:
1528                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_HS400);
1529                 break;
1530         default:
1531                 pr_warn("%s: Invalid UHS-I mode selected\n",
1532                         mmc_hostname(host->mmc));
1533                 preset = sdhci_readw(host, SDHCI_PRESET_FOR_SDR12);
1534                 break;
1535         }
1536         return preset;
1537 }
1538
1539 u16 sdhci_calc_clk(struct sdhci_host *host, unsigned int clock,
1540                    unsigned int *actual_clock)
1541 {
1542         int div = 0; /* Initialized for compiler warning */
1543         int real_div = div, clk_mul = 1;
1544         u16 clk = 0;
1545         bool switch_base_clk = false;
1546
1547         if (host->version >= SDHCI_SPEC_300) {
1548                 if (host->preset_enabled) {
1549                         u16 pre_val;
1550
1551                         clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1552                         pre_val = sdhci_get_preset_value(host);
1553                         div = (pre_val & SDHCI_PRESET_SDCLK_FREQ_MASK)
1554                                 >> SDHCI_PRESET_SDCLK_FREQ_SHIFT;
1555                         if (host->clk_mul &&
1556                                 (pre_val & SDHCI_PRESET_CLKGEN_SEL_MASK)) {
1557                                 clk = SDHCI_PROG_CLOCK_MODE;
1558                                 real_div = div + 1;
1559                                 clk_mul = host->clk_mul;
1560                         } else {
1561                                 real_div = max_t(int, 1, div << 1);
1562                         }
1563                         goto clock_set;
1564                 }
1565
1566                 /*
1567                  * Check if the Host Controller supports Programmable Clock
1568                  * Mode.
1569                  */
1570                 if (host->clk_mul) {
1571                         for (div = 1; div <= 1024; div++) {
1572                                 if ((host->max_clk * host->clk_mul / div)
1573                                         <= clock)
1574                                         break;
1575                         }
1576                         if ((host->max_clk * host->clk_mul / div) <= clock) {
1577                                 /*
1578                                  * Set Programmable Clock Mode in the Clock
1579                                  * Control register.
1580                                  */
1581                                 clk = SDHCI_PROG_CLOCK_MODE;
1582                                 real_div = div;
1583                                 clk_mul = host->clk_mul;
1584                                 div--;
1585                         } else {
1586                                 /*
1587                                  * Divisor can be too small to reach clock
1588                                  * speed requirement. Then use the base clock.
1589                                  */
1590                                 switch_base_clk = true;
1591                         }
1592                 }
1593
1594                 if (!host->clk_mul || switch_base_clk) {
1595                         /* Version 3.00 divisors must be a multiple of 2. */
1596                         if (host->max_clk <= clock)
1597                                 div = 1;
1598                         else {
1599                                 for (div = 2; div < SDHCI_MAX_DIV_SPEC_300;
1600                                      div += 2) {
1601                                         if ((host->max_clk / div) <= clock)
1602                                                 break;
1603                                 }
1604                         }
1605                         real_div = div;
1606                         div >>= 1;
1607                         if ((host->quirks2 & SDHCI_QUIRK2_CLOCK_DIV_ZERO_BROKEN)
1608                                 && !div && host->max_clk <= 25000000)
1609                                 div = 1;
1610                 }
1611         } else {
1612                 /* Version 2.00 divisors must be a power of 2. */
1613                 for (div = 1; div < SDHCI_MAX_DIV_SPEC_200; div *= 2) {
1614                         if ((host->max_clk / div) <= clock)
1615                                 break;
1616                 }
1617                 real_div = div;
1618                 div >>= 1;
1619         }
1620
1621 clock_set:
1622         if (real_div)
1623                 *actual_clock = (host->max_clk * clk_mul) / real_div;
1624         clk |= (div & SDHCI_DIV_MASK) << SDHCI_DIVIDER_SHIFT;
1625         clk |= ((div & SDHCI_DIV_HI_MASK) >> SDHCI_DIV_MASK_LEN)
1626                 << SDHCI_DIVIDER_HI_SHIFT;
1627
1628         return clk;
1629 }
1630 EXPORT_SYMBOL_GPL(sdhci_calc_clk);
1631
1632 void sdhci_enable_clk(struct sdhci_host *host, u16 clk)
1633 {
1634         ktime_t timeout;
1635
1636         clk |= SDHCI_CLOCK_INT_EN;
1637         sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1638
1639         /* Wait max 20 ms */
1640         timeout = ktime_add_ms(ktime_get(), 20);
1641         while (1) {
1642                 bool timedout = ktime_after(ktime_get(), timeout);
1643
1644                 clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1645                 if (clk & SDHCI_CLOCK_INT_STABLE)
1646                         break;
1647                 if (timedout) {
1648                         pr_err("%s: Internal clock never stabilised.\n",
1649                                mmc_hostname(host->mmc));
1650                         sdhci_dumpregs(host);
1651                         return;
1652                 }
1653                 udelay(10);
1654         }
1655
1656         clk |= SDHCI_CLOCK_CARD_EN;
1657         sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1658 }
1659 EXPORT_SYMBOL_GPL(sdhci_enable_clk);
1660
1661 void sdhci_set_clock(struct sdhci_host *host, unsigned int clock)
1662 {
1663         u16 clk;
1664
1665         host->mmc->actual_clock = 0;
1666
1667         sdhci_writew(host, 0, SDHCI_CLOCK_CONTROL);
1668
1669         if (clock == 0)
1670                 return;
1671
1672         clk = sdhci_calc_clk(host, clock, &host->mmc->actual_clock);
1673         sdhci_enable_clk(host, clk);
1674 }
1675 EXPORT_SYMBOL_GPL(sdhci_set_clock);
1676
1677 static void sdhci_set_power_reg(struct sdhci_host *host, unsigned char mode,
1678                                 unsigned short vdd)
1679 {
1680         struct mmc_host *mmc = host->mmc;
1681
1682         mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, vdd);
1683
1684         if (mode != MMC_POWER_OFF)
1685                 sdhci_writeb(host, SDHCI_POWER_ON, SDHCI_POWER_CONTROL);
1686         else
1687                 sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
1688 }
1689
1690 void sdhci_set_power_noreg(struct sdhci_host *host, unsigned char mode,
1691                            unsigned short vdd)
1692 {
1693         u8 pwr = 0;
1694
1695         if (mode != MMC_POWER_OFF) {
1696                 switch (1 << vdd) {
1697                 case MMC_VDD_165_195:
1698                 /*
1699                  * Without a regulator, SDHCI does not support 2.0v
1700                  * so we only get here if the driver deliberately
1701                  * added the 2.0v range to ocr_avail. Map it to 1.8v
1702                  * for the purpose of turning on the power.
1703                  */
1704                 case MMC_VDD_20_21:
1705                         pwr = SDHCI_POWER_180;
1706                         break;
1707                 case MMC_VDD_29_30:
1708                 case MMC_VDD_30_31:
1709                         pwr = SDHCI_POWER_300;
1710                         break;
1711                 case MMC_VDD_32_33:
1712                 case MMC_VDD_33_34:
1713                         pwr = SDHCI_POWER_330;
1714                         break;
1715                 default:
1716                         WARN(1, "%s: Invalid vdd %#x\n",
1717                              mmc_hostname(host->mmc), vdd);
1718                         break;
1719                 }
1720         }
1721
1722         if (host->pwr == pwr)
1723                 return;
1724
1725         host->pwr = pwr;
1726
1727         if (pwr == 0) {
1728                 sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
1729                 if (host->quirks2 & SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON)
1730                         sdhci_runtime_pm_bus_off(host);
1731         } else {
1732                 /*
1733                  * Spec says that we should clear the power reg before setting
1734                  * a new value. Some controllers don't seem to like this though.
1735                  */
1736                 if (!(host->quirks & SDHCI_QUIRK_SINGLE_POWER_WRITE))
1737                         sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
1738
1739                 /*
1740                  * At least the Marvell CaFe chip gets confused if we set the
1741                  * voltage and set turn on power at the same time, so set the
1742                  * voltage first.
1743                  */
1744                 if (host->quirks & SDHCI_QUIRK_NO_SIMULT_VDD_AND_POWER)
1745                         sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
1746
1747                 pwr |= SDHCI_POWER_ON;
1748
1749                 sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
1750
1751                 if (host->quirks2 & SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON)
1752                         sdhci_runtime_pm_bus_on(host);
1753
1754                 /*
1755                  * Some controllers need an extra 10ms delay of 10ms before
1756                  * they can apply clock after applying power
1757                  */
1758                 if (host->quirks & SDHCI_QUIRK_DELAY_AFTER_POWER)
1759                         mdelay(10);
1760         }
1761 }
1762 EXPORT_SYMBOL_GPL(sdhci_set_power_noreg);
1763
1764 void sdhci_set_power(struct sdhci_host *host, unsigned char mode,
1765                      unsigned short vdd)
1766 {
1767         if (IS_ERR(host->mmc->supply.vmmc))
1768                 sdhci_set_power_noreg(host, mode, vdd);
1769         else
1770                 sdhci_set_power_reg(host, mode, vdd);
1771 }
1772 EXPORT_SYMBOL_GPL(sdhci_set_power);
1773
1774 /*****************************************************************************\
1775  *                                                                           *
1776  * MMC callbacks                                                             *
1777  *                                                                           *
1778 \*****************************************************************************/
1779
1780 void sdhci_request(struct mmc_host *mmc, struct mmc_request *mrq)
1781 {
1782         struct sdhci_host *host;
1783         int present;
1784         unsigned long flags;
1785
1786         host = mmc_priv(mmc);
1787
1788         /* Firstly check card presence */
1789         present = mmc->ops->get_cd(mmc);
1790
1791         spin_lock_irqsave(&host->lock, flags);
1792
1793         sdhci_led_activate(host);
1794
1795         /*
1796          * Ensure we don't send the STOP for non-SET_BLOCK_COUNTED
1797          * requests if Auto-CMD12 is enabled.
1798          */
1799         if (sdhci_auto_cmd12(host, mrq)) {
1800                 if (mrq->stop) {
1801                         mrq->data->stop = NULL;
1802                         mrq->stop = NULL;
1803                 }
1804         }
1805
1806         if (!present || host->flags & SDHCI_DEVICE_DEAD) {
1807                 mrq->cmd->error = -ENOMEDIUM;
1808                 sdhci_finish_mrq(host, mrq);
1809         } else {
1810                 if (mrq->sbc && !(host->flags & SDHCI_AUTO_CMD23))
1811                         sdhci_send_command(host, mrq->sbc);
1812                 else
1813                         sdhci_send_command(host, mrq->cmd);
1814         }
1815
1816         spin_unlock_irqrestore(&host->lock, flags);
1817 }
1818 EXPORT_SYMBOL_GPL(sdhci_request);
1819
1820 void sdhci_set_bus_width(struct sdhci_host *host, int width)
1821 {
1822         u8 ctrl;
1823
1824         ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
1825         if (width == MMC_BUS_WIDTH_8) {
1826                 ctrl &= ~SDHCI_CTRL_4BITBUS;
1827                 ctrl |= SDHCI_CTRL_8BITBUS;
1828         } else {
1829                 if (host->mmc->caps & MMC_CAP_8_BIT_DATA)
1830                         ctrl &= ~SDHCI_CTRL_8BITBUS;
1831                 if (width == MMC_BUS_WIDTH_4)
1832                         ctrl |= SDHCI_CTRL_4BITBUS;
1833                 else
1834                         ctrl &= ~SDHCI_CTRL_4BITBUS;
1835         }
1836         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1837 }
1838 EXPORT_SYMBOL_GPL(sdhci_set_bus_width);
1839
1840 void sdhci_set_uhs_signaling(struct sdhci_host *host, unsigned timing)
1841 {
1842         u16 ctrl_2;
1843
1844         ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1845         /* Select Bus Speed Mode for host */
1846         ctrl_2 &= ~SDHCI_CTRL_UHS_MASK;
1847         if ((timing == MMC_TIMING_MMC_HS200) ||
1848             (timing == MMC_TIMING_UHS_SDR104))
1849                 ctrl_2 |= SDHCI_CTRL_UHS_SDR104;
1850         else if (timing == MMC_TIMING_UHS_SDR12)
1851                 ctrl_2 |= SDHCI_CTRL_UHS_SDR12;
1852         else if (timing == MMC_TIMING_SD_HS ||
1853                  timing == MMC_TIMING_MMC_HS ||
1854                  timing == MMC_TIMING_UHS_SDR25)
1855                 ctrl_2 |= SDHCI_CTRL_UHS_SDR25;
1856         else if (timing == MMC_TIMING_UHS_SDR50)
1857                 ctrl_2 |= SDHCI_CTRL_UHS_SDR50;
1858         else if ((timing == MMC_TIMING_UHS_DDR50) ||
1859                  (timing == MMC_TIMING_MMC_DDR52))
1860                 ctrl_2 |= SDHCI_CTRL_UHS_DDR50;
1861         else if (timing == MMC_TIMING_MMC_HS400)
1862                 ctrl_2 |= SDHCI_CTRL_HS400; /* Non-standard */
1863         sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
1864 }
1865 EXPORT_SYMBOL_GPL(sdhci_set_uhs_signaling);
1866
1867 void sdhci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
1868 {
1869         struct sdhci_host *host = mmc_priv(mmc);
1870         u8 ctrl;
1871
1872         if (ios->power_mode == MMC_POWER_UNDEFINED)
1873                 return;
1874
1875         if (host->flags & SDHCI_DEVICE_DEAD) {
1876                 if (!IS_ERR(mmc->supply.vmmc) &&
1877                     ios->power_mode == MMC_POWER_OFF)
1878                         mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0);
1879                 return;
1880         }
1881
1882         /*
1883          * Reset the chip on each power off.
1884          * Should clear out any weird states.
1885          */
1886         if (ios->power_mode == MMC_POWER_OFF) {
1887                 sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
1888                 sdhci_reinit(host);
1889         }
1890
1891         if (host->version >= SDHCI_SPEC_300 &&
1892                 (ios->power_mode == MMC_POWER_UP) &&
1893                 !(host->quirks2 & SDHCI_QUIRK2_PRESET_VALUE_BROKEN))
1894                 sdhci_enable_preset_value(host, false);
1895
1896         if (!ios->clock || ios->clock != host->clock) {
1897                 host->ops->set_clock(host, ios->clock);
1898                 host->clock = ios->clock;
1899
1900                 if (host->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK &&
1901                     host->clock) {
1902                         host->timeout_clk = host->mmc->actual_clock ?
1903                                                 host->mmc->actual_clock / 1000 :
1904                                                 host->clock / 1000;
1905                         host->mmc->max_busy_timeout =
1906                                 host->ops->get_max_timeout_count ?
1907                                 host->ops->get_max_timeout_count(host) :
1908                                 1 << 27;
1909                         host->mmc->max_busy_timeout /= host->timeout_clk;
1910                 }
1911         }
1912
1913         if (host->ops->set_power)
1914                 host->ops->set_power(host, ios->power_mode, ios->vdd);
1915         else
1916                 sdhci_set_power(host, ios->power_mode, ios->vdd);
1917
1918         if (host->ops->platform_send_init_74_clocks)
1919                 host->ops->platform_send_init_74_clocks(host, ios->power_mode);
1920
1921         host->ops->set_bus_width(host, ios->bus_width);
1922
1923         ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
1924
1925         if (!(host->quirks & SDHCI_QUIRK_NO_HISPD_BIT)) {
1926                 if (ios->timing == MMC_TIMING_SD_HS ||
1927                      ios->timing == MMC_TIMING_MMC_HS ||
1928                      ios->timing == MMC_TIMING_MMC_HS400 ||
1929                      ios->timing == MMC_TIMING_MMC_HS200 ||
1930                      ios->timing == MMC_TIMING_MMC_DDR52 ||
1931                      ios->timing == MMC_TIMING_UHS_SDR50 ||
1932                      ios->timing == MMC_TIMING_UHS_SDR104 ||
1933                      ios->timing == MMC_TIMING_UHS_DDR50 ||
1934                      ios->timing == MMC_TIMING_UHS_SDR25)
1935                         ctrl |= SDHCI_CTRL_HISPD;
1936                 else
1937                         ctrl &= ~SDHCI_CTRL_HISPD;
1938         }
1939
1940         if (host->version >= SDHCI_SPEC_300) {
1941                 u16 clk, ctrl_2;
1942
1943                 if (!host->preset_enabled) {
1944                         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1945                         /*
1946                          * We only need to set Driver Strength if the
1947                          * preset value enable is not set.
1948                          */
1949                         ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
1950                         ctrl_2 &= ~SDHCI_CTRL_DRV_TYPE_MASK;
1951                         if (ios->drv_type == MMC_SET_DRIVER_TYPE_A)
1952                                 ctrl_2 |= SDHCI_CTRL_DRV_TYPE_A;
1953                         else if (ios->drv_type == MMC_SET_DRIVER_TYPE_B)
1954                                 ctrl_2 |= SDHCI_CTRL_DRV_TYPE_B;
1955                         else if (ios->drv_type == MMC_SET_DRIVER_TYPE_C)
1956                                 ctrl_2 |= SDHCI_CTRL_DRV_TYPE_C;
1957                         else if (ios->drv_type == MMC_SET_DRIVER_TYPE_D)
1958                                 ctrl_2 |= SDHCI_CTRL_DRV_TYPE_D;
1959                         else {
1960                                 pr_warn("%s: invalid driver type, default to driver type B\n",
1961                                         mmc_hostname(mmc));
1962                                 ctrl_2 |= SDHCI_CTRL_DRV_TYPE_B;
1963                         }
1964
1965                         sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
1966                 } else {
1967                         /*
1968                          * According to SDHC Spec v3.00, if the Preset Value
1969                          * Enable in the Host Control 2 register is set, we
1970                          * need to reset SD Clock Enable before changing High
1971                          * Speed Enable to avoid generating clock gliches.
1972                          */
1973
1974                         /* Reset SD Clock Enable */
1975                         clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1976                         clk &= ~SDHCI_CLOCK_CARD_EN;
1977                         sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1978
1979                         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
1980
1981                         /* Re-enable SD Clock */
1982                         host->ops->set_clock(host, host->clock);
1983                 }
1984
1985                 /* Reset SD Clock Enable */
1986                 clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
1987                 clk &= ~SDHCI_CLOCK_CARD_EN;
1988                 sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
1989
1990                 host->ops->set_uhs_signaling(host, ios->timing);
1991                 host->timing = ios->timing;
1992
1993                 if (!(host->quirks2 & SDHCI_QUIRK2_PRESET_VALUE_BROKEN) &&
1994                                 ((ios->timing == MMC_TIMING_UHS_SDR12) ||
1995                                  (ios->timing == MMC_TIMING_UHS_SDR25) ||
1996                                  (ios->timing == MMC_TIMING_UHS_SDR50) ||
1997                                  (ios->timing == MMC_TIMING_UHS_SDR104) ||
1998                                  (ios->timing == MMC_TIMING_UHS_DDR50) ||
1999                                  (ios->timing == MMC_TIMING_MMC_DDR52))) {
2000                         u16 preset;
2001
2002                         sdhci_enable_preset_value(host, true);
2003                         preset = sdhci_get_preset_value(host);
2004                         ios->drv_type = (preset & SDHCI_PRESET_DRV_MASK)
2005                                 >> SDHCI_PRESET_DRV_SHIFT;
2006                 }
2007
2008                 /* Re-enable SD Clock */
2009                 host->ops->set_clock(host, host->clock);
2010         } else
2011                 sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
2012
2013         /*
2014          * Some (ENE) controllers go apeshit on some ios operation,
2015          * signalling timeout and CRC errors even on CMD0. Resetting
2016          * it on each ios seems to solve the problem.
2017          */
2018         if (host->quirks & SDHCI_QUIRK_RESET_CMD_DATA_ON_IOS)
2019                 sdhci_do_reset(host, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
2020 }
2021 EXPORT_SYMBOL_GPL(sdhci_set_ios);
2022
2023 static int sdhci_get_cd(struct mmc_host *mmc)
2024 {
2025         struct sdhci_host *host = mmc_priv(mmc);
2026         int gpio_cd = mmc_gpio_get_cd(mmc);
2027
2028         if (host->flags & SDHCI_DEVICE_DEAD)
2029                 return 0;
2030
2031         /* If nonremovable, assume that the card is always present. */
2032         if (!mmc_card_is_removable(host->mmc))
2033                 return 1;
2034
2035         /*
2036          * Try slot gpio detect, if defined it take precedence
2037          * over build in controller functionality
2038          */
2039         if (gpio_cd >= 0)
2040                 return !!gpio_cd;
2041
2042         /* If polling, assume that the card is always present. */
2043         if (host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION)
2044                 return 1;
2045
2046         /* Host native card detect */
2047         return !!(sdhci_readl(host, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
2048 }
2049
2050 static int sdhci_check_ro(struct sdhci_host *host)
2051 {
2052         unsigned long flags;
2053         int is_readonly;
2054
2055         spin_lock_irqsave(&host->lock, flags);
2056
2057         if (host->flags & SDHCI_DEVICE_DEAD)
2058                 is_readonly = 0;
2059         else if (host->ops->get_ro)
2060                 is_readonly = host->ops->get_ro(host);
2061         else if (mmc_can_gpio_ro(host->mmc))
2062                 is_readonly = mmc_gpio_get_ro(host->mmc);
2063         else
2064                 is_readonly = !(sdhci_readl(host, SDHCI_PRESENT_STATE)
2065                                 & SDHCI_WRITE_PROTECT);
2066
2067         spin_unlock_irqrestore(&host->lock, flags);
2068
2069         /* This quirk needs to be replaced by a callback-function later */
2070         return host->quirks & SDHCI_QUIRK_INVERTED_WRITE_PROTECT ?
2071                 !is_readonly : is_readonly;
2072 }
2073
2074 #define SAMPLE_COUNT    5
2075
2076 static int sdhci_get_ro(struct mmc_host *mmc)
2077 {
2078         struct sdhci_host *host = mmc_priv(mmc);
2079         int i, ro_count;
2080
2081         if (!(host->quirks & SDHCI_QUIRK_UNSTABLE_RO_DETECT))
2082                 return sdhci_check_ro(host);
2083
2084         ro_count = 0;
2085         for (i = 0; i < SAMPLE_COUNT; i++) {
2086                 if (sdhci_check_ro(host)) {
2087                         if (++ro_count > SAMPLE_COUNT / 2)
2088                                 return 1;
2089                 }
2090                 msleep(30);
2091         }
2092         return 0;
2093 }
2094
2095 static void sdhci_hw_reset(struct mmc_host *mmc)
2096 {
2097         struct sdhci_host *host = mmc_priv(mmc);
2098
2099         if (host->ops && host->ops->hw_reset)
2100                 host->ops->hw_reset(host);
2101 }
2102
2103 static void sdhci_enable_sdio_irq_nolock(struct sdhci_host *host, int enable)
2104 {
2105         if (!(host->flags & SDHCI_DEVICE_DEAD)) {
2106                 if (enable)
2107                         host->ier |= SDHCI_INT_CARD_INT;
2108                 else
2109                         host->ier &= ~SDHCI_INT_CARD_INT;
2110
2111                 sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
2112                 sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
2113         }
2114 }
2115
2116 void sdhci_enable_sdio_irq(struct mmc_host *mmc, int enable)
2117 {
2118         struct sdhci_host *host = mmc_priv(mmc);
2119         unsigned long flags;
2120
2121         if (enable)
2122                 pm_runtime_get_noresume(host->mmc->parent);
2123
2124         spin_lock_irqsave(&host->lock, flags);
2125         if (enable)
2126                 host->flags |= SDHCI_SDIO_IRQ_ENABLED;
2127         else
2128                 host->flags &= ~SDHCI_SDIO_IRQ_ENABLED;
2129
2130         sdhci_enable_sdio_irq_nolock(host, enable);
2131         spin_unlock_irqrestore(&host->lock, flags);
2132
2133         if (!enable)
2134                 pm_runtime_put_noidle(host->mmc->parent);
2135 }
2136 EXPORT_SYMBOL_GPL(sdhci_enable_sdio_irq);
2137
2138 static void sdhci_ack_sdio_irq(struct mmc_host *mmc)
2139 {
2140         struct sdhci_host *host = mmc_priv(mmc);
2141         unsigned long flags;
2142
2143         spin_lock_irqsave(&host->lock, flags);
2144         if (host->flags & SDHCI_SDIO_IRQ_ENABLED)
2145                 sdhci_enable_sdio_irq_nolock(host, true);
2146         spin_unlock_irqrestore(&host->lock, flags);
2147 }
2148
2149 int sdhci_start_signal_voltage_switch(struct mmc_host *mmc,
2150                                       struct mmc_ios *ios)
2151 {
2152         struct sdhci_host *host = mmc_priv(mmc);
2153         u16 ctrl;
2154         int ret;
2155
2156         /*
2157          * Signal Voltage Switching is only applicable for Host Controllers
2158          * v3.00 and above.
2159          */
2160         if (host->version < SDHCI_SPEC_300)
2161                 return 0;
2162
2163         ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2164
2165         switch (ios->signal_voltage) {
2166         case MMC_SIGNAL_VOLTAGE_330:
2167                 if (!(host->flags & SDHCI_SIGNALING_330))
2168                         return -EINVAL;
2169                 /* Set 1.8V Signal Enable in the Host Control2 register to 0 */
2170                 ctrl &= ~SDHCI_CTRL_VDD_180;
2171                 sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2172
2173                 if (!IS_ERR(mmc->supply.vqmmc)) {
2174                         ret = mmc_regulator_set_vqmmc(mmc, ios);
2175                         if (ret) {
2176                                 pr_warn("%s: Switching to 3.3V signalling voltage failed\n",
2177                                         mmc_hostname(mmc));
2178                                 return -EIO;
2179                         }
2180                 }
2181                 /* Wait for 5ms */
2182                 usleep_range(5000, 5500);
2183
2184                 /* 3.3V regulator output should be stable within 5 ms */
2185                 ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2186                 if (!(ctrl & SDHCI_CTRL_VDD_180))
2187                         return 0;
2188
2189                 pr_warn("%s: 3.3V regulator output did not became stable\n",
2190                         mmc_hostname(mmc));
2191
2192                 return -EAGAIN;
2193         case MMC_SIGNAL_VOLTAGE_180:
2194                 if (!(host->flags & SDHCI_SIGNALING_180))
2195                         return -EINVAL;
2196                 if (!IS_ERR(mmc->supply.vqmmc)) {
2197                         ret = mmc_regulator_set_vqmmc(mmc, ios);
2198                         if (ret) {
2199                                 pr_warn("%s: Switching to 1.8V signalling voltage failed\n",
2200                                         mmc_hostname(mmc));
2201                                 return -EIO;
2202                         }
2203                 }
2204
2205                 /*
2206                  * Enable 1.8V Signal Enable in the Host Control2
2207                  * register
2208                  */
2209                 ctrl |= SDHCI_CTRL_VDD_180;
2210                 sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2211
2212                 /* Some controller need to do more when switching */
2213                 if (host->ops->voltage_switch)
2214                         host->ops->voltage_switch(host);
2215
2216                 /* 1.8V regulator output should be stable within 5 ms */
2217                 ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2218                 if (ctrl & SDHCI_CTRL_VDD_180)
2219                         return 0;
2220
2221                 pr_warn("%s: 1.8V regulator output did not became stable\n",
2222                         mmc_hostname(mmc));
2223
2224                 return -EAGAIN;
2225         case MMC_SIGNAL_VOLTAGE_120:
2226                 if (!(host->flags & SDHCI_SIGNALING_120))
2227                         return -EINVAL;
2228                 if (!IS_ERR(mmc->supply.vqmmc)) {
2229                         ret = mmc_regulator_set_vqmmc(mmc, ios);
2230                         if (ret) {
2231                                 pr_warn("%s: Switching to 1.2V signalling voltage failed\n",
2232                                         mmc_hostname(mmc));
2233                                 return -EIO;
2234                         }
2235                 }
2236                 return 0;
2237         default:
2238                 /* No signal voltage switch required */
2239                 return 0;
2240         }
2241 }
2242 EXPORT_SYMBOL_GPL(sdhci_start_signal_voltage_switch);
2243
2244 static int sdhci_card_busy(struct mmc_host *mmc)
2245 {
2246         struct sdhci_host *host = mmc_priv(mmc);
2247         u32 present_state;
2248
2249         /* Check whether DAT[0] is 0 */
2250         present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
2251
2252         return !(present_state & SDHCI_DATA_0_LVL_MASK);
2253 }
2254
2255 static int sdhci_prepare_hs400_tuning(struct mmc_host *mmc, struct mmc_ios *ios)
2256 {
2257         struct sdhci_host *host = mmc_priv(mmc);
2258         unsigned long flags;
2259
2260         spin_lock_irqsave(&host->lock, flags);
2261         host->flags |= SDHCI_HS400_TUNING;
2262         spin_unlock_irqrestore(&host->lock, flags);
2263
2264         return 0;
2265 }
2266
2267 void sdhci_start_tuning(struct sdhci_host *host)
2268 {
2269         u16 ctrl;
2270
2271         ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2272         ctrl |= SDHCI_CTRL_EXEC_TUNING;
2273         if (host->quirks2 & SDHCI_QUIRK2_TUNING_WORK_AROUND)
2274                 ctrl |= SDHCI_CTRL_TUNED_CLK;
2275         sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2276
2277         /*
2278          * As per the Host Controller spec v3.00, tuning command
2279          * generates Buffer Read Ready interrupt, so enable that.
2280          *
2281          * Note: The spec clearly says that when tuning sequence
2282          * is being performed, the controller does not generate
2283          * interrupts other than Buffer Read Ready interrupt. But
2284          * to make sure we don't hit a controller bug, we _only_
2285          * enable Buffer Read Ready interrupt here.
2286          */
2287         sdhci_writel(host, SDHCI_INT_DATA_AVAIL, SDHCI_INT_ENABLE);
2288         sdhci_writel(host, SDHCI_INT_DATA_AVAIL, SDHCI_SIGNAL_ENABLE);
2289 }
2290 EXPORT_SYMBOL_GPL(sdhci_start_tuning);
2291
2292 void sdhci_end_tuning(struct sdhci_host *host)
2293 {
2294         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
2295         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
2296 }
2297 EXPORT_SYMBOL_GPL(sdhci_end_tuning);
2298
2299 void sdhci_reset_tuning(struct sdhci_host *host)
2300 {
2301         u16 ctrl;
2302
2303         ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2304         ctrl &= ~SDHCI_CTRL_TUNED_CLK;
2305         ctrl &= ~SDHCI_CTRL_EXEC_TUNING;
2306         sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2307 }
2308 EXPORT_SYMBOL_GPL(sdhci_reset_tuning);
2309
2310 static void sdhci_abort_tuning(struct sdhci_host *host, u32 opcode)
2311 {
2312         sdhci_reset_tuning(host);
2313
2314         sdhci_do_reset(host, SDHCI_RESET_CMD);
2315         sdhci_do_reset(host, SDHCI_RESET_DATA);
2316
2317         sdhci_end_tuning(host);
2318
2319         mmc_abort_tuning(host->mmc, opcode);
2320 }
2321
2322 /*
2323  * We use sdhci_send_tuning() because mmc_send_tuning() is not a good fit. SDHCI
2324  * tuning command does not have a data payload (or rather the hardware does it
2325  * automatically) so mmc_send_tuning() will return -EIO. Also the tuning command
2326  * interrupt setup is different to other commands and there is no timeout
2327  * interrupt so special handling is needed.
2328  */
2329 void sdhci_send_tuning(struct sdhci_host *host, u32 opcode)
2330 {
2331         struct mmc_host *mmc = host->mmc;
2332         struct mmc_command cmd = {};
2333         struct mmc_request mrq = {};
2334         unsigned long flags;
2335         u32 b = host->sdma_boundary;
2336
2337         spin_lock_irqsave(&host->lock, flags);
2338
2339         cmd.opcode = opcode;
2340         cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
2341         cmd.mrq = &mrq;
2342
2343         mrq.cmd = &cmd;
2344         /*
2345          * In response to CMD19, the card sends 64 bytes of tuning
2346          * block to the Host Controller. So we set the block size
2347          * to 64 here.
2348          */
2349         if (cmd.opcode == MMC_SEND_TUNING_BLOCK_HS200 &&
2350             mmc->ios.bus_width == MMC_BUS_WIDTH_8)
2351                 sdhci_writew(host, SDHCI_MAKE_BLKSZ(b, 128), SDHCI_BLOCK_SIZE);
2352         else
2353                 sdhci_writew(host, SDHCI_MAKE_BLKSZ(b, 64), SDHCI_BLOCK_SIZE);
2354
2355         /*
2356          * The tuning block is sent by the card to the host controller.
2357          * So we set the TRNS_READ bit in the Transfer Mode register.
2358          * This also takes care of setting DMA Enable and Multi Block
2359          * Select in the same register to 0.
2360          */
2361         sdhci_writew(host, SDHCI_TRNS_READ, SDHCI_TRANSFER_MODE);
2362
2363         sdhci_send_command(host, &cmd);
2364
2365         host->cmd = NULL;
2366
2367         sdhci_del_timer(host, &mrq);
2368
2369         host->tuning_done = 0;
2370
2371         spin_unlock_irqrestore(&host->lock, flags);
2372
2373         /* Wait for Buffer Read Ready interrupt */
2374         wait_event_timeout(host->buf_ready_int, (host->tuning_done == 1),
2375                            msecs_to_jiffies(50));
2376
2377 }
2378 EXPORT_SYMBOL_GPL(sdhci_send_tuning);
2379
2380 static int __sdhci_execute_tuning(struct sdhci_host *host, u32 opcode)
2381 {
2382         int i;
2383
2384         /*
2385          * Issue opcode repeatedly till Execute Tuning is set to 0 or the number
2386          * of loops reaches tuning loop count.
2387          */
2388         for (i = 0; i < host->tuning_loop_count; i++) {
2389                 u16 ctrl;
2390
2391                 sdhci_send_tuning(host, opcode);
2392
2393                 if (!host->tuning_done) {
2394                         pr_info("%s: Tuning timeout, falling back to fixed sampling clock\n",
2395                                 mmc_hostname(host->mmc));
2396                         sdhci_abort_tuning(host, opcode);
2397                         return -ETIMEDOUT;
2398                 }
2399
2400                 /* Spec does not require a delay between tuning cycles */
2401                 if (host->tuning_delay > 0)
2402                         mdelay(host->tuning_delay);
2403
2404                 ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2405                 if (!(ctrl & SDHCI_CTRL_EXEC_TUNING)) {
2406                         if (ctrl & SDHCI_CTRL_TUNED_CLK)
2407                                 return 0; /* Success! */
2408                         break;
2409                 }
2410
2411         }
2412
2413         pr_info("%s: Tuning failed, falling back to fixed sampling clock\n",
2414                 mmc_hostname(host->mmc));
2415         sdhci_reset_tuning(host);
2416         return -EAGAIN;
2417 }
2418
2419 int sdhci_execute_tuning(struct mmc_host *mmc, u32 opcode)
2420 {
2421         struct sdhci_host *host = mmc_priv(mmc);
2422         int err = 0;
2423         unsigned int tuning_count = 0;
2424         bool hs400_tuning;
2425
2426         hs400_tuning = host->flags & SDHCI_HS400_TUNING;
2427
2428         if (host->tuning_mode == SDHCI_TUNING_MODE_1)
2429                 tuning_count = host->tuning_count;
2430
2431         /*
2432          * The Host Controller needs tuning in case of SDR104 and DDR50
2433          * mode, and for SDR50 mode when Use Tuning for SDR50 is set in
2434          * the Capabilities register.
2435          * If the Host Controller supports the HS200 mode then the
2436          * tuning function has to be executed.
2437          */
2438         switch (host->timing) {
2439         /* HS400 tuning is done in HS200 mode */
2440         case MMC_TIMING_MMC_HS400:
2441                 err = -EINVAL;
2442                 goto out;
2443
2444         case MMC_TIMING_MMC_HS200:
2445                 /*
2446                  * Periodic re-tuning for HS400 is not expected to be needed, so
2447                  * disable it here.
2448                  */
2449                 if (hs400_tuning)
2450                         tuning_count = 0;
2451                 break;
2452
2453         case MMC_TIMING_UHS_SDR104:
2454         case MMC_TIMING_UHS_DDR50:
2455                 break;
2456
2457         case MMC_TIMING_UHS_SDR50:
2458                 if (host->flags & SDHCI_SDR50_NEEDS_TUNING)
2459                         break;
2460                 /* FALLTHROUGH */
2461
2462         default:
2463                 goto out;
2464         }
2465
2466         if (host->ops->platform_execute_tuning) {
2467                 err = host->ops->platform_execute_tuning(host, opcode);
2468                 goto out;
2469         }
2470
2471         host->mmc->retune_period = tuning_count;
2472
2473         if (host->tuning_delay < 0)
2474                 host->tuning_delay = opcode == MMC_SEND_TUNING_BLOCK;
2475
2476         sdhci_start_tuning(host);
2477
2478         host->tuning_err = __sdhci_execute_tuning(host, opcode);
2479
2480         sdhci_end_tuning(host);
2481 out:
2482         host->flags &= ~SDHCI_HS400_TUNING;
2483
2484         return err;
2485 }
2486 EXPORT_SYMBOL_GPL(sdhci_execute_tuning);
2487
2488 static void sdhci_enable_preset_value(struct sdhci_host *host, bool enable)
2489 {
2490         /* Host Controller v3.00 defines preset value registers */
2491         if (host->version < SDHCI_SPEC_300)
2492                 return;
2493
2494         /*
2495          * We only enable or disable Preset Value if they are not already
2496          * enabled or disabled respectively. Otherwise, we bail out.
2497          */
2498         if (host->preset_enabled != enable) {
2499                 u16 ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
2500
2501                 if (enable)
2502                         ctrl |= SDHCI_CTRL_PRESET_VAL_ENABLE;
2503                 else
2504                         ctrl &= ~SDHCI_CTRL_PRESET_VAL_ENABLE;
2505
2506                 sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
2507
2508                 if (enable)
2509                         host->flags |= SDHCI_PV_ENABLED;
2510                 else
2511                         host->flags &= ~SDHCI_PV_ENABLED;
2512
2513                 host->preset_enabled = enable;
2514         }
2515 }
2516
2517 static void sdhci_post_req(struct mmc_host *mmc, struct mmc_request *mrq,
2518                                 int err)
2519 {
2520         struct sdhci_host *host = mmc_priv(mmc);
2521         struct mmc_data *data = mrq->data;
2522
2523         if (data->host_cookie != COOKIE_UNMAPPED)
2524                 dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
2525                              mmc_get_dma_dir(data));
2526
2527         data->host_cookie = COOKIE_UNMAPPED;
2528 }
2529
2530 static void sdhci_pre_req(struct mmc_host *mmc, struct mmc_request *mrq)
2531 {
2532         struct sdhci_host *host = mmc_priv(mmc);
2533
2534         mrq->data->host_cookie = COOKIE_UNMAPPED;
2535
2536         /*
2537          * No pre-mapping in the pre hook if we're using the bounce buffer,
2538          * for that we would need two bounce buffers since one buffer is
2539          * in flight when this is getting called.
2540          */
2541         if (host->flags & SDHCI_REQ_USE_DMA && !host->bounce_buffer)
2542                 sdhci_pre_dma_transfer(host, mrq->data, COOKIE_PRE_MAPPED);
2543 }
2544
2545 static void sdhci_error_out_mrqs(struct sdhci_host *host, int err)
2546 {
2547         if (host->data_cmd) {
2548                 host->data_cmd->error = err;
2549                 sdhci_finish_mrq(host, host->data_cmd->mrq);
2550         }
2551
2552         if (host->cmd) {
2553                 host->cmd->error = err;
2554                 sdhci_finish_mrq(host, host->cmd->mrq);
2555         }
2556 }
2557
2558 static void sdhci_card_event(struct mmc_host *mmc)
2559 {
2560         struct sdhci_host *host = mmc_priv(mmc);
2561         unsigned long flags;
2562         int present;
2563
2564         /* First check if client has provided their own card event */
2565         if (host->ops->card_event)
2566                 host->ops->card_event(host);
2567
2568         present = mmc->ops->get_cd(mmc);
2569
2570         spin_lock_irqsave(&host->lock, flags);
2571
2572         /* Check sdhci_has_requests() first in case we are runtime suspended */
2573         if (sdhci_has_requests(host) && !present) {
2574                 pr_err("%s: Card removed during transfer!\n",
2575                         mmc_hostname(host->mmc));
2576                 pr_err("%s: Resetting controller.\n",
2577                         mmc_hostname(host->mmc));
2578
2579                 sdhci_do_reset(host, SDHCI_RESET_CMD);
2580                 sdhci_do_reset(host, SDHCI_RESET_DATA);
2581
2582                 sdhci_error_out_mrqs(host, -ENOMEDIUM);
2583         }
2584
2585         spin_unlock_irqrestore(&host->lock, flags);
2586 }
2587
2588 static const struct mmc_host_ops sdhci_ops = {
2589         .request        = sdhci_request,
2590         .post_req       = sdhci_post_req,
2591         .pre_req        = sdhci_pre_req,
2592         .set_ios        = sdhci_set_ios,
2593         .get_cd         = sdhci_get_cd,
2594         .get_ro         = sdhci_get_ro,
2595         .hw_reset       = sdhci_hw_reset,
2596         .enable_sdio_irq = sdhci_enable_sdio_irq,
2597         .ack_sdio_irq    = sdhci_ack_sdio_irq,
2598         .start_signal_voltage_switch    = sdhci_start_signal_voltage_switch,
2599         .prepare_hs400_tuning           = sdhci_prepare_hs400_tuning,
2600         .execute_tuning                 = sdhci_execute_tuning,
2601         .card_event                     = sdhci_card_event,
2602         .card_busy      = sdhci_card_busy,
2603 };
2604
2605 /*****************************************************************************\
2606  *                                                                           *
2607  * Request done                                                              *
2608  *                                                                           *
2609 \*****************************************************************************/
2610
2611 static bool sdhci_request_done(struct sdhci_host *host)
2612 {
2613         unsigned long flags;
2614         struct mmc_request *mrq;
2615         int i;
2616
2617         spin_lock_irqsave(&host->lock, flags);
2618
2619         for (i = 0; i < SDHCI_MAX_MRQS; i++) {
2620                 mrq = host->mrqs_done[i];
2621                 if (mrq)
2622                         break;
2623         }
2624
2625         if (!mrq) {
2626                 spin_unlock_irqrestore(&host->lock, flags);
2627                 return true;
2628         }
2629
2630         /*
2631          * Always unmap the data buffers if they were mapped by
2632          * sdhci_prepare_data() whenever we finish with a request.
2633          * This avoids leaking DMA mappings on error.
2634          */
2635         if (host->flags & SDHCI_REQ_USE_DMA) {
2636                 struct mmc_data *data = mrq->data;
2637
2638                 if (data && data->host_cookie == COOKIE_MAPPED) {
2639                         if (host->bounce_buffer) {
2640                                 /*
2641                                  * On reads, copy the bounced data into the
2642                                  * sglist
2643                                  */
2644                                 if (mmc_get_dma_dir(data) == DMA_FROM_DEVICE) {
2645                                         unsigned int length = data->bytes_xfered;
2646
2647                                         if (length > host->bounce_buffer_size) {
2648                                                 pr_err("%s: bounce buffer is %u bytes but DMA claims to have transferred %u bytes\n",
2649                                                        mmc_hostname(host->mmc),
2650                                                        host->bounce_buffer_size,
2651                                                        data->bytes_xfered);
2652                                                 /* Cap it down and continue */
2653                                                 length = host->bounce_buffer_size;
2654                                         }
2655                                         dma_sync_single_for_cpu(
2656                                                 host->mmc->parent,
2657                                                 host->bounce_addr,
2658                                                 host->bounce_buffer_size,
2659                                                 DMA_FROM_DEVICE);
2660                                         sg_copy_from_buffer(data->sg,
2661                                                 data->sg_len,
2662                                                 host->bounce_buffer,
2663                                                 length);
2664                                 } else {
2665                                         /* No copying, just switch ownership */
2666                                         dma_sync_single_for_cpu(
2667                                                 host->mmc->parent,
2668                                                 host->bounce_addr,
2669                                                 host->bounce_buffer_size,
2670                                                 mmc_get_dma_dir(data));
2671                                 }
2672                         } else {
2673                                 /* Unmap the raw data */
2674                                 dma_unmap_sg(mmc_dev(host->mmc), data->sg,
2675                                              data->sg_len,
2676                                              mmc_get_dma_dir(data));
2677                         }
2678                         data->host_cookie = COOKIE_UNMAPPED;
2679                 }
2680         }
2681
2682         /*
2683          * The controller needs a reset of internal state machines
2684          * upon error conditions.
2685          */
2686         if (sdhci_needs_reset(host, mrq)) {
2687                 /*
2688                  * Do not finish until command and data lines are available for
2689                  * reset. Note there can only be one other mrq, so it cannot
2690                  * also be in mrqs_done, otherwise host->cmd and host->data_cmd
2691                  * would both be null.
2692                  */
2693                 if (host->cmd || host->data_cmd) {
2694                         spin_unlock_irqrestore(&host->lock, flags);
2695                         return true;
2696                 }
2697
2698                 /* Some controllers need this kick or reset won't work here */
2699                 if (host->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET)
2700                         /* This is to force an update */
2701                         host->ops->set_clock(host, host->clock);
2702
2703                 /* Spec says we should do both at the same time, but Ricoh
2704                    controllers do not like that. */
2705                 sdhci_do_reset(host, SDHCI_RESET_CMD);
2706                 sdhci_do_reset(host, SDHCI_RESET_DATA);
2707
2708                 host->pending_reset = false;
2709         }
2710
2711         host->mrqs_done[i] = NULL;
2712
2713         spin_unlock_irqrestore(&host->lock, flags);
2714
2715         mmc_request_done(host->mmc, mrq);
2716
2717         return false;
2718 }
2719
2720 static void sdhci_complete_work(struct work_struct *work)
2721 {
2722         struct sdhci_host *host = container_of(work, struct sdhci_host,
2723                                                complete_work);
2724
2725         while (!sdhci_request_done(host))
2726                 ;
2727 }
2728
2729 static void sdhci_timeout_timer(struct timer_list *t)
2730 {
2731         struct sdhci_host *host;
2732         unsigned long flags;
2733
2734         host = from_timer(host, t, timer);
2735
2736         spin_lock_irqsave(&host->lock, flags);
2737
2738         if (host->cmd && !sdhci_data_line_cmd(host->cmd)) {
2739                 pr_err("%s: Timeout waiting for hardware cmd interrupt.\n",
2740                        mmc_hostname(host->mmc));
2741                 sdhci_dumpregs(host);
2742
2743                 host->cmd->error = -ETIMEDOUT;
2744                 sdhci_finish_mrq(host, host->cmd->mrq);
2745         }
2746
2747         spin_unlock_irqrestore(&host->lock, flags);
2748 }
2749
2750 static void sdhci_timeout_data_timer(struct timer_list *t)
2751 {
2752         struct sdhci_host *host;
2753         unsigned long flags;
2754
2755         host = from_timer(host, t, data_timer);
2756
2757         spin_lock_irqsave(&host->lock, flags);
2758
2759         if (host->data || host->data_cmd ||
2760             (host->cmd && sdhci_data_line_cmd(host->cmd))) {
2761                 pr_err("%s: Timeout waiting for hardware interrupt.\n",
2762                        mmc_hostname(host->mmc));
2763                 sdhci_dumpregs(host);
2764
2765                 if (host->data) {
2766                         host->data->error = -ETIMEDOUT;
2767                         sdhci_finish_data(host);
2768                         queue_work(host->complete_wq, &host->complete_work);
2769                 } else if (host->data_cmd) {
2770                         host->data_cmd->error = -ETIMEDOUT;
2771                         sdhci_finish_mrq(host, host->data_cmd->mrq);
2772                 } else {
2773                         host->cmd->error = -ETIMEDOUT;
2774                         sdhci_finish_mrq(host, host->cmd->mrq);
2775                 }
2776         }
2777
2778         spin_unlock_irqrestore(&host->lock, flags);
2779 }
2780
2781 /*****************************************************************************\
2782  *                                                                           *
2783  * Interrupt handling                                                        *
2784  *                                                                           *
2785 \*****************************************************************************/
2786
2787 static void sdhci_cmd_irq(struct sdhci_host *host, u32 intmask, u32 *intmask_p)
2788 {
2789         /* Handle auto-CMD12 error */
2790         if (intmask & SDHCI_INT_AUTO_CMD_ERR && host->data_cmd) {
2791                 struct mmc_request *mrq = host->data_cmd->mrq;
2792                 u16 auto_cmd_status = sdhci_readw(host, SDHCI_AUTO_CMD_STATUS);
2793                 int data_err_bit = (auto_cmd_status & SDHCI_AUTO_CMD_TIMEOUT) ?
2794                                    SDHCI_INT_DATA_TIMEOUT :
2795                                    SDHCI_INT_DATA_CRC;
2796
2797                 /* Treat auto-CMD12 error the same as data error */
2798                 if (!mrq->sbc && (host->flags & SDHCI_AUTO_CMD12)) {
2799                         *intmask_p |= data_err_bit;
2800                         return;
2801                 }
2802         }
2803
2804         if (!host->cmd) {
2805                 /*
2806                  * SDHCI recovers from errors by resetting the cmd and data
2807                  * circuits.  Until that is done, there very well might be more
2808                  * interrupts, so ignore them in that case.
2809                  */
2810                 if (host->pending_reset)
2811                         return;
2812                 pr_err("%s: Got command interrupt 0x%08x even though no command operation was in progress.\n",
2813                        mmc_hostname(host->mmc), (unsigned)intmask);
2814                 sdhci_dumpregs(host);
2815                 return;
2816         }
2817
2818         if (intmask & (SDHCI_INT_TIMEOUT | SDHCI_INT_CRC |
2819                        SDHCI_INT_END_BIT | SDHCI_INT_INDEX)) {
2820                 if (intmask & SDHCI_INT_TIMEOUT)
2821                         host->cmd->error = -ETIMEDOUT;
2822                 else
2823                         host->cmd->error = -EILSEQ;
2824
2825                 /* Treat data command CRC error the same as data CRC error */
2826                 if (host->cmd->data &&
2827                     (intmask & (SDHCI_INT_CRC | SDHCI_INT_TIMEOUT)) ==
2828                      SDHCI_INT_CRC) {
2829                         host->cmd = NULL;
2830                         *intmask_p |= SDHCI_INT_DATA_CRC;
2831                         return;
2832                 }
2833
2834                 __sdhci_finish_mrq(host, host->cmd->mrq);
2835                 return;
2836         }
2837
2838         /* Handle auto-CMD23 error */
2839         if (intmask & SDHCI_INT_AUTO_CMD_ERR) {
2840                 struct mmc_request *mrq = host->cmd->mrq;
2841                 u16 auto_cmd_status = sdhci_readw(host, SDHCI_AUTO_CMD_STATUS);
2842                 int err = (auto_cmd_status & SDHCI_AUTO_CMD_TIMEOUT) ?
2843                           -ETIMEDOUT :
2844                           -EILSEQ;
2845
2846                 if (mrq->sbc && (host->flags & SDHCI_AUTO_CMD23)) {
2847                         mrq->sbc->error = err;
2848                         __sdhci_finish_mrq(host, mrq);
2849                         return;
2850                 }
2851         }
2852
2853         if (intmask & SDHCI_INT_RESPONSE)
2854                 sdhci_finish_command(host);
2855 }
2856
2857 static void sdhci_adma_show_error(struct sdhci_host *host)
2858 {
2859         void *desc = host->adma_table;
2860         dma_addr_t dma = host->adma_addr;
2861
2862         sdhci_dumpregs(host);
2863
2864         while (true) {
2865                 struct sdhci_adma2_64_desc *dma_desc = desc;
2866
2867                 if (host->flags & SDHCI_USE_64_BIT_DMA)
2868                         SDHCI_DUMP("%08llx: DMA 0x%08x%08x, LEN 0x%04x, Attr=0x%02x\n",
2869                             (unsigned long long)dma,
2870                             le32_to_cpu(dma_desc->addr_hi),
2871                             le32_to_cpu(dma_desc->addr_lo),
2872                             le16_to_cpu(dma_desc->len),
2873                             le16_to_cpu(dma_desc->cmd));
2874                 else
2875                         SDHCI_DUMP("%08llx: DMA 0x%08x, LEN 0x%04x, Attr=0x%02x\n",
2876                             (unsigned long long)dma,
2877                             le32_to_cpu(dma_desc->addr_lo),
2878                             le16_to_cpu(dma_desc->len),
2879                             le16_to_cpu(dma_desc->cmd));
2880
2881                 desc += host->desc_sz;
2882                 dma += host->desc_sz;
2883
2884                 if (dma_desc->cmd & cpu_to_le16(ADMA2_END))
2885                         break;
2886         }
2887 }
2888
2889 static void sdhci_data_irq(struct sdhci_host *host, u32 intmask)
2890 {
2891         u32 command;
2892
2893         /* CMD19 generates _only_ Buffer Read Ready interrupt */
2894         if (intmask & SDHCI_INT_DATA_AVAIL) {
2895                 command = SDHCI_GET_CMD(sdhci_readw(host, SDHCI_COMMAND));
2896                 if (command == MMC_SEND_TUNING_BLOCK ||
2897                     command == MMC_SEND_TUNING_BLOCK_HS200) {
2898                         host->tuning_done = 1;
2899                         wake_up(&host->buf_ready_int);
2900                         return;
2901                 }
2902         }
2903
2904         if (!host->data) {
2905                 struct mmc_command *data_cmd = host->data_cmd;
2906
2907                 /*
2908                  * The "data complete" interrupt is also used to
2909                  * indicate that a busy state has ended. See comment
2910                  * above in sdhci_cmd_irq().
2911                  */
2912                 if (data_cmd && (data_cmd->flags & MMC_RSP_BUSY)) {
2913                         if (intmask & SDHCI_INT_DATA_TIMEOUT) {
2914                                 host->data_cmd = NULL;
2915                                 data_cmd->error = -ETIMEDOUT;
2916                                 __sdhci_finish_mrq(host, data_cmd->mrq);
2917                                 return;
2918                         }
2919                         if (intmask & SDHCI_INT_DATA_END) {
2920                                 host->data_cmd = NULL;
2921                                 /*
2922                                  * Some cards handle busy-end interrupt
2923                                  * before the command completed, so make
2924                                  * sure we do things in the proper order.
2925                                  */
2926                                 if (host->cmd == data_cmd)
2927                                         return;
2928
2929                                 __sdhci_finish_mrq(host, data_cmd->mrq);
2930                                 return;
2931                         }
2932                 }
2933
2934                 /*
2935                  * SDHCI recovers from errors by resetting the cmd and data
2936                  * circuits. Until that is done, there very well might be more
2937                  * interrupts, so ignore them in that case.
2938                  */
2939                 if (host->pending_reset)
2940                         return;
2941
2942                 pr_err("%s: Got data interrupt 0x%08x even though no data operation was in progress.\n",
2943                        mmc_hostname(host->mmc), (unsigned)intmask);
2944                 sdhci_dumpregs(host);
2945
2946                 return;
2947         }
2948
2949         if (intmask & SDHCI_INT_DATA_TIMEOUT)
2950                 host->data->error = -ETIMEDOUT;
2951         else if (intmask & SDHCI_INT_DATA_END_BIT)
2952                 host->data->error = -EILSEQ;
2953         else if ((intmask & SDHCI_INT_DATA_CRC) &&
2954                 SDHCI_GET_CMD(sdhci_readw(host, SDHCI_COMMAND))
2955                         != MMC_BUS_TEST_R)
2956                 host->data->error = -EILSEQ;
2957         else if (intmask & SDHCI_INT_ADMA_ERROR) {
2958                 pr_err("%s: ADMA error: 0x%08x\n", mmc_hostname(host->mmc),
2959                        intmask);
2960                 sdhci_adma_show_error(host);
2961                 host->data->error = -EIO;
2962                 if (host->ops->adma_workaround)
2963                         host->ops->adma_workaround(host, intmask);
2964         }
2965
2966         if (host->data->error)
2967                 sdhci_finish_data(host);
2968         else {
2969                 if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL))
2970                         sdhci_transfer_pio(host);
2971
2972                 /*
2973                  * We currently don't do anything fancy with DMA
2974                  * boundaries, but as we can't disable the feature
2975                  * we need to at least restart the transfer.
2976                  *
2977                  * According to the spec sdhci_readl(host, SDHCI_DMA_ADDRESS)
2978                  * should return a valid address to continue from, but as
2979                  * some controllers are faulty, don't trust them.
2980                  */
2981                 if (intmask & SDHCI_INT_DMA_END) {
2982                         dma_addr_t dmastart, dmanow;
2983
2984                         dmastart = sdhci_sdma_address(host);
2985                         dmanow = dmastart + host->data->bytes_xfered;
2986                         /*
2987                          * Force update to the next DMA block boundary.
2988                          */
2989                         dmanow = (dmanow &
2990                                 ~((dma_addr_t)SDHCI_DEFAULT_BOUNDARY_SIZE - 1)) +
2991                                 SDHCI_DEFAULT_BOUNDARY_SIZE;
2992                         host->data->bytes_xfered = dmanow - dmastart;
2993                         DBG("DMA base %pad, transferred 0x%06x bytes, next %pad\n",
2994                             &dmastart, host->data->bytes_xfered, &dmanow);
2995                         sdhci_set_sdma_addr(host, dmanow);
2996                 }
2997
2998                 if (intmask & SDHCI_INT_DATA_END) {
2999                         if (host->cmd == host->data_cmd) {
3000                                 /*
3001                                  * Data managed to finish before the
3002                                  * command completed. Make sure we do
3003                                  * things in the proper order.
3004                                  */
3005                                 host->data_early = 1;
3006                         } else {
3007                                 sdhci_finish_data(host);
3008                         }
3009                 }
3010         }
3011 }
3012
3013 static inline bool sdhci_defer_done(struct sdhci_host *host,
3014                                     struct mmc_request *mrq)
3015 {
3016         struct mmc_data *data = mrq->data;
3017
3018         return host->pending_reset ||
3019                ((host->flags & SDHCI_REQ_USE_DMA) && data &&
3020                 data->host_cookie == COOKIE_MAPPED);
3021 }
3022
3023 static irqreturn_t sdhci_irq(int irq, void *dev_id)
3024 {
3025         struct mmc_request *mrqs_done[SDHCI_MAX_MRQS] = {0};
3026         irqreturn_t result = IRQ_NONE;
3027         struct sdhci_host *host = dev_id;
3028         u32 intmask, mask, unexpected = 0;
3029         int max_loops = 16;
3030         int i;
3031
3032         spin_lock(&host->lock);
3033
3034         if (host->runtime_suspended && !sdhci_sdio_irq_enabled(host)) {
3035                 spin_unlock(&host->lock);
3036                 return IRQ_NONE;
3037         }
3038
3039         intmask = sdhci_readl(host, SDHCI_INT_STATUS);
3040         if (!intmask || intmask == 0xffffffff) {
3041                 result = IRQ_NONE;
3042                 goto out;
3043         }
3044
3045         do {
3046                 DBG("IRQ status 0x%08x\n", intmask);
3047
3048                 if (host->ops->irq) {
3049                         intmask = host->ops->irq(host, intmask);
3050                         if (!intmask)
3051                                 goto cont;
3052                 }
3053
3054                 /* Clear selected interrupts. */
3055                 mask = intmask & (SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK |
3056                                   SDHCI_INT_BUS_POWER);
3057                 sdhci_writel(host, mask, SDHCI_INT_STATUS);
3058
3059                 if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
3060                         u32 present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
3061                                       SDHCI_CARD_PRESENT;
3062
3063                         /*
3064                          * There is a observation on i.mx esdhc.  INSERT
3065                          * bit will be immediately set again when it gets
3066                          * cleared, if a card is inserted.  We have to mask
3067                          * the irq to prevent interrupt storm which will
3068                          * freeze the system.  And the REMOVE gets the
3069                          * same situation.
3070                          *
3071                          * More testing are needed here to ensure it works
3072                          * for other platforms though.
3073                          */
3074                         host->ier &= ~(SDHCI_INT_CARD_INSERT |
3075                                        SDHCI_INT_CARD_REMOVE);
3076                         host->ier |= present ? SDHCI_INT_CARD_REMOVE :
3077                                                SDHCI_INT_CARD_INSERT;
3078                         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
3079                         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
3080
3081                         sdhci_writel(host, intmask & (SDHCI_INT_CARD_INSERT |
3082                                      SDHCI_INT_CARD_REMOVE), SDHCI_INT_STATUS);
3083
3084                         host->thread_isr |= intmask & (SDHCI_INT_CARD_INSERT |
3085                                                        SDHCI_INT_CARD_REMOVE);
3086                         result = IRQ_WAKE_THREAD;
3087                 }
3088
3089                 if (intmask & SDHCI_INT_CMD_MASK)
3090                         sdhci_cmd_irq(host, intmask & SDHCI_INT_CMD_MASK, &intmask);
3091
3092                 if (intmask & SDHCI_INT_DATA_MASK)
3093                         sdhci_data_irq(host, intmask & SDHCI_INT_DATA_MASK);
3094
3095                 if (intmask & SDHCI_INT_BUS_POWER)
3096                         pr_err("%s: Card is consuming too much power!\n",
3097                                 mmc_hostname(host->mmc));
3098
3099                 if (intmask & SDHCI_INT_RETUNE)
3100                         mmc_retune_needed(host->mmc);
3101
3102                 if ((intmask & SDHCI_INT_CARD_INT) &&
3103                     (host->ier & SDHCI_INT_CARD_INT)) {
3104                         sdhci_enable_sdio_irq_nolock(host, false);
3105                         sdio_signal_irq(host->mmc);
3106                 }
3107
3108                 intmask &= ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE |
3109                              SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK |
3110                              SDHCI_INT_ERROR | SDHCI_INT_BUS_POWER |
3111                              SDHCI_INT_RETUNE | SDHCI_INT_CARD_INT);
3112
3113                 if (intmask) {
3114                         unexpected |= intmask;
3115                         sdhci_writel(host, intmask, SDHCI_INT_STATUS);
3116                 }
3117 cont:
3118                 if (result == IRQ_NONE)
3119                         result = IRQ_HANDLED;
3120
3121                 intmask = sdhci_readl(host, SDHCI_INT_STATUS);
3122         } while (intmask && --max_loops);
3123
3124         /* Determine if mrqs can be completed immediately */
3125         for (i = 0; i < SDHCI_MAX_MRQS; i++) {
3126                 struct mmc_request *mrq = host->mrqs_done[i];
3127
3128                 if (!mrq)
3129                         continue;
3130
3131                 if (sdhci_defer_done(host, mrq)) {
3132                         result = IRQ_WAKE_THREAD;
3133                 } else {
3134                         mrqs_done[i] = mrq;
3135                         host->mrqs_done[i] = NULL;
3136                 }
3137         }
3138 out:
3139         spin_unlock(&host->lock);
3140
3141         /* Process mrqs ready for immediate completion */
3142         for (i = 0; i < SDHCI_MAX_MRQS; i++) {
3143                 if (mrqs_done[i])
3144                         mmc_request_done(host->mmc, mrqs_done[i]);
3145         }
3146
3147         if (unexpected) {
3148                 pr_err("%s: Unexpected interrupt 0x%08x.\n",
3149                            mmc_hostname(host->mmc), unexpected);
3150                 sdhci_dumpregs(host);
3151         }
3152
3153         return result;
3154 }
3155
3156 static irqreturn_t sdhci_thread_irq(int irq, void *dev_id)
3157 {
3158         struct sdhci_host *host = dev_id;
3159         unsigned long flags;
3160         u32 isr;
3161
3162         while (!sdhci_request_done(host))
3163                 ;
3164
3165         spin_lock_irqsave(&host->lock, flags);
3166         isr = host->thread_isr;
3167         host->thread_isr = 0;
3168         spin_unlock_irqrestore(&host->lock, flags);
3169
3170         if (isr & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
3171                 struct mmc_host *mmc = host->mmc;
3172
3173                 mmc->ops->card_event(mmc);
3174                 mmc_detect_change(mmc, msecs_to_jiffies(200));
3175         }
3176
3177         return IRQ_HANDLED;
3178 }
3179
3180 /*****************************************************************************\
3181  *                                                                           *
3182  * Suspend/resume                                                            *
3183  *                                                                           *
3184 \*****************************************************************************/
3185
3186 #ifdef CONFIG_PM
3187
3188 static bool sdhci_cd_irq_can_wakeup(struct sdhci_host *host)
3189 {
3190         return mmc_card_is_removable(host->mmc) &&
3191                !(host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) &&
3192                !mmc_can_gpio_cd(host->mmc);
3193 }
3194
3195 /*
3196  * To enable wakeup events, the corresponding events have to be enabled in
3197  * the Interrupt Status Enable register too. See 'Table 1-6: Wakeup Signal
3198  * Table' in the SD Host Controller Standard Specification.
3199  * It is useless to restore SDHCI_INT_ENABLE state in
3200  * sdhci_disable_irq_wakeups() since it will be set by
3201  * sdhci_enable_card_detection() or sdhci_init().
3202  */
3203 static bool sdhci_enable_irq_wakeups(struct sdhci_host *host)
3204 {
3205         u8 mask = SDHCI_WAKE_ON_INSERT | SDHCI_WAKE_ON_REMOVE |
3206                   SDHCI_WAKE_ON_INT;
3207         u32 irq_val = 0;
3208         u8 wake_val = 0;
3209         u8 val;
3210
3211         if (sdhci_cd_irq_can_wakeup(host)) {
3212                 wake_val |= SDHCI_WAKE_ON_INSERT | SDHCI_WAKE_ON_REMOVE;
3213                 irq_val |= SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE;
3214         }
3215
3216         if (mmc_card_wake_sdio_irq(host->mmc)) {
3217                 wake_val |= SDHCI_WAKE_ON_INT;
3218                 irq_val |= SDHCI_INT_CARD_INT;
3219         }
3220
3221         if (!irq_val)
3222                 return false;
3223
3224         val = sdhci_readb(host, SDHCI_WAKE_UP_CONTROL);
3225         val &= ~mask;
3226         val |= wake_val;
3227         sdhci_writeb(host, val, SDHCI_WAKE_UP_CONTROL);
3228
3229         sdhci_writel(host, irq_val, SDHCI_INT_ENABLE);
3230
3231         host->irq_wake_enabled = !enable_irq_wake(host->irq);
3232
3233         return host->irq_wake_enabled;
3234 }
3235
3236 static void sdhci_disable_irq_wakeups(struct sdhci_host *host)
3237 {
3238         u8 val;
3239         u8 mask = SDHCI_WAKE_ON_INSERT | SDHCI_WAKE_ON_REMOVE
3240                         | SDHCI_WAKE_ON_INT;
3241
3242         val = sdhci_readb(host, SDHCI_WAKE_UP_CONTROL);
3243         val &= ~mask;
3244         sdhci_writeb(host, val, SDHCI_WAKE_UP_CONTROL);
3245
3246         disable_irq_wake(host->irq);
3247
3248         host->irq_wake_enabled = false;
3249 }
3250
3251 int sdhci_suspend_host(struct sdhci_host *host)
3252 {
3253         sdhci_disable_card_detection(host);
3254
3255         mmc_retune_timer_stop(host->mmc);
3256
3257         if (!device_may_wakeup(mmc_dev(host->mmc)) ||
3258             !sdhci_enable_irq_wakeups(host)) {
3259                 host->ier = 0;
3260                 sdhci_writel(host, 0, SDHCI_INT_ENABLE);
3261                 sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
3262                 free_irq(host->irq, host);
3263         }
3264
3265         return 0;
3266 }
3267
3268 EXPORT_SYMBOL_GPL(sdhci_suspend_host);
3269
3270 int sdhci_resume_host(struct sdhci_host *host)
3271 {
3272         struct mmc_host *mmc = host->mmc;
3273         int ret = 0;
3274
3275         if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
3276                 if (host->ops->enable_dma)
3277                         host->ops->enable_dma(host);
3278         }
3279
3280         if ((host->mmc->pm_flags & MMC_PM_KEEP_POWER) &&
3281             (host->quirks2 & SDHCI_QUIRK2_HOST_OFF_CARD_ON)) {
3282                 /* Card keeps power but host controller does not */
3283                 sdhci_init(host, 0);
3284                 host->pwr = 0;
3285                 host->clock = 0;
3286                 mmc->ops->set_ios(mmc, &mmc->ios);
3287         } else {
3288                 sdhci_init(host, (host->mmc->pm_flags & MMC_PM_KEEP_POWER));
3289         }
3290
3291         if (host->irq_wake_enabled) {
3292                 sdhci_disable_irq_wakeups(host);
3293         } else {
3294                 ret = request_threaded_irq(host->irq, sdhci_irq,
3295                                            sdhci_thread_irq, IRQF_SHARED,
3296                                            mmc_hostname(host->mmc), host);
3297                 if (ret)
3298                         return ret;
3299         }
3300
3301         sdhci_enable_card_detection(host);
3302
3303         return ret;
3304 }
3305
3306 EXPORT_SYMBOL_GPL(sdhci_resume_host);
3307
3308 int sdhci_runtime_suspend_host(struct sdhci_host *host)
3309 {
3310         unsigned long flags;
3311
3312         mmc_retune_timer_stop(host->mmc);
3313
3314         spin_lock_irqsave(&host->lock, flags);
3315         host->ier &= SDHCI_INT_CARD_INT;
3316         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
3317         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
3318         spin_unlock_irqrestore(&host->lock, flags);
3319
3320         synchronize_hardirq(host->irq);
3321
3322         spin_lock_irqsave(&host->lock, flags);
3323         host->runtime_suspended = true;
3324         spin_unlock_irqrestore(&host->lock, flags);
3325
3326         return 0;
3327 }
3328 EXPORT_SYMBOL_GPL(sdhci_runtime_suspend_host);
3329
3330 int sdhci_runtime_resume_host(struct sdhci_host *host, int soft_reset)
3331 {
3332         struct mmc_host *mmc = host->mmc;
3333         unsigned long flags;
3334         int host_flags = host->flags;
3335
3336         if (host_flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
3337                 if (host->ops->enable_dma)
3338                         host->ops->enable_dma(host);
3339         }
3340
3341         sdhci_init(host, soft_reset);
3342
3343         if (mmc->ios.power_mode != MMC_POWER_UNDEFINED &&
3344             mmc->ios.power_mode != MMC_POWER_OFF) {
3345                 /* Force clock and power re-program */
3346                 host->pwr = 0;
3347                 host->clock = 0;
3348                 mmc->ops->start_signal_voltage_switch(mmc, &mmc->ios);
3349                 mmc->ops->set_ios(mmc, &mmc->ios);
3350
3351                 if ((host_flags & SDHCI_PV_ENABLED) &&
3352                     !(host->quirks2 & SDHCI_QUIRK2_PRESET_VALUE_BROKEN)) {
3353                         spin_lock_irqsave(&host->lock, flags);
3354                         sdhci_enable_preset_value(host, true);
3355                         spin_unlock_irqrestore(&host->lock, flags);
3356                 }
3357
3358                 if ((mmc->caps2 & MMC_CAP2_HS400_ES) &&
3359                     mmc->ops->hs400_enhanced_strobe)
3360                         mmc->ops->hs400_enhanced_strobe(mmc, &mmc->ios);
3361         }
3362
3363         spin_lock_irqsave(&host->lock, flags);
3364
3365         host->runtime_suspended = false;
3366
3367         /* Enable SDIO IRQ */
3368         if (host->flags & SDHCI_SDIO_IRQ_ENABLED)
3369                 sdhci_enable_sdio_irq_nolock(host, true);
3370
3371         /* Enable Card Detection */
3372         sdhci_enable_card_detection(host);
3373
3374         spin_unlock_irqrestore(&host->lock, flags);
3375
3376         return 0;
3377 }
3378 EXPORT_SYMBOL_GPL(sdhci_runtime_resume_host);
3379
3380 #endif /* CONFIG_PM */
3381
3382 /*****************************************************************************\
3383  *                                                                           *
3384  * Command Queue Engine (CQE) helpers                                        *
3385  *                                                                           *
3386 \*****************************************************************************/
3387
3388 void sdhci_cqe_enable(struct mmc_host *mmc)
3389 {
3390         struct sdhci_host *host = mmc_priv(mmc);
3391         unsigned long flags;
3392         u8 ctrl;
3393
3394         spin_lock_irqsave(&host->lock, flags);
3395
3396         ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
3397         ctrl &= ~SDHCI_CTRL_DMA_MASK;
3398         /*
3399          * Host from V4.10 supports ADMA3 DMA type.
3400          * ADMA3 performs integrated descriptor which is more suitable
3401          * for cmd queuing to fetch both command and transfer descriptors.
3402          */
3403         if (host->v4_mode && (host->caps1 & SDHCI_CAN_DO_ADMA3))
3404                 ctrl |= SDHCI_CTRL_ADMA3;
3405         else if (host->flags & SDHCI_USE_64_BIT_DMA)
3406                 ctrl |= SDHCI_CTRL_ADMA64;
3407         else
3408                 ctrl |= SDHCI_CTRL_ADMA32;
3409         sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
3410
3411         sdhci_writew(host, SDHCI_MAKE_BLKSZ(host->sdma_boundary, 512),
3412                      SDHCI_BLOCK_SIZE);
3413
3414         /* Set maximum timeout */
3415         sdhci_set_timeout(host, NULL);
3416
3417         host->ier = host->cqe_ier;
3418
3419         sdhci_writel(host, host->ier, SDHCI_INT_ENABLE);
3420         sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE);
3421
3422         host->cqe_on = true;
3423
3424         pr_debug("%s: sdhci: CQE on, IRQ mask %#x, IRQ status %#x\n",
3425                  mmc_hostname(mmc), host->ier,
3426                  sdhci_readl(host, SDHCI_INT_STATUS));
3427
3428         spin_unlock_irqrestore(&host->lock, flags);
3429 }
3430 EXPORT_SYMBOL_GPL(sdhci_cqe_enable);
3431
3432 void sdhci_cqe_disable(struct mmc_host *mmc, bool recovery)
3433 {
3434         struct sdhci_host *host = mmc_priv(mmc);
3435         unsigned long flags;
3436
3437         spin_lock_irqsave(&host->lock, flags);
3438
3439         sdhci_set_default_irqs(host);
3440
3441         host->cqe_on = false;
3442
3443         if (recovery) {
3444                 sdhci_do_reset(host, SDHCI_RESET_CMD);
3445                 sdhci_do_reset(host, SDHCI_RESET_DATA);
3446         }
3447
3448         pr_debug("%s: sdhci: CQE off, IRQ mask %#x, IRQ status %#x\n",
3449                  mmc_hostname(mmc), host->ier,
3450                  sdhci_readl(host, SDHCI_INT_STATUS));
3451
3452         spin_unlock_irqrestore(&host->lock, flags);
3453 }
3454 EXPORT_SYMBOL_GPL(sdhci_cqe_disable);
3455
3456 bool sdhci_cqe_irq(struct sdhci_host *host, u32 intmask, int *cmd_error,
3457                    int *data_error)
3458 {
3459         u32 mask;
3460
3461         if (!host->cqe_on)
3462                 return false;
3463
3464         if (intmask & (SDHCI_INT_INDEX | SDHCI_INT_END_BIT | SDHCI_INT_CRC))
3465                 *cmd_error = -EILSEQ;
3466         else if (intmask & SDHCI_INT_TIMEOUT)
3467                 *cmd_error = -ETIMEDOUT;
3468         else
3469                 *cmd_error = 0;
3470
3471         if (intmask & (SDHCI_INT_DATA_END_BIT | SDHCI_INT_DATA_CRC))
3472                 *data_error = -EILSEQ;
3473         else if (intmask & SDHCI_INT_DATA_TIMEOUT)
3474                 *data_error = -ETIMEDOUT;
3475         else if (intmask & SDHCI_INT_ADMA_ERROR)
3476                 *data_error = -EIO;
3477         else
3478                 *data_error = 0;
3479
3480         /* Clear selected interrupts. */
3481         mask = intmask & host->cqe_ier;
3482         sdhci_writel(host, mask, SDHCI_INT_STATUS);
3483
3484         if (intmask & SDHCI_INT_BUS_POWER)
3485                 pr_err("%s: Card is consuming too much power!\n",
3486                        mmc_hostname(host->mmc));
3487
3488         intmask &= ~(host->cqe_ier | SDHCI_INT_ERROR);
3489         if (intmask) {
3490                 sdhci_writel(host, intmask, SDHCI_INT_STATUS);
3491                 pr_err("%s: CQE: Unexpected interrupt 0x%08x.\n",
3492                        mmc_hostname(host->mmc), intmask);
3493                 sdhci_dumpregs(host);
3494         }
3495
3496         return true;
3497 }
3498 EXPORT_SYMBOL_GPL(sdhci_cqe_irq);
3499
3500 /*****************************************************************************\
3501  *                                                                           *
3502  * Device allocation/registration                                            *
3503  *                                                                           *
3504 \*****************************************************************************/
3505
3506 struct sdhci_host *sdhci_alloc_host(struct device *dev,
3507         size_t priv_size)
3508 {
3509         struct mmc_host *mmc;
3510         struct sdhci_host *host;
3511
3512         WARN_ON(dev == NULL);
3513
3514         mmc = mmc_alloc_host(sizeof(struct sdhci_host) + priv_size, dev);
3515         if (!mmc)
3516                 return ERR_PTR(-ENOMEM);
3517
3518         host = mmc_priv(mmc);
3519         host->mmc = mmc;
3520         host->mmc_host_ops = sdhci_ops;
3521         mmc->ops = &host->mmc_host_ops;
3522
3523         host->flags = SDHCI_SIGNALING_330;
3524
3525         host->cqe_ier     = SDHCI_CQE_INT_MASK;
3526         host->cqe_err_ier = SDHCI_CQE_INT_ERR_MASK;
3527
3528         host->tuning_delay = -1;
3529         host->tuning_loop_count = MAX_TUNING_LOOP;
3530
3531         host->sdma_boundary = SDHCI_DEFAULT_BOUNDARY_ARG;
3532
3533         /*
3534          * The DMA table descriptor count is calculated as the maximum
3535          * number of segments times 2, to allow for an alignment
3536          * descriptor for each segment, plus 1 for a nop end descriptor.
3537          */
3538         host->adma_table_cnt = SDHCI_MAX_SEGS * 2 + 1;
3539
3540         return host;
3541 }
3542
3543 EXPORT_SYMBOL_GPL(sdhci_alloc_host);
3544
3545 static int sdhci_set_dma_mask(struct sdhci_host *host)
3546 {
3547         struct mmc_host *mmc = host->mmc;
3548         struct device *dev = mmc_dev(mmc);
3549         int ret = -EINVAL;
3550
3551         if (host->quirks2 & SDHCI_QUIRK2_BROKEN_64_BIT_DMA)
3552                 host->flags &= ~SDHCI_USE_64_BIT_DMA;
3553
3554         /* Try 64-bit mask if hardware is capable  of it */
3555         if (host->flags & SDHCI_USE_64_BIT_DMA) {
3556                 ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64));
3557                 if (ret) {
3558                         pr_warn("%s: Failed to set 64-bit DMA mask.\n",
3559                                 mmc_hostname(mmc));
3560                         host->flags &= ~SDHCI_USE_64_BIT_DMA;
3561                 }
3562         }
3563
3564         /* 32-bit mask as default & fallback */
3565         if (ret) {
3566                 ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
3567                 if (ret)
3568                         pr_warn("%s: Failed to set 32-bit DMA mask.\n",
3569                                 mmc_hostname(mmc));
3570         }
3571
3572         return ret;
3573 }
3574
3575 void __sdhci_read_caps(struct sdhci_host *host, u16 *ver, u32 *caps, u32 *caps1)
3576 {
3577         u16 v;
3578         u64 dt_caps_mask = 0;
3579         u64 dt_caps = 0;
3580
3581         if (host->read_caps)
3582                 return;
3583
3584         host->read_caps = true;
3585
3586         if (debug_quirks)
3587                 host->quirks = debug_quirks;
3588
3589         if (debug_quirks2)
3590                 host->quirks2 = debug_quirks2;
3591
3592         sdhci_do_reset(host, SDHCI_RESET_ALL);
3593
3594         if (host->v4_mode)
3595                 sdhci_do_enable_v4_mode(host);
3596
3597         of_property_read_u64(mmc_dev(host->mmc)->of_node,
3598                              "sdhci-caps-mask", &dt_caps_mask);
3599         of_property_read_u64(mmc_dev(host->mmc)->of_node,
3600                              "sdhci-caps", &dt_caps);
3601
3602         v = ver ? *ver : sdhci_readw(host, SDHCI_HOST_VERSION);
3603         host->version = (v & SDHCI_SPEC_VER_MASK) >> SDHCI_SPEC_VER_SHIFT;
3604
3605         if (host->quirks & SDHCI_QUIRK_MISSING_CAPS)
3606                 return;
3607
3608         if (caps) {
3609                 host->caps = *caps;
3610         } else {
3611                 host->caps = sdhci_readl(host, SDHCI_CAPABILITIES);
3612                 host->caps &= ~lower_32_bits(dt_caps_mask);
3613                 host->caps |= lower_32_bits(dt_caps);
3614         }
3615
3616         if (host->version < SDHCI_SPEC_300)
3617                 return;
3618
3619         if (caps1) {
3620                 host->caps1 = *caps1;
3621         } else {
3622                 host->caps1 = sdhci_readl(host, SDHCI_CAPABILITIES_1);
3623                 host->caps1 &= ~upper_32_bits(dt_caps_mask);
3624                 host->caps1 |= upper_32_bits(dt_caps);
3625         }
3626 }
3627 EXPORT_SYMBOL_GPL(__sdhci_read_caps);
3628
3629 static void sdhci_allocate_bounce_buffer(struct sdhci_host *host)
3630 {
3631         struct mmc_host *mmc = host->mmc;
3632         unsigned int max_blocks;
3633         unsigned int bounce_size;
3634         int ret;
3635
3636         /*
3637          * Cap the bounce buffer at 64KB. Using a bigger bounce buffer
3638          * has diminishing returns, this is probably because SD/MMC
3639          * cards are usually optimized to handle this size of requests.
3640          */
3641         bounce_size = SZ_64K;
3642         /*
3643          * Adjust downwards to maximum request size if this is less
3644          * than our segment size, else hammer down the maximum
3645          * request size to the maximum buffer size.
3646          */
3647         if (mmc->max_req_size < bounce_size)
3648                 bounce_size = mmc->max_req_size;
3649         max_blocks = bounce_size / 512;
3650
3651         /*
3652          * When we just support one segment, we can get significant
3653          * speedups by the help of a bounce buffer to group scattered
3654          * reads/writes together.
3655          */
3656         host->bounce_buffer = devm_kmalloc(mmc->parent,
3657                                            bounce_size,
3658                                            GFP_KERNEL);
3659         if (!host->bounce_buffer) {
3660                 pr_err("%s: failed to allocate %u bytes for bounce buffer, falling back to single segments\n",
3661                        mmc_hostname(mmc),
3662                        bounce_size);
3663                 /*
3664                  * Exiting with zero here makes sure we proceed with
3665                  * mmc->max_segs == 1.
3666                  */
3667                 return;
3668         }
3669
3670         host->bounce_addr = dma_map_single(mmc->parent,
3671                                            host->bounce_buffer,
3672                                            bounce_size,
3673                                            DMA_BIDIRECTIONAL);
3674         ret = dma_mapping_error(mmc->parent, host->bounce_addr);
3675         if (ret)
3676                 /* Again fall back to max_segs == 1 */
3677                 return;
3678         host->bounce_buffer_size = bounce_size;
3679
3680         /* Lie about this since we're bouncing */
3681         mmc->max_segs = max_blocks;
3682         mmc->max_seg_size = bounce_size;
3683         mmc->max_req_size = bounce_size;
3684
3685         pr_info("%s bounce up to %u segments into one, max segment size %u bytes\n",
3686                 mmc_hostname(mmc), max_blocks, bounce_size);
3687 }
3688
3689 static inline bool sdhci_can_64bit_dma(struct sdhci_host *host)
3690 {
3691         /*
3692          * According to SD Host Controller spec v4.10, bit[27] added from
3693          * version 4.10 in Capabilities Register is used as 64-bit System
3694          * Address support for V4 mode.
3695          */
3696         if (host->version >= SDHCI_SPEC_410 && host->v4_mode)
3697                 return host->caps & SDHCI_CAN_64BIT_V4;
3698
3699         return host->caps & SDHCI_CAN_64BIT;
3700 }
3701
3702 int sdhci_setup_host(struct sdhci_host *host)
3703 {
3704         struct mmc_host *mmc;
3705         u32 max_current_caps;
3706         unsigned int ocr_avail;
3707         unsigned int override_timeout_clk;
3708         u32 max_clk;
3709         int ret;
3710
3711         WARN_ON(host == NULL);
3712         if (host == NULL)
3713                 return -EINVAL;
3714
3715         mmc = host->mmc;
3716
3717         /*
3718          * If there are external regulators, get them. Note this must be done
3719          * early before resetting the host and reading the capabilities so that
3720          * the host can take the appropriate action if regulators are not
3721          * available.
3722          */
3723         ret = mmc_regulator_get_supply(mmc);
3724         if (ret)
3725                 return ret;
3726
3727         DBG("Version:   0x%08x | Present:  0x%08x\n",
3728             sdhci_readw(host, SDHCI_HOST_VERSION),
3729             sdhci_readl(host, SDHCI_PRESENT_STATE));
3730         DBG("Caps:      0x%08x | Caps_1:   0x%08x\n",
3731             sdhci_readl(host, SDHCI_CAPABILITIES),
3732             sdhci_readl(host, SDHCI_CAPABILITIES_1));
3733
3734         sdhci_read_caps(host);
3735
3736         override_timeout_clk = host->timeout_clk;
3737
3738         if (host->version > SDHCI_SPEC_420) {
3739                 pr_err("%s: Unknown controller version (%d). You may experience problems.\n",
3740                        mmc_hostname(mmc), host->version);
3741         }
3742
3743         if (host->quirks & SDHCI_QUIRK_FORCE_DMA)
3744                 host->flags |= SDHCI_USE_SDMA;
3745         else if (!(host->caps & SDHCI_CAN_DO_SDMA))
3746                 DBG("Controller doesn't have SDMA capability\n");
3747         else
3748                 host->flags |= SDHCI_USE_SDMA;
3749
3750         if ((host->quirks & SDHCI_QUIRK_BROKEN_DMA) &&
3751                 (host->flags & SDHCI_USE_SDMA)) {
3752                 DBG("Disabling DMA as it is marked broken\n");
3753                 host->flags &= ~SDHCI_USE_SDMA;
3754         }
3755
3756         if ((host->version >= SDHCI_SPEC_200) &&
3757                 (host->caps & SDHCI_CAN_DO_ADMA2))
3758                 host->flags |= SDHCI_USE_ADMA;
3759
3760         if ((host->quirks & SDHCI_QUIRK_BROKEN_ADMA) &&
3761                 (host->flags & SDHCI_USE_ADMA)) {
3762                 DBG("Disabling ADMA as it is marked broken\n");
3763                 host->flags &= ~SDHCI_USE_ADMA;
3764         }
3765
3766         if (sdhci_can_64bit_dma(host))
3767                 host->flags |= SDHCI_USE_64_BIT_DMA;
3768
3769         if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
3770                 if (host->ops->set_dma_mask)
3771                         ret = host->ops->set_dma_mask(host);
3772                 else
3773                         ret = sdhci_set_dma_mask(host);
3774
3775                 if (!ret && host->ops->enable_dma)
3776                         ret = host->ops->enable_dma(host);
3777
3778                 if (ret) {
3779                         pr_warn("%s: No suitable DMA available - falling back to PIO\n",
3780                                 mmc_hostname(mmc));
3781                         host->flags &= ~(SDHCI_USE_SDMA | SDHCI_USE_ADMA);
3782
3783                         ret = 0;
3784                 }
3785         }
3786
3787         /* SDMA does not support 64-bit DMA if v4 mode not set */
3788         if ((host->flags & SDHCI_USE_64_BIT_DMA) && !host->v4_mode)
3789                 host->flags &= ~SDHCI_USE_SDMA;
3790
3791         if (host->flags & SDHCI_USE_ADMA) {
3792                 dma_addr_t dma;
3793                 void *buf;
3794
3795                 if (host->flags & SDHCI_USE_64_BIT_DMA) {
3796                         host->adma_table_sz = host->adma_table_cnt *
3797                                               SDHCI_ADMA2_64_DESC_SZ(host);
3798                         host->desc_sz = SDHCI_ADMA2_64_DESC_SZ(host);
3799                 } else {
3800                         host->adma_table_sz = host->adma_table_cnt *
3801                                               SDHCI_ADMA2_32_DESC_SZ;
3802                         host->desc_sz = SDHCI_ADMA2_32_DESC_SZ;
3803                 }
3804
3805                 host->align_buffer_sz = SDHCI_MAX_SEGS * SDHCI_ADMA2_ALIGN;
3806                 /*
3807                  * Use zalloc to zero the reserved high 32-bits of 128-bit
3808                  * descriptors so that they never need to be written.
3809                  */
3810                 buf = dma_alloc_coherent(mmc_dev(mmc),
3811                                          host->align_buffer_sz + host->adma_table_sz,
3812                                          &dma, GFP_KERNEL);
3813                 if (!buf) {
3814                         pr_warn("%s: Unable to allocate ADMA buffers - falling back to standard DMA\n",
3815                                 mmc_hostname(mmc));
3816                         host->flags &= ~SDHCI_USE_ADMA;
3817                 } else if ((dma + host->align_buffer_sz) &
3818                            (SDHCI_ADMA2_DESC_ALIGN - 1)) {
3819                         pr_warn("%s: unable to allocate aligned ADMA descriptor\n",
3820                                 mmc_hostname(mmc));
3821                         host->flags &= ~SDHCI_USE_ADMA;
3822                         dma_free_coherent(mmc_dev(mmc), host->align_buffer_sz +
3823                                           host->adma_table_sz, buf, dma);
3824                 } else {
3825                         host->align_buffer = buf;
3826                         host->align_addr = dma;
3827
3828                         host->adma_table = buf + host->align_buffer_sz;
3829                         host->adma_addr = dma + host->align_buffer_sz;
3830                 }
3831         }
3832
3833         /*
3834          * If we use DMA, then it's up to the caller to set the DMA
3835          * mask, but PIO does not need the hw shim so we set a new
3836          * mask here in that case.
3837          */
3838         if (!(host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA))) {
3839                 host->dma_mask = DMA_BIT_MASK(64);
3840                 mmc_dev(mmc)->dma_mask = &host->dma_mask;
3841         }
3842
3843         if (host->version >= SDHCI_SPEC_300)
3844                 host->max_clk = (host->caps & SDHCI_CLOCK_V3_BASE_MASK)
3845                         >> SDHCI_CLOCK_BASE_SHIFT;
3846         else
3847                 host->max_clk = (host->caps & SDHCI_CLOCK_BASE_MASK)
3848                         >> SDHCI_CLOCK_BASE_SHIFT;
3849
3850         host->max_clk *= 1000000;
3851         if (host->max_clk == 0 || host->quirks &
3852                         SDHCI_QUIRK_CAP_CLOCK_BASE_BROKEN) {
3853                 if (!host->ops->get_max_clock) {
3854                         pr_err("%s: Hardware doesn't specify base clock frequency.\n",
3855                                mmc_hostname(mmc));
3856                         ret = -ENODEV;
3857                         goto undma;
3858                 }
3859                 host->max_clk = host->ops->get_max_clock(host);
3860         }
3861
3862         /*
3863          * In case of Host Controller v3.00, find out whether clock
3864          * multiplier is supported.
3865          */
3866         host->clk_mul = (host->caps1 & SDHCI_CLOCK_MUL_MASK) >>
3867                         SDHCI_CLOCK_MUL_SHIFT;
3868
3869         /*
3870          * In case the value in Clock Multiplier is 0, then programmable
3871          * clock mode is not supported, otherwise the actual clock
3872          * multiplier is one more than the value of Clock Multiplier
3873          * in the Capabilities Register.
3874          */
3875         if (host->clk_mul)
3876                 host->clk_mul += 1;
3877
3878         /*
3879          * Set host parameters.
3880          */
3881         max_clk = host->max_clk;
3882
3883         if (host->ops->get_min_clock)
3884                 mmc->f_min = host->ops->get_min_clock(host);
3885         else if (host->version >= SDHCI_SPEC_300) {
3886                 if (host->clk_mul) {
3887                         mmc->f_min = (host->max_clk * host->clk_mul) / 1024;
3888                         max_clk = host->max_clk * host->clk_mul;
3889                 } else
3890                         mmc->f_min = host->max_clk / SDHCI_MAX_DIV_SPEC_300;
3891         } else
3892                 mmc->f_min = host->max_clk / SDHCI_MAX_DIV_SPEC_200;
3893
3894         if (!mmc->f_max || mmc->f_max > max_clk)
3895                 mmc->f_max = max_clk;
3896
3897         if (!(host->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)) {
3898                 host->timeout_clk = (host->caps & SDHCI_TIMEOUT_CLK_MASK) >>
3899                                         SDHCI_TIMEOUT_CLK_SHIFT;
3900
3901                 if (host->caps & SDHCI_TIMEOUT_CLK_UNIT)
3902                         host->timeout_clk *= 1000;
3903
3904                 if (host->timeout_clk == 0) {
3905                         if (!host->ops->get_timeout_clock) {
3906                                 pr_err("%s: Hardware doesn't specify timeout clock frequency.\n",
3907                                         mmc_hostname(mmc));
3908                                 ret = -ENODEV;
3909                                 goto undma;
3910                         }
3911
3912                         host->timeout_clk =
3913                                 DIV_ROUND_UP(host->ops->get_timeout_clock(host),
3914                                              1000);
3915                 }
3916
3917                 if (override_timeout_clk)
3918                         host->timeout_clk = override_timeout_clk;
3919
3920                 mmc->max_busy_timeout = host->ops->get_max_timeout_count ?
3921                         host->ops->get_max_timeout_count(host) : 1 << 27;
3922                 mmc->max_busy_timeout /= host->timeout_clk;
3923         }
3924
3925         if (host->quirks2 & SDHCI_QUIRK2_DISABLE_HW_TIMEOUT &&
3926             !host->ops->get_max_timeout_count)
3927                 mmc->max_busy_timeout = 0;
3928
3929         mmc->caps |= MMC_CAP_SDIO_IRQ | MMC_CAP_ERASE | MMC_CAP_CMD23;
3930         mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD;
3931
3932         if (host->quirks & SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12)
3933                 host->flags |= SDHCI_AUTO_CMD12;
3934
3935         /*
3936          * For v3 mode, Auto-CMD23 stuff only works in ADMA or PIO.
3937          * For v4 mode, SDMA may use Auto-CMD23 as well.
3938          */
3939         if ((host->version >= SDHCI_SPEC_300) &&
3940             ((host->flags & SDHCI_USE_ADMA) ||
3941              !(host->flags & SDHCI_USE_SDMA) || host->v4_mode) &&
3942              !(host->quirks2 & SDHCI_QUIRK2_ACMD23_BROKEN)) {
3943                 host->flags |= SDHCI_AUTO_CMD23;
3944                 DBG("Auto-CMD23 available\n");
3945         } else {
3946                 DBG("Auto-CMD23 unavailable\n");
3947         }
3948
3949         /*
3950          * A controller may support 8-bit width, but the board itself
3951          * might not have the pins brought out.  Boards that support
3952          * 8-bit width must set "mmc->caps |= MMC_CAP_8_BIT_DATA;" in
3953          * their platform code before calling sdhci_add_host(), and we
3954          * won't assume 8-bit width for hosts without that CAP.
3955          */
3956         if (!(host->quirks & SDHCI_QUIRK_FORCE_1_BIT_DATA))
3957                 mmc->caps |= MMC_CAP_4_BIT_DATA;
3958
3959         if (host->quirks2 & SDHCI_QUIRK2_HOST_NO_CMD23)
3960                 mmc->caps &= ~MMC_CAP_CMD23;
3961
3962         if (host->caps & SDHCI_CAN_DO_HISPD)
3963                 mmc->caps |= MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED;
3964
3965         if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) &&
3966             mmc_card_is_removable(mmc) &&
3967             mmc_gpio_get_cd(host->mmc) < 0)
3968                 mmc->caps |= MMC_CAP_NEEDS_POLL;
3969
3970         if (!IS_ERR(mmc->supply.vqmmc)) {
3971                 ret = regulator_enable(mmc->supply.vqmmc);
3972
3973                 /* If vqmmc provides no 1.8V signalling, then there's no UHS */
3974                 if (!regulator_is_supported_voltage(mmc->supply.vqmmc, 1700000,
3975                                                     1950000))
3976                         host->caps1 &= ~(SDHCI_SUPPORT_SDR104 |
3977                                          SDHCI_SUPPORT_SDR50 |
3978                                          SDHCI_SUPPORT_DDR50);
3979
3980                 /* In eMMC case vqmmc might be a fixed 1.8V regulator */
3981                 if (!regulator_is_supported_voltage(mmc->supply.vqmmc, 2700000,
3982                                                     3600000))
3983                         host->flags &= ~SDHCI_SIGNALING_330;
3984
3985                 if (ret) {
3986                         pr_warn("%s: Failed to enable vqmmc regulator: %d\n",
3987                                 mmc_hostname(mmc), ret);
3988                         mmc->supply.vqmmc = ERR_PTR(-EINVAL);
3989                 }
3990         }
3991
3992         if (host->quirks2 & SDHCI_QUIRK2_NO_1_8_V) {
3993                 host->caps1 &= ~(SDHCI_SUPPORT_SDR104 | SDHCI_SUPPORT_SDR50 |
3994                                  SDHCI_SUPPORT_DDR50);
3995                 /*
3996                  * The SDHCI controller in a SoC might support HS200/HS400
3997                  * (indicated using mmc-hs200-1_8v/mmc-hs400-1_8v dt property),
3998                  * but if the board is modeled such that the IO lines are not
3999                  * connected to 1.8v then HS200/HS400 cannot be supported.
4000                  * Disable HS200/HS400 if the board does not have 1.8v connected
4001                  * to the IO lines. (Applicable for other modes in 1.8v)
4002                  */
4003                 mmc->caps2 &= ~(MMC_CAP2_HSX00_1_8V | MMC_CAP2_HS400_ES);
4004                 mmc->caps &= ~(MMC_CAP_1_8V_DDR | MMC_CAP_UHS);
4005         }
4006
4007         /* Any UHS-I mode in caps implies SDR12 and SDR25 support. */
4008         if (host->caps1 & (SDHCI_SUPPORT_SDR104 | SDHCI_SUPPORT_SDR50 |
4009                            SDHCI_SUPPORT_DDR50))
4010                 mmc->caps |= MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
4011
4012         /* SDR104 supports also implies SDR50 support */
4013         if (host->caps1 & SDHCI_SUPPORT_SDR104) {
4014                 mmc->caps |= MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_SDR50;
4015                 /* SD3.0: SDR104 is supported so (for eMMC) the caps2
4016                  * field can be promoted to support HS200.
4017                  */
4018                 if (!(host->quirks2 & SDHCI_QUIRK2_BROKEN_HS200))
4019                         mmc->caps2 |= MMC_CAP2_HS200;
4020         } else if (host->caps1 & SDHCI_SUPPORT_SDR50) {
4021                 mmc->caps |= MMC_CAP_UHS_SDR50;
4022         }
4023
4024         if (host->quirks2 & SDHCI_QUIRK2_CAPS_BIT63_FOR_HS400 &&
4025             (host->caps1 & SDHCI_SUPPORT_HS400))
4026                 mmc->caps2 |= MMC_CAP2_HS400;
4027
4028         if ((mmc->caps2 & MMC_CAP2_HSX00_1_2V) &&
4029             (IS_ERR(mmc->supply.vqmmc) ||
4030              !regulator_is_supported_voltage(mmc->supply.vqmmc, 1100000,
4031                                              1300000)))
4032                 mmc->caps2 &= ~MMC_CAP2_HSX00_1_2V;
4033
4034         if ((host->caps1 & SDHCI_SUPPORT_DDR50) &&
4035             !(host->quirks2 & SDHCI_QUIRK2_BROKEN_DDR50))
4036                 mmc->caps |= MMC_CAP_UHS_DDR50;
4037
4038         /* Does the host need tuning for SDR50? */
4039         if (host->caps1 & SDHCI_USE_SDR50_TUNING)
4040                 host->flags |= SDHCI_SDR50_NEEDS_TUNING;
4041
4042         /* Driver Type(s) (A, C, D) supported by the host */
4043         if (host->caps1 & SDHCI_DRIVER_TYPE_A)
4044                 mmc->caps |= MMC_CAP_DRIVER_TYPE_A;
4045         if (host->caps1 & SDHCI_DRIVER_TYPE_C)
4046                 mmc->caps |= MMC_CAP_DRIVER_TYPE_C;
4047         if (host->caps1 & SDHCI_DRIVER_TYPE_D)
4048                 mmc->caps |= MMC_CAP_DRIVER_TYPE_D;
4049
4050         /* Initial value for re-tuning timer count */
4051         host->tuning_count = (host->caps1 & SDHCI_RETUNING_TIMER_COUNT_MASK) >>
4052                              SDHCI_RETUNING_TIMER_COUNT_SHIFT;
4053
4054         /*
4055          * In case Re-tuning Timer is not disabled, the actual value of
4056          * re-tuning timer will be 2 ^ (n - 1).
4057          */
4058         if (host->tuning_count)
4059                 host->tuning_count = 1 << (host->tuning_count - 1);
4060
4061         /* Re-tuning mode supported by the Host Controller */
4062         host->tuning_mode = (host->caps1 & SDHCI_RETUNING_MODE_MASK) >>
4063                              SDHCI_RETUNING_MODE_SHIFT;
4064
4065         ocr_avail = 0;
4066
4067         /*
4068          * According to SD Host Controller spec v3.00, if the Host System
4069          * can afford more than 150mA, Host Driver should set XPC to 1. Also
4070          * the value is meaningful only if Voltage Support in the Capabilities
4071          * register is set. The actual current value is 4 times the register
4072          * value.
4073          */
4074         max_current_caps = sdhci_readl(host, SDHCI_MAX_CURRENT);
4075         if (!max_current_caps && !IS_ERR(mmc->supply.vmmc)) {
4076                 int curr = regulator_get_current_limit(mmc->supply.vmmc);
4077                 if (curr > 0) {
4078
4079                         /* convert to SDHCI_MAX_CURRENT format */
4080                         curr = curr/1000;  /* convert to mA */
4081                         curr = curr/SDHCI_MAX_CURRENT_MULTIPLIER;
4082
4083                         curr = min_t(u32, curr, SDHCI_MAX_CURRENT_LIMIT);
4084                         max_current_caps =
4085                                 (curr << SDHCI_MAX_CURRENT_330_SHIFT) |
4086                                 (curr << SDHCI_MAX_CURRENT_300_SHIFT) |
4087                                 (curr << SDHCI_MAX_CURRENT_180_SHIFT);
4088                 }
4089         }
4090
4091         if (host->caps & SDHCI_CAN_VDD_330) {
4092                 ocr_avail |= MMC_VDD_32_33 | MMC_VDD_33_34;
4093
4094                 mmc->max_current_330 = ((max_current_caps &
4095                                    SDHCI_MAX_CURRENT_330_MASK) >>
4096                                    SDHCI_MAX_CURRENT_330_SHIFT) *
4097                                    SDHCI_MAX_CURRENT_MULTIPLIER;
4098         }
4099         if (host->caps & SDHCI_CAN_VDD_300) {
4100                 ocr_avail |= MMC_VDD_29_30 | MMC_VDD_30_31;
4101
4102                 mmc->max_current_300 = ((max_current_caps &
4103                                    SDHCI_MAX_CURRENT_300_MASK) >>
4104                                    SDHCI_MAX_CURRENT_300_SHIFT) *
4105                                    SDHCI_MAX_CURRENT_MULTIPLIER;
4106         }
4107         if (host->caps & SDHCI_CAN_VDD_180) {
4108                 ocr_avail |= MMC_VDD_165_195;
4109
4110                 mmc->max_current_180 = ((max_current_caps &
4111                                    SDHCI_MAX_CURRENT_180_MASK) >>
4112                                    SDHCI_MAX_CURRENT_180_SHIFT) *
4113                                    SDHCI_MAX_CURRENT_MULTIPLIER;
4114         }
4115
4116         /* If OCR set by host, use it instead. */
4117         if (host->ocr_mask)
4118                 ocr_avail = host->ocr_mask;
4119
4120         /* If OCR set by external regulators, give it highest prio. */
4121         if (mmc->ocr_avail)
4122                 ocr_avail = mmc->ocr_avail;
4123
4124         mmc->ocr_avail = ocr_avail;
4125         mmc->ocr_avail_sdio = ocr_avail;
4126         if (host->ocr_avail_sdio)
4127                 mmc->ocr_avail_sdio &= host->ocr_avail_sdio;
4128         mmc->ocr_avail_sd = ocr_avail;
4129         if (host->ocr_avail_sd)
4130                 mmc->ocr_avail_sd &= host->ocr_avail_sd;
4131         else /* normal SD controllers don't support 1.8V */
4132                 mmc->ocr_avail_sd &= ~MMC_VDD_165_195;
4133         mmc->ocr_avail_mmc = ocr_avail;
4134         if (host->ocr_avail_mmc)
4135                 mmc->ocr_avail_mmc &= host->ocr_avail_mmc;
4136
4137         if (mmc->ocr_avail == 0) {
4138                 pr_err("%s: Hardware doesn't report any support voltages.\n",
4139                        mmc_hostname(mmc));
4140                 ret = -ENODEV;
4141                 goto unreg;
4142         }
4143
4144         if ((mmc->caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
4145                           MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR104 |
4146                           MMC_CAP_UHS_DDR50 | MMC_CAP_1_8V_DDR)) ||
4147             (mmc->caps2 & (MMC_CAP2_HS200_1_8V_SDR | MMC_CAP2_HS400_1_8V)))
4148                 host->flags |= SDHCI_SIGNALING_180;
4149
4150         if (mmc->caps2 & MMC_CAP2_HSX00_1_2V)
4151                 host->flags |= SDHCI_SIGNALING_120;
4152
4153         spin_lock_init(&host->lock);
4154
4155         /*
4156          * Maximum number of sectors in one transfer. Limited by SDMA boundary
4157          * size (512KiB). Note some tuning modes impose a 4MiB limit, but this
4158          * is less anyway.
4159          */
4160         mmc->max_req_size = 524288;
4161
4162         /*
4163          * Maximum number of segments. Depends on if the hardware
4164          * can do scatter/gather or not.
4165          */
4166         if (host->flags & SDHCI_USE_ADMA) {
4167                 mmc->max_segs = SDHCI_MAX_SEGS;
4168         } else if (host->flags & SDHCI_USE_SDMA) {
4169                 mmc->max_segs = 1;
4170                 if (swiotlb_max_segment()) {
4171                         unsigned int max_req_size = (1 << IO_TLB_SHIFT) *
4172                                                 IO_TLB_SEGSIZE;
4173                         mmc->max_req_size = min(mmc->max_req_size,
4174                                                 max_req_size);
4175                 }
4176         } else { /* PIO */
4177                 mmc->max_segs = SDHCI_MAX_SEGS;
4178         }
4179
4180         /*
4181          * Maximum segment size. Could be one segment with the maximum number
4182          * of bytes. When doing hardware scatter/gather, each entry cannot
4183          * be larger than 64 KiB though.
4184          */
4185         if (host->flags & SDHCI_USE_ADMA) {
4186                 if (host->quirks & SDHCI_QUIRK_BROKEN_ADMA_ZEROLEN_DESC)
4187                         mmc->max_seg_size = 65535;
4188                 else
4189                         mmc->max_seg_size = 65536;
4190         } else {
4191                 mmc->max_seg_size = mmc->max_req_size;
4192         }
4193
4194         /*
4195          * Maximum block size. This varies from controller to controller and
4196          * is specified in the capabilities register.
4197          */
4198         if (host->quirks & SDHCI_QUIRK_FORCE_BLK_SZ_2048) {
4199                 mmc->max_blk_size = 2;
4200         } else {
4201                 mmc->max_blk_size = (host->caps & SDHCI_MAX_BLOCK_MASK) >>
4202                                 SDHCI_MAX_BLOCK_SHIFT;
4203                 if (mmc->max_blk_size >= 3) {
4204                         pr_warn("%s: Invalid maximum block size, assuming 512 bytes\n",
4205                                 mmc_hostname(mmc));
4206                         mmc->max_blk_size = 0;
4207                 }
4208         }
4209
4210         mmc->max_blk_size = 512 << mmc->max_blk_size;
4211
4212         /*
4213          * Maximum block count.
4214          */
4215         mmc->max_blk_count = (host->quirks & SDHCI_QUIRK_NO_MULTIBLOCK) ? 1 : 65535;
4216
4217         if (mmc->max_segs == 1)
4218                 /* This may alter mmc->*_blk_* parameters */
4219                 sdhci_allocate_bounce_buffer(host);
4220
4221         return 0;
4222
4223 unreg:
4224         if (!IS_ERR(mmc->supply.vqmmc))
4225                 regulator_disable(mmc->supply.vqmmc);
4226 undma:
4227         if (host->align_buffer)
4228                 dma_free_coherent(mmc_dev(mmc), host->align_buffer_sz +
4229                                   host->adma_table_sz, host->align_buffer,
4230                                   host->align_addr);
4231         host->adma_table = NULL;
4232         host->align_buffer = NULL;
4233
4234         return ret;
4235 }
4236 EXPORT_SYMBOL_GPL(sdhci_setup_host);
4237
4238 void sdhci_cleanup_host(struct sdhci_host *host)
4239 {
4240         struct mmc_host *mmc = host->mmc;
4241
4242         if (!IS_ERR(mmc->supply.vqmmc))
4243                 regulator_disable(mmc->supply.vqmmc);
4244
4245         if (host->align_buffer)
4246                 dma_free_coherent(mmc_dev(mmc), host->align_buffer_sz +
4247                                   host->adma_table_sz, host->align_buffer,
4248                                   host->align_addr);
4249         host->adma_table = NULL;
4250         host->align_buffer = NULL;
4251 }
4252 EXPORT_SYMBOL_GPL(sdhci_cleanup_host);
4253
4254 int __sdhci_add_host(struct sdhci_host *host)
4255 {
4256         unsigned int flags = WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_HIGHPRI;
4257         struct mmc_host *mmc = host->mmc;
4258         int ret;
4259
4260         host->complete_wq = alloc_workqueue("sdhci", flags, 0);
4261         if (!host->complete_wq)
4262                 return -ENOMEM;
4263
4264         INIT_WORK(&host->complete_work, sdhci_complete_work);
4265
4266         timer_setup(&host->timer, sdhci_timeout_timer, 0);
4267         timer_setup(&host->data_timer, sdhci_timeout_data_timer, 0);
4268
4269         init_waitqueue_head(&host->buf_ready_int);
4270
4271         sdhci_init(host, 0);
4272
4273         ret = request_threaded_irq(host->irq, sdhci_irq, sdhci_thread_irq,
4274                                    IRQF_SHARED, mmc_hostname(mmc), host);
4275         if (ret) {
4276                 pr_err("%s: Failed to request IRQ %d: %d\n",
4277                        mmc_hostname(mmc), host->irq, ret);
4278                 goto unwq;
4279         }
4280
4281         ret = sdhci_led_register(host);
4282         if (ret) {
4283                 pr_err("%s: Failed to register LED device: %d\n",
4284                        mmc_hostname(mmc), ret);
4285                 goto unirq;
4286         }
4287
4288         ret = mmc_add_host(mmc);
4289         if (ret)
4290                 goto unled;
4291
4292         pr_info("%s: SDHCI controller on %s [%s] using %s\n",
4293                 mmc_hostname(mmc), host->hw_name, dev_name(mmc_dev(mmc)),
4294                 (host->flags & SDHCI_USE_ADMA) ?
4295                 (host->flags & SDHCI_USE_64_BIT_DMA) ? "ADMA 64-bit" : "ADMA" :
4296                 (host->flags & SDHCI_USE_SDMA) ? "DMA" : "PIO");
4297
4298         sdhci_enable_card_detection(host);
4299
4300         return 0;
4301
4302 unled:
4303         sdhci_led_unregister(host);
4304 unirq:
4305         sdhci_do_reset(host, SDHCI_RESET_ALL);
4306         sdhci_writel(host, 0, SDHCI_INT_ENABLE);
4307         sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
4308         free_irq(host->irq, host);
4309 unwq:
4310         destroy_workqueue(host->complete_wq);
4311
4312         return ret;
4313 }
4314 EXPORT_SYMBOL_GPL(__sdhci_add_host);
4315
4316 int sdhci_add_host(struct sdhci_host *host)
4317 {
4318         int ret;
4319
4320         ret = sdhci_setup_host(host);
4321         if (ret)
4322                 return ret;
4323
4324         ret = __sdhci_add_host(host);
4325         if (ret)
4326                 goto cleanup;
4327
4328         return 0;
4329
4330 cleanup:
4331         sdhci_cleanup_host(host);
4332
4333         return ret;
4334 }
4335 EXPORT_SYMBOL_GPL(sdhci_add_host);
4336
4337 void sdhci_remove_host(struct sdhci_host *host, int dead)
4338 {
4339         struct mmc_host *mmc = host->mmc;
4340         unsigned long flags;
4341
4342         if (dead) {
4343                 spin_lock_irqsave(&host->lock, flags);
4344
4345                 host->flags |= SDHCI_DEVICE_DEAD;
4346
4347                 if (sdhci_has_requests(host)) {
4348                         pr_err("%s: Controller removed during "
4349                                 " transfer!\n", mmc_hostname(mmc));
4350                         sdhci_error_out_mrqs(host, -ENOMEDIUM);
4351                 }
4352
4353                 spin_unlock_irqrestore(&host->lock, flags);
4354         }
4355
4356         sdhci_disable_card_detection(host);
4357
4358         mmc_remove_host(mmc);
4359
4360         sdhci_led_unregister(host);
4361
4362         if (!dead)
4363                 sdhci_do_reset(host, SDHCI_RESET_ALL);
4364
4365         sdhci_writel(host, 0, SDHCI_INT_ENABLE);
4366         sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
4367         free_irq(host->irq, host);
4368
4369         del_timer_sync(&host->timer);
4370         del_timer_sync(&host->data_timer);
4371
4372         destroy_workqueue(host->complete_wq);
4373
4374         if (!IS_ERR(mmc->supply.vqmmc))
4375                 regulator_disable(mmc->supply.vqmmc);
4376
4377         if (host->align_buffer)
4378                 dma_free_coherent(mmc_dev(mmc), host->align_buffer_sz +
4379                                   host->adma_table_sz, host->align_buffer,
4380                                   host->align_addr);
4381
4382         host->adma_table = NULL;
4383         host->align_buffer = NULL;
4384 }
4385
4386 EXPORT_SYMBOL_GPL(sdhci_remove_host);
4387
4388 void sdhci_free_host(struct sdhci_host *host)
4389 {
4390         mmc_free_host(host->mmc);
4391 }
4392
4393 EXPORT_SYMBOL_GPL(sdhci_free_host);
4394
4395 /*****************************************************************************\
4396  *                                                                           *
4397  * Driver init/exit                                                          *
4398  *                                                                           *
4399 \*****************************************************************************/
4400
4401 static int __init sdhci_drv_init(void)
4402 {
4403         pr_info(DRIVER_NAME
4404                 ": Secure Digital Host Controller Interface driver\n");
4405         pr_info(DRIVER_NAME ": Copyright(c) Pierre Ossman\n");
4406
4407         return 0;
4408 }
4409
4410 static void __exit sdhci_drv_exit(void)
4411 {
4412 }
4413
4414 module_init(sdhci_drv_init);
4415 module_exit(sdhci_drv_exit);
4416
4417 module_param(debug_quirks, uint, 0444);
4418 module_param(debug_quirks2, uint, 0444);
4419
4420 MODULE_AUTHOR("Pierre Ossman <pierre@ossman.eu>");
4421 MODULE_DESCRIPTION("Secure Digital Host Controller Interface core driver");
4422 MODULE_LICENSE("GPL");
4423
4424 MODULE_PARM_DESC(debug_quirks, "Force certain quirks.");
4425 MODULE_PARM_DESC(debug_quirks2, "Force certain other quirks.");