mmc: start removing enable / disable API
[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/suspend.h>
27 #include <linux/fault-inject.h>
28 #include <linux/random.h>
29
30 #include <linux/mmc/card.h>
31 #include <linux/mmc/host.h>
32 #include <linux/mmc/mmc.h>
33 #include <linux/mmc/sd.h>
34
35 #include "core.h"
36 #include "bus.h"
37 #include "host.h"
38 #include "sdio_bus.h"
39
40 #include "mmc_ops.h"
41 #include "sd_ops.h"
42 #include "sdio_ops.h"
43
44 static struct workqueue_struct *workqueue;
45
46 /*
47  * Enabling software CRCs on the data blocks can be a significant (30%)
48  * performance cost, and for other reasons may not always be desired.
49  * So we allow it it to be disabled.
50  */
51 bool use_spi_crc = 1;
52 module_param(use_spi_crc, bool, 0);
53
54 /*
55  * We normally treat cards as removed during suspend if they are not
56  * known to be on a non-removable bus, to avoid the risk of writing
57  * back data to a different card after resume.  Allow this to be
58  * overridden if necessary.
59  */
60 #ifdef CONFIG_MMC_UNSAFE_RESUME
61 bool mmc_assume_removable;
62 #else
63 bool mmc_assume_removable = 1;
64 #endif
65 EXPORT_SYMBOL(mmc_assume_removable);
66 module_param_named(removable, mmc_assume_removable, bool, 0644);
67 MODULE_PARM_DESC(
68         removable,
69         "MMC/SD cards are removable and may be removed during suspend");
70
71 /*
72  * Internal function. Schedule delayed work in the MMC work queue.
73  */
74 static int mmc_schedule_delayed_work(struct delayed_work *work,
75                                      unsigned long delay)
76 {
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 #ifdef CONFIG_FAIL_MMC_REQUEST
89
90 /*
91  * Internal function. Inject random data errors.
92  * If mmc_data is NULL no errors are injected.
93  */
94 static void mmc_should_fail_request(struct mmc_host *host,
95                                     struct mmc_request *mrq)
96 {
97         struct mmc_command *cmd = mrq->cmd;
98         struct mmc_data *data = mrq->data;
99         static const int data_errors[] = {
100                 -ETIMEDOUT,
101                 -EILSEQ,
102                 -EIO,
103         };
104
105         if (!data)
106                 return;
107
108         if (cmd->error || data->error ||
109             !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
110                 return;
111
112         data->error = data_errors[random32() % ARRAY_SIZE(data_errors)];
113         data->bytes_xfered = (random32() % (data->bytes_xfered >> 9)) << 9;
114 }
115
116 #else /* CONFIG_FAIL_MMC_REQUEST */
117
118 static inline void mmc_should_fail_request(struct mmc_host *host,
119                                            struct mmc_request *mrq)
120 {
121 }
122
123 #endif /* CONFIG_FAIL_MMC_REQUEST */
124
125 /**
126  *      mmc_request_done - finish processing an MMC request
127  *      @host: MMC host which completed request
128  *      @mrq: MMC request which request
129  *
130  *      MMC drivers should call this function when they have completed
131  *      their processing of a request.
132  */
133 void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
134 {
135         struct mmc_command *cmd = mrq->cmd;
136         int err = cmd->error;
137
138         if (err && cmd->retries && mmc_host_is_spi(host)) {
139                 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
140                         cmd->retries = 0;
141         }
142
143         if (err && cmd->retries && !mmc_card_removed(host->card)) {
144                 /*
145                  * Request starter must handle retries - see
146                  * mmc_wait_for_req_done().
147                  */
148                 if (mrq->done)
149                         mrq->done(mrq);
150         } else {
151                 mmc_should_fail_request(host, mrq);
152
153                 led_trigger_event(host->led, LED_OFF);
154
155                 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
156                         mmc_hostname(host), cmd->opcode, err,
157                         cmd->resp[0], cmd->resp[1],
158                         cmd->resp[2], cmd->resp[3]);
159
160                 if (mrq->data) {
161                         pr_debug("%s:     %d bytes transferred: %d\n",
162                                 mmc_hostname(host),
163                                 mrq->data->bytes_xfered, mrq->data->error);
164                 }
165
166                 if (mrq->stop) {
167                         pr_debug("%s:     (CMD%u): %d: %08x %08x %08x %08x\n",
168                                 mmc_hostname(host), mrq->stop->opcode,
169                                 mrq->stop->error,
170                                 mrq->stop->resp[0], mrq->stop->resp[1],
171                                 mrq->stop->resp[2], mrq->stop->resp[3]);
172                 }
173
174                 if (mrq->done)
175                         mrq->done(mrq);
176
177                 mmc_host_clk_release(host);
178         }
179 }
180
181 EXPORT_SYMBOL(mmc_request_done);
182
183 static void
184 mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
185 {
186 #ifdef CONFIG_MMC_DEBUG
187         unsigned int i, sz;
188         struct scatterlist *sg;
189 #endif
190
191         if (mrq->sbc) {
192                 pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n",
193                          mmc_hostname(host), mrq->sbc->opcode,
194                          mrq->sbc->arg, mrq->sbc->flags);
195         }
196
197         pr_debug("%s: starting CMD%u arg %08x flags %08x\n",
198                  mmc_hostname(host), mrq->cmd->opcode,
199                  mrq->cmd->arg, mrq->cmd->flags);
200
201         if (mrq->data) {
202                 pr_debug("%s:     blksz %d blocks %d flags %08x "
203                         "tsac %d ms nsac %d\n",
204                         mmc_hostname(host), mrq->data->blksz,
205                         mrq->data->blocks, mrq->data->flags,
206                         mrq->data->timeout_ns / 1000000,
207                         mrq->data->timeout_clks);
208         }
209
210         if (mrq->stop) {
211                 pr_debug("%s:     CMD%u arg %08x flags %08x\n",
212                          mmc_hostname(host), mrq->stop->opcode,
213                          mrq->stop->arg, mrq->stop->flags);
214         }
215
216         WARN_ON(!host->claimed);
217
218         mrq->cmd->error = 0;
219         mrq->cmd->mrq = mrq;
220         if (mrq->data) {
221                 BUG_ON(mrq->data->blksz > host->max_blk_size);
222                 BUG_ON(mrq->data->blocks > host->max_blk_count);
223                 BUG_ON(mrq->data->blocks * mrq->data->blksz >
224                         host->max_req_size);
225
226 #ifdef CONFIG_MMC_DEBUG
227                 sz = 0;
228                 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
229                         sz += sg->length;
230                 BUG_ON(sz != mrq->data->blocks * mrq->data->blksz);
231 #endif
232
233                 mrq->cmd->data = mrq->data;
234                 mrq->data->error = 0;
235                 mrq->data->mrq = mrq;
236                 if (mrq->stop) {
237                         mrq->data->stop = mrq->stop;
238                         mrq->stop->error = 0;
239                         mrq->stop->mrq = mrq;
240                 }
241         }
242         mmc_host_clk_hold(host);
243         led_trigger_event(host->led, LED_FULL);
244         host->ops->request(host, mrq);
245 }
246
247 static void mmc_wait_done(struct mmc_request *mrq)
248 {
249         complete(&mrq->completion);
250 }
251
252 static void __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
253 {
254         init_completion(&mrq->completion);
255         mrq->done = mmc_wait_done;
256         if (mmc_card_removed(host->card)) {
257                 mrq->cmd->error = -ENOMEDIUM;
258                 complete(&mrq->completion);
259                 return;
260         }
261         mmc_start_request(host, mrq);
262 }
263
264 static void mmc_wait_for_req_done(struct mmc_host *host,
265                                   struct mmc_request *mrq)
266 {
267         struct mmc_command *cmd;
268
269         while (1) {
270                 wait_for_completion(&mrq->completion);
271
272                 cmd = mrq->cmd;
273                 if (!cmd->error || !cmd->retries ||
274                     mmc_card_removed(host->card))
275                         break;
276
277                 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
278                          mmc_hostname(host), cmd->opcode, cmd->error);
279                 cmd->retries--;
280                 cmd->error = 0;
281                 host->ops->request(host, mrq);
282         }
283 }
284
285 /**
286  *      mmc_pre_req - Prepare for a new request
287  *      @host: MMC host to prepare command
288  *      @mrq: MMC request to prepare for
289  *      @is_first_req: true if there is no previous started request
290  *                     that may run in parellel to this call, otherwise false
291  *
292  *      mmc_pre_req() is called in prior to mmc_start_req() to let
293  *      host prepare for the new request. Preparation of a request may be
294  *      performed while another request is running on the host.
295  */
296 static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq,
297                  bool is_first_req)
298 {
299         if (host->ops->pre_req) {
300                 mmc_host_clk_hold(host);
301                 host->ops->pre_req(host, mrq, is_first_req);
302                 mmc_host_clk_release(host);
303         }
304 }
305
306 /**
307  *      mmc_post_req - Post process a completed request
308  *      @host: MMC host to post process command
309  *      @mrq: MMC request to post process for
310  *      @err: Error, if non zero, clean up any resources made in pre_req
311  *
312  *      Let the host post process a completed request. Post processing of
313  *      a request may be performed while another reuqest is running.
314  */
315 static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq,
316                          int err)
317 {
318         if (host->ops->post_req) {
319                 mmc_host_clk_hold(host);
320                 host->ops->post_req(host, mrq, err);
321                 mmc_host_clk_release(host);
322         }
323 }
324
325 /**
326  *      mmc_start_req - start a non-blocking request
327  *      @host: MMC host to start command
328  *      @areq: async request to start
329  *      @error: out parameter returns 0 for success, otherwise non zero
330  *
331  *      Start a new MMC custom command request for a host.
332  *      If there is on ongoing async request wait for completion
333  *      of that request and start the new one and return.
334  *      Does not wait for the new request to complete.
335  *
336  *      Returns the completed request, NULL in case of none completed.
337  *      Wait for the an ongoing request (previoulsy started) to complete and
338  *      return the completed request. If there is no ongoing request, NULL
339  *      is returned without waiting. NULL is not an error condition.
340  */
341 struct mmc_async_req *mmc_start_req(struct mmc_host *host,
342                                     struct mmc_async_req *areq, int *error)
343 {
344         int err = 0;
345         struct mmc_async_req *data = host->areq;
346
347         /* Prepare a new request */
348         if (areq)
349                 mmc_pre_req(host, areq->mrq, !host->areq);
350
351         if (host->areq) {
352                 mmc_wait_for_req_done(host, host->areq->mrq);
353                 err = host->areq->err_check(host->card, host->areq);
354                 if (err) {
355                         /* post process the completed failed request */
356                         mmc_post_req(host, host->areq->mrq, 0);
357                         if (areq)
358                                 /*
359                                  * Cancel the new prepared request, because
360                                  * it can't run until the failed
361                                  * request has been properly handled.
362                                  */
363                                 mmc_post_req(host, areq->mrq, -EINVAL);
364
365                         host->areq = NULL;
366                         goto out;
367                 }
368         }
369
370         if (areq)
371                 __mmc_start_req(host, areq->mrq);
372
373         if (host->areq)
374                 mmc_post_req(host, host->areq->mrq, 0);
375
376         host->areq = areq;
377  out:
378         if (error)
379                 *error = err;
380         return data;
381 }
382 EXPORT_SYMBOL(mmc_start_req);
383
384 /**
385  *      mmc_wait_for_req - start a request and wait for completion
386  *      @host: MMC host to start command
387  *      @mrq: MMC request to start
388  *
389  *      Start a new MMC custom command request for a host, and wait
390  *      for the command to complete. Does not attempt to parse the
391  *      response.
392  */
393 void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
394 {
395         __mmc_start_req(host, mrq);
396         mmc_wait_for_req_done(host, mrq);
397 }
398 EXPORT_SYMBOL(mmc_wait_for_req);
399
400 /**
401  *      mmc_interrupt_hpi - Issue for High priority Interrupt
402  *      @card: the MMC card associated with the HPI transfer
403  *
404  *      Issued High Priority Interrupt, and check for card status
405  *      util out-of prg-state.
406  */
407 int mmc_interrupt_hpi(struct mmc_card *card)
408 {
409         int err;
410         u32 status;
411
412         BUG_ON(!card);
413
414         if (!card->ext_csd.hpi_en) {
415                 pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host));
416                 return 1;
417         }
418
419         mmc_claim_host(card->host);
420         err = mmc_send_status(card, &status);
421         if (err) {
422                 pr_err("%s: Get card status fail\n", mmc_hostname(card->host));
423                 goto out;
424         }
425
426         /*
427          * If the card status is in PRG-state, we can send the HPI command.
428          */
429         if (R1_CURRENT_STATE(status) == R1_STATE_PRG) {
430                 do {
431                         /*
432                          * We don't know when the HPI command will finish
433                          * processing, so we need to resend HPI until out
434                          * of prg-state, and keep checking the card status
435                          * with SEND_STATUS.  If a timeout error occurs when
436                          * sending the HPI command, we are already out of
437                          * prg-state.
438                          */
439                         err = mmc_send_hpi_cmd(card, &status);
440                         if (err)
441                                 pr_debug("%s: abort HPI (%d error)\n",
442                                          mmc_hostname(card->host), err);
443
444                         err = mmc_send_status(card, &status);
445                         if (err)
446                                 break;
447                 } while (R1_CURRENT_STATE(status) == R1_STATE_PRG);
448         } else
449                 pr_debug("%s: Left prg-state\n", mmc_hostname(card->host));
450
451 out:
452         mmc_release_host(card->host);
453         return err;
454 }
455 EXPORT_SYMBOL(mmc_interrupt_hpi);
456
457 /**
458  *      mmc_wait_for_cmd - start a command and wait for completion
459  *      @host: MMC host to start command
460  *      @cmd: MMC command to start
461  *      @retries: maximum number of retries
462  *
463  *      Start a new MMC command for a host, and wait for the command
464  *      to complete.  Return any error that occurred while the command
465  *      was executing.  Do not attempt to parse the response.
466  */
467 int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
468 {
469         struct mmc_request mrq = {NULL};
470
471         WARN_ON(!host->claimed);
472
473         memset(cmd->resp, 0, sizeof(cmd->resp));
474         cmd->retries = retries;
475
476         mrq.cmd = cmd;
477         cmd->data = NULL;
478
479         mmc_wait_for_req(host, &mrq);
480
481         return cmd->error;
482 }
483
484 EXPORT_SYMBOL(mmc_wait_for_cmd);
485
486 /**
487  *      mmc_set_data_timeout - set the timeout for a data command
488  *      @data: data phase for command
489  *      @card: the MMC card associated with the data transfer
490  *
491  *      Computes the data timeout parameters according to the
492  *      correct algorithm given the card type.
493  */
494 void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
495 {
496         unsigned int mult;
497
498         /*
499          * SDIO cards only define an upper 1 s limit on access.
500          */
501         if (mmc_card_sdio(card)) {
502                 data->timeout_ns = 1000000000;
503                 data->timeout_clks = 0;
504                 return;
505         }
506
507         /*
508          * SD cards use a 100 multiplier rather than 10
509          */
510         mult = mmc_card_sd(card) ? 100 : 10;
511
512         /*
513          * Scale up the multiplier (and therefore the timeout) by
514          * the r2w factor for writes.
515          */
516         if (data->flags & MMC_DATA_WRITE)
517                 mult <<= card->csd.r2w_factor;
518
519         data->timeout_ns = card->csd.tacc_ns * mult;
520         data->timeout_clks = card->csd.tacc_clks * mult;
521
522         /*
523          * SD cards also have an upper limit on the timeout.
524          */
525         if (mmc_card_sd(card)) {
526                 unsigned int timeout_us, limit_us;
527
528                 timeout_us = data->timeout_ns / 1000;
529                 if (mmc_host_clk_rate(card->host))
530                         timeout_us += data->timeout_clks * 1000 /
531                                 (mmc_host_clk_rate(card->host) / 1000);
532
533                 if (data->flags & MMC_DATA_WRITE)
534                         /*
535                          * The limit is really 250 ms, but that is
536                          * insufficient for some crappy cards.
537                          */
538                         limit_us = 300000;
539                 else
540                         limit_us = 100000;
541
542                 /*
543                  * SDHC cards always use these fixed values.
544                  */
545                 if (timeout_us > limit_us || mmc_card_blockaddr(card)) {
546                         data->timeout_ns = limit_us * 1000;
547                         data->timeout_clks = 0;
548                 }
549         }
550
551         /*
552          * Some cards require longer data read timeout than indicated in CSD.
553          * Address this by setting the read timeout to a "reasonably high"
554          * value. For the cards tested, 300ms has proven enough. If necessary,
555          * this value can be increased if other problematic cards require this.
556          */
557         if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
558                 data->timeout_ns = 300000000;
559                 data->timeout_clks = 0;
560         }
561
562         /*
563          * Some cards need very high timeouts if driven in SPI mode.
564          * The worst observed timeout was 900ms after writing a
565          * continuous stream of data until the internal logic
566          * overflowed.
567          */
568         if (mmc_host_is_spi(card->host)) {
569                 if (data->flags & MMC_DATA_WRITE) {
570                         if (data->timeout_ns < 1000000000)
571                                 data->timeout_ns = 1000000000;  /* 1s */
572                 } else {
573                         if (data->timeout_ns < 100000000)
574                                 data->timeout_ns =  100000000;  /* 100ms */
575                 }
576         }
577 }
578 EXPORT_SYMBOL(mmc_set_data_timeout);
579
580 /**
581  *      mmc_align_data_size - pads a transfer size to a more optimal value
582  *      @card: the MMC card associated with the data transfer
583  *      @sz: original transfer size
584  *
585  *      Pads the original data size with a number of extra bytes in
586  *      order to avoid controller bugs and/or performance hits
587  *      (e.g. some controllers revert to PIO for certain sizes).
588  *
589  *      Returns the improved size, which might be unmodified.
590  *
591  *      Note that this function is only relevant when issuing a
592  *      single scatter gather entry.
593  */
594 unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
595 {
596         /*
597          * FIXME: We don't have a system for the controller to tell
598          * the core about its problems yet, so for now we just 32-bit
599          * align the size.
600          */
601         sz = ((sz + 3) / 4) * 4;
602
603         return sz;
604 }
605 EXPORT_SYMBOL(mmc_align_data_size);
606
607 /**
608  *      __mmc_claim_host - exclusively claim a host
609  *      @host: mmc host to claim
610  *      @abort: whether or not the operation should be aborted
611  *
612  *      Claim a host for a set of operations.  If @abort is non null and
613  *      dereference a non-zero value then this will return prematurely with
614  *      that non-zero value without acquiring the lock.  Returns zero
615  *      with the lock held otherwise.
616  */
617 int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
618 {
619         DECLARE_WAITQUEUE(wait, current);
620         unsigned long flags;
621         int stop;
622
623         might_sleep();
624
625         add_wait_queue(&host->wq, &wait);
626         spin_lock_irqsave(&host->lock, flags);
627         while (1) {
628                 set_current_state(TASK_UNINTERRUPTIBLE);
629                 stop = abort ? atomic_read(abort) : 0;
630                 if (stop || !host->claimed || host->claimer == current)
631                         break;
632                 spin_unlock_irqrestore(&host->lock, flags);
633                 schedule();
634                 spin_lock_irqsave(&host->lock, flags);
635         }
636         set_current_state(TASK_RUNNING);
637         if (!stop) {
638                 host->claimed = 1;
639                 host->claimer = current;
640                 host->claim_cnt += 1;
641         } else
642                 wake_up(&host->wq);
643         spin_unlock_irqrestore(&host->lock, flags);
644         remove_wait_queue(&host->wq, &wait);
645         if (host->ops->enable && !stop && host->claim_cnt == 1)
646                 host->ops->enable(host);
647         return stop;
648 }
649
650 EXPORT_SYMBOL(__mmc_claim_host);
651
652 /**
653  *      mmc_try_claim_host - try exclusively to claim a host
654  *      @host: mmc host to claim
655  *
656  *      Returns %1 if the host is claimed, %0 otherwise.
657  */
658 int mmc_try_claim_host(struct mmc_host *host)
659 {
660         int claimed_host = 0;
661         unsigned long flags;
662
663         spin_lock_irqsave(&host->lock, flags);
664         if (!host->claimed || host->claimer == current) {
665                 host->claimed = 1;
666                 host->claimer = current;
667                 host->claim_cnt += 1;
668                 claimed_host = 1;
669         }
670         spin_unlock_irqrestore(&host->lock, flags);
671         if (host->ops->enable && claimed_host && host->claim_cnt == 1)
672                 host->ops->enable(host);
673         return claimed_host;
674 }
675 EXPORT_SYMBOL(mmc_try_claim_host);
676
677 /**
678  *      mmc_release_host - release a host
679  *      @host: mmc host to release
680  *
681  *      Release a MMC host, allowing others to claim the host
682  *      for their operations.
683  */
684 void mmc_release_host(struct mmc_host *host)
685 {
686         unsigned long flags;
687
688         WARN_ON(!host->claimed);
689
690         if (host->ops->disable && host->claim_cnt == 1)
691                 host->ops->disable(host);
692
693         spin_lock_irqsave(&host->lock, flags);
694         if (--host->claim_cnt) {
695                 /* Release for nested claim */
696                 spin_unlock_irqrestore(&host->lock, flags);
697         } else {
698                 host->claimed = 0;
699                 host->claimer = NULL;
700                 spin_unlock_irqrestore(&host->lock, flags);
701                 wake_up(&host->wq);
702         }
703 }
704 EXPORT_SYMBOL(mmc_release_host);
705
706 /*
707  * Internal function that does the actual ios call to the host driver,
708  * optionally printing some debug output.
709  */
710 static inline void mmc_set_ios(struct mmc_host *host)
711 {
712         struct mmc_ios *ios = &host->ios;
713
714         pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
715                 "width %u timing %u\n",
716                  mmc_hostname(host), ios->clock, ios->bus_mode,
717                  ios->power_mode, ios->chip_select, ios->vdd,
718                  ios->bus_width, ios->timing);
719
720         if (ios->clock > 0)
721                 mmc_set_ungated(host);
722         host->ops->set_ios(host, ios);
723 }
724
725 /*
726  * Control chip select pin on a host.
727  */
728 void mmc_set_chip_select(struct mmc_host *host, int mode)
729 {
730         mmc_host_clk_hold(host);
731         host->ios.chip_select = mode;
732         mmc_set_ios(host);
733         mmc_host_clk_release(host);
734 }
735
736 /*
737  * Sets the host clock to the highest possible frequency that
738  * is below "hz".
739  */
740 static void __mmc_set_clock(struct mmc_host *host, unsigned int hz)
741 {
742         WARN_ON(hz < host->f_min);
743
744         if (hz > host->f_max)
745                 hz = host->f_max;
746
747         host->ios.clock = hz;
748         mmc_set_ios(host);
749 }
750
751 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
752 {
753         mmc_host_clk_hold(host);
754         __mmc_set_clock(host, hz);
755         mmc_host_clk_release(host);
756 }
757
758 #ifdef CONFIG_MMC_CLKGATE
759 /*
760  * This gates the clock by setting it to 0 Hz.
761  */
762 void mmc_gate_clock(struct mmc_host *host)
763 {
764         unsigned long flags;
765
766         spin_lock_irqsave(&host->clk_lock, flags);
767         host->clk_old = host->ios.clock;
768         host->ios.clock = 0;
769         host->clk_gated = true;
770         spin_unlock_irqrestore(&host->clk_lock, flags);
771         mmc_set_ios(host);
772 }
773
774 /*
775  * This restores the clock from gating by using the cached
776  * clock value.
777  */
778 void mmc_ungate_clock(struct mmc_host *host)
779 {
780         /*
781          * We should previously have gated the clock, so the clock shall
782          * be 0 here! The clock may however be 0 during initialization,
783          * when some request operations are performed before setting
784          * the frequency. When ungate is requested in that situation
785          * we just ignore the call.
786          */
787         if (host->clk_old) {
788                 BUG_ON(host->ios.clock);
789                 /* This call will also set host->clk_gated to false */
790                 __mmc_set_clock(host, host->clk_old);
791         }
792 }
793
794 void mmc_set_ungated(struct mmc_host *host)
795 {
796         unsigned long flags;
797
798         /*
799          * We've been given a new frequency while the clock is gated,
800          * so make sure we regard this as ungating it.
801          */
802         spin_lock_irqsave(&host->clk_lock, flags);
803         host->clk_gated = false;
804         spin_unlock_irqrestore(&host->clk_lock, flags);
805 }
806
807 #else
808 void mmc_set_ungated(struct mmc_host *host)
809 {
810 }
811 #endif
812
813 /*
814  * Change the bus mode (open drain/push-pull) of a host.
815  */
816 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
817 {
818         mmc_host_clk_hold(host);
819         host->ios.bus_mode = mode;
820         mmc_set_ios(host);
821         mmc_host_clk_release(host);
822 }
823
824 /*
825  * Change data bus width of a host.
826  */
827 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
828 {
829         mmc_host_clk_hold(host);
830         host->ios.bus_width = width;
831         mmc_set_ios(host);
832         mmc_host_clk_release(host);
833 }
834
835 /**
836  * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
837  * @vdd:        voltage (mV)
838  * @low_bits:   prefer low bits in boundary cases
839  *
840  * This function returns the OCR bit number according to the provided @vdd
841  * value. If conversion is not possible a negative errno value returned.
842  *
843  * Depending on the @low_bits flag the function prefers low or high OCR bits
844  * on boundary voltages. For example,
845  * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
846  * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
847  *
848  * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
849  */
850 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
851 {
852         const int max_bit = ilog2(MMC_VDD_35_36);
853         int bit;
854
855         if (vdd < 1650 || vdd > 3600)
856                 return -EINVAL;
857
858         if (vdd >= 1650 && vdd <= 1950)
859                 return ilog2(MMC_VDD_165_195);
860
861         if (low_bits)
862                 vdd -= 1;
863
864         /* Base 2000 mV, step 100 mV, bit's base 8. */
865         bit = (vdd - 2000) / 100 + 8;
866         if (bit > max_bit)
867                 return max_bit;
868         return bit;
869 }
870
871 /**
872  * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
873  * @vdd_min:    minimum voltage value (mV)
874  * @vdd_max:    maximum voltage value (mV)
875  *
876  * This function returns the OCR mask bits according to the provided @vdd_min
877  * and @vdd_max values. If conversion is not possible the function returns 0.
878  *
879  * Notes wrt boundary cases:
880  * This function sets the OCR bits for all boundary voltages, for example
881  * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
882  * MMC_VDD_34_35 mask.
883  */
884 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
885 {
886         u32 mask = 0;
887
888         if (vdd_max < vdd_min)
889                 return 0;
890
891         /* Prefer high bits for the boundary vdd_max values. */
892         vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
893         if (vdd_max < 0)
894                 return 0;
895
896         /* Prefer low bits for the boundary vdd_min values. */
897         vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
898         if (vdd_min < 0)
899                 return 0;
900
901         /* Fill the mask, from max bit to min bit. */
902         while (vdd_max >= vdd_min)
903                 mask |= 1 << vdd_max--;
904
905         return mask;
906 }
907 EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
908
909 #ifdef CONFIG_REGULATOR
910
911 /**
912  * mmc_regulator_get_ocrmask - return mask of supported voltages
913  * @supply: regulator to use
914  *
915  * This returns either a negative errno, or a mask of voltages that
916  * can be provided to MMC/SD/SDIO devices using the specified voltage
917  * regulator.  This would normally be called before registering the
918  * MMC host adapter.
919  */
920 int mmc_regulator_get_ocrmask(struct regulator *supply)
921 {
922         int                     result = 0;
923         int                     count;
924         int                     i;
925
926         count = regulator_count_voltages(supply);
927         if (count < 0)
928                 return count;
929
930         for (i = 0; i < count; i++) {
931                 int             vdd_uV;
932                 int             vdd_mV;
933
934                 vdd_uV = regulator_list_voltage(supply, i);
935                 if (vdd_uV <= 0)
936                         continue;
937
938                 vdd_mV = vdd_uV / 1000;
939                 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
940         }
941
942         return result;
943 }
944 EXPORT_SYMBOL(mmc_regulator_get_ocrmask);
945
946 /**
947  * mmc_regulator_set_ocr - set regulator to match host->ios voltage
948  * @mmc: the host to regulate
949  * @supply: regulator to use
950  * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
951  *
952  * Returns zero on success, else negative errno.
953  *
954  * MMC host drivers may use this to enable or disable a regulator using
955  * a particular supply voltage.  This would normally be called from the
956  * set_ios() method.
957  */
958 int mmc_regulator_set_ocr(struct mmc_host *mmc,
959                         struct regulator *supply,
960                         unsigned short vdd_bit)
961 {
962         int                     result = 0;
963         int                     min_uV, max_uV;
964
965         if (vdd_bit) {
966                 int             tmp;
967                 int             voltage;
968
969                 /* REVISIT mmc_vddrange_to_ocrmask() may have set some
970                  * bits this regulator doesn't quite support ... don't
971                  * be too picky, most cards and regulators are OK with
972                  * a 0.1V range goof (it's a small error percentage).
973                  */
974                 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
975                 if (tmp == 0) {
976                         min_uV = 1650 * 1000;
977                         max_uV = 1950 * 1000;
978                 } else {
979                         min_uV = 1900 * 1000 + tmp * 100 * 1000;
980                         max_uV = min_uV + 100 * 1000;
981                 }
982
983                 /* avoid needless changes to this voltage; the regulator
984                  * might not allow this operation
985                  */
986                 voltage = regulator_get_voltage(supply);
987
988                 if (mmc->caps2 & MMC_CAP2_BROKEN_VOLTAGE)
989                         min_uV = max_uV = voltage;
990
991                 if (voltage < 0)
992                         result = voltage;
993                 else if (voltage < min_uV || voltage > max_uV)
994                         result = regulator_set_voltage(supply, min_uV, max_uV);
995                 else
996                         result = 0;
997
998                 if (result == 0 && !mmc->regulator_enabled) {
999                         result = regulator_enable(supply);
1000                         if (!result)
1001                                 mmc->regulator_enabled = true;
1002                 }
1003         } else if (mmc->regulator_enabled) {
1004                 result = regulator_disable(supply);
1005                 if (result == 0)
1006                         mmc->regulator_enabled = false;
1007         }
1008
1009         if (result)
1010                 dev_err(mmc_dev(mmc),
1011                         "could not set regulator OCR (%d)\n", result);
1012         return result;
1013 }
1014 EXPORT_SYMBOL(mmc_regulator_set_ocr);
1015
1016 #endif /* CONFIG_REGULATOR */
1017
1018 /*
1019  * Mask off any voltages we don't support and select
1020  * the lowest voltage
1021  */
1022 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1023 {
1024         int bit;
1025
1026         ocr &= host->ocr_avail;
1027
1028         bit = ffs(ocr);
1029         if (bit) {
1030                 bit -= 1;
1031
1032                 ocr &= 3 << bit;
1033
1034                 mmc_host_clk_hold(host);
1035                 host->ios.vdd = bit;
1036                 mmc_set_ios(host);
1037                 mmc_host_clk_release(host);
1038         } else {
1039                 pr_warning("%s: host doesn't support card's voltages\n",
1040                                 mmc_hostname(host));
1041                 ocr = 0;
1042         }
1043
1044         return ocr;
1045 }
1046
1047 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, bool cmd11)
1048 {
1049         struct mmc_command cmd = {0};
1050         int err = 0;
1051
1052         BUG_ON(!host);
1053
1054         /*
1055          * Send CMD11 only if the request is to switch the card to
1056          * 1.8V signalling.
1057          */
1058         if ((signal_voltage != MMC_SIGNAL_VOLTAGE_330) && cmd11) {
1059                 cmd.opcode = SD_SWITCH_VOLTAGE;
1060                 cmd.arg = 0;
1061                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1062
1063                 err = mmc_wait_for_cmd(host, &cmd, 0);
1064                 if (err)
1065                         return err;
1066
1067                 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1068                         return -EIO;
1069         }
1070
1071         host->ios.signal_voltage = signal_voltage;
1072
1073         if (host->ops->start_signal_voltage_switch) {
1074                 mmc_host_clk_hold(host);
1075                 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1076                 mmc_host_clk_release(host);
1077         }
1078
1079         return err;
1080 }
1081
1082 /*
1083  * Select timing parameters for host.
1084  */
1085 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1086 {
1087         mmc_host_clk_hold(host);
1088         host->ios.timing = timing;
1089         mmc_set_ios(host);
1090         mmc_host_clk_release(host);
1091 }
1092
1093 /*
1094  * Select appropriate driver type for host.
1095  */
1096 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1097 {
1098         mmc_host_clk_hold(host);
1099         host->ios.drv_type = drv_type;
1100         mmc_set_ios(host);
1101         mmc_host_clk_release(host);
1102 }
1103
1104 static void mmc_poweroff_notify(struct mmc_host *host)
1105 {
1106         struct mmc_card *card;
1107         unsigned int timeout;
1108         unsigned int notify_type = EXT_CSD_NO_POWER_NOTIFICATION;
1109         int err = 0;
1110
1111         card = host->card;
1112         mmc_claim_host(host);
1113
1114         /*
1115          * Send power notify command only if card
1116          * is mmc and notify state is powered ON
1117          */
1118         if (card && mmc_card_mmc(card) &&
1119             (card->poweroff_notify_state == MMC_POWERED_ON)) {
1120
1121                 if (host->power_notify_type == MMC_HOST_PW_NOTIFY_SHORT) {
1122                         notify_type = EXT_CSD_POWER_OFF_SHORT;
1123                         timeout = card->ext_csd.generic_cmd6_time;
1124                         card->poweroff_notify_state = MMC_POWEROFF_SHORT;
1125                 } else {
1126                         notify_type = EXT_CSD_POWER_OFF_LONG;
1127                         timeout = card->ext_csd.power_off_longtime;
1128                         card->poweroff_notify_state = MMC_POWEROFF_LONG;
1129                 }
1130
1131                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1132                                  EXT_CSD_POWER_OFF_NOTIFICATION,
1133                                  notify_type, timeout);
1134
1135                 if (err && err != -EBADMSG)
1136                         pr_err("Device failed to respond within %d poweroff "
1137                                "time. Forcefully powering down the device\n",
1138                                timeout);
1139
1140                 /* Set the card state to no notification after the poweroff */
1141                 card->poweroff_notify_state = MMC_NO_POWER_NOTIFICATION;
1142         }
1143         mmc_release_host(host);
1144 }
1145
1146 /*
1147  * Apply power to the MMC stack.  This is a two-stage process.
1148  * First, we enable power to the card without the clock running.
1149  * We then wait a bit for the power to stabilise.  Finally,
1150  * enable the bus drivers and clock to the card.
1151  *
1152  * We must _NOT_ enable the clock prior to power stablising.
1153  *
1154  * If a host does all the power sequencing itself, ignore the
1155  * initial MMC_POWER_UP stage.
1156  */
1157 static void mmc_power_up(struct mmc_host *host)
1158 {
1159         int bit;
1160
1161         mmc_host_clk_hold(host);
1162
1163         /* If ocr is set, we use it */
1164         if (host->ocr)
1165                 bit = ffs(host->ocr) - 1;
1166         else
1167                 bit = fls(host->ocr_avail) - 1;
1168
1169         host->ios.vdd = bit;
1170         if (mmc_host_is_spi(host))
1171                 host->ios.chip_select = MMC_CS_HIGH;
1172         else
1173                 host->ios.chip_select = MMC_CS_DONTCARE;
1174         host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1175         host->ios.power_mode = MMC_POWER_UP;
1176         host->ios.bus_width = MMC_BUS_WIDTH_1;
1177         host->ios.timing = MMC_TIMING_LEGACY;
1178         mmc_set_ios(host);
1179
1180         /*
1181          * This delay should be sufficient to allow the power supply
1182          * to reach the minimum voltage.
1183          */
1184         mmc_delay(10);
1185
1186         host->ios.clock = host->f_init;
1187
1188         host->ios.power_mode = MMC_POWER_ON;
1189         mmc_set_ios(host);
1190
1191         /*
1192          * This delay must be at least 74 clock sizes, or 1 ms, or the
1193          * time required to reach a stable voltage.
1194          */
1195         mmc_delay(10);
1196
1197         mmc_host_clk_release(host);
1198 }
1199
1200 void mmc_power_off(struct mmc_host *host)
1201 {
1202         int err = 0;
1203         mmc_host_clk_hold(host);
1204
1205         host->ios.clock = 0;
1206         host->ios.vdd = 0;
1207
1208         /*
1209          * For eMMC 4.5 device send AWAKE command before
1210          * POWER_OFF_NOTIFY command, because in sleep state
1211          * eMMC 4.5 devices respond to only RESET and AWAKE cmd
1212          */
1213         if (host->card && mmc_card_is_sleep(host->card) &&
1214             host->bus_ops->resume) {
1215                 err = host->bus_ops->resume(host);
1216
1217                 if (!err)
1218                         mmc_poweroff_notify(host);
1219                 else
1220                         pr_warning("%s: error %d during resume "
1221                                    "(continue with poweroff sequence)\n",
1222                                    mmc_hostname(host), err);
1223         }
1224
1225         /*
1226          * Reset ocr mask to be the highest possible voltage supported for
1227          * this mmc host. This value will be used at next power up.
1228          */
1229         host->ocr = 1 << (fls(host->ocr_avail) - 1);
1230
1231         if (!mmc_host_is_spi(host)) {
1232                 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
1233                 host->ios.chip_select = MMC_CS_DONTCARE;
1234         }
1235         host->ios.power_mode = MMC_POWER_OFF;
1236         host->ios.bus_width = MMC_BUS_WIDTH_1;
1237         host->ios.timing = MMC_TIMING_LEGACY;
1238         mmc_set_ios(host);
1239
1240         /*
1241          * Some configurations, such as the 802.11 SDIO card in the OLPC
1242          * XO-1.5, require a short delay after poweroff before the card
1243          * can be successfully turned on again.
1244          */
1245         mmc_delay(1);
1246
1247         mmc_host_clk_release(host);
1248 }
1249
1250 /*
1251  * Cleanup when the last reference to the bus operator is dropped.
1252  */
1253 static void __mmc_release_bus(struct mmc_host *host)
1254 {
1255         BUG_ON(!host);
1256         BUG_ON(host->bus_refs);
1257         BUG_ON(!host->bus_dead);
1258
1259         host->bus_ops = NULL;
1260 }
1261
1262 /*
1263  * Increase reference count of bus operator
1264  */
1265 static inline void mmc_bus_get(struct mmc_host *host)
1266 {
1267         unsigned long flags;
1268
1269         spin_lock_irqsave(&host->lock, flags);
1270         host->bus_refs++;
1271         spin_unlock_irqrestore(&host->lock, flags);
1272 }
1273
1274 /*
1275  * Decrease reference count of bus operator and free it if
1276  * it is the last reference.
1277  */
1278 static inline void mmc_bus_put(struct mmc_host *host)
1279 {
1280         unsigned long flags;
1281
1282         spin_lock_irqsave(&host->lock, flags);
1283         host->bus_refs--;
1284         if ((host->bus_refs == 0) && host->bus_ops)
1285                 __mmc_release_bus(host);
1286         spin_unlock_irqrestore(&host->lock, flags);
1287 }
1288
1289 /*
1290  * Assign a mmc bus handler to a host. Only one bus handler may control a
1291  * host at any given time.
1292  */
1293 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1294 {
1295         unsigned long flags;
1296
1297         BUG_ON(!host);
1298         BUG_ON(!ops);
1299
1300         WARN_ON(!host->claimed);
1301
1302         spin_lock_irqsave(&host->lock, flags);
1303
1304         BUG_ON(host->bus_ops);
1305         BUG_ON(host->bus_refs);
1306
1307         host->bus_ops = ops;
1308         host->bus_refs = 1;
1309         host->bus_dead = 0;
1310
1311         spin_unlock_irqrestore(&host->lock, flags);
1312 }
1313
1314 /*
1315  * Remove the current bus handler from a host.
1316  */
1317 void mmc_detach_bus(struct mmc_host *host)
1318 {
1319         unsigned long flags;
1320
1321         BUG_ON(!host);
1322
1323         WARN_ON(!host->claimed);
1324         WARN_ON(!host->bus_ops);
1325
1326         spin_lock_irqsave(&host->lock, flags);
1327
1328         host->bus_dead = 1;
1329
1330         spin_unlock_irqrestore(&host->lock, flags);
1331
1332         mmc_bus_put(host);
1333 }
1334
1335 /**
1336  *      mmc_detect_change - process change of state on a MMC socket
1337  *      @host: host which changed state.
1338  *      @delay: optional delay to wait before detection (jiffies)
1339  *
1340  *      MMC drivers should call this when they detect a card has been
1341  *      inserted or removed. The MMC layer will confirm that any
1342  *      present card is still functional, and initialize any newly
1343  *      inserted.
1344  */
1345 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1346 {
1347 #ifdef CONFIG_MMC_DEBUG
1348         unsigned long flags;
1349         spin_lock_irqsave(&host->lock, flags);
1350         WARN_ON(host->removed);
1351         spin_unlock_irqrestore(&host->lock, flags);
1352 #endif
1353         host->detect_change = 1;
1354         mmc_schedule_delayed_work(&host->detect, delay);
1355 }
1356
1357 EXPORT_SYMBOL(mmc_detect_change);
1358
1359 void mmc_init_erase(struct mmc_card *card)
1360 {
1361         unsigned int sz;
1362
1363         if (is_power_of_2(card->erase_size))
1364                 card->erase_shift = ffs(card->erase_size) - 1;
1365         else
1366                 card->erase_shift = 0;
1367
1368         /*
1369          * It is possible to erase an arbitrarily large area of an SD or MMC
1370          * card.  That is not desirable because it can take a long time
1371          * (minutes) potentially delaying more important I/O, and also the
1372          * timeout calculations become increasingly hugely over-estimated.
1373          * Consequently, 'pref_erase' is defined as a guide to limit erases
1374          * to that size and alignment.
1375          *
1376          * For SD cards that define Allocation Unit size, limit erases to one
1377          * Allocation Unit at a time.  For MMC cards that define High Capacity
1378          * Erase Size, whether it is switched on or not, limit to that size.
1379          * Otherwise just have a stab at a good value.  For modern cards it
1380          * will end up being 4MiB.  Note that if the value is too small, it
1381          * can end up taking longer to erase.
1382          */
1383         if (mmc_card_sd(card) && card->ssr.au) {
1384                 card->pref_erase = card->ssr.au;
1385                 card->erase_shift = ffs(card->ssr.au) - 1;
1386         } else if (card->ext_csd.hc_erase_size) {
1387                 card->pref_erase = card->ext_csd.hc_erase_size;
1388         } else {
1389                 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1390                 if (sz < 128)
1391                         card->pref_erase = 512 * 1024 / 512;
1392                 else if (sz < 512)
1393                         card->pref_erase = 1024 * 1024 / 512;
1394                 else if (sz < 1024)
1395                         card->pref_erase = 2 * 1024 * 1024 / 512;
1396                 else
1397                         card->pref_erase = 4 * 1024 * 1024 / 512;
1398                 if (card->pref_erase < card->erase_size)
1399                         card->pref_erase = card->erase_size;
1400                 else {
1401                         sz = card->pref_erase % card->erase_size;
1402                         if (sz)
1403                                 card->pref_erase += card->erase_size - sz;
1404                 }
1405         }
1406 }
1407
1408 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1409                                           unsigned int arg, unsigned int qty)
1410 {
1411         unsigned int erase_timeout;
1412
1413         if (card->ext_csd.erase_group_def & 1) {
1414                 /* High Capacity Erase Group Size uses HC timeouts */
1415                 if (arg == MMC_TRIM_ARG)
1416                         erase_timeout = card->ext_csd.trim_timeout;
1417                 else
1418                         erase_timeout = card->ext_csd.hc_erase_timeout;
1419         } else {
1420                 /* CSD Erase Group Size uses write timeout */
1421                 unsigned int mult = (10 << card->csd.r2w_factor);
1422                 unsigned int timeout_clks = card->csd.tacc_clks * mult;
1423                 unsigned int timeout_us;
1424
1425                 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
1426                 if (card->csd.tacc_ns < 1000000)
1427                         timeout_us = (card->csd.tacc_ns * mult) / 1000;
1428                 else
1429                         timeout_us = (card->csd.tacc_ns / 1000) * mult;
1430
1431                 /*
1432                  * ios.clock is only a target.  The real clock rate might be
1433                  * less but not that much less, so fudge it by multiplying by 2.
1434                  */
1435                 timeout_clks <<= 1;
1436                 timeout_us += (timeout_clks * 1000) /
1437                               (mmc_host_clk_rate(card->host) / 1000);
1438
1439                 erase_timeout = timeout_us / 1000;
1440
1441                 /*
1442                  * Theoretically, the calculation could underflow so round up
1443                  * to 1ms in that case.
1444                  */
1445                 if (!erase_timeout)
1446                         erase_timeout = 1;
1447         }
1448
1449         /* Multiplier for secure operations */
1450         if (arg & MMC_SECURE_ARGS) {
1451                 if (arg == MMC_SECURE_ERASE_ARG)
1452                         erase_timeout *= card->ext_csd.sec_erase_mult;
1453                 else
1454                         erase_timeout *= card->ext_csd.sec_trim_mult;
1455         }
1456
1457         erase_timeout *= qty;
1458
1459         /*
1460          * Ensure at least a 1 second timeout for SPI as per
1461          * 'mmc_set_data_timeout()'
1462          */
1463         if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
1464                 erase_timeout = 1000;
1465
1466         return erase_timeout;
1467 }
1468
1469 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
1470                                          unsigned int arg,
1471                                          unsigned int qty)
1472 {
1473         unsigned int erase_timeout;
1474
1475         if (card->ssr.erase_timeout) {
1476                 /* Erase timeout specified in SD Status Register (SSR) */
1477                 erase_timeout = card->ssr.erase_timeout * qty +
1478                                 card->ssr.erase_offset;
1479         } else {
1480                 /*
1481                  * Erase timeout not specified in SD Status Register (SSR) so
1482                  * use 250ms per write block.
1483                  */
1484                 erase_timeout = 250 * qty;
1485         }
1486
1487         /* Must not be less than 1 second */
1488         if (erase_timeout < 1000)
1489                 erase_timeout = 1000;
1490
1491         return erase_timeout;
1492 }
1493
1494 static unsigned int mmc_erase_timeout(struct mmc_card *card,
1495                                       unsigned int arg,
1496                                       unsigned int qty)
1497 {
1498         if (mmc_card_sd(card))
1499                 return mmc_sd_erase_timeout(card, arg, qty);
1500         else
1501                 return mmc_mmc_erase_timeout(card, arg, qty);
1502 }
1503
1504 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
1505                         unsigned int to, unsigned int arg)
1506 {
1507         struct mmc_command cmd = {0};
1508         unsigned int qty = 0;
1509         int err;
1510
1511         /*
1512          * qty is used to calculate the erase timeout which depends on how many
1513          * erase groups (or allocation units in SD terminology) are affected.
1514          * We count erasing part of an erase group as one erase group.
1515          * For SD, the allocation units are always a power of 2.  For MMC, the
1516          * erase group size is almost certainly also power of 2, but it does not
1517          * seem to insist on that in the JEDEC standard, so we fall back to
1518          * division in that case.  SD may not specify an allocation unit size,
1519          * in which case the timeout is based on the number of write blocks.
1520          *
1521          * Note that the timeout for secure trim 2 will only be correct if the
1522          * number of erase groups specified is the same as the total of all
1523          * preceding secure trim 1 commands.  Since the power may have been
1524          * lost since the secure trim 1 commands occurred, it is generally
1525          * impossible to calculate the secure trim 2 timeout correctly.
1526          */
1527         if (card->erase_shift)
1528                 qty += ((to >> card->erase_shift) -
1529                         (from >> card->erase_shift)) + 1;
1530         else if (mmc_card_sd(card))
1531                 qty += to - from + 1;
1532         else
1533                 qty += ((to / card->erase_size) -
1534                         (from / card->erase_size)) + 1;
1535
1536         if (!mmc_card_blockaddr(card)) {
1537                 from <<= 9;
1538                 to <<= 9;
1539         }
1540
1541         if (mmc_card_sd(card))
1542                 cmd.opcode = SD_ERASE_WR_BLK_START;
1543         else
1544                 cmd.opcode = MMC_ERASE_GROUP_START;
1545         cmd.arg = from;
1546         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1547         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1548         if (err) {
1549                 pr_err("mmc_erase: group start error %d, "
1550                        "status %#x\n", err, cmd.resp[0]);
1551                 err = -EIO;
1552                 goto out;
1553         }
1554
1555         memset(&cmd, 0, sizeof(struct mmc_command));
1556         if (mmc_card_sd(card))
1557                 cmd.opcode = SD_ERASE_WR_BLK_END;
1558         else
1559                 cmd.opcode = MMC_ERASE_GROUP_END;
1560         cmd.arg = to;
1561         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1562         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1563         if (err) {
1564                 pr_err("mmc_erase: group end error %d, status %#x\n",
1565                        err, cmd.resp[0]);
1566                 err = -EIO;
1567                 goto out;
1568         }
1569
1570         memset(&cmd, 0, sizeof(struct mmc_command));
1571         cmd.opcode = MMC_ERASE;
1572         cmd.arg = arg;
1573         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1574         cmd.cmd_timeout_ms = mmc_erase_timeout(card, arg, qty);
1575         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1576         if (err) {
1577                 pr_err("mmc_erase: erase error %d, status %#x\n",
1578                        err, cmd.resp[0]);
1579                 err = -EIO;
1580                 goto out;
1581         }
1582
1583         if (mmc_host_is_spi(card->host))
1584                 goto out;
1585
1586         do {
1587                 memset(&cmd, 0, sizeof(struct mmc_command));
1588                 cmd.opcode = MMC_SEND_STATUS;
1589                 cmd.arg = card->rca << 16;
1590                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1591                 /* Do not retry else we can't see errors */
1592                 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1593                 if (err || (cmd.resp[0] & 0xFDF92000)) {
1594                         pr_err("error %d requesting status %#x\n",
1595                                 err, cmd.resp[0]);
1596                         err = -EIO;
1597                         goto out;
1598                 }
1599         } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
1600                  R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG);
1601 out:
1602         return err;
1603 }
1604
1605 /**
1606  * mmc_erase - erase sectors.
1607  * @card: card to erase
1608  * @from: first sector to erase
1609  * @nr: number of sectors to erase
1610  * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
1611  *
1612  * Caller must claim host before calling this function.
1613  */
1614 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
1615               unsigned int arg)
1616 {
1617         unsigned int rem, to = from + nr;
1618
1619         if (!(card->host->caps & MMC_CAP_ERASE) ||
1620             !(card->csd.cmdclass & CCC_ERASE))
1621                 return -EOPNOTSUPP;
1622
1623         if (!card->erase_size)
1624                 return -EOPNOTSUPP;
1625
1626         if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
1627                 return -EOPNOTSUPP;
1628
1629         if ((arg & MMC_SECURE_ARGS) &&
1630             !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
1631                 return -EOPNOTSUPP;
1632
1633         if ((arg & MMC_TRIM_ARGS) &&
1634             !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
1635                 return -EOPNOTSUPP;
1636
1637         if (arg == MMC_SECURE_ERASE_ARG) {
1638                 if (from % card->erase_size || nr % card->erase_size)
1639                         return -EINVAL;
1640         }
1641
1642         if (arg == MMC_ERASE_ARG) {
1643                 rem = from % card->erase_size;
1644                 if (rem) {
1645                         rem = card->erase_size - rem;
1646                         from += rem;
1647                         if (nr > rem)
1648                                 nr -= rem;
1649                         else
1650                                 return 0;
1651                 }
1652                 rem = nr % card->erase_size;
1653                 if (rem)
1654                         nr -= rem;
1655         }
1656
1657         if (nr == 0)
1658                 return 0;
1659
1660         to = from + nr;
1661
1662         if (to <= from)
1663                 return -EINVAL;
1664
1665         /* 'from' and 'to' are inclusive */
1666         to -= 1;
1667
1668         return mmc_do_erase(card, from, to, arg);
1669 }
1670 EXPORT_SYMBOL(mmc_erase);
1671
1672 int mmc_can_erase(struct mmc_card *card)
1673 {
1674         if ((card->host->caps & MMC_CAP_ERASE) &&
1675             (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
1676                 return 1;
1677         return 0;
1678 }
1679 EXPORT_SYMBOL(mmc_can_erase);
1680
1681 int mmc_can_trim(struct mmc_card *card)
1682 {
1683         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN)
1684                 return 1;
1685         if (mmc_can_discard(card))
1686                 return 1;
1687         return 0;
1688 }
1689 EXPORT_SYMBOL(mmc_can_trim);
1690
1691 int mmc_can_discard(struct mmc_card *card)
1692 {
1693         /*
1694          * As there's no way to detect the discard support bit at v4.5
1695          * use the s/w feature support filed.
1696          */
1697         if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
1698                 return 1;
1699         return 0;
1700 }
1701 EXPORT_SYMBOL(mmc_can_discard);
1702
1703 int mmc_can_sanitize(struct mmc_card *card)
1704 {
1705         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
1706                 return 1;
1707         return 0;
1708 }
1709 EXPORT_SYMBOL(mmc_can_sanitize);
1710
1711 int mmc_can_secure_erase_trim(struct mmc_card *card)
1712 {
1713         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)
1714                 return 1;
1715         return 0;
1716 }
1717 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
1718
1719 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
1720                             unsigned int nr)
1721 {
1722         if (!card->erase_size)
1723                 return 0;
1724         if (from % card->erase_size || nr % card->erase_size)
1725                 return 0;
1726         return 1;
1727 }
1728 EXPORT_SYMBOL(mmc_erase_group_aligned);
1729
1730 static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
1731                                             unsigned int arg)
1732 {
1733         struct mmc_host *host = card->host;
1734         unsigned int max_discard, x, y, qty = 0, max_qty, timeout;
1735         unsigned int last_timeout = 0;
1736
1737         if (card->erase_shift)
1738                 max_qty = UINT_MAX >> card->erase_shift;
1739         else if (mmc_card_sd(card))
1740                 max_qty = UINT_MAX;
1741         else
1742                 max_qty = UINT_MAX / card->erase_size;
1743
1744         /* Find the largest qty with an OK timeout */
1745         do {
1746                 y = 0;
1747                 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
1748                         timeout = mmc_erase_timeout(card, arg, qty + x);
1749                         if (timeout > host->max_discard_to)
1750                                 break;
1751                         if (timeout < last_timeout)
1752                                 break;
1753                         last_timeout = timeout;
1754                         y = x;
1755                 }
1756                 qty += y;
1757         } while (y);
1758
1759         if (!qty)
1760                 return 0;
1761
1762         if (qty == 1)
1763                 return 1;
1764
1765         /* Convert qty to sectors */
1766         if (card->erase_shift)
1767                 max_discard = --qty << card->erase_shift;
1768         else if (mmc_card_sd(card))
1769                 max_discard = qty;
1770         else
1771                 max_discard = --qty * card->erase_size;
1772
1773         return max_discard;
1774 }
1775
1776 unsigned int mmc_calc_max_discard(struct mmc_card *card)
1777 {
1778         struct mmc_host *host = card->host;
1779         unsigned int max_discard, max_trim;
1780
1781         if (!host->max_discard_to)
1782                 return UINT_MAX;
1783
1784         /*
1785          * Without erase_group_def set, MMC erase timeout depends on clock
1786          * frequence which can change.  In that case, the best choice is
1787          * just the preferred erase size.
1788          */
1789         if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
1790                 return card->pref_erase;
1791
1792         max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
1793         if (mmc_can_trim(card)) {
1794                 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
1795                 if (max_trim < max_discard)
1796                         max_discard = max_trim;
1797         } else if (max_discard < card->erase_size) {
1798                 max_discard = 0;
1799         }
1800         pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
1801                  mmc_hostname(host), max_discard, host->max_discard_to);
1802         return max_discard;
1803 }
1804 EXPORT_SYMBOL(mmc_calc_max_discard);
1805
1806 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
1807 {
1808         struct mmc_command cmd = {0};
1809
1810         if (mmc_card_blockaddr(card) || mmc_card_ddr_mode(card))
1811                 return 0;
1812
1813         cmd.opcode = MMC_SET_BLOCKLEN;
1814         cmd.arg = blocklen;
1815         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1816         return mmc_wait_for_cmd(card->host, &cmd, 5);
1817 }
1818 EXPORT_SYMBOL(mmc_set_blocklen);
1819
1820 static void mmc_hw_reset_for_init(struct mmc_host *host)
1821 {
1822         if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
1823                 return;
1824         mmc_host_clk_hold(host);
1825         host->ops->hw_reset(host);
1826         mmc_host_clk_release(host);
1827 }
1828
1829 int mmc_can_reset(struct mmc_card *card)
1830 {
1831         u8 rst_n_function;
1832
1833         if (!mmc_card_mmc(card))
1834                 return 0;
1835         rst_n_function = card->ext_csd.rst_n_function;
1836         if ((rst_n_function & EXT_CSD_RST_N_EN_MASK) != EXT_CSD_RST_N_ENABLED)
1837                 return 0;
1838         return 1;
1839 }
1840 EXPORT_SYMBOL(mmc_can_reset);
1841
1842 static int mmc_do_hw_reset(struct mmc_host *host, int check)
1843 {
1844         struct mmc_card *card = host->card;
1845
1846         if (!host->bus_ops->power_restore)
1847                 return -EOPNOTSUPP;
1848
1849         if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
1850                 return -EOPNOTSUPP;
1851
1852         if (!card)
1853                 return -EINVAL;
1854
1855         if (!mmc_can_reset(card))
1856                 return -EOPNOTSUPP;
1857
1858         mmc_host_clk_hold(host);
1859         mmc_set_clock(host, host->f_init);
1860
1861         host->ops->hw_reset(host);
1862
1863         /* If the reset has happened, then a status command will fail */
1864         if (check) {
1865                 struct mmc_command cmd = {0};
1866                 int err;
1867
1868                 cmd.opcode = MMC_SEND_STATUS;
1869                 if (!mmc_host_is_spi(card->host))
1870                         cmd.arg = card->rca << 16;
1871                 cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
1872                 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1873                 if (!err) {
1874                         mmc_host_clk_release(host);
1875                         return -ENOSYS;
1876                 }
1877         }
1878
1879         host->card->state &= ~(MMC_STATE_HIGHSPEED | MMC_STATE_HIGHSPEED_DDR);
1880         if (mmc_host_is_spi(host)) {
1881                 host->ios.chip_select = MMC_CS_HIGH;
1882                 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1883         } else {
1884                 host->ios.chip_select = MMC_CS_DONTCARE;
1885                 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
1886         }
1887         host->ios.bus_width = MMC_BUS_WIDTH_1;
1888         host->ios.timing = MMC_TIMING_LEGACY;
1889         mmc_set_ios(host);
1890
1891         mmc_host_clk_release(host);
1892
1893         return host->bus_ops->power_restore(host);
1894 }
1895
1896 int mmc_hw_reset(struct mmc_host *host)
1897 {
1898         return mmc_do_hw_reset(host, 0);
1899 }
1900 EXPORT_SYMBOL(mmc_hw_reset);
1901
1902 int mmc_hw_reset_check(struct mmc_host *host)
1903 {
1904         return mmc_do_hw_reset(host, 1);
1905 }
1906 EXPORT_SYMBOL(mmc_hw_reset_check);
1907
1908 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
1909 {
1910         host->f_init = freq;
1911
1912 #ifdef CONFIG_MMC_DEBUG
1913         pr_info("%s: %s: trying to init card at %u Hz\n",
1914                 mmc_hostname(host), __func__, host->f_init);
1915 #endif
1916         mmc_power_up(host);
1917
1918         /*
1919          * Some eMMCs (with VCCQ always on) may not be reset after power up, so
1920          * do a hardware reset if possible.
1921          */
1922         mmc_hw_reset_for_init(host);
1923
1924         /* Initialization should be done at 3.3 V I/O voltage. */
1925         mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330, 0);
1926
1927         /*
1928          * sdio_reset sends CMD52 to reset card.  Since we do not know
1929          * if the card is being re-initialized, just send it.  CMD52
1930          * should be ignored by SD/eMMC cards.
1931          */
1932         sdio_reset(host);
1933         mmc_go_idle(host);
1934
1935         mmc_send_if_cond(host, host->ocr_avail);
1936
1937         /* Order's important: probe SDIO, then SD, then MMC */
1938         if (!mmc_attach_sdio(host))
1939                 return 0;
1940         if (!mmc_attach_sd(host))
1941                 return 0;
1942         if (!mmc_attach_mmc(host))
1943                 return 0;
1944
1945         mmc_power_off(host);
1946         return -EIO;
1947 }
1948
1949 int _mmc_detect_card_removed(struct mmc_host *host)
1950 {
1951         int ret;
1952
1953         if ((host->caps & MMC_CAP_NONREMOVABLE) || !host->bus_ops->alive)
1954                 return 0;
1955
1956         if (!host->card || mmc_card_removed(host->card))
1957                 return 1;
1958
1959         ret = host->bus_ops->alive(host);
1960         if (ret) {
1961                 mmc_card_set_removed(host->card);
1962                 pr_debug("%s: card remove detected\n", mmc_hostname(host));
1963         }
1964
1965         return ret;
1966 }
1967
1968 int mmc_detect_card_removed(struct mmc_host *host)
1969 {
1970         struct mmc_card *card = host->card;
1971         int ret;
1972
1973         WARN_ON(!host->claimed);
1974
1975         if (!card)
1976                 return 1;
1977
1978         ret = mmc_card_removed(card);
1979         /*
1980          * The card will be considered unchanged unless we have been asked to
1981          * detect a change or host requires polling to provide card detection.
1982          */
1983         if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL) &&
1984             !(host->caps2 & MMC_CAP2_DETECT_ON_ERR))
1985                 return ret;
1986
1987         host->detect_change = 0;
1988         if (!ret) {
1989                 ret = _mmc_detect_card_removed(host);
1990                 if (ret && (host->caps2 & MMC_CAP2_DETECT_ON_ERR)) {
1991                         /*
1992                          * Schedule a detect work as soon as possible to let a
1993                          * rescan handle the card removal.
1994                          */
1995                         cancel_delayed_work(&host->detect);
1996                         mmc_detect_change(host, 0);
1997                 }
1998         }
1999
2000         return ret;
2001 }
2002 EXPORT_SYMBOL(mmc_detect_card_removed);
2003
2004 void mmc_rescan(struct work_struct *work)
2005 {
2006         static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
2007         struct mmc_host *host =
2008                 container_of(work, struct mmc_host, detect.work);
2009         int i;
2010
2011         if (host->rescan_disable)
2012                 return;
2013
2014         mmc_bus_get(host);
2015
2016         /*
2017          * if there is a _removable_ card registered, check whether it is
2018          * still present
2019          */
2020         if (host->bus_ops && host->bus_ops->detect && !host->bus_dead
2021             && !(host->caps & MMC_CAP_NONREMOVABLE))
2022                 host->bus_ops->detect(host);
2023
2024         host->detect_change = 0;
2025
2026         /*
2027          * Let mmc_bus_put() free the bus/bus_ops if we've found that
2028          * the card is no longer present.
2029          */
2030         mmc_bus_put(host);
2031         mmc_bus_get(host);
2032
2033         /* if there still is a card present, stop here */
2034         if (host->bus_ops != NULL) {
2035                 mmc_bus_put(host);
2036                 goto out;
2037         }
2038
2039         /*
2040          * Only we can add a new handler, so it's safe to
2041          * release the lock here.
2042          */
2043         mmc_bus_put(host);
2044
2045         if (host->ops->get_cd && host->ops->get_cd(host) == 0)
2046                 goto out;
2047
2048         mmc_claim_host(host);
2049         for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2050                 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2051                         break;
2052                 if (freqs[i] <= host->f_min)
2053                         break;
2054         }
2055         mmc_release_host(host);
2056
2057  out:
2058         if (host->caps & MMC_CAP_NEEDS_POLL)
2059                 mmc_schedule_delayed_work(&host->detect, HZ);
2060 }
2061
2062 void mmc_start_host(struct mmc_host *host)
2063 {
2064         mmc_power_off(host);
2065         mmc_detect_change(host, 0);
2066 }
2067
2068 void mmc_stop_host(struct mmc_host *host)
2069 {
2070 #ifdef CONFIG_MMC_DEBUG
2071         unsigned long flags;
2072         spin_lock_irqsave(&host->lock, flags);
2073         host->removed = 1;
2074         spin_unlock_irqrestore(&host->lock, flags);
2075 #endif
2076
2077         cancel_delayed_work_sync(&host->detect);
2078         mmc_flush_scheduled_work();
2079
2080         /* clear pm flags now and let card drivers set them as needed */
2081         host->pm_flags = 0;
2082
2083         mmc_bus_get(host);
2084         if (host->bus_ops && !host->bus_dead) {
2085                 /* Calling bus_ops->remove() with a claimed host can deadlock */
2086                 if (host->bus_ops->remove)
2087                         host->bus_ops->remove(host);
2088
2089                 mmc_claim_host(host);
2090                 mmc_detach_bus(host);
2091                 mmc_power_off(host);
2092                 mmc_release_host(host);
2093                 mmc_bus_put(host);
2094                 return;
2095         }
2096         mmc_bus_put(host);
2097
2098         BUG_ON(host->card);
2099
2100         mmc_power_off(host);
2101 }
2102
2103 int mmc_power_save_host(struct mmc_host *host)
2104 {
2105         int ret = 0;
2106
2107 #ifdef CONFIG_MMC_DEBUG
2108         pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__);
2109 #endif
2110
2111         mmc_bus_get(host);
2112
2113         if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
2114                 mmc_bus_put(host);
2115                 return -EINVAL;
2116         }
2117
2118         if (host->bus_ops->power_save)
2119                 ret = host->bus_ops->power_save(host);
2120
2121         mmc_bus_put(host);
2122
2123         mmc_power_off(host);
2124
2125         return ret;
2126 }
2127 EXPORT_SYMBOL(mmc_power_save_host);
2128
2129 int mmc_power_restore_host(struct mmc_host *host)
2130 {
2131         int ret;
2132
2133 #ifdef CONFIG_MMC_DEBUG
2134         pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__);
2135 #endif
2136
2137         mmc_bus_get(host);
2138
2139         if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
2140                 mmc_bus_put(host);
2141                 return -EINVAL;
2142         }
2143
2144         mmc_power_up(host);
2145         ret = host->bus_ops->power_restore(host);
2146
2147         mmc_bus_put(host);
2148
2149         return ret;
2150 }
2151 EXPORT_SYMBOL(mmc_power_restore_host);
2152
2153 int mmc_card_awake(struct mmc_host *host)
2154 {
2155         int err = -ENOSYS;
2156
2157         if (host->caps2 & MMC_CAP2_NO_SLEEP_CMD)
2158                 return 0;
2159
2160         mmc_bus_get(host);
2161
2162         if (host->bus_ops && !host->bus_dead && host->bus_ops->awake)
2163                 err = host->bus_ops->awake(host);
2164
2165         mmc_bus_put(host);
2166
2167         return err;
2168 }
2169 EXPORT_SYMBOL(mmc_card_awake);
2170
2171 int mmc_card_sleep(struct mmc_host *host)
2172 {
2173         int err = -ENOSYS;
2174
2175         if (host->caps2 & MMC_CAP2_NO_SLEEP_CMD)
2176                 return 0;
2177
2178         mmc_bus_get(host);
2179
2180         if (host->bus_ops && !host->bus_dead && host->bus_ops->sleep)
2181                 err = host->bus_ops->sleep(host);
2182
2183         mmc_bus_put(host);
2184
2185         return err;
2186 }
2187 EXPORT_SYMBOL(mmc_card_sleep);
2188
2189 int mmc_card_can_sleep(struct mmc_host *host)
2190 {
2191         struct mmc_card *card = host->card;
2192
2193         if (card && mmc_card_mmc(card) && card->ext_csd.rev >= 3)
2194                 return 1;
2195         return 0;
2196 }
2197 EXPORT_SYMBOL(mmc_card_can_sleep);
2198
2199 /*
2200  * Flush the cache to the non-volatile storage.
2201  */
2202 int mmc_flush_cache(struct mmc_card *card)
2203 {
2204         struct mmc_host *host = card->host;
2205         int err = 0;
2206
2207         if (!(host->caps2 & MMC_CAP2_CACHE_CTRL))
2208                 return err;
2209
2210         if (mmc_card_mmc(card) &&
2211                         (card->ext_csd.cache_size > 0) &&
2212                         (card->ext_csd.cache_ctrl & 1)) {
2213                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2214                                 EXT_CSD_FLUSH_CACHE, 1, 0);
2215                 if (err)
2216                         pr_err("%s: cache flush error %d\n",
2217                                         mmc_hostname(card->host), err);
2218         }
2219
2220         return err;
2221 }
2222 EXPORT_SYMBOL(mmc_flush_cache);
2223
2224 /*
2225  * Turn the cache ON/OFF.
2226  * Turning the cache OFF shall trigger flushing of the data
2227  * to the non-volatile storage.
2228  */
2229 int mmc_cache_ctrl(struct mmc_host *host, u8 enable)
2230 {
2231         struct mmc_card *card = host->card;
2232         unsigned int timeout;
2233         int err = 0;
2234
2235         if (!(host->caps2 & MMC_CAP2_CACHE_CTRL) ||
2236                         mmc_card_is_removable(host))
2237                 return err;
2238
2239         if (card && mmc_card_mmc(card) &&
2240                         (card->ext_csd.cache_size > 0)) {
2241                 enable = !!enable;
2242
2243                 if (card->ext_csd.cache_ctrl ^ enable) {
2244                         timeout = enable ? card->ext_csd.generic_cmd6_time : 0;
2245                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2246                                         EXT_CSD_CACHE_CTRL, enable, timeout);
2247                         if (err)
2248                                 pr_err("%s: cache %s error %d\n",
2249                                                 mmc_hostname(card->host),
2250                                                 enable ? "on" : "off",
2251                                                 err);
2252                         else
2253                                 card->ext_csd.cache_ctrl = enable;
2254                 }
2255         }
2256
2257         return err;
2258 }
2259 EXPORT_SYMBOL(mmc_cache_ctrl);
2260
2261 #ifdef CONFIG_PM
2262
2263 /**
2264  *      mmc_suspend_host - suspend a host
2265  *      @host: mmc host
2266  */
2267 int mmc_suspend_host(struct mmc_host *host)
2268 {
2269         int err = 0;
2270
2271         cancel_delayed_work(&host->detect);
2272         mmc_flush_scheduled_work();
2273         if (mmc_try_claim_host(host)) {
2274                 err = mmc_cache_ctrl(host, 0);
2275                 mmc_release_host(host);
2276         } else {
2277                 err = -EBUSY;
2278         }
2279
2280         if (err)
2281                 goto out;
2282
2283         mmc_bus_get(host);
2284         if (host->bus_ops && !host->bus_dead) {
2285
2286                 /*
2287                  * A long response time is not acceptable for device drivers
2288                  * when doing suspend. Prevent mmc_claim_host in the suspend
2289                  * sequence, to potentially wait "forever" by trying to
2290                  * pre-claim the host.
2291                  */
2292                 if (mmc_try_claim_host(host)) {
2293                         if (host->bus_ops->suspend) {
2294                                 err = host->bus_ops->suspend(host);
2295                         }
2296                         mmc_release_host(host);
2297
2298                         if (err == -ENOSYS || !host->bus_ops->resume) {
2299                                 /*
2300                                  * We simply "remove" the card in this case.
2301                                  * It will be redetected on resume.  (Calling
2302                                  * bus_ops->remove() with a claimed host can
2303                                  * deadlock.)
2304                                  */
2305                                 if (host->bus_ops->remove)
2306                                         host->bus_ops->remove(host);
2307                                 mmc_claim_host(host);
2308                                 mmc_detach_bus(host);
2309                                 mmc_power_off(host);
2310                                 mmc_release_host(host);
2311                                 host->pm_flags = 0;
2312                                 err = 0;
2313                         }
2314                 } else {
2315                         err = -EBUSY;
2316                 }
2317         }
2318         mmc_bus_put(host);
2319
2320         if (!err && !mmc_card_keep_power(host))
2321                 mmc_power_off(host);
2322
2323 out:
2324         return err;
2325 }
2326
2327 EXPORT_SYMBOL(mmc_suspend_host);
2328
2329 /**
2330  *      mmc_resume_host - resume a previously suspended host
2331  *      @host: mmc host
2332  */
2333 int mmc_resume_host(struct mmc_host *host)
2334 {
2335         int err = 0;
2336
2337         mmc_bus_get(host);
2338         if (host->bus_ops && !host->bus_dead) {
2339                 if (!mmc_card_keep_power(host)) {
2340                         mmc_power_up(host);
2341                         mmc_select_voltage(host, host->ocr);
2342                         /*
2343                          * Tell runtime PM core we just powered up the card,
2344                          * since it still believes the card is powered off.
2345                          * Note that currently runtime PM is only enabled
2346                          * for SDIO cards that are MMC_CAP_POWER_OFF_CARD
2347                          */
2348                         if (mmc_card_sdio(host->card) &&
2349                             (host->caps & MMC_CAP_POWER_OFF_CARD)) {
2350                                 pm_runtime_disable(&host->card->dev);
2351                                 pm_runtime_set_active(&host->card->dev);
2352                                 pm_runtime_enable(&host->card->dev);
2353                         }
2354                 }
2355                 BUG_ON(!host->bus_ops->resume);
2356                 err = host->bus_ops->resume(host);
2357                 if (err) {
2358                         pr_warning("%s: error %d during resume "
2359                                             "(card was removed?)\n",
2360                                             mmc_hostname(host), err);
2361                         err = 0;
2362                 }
2363         }
2364         host->pm_flags &= ~MMC_PM_KEEP_POWER;
2365         mmc_bus_put(host);
2366
2367         return err;
2368 }
2369 EXPORT_SYMBOL(mmc_resume_host);
2370
2371 /* Do the card removal on suspend if card is assumed removeable
2372  * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2373    to sync the card.
2374 */
2375 int mmc_pm_notify(struct notifier_block *notify_block,
2376                                         unsigned long mode, void *unused)
2377 {
2378         struct mmc_host *host = container_of(
2379                 notify_block, struct mmc_host, pm_notify);
2380         unsigned long flags;
2381
2382
2383         switch (mode) {
2384         case PM_HIBERNATION_PREPARE:
2385         case PM_SUSPEND_PREPARE:
2386
2387                 spin_lock_irqsave(&host->lock, flags);
2388                 host->rescan_disable = 1;
2389                 host->power_notify_type = MMC_HOST_PW_NOTIFY_SHORT;
2390                 spin_unlock_irqrestore(&host->lock, flags);
2391                 cancel_delayed_work_sync(&host->detect);
2392
2393                 if (!host->bus_ops || host->bus_ops->suspend)
2394                         break;
2395
2396                 /* Calling bus_ops->remove() with a claimed host can deadlock */
2397                 if (host->bus_ops->remove)
2398                         host->bus_ops->remove(host);
2399
2400                 mmc_claim_host(host);
2401                 mmc_detach_bus(host);
2402                 mmc_power_off(host);
2403                 mmc_release_host(host);
2404                 host->pm_flags = 0;
2405                 break;
2406
2407         case PM_POST_SUSPEND:
2408         case PM_POST_HIBERNATION:
2409         case PM_POST_RESTORE:
2410
2411                 spin_lock_irqsave(&host->lock, flags);
2412                 host->rescan_disable = 0;
2413                 host->power_notify_type = MMC_HOST_PW_NOTIFY_LONG;
2414                 spin_unlock_irqrestore(&host->lock, flags);
2415                 mmc_detect_change(host, 0);
2416
2417         }
2418
2419         return 0;
2420 }
2421 #endif
2422
2423 static int __init mmc_init(void)
2424 {
2425         int ret;
2426
2427         workqueue = alloc_ordered_workqueue("kmmcd", 0);
2428         if (!workqueue)
2429                 return -ENOMEM;
2430
2431         ret = mmc_register_bus();
2432         if (ret)
2433                 goto destroy_workqueue;
2434
2435         ret = mmc_register_host_class();
2436         if (ret)
2437                 goto unregister_bus;
2438
2439         ret = sdio_register_bus();
2440         if (ret)
2441                 goto unregister_host_class;
2442
2443         return 0;
2444
2445 unregister_host_class:
2446         mmc_unregister_host_class();
2447 unregister_bus:
2448         mmc_unregister_bus();
2449 destroy_workqueue:
2450         destroy_workqueue(workqueue);
2451
2452         return ret;
2453 }
2454
2455 static void __exit mmc_exit(void)
2456 {
2457         sdio_unregister_bus();
2458         mmc_unregister_host_class();
2459         mmc_unregister_bus();
2460         destroy_workqueue(workqueue);
2461 }
2462
2463 subsys_initcall(mmc_init);
2464 module_exit(mmc_exit);
2465
2466 MODULE_LICENSE("GPL");