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