Merge commit 'v3.0' into android-3.0
[firefly-linux-kernel-4.4.55.git] / drivers / mmc / core / core.c
1 /*
2  *  linux/drivers/mmc/core/core.c
3  *
4  *  Copyright (C) 2003-2004 Russell King, All Rights Reserved.
5  *  SD support Copyright (C) 2004 Ian Molton, All Rights Reserved.
6  *  Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved.
7  *  MMCv4 support Copyright (C) 2006 Philip Langdale, All Rights Reserved.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13 #include <linux/module.h>
14 #include <linux/init.h>
15 #include <linux/interrupt.h>
16 #include <linux/completion.h>
17 #include <linux/device.h>
18 #include <linux/delay.h>
19 #include <linux/pagemap.h>
20 #include <linux/err.h>
21 #include <linux/leds.h>
22 #include <linux/scatterlist.h>
23 #include <linux/log2.h>
24 #include <linux/regulator/consumer.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/wakelock.h>
27
28 #include <linux/mmc/card.h>
29 #include <linux/mmc/host.h>
30 #include <linux/mmc/mmc.h>
31 #include <linux/mmc/sd.h>
32
33 #include "core.h"
34 #include "bus.h"
35 #include "host.h"
36 #include "sdio_bus.h"
37
38 #include "mmc_ops.h"
39 #include "sd_ops.h"
40 #include "sdio_ops.h"
41
42 static struct workqueue_struct *workqueue;
43 static struct wake_lock mmc_delayed_work_wake_lock;
44
45 /*
46  * Enabling software CRCs on the data blocks can be a significant (30%)
47  * performance cost, and for other reasons may not always be desired.
48  * So we allow it it to be disabled.
49  */
50 int use_spi_crc = 1;
51 module_param(use_spi_crc, bool, 0);
52
53 /*
54  * We normally treat cards as removed during suspend if they are not
55  * known to be on a non-removable bus, to avoid the risk of writing
56  * back data to a different card after resume.  Allow this to be
57  * overridden if necessary.
58  */
59 #ifdef CONFIG_MMC_UNSAFE_RESUME
60 int mmc_assume_removable;
61 #else
62 int mmc_assume_removable = 1;
63 #endif
64 EXPORT_SYMBOL(mmc_assume_removable);
65 module_param_named(removable, mmc_assume_removable, bool, 0644);
66 MODULE_PARM_DESC(
67         removable,
68         "MMC/SD cards are removable and may be removed during suspend");
69
70 /*
71  * Internal function. Schedule delayed work in the MMC work queue.
72  */
73 static int mmc_schedule_delayed_work(struct delayed_work *work,
74                                      unsigned long delay)
75 {
76         wake_lock(&mmc_delayed_work_wake_lock);
77         return queue_delayed_work(workqueue, work, delay);
78 }
79
80 /*
81  * Internal function. Flush all scheduled work from the MMC work queue.
82  */
83 static void mmc_flush_scheduled_work(void)
84 {
85         flush_workqueue(workqueue);
86 }
87
88 /**
89  *      mmc_request_done - finish processing an MMC request
90  *      @host: MMC host which completed request
91  *      @mrq: MMC request which request
92  *
93  *      MMC drivers should call this function when they have completed
94  *      their processing of a request.
95  */
96 void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
97 {
98         struct mmc_command *cmd = mrq->cmd;
99         int err = cmd->error;
100
101         if (err && cmd->retries && mmc_host_is_spi(host)) {
102                 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
103                         cmd->retries = 0;
104         }
105
106         if (err && cmd->retries) {
107                 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
108                         mmc_hostname(host), cmd->opcode, err);
109
110                 cmd->retries--;
111                 cmd->error = 0;
112                 host->ops->request(host, mrq);
113         } else {
114                 led_trigger_event(host->led, LED_OFF);
115
116                 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
117                         mmc_hostname(host), cmd->opcode, err,
118                         cmd->resp[0], cmd->resp[1],
119                         cmd->resp[2], cmd->resp[3]);
120
121                 if (mrq->data) {
122                         pr_debug("%s:     %d bytes transferred: %d\n",
123                                 mmc_hostname(host),
124                                 mrq->data->bytes_xfered, mrq->data->error);
125                 }
126
127                 if (mrq->stop) {
128                         pr_debug("%s:     (CMD%u): %d: %08x %08x %08x %08x\n",
129                                 mmc_hostname(host), mrq->stop->opcode,
130                                 mrq->stop->error,
131                                 mrq->stop->resp[0], mrq->stop->resp[1],
132                                 mrq->stop->resp[2], mrq->stop->resp[3]);
133                 }
134
135                 if (mrq->done)
136                         mrq->done(mrq);
137
138                 mmc_host_clk_gate(host);
139         }
140 }
141
142 EXPORT_SYMBOL(mmc_request_done);
143
144 static void
145 mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
146 {
147 #ifdef CONFIG_MMC_DEBUG
148         unsigned int i, sz;
149         struct scatterlist *sg;
150 #endif
151
152         pr_debug("%s: starting CMD%u arg %08x flags %08x\n",
153                  mmc_hostname(host), mrq->cmd->opcode,
154                  mrq->cmd->arg, mrq->cmd->flags);
155
156         if (mrq->data) {
157                 pr_debug("%s:     blksz %d blocks %d flags %08x "
158                         "tsac %d ms nsac %d\n",
159                         mmc_hostname(host), mrq->data->blksz,
160                         mrq->data->blocks, mrq->data->flags,
161                         mrq->data->timeout_ns / 1000000,
162                         mrq->data->timeout_clks);
163         }
164
165         if (mrq->stop) {
166                 pr_debug("%s:     CMD%u arg %08x flags %08x\n",
167                          mmc_hostname(host), mrq->stop->opcode,
168                          mrq->stop->arg, mrq->stop->flags);
169         }
170
171         WARN_ON(!host->claimed);
172
173         mrq->cmd->error = 0;
174         mrq->cmd->mrq = mrq;
175         if (mrq->data) {
176                 BUG_ON(mrq->data->blksz > host->max_blk_size);
177                 BUG_ON(mrq->data->blocks > host->max_blk_count);
178                 BUG_ON(mrq->data->blocks * mrq->data->blksz >
179                         host->max_req_size);
180
181 #ifdef CONFIG_MMC_DEBUG
182                 sz = 0;
183                 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
184                         sz += sg->length;
185                 BUG_ON(sz != mrq->data->blocks * mrq->data->blksz);
186 #endif
187
188                 mrq->cmd->data = mrq->data;
189                 mrq->data->error = 0;
190                 mrq->data->mrq = mrq;
191                 if (mrq->stop) {
192                         mrq->data->stop = mrq->stop;
193                         mrq->stop->error = 0;
194                         mrq->stop->mrq = mrq;
195                 }
196         }
197         mmc_host_clk_ungate(host);
198         led_trigger_event(host->led, LED_FULL);
199         host->ops->request(host, mrq);
200 }
201
202 static void mmc_wait_done(struct mmc_request *mrq)
203 {
204         complete(mrq->done_data);
205 }
206
207 /**
208  *      mmc_wait_for_req - start a request and wait for completion
209  *      @host: MMC host to start command
210  *      @mrq: MMC request to start
211  *
212  *      Start a new MMC custom command request for a host, and wait
213  *      for the command to complete. Does not attempt to parse the
214  *      response.
215  */
216 void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
217 {
218         DECLARE_COMPLETION_ONSTACK(complete);
219
220         mrq->done_data = &complete;
221         mrq->done = mmc_wait_done;
222
223         mmc_start_request(host, mrq);
224
225         wait_for_completion(&complete);
226 }
227
228 EXPORT_SYMBOL(mmc_wait_for_req);
229
230 /**
231  *      mmc_wait_for_cmd - start a command and wait for completion
232  *      @host: MMC host to start command
233  *      @cmd: MMC command to start
234  *      @retries: maximum number of retries
235  *
236  *      Start a new MMC command for a host, and wait for the command
237  *      to complete.  Return any error that occurred while the command
238  *      was executing.  Do not attempt to parse the response.
239  */
240 int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
241 {
242         struct mmc_request mrq = {0};
243
244         WARN_ON(!host->claimed);
245
246         memset(cmd->resp, 0, sizeof(cmd->resp));
247         cmd->retries = retries;
248
249         mrq.cmd = cmd;
250         cmd->data = NULL;
251
252         mmc_wait_for_req(host, &mrq);
253
254         return cmd->error;
255 }
256
257 EXPORT_SYMBOL(mmc_wait_for_cmd);
258
259 /**
260  *      mmc_set_data_timeout - set the timeout for a data command
261  *      @data: data phase for command
262  *      @card: the MMC card associated with the data transfer
263  *
264  *      Computes the data timeout parameters according to the
265  *      correct algorithm given the card type.
266  */
267 void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
268 {
269         unsigned int mult;
270
271         /*
272          * SDIO cards only define an upper 1 s limit on access.
273          */
274         if (mmc_card_sdio(card)) {
275                 data->timeout_ns = 1000000000;
276                 data->timeout_clks = 0;
277                 return;
278         }
279
280         /*
281          * SD cards use a 100 multiplier rather than 10
282          */
283         mult = mmc_card_sd(card) ? 100 : 10;
284
285         /*
286          * Scale up the multiplier (and therefore the timeout) by
287          * the r2w factor for writes.
288          */
289         if (data->flags & MMC_DATA_WRITE)
290                 mult <<= card->csd.r2w_factor;
291
292         data->timeout_ns = card->csd.tacc_ns * mult;
293         data->timeout_clks = card->csd.tacc_clks * mult;
294
295         /*
296          * SD cards also have an upper limit on the timeout.
297          */
298         if (mmc_card_sd(card)) {
299                 unsigned int timeout_us, limit_us;
300
301                 timeout_us = data->timeout_ns / 1000;
302                 if (mmc_host_clk_rate(card->host))
303                         timeout_us += data->timeout_clks * 1000 /
304                                 (mmc_host_clk_rate(card->host) / 1000);
305
306                 if (data->flags & MMC_DATA_WRITE)
307                         /*
308                          * The limit is really 250 ms, but that is
309                          * insufficient for some crappy cards.
310                          */
311                         limit_us = 300000;
312                 else
313                         limit_us = 100000;
314
315                 /*
316                  * SDHC cards always use these fixed values.
317                  */
318                 if (timeout_us > limit_us || mmc_card_blockaddr(card)) {
319                         data->timeout_ns = limit_us * 1000;
320                         data->timeout_clks = 0;
321                 }
322         }
323         /*
324          * Some cards need very high timeouts if driven in SPI mode.
325          * The worst observed timeout was 900ms after writing a
326          * continuous stream of data until the internal logic
327          * overflowed.
328          */
329         if (mmc_host_is_spi(card->host)) {
330                 if (data->flags & MMC_DATA_WRITE) {
331                         if (data->timeout_ns < 1000000000)
332                                 data->timeout_ns = 1000000000;  /* 1s */
333                 } else {
334                         if (data->timeout_ns < 100000000)
335                                 data->timeout_ns =  100000000;  /* 100ms */
336                 }
337         }
338 }
339 EXPORT_SYMBOL(mmc_set_data_timeout);
340
341 /**
342  *      mmc_align_data_size - pads a transfer size to a more optimal value
343  *      @card: the MMC card associated with the data transfer
344  *      @sz: original transfer size
345  *
346  *      Pads the original data size with a number of extra bytes in
347  *      order to avoid controller bugs and/or performance hits
348  *      (e.g. some controllers revert to PIO for certain sizes).
349  *
350  *      Returns the improved size, which might be unmodified.
351  *
352  *      Note that this function is only relevant when issuing a
353  *      single scatter gather entry.
354  */
355 unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
356 {
357         /*
358          * FIXME: We don't have a system for the controller to tell
359          * the core about its problems yet, so for now we just 32-bit
360          * align the size.
361          */
362         sz = ((sz + 3) / 4) * 4;
363
364         return sz;
365 }
366 EXPORT_SYMBOL(mmc_align_data_size);
367
368 /**
369  *      mmc_host_enable - enable a host.
370  *      @host: mmc host to enable
371  *
372  *      Hosts that support power saving can use the 'enable' and 'disable'
373  *      methods to exit and enter power saving states. For more information
374  *      see comments for struct mmc_host_ops.
375  */
376 int mmc_host_enable(struct mmc_host *host)
377 {
378         if (!(host->caps & MMC_CAP_DISABLE))
379                 return 0;
380
381         if (host->en_dis_recurs)
382                 return 0;
383
384         if (host->nesting_cnt++)
385                 return 0;
386
387         cancel_delayed_work_sync(&host->disable);
388
389         if (host->enabled)
390                 return 0;
391
392         if (host->ops->enable) {
393                 int err;
394
395                 host->en_dis_recurs = 1;
396                 err = host->ops->enable(host);
397                 host->en_dis_recurs = 0;
398
399                 if (err) {
400                         pr_debug("%s: enable error %d\n",
401                                  mmc_hostname(host), err);
402                         return err;
403                 }
404         }
405         host->enabled = 1;
406         return 0;
407 }
408 EXPORT_SYMBOL(mmc_host_enable);
409
410 static int mmc_host_do_disable(struct mmc_host *host, int lazy)
411 {
412         if (host->ops->disable) {
413                 int err;
414
415                 host->en_dis_recurs = 1;
416                 err = host->ops->disable(host, lazy);
417                 host->en_dis_recurs = 0;
418
419                 if (err < 0) {
420                         pr_debug("%s: disable error %d\n",
421                                  mmc_hostname(host), err);
422                         return err;
423                 }
424                 if (err > 0) {
425                         unsigned long delay = msecs_to_jiffies(err);
426
427                         mmc_schedule_delayed_work(&host->disable, delay);
428                 }
429         }
430         host->enabled = 0;
431         return 0;
432 }
433
434 /**
435  *      mmc_host_disable - disable a host.
436  *      @host: mmc host to disable
437  *
438  *      Hosts that support power saving can use the 'enable' and 'disable'
439  *      methods to exit and enter power saving states. For more information
440  *      see comments for struct mmc_host_ops.
441  */
442 int mmc_host_disable(struct mmc_host *host)
443 {
444         int err;
445
446         if (!(host->caps & MMC_CAP_DISABLE))
447                 return 0;
448
449         if (host->en_dis_recurs)
450                 return 0;
451
452         if (--host->nesting_cnt)
453                 return 0;
454
455         if (!host->enabled)
456                 return 0;
457
458         err = mmc_host_do_disable(host, 0);
459         return err;
460 }
461 EXPORT_SYMBOL(mmc_host_disable);
462
463 /**
464  *      __mmc_claim_host - exclusively claim a host
465  *      @host: mmc host to claim
466  *      @abort: whether or not the operation should be aborted
467  *
468  *      Claim a host for a set of operations.  If @abort is non null and
469  *      dereference a non-zero value then this will return prematurely with
470  *      that non-zero value without acquiring the lock.  Returns zero
471  *      with the lock held otherwise.
472  */
473 int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
474 {
475         DECLARE_WAITQUEUE(wait, current);
476         unsigned long flags;
477         int stop;
478
479         might_sleep();
480
481         add_wait_queue(&host->wq, &wait);
482         spin_lock_irqsave(&host->lock, flags);
483         while (1) {
484                 set_current_state(TASK_UNINTERRUPTIBLE);
485                 stop = abort ? atomic_read(abort) : 0;
486                 if (stop || !host->claimed || host->claimer == current)
487                         break;
488                 spin_unlock_irqrestore(&host->lock, flags);
489                 schedule();
490                 spin_lock_irqsave(&host->lock, flags);
491         }
492         set_current_state(TASK_RUNNING);
493         if (!stop) {
494                 host->claimed = 1;
495                 host->claimer = current;
496                 host->claim_cnt += 1;
497         } else
498                 wake_up(&host->wq);
499         spin_unlock_irqrestore(&host->lock, flags);
500         remove_wait_queue(&host->wq, &wait);
501         if (!stop)
502                 mmc_host_enable(host);
503         return stop;
504 }
505
506 EXPORT_SYMBOL(__mmc_claim_host);
507
508 /**
509  *      mmc_try_claim_host - try exclusively to claim a host
510  *      @host: mmc host to claim
511  *
512  *      Returns %1 if the host is claimed, %0 otherwise.
513  */
514 int mmc_try_claim_host(struct mmc_host *host)
515 {
516         int claimed_host = 0;
517         unsigned long flags;
518
519         spin_lock_irqsave(&host->lock, flags);
520         if (!host->claimed || host->claimer == current) {
521                 host->claimed = 1;
522                 host->claimer = current;
523                 host->claim_cnt += 1;
524                 claimed_host = 1;
525         }
526         spin_unlock_irqrestore(&host->lock, flags);
527         return claimed_host;
528 }
529 EXPORT_SYMBOL(mmc_try_claim_host);
530
531 /**
532  *      mmc_do_release_host - release a claimed host
533  *      @host: mmc host to release
534  *
535  *      If you successfully claimed a host, this function will
536  *      release it again.
537  */
538 void mmc_do_release_host(struct mmc_host *host)
539 {
540         unsigned long flags;
541
542         spin_lock_irqsave(&host->lock, flags);
543         if (--host->claim_cnt) {
544                 /* Release for nested claim */
545                 spin_unlock_irqrestore(&host->lock, flags);
546         } else {
547                 host->claimed = 0;
548                 host->claimer = NULL;
549                 spin_unlock_irqrestore(&host->lock, flags);
550                 wake_up(&host->wq);
551         }
552 }
553 EXPORT_SYMBOL(mmc_do_release_host);
554
555 void mmc_host_deeper_disable(struct work_struct *work)
556 {
557         struct mmc_host *host =
558                 container_of(work, struct mmc_host, disable.work);
559
560         /* If the host is claimed then we do not want to disable it anymore */
561         if (!mmc_try_claim_host(host))
562                 goto out;
563         mmc_host_do_disable(host, 1);
564         mmc_do_release_host(host);
565
566 out:
567         wake_unlock(&mmc_delayed_work_wake_lock);
568 }
569
570 /**
571  *      mmc_host_lazy_disable - lazily disable a host.
572  *      @host: mmc host to disable
573  *
574  *      Hosts that support power saving can use the 'enable' and 'disable'
575  *      methods to exit and enter power saving states. For more information
576  *      see comments for struct mmc_host_ops.
577  */
578 int mmc_host_lazy_disable(struct mmc_host *host)
579 {
580         if (!(host->caps & MMC_CAP_DISABLE))
581                 return 0;
582
583         if (host->en_dis_recurs)
584                 return 0;
585
586         if (--host->nesting_cnt)
587                 return 0;
588
589         if (!host->enabled)
590                 return 0;
591
592         if (host->disable_delay) {
593                 mmc_schedule_delayed_work(&host->disable,
594                                 msecs_to_jiffies(host->disable_delay));
595                 return 0;
596         } else
597                 return mmc_host_do_disable(host, 1);
598 }
599 EXPORT_SYMBOL(mmc_host_lazy_disable);
600
601 /**
602  *      mmc_release_host - release a host
603  *      @host: mmc host to release
604  *
605  *      Release a MMC host, allowing others to claim the host
606  *      for their operations.
607  */
608 void mmc_release_host(struct mmc_host *host)
609 {
610         WARN_ON(!host->claimed);
611
612         mmc_host_lazy_disable(host);
613
614         mmc_do_release_host(host);
615 }
616
617 EXPORT_SYMBOL(mmc_release_host);
618
619 /*
620  * Internal function that does the actual ios call to the host driver,
621  * optionally printing some debug output.
622  */
623 static inline void mmc_set_ios(struct mmc_host *host)
624 {
625         struct mmc_ios *ios = &host->ios;
626
627         pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
628                 "width %u timing %u\n",
629                  mmc_hostname(host), ios->clock, ios->bus_mode,
630                  ios->power_mode, ios->chip_select, ios->vdd,
631                  ios->bus_width, ios->timing);
632
633         if (ios->clock > 0)
634                 mmc_set_ungated(host);
635         host->ops->set_ios(host, ios);
636 }
637
638 /*
639  * Control chip select pin on a host.
640  */
641 void mmc_set_chip_select(struct mmc_host *host, int mode)
642 {
643         host->ios.chip_select = mode;
644         mmc_set_ios(host);
645 }
646
647 /*
648  * Sets the host clock to the highest possible frequency that
649  * is below "hz".
650  */
651 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
652 {
653         WARN_ON(hz < host->f_min);
654
655         if (hz > host->f_max)
656                 hz = host->f_max;
657
658         host->ios.clock = hz;
659         mmc_set_ios(host);
660 }
661
662 #ifdef CONFIG_MMC_CLKGATE
663 /*
664  * This gates the clock by setting it to 0 Hz.
665  */
666 void mmc_gate_clock(struct mmc_host *host)
667 {
668         unsigned long flags;
669
670         spin_lock_irqsave(&host->clk_lock, flags);
671         host->clk_old = host->ios.clock;
672         host->ios.clock = 0;
673         host->clk_gated = true;
674         spin_unlock_irqrestore(&host->clk_lock, flags);
675         mmc_set_ios(host);
676 }
677
678 /*
679  * This restores the clock from gating by using the cached
680  * clock value.
681  */
682 void mmc_ungate_clock(struct mmc_host *host)
683 {
684         /*
685          * We should previously have gated the clock, so the clock shall
686          * be 0 here! The clock may however be 0 during initialization,
687          * when some request operations are performed before setting
688          * the frequency. When ungate is requested in that situation
689          * we just ignore the call.
690          */
691         if (host->clk_old) {
692                 BUG_ON(host->ios.clock);
693                 /* This call will also set host->clk_gated to false */
694                 mmc_set_clock(host, host->clk_old);
695         }
696 }
697
698 void mmc_set_ungated(struct mmc_host *host)
699 {
700         unsigned long flags;
701
702         /*
703          * We've been given a new frequency while the clock is gated,
704          * so make sure we regard this as ungating it.
705          */
706         spin_lock_irqsave(&host->clk_lock, flags);
707         host->clk_gated = false;
708         spin_unlock_irqrestore(&host->clk_lock, flags);
709 }
710
711 #else
712 void mmc_set_ungated(struct mmc_host *host)
713 {
714 }
715 #endif
716
717 /*
718  * Change the bus mode (open drain/push-pull) of a host.
719  */
720 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
721 {
722         host->ios.bus_mode = mode;
723         mmc_set_ios(host);
724 }
725
726 /*
727  * Change data bus width of a host.
728  */
729 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
730 {
731         host->ios.bus_width = width;
732         mmc_set_ios(host);
733 }
734
735 /**
736  * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
737  * @vdd:        voltage (mV)
738  * @low_bits:   prefer low bits in boundary cases
739  *
740  * This function returns the OCR bit number according to the provided @vdd
741  * value. If conversion is not possible a negative errno value returned.
742  *
743  * Depending on the @low_bits flag the function prefers low or high OCR bits
744  * on boundary voltages. For example,
745  * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
746  * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
747  *
748  * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
749  */
750 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
751 {
752         const int max_bit = ilog2(MMC_VDD_35_36);
753         int bit;
754
755         if (vdd < 1650 || vdd > 3600)
756                 return -EINVAL;
757
758         if (vdd >= 1650 && vdd <= 1950)
759                 return ilog2(MMC_VDD_165_195);
760
761         if (low_bits)
762                 vdd -= 1;
763
764         /* Base 2000 mV, step 100 mV, bit's base 8. */
765         bit = (vdd - 2000) / 100 + 8;
766         if (bit > max_bit)
767                 return max_bit;
768         return bit;
769 }
770
771 /**
772  * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
773  * @vdd_min:    minimum voltage value (mV)
774  * @vdd_max:    maximum voltage value (mV)
775  *
776  * This function returns the OCR mask bits according to the provided @vdd_min
777  * and @vdd_max values. If conversion is not possible the function returns 0.
778  *
779  * Notes wrt boundary cases:
780  * This function sets the OCR bits for all boundary voltages, for example
781  * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
782  * MMC_VDD_34_35 mask.
783  */
784 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
785 {
786         u32 mask = 0;
787
788         if (vdd_max < vdd_min)
789                 return 0;
790
791         /* Prefer high bits for the boundary vdd_max values. */
792         vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
793         if (vdd_max < 0)
794                 return 0;
795
796         /* Prefer low bits for the boundary vdd_min values. */
797         vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
798         if (vdd_min < 0)
799                 return 0;
800
801         /* Fill the mask, from max bit to min bit. */
802         while (vdd_max >= vdd_min)
803                 mask |= 1 << vdd_max--;
804
805         return mask;
806 }
807 EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
808
809 #ifdef CONFIG_REGULATOR
810
811 /**
812  * mmc_regulator_get_ocrmask - return mask of supported voltages
813  * @supply: regulator to use
814  *
815  * This returns either a negative errno, or a mask of voltages that
816  * can be provided to MMC/SD/SDIO devices using the specified voltage
817  * regulator.  This would normally be called before registering the
818  * MMC host adapter.
819  */
820 int mmc_regulator_get_ocrmask(struct regulator *supply)
821 {
822         int                     result = 0;
823         int                     count;
824         int                     i;
825
826         count = regulator_count_voltages(supply);
827         if (count < 0)
828                 return count;
829
830         for (i = 0; i < count; i++) {
831                 int             vdd_uV;
832                 int             vdd_mV;
833
834                 vdd_uV = regulator_list_voltage(supply, i);
835                 if (vdd_uV <= 0)
836                         continue;
837
838                 vdd_mV = vdd_uV / 1000;
839                 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
840         }
841
842         return result;
843 }
844 EXPORT_SYMBOL(mmc_regulator_get_ocrmask);
845
846 /**
847  * mmc_regulator_set_ocr - set regulator to match host->ios voltage
848  * @mmc: the host to regulate
849  * @supply: regulator to use
850  * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
851  *
852  * Returns zero on success, else negative errno.
853  *
854  * MMC host drivers may use this to enable or disable a regulator using
855  * a particular supply voltage.  This would normally be called from the
856  * set_ios() method.
857  */
858 int mmc_regulator_set_ocr(struct mmc_host *mmc,
859                         struct regulator *supply,
860                         unsigned short vdd_bit)
861 {
862         int                     result = 0;
863         int                     min_uV, max_uV;
864
865         if (vdd_bit) {
866                 int             tmp;
867                 int             voltage;
868
869                 /* REVISIT mmc_vddrange_to_ocrmask() may have set some
870                  * bits this regulator doesn't quite support ... don't
871                  * be too picky, most cards and regulators are OK with
872                  * a 0.1V range goof (it's a small error percentage).
873                  */
874                 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
875                 if (tmp == 0) {
876                         min_uV = 1650 * 1000;
877                         max_uV = 1950 * 1000;
878                 } else {
879                         min_uV = 1900 * 1000 + tmp * 100 * 1000;
880                         max_uV = min_uV + 100 * 1000;
881                 }
882
883                 /* avoid needless changes to this voltage; the regulator
884                  * might not allow this operation
885                  */
886                 voltage = regulator_get_voltage(supply);
887                 if (voltage < 0)
888                         result = voltage;
889                 else if (voltage < min_uV || voltage > max_uV)
890                         result = regulator_set_voltage(supply, min_uV, max_uV);
891                 else
892                         result = 0;
893
894                 if (result == 0 && !mmc->regulator_enabled) {
895                         result = regulator_enable(supply);
896                         if (!result)
897                                 mmc->regulator_enabled = true;
898                 }
899         } else if (mmc->regulator_enabled) {
900                 result = regulator_disable(supply);
901                 if (result == 0)
902                         mmc->regulator_enabled = false;
903         }
904
905         if (result)
906                 dev_err(mmc_dev(mmc),
907                         "could not set regulator OCR (%d)\n", result);
908         return result;
909 }
910 EXPORT_SYMBOL(mmc_regulator_set_ocr);
911
912 #endif /* CONFIG_REGULATOR */
913
914 /*
915  * Mask off any voltages we don't support and select
916  * the lowest voltage
917  */
918 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
919 {
920         int bit;
921
922         ocr &= host->ocr_avail;
923
924         bit = ffs(ocr);
925         if (bit) {
926                 bit -= 1;
927
928                 ocr &= 3 << bit;
929
930                 host->ios.vdd = bit;
931                 mmc_set_ios(host);
932         } else {
933                 pr_warning("%s: host doesn't support card's voltages\n",
934                                 mmc_hostname(host));
935                 ocr = 0;
936         }
937
938         return ocr;
939 }
940
941 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, bool cmd11)
942 {
943         struct mmc_command cmd = {0};
944         int err = 0;
945
946         BUG_ON(!host);
947
948         /*
949          * Send CMD11 only if the request is to switch the card to
950          * 1.8V signalling.
951          */
952         if ((signal_voltage != MMC_SIGNAL_VOLTAGE_330) && cmd11) {
953                 cmd.opcode = SD_SWITCH_VOLTAGE;
954                 cmd.arg = 0;
955                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
956
957                 err = mmc_wait_for_cmd(host, &cmd, 0);
958                 if (err)
959                         return err;
960
961                 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
962                         return -EIO;
963         }
964
965         host->ios.signal_voltage = signal_voltage;
966
967         if (host->ops->start_signal_voltage_switch)
968                 err = host->ops->start_signal_voltage_switch(host, &host->ios);
969
970         return err;
971 }
972
973 /*
974  * Select timing parameters for host.
975  */
976 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
977 {
978         host->ios.timing = timing;
979         mmc_set_ios(host);
980 }
981
982 /*
983  * Select appropriate driver type for host.
984  */
985 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
986 {
987         host->ios.drv_type = drv_type;
988         mmc_set_ios(host);
989 }
990
991 /*
992  * Apply power to the MMC stack.  This is a two-stage process.
993  * First, we enable power to the card without the clock running.
994  * We then wait a bit for the power to stabilise.  Finally,
995  * enable the bus drivers and clock to the card.
996  *
997  * We must _NOT_ enable the clock prior to power stablising.
998  *
999  * If a host does all the power sequencing itself, ignore the
1000  * initial MMC_POWER_UP stage.
1001  */
1002 static void mmc_power_up(struct mmc_host *host)
1003 {
1004         int bit;
1005
1006         /* If ocr is set, we use it */
1007         if (host->ocr)
1008                 bit = ffs(host->ocr) - 1;
1009         else
1010                 bit = fls(host->ocr_avail) - 1;
1011
1012         host->ios.vdd = bit;
1013         if (mmc_host_is_spi(host)) {
1014                 host->ios.chip_select = MMC_CS_HIGH;
1015                 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1016         } else {
1017                 host->ios.chip_select = MMC_CS_DONTCARE;
1018                 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
1019         }
1020         host->ios.power_mode = MMC_POWER_UP;
1021         host->ios.bus_width = MMC_BUS_WIDTH_1;
1022         host->ios.timing = MMC_TIMING_LEGACY;
1023         mmc_set_ios(host);
1024
1025         /*
1026          * This delay should be sufficient to allow the power supply
1027          * to reach the minimum voltage.
1028          */
1029         mmc_delay(10);
1030
1031         host->ios.clock = host->f_init;
1032
1033         host->ios.power_mode = MMC_POWER_ON;
1034         mmc_set_ios(host);
1035
1036         /*
1037          * This delay must be at least 74 clock sizes, or 1 ms, or the
1038          * time required to reach a stable voltage.
1039          */
1040         mmc_delay(10);
1041 }
1042
1043 static void mmc_power_off(struct mmc_host *host)
1044 {
1045         host->ios.clock = 0;
1046         host->ios.vdd = 0;
1047
1048         /*
1049          * Reset ocr mask to be the highest possible voltage supported for
1050          * this mmc host. This value will be used at next power up.
1051          */
1052         host->ocr = 1 << (fls(host->ocr_avail) - 1);
1053
1054         if (!mmc_host_is_spi(host)) {
1055                 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
1056                 host->ios.chip_select = MMC_CS_DONTCARE;
1057         }
1058         host->ios.power_mode = MMC_POWER_OFF;
1059         host->ios.bus_width = MMC_BUS_WIDTH_1;
1060         host->ios.timing = MMC_TIMING_LEGACY;
1061         mmc_set_ios(host);
1062 }
1063
1064 /*
1065  * Cleanup when the last reference to the bus operator is dropped.
1066  */
1067 static void __mmc_release_bus(struct mmc_host *host)
1068 {
1069         BUG_ON(!host);
1070         BUG_ON(host->bus_refs);
1071         BUG_ON(!host->bus_dead);
1072
1073         host->bus_ops = NULL;
1074 }
1075
1076 /*
1077  * Increase reference count of bus operator
1078  */
1079 static inline void mmc_bus_get(struct mmc_host *host)
1080 {
1081         unsigned long flags;
1082
1083         spin_lock_irqsave(&host->lock, flags);
1084         host->bus_refs++;
1085         spin_unlock_irqrestore(&host->lock, flags);
1086 }
1087
1088 /*
1089  * Decrease reference count of bus operator and free it if
1090  * it is the last reference.
1091  */
1092 static inline void mmc_bus_put(struct mmc_host *host)
1093 {
1094         unsigned long flags;
1095
1096         spin_lock_irqsave(&host->lock, flags);
1097         host->bus_refs--;
1098         if ((host->bus_refs == 0) && host->bus_ops)
1099                 __mmc_release_bus(host);
1100         spin_unlock_irqrestore(&host->lock, flags);
1101 }
1102
1103 int mmc_resume_bus(struct mmc_host *host)
1104 {
1105         unsigned long flags;
1106
1107         if (!mmc_bus_needs_resume(host))
1108                 return -EINVAL;
1109
1110         printk("%s: Starting deferred resume\n", mmc_hostname(host));
1111         spin_lock_irqsave(&host->lock, flags);
1112         host->bus_resume_flags &= ~MMC_BUSRESUME_NEEDS_RESUME;
1113         host->rescan_disable = 0;
1114         spin_unlock_irqrestore(&host->lock, flags);
1115
1116         mmc_bus_get(host);
1117         if (host->bus_ops && !host->bus_dead) {
1118                 mmc_power_up(host);
1119                 BUG_ON(!host->bus_ops->resume);
1120                 host->bus_ops->resume(host);
1121         }
1122
1123         if (host->bus_ops->detect && !host->bus_dead)
1124                 host->bus_ops->detect(host);
1125
1126         mmc_bus_put(host);
1127         printk("%s: Deferred resume completed\n", mmc_hostname(host));
1128         return 0;
1129 }
1130
1131 EXPORT_SYMBOL(mmc_resume_bus);
1132
1133 /*
1134  * Assign a mmc bus handler to a host. Only one bus handler may control a
1135  * host at any given time.
1136  */
1137 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1138 {
1139         unsigned long flags;
1140
1141         BUG_ON(!host);
1142         BUG_ON(!ops);
1143
1144         WARN_ON(!host->claimed);
1145
1146         spin_lock_irqsave(&host->lock, flags);
1147
1148         BUG_ON(host->bus_ops);
1149         BUG_ON(host->bus_refs);
1150
1151         host->bus_ops = ops;
1152         host->bus_refs = 1;
1153         host->bus_dead = 0;
1154
1155         spin_unlock_irqrestore(&host->lock, flags);
1156 }
1157
1158 /*
1159  * Remove the current bus handler from a host. Assumes that there are
1160  * no interesting cards left, so the bus is powered down.
1161  */
1162 void mmc_detach_bus(struct mmc_host *host)
1163 {
1164         unsigned long flags;
1165
1166         BUG_ON(!host);
1167
1168         WARN_ON(!host->claimed);
1169         WARN_ON(!host->bus_ops);
1170
1171         spin_lock_irqsave(&host->lock, flags);
1172
1173         host->bus_dead = 1;
1174
1175         spin_unlock_irqrestore(&host->lock, flags);
1176
1177         mmc_power_off(host);
1178
1179         mmc_bus_put(host);
1180 }
1181
1182 /**
1183  *      mmc_detect_change - process change of state on a MMC socket
1184  *      @host: host which changed state.
1185  *      @delay: optional delay to wait before detection (jiffies)
1186  *
1187  *      MMC drivers should call this when they detect a card has been
1188  *      inserted or removed. The MMC layer will confirm that any
1189  *      present card is still functional, and initialize any newly
1190  *      inserted.
1191  */
1192 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1193 {
1194 #ifdef CONFIG_MMC_DEBUG
1195         unsigned long flags;
1196         spin_lock_irqsave(&host->lock, flags);
1197         WARN_ON(host->removed);
1198         spin_unlock_irqrestore(&host->lock, flags);
1199 #endif
1200
1201         mmc_schedule_delayed_work(&host->detect, delay);
1202 }
1203
1204 EXPORT_SYMBOL(mmc_detect_change);
1205
1206 void mmc_init_erase(struct mmc_card *card)
1207 {
1208         unsigned int sz;
1209
1210         if (is_power_of_2(card->erase_size))
1211                 card->erase_shift = ffs(card->erase_size) - 1;
1212         else
1213                 card->erase_shift = 0;
1214
1215         /*
1216          * It is possible to erase an arbitrarily large area of an SD or MMC
1217          * card.  That is not desirable because it can take a long time
1218          * (minutes) potentially delaying more important I/O, and also the
1219          * timeout calculations become increasingly hugely over-estimated.
1220          * Consequently, 'pref_erase' is defined as a guide to limit erases
1221          * to that size and alignment.
1222          *
1223          * For SD cards that define Allocation Unit size, limit erases to one
1224          * Allocation Unit at a time.  For MMC cards that define High Capacity
1225          * Erase Size, whether it is switched on or not, limit to that size.
1226          * Otherwise just have a stab at a good value.  For modern cards it
1227          * will end up being 4MiB.  Note that if the value is too small, it
1228          * can end up taking longer to erase.
1229          */
1230         if (mmc_card_sd(card) && card->ssr.au) {
1231                 card->pref_erase = card->ssr.au;
1232                 card->erase_shift = ffs(card->ssr.au) - 1;
1233         } else if (card->ext_csd.hc_erase_size) {
1234                 card->pref_erase = card->ext_csd.hc_erase_size;
1235         } else {
1236                 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1237                 if (sz < 128)
1238                         card->pref_erase = 512 * 1024 / 512;
1239                 else if (sz < 512)
1240                         card->pref_erase = 1024 * 1024 / 512;
1241                 else if (sz < 1024)
1242                         card->pref_erase = 2 * 1024 * 1024 / 512;
1243                 else
1244                         card->pref_erase = 4 * 1024 * 1024 / 512;
1245                 if (card->pref_erase < card->erase_size)
1246                         card->pref_erase = card->erase_size;
1247                 else {
1248                         sz = card->pref_erase % card->erase_size;
1249                         if (sz)
1250                                 card->pref_erase += card->erase_size - sz;
1251                 }
1252         }
1253 }
1254
1255 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1256                                           unsigned int arg, unsigned int qty)
1257 {
1258         unsigned int erase_timeout;
1259
1260         if (card->ext_csd.erase_group_def & 1) {
1261                 /* High Capacity Erase Group Size uses HC timeouts */
1262                 if (arg == MMC_TRIM_ARG)
1263                         erase_timeout = card->ext_csd.trim_timeout;
1264                 else
1265                         erase_timeout = card->ext_csd.hc_erase_timeout;
1266         } else {
1267                 /* CSD Erase Group Size uses write timeout */
1268                 unsigned int mult = (10 << card->csd.r2w_factor);
1269                 unsigned int timeout_clks = card->csd.tacc_clks * mult;
1270                 unsigned int timeout_us;
1271
1272                 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
1273                 if (card->csd.tacc_ns < 1000000)
1274                         timeout_us = (card->csd.tacc_ns * mult) / 1000;
1275                 else
1276                         timeout_us = (card->csd.tacc_ns / 1000) * mult;
1277
1278                 /*
1279                  * ios.clock is only a target.  The real clock rate might be
1280                  * less but not that much less, so fudge it by multiplying by 2.
1281                  */
1282                 timeout_clks <<= 1;
1283                 timeout_us += (timeout_clks * 1000) /
1284                               (mmc_host_clk_rate(card->host) / 1000);
1285
1286                 erase_timeout = timeout_us / 1000;
1287
1288                 /*
1289                  * Theoretically, the calculation could underflow so round up
1290                  * to 1ms in that case.
1291                  */
1292                 if (!erase_timeout)
1293                         erase_timeout = 1;
1294         }
1295
1296         /* Multiplier for secure operations */
1297         if (arg & MMC_SECURE_ARGS) {
1298                 if (arg == MMC_SECURE_ERASE_ARG)
1299                         erase_timeout *= card->ext_csd.sec_erase_mult;
1300                 else
1301                         erase_timeout *= card->ext_csd.sec_trim_mult;
1302         }
1303
1304         erase_timeout *= qty;
1305
1306         /*
1307          * Ensure at least a 1 second timeout for SPI as per
1308          * 'mmc_set_data_timeout()'
1309          */
1310         if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
1311                 erase_timeout = 1000;
1312
1313         return erase_timeout;
1314 }
1315
1316 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
1317                                          unsigned int arg,
1318                                          unsigned int qty)
1319 {
1320         unsigned int erase_timeout;
1321
1322         if (card->ssr.erase_timeout) {
1323                 /* Erase timeout specified in SD Status Register (SSR) */
1324                 erase_timeout = card->ssr.erase_timeout * qty +
1325                                 card->ssr.erase_offset;
1326         } else {
1327                 /*
1328                  * Erase timeout not specified in SD Status Register (SSR) so
1329                  * use 250ms per write block.
1330                  */
1331                 erase_timeout = 250 * qty;
1332         }
1333
1334         /* Must not be less than 1 second */
1335         if (erase_timeout < 1000)
1336                 erase_timeout = 1000;
1337
1338         return erase_timeout;
1339 }
1340
1341 static unsigned int mmc_erase_timeout(struct mmc_card *card,
1342                                       unsigned int arg,
1343                                       unsigned int qty)
1344 {
1345         if (mmc_card_sd(card))
1346                 return mmc_sd_erase_timeout(card, arg, qty);
1347         else
1348                 return mmc_mmc_erase_timeout(card, arg, qty);
1349 }
1350
1351 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
1352                         unsigned int to, unsigned int arg)
1353 {
1354         struct mmc_command cmd = {0};
1355         unsigned int qty = 0;
1356         int err;
1357
1358         /*
1359          * qty is used to calculate the erase timeout which depends on how many
1360          * erase groups (or allocation units in SD terminology) are affected.
1361          * We count erasing part of an erase group as one erase group.
1362          * For SD, the allocation units are always a power of 2.  For MMC, the
1363          * erase group size is almost certainly also power of 2, but it does not
1364          * seem to insist on that in the JEDEC standard, so we fall back to
1365          * division in that case.  SD may not specify an allocation unit size,
1366          * in which case the timeout is based on the number of write blocks.
1367          *
1368          * Note that the timeout for secure trim 2 will only be correct if the
1369          * number of erase groups specified is the same as the total of all
1370          * preceding secure trim 1 commands.  Since the power may have been
1371          * lost since the secure trim 1 commands occurred, it is generally
1372          * impossible to calculate the secure trim 2 timeout correctly.
1373          */
1374         if (card->erase_shift)
1375                 qty += ((to >> card->erase_shift) -
1376                         (from >> card->erase_shift)) + 1;
1377         else if (mmc_card_sd(card))
1378                 qty += to - from + 1;
1379         else
1380                 qty += ((to / card->erase_size) -
1381                         (from / card->erase_size)) + 1;
1382
1383         if (!mmc_card_blockaddr(card)) {
1384                 from <<= 9;
1385                 to <<= 9;
1386         }
1387
1388         if (mmc_card_sd(card))
1389                 cmd.opcode = SD_ERASE_WR_BLK_START;
1390         else
1391                 cmd.opcode = MMC_ERASE_GROUP_START;
1392         cmd.arg = from;
1393         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1394         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1395         if (err) {
1396                 printk(KERN_ERR "mmc_erase: group start error %d, "
1397                        "status %#x\n", err, cmd.resp[0]);
1398                 err = -EINVAL;
1399                 goto out;
1400         }
1401
1402         memset(&cmd, 0, sizeof(struct mmc_command));
1403         if (mmc_card_sd(card))
1404                 cmd.opcode = SD_ERASE_WR_BLK_END;
1405         else
1406                 cmd.opcode = MMC_ERASE_GROUP_END;
1407         cmd.arg = to;
1408         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1409         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1410         if (err) {
1411                 printk(KERN_ERR "mmc_erase: group end error %d, status %#x\n",
1412                        err, cmd.resp[0]);
1413                 err = -EINVAL;
1414                 goto out;
1415         }
1416
1417         memset(&cmd, 0, sizeof(struct mmc_command));
1418         cmd.opcode = MMC_ERASE;
1419         cmd.arg = arg;
1420         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1421         cmd.cmd_timeout_ms = mmc_erase_timeout(card, arg, qty);
1422         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1423         if (err) {
1424                 printk(KERN_ERR "mmc_erase: erase error %d, status %#x\n",
1425                        err, cmd.resp[0]);
1426                 err = -EIO;
1427                 goto out;
1428         }
1429
1430         if (mmc_host_is_spi(card->host))
1431                 goto out;
1432
1433         do {
1434                 memset(&cmd, 0, sizeof(struct mmc_command));
1435                 cmd.opcode = MMC_SEND_STATUS;
1436                 cmd.arg = card->rca << 16;
1437                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1438                 /* Do not retry else we can't see errors */
1439                 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1440                 if (err || (cmd.resp[0] & 0xFDF92000)) {
1441                         printk(KERN_ERR "error %d requesting status %#x\n",
1442                                 err, cmd.resp[0]);
1443                         err = -EIO;
1444                         goto out;
1445                 }
1446         } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
1447                  R1_CURRENT_STATE(cmd.resp[0]) == 7);
1448 out:
1449         return err;
1450 }
1451
1452 /**
1453  * mmc_erase - erase sectors.
1454  * @card: card to erase
1455  * @from: first sector to erase
1456  * @nr: number of sectors to erase
1457  * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
1458  *
1459  * Caller must claim host before calling this function.
1460  */
1461 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
1462               unsigned int arg)
1463 {
1464         unsigned int rem, to = from + nr;
1465
1466         if (!(card->host->caps & MMC_CAP_ERASE) ||
1467             !(card->csd.cmdclass & CCC_ERASE))
1468                 return -EOPNOTSUPP;
1469
1470         if (!card->erase_size)
1471                 return -EOPNOTSUPP;
1472
1473         if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
1474                 return -EOPNOTSUPP;
1475
1476         if ((arg & MMC_SECURE_ARGS) &&
1477             !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
1478                 return -EOPNOTSUPP;
1479
1480         if ((arg & MMC_TRIM_ARGS) &&
1481             !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
1482                 return -EOPNOTSUPP;
1483
1484         if (arg == MMC_SECURE_ERASE_ARG) {
1485                 if (from % card->erase_size || nr % card->erase_size)
1486                         return -EINVAL;
1487         }
1488
1489         if (arg == MMC_ERASE_ARG) {
1490                 rem = from % card->erase_size;
1491                 if (rem) {
1492                         rem = card->erase_size - rem;
1493                         from += rem;
1494                         if (nr > rem)
1495                                 nr -= rem;
1496                         else
1497                                 return 0;
1498                 }
1499                 rem = nr % card->erase_size;
1500                 if (rem)
1501                         nr -= rem;
1502         }
1503
1504         if (nr == 0)
1505                 return 0;
1506
1507         to = from + nr;
1508
1509         if (to <= from)
1510                 return -EINVAL;
1511
1512         /* 'from' and 'to' are inclusive */
1513         to -= 1;
1514
1515         return mmc_do_erase(card, from, to, arg);
1516 }
1517 EXPORT_SYMBOL(mmc_erase);
1518
1519 int mmc_can_erase(struct mmc_card *card)
1520 {
1521         if ((card->host->caps & MMC_CAP_ERASE) &&
1522             (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
1523                 return 1;
1524         return 0;
1525 }
1526 EXPORT_SYMBOL(mmc_can_erase);
1527
1528 int mmc_can_trim(struct mmc_card *card)
1529 {
1530         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN)
1531                 return 1;
1532         return 0;
1533 }
1534 EXPORT_SYMBOL(mmc_can_trim);
1535
1536 int mmc_can_secure_erase_trim(struct mmc_card *card)
1537 {
1538         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)
1539                 return 1;
1540         return 0;
1541 }
1542 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
1543
1544 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
1545                             unsigned int nr)
1546 {
1547         if (!card->erase_size)
1548                 return 0;
1549         if (from % card->erase_size || nr % card->erase_size)
1550                 return 0;
1551         return 1;
1552 }
1553 EXPORT_SYMBOL(mmc_erase_group_aligned);
1554
1555 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
1556 {
1557         struct mmc_command cmd = {0};
1558
1559         if (mmc_card_blockaddr(card) || mmc_card_ddr_mode(card))
1560                 return 0;
1561
1562         cmd.opcode = MMC_SET_BLOCKLEN;
1563         cmd.arg = blocklen;
1564         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1565         return mmc_wait_for_cmd(card->host, &cmd, 5);
1566 }
1567 EXPORT_SYMBOL(mmc_set_blocklen);
1568
1569 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
1570 {
1571         host->f_init = freq;
1572
1573 #ifdef CONFIG_MMC_DEBUG
1574         pr_info("%s: %s: trying to init card at %u Hz\n",
1575                 mmc_hostname(host), __func__, host->f_init);
1576 #endif
1577         mmc_power_up(host);
1578
1579         /*
1580          * sdio_reset sends CMD52 to reset card.  Since we do not know
1581          * if the card is being re-initialized, just send it.  CMD52
1582          * should be ignored by SD/eMMC cards.
1583          */
1584         sdio_reset(host);
1585         mmc_go_idle(host);
1586
1587         mmc_send_if_cond(host, host->ocr_avail);
1588
1589         /* Order's important: probe SDIO, then SD, then MMC */
1590         if (!mmc_attach_sdio(host))
1591                 return 0;
1592         if (!mmc_attach_sd(host))
1593                 return 0;
1594         if (!mmc_attach_mmc(host))
1595                 return 0;
1596
1597         mmc_power_off(host);
1598         return -EIO;
1599 }
1600
1601 void mmc_rescan(struct work_struct *work)
1602 {
1603         static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
1604         struct mmc_host *host =
1605                 container_of(work, struct mmc_host, detect.work);
1606         int i;
1607         bool extend_wakelock = false;
1608
1609         if (host->rescan_disable)
1610                 return;
1611
1612         mmc_bus_get(host);
1613
1614         /*
1615          * if there is a _removable_ card registered, check whether it is
1616          * still present
1617          */
1618         if (host->bus_ops && host->bus_ops->detect && !host->bus_dead
1619             && !(host->caps & MMC_CAP_NONREMOVABLE))
1620                 host->bus_ops->detect(host);
1621
1622         /* If the card was removed the bus will be marked
1623          * as dead - extend the wakelock so userspace
1624          * can respond */
1625         if (host->bus_dead)
1626                 extend_wakelock = 1;
1627
1628         /*
1629          * Let mmc_bus_put() free the bus/bus_ops if we've found that
1630          * the card is no longer present.
1631          */
1632         mmc_bus_put(host);
1633         mmc_bus_get(host);
1634
1635         /* if there still is a card present, stop here */
1636         if (host->bus_ops != NULL) {
1637                 mmc_bus_put(host);
1638                 goto out;
1639         }
1640
1641         /*
1642          * Only we can add a new handler, so it's safe to
1643          * release the lock here.
1644          */
1645         mmc_bus_put(host);
1646
1647         if (host->ops->get_cd && host->ops->get_cd(host) == 0)
1648                 goto out;
1649
1650         mmc_claim_host(host);
1651         for (i = 0; i < ARRAY_SIZE(freqs); i++) {
1652                 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min))) {
1653                         extend_wakelock = true;
1654                         break;
1655                 }
1656                 if (freqs[i] <= host->f_min)
1657                         break;
1658         }
1659         mmc_release_host(host);
1660
1661  out:
1662         if (extend_wakelock)
1663                 wake_lock_timeout(&mmc_delayed_work_wake_lock, HZ / 2);
1664         else
1665                 wake_unlock(&mmc_delayed_work_wake_lock);
1666         if (host->caps & MMC_CAP_NEEDS_POLL)
1667                 mmc_schedule_delayed_work(&host->detect, HZ);
1668 }
1669
1670 void mmc_start_host(struct mmc_host *host)
1671 {
1672         mmc_power_off(host);
1673         mmc_detect_change(host, 0);
1674 }
1675
1676 void mmc_stop_host(struct mmc_host *host)
1677 {
1678 #ifdef CONFIG_MMC_DEBUG
1679         unsigned long flags;
1680         spin_lock_irqsave(&host->lock, flags);
1681         host->removed = 1;
1682         spin_unlock_irqrestore(&host->lock, flags);
1683 #endif
1684
1685         if (host->caps & MMC_CAP_DISABLE)
1686                 cancel_delayed_work(&host->disable);
1687         cancel_delayed_work_sync(&host->detect);
1688         mmc_flush_scheduled_work();
1689
1690         /* clear pm flags now and let card drivers set them as needed */
1691         host->pm_flags = 0;
1692
1693         mmc_bus_get(host);
1694         if (host->bus_ops && !host->bus_dead) {
1695                 if (host->bus_ops->remove)
1696                         host->bus_ops->remove(host);
1697
1698                 mmc_claim_host(host);
1699                 mmc_detach_bus(host);
1700                 mmc_release_host(host);
1701                 mmc_bus_put(host);
1702                 return;
1703         }
1704         mmc_bus_put(host);
1705
1706         BUG_ON(host->card);
1707
1708         mmc_power_off(host);
1709 }
1710
1711 int mmc_power_save_host(struct mmc_host *host)
1712 {
1713         int ret = 0;
1714
1715         mmc_bus_get(host);
1716
1717         if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
1718                 mmc_bus_put(host);
1719                 return -EINVAL;
1720         }
1721
1722         if (host->bus_ops->power_save)
1723                 ret = host->bus_ops->power_save(host);
1724
1725         mmc_bus_put(host);
1726
1727         mmc_power_off(host);
1728
1729         return ret;
1730 }
1731 EXPORT_SYMBOL(mmc_power_save_host);
1732
1733 int mmc_power_restore_host(struct mmc_host *host)
1734 {
1735         int ret;
1736
1737         mmc_bus_get(host);
1738
1739         if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
1740                 mmc_bus_put(host);
1741                 return -EINVAL;
1742         }
1743
1744         mmc_power_up(host);
1745         ret = host->bus_ops->power_restore(host);
1746
1747         mmc_bus_put(host);
1748
1749         return ret;
1750 }
1751 EXPORT_SYMBOL(mmc_power_restore_host);
1752
1753 int mmc_card_awake(struct mmc_host *host)
1754 {
1755         int err = -ENOSYS;
1756
1757         mmc_bus_get(host);
1758
1759         if (host->bus_ops && !host->bus_dead && host->bus_ops->awake)
1760                 err = host->bus_ops->awake(host);
1761
1762         mmc_bus_put(host);
1763
1764         return err;
1765 }
1766 EXPORT_SYMBOL(mmc_card_awake);
1767
1768 int mmc_card_sleep(struct mmc_host *host)
1769 {
1770         int err = -ENOSYS;
1771
1772         mmc_bus_get(host);
1773
1774         if (host->bus_ops && !host->bus_dead && host->bus_ops->awake)
1775                 err = host->bus_ops->sleep(host);
1776
1777         mmc_bus_put(host);
1778
1779         return err;
1780 }
1781 EXPORT_SYMBOL(mmc_card_sleep);
1782
1783 int mmc_card_can_sleep(struct mmc_host *host)
1784 {
1785         struct mmc_card *card = host->card;
1786
1787         if (card && mmc_card_mmc(card) && card->ext_csd.rev >= 3)
1788                 return 1;
1789         return 0;
1790 }
1791 EXPORT_SYMBOL(mmc_card_can_sleep);
1792
1793 #ifdef CONFIG_PM
1794
1795 /**
1796  *      mmc_suspend_host - suspend a host
1797  *      @host: mmc host
1798  */
1799 int mmc_suspend_host(struct mmc_host *host)
1800 {
1801         int err = 0;
1802
1803         if (mmc_bus_needs_resume(host))
1804                 return 0;
1805
1806         if (host->caps & MMC_CAP_DISABLE)
1807                 cancel_delayed_work(&host->disable);
1808         cancel_delayed_work(&host->detect);
1809         mmc_flush_scheduled_work();
1810
1811         mmc_bus_get(host);
1812         if (host->bus_ops && !host->bus_dead) {
1813                 if (host->bus_ops->suspend)
1814                         err = host->bus_ops->suspend(host);
1815                 if (err == -ENOSYS || !host->bus_ops->resume) {
1816                         /*
1817                          * We simply "remove" the card in this case.
1818                          * It will be redetected on resume.
1819                          */
1820                         if (host->bus_ops->remove)
1821                                 host->bus_ops->remove(host);
1822                         mmc_claim_host(host);
1823                         mmc_detach_bus(host);
1824                         mmc_release_host(host);
1825                         host->pm_flags = 0;
1826                         err = 0;
1827                 }
1828         }
1829         mmc_bus_put(host);
1830
1831         if (!err && !mmc_card_keep_power(host))
1832                 mmc_power_off(host);
1833
1834         return err;
1835 }
1836
1837 EXPORT_SYMBOL(mmc_suspend_host);
1838
1839 /**
1840  *      mmc_resume_host - resume a previously suspended host
1841  *      @host: mmc host
1842  */
1843 int mmc_resume_host(struct mmc_host *host)
1844 {
1845         int err = 0;
1846
1847         mmc_bus_get(host);
1848         if (mmc_bus_manual_resume(host)) {
1849                 host->bus_resume_flags |= MMC_BUSRESUME_NEEDS_RESUME;
1850                 mmc_bus_put(host);
1851                 return 0;
1852         }
1853
1854         if (host->bus_ops && !host->bus_dead) {
1855                 if (!mmc_card_keep_power(host)) {
1856                         mmc_power_up(host);
1857                         mmc_select_voltage(host, host->ocr);
1858                         /*
1859                          * Tell runtime PM core we just powered up the card,
1860                          * since it still believes the card is powered off.
1861                          * Note that currently runtime PM is only enabled
1862                          * for SDIO cards that are MMC_CAP_POWER_OFF_CARD
1863                          */
1864                         if (mmc_card_sdio(host->card) &&
1865                             (host->caps & MMC_CAP_POWER_OFF_CARD)) {
1866                                 pm_runtime_disable(&host->card->dev);
1867                                 pm_runtime_set_active(&host->card->dev);
1868                                 pm_runtime_enable(&host->card->dev);
1869                         }
1870                 }
1871                 BUG_ON(!host->bus_ops->resume);
1872                 err = host->bus_ops->resume(host);
1873                 if (err) {
1874                         printk(KERN_WARNING "%s: error %d during resume "
1875                                             "(card was removed?)\n",
1876                                             mmc_hostname(host), err);
1877                         err = 0;
1878                 }
1879         }
1880         host->pm_flags &= ~MMC_PM_KEEP_POWER;
1881         mmc_bus_put(host);
1882
1883         return err;
1884 }
1885 EXPORT_SYMBOL(mmc_resume_host);
1886
1887 /* Do the card removal on suspend if card is assumed removeable
1888  * Do that in pm notifier while userspace isn't yet frozen, so we will be able
1889    to sync the card.
1890 */
1891 int mmc_pm_notify(struct notifier_block *notify_block,
1892                                         unsigned long mode, void *unused)
1893 {
1894         struct mmc_host *host = container_of(
1895                 notify_block, struct mmc_host, pm_notify);
1896         unsigned long flags;
1897
1898
1899         switch (mode) {
1900         case PM_HIBERNATION_PREPARE:
1901         case PM_SUSPEND_PREPARE:
1902
1903                 spin_lock_irqsave(&host->lock, flags);
1904                 if (mmc_bus_needs_resume(host)) {
1905                         spin_unlock_irqrestore(&host->lock, flags);
1906                         break;
1907                 }
1908                 host->rescan_disable = 1;
1909                 spin_unlock_irqrestore(&host->lock, flags);
1910                 cancel_delayed_work_sync(&host->detect);
1911
1912                 if (!host->bus_ops || host->bus_ops->suspend)
1913                         break;
1914
1915                 mmc_claim_host(host);
1916
1917                 if (host->bus_ops->remove)
1918                         host->bus_ops->remove(host);
1919
1920                 mmc_detach_bus(host);
1921                 mmc_release_host(host);
1922                 host->pm_flags = 0;
1923                 break;
1924
1925         case PM_POST_SUSPEND:
1926         case PM_POST_HIBERNATION:
1927         case PM_POST_RESTORE:
1928
1929                 spin_lock_irqsave(&host->lock, flags);
1930                 if (mmc_bus_manual_resume(host)) {
1931                         spin_unlock_irqrestore(&host->lock, flags);
1932                         break;
1933                 }
1934                 host->rescan_disable = 0;
1935                 spin_unlock_irqrestore(&host->lock, flags);
1936                 mmc_detect_change(host, 0);
1937
1938         }
1939
1940         return 0;
1941 }
1942 #endif
1943
1944 #ifdef CONFIG_MMC_EMBEDDED_SDIO
1945 void mmc_set_embedded_sdio_data(struct mmc_host *host,
1946                                 struct sdio_cis *cis,
1947                                 struct sdio_cccr *cccr,
1948                                 struct sdio_embedded_func *funcs,
1949                                 int num_funcs)
1950 {
1951         host->embedded_sdio_data.cis = cis;
1952         host->embedded_sdio_data.cccr = cccr;
1953         host->embedded_sdio_data.funcs = funcs;
1954         host->embedded_sdio_data.num_funcs = num_funcs;
1955 }
1956
1957 EXPORT_SYMBOL(mmc_set_embedded_sdio_data);
1958 #endif
1959
1960 static int __init mmc_init(void)
1961 {
1962         int ret;
1963
1964         workqueue = alloc_ordered_workqueue("kmmcd", 0);
1965         if (!workqueue)
1966                 return -ENOMEM;
1967
1968         wake_lock_init(&mmc_delayed_work_wake_lock, WAKE_LOCK_SUSPEND,
1969                        "mmc_delayed_work");
1970
1971         ret = mmc_register_bus();
1972         if (ret)
1973                 goto destroy_workqueue;
1974
1975         ret = mmc_register_host_class();
1976         if (ret)
1977                 goto unregister_bus;
1978
1979         ret = sdio_register_bus();
1980         if (ret)
1981                 goto unregister_host_class;
1982
1983         return 0;
1984
1985 unregister_host_class:
1986         mmc_unregister_host_class();
1987 unregister_bus:
1988         mmc_unregister_bus();
1989 destroy_workqueue:
1990         destroy_workqueue(workqueue);
1991         wake_lock_destroy(&mmc_delayed_work_wake_lock);
1992
1993         return ret;
1994 }
1995
1996 static void __exit mmc_exit(void)
1997 {
1998         sdio_unregister_bus();
1999         mmc_unregister_host_class();
2000         mmc_unregister_bus();
2001         destroy_workqueue(workqueue);
2002         wake_lock_destroy(&mmc_delayed_work_wake_lock);
2003 }
2004
2005 subsys_initcall(mmc_init);
2006 module_exit(mmc_exit);
2007
2008 MODULE_LICENSE("GPL");