mmc: core: add a debug message for SET_BLOCK_COUNT
[platform/kernel/linux-starfive.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_host_enable - enable a host.
609  *      @host: mmc host to enable
610  *
611  *      Hosts that support power saving can use the 'enable' and 'disable'
612  *      methods to exit and enter power saving states. For more information
613  *      see comments for struct mmc_host_ops.
614  */
615 int mmc_host_enable(struct mmc_host *host)
616 {
617         if (!(host->caps & MMC_CAP_DISABLE))
618                 return 0;
619
620         if (host->en_dis_recurs)
621                 return 0;
622
623         if (host->nesting_cnt++)
624                 return 0;
625
626         cancel_delayed_work_sync(&host->disable);
627
628         if (host->enabled)
629                 return 0;
630
631         if (host->ops->enable) {
632                 int err;
633
634                 host->en_dis_recurs = 1;
635                 mmc_host_clk_hold(host);
636                 err = host->ops->enable(host);
637                 mmc_host_clk_release(host);
638                 host->en_dis_recurs = 0;
639
640                 if (err) {
641                         pr_debug("%s: enable error %d\n",
642                                  mmc_hostname(host), err);
643                         return err;
644                 }
645         }
646         host->enabled = 1;
647         return 0;
648 }
649 EXPORT_SYMBOL(mmc_host_enable);
650
651 static int mmc_host_do_disable(struct mmc_host *host, int lazy)
652 {
653         if (host->ops->disable) {
654                 int err;
655
656                 host->en_dis_recurs = 1;
657                 mmc_host_clk_hold(host);
658                 err = host->ops->disable(host, lazy);
659                 mmc_host_clk_release(host);
660                 host->en_dis_recurs = 0;
661
662                 if (err < 0) {
663                         pr_debug("%s: disable error %d\n",
664                                  mmc_hostname(host), err);
665                         return err;
666                 }
667                 if (err > 0) {
668                         unsigned long delay = msecs_to_jiffies(err);
669
670                         mmc_schedule_delayed_work(&host->disable, delay);
671                 }
672         }
673         host->enabled = 0;
674         return 0;
675 }
676
677 /**
678  *      mmc_host_disable - disable a host.
679  *      @host: mmc host to disable
680  *
681  *      Hosts that support power saving can use the 'enable' and 'disable'
682  *      methods to exit and enter power saving states. For more information
683  *      see comments for struct mmc_host_ops.
684  */
685 int mmc_host_disable(struct mmc_host *host)
686 {
687         int err;
688
689         if (!(host->caps & MMC_CAP_DISABLE))
690                 return 0;
691
692         if (host->en_dis_recurs)
693                 return 0;
694
695         if (--host->nesting_cnt)
696                 return 0;
697
698         if (!host->enabled)
699                 return 0;
700
701         err = mmc_host_do_disable(host, 0);
702         return err;
703 }
704 EXPORT_SYMBOL(mmc_host_disable);
705
706 /**
707  *      __mmc_claim_host - exclusively claim a host
708  *      @host: mmc host to claim
709  *      @abort: whether or not the operation should be aborted
710  *
711  *      Claim a host for a set of operations.  If @abort is non null and
712  *      dereference a non-zero value then this will return prematurely with
713  *      that non-zero value without acquiring the lock.  Returns zero
714  *      with the lock held otherwise.
715  */
716 int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
717 {
718         DECLARE_WAITQUEUE(wait, current);
719         unsigned long flags;
720         int stop;
721
722         might_sleep();
723
724         add_wait_queue(&host->wq, &wait);
725         spin_lock_irqsave(&host->lock, flags);
726         while (1) {
727                 set_current_state(TASK_UNINTERRUPTIBLE);
728                 stop = abort ? atomic_read(abort) : 0;
729                 if (stop || !host->claimed || host->claimer == current)
730                         break;
731                 spin_unlock_irqrestore(&host->lock, flags);
732                 schedule();
733                 spin_lock_irqsave(&host->lock, flags);
734         }
735         set_current_state(TASK_RUNNING);
736         if (!stop) {
737                 host->claimed = 1;
738                 host->claimer = current;
739                 host->claim_cnt += 1;
740         } else
741                 wake_up(&host->wq);
742         spin_unlock_irqrestore(&host->lock, flags);
743         remove_wait_queue(&host->wq, &wait);
744         if (!stop)
745                 mmc_host_enable(host);
746         return stop;
747 }
748
749 EXPORT_SYMBOL(__mmc_claim_host);
750
751 /**
752  *      mmc_try_claim_host - try exclusively to claim a host
753  *      @host: mmc host to claim
754  *
755  *      Returns %1 if the host is claimed, %0 otherwise.
756  */
757 int mmc_try_claim_host(struct mmc_host *host)
758 {
759         int claimed_host = 0;
760         unsigned long flags;
761
762         spin_lock_irqsave(&host->lock, flags);
763         if (!host->claimed || host->claimer == current) {
764                 host->claimed = 1;
765                 host->claimer = current;
766                 host->claim_cnt += 1;
767                 claimed_host = 1;
768         }
769         spin_unlock_irqrestore(&host->lock, flags);
770         return claimed_host;
771 }
772 EXPORT_SYMBOL(mmc_try_claim_host);
773
774 /**
775  *      mmc_do_release_host - release a claimed host
776  *      @host: mmc host to release
777  *
778  *      If you successfully claimed a host, this function will
779  *      release it again.
780  */
781 void mmc_do_release_host(struct mmc_host *host)
782 {
783         unsigned long flags;
784
785         spin_lock_irqsave(&host->lock, flags);
786         if (--host->claim_cnt) {
787                 /* Release for nested claim */
788                 spin_unlock_irqrestore(&host->lock, flags);
789         } else {
790                 host->claimed = 0;
791                 host->claimer = NULL;
792                 spin_unlock_irqrestore(&host->lock, flags);
793                 wake_up(&host->wq);
794         }
795 }
796 EXPORT_SYMBOL(mmc_do_release_host);
797
798 void mmc_host_deeper_disable(struct work_struct *work)
799 {
800         struct mmc_host *host =
801                 container_of(work, struct mmc_host, disable.work);
802
803         /* If the host is claimed then we do not want to disable it anymore */
804         if (!mmc_try_claim_host(host))
805                 return;
806         mmc_host_do_disable(host, 1);
807         mmc_do_release_host(host);
808 }
809
810 /**
811  *      mmc_host_lazy_disable - lazily disable a host.
812  *      @host: mmc host to disable
813  *
814  *      Hosts that support power saving can use the 'enable' and 'disable'
815  *      methods to exit and enter power saving states. For more information
816  *      see comments for struct mmc_host_ops.
817  */
818 int mmc_host_lazy_disable(struct mmc_host *host)
819 {
820         if (!(host->caps & MMC_CAP_DISABLE))
821                 return 0;
822
823         if (host->en_dis_recurs)
824                 return 0;
825
826         if (--host->nesting_cnt)
827                 return 0;
828
829         if (!host->enabled)
830                 return 0;
831
832         if (host->disable_delay) {
833                 mmc_schedule_delayed_work(&host->disable,
834                                 msecs_to_jiffies(host->disable_delay));
835                 return 0;
836         } else
837                 return mmc_host_do_disable(host, 1);
838 }
839 EXPORT_SYMBOL(mmc_host_lazy_disable);
840
841 /**
842  *      mmc_release_host - release a host
843  *      @host: mmc host to release
844  *
845  *      Release a MMC host, allowing others to claim the host
846  *      for their operations.
847  */
848 void mmc_release_host(struct mmc_host *host)
849 {
850         WARN_ON(!host->claimed);
851
852         mmc_host_lazy_disable(host);
853
854         mmc_do_release_host(host);
855 }
856
857 EXPORT_SYMBOL(mmc_release_host);
858
859 /*
860  * Internal function that does the actual ios call to the host driver,
861  * optionally printing some debug output.
862  */
863 static inline void mmc_set_ios(struct mmc_host *host)
864 {
865         struct mmc_ios *ios = &host->ios;
866
867         pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
868                 "width %u timing %u\n",
869                  mmc_hostname(host), ios->clock, ios->bus_mode,
870                  ios->power_mode, ios->chip_select, ios->vdd,
871                  ios->bus_width, ios->timing);
872
873         if (ios->clock > 0)
874                 mmc_set_ungated(host);
875         host->ops->set_ios(host, ios);
876 }
877
878 /*
879  * Control chip select pin on a host.
880  */
881 void mmc_set_chip_select(struct mmc_host *host, int mode)
882 {
883         mmc_host_clk_hold(host);
884         host->ios.chip_select = mode;
885         mmc_set_ios(host);
886         mmc_host_clk_release(host);
887 }
888
889 /*
890  * Sets the host clock to the highest possible frequency that
891  * is below "hz".
892  */
893 static void __mmc_set_clock(struct mmc_host *host, unsigned int hz)
894 {
895         WARN_ON(hz < host->f_min);
896
897         if (hz > host->f_max)
898                 hz = host->f_max;
899
900         host->ios.clock = hz;
901         mmc_set_ios(host);
902 }
903
904 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
905 {
906         mmc_host_clk_hold(host);
907         __mmc_set_clock(host, hz);
908         mmc_host_clk_release(host);
909 }
910
911 #ifdef CONFIG_MMC_CLKGATE
912 /*
913  * This gates the clock by setting it to 0 Hz.
914  */
915 void mmc_gate_clock(struct mmc_host *host)
916 {
917         unsigned long flags;
918
919         spin_lock_irqsave(&host->clk_lock, flags);
920         host->clk_old = host->ios.clock;
921         host->ios.clock = 0;
922         host->clk_gated = true;
923         spin_unlock_irqrestore(&host->clk_lock, flags);
924         mmc_set_ios(host);
925 }
926
927 /*
928  * This restores the clock from gating by using the cached
929  * clock value.
930  */
931 void mmc_ungate_clock(struct mmc_host *host)
932 {
933         /*
934          * We should previously have gated the clock, so the clock shall
935          * be 0 here! The clock may however be 0 during initialization,
936          * when some request operations are performed before setting
937          * the frequency. When ungate is requested in that situation
938          * we just ignore the call.
939          */
940         if (host->clk_old) {
941                 BUG_ON(host->ios.clock);
942                 /* This call will also set host->clk_gated to false */
943                 __mmc_set_clock(host, host->clk_old);
944         }
945 }
946
947 void mmc_set_ungated(struct mmc_host *host)
948 {
949         unsigned long flags;
950
951         /*
952          * We've been given a new frequency while the clock is gated,
953          * so make sure we regard this as ungating it.
954          */
955         spin_lock_irqsave(&host->clk_lock, flags);
956         host->clk_gated = false;
957         spin_unlock_irqrestore(&host->clk_lock, flags);
958 }
959
960 #else
961 void mmc_set_ungated(struct mmc_host *host)
962 {
963 }
964 #endif
965
966 /*
967  * Change the bus mode (open drain/push-pull) of a host.
968  */
969 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
970 {
971         mmc_host_clk_hold(host);
972         host->ios.bus_mode = mode;
973         mmc_set_ios(host);
974         mmc_host_clk_release(host);
975 }
976
977 /*
978  * Change data bus width of a host.
979  */
980 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
981 {
982         mmc_host_clk_hold(host);
983         host->ios.bus_width = width;
984         mmc_set_ios(host);
985         mmc_host_clk_release(host);
986 }
987
988 /**
989  * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
990  * @vdd:        voltage (mV)
991  * @low_bits:   prefer low bits in boundary cases
992  *
993  * This function returns the OCR bit number according to the provided @vdd
994  * value. If conversion is not possible a negative errno value returned.
995  *
996  * Depending on the @low_bits flag the function prefers low or high OCR bits
997  * on boundary voltages. For example,
998  * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
999  * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1000  *
1001  * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1002  */
1003 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1004 {
1005         const int max_bit = ilog2(MMC_VDD_35_36);
1006         int bit;
1007
1008         if (vdd < 1650 || vdd > 3600)
1009                 return -EINVAL;
1010
1011         if (vdd >= 1650 && vdd <= 1950)
1012                 return ilog2(MMC_VDD_165_195);
1013
1014         if (low_bits)
1015                 vdd -= 1;
1016
1017         /* Base 2000 mV, step 100 mV, bit's base 8. */
1018         bit = (vdd - 2000) / 100 + 8;
1019         if (bit > max_bit)
1020                 return max_bit;
1021         return bit;
1022 }
1023
1024 /**
1025  * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1026  * @vdd_min:    minimum voltage value (mV)
1027  * @vdd_max:    maximum voltage value (mV)
1028  *
1029  * This function returns the OCR mask bits according to the provided @vdd_min
1030  * and @vdd_max values. If conversion is not possible the function returns 0.
1031  *
1032  * Notes wrt boundary cases:
1033  * This function sets the OCR bits for all boundary voltages, for example
1034  * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1035  * MMC_VDD_34_35 mask.
1036  */
1037 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1038 {
1039         u32 mask = 0;
1040
1041         if (vdd_max < vdd_min)
1042                 return 0;
1043
1044         /* Prefer high bits for the boundary vdd_max values. */
1045         vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1046         if (vdd_max < 0)
1047                 return 0;
1048
1049         /* Prefer low bits for the boundary vdd_min values. */
1050         vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1051         if (vdd_min < 0)
1052                 return 0;
1053
1054         /* Fill the mask, from max bit to min bit. */
1055         while (vdd_max >= vdd_min)
1056                 mask |= 1 << vdd_max--;
1057
1058         return mask;
1059 }
1060 EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
1061
1062 #ifdef CONFIG_REGULATOR
1063
1064 /**
1065  * mmc_regulator_get_ocrmask - return mask of supported voltages
1066  * @supply: regulator to use
1067  *
1068  * This returns either a negative errno, or a mask of voltages that
1069  * can be provided to MMC/SD/SDIO devices using the specified voltage
1070  * regulator.  This would normally be called before registering the
1071  * MMC host adapter.
1072  */
1073 int mmc_regulator_get_ocrmask(struct regulator *supply)
1074 {
1075         int                     result = 0;
1076         int                     count;
1077         int                     i;
1078
1079         count = regulator_count_voltages(supply);
1080         if (count < 0)
1081                 return count;
1082
1083         for (i = 0; i < count; i++) {
1084                 int             vdd_uV;
1085                 int             vdd_mV;
1086
1087                 vdd_uV = regulator_list_voltage(supply, i);
1088                 if (vdd_uV <= 0)
1089                         continue;
1090
1091                 vdd_mV = vdd_uV / 1000;
1092                 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1093         }
1094
1095         return result;
1096 }
1097 EXPORT_SYMBOL(mmc_regulator_get_ocrmask);
1098
1099 /**
1100  * mmc_regulator_set_ocr - set regulator to match host->ios voltage
1101  * @mmc: the host to regulate
1102  * @supply: regulator to use
1103  * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
1104  *
1105  * Returns zero on success, else negative errno.
1106  *
1107  * MMC host drivers may use this to enable or disable a regulator using
1108  * a particular supply voltage.  This would normally be called from the
1109  * set_ios() method.
1110  */
1111 int mmc_regulator_set_ocr(struct mmc_host *mmc,
1112                         struct regulator *supply,
1113                         unsigned short vdd_bit)
1114 {
1115         int                     result = 0;
1116         int                     min_uV, max_uV;
1117
1118         if (vdd_bit) {
1119                 int             tmp;
1120                 int             voltage;
1121
1122                 /* REVISIT mmc_vddrange_to_ocrmask() may have set some
1123                  * bits this regulator doesn't quite support ... don't
1124                  * be too picky, most cards and regulators are OK with
1125                  * a 0.1V range goof (it's a small error percentage).
1126                  */
1127                 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
1128                 if (tmp == 0) {
1129                         min_uV = 1650 * 1000;
1130                         max_uV = 1950 * 1000;
1131                 } else {
1132                         min_uV = 1900 * 1000 + tmp * 100 * 1000;
1133                         max_uV = min_uV + 100 * 1000;
1134                 }
1135
1136                 /* avoid needless changes to this voltage; the regulator
1137                  * might not allow this operation
1138                  */
1139                 voltage = regulator_get_voltage(supply);
1140
1141                 if (mmc->caps2 & MMC_CAP2_BROKEN_VOLTAGE)
1142                         min_uV = max_uV = voltage;
1143
1144                 if (voltage < 0)
1145                         result = voltage;
1146                 else if (voltage < min_uV || voltage > max_uV)
1147                         result = regulator_set_voltage(supply, min_uV, max_uV);
1148                 else
1149                         result = 0;
1150
1151                 if (result == 0 && !mmc->regulator_enabled) {
1152                         result = regulator_enable(supply);
1153                         if (!result)
1154                                 mmc->regulator_enabled = true;
1155                 }
1156         } else if (mmc->regulator_enabled) {
1157                 result = regulator_disable(supply);
1158                 if (result == 0)
1159                         mmc->regulator_enabled = false;
1160         }
1161
1162         if (result)
1163                 dev_err(mmc_dev(mmc),
1164                         "could not set regulator OCR (%d)\n", result);
1165         return result;
1166 }
1167 EXPORT_SYMBOL(mmc_regulator_set_ocr);
1168
1169 #endif /* CONFIG_REGULATOR */
1170
1171 /*
1172  * Mask off any voltages we don't support and select
1173  * the lowest voltage
1174  */
1175 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1176 {
1177         int bit;
1178
1179         ocr &= host->ocr_avail;
1180
1181         bit = ffs(ocr);
1182         if (bit) {
1183                 bit -= 1;
1184
1185                 ocr &= 3 << bit;
1186
1187                 mmc_host_clk_hold(host);
1188                 host->ios.vdd = bit;
1189                 mmc_set_ios(host);
1190                 mmc_host_clk_release(host);
1191         } else {
1192                 pr_warning("%s: host doesn't support card's voltages\n",
1193                                 mmc_hostname(host));
1194                 ocr = 0;
1195         }
1196
1197         return ocr;
1198 }
1199
1200 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, bool cmd11)
1201 {
1202         struct mmc_command cmd = {0};
1203         int err = 0;
1204
1205         BUG_ON(!host);
1206
1207         /*
1208          * Send CMD11 only if the request is to switch the card to
1209          * 1.8V signalling.
1210          */
1211         if ((signal_voltage != MMC_SIGNAL_VOLTAGE_330) && cmd11) {
1212                 cmd.opcode = SD_SWITCH_VOLTAGE;
1213                 cmd.arg = 0;
1214                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1215
1216                 err = mmc_wait_for_cmd(host, &cmd, 0);
1217                 if (err)
1218                         return err;
1219
1220                 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1221                         return -EIO;
1222         }
1223
1224         host->ios.signal_voltage = signal_voltage;
1225
1226         if (host->ops->start_signal_voltage_switch) {
1227                 mmc_host_clk_hold(host);
1228                 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1229                 mmc_host_clk_release(host);
1230         }
1231
1232         return err;
1233 }
1234
1235 /*
1236  * Select timing parameters for host.
1237  */
1238 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1239 {
1240         mmc_host_clk_hold(host);
1241         host->ios.timing = timing;
1242         mmc_set_ios(host);
1243         mmc_host_clk_release(host);
1244 }
1245
1246 /*
1247  * Select appropriate driver type for host.
1248  */
1249 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1250 {
1251         mmc_host_clk_hold(host);
1252         host->ios.drv_type = drv_type;
1253         mmc_set_ios(host);
1254         mmc_host_clk_release(host);
1255 }
1256
1257 static void mmc_poweroff_notify(struct mmc_host *host)
1258 {
1259         struct mmc_card *card;
1260         unsigned int timeout;
1261         unsigned int notify_type = EXT_CSD_NO_POWER_NOTIFICATION;
1262         int err = 0;
1263
1264         card = host->card;
1265         mmc_claim_host(host);
1266
1267         /*
1268          * Send power notify command only if card
1269          * is mmc and notify state is powered ON
1270          */
1271         if (card && mmc_card_mmc(card) &&
1272             (card->poweroff_notify_state == MMC_POWERED_ON)) {
1273
1274                 if (host->power_notify_type == MMC_HOST_PW_NOTIFY_SHORT) {
1275                         notify_type = EXT_CSD_POWER_OFF_SHORT;
1276                         timeout = card->ext_csd.generic_cmd6_time;
1277                         card->poweroff_notify_state = MMC_POWEROFF_SHORT;
1278                 } else {
1279                         notify_type = EXT_CSD_POWER_OFF_LONG;
1280                         timeout = card->ext_csd.power_off_longtime;
1281                         card->poweroff_notify_state = MMC_POWEROFF_LONG;
1282                 }
1283
1284                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1285                                  EXT_CSD_POWER_OFF_NOTIFICATION,
1286                                  notify_type, timeout);
1287
1288                 if (err && err != -EBADMSG)
1289                         pr_err("Device failed to respond within %d poweroff "
1290                                "time. Forcefully powering down the device\n",
1291                                timeout);
1292
1293                 /* Set the card state to no notification after the poweroff */
1294                 card->poweroff_notify_state = MMC_NO_POWER_NOTIFICATION;
1295         }
1296         mmc_release_host(host);
1297 }
1298
1299 /*
1300  * Apply power to the MMC stack.  This is a two-stage process.
1301  * First, we enable power to the card without the clock running.
1302  * We then wait a bit for the power to stabilise.  Finally,
1303  * enable the bus drivers and clock to the card.
1304  *
1305  * We must _NOT_ enable the clock prior to power stablising.
1306  *
1307  * If a host does all the power sequencing itself, ignore the
1308  * initial MMC_POWER_UP stage.
1309  */
1310 static void mmc_power_up(struct mmc_host *host)
1311 {
1312         int bit;
1313
1314         mmc_host_clk_hold(host);
1315
1316         /* If ocr is set, we use it */
1317         if (host->ocr)
1318                 bit = ffs(host->ocr) - 1;
1319         else
1320                 bit = fls(host->ocr_avail) - 1;
1321
1322         host->ios.vdd = bit;
1323         if (mmc_host_is_spi(host))
1324                 host->ios.chip_select = MMC_CS_HIGH;
1325         else
1326                 host->ios.chip_select = MMC_CS_DONTCARE;
1327         host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1328         host->ios.power_mode = MMC_POWER_UP;
1329         host->ios.bus_width = MMC_BUS_WIDTH_1;
1330         host->ios.timing = MMC_TIMING_LEGACY;
1331         mmc_set_ios(host);
1332
1333         /*
1334          * This delay should be sufficient to allow the power supply
1335          * to reach the minimum voltage.
1336          */
1337         mmc_delay(10);
1338
1339         host->ios.clock = host->f_init;
1340
1341         host->ios.power_mode = MMC_POWER_ON;
1342         mmc_set_ios(host);
1343
1344         /*
1345          * This delay must be at least 74 clock sizes, or 1 ms, or the
1346          * time required to reach a stable voltage.
1347          */
1348         mmc_delay(10);
1349
1350         mmc_host_clk_release(host);
1351 }
1352
1353 void mmc_power_off(struct mmc_host *host)
1354 {
1355         int err = 0;
1356         mmc_host_clk_hold(host);
1357
1358         host->ios.clock = 0;
1359         host->ios.vdd = 0;
1360
1361         /*
1362          * For eMMC 4.5 device send AWAKE command before
1363          * POWER_OFF_NOTIFY command, because in sleep state
1364          * eMMC 4.5 devices respond to only RESET and AWAKE cmd
1365          */
1366         if (host->card && mmc_card_is_sleep(host->card) &&
1367             host->bus_ops->resume) {
1368                 err = host->bus_ops->resume(host);
1369
1370                 if (!err)
1371                         mmc_poweroff_notify(host);
1372                 else
1373                         pr_warning("%s: error %d during resume "
1374                                    "(continue with poweroff sequence)\n",
1375                                    mmc_hostname(host), err);
1376         }
1377
1378         /*
1379          * Reset ocr mask to be the highest possible voltage supported for
1380          * this mmc host. This value will be used at next power up.
1381          */
1382         host->ocr = 1 << (fls(host->ocr_avail) - 1);
1383
1384         if (!mmc_host_is_spi(host)) {
1385                 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
1386                 host->ios.chip_select = MMC_CS_DONTCARE;
1387         }
1388         host->ios.power_mode = MMC_POWER_OFF;
1389         host->ios.bus_width = MMC_BUS_WIDTH_1;
1390         host->ios.timing = MMC_TIMING_LEGACY;
1391         mmc_set_ios(host);
1392
1393         /*
1394          * Some configurations, such as the 802.11 SDIO card in the OLPC
1395          * XO-1.5, require a short delay after poweroff before the card
1396          * can be successfully turned on again.
1397          */
1398         mmc_delay(1);
1399
1400         mmc_host_clk_release(host);
1401 }
1402
1403 /*
1404  * Cleanup when the last reference to the bus operator is dropped.
1405  */
1406 static void __mmc_release_bus(struct mmc_host *host)
1407 {
1408         BUG_ON(!host);
1409         BUG_ON(host->bus_refs);
1410         BUG_ON(!host->bus_dead);
1411
1412         host->bus_ops = NULL;
1413 }
1414
1415 /*
1416  * Increase reference count of bus operator
1417  */
1418 static inline void mmc_bus_get(struct mmc_host *host)
1419 {
1420         unsigned long flags;
1421
1422         spin_lock_irqsave(&host->lock, flags);
1423         host->bus_refs++;
1424         spin_unlock_irqrestore(&host->lock, flags);
1425 }
1426
1427 /*
1428  * Decrease reference count of bus operator and free it if
1429  * it is the last reference.
1430  */
1431 static inline void mmc_bus_put(struct mmc_host *host)
1432 {
1433         unsigned long flags;
1434
1435         spin_lock_irqsave(&host->lock, flags);
1436         host->bus_refs--;
1437         if ((host->bus_refs == 0) && host->bus_ops)
1438                 __mmc_release_bus(host);
1439         spin_unlock_irqrestore(&host->lock, flags);
1440 }
1441
1442 /*
1443  * Assign a mmc bus handler to a host. Only one bus handler may control a
1444  * host at any given time.
1445  */
1446 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1447 {
1448         unsigned long flags;
1449
1450         BUG_ON(!host);
1451         BUG_ON(!ops);
1452
1453         WARN_ON(!host->claimed);
1454
1455         spin_lock_irqsave(&host->lock, flags);
1456
1457         BUG_ON(host->bus_ops);
1458         BUG_ON(host->bus_refs);
1459
1460         host->bus_ops = ops;
1461         host->bus_refs = 1;
1462         host->bus_dead = 0;
1463
1464         spin_unlock_irqrestore(&host->lock, flags);
1465 }
1466
1467 /*
1468  * Remove the current bus handler from a host.
1469  */
1470 void mmc_detach_bus(struct mmc_host *host)
1471 {
1472         unsigned long flags;
1473
1474         BUG_ON(!host);
1475
1476         WARN_ON(!host->claimed);
1477         WARN_ON(!host->bus_ops);
1478
1479         spin_lock_irqsave(&host->lock, flags);
1480
1481         host->bus_dead = 1;
1482
1483         spin_unlock_irqrestore(&host->lock, flags);
1484
1485         mmc_bus_put(host);
1486 }
1487
1488 /**
1489  *      mmc_detect_change - process change of state on a MMC socket
1490  *      @host: host which changed state.
1491  *      @delay: optional delay to wait before detection (jiffies)
1492  *
1493  *      MMC drivers should call this when they detect a card has been
1494  *      inserted or removed. The MMC layer will confirm that any
1495  *      present card is still functional, and initialize any newly
1496  *      inserted.
1497  */
1498 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1499 {
1500 #ifdef CONFIG_MMC_DEBUG
1501         unsigned long flags;
1502         spin_lock_irqsave(&host->lock, flags);
1503         WARN_ON(host->removed);
1504         spin_unlock_irqrestore(&host->lock, flags);
1505 #endif
1506         host->detect_change = 1;
1507         mmc_schedule_delayed_work(&host->detect, delay);
1508 }
1509
1510 EXPORT_SYMBOL(mmc_detect_change);
1511
1512 void mmc_init_erase(struct mmc_card *card)
1513 {
1514         unsigned int sz;
1515
1516         if (is_power_of_2(card->erase_size))
1517                 card->erase_shift = ffs(card->erase_size) - 1;
1518         else
1519                 card->erase_shift = 0;
1520
1521         /*
1522          * It is possible to erase an arbitrarily large area of an SD or MMC
1523          * card.  That is not desirable because it can take a long time
1524          * (minutes) potentially delaying more important I/O, and also the
1525          * timeout calculations become increasingly hugely over-estimated.
1526          * Consequently, 'pref_erase' is defined as a guide to limit erases
1527          * to that size and alignment.
1528          *
1529          * For SD cards that define Allocation Unit size, limit erases to one
1530          * Allocation Unit at a time.  For MMC cards that define High Capacity
1531          * Erase Size, whether it is switched on or not, limit to that size.
1532          * Otherwise just have a stab at a good value.  For modern cards it
1533          * will end up being 4MiB.  Note that if the value is too small, it
1534          * can end up taking longer to erase.
1535          */
1536         if (mmc_card_sd(card) && card->ssr.au) {
1537                 card->pref_erase = card->ssr.au;
1538                 card->erase_shift = ffs(card->ssr.au) - 1;
1539         } else if (card->ext_csd.hc_erase_size) {
1540                 card->pref_erase = card->ext_csd.hc_erase_size;
1541         } else {
1542                 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1543                 if (sz < 128)
1544                         card->pref_erase = 512 * 1024 / 512;
1545                 else if (sz < 512)
1546                         card->pref_erase = 1024 * 1024 / 512;
1547                 else if (sz < 1024)
1548                         card->pref_erase = 2 * 1024 * 1024 / 512;
1549                 else
1550                         card->pref_erase = 4 * 1024 * 1024 / 512;
1551                 if (card->pref_erase < card->erase_size)
1552                         card->pref_erase = card->erase_size;
1553                 else {
1554                         sz = card->pref_erase % card->erase_size;
1555                         if (sz)
1556                                 card->pref_erase += card->erase_size - sz;
1557                 }
1558         }
1559 }
1560
1561 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1562                                           unsigned int arg, unsigned int qty)
1563 {
1564         unsigned int erase_timeout;
1565
1566         if (card->ext_csd.erase_group_def & 1) {
1567                 /* High Capacity Erase Group Size uses HC timeouts */
1568                 if (arg == MMC_TRIM_ARG)
1569                         erase_timeout = card->ext_csd.trim_timeout;
1570                 else
1571                         erase_timeout = card->ext_csd.hc_erase_timeout;
1572         } else {
1573                 /* CSD Erase Group Size uses write timeout */
1574                 unsigned int mult = (10 << card->csd.r2w_factor);
1575                 unsigned int timeout_clks = card->csd.tacc_clks * mult;
1576                 unsigned int timeout_us;
1577
1578                 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
1579                 if (card->csd.tacc_ns < 1000000)
1580                         timeout_us = (card->csd.tacc_ns * mult) / 1000;
1581                 else
1582                         timeout_us = (card->csd.tacc_ns / 1000) * mult;
1583
1584                 /*
1585                  * ios.clock is only a target.  The real clock rate might be
1586                  * less but not that much less, so fudge it by multiplying by 2.
1587                  */
1588                 timeout_clks <<= 1;
1589                 timeout_us += (timeout_clks * 1000) /
1590                               (mmc_host_clk_rate(card->host) / 1000);
1591
1592                 erase_timeout = timeout_us / 1000;
1593
1594                 /*
1595                  * Theoretically, the calculation could underflow so round up
1596                  * to 1ms in that case.
1597                  */
1598                 if (!erase_timeout)
1599                         erase_timeout = 1;
1600         }
1601
1602         /* Multiplier for secure operations */
1603         if (arg & MMC_SECURE_ARGS) {
1604                 if (arg == MMC_SECURE_ERASE_ARG)
1605                         erase_timeout *= card->ext_csd.sec_erase_mult;
1606                 else
1607                         erase_timeout *= card->ext_csd.sec_trim_mult;
1608         }
1609
1610         erase_timeout *= qty;
1611
1612         /*
1613          * Ensure at least a 1 second timeout for SPI as per
1614          * 'mmc_set_data_timeout()'
1615          */
1616         if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
1617                 erase_timeout = 1000;
1618
1619         return erase_timeout;
1620 }
1621
1622 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
1623                                          unsigned int arg,
1624                                          unsigned int qty)
1625 {
1626         unsigned int erase_timeout;
1627
1628         if (card->ssr.erase_timeout) {
1629                 /* Erase timeout specified in SD Status Register (SSR) */
1630                 erase_timeout = card->ssr.erase_timeout * qty +
1631                                 card->ssr.erase_offset;
1632         } else {
1633                 /*
1634                  * Erase timeout not specified in SD Status Register (SSR) so
1635                  * use 250ms per write block.
1636                  */
1637                 erase_timeout = 250 * qty;
1638         }
1639
1640         /* Must not be less than 1 second */
1641         if (erase_timeout < 1000)
1642                 erase_timeout = 1000;
1643
1644         return erase_timeout;
1645 }
1646
1647 static unsigned int mmc_erase_timeout(struct mmc_card *card,
1648                                       unsigned int arg,
1649                                       unsigned int qty)
1650 {
1651         if (mmc_card_sd(card))
1652                 return mmc_sd_erase_timeout(card, arg, qty);
1653         else
1654                 return mmc_mmc_erase_timeout(card, arg, qty);
1655 }
1656
1657 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
1658                         unsigned int to, unsigned int arg)
1659 {
1660         struct mmc_command cmd = {0};
1661         unsigned int qty = 0;
1662         int err;
1663
1664         /*
1665          * qty is used to calculate the erase timeout which depends on how many
1666          * erase groups (or allocation units in SD terminology) are affected.
1667          * We count erasing part of an erase group as one erase group.
1668          * For SD, the allocation units are always a power of 2.  For MMC, the
1669          * erase group size is almost certainly also power of 2, but it does not
1670          * seem to insist on that in the JEDEC standard, so we fall back to
1671          * division in that case.  SD may not specify an allocation unit size,
1672          * in which case the timeout is based on the number of write blocks.
1673          *
1674          * Note that the timeout for secure trim 2 will only be correct if the
1675          * number of erase groups specified is the same as the total of all
1676          * preceding secure trim 1 commands.  Since the power may have been
1677          * lost since the secure trim 1 commands occurred, it is generally
1678          * impossible to calculate the secure trim 2 timeout correctly.
1679          */
1680         if (card->erase_shift)
1681                 qty += ((to >> card->erase_shift) -
1682                         (from >> card->erase_shift)) + 1;
1683         else if (mmc_card_sd(card))
1684                 qty += to - from + 1;
1685         else
1686                 qty += ((to / card->erase_size) -
1687                         (from / card->erase_size)) + 1;
1688
1689         if (!mmc_card_blockaddr(card)) {
1690                 from <<= 9;
1691                 to <<= 9;
1692         }
1693
1694         if (mmc_card_sd(card))
1695                 cmd.opcode = SD_ERASE_WR_BLK_START;
1696         else
1697                 cmd.opcode = MMC_ERASE_GROUP_START;
1698         cmd.arg = from;
1699         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1700         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1701         if (err) {
1702                 pr_err("mmc_erase: group start error %d, "
1703                        "status %#x\n", err, cmd.resp[0]);
1704                 err = -EIO;
1705                 goto out;
1706         }
1707
1708         memset(&cmd, 0, sizeof(struct mmc_command));
1709         if (mmc_card_sd(card))
1710                 cmd.opcode = SD_ERASE_WR_BLK_END;
1711         else
1712                 cmd.opcode = MMC_ERASE_GROUP_END;
1713         cmd.arg = to;
1714         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1715         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1716         if (err) {
1717                 pr_err("mmc_erase: group end error %d, status %#x\n",
1718                        err, cmd.resp[0]);
1719                 err = -EIO;
1720                 goto out;
1721         }
1722
1723         memset(&cmd, 0, sizeof(struct mmc_command));
1724         cmd.opcode = MMC_ERASE;
1725         cmd.arg = arg;
1726         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1727         cmd.cmd_timeout_ms = mmc_erase_timeout(card, arg, qty);
1728         err = mmc_wait_for_cmd(card->host, &cmd, 0);
1729         if (err) {
1730                 pr_err("mmc_erase: erase error %d, status %#x\n",
1731                        err, cmd.resp[0]);
1732                 err = -EIO;
1733                 goto out;
1734         }
1735
1736         if (mmc_host_is_spi(card->host))
1737                 goto out;
1738
1739         do {
1740                 memset(&cmd, 0, sizeof(struct mmc_command));
1741                 cmd.opcode = MMC_SEND_STATUS;
1742                 cmd.arg = card->rca << 16;
1743                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1744                 /* Do not retry else we can't see errors */
1745                 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1746                 if (err || (cmd.resp[0] & 0xFDF92000)) {
1747                         pr_err("error %d requesting status %#x\n",
1748                                 err, cmd.resp[0]);
1749                         err = -EIO;
1750                         goto out;
1751                 }
1752         } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
1753                  R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG);
1754 out:
1755         return err;
1756 }
1757
1758 /**
1759  * mmc_erase - erase sectors.
1760  * @card: card to erase
1761  * @from: first sector to erase
1762  * @nr: number of sectors to erase
1763  * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
1764  *
1765  * Caller must claim host before calling this function.
1766  */
1767 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
1768               unsigned int arg)
1769 {
1770         unsigned int rem, to = from + nr;
1771
1772         if (!(card->host->caps & MMC_CAP_ERASE) ||
1773             !(card->csd.cmdclass & CCC_ERASE))
1774                 return -EOPNOTSUPP;
1775
1776         if (!card->erase_size)
1777                 return -EOPNOTSUPP;
1778
1779         if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
1780                 return -EOPNOTSUPP;
1781
1782         if ((arg & MMC_SECURE_ARGS) &&
1783             !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
1784                 return -EOPNOTSUPP;
1785
1786         if ((arg & MMC_TRIM_ARGS) &&
1787             !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
1788                 return -EOPNOTSUPP;
1789
1790         if (arg == MMC_SECURE_ERASE_ARG) {
1791                 if (from % card->erase_size || nr % card->erase_size)
1792                         return -EINVAL;
1793         }
1794
1795         if (arg == MMC_ERASE_ARG) {
1796                 rem = from % card->erase_size;
1797                 if (rem) {
1798                         rem = card->erase_size - rem;
1799                         from += rem;
1800                         if (nr > rem)
1801                                 nr -= rem;
1802                         else
1803                                 return 0;
1804                 }
1805                 rem = nr % card->erase_size;
1806                 if (rem)
1807                         nr -= rem;
1808         }
1809
1810         if (nr == 0)
1811                 return 0;
1812
1813         to = from + nr;
1814
1815         if (to <= from)
1816                 return -EINVAL;
1817
1818         /* 'from' and 'to' are inclusive */
1819         to -= 1;
1820
1821         return mmc_do_erase(card, from, to, arg);
1822 }
1823 EXPORT_SYMBOL(mmc_erase);
1824
1825 int mmc_can_erase(struct mmc_card *card)
1826 {
1827         if ((card->host->caps & MMC_CAP_ERASE) &&
1828             (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
1829                 return 1;
1830         return 0;
1831 }
1832 EXPORT_SYMBOL(mmc_can_erase);
1833
1834 int mmc_can_trim(struct mmc_card *card)
1835 {
1836         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN)
1837                 return 1;
1838         if (mmc_can_discard(card))
1839                 return 1;
1840         return 0;
1841 }
1842 EXPORT_SYMBOL(mmc_can_trim);
1843
1844 int mmc_can_discard(struct mmc_card *card)
1845 {
1846         /*
1847          * As there's no way to detect the discard support bit at v4.5
1848          * use the s/w feature support filed.
1849          */
1850         if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
1851                 return 1;
1852         return 0;
1853 }
1854 EXPORT_SYMBOL(mmc_can_discard);
1855
1856 int mmc_can_sanitize(struct mmc_card *card)
1857 {
1858         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
1859                 return 1;
1860         return 0;
1861 }
1862 EXPORT_SYMBOL(mmc_can_sanitize);
1863
1864 int mmc_can_secure_erase_trim(struct mmc_card *card)
1865 {
1866         if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)
1867                 return 1;
1868         return 0;
1869 }
1870 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
1871
1872 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
1873                             unsigned int nr)
1874 {
1875         if (!card->erase_size)
1876                 return 0;
1877         if (from % card->erase_size || nr % card->erase_size)
1878                 return 0;
1879         return 1;
1880 }
1881 EXPORT_SYMBOL(mmc_erase_group_aligned);
1882
1883 static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
1884                                             unsigned int arg)
1885 {
1886         struct mmc_host *host = card->host;
1887         unsigned int max_discard, x, y, qty = 0, max_qty, timeout;
1888         unsigned int last_timeout = 0;
1889
1890         if (card->erase_shift)
1891                 max_qty = UINT_MAX >> card->erase_shift;
1892         else if (mmc_card_sd(card))
1893                 max_qty = UINT_MAX;
1894         else
1895                 max_qty = UINT_MAX / card->erase_size;
1896
1897         /* Find the largest qty with an OK timeout */
1898         do {
1899                 y = 0;
1900                 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
1901                         timeout = mmc_erase_timeout(card, arg, qty + x);
1902                         if (timeout > host->max_discard_to)
1903                                 break;
1904                         if (timeout < last_timeout)
1905                                 break;
1906                         last_timeout = timeout;
1907                         y = x;
1908                 }
1909                 qty += y;
1910         } while (y);
1911
1912         if (!qty)
1913                 return 0;
1914
1915         if (qty == 1)
1916                 return 1;
1917
1918         /* Convert qty to sectors */
1919         if (card->erase_shift)
1920                 max_discard = --qty << card->erase_shift;
1921         else if (mmc_card_sd(card))
1922                 max_discard = qty;
1923         else
1924                 max_discard = --qty * card->erase_size;
1925
1926         return max_discard;
1927 }
1928
1929 unsigned int mmc_calc_max_discard(struct mmc_card *card)
1930 {
1931         struct mmc_host *host = card->host;
1932         unsigned int max_discard, max_trim;
1933
1934         if (!host->max_discard_to)
1935                 return UINT_MAX;
1936
1937         /*
1938          * Without erase_group_def set, MMC erase timeout depends on clock
1939          * frequence which can change.  In that case, the best choice is
1940          * just the preferred erase size.
1941          */
1942         if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
1943                 return card->pref_erase;
1944
1945         max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
1946         if (mmc_can_trim(card)) {
1947                 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
1948                 if (max_trim < max_discard)
1949                         max_discard = max_trim;
1950         } else if (max_discard < card->erase_size) {
1951                 max_discard = 0;
1952         }
1953         pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
1954                  mmc_hostname(host), max_discard, host->max_discard_to);
1955         return max_discard;
1956 }
1957 EXPORT_SYMBOL(mmc_calc_max_discard);
1958
1959 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
1960 {
1961         struct mmc_command cmd = {0};
1962
1963         if (mmc_card_blockaddr(card) || mmc_card_ddr_mode(card))
1964                 return 0;
1965
1966         cmd.opcode = MMC_SET_BLOCKLEN;
1967         cmd.arg = blocklen;
1968         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1969         return mmc_wait_for_cmd(card->host, &cmd, 5);
1970 }
1971 EXPORT_SYMBOL(mmc_set_blocklen);
1972
1973 static void mmc_hw_reset_for_init(struct mmc_host *host)
1974 {
1975         if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
1976                 return;
1977         mmc_host_clk_hold(host);
1978         host->ops->hw_reset(host);
1979         mmc_host_clk_release(host);
1980 }
1981
1982 int mmc_can_reset(struct mmc_card *card)
1983 {
1984         u8 rst_n_function;
1985
1986         if (!mmc_card_mmc(card))
1987                 return 0;
1988         rst_n_function = card->ext_csd.rst_n_function;
1989         if ((rst_n_function & EXT_CSD_RST_N_EN_MASK) != EXT_CSD_RST_N_ENABLED)
1990                 return 0;
1991         return 1;
1992 }
1993 EXPORT_SYMBOL(mmc_can_reset);
1994
1995 static int mmc_do_hw_reset(struct mmc_host *host, int check)
1996 {
1997         struct mmc_card *card = host->card;
1998
1999         if (!host->bus_ops->power_restore)
2000                 return -EOPNOTSUPP;
2001
2002         if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2003                 return -EOPNOTSUPP;
2004
2005         if (!card)
2006                 return -EINVAL;
2007
2008         if (!mmc_can_reset(card))
2009                 return -EOPNOTSUPP;
2010
2011         mmc_host_clk_hold(host);
2012         mmc_set_clock(host, host->f_init);
2013
2014         host->ops->hw_reset(host);
2015
2016         /* If the reset has happened, then a status command will fail */
2017         if (check) {
2018                 struct mmc_command cmd = {0};
2019                 int err;
2020
2021                 cmd.opcode = MMC_SEND_STATUS;
2022                 if (!mmc_host_is_spi(card->host))
2023                         cmd.arg = card->rca << 16;
2024                 cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
2025                 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2026                 if (!err) {
2027                         mmc_host_clk_release(host);
2028                         return -ENOSYS;
2029                 }
2030         }
2031
2032         host->card->state &= ~(MMC_STATE_HIGHSPEED | MMC_STATE_HIGHSPEED_DDR);
2033         if (mmc_host_is_spi(host)) {
2034                 host->ios.chip_select = MMC_CS_HIGH;
2035                 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
2036         } else {
2037                 host->ios.chip_select = MMC_CS_DONTCARE;
2038                 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
2039         }
2040         host->ios.bus_width = MMC_BUS_WIDTH_1;
2041         host->ios.timing = MMC_TIMING_LEGACY;
2042         mmc_set_ios(host);
2043
2044         mmc_host_clk_release(host);
2045
2046         return host->bus_ops->power_restore(host);
2047 }
2048
2049 int mmc_hw_reset(struct mmc_host *host)
2050 {
2051         return mmc_do_hw_reset(host, 0);
2052 }
2053 EXPORT_SYMBOL(mmc_hw_reset);
2054
2055 int mmc_hw_reset_check(struct mmc_host *host)
2056 {
2057         return mmc_do_hw_reset(host, 1);
2058 }
2059 EXPORT_SYMBOL(mmc_hw_reset_check);
2060
2061 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2062 {
2063         host->f_init = freq;
2064
2065 #ifdef CONFIG_MMC_DEBUG
2066         pr_info("%s: %s: trying to init card at %u Hz\n",
2067                 mmc_hostname(host), __func__, host->f_init);
2068 #endif
2069         mmc_power_up(host);
2070
2071         /*
2072          * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2073          * do a hardware reset if possible.
2074          */
2075         mmc_hw_reset_for_init(host);
2076
2077         /* Initialization should be done at 3.3 V I/O voltage. */
2078         mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330, 0);
2079
2080         /*
2081          * sdio_reset sends CMD52 to reset card.  Since we do not know
2082          * if the card is being re-initialized, just send it.  CMD52
2083          * should be ignored by SD/eMMC cards.
2084          */
2085         sdio_reset(host);
2086         mmc_go_idle(host);
2087
2088         mmc_send_if_cond(host, host->ocr_avail);
2089
2090         /* Order's important: probe SDIO, then SD, then MMC */
2091         if (!mmc_attach_sdio(host))
2092                 return 0;
2093         if (!mmc_attach_sd(host))
2094                 return 0;
2095         if (!mmc_attach_mmc(host))
2096                 return 0;
2097
2098         mmc_power_off(host);
2099         return -EIO;
2100 }
2101
2102 int _mmc_detect_card_removed(struct mmc_host *host)
2103 {
2104         int ret;
2105
2106         if ((host->caps & MMC_CAP_NONREMOVABLE) || !host->bus_ops->alive)
2107                 return 0;
2108
2109         if (!host->card || mmc_card_removed(host->card))
2110                 return 1;
2111
2112         ret = host->bus_ops->alive(host);
2113         if (ret) {
2114                 mmc_card_set_removed(host->card);
2115                 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2116         }
2117
2118         return ret;
2119 }
2120
2121 int mmc_detect_card_removed(struct mmc_host *host)
2122 {
2123         struct mmc_card *card = host->card;
2124
2125         WARN_ON(!host->claimed);
2126         /*
2127          * The card will be considered unchanged unless we have been asked to
2128          * detect a change or host requires polling to provide card detection.
2129          */
2130         if (card && !host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
2131                 return mmc_card_removed(card);
2132
2133         host->detect_change = 0;
2134
2135         return _mmc_detect_card_removed(host);
2136 }
2137 EXPORT_SYMBOL(mmc_detect_card_removed);
2138
2139 void mmc_rescan(struct work_struct *work)
2140 {
2141         static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
2142         struct mmc_host *host =
2143                 container_of(work, struct mmc_host, detect.work);
2144         int i;
2145
2146         if (host->rescan_disable)
2147                 return;
2148
2149         mmc_bus_get(host);
2150
2151         /*
2152          * if there is a _removable_ card registered, check whether it is
2153          * still present
2154          */
2155         if (host->bus_ops && host->bus_ops->detect && !host->bus_dead
2156             && !(host->caps & MMC_CAP_NONREMOVABLE))
2157                 host->bus_ops->detect(host);
2158
2159         host->detect_change = 0;
2160
2161         /*
2162          * Let mmc_bus_put() free the bus/bus_ops if we've found that
2163          * the card is no longer present.
2164          */
2165         mmc_bus_put(host);
2166         mmc_bus_get(host);
2167
2168         /* if there still is a card present, stop here */
2169         if (host->bus_ops != NULL) {
2170                 mmc_bus_put(host);
2171                 goto out;
2172         }
2173
2174         /*
2175          * Only we can add a new handler, so it's safe to
2176          * release the lock here.
2177          */
2178         mmc_bus_put(host);
2179
2180         if (host->ops->get_cd && host->ops->get_cd(host) == 0)
2181                 goto out;
2182
2183         mmc_claim_host(host);
2184         for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2185                 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2186                         break;
2187                 if (freqs[i] <= host->f_min)
2188                         break;
2189         }
2190         mmc_release_host(host);
2191
2192  out:
2193         if (host->caps & MMC_CAP_NEEDS_POLL)
2194                 mmc_schedule_delayed_work(&host->detect, HZ);
2195 }
2196
2197 void mmc_start_host(struct mmc_host *host)
2198 {
2199         mmc_power_off(host);
2200         mmc_detect_change(host, 0);
2201 }
2202
2203 void mmc_stop_host(struct mmc_host *host)
2204 {
2205 #ifdef CONFIG_MMC_DEBUG
2206         unsigned long flags;
2207         spin_lock_irqsave(&host->lock, flags);
2208         host->removed = 1;
2209         spin_unlock_irqrestore(&host->lock, flags);
2210 #endif
2211
2212         if (host->caps & MMC_CAP_DISABLE)
2213                 cancel_delayed_work(&host->disable);
2214         cancel_delayed_work_sync(&host->detect);
2215         mmc_flush_scheduled_work();
2216
2217         /* clear pm flags now and let card drivers set them as needed */
2218         host->pm_flags = 0;
2219
2220         mmc_bus_get(host);
2221         if (host->bus_ops && !host->bus_dead) {
2222                 /* Calling bus_ops->remove() with a claimed host can deadlock */
2223                 if (host->bus_ops->remove)
2224                         host->bus_ops->remove(host);
2225
2226                 mmc_claim_host(host);
2227                 mmc_detach_bus(host);
2228                 mmc_power_off(host);
2229                 mmc_release_host(host);
2230                 mmc_bus_put(host);
2231                 return;
2232         }
2233         mmc_bus_put(host);
2234
2235         BUG_ON(host->card);
2236
2237         mmc_power_off(host);
2238 }
2239
2240 int mmc_power_save_host(struct mmc_host *host)
2241 {
2242         int ret = 0;
2243
2244 #ifdef CONFIG_MMC_DEBUG
2245         pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__);
2246 #endif
2247
2248         mmc_bus_get(host);
2249
2250         if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
2251                 mmc_bus_put(host);
2252                 return -EINVAL;
2253         }
2254
2255         if (host->bus_ops->power_save)
2256                 ret = host->bus_ops->power_save(host);
2257
2258         mmc_bus_put(host);
2259
2260         mmc_power_off(host);
2261
2262         return ret;
2263 }
2264 EXPORT_SYMBOL(mmc_power_save_host);
2265
2266 int mmc_power_restore_host(struct mmc_host *host)
2267 {
2268         int ret;
2269
2270 #ifdef CONFIG_MMC_DEBUG
2271         pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__);
2272 #endif
2273
2274         mmc_bus_get(host);
2275
2276         if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
2277                 mmc_bus_put(host);
2278                 return -EINVAL;
2279         }
2280
2281         mmc_power_up(host);
2282         ret = host->bus_ops->power_restore(host);
2283
2284         mmc_bus_put(host);
2285
2286         return ret;
2287 }
2288 EXPORT_SYMBOL(mmc_power_restore_host);
2289
2290 int mmc_card_awake(struct mmc_host *host)
2291 {
2292         int err = -ENOSYS;
2293
2294         if (host->caps2 & MMC_CAP2_NO_SLEEP_CMD)
2295                 return 0;
2296
2297         mmc_bus_get(host);
2298
2299         if (host->bus_ops && !host->bus_dead && host->bus_ops->awake)
2300                 err = host->bus_ops->awake(host);
2301
2302         mmc_bus_put(host);
2303
2304         return err;
2305 }
2306 EXPORT_SYMBOL(mmc_card_awake);
2307
2308 int mmc_card_sleep(struct mmc_host *host)
2309 {
2310         int err = -ENOSYS;
2311
2312         if (host->caps2 & MMC_CAP2_NO_SLEEP_CMD)
2313                 return 0;
2314
2315         mmc_bus_get(host);
2316
2317         if (host->bus_ops && !host->bus_dead && host->bus_ops->sleep)
2318                 err = host->bus_ops->sleep(host);
2319
2320         mmc_bus_put(host);
2321
2322         return err;
2323 }
2324 EXPORT_SYMBOL(mmc_card_sleep);
2325
2326 int mmc_card_can_sleep(struct mmc_host *host)
2327 {
2328         struct mmc_card *card = host->card;
2329
2330         if (card && mmc_card_mmc(card) && card->ext_csd.rev >= 3)
2331                 return 1;
2332         return 0;
2333 }
2334 EXPORT_SYMBOL(mmc_card_can_sleep);
2335
2336 /*
2337  * Flush the cache to the non-volatile storage.
2338  */
2339 int mmc_flush_cache(struct mmc_card *card)
2340 {
2341         struct mmc_host *host = card->host;
2342         int err = 0;
2343
2344         if (!(host->caps2 & MMC_CAP2_CACHE_CTRL))
2345                 return err;
2346
2347         if (mmc_card_mmc(card) &&
2348                         (card->ext_csd.cache_size > 0) &&
2349                         (card->ext_csd.cache_ctrl & 1)) {
2350                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2351                                 EXT_CSD_FLUSH_CACHE, 1, 0);
2352                 if (err)
2353                         pr_err("%s: cache flush error %d\n",
2354                                         mmc_hostname(card->host), err);
2355         }
2356
2357         return err;
2358 }
2359 EXPORT_SYMBOL(mmc_flush_cache);
2360
2361 /*
2362  * Turn the cache ON/OFF.
2363  * Turning the cache OFF shall trigger flushing of the data
2364  * to the non-volatile storage.
2365  */
2366 int mmc_cache_ctrl(struct mmc_host *host, u8 enable)
2367 {
2368         struct mmc_card *card = host->card;
2369         unsigned int timeout;
2370         int err = 0;
2371
2372         if (!(host->caps2 & MMC_CAP2_CACHE_CTRL) ||
2373                         mmc_card_is_removable(host))
2374                 return err;
2375
2376         if (card && mmc_card_mmc(card) &&
2377                         (card->ext_csd.cache_size > 0)) {
2378                 enable = !!enable;
2379
2380                 if (card->ext_csd.cache_ctrl ^ enable) {
2381                         timeout = enable ? card->ext_csd.generic_cmd6_time : 0;
2382                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2383                                         EXT_CSD_CACHE_CTRL, enable, timeout);
2384                         if (err)
2385                                 pr_err("%s: cache %s error %d\n",
2386                                                 mmc_hostname(card->host),
2387                                                 enable ? "on" : "off",
2388                                                 err);
2389                         else
2390                                 card->ext_csd.cache_ctrl = enable;
2391                 }
2392         }
2393
2394         return err;
2395 }
2396 EXPORT_SYMBOL(mmc_cache_ctrl);
2397
2398 #ifdef CONFIG_PM
2399
2400 /**
2401  *      mmc_suspend_host - suspend a host
2402  *      @host: mmc host
2403  */
2404 int mmc_suspend_host(struct mmc_host *host)
2405 {
2406         int err = 0;
2407
2408         if (host->caps & MMC_CAP_DISABLE)
2409                 cancel_delayed_work(&host->disable);
2410         cancel_delayed_work(&host->detect);
2411         mmc_flush_scheduled_work();
2412         if (mmc_try_claim_host(host)) {
2413                 err = mmc_cache_ctrl(host, 0);
2414                 mmc_do_release_host(host);
2415         } else {
2416                 err = -EBUSY;
2417         }
2418
2419         if (err)
2420                 goto out;
2421
2422         mmc_bus_get(host);
2423         if (host->bus_ops && !host->bus_dead) {
2424
2425                 /*
2426                  * A long response time is not acceptable for device drivers
2427                  * when doing suspend. Prevent mmc_claim_host in the suspend
2428                  * sequence, to potentially wait "forever" by trying to
2429                  * pre-claim the host.
2430                  */
2431                 if (mmc_try_claim_host(host)) {
2432                         if (host->bus_ops->suspend) {
2433                                 err = host->bus_ops->suspend(host);
2434                         }
2435                         mmc_do_release_host(host);
2436
2437                         if (err == -ENOSYS || !host->bus_ops->resume) {
2438                                 /*
2439                                  * We simply "remove" the card in this case.
2440                                  * It will be redetected on resume.  (Calling
2441                                  * bus_ops->remove() with a claimed host can
2442                                  * deadlock.)
2443                                  */
2444                                 if (host->bus_ops->remove)
2445                                         host->bus_ops->remove(host);
2446                                 mmc_claim_host(host);
2447                                 mmc_detach_bus(host);
2448                                 mmc_power_off(host);
2449                                 mmc_release_host(host);
2450                                 host->pm_flags = 0;
2451                                 err = 0;
2452                         }
2453                 } else {
2454                         err = -EBUSY;
2455                 }
2456         }
2457         mmc_bus_put(host);
2458
2459         if (!err && !mmc_card_keep_power(host))
2460                 mmc_power_off(host);
2461
2462 out:
2463         return err;
2464 }
2465
2466 EXPORT_SYMBOL(mmc_suspend_host);
2467
2468 /**
2469  *      mmc_resume_host - resume a previously suspended host
2470  *      @host: mmc host
2471  */
2472 int mmc_resume_host(struct mmc_host *host)
2473 {
2474         int err = 0;
2475
2476         mmc_bus_get(host);
2477         if (host->bus_ops && !host->bus_dead) {
2478                 if (!mmc_card_keep_power(host)) {
2479                         mmc_power_up(host);
2480                         mmc_select_voltage(host, host->ocr);
2481                         /*
2482                          * Tell runtime PM core we just powered up the card,
2483                          * since it still believes the card is powered off.
2484                          * Note that currently runtime PM is only enabled
2485                          * for SDIO cards that are MMC_CAP_POWER_OFF_CARD
2486                          */
2487                         if (mmc_card_sdio(host->card) &&
2488                             (host->caps & MMC_CAP_POWER_OFF_CARD)) {
2489                                 pm_runtime_disable(&host->card->dev);
2490                                 pm_runtime_set_active(&host->card->dev);
2491                                 pm_runtime_enable(&host->card->dev);
2492                         }
2493                 }
2494                 BUG_ON(!host->bus_ops->resume);
2495                 err = host->bus_ops->resume(host);
2496                 if (err) {
2497                         pr_warning("%s: error %d during resume "
2498                                             "(card was removed?)\n",
2499                                             mmc_hostname(host), err);
2500                         err = 0;
2501                 }
2502         }
2503         host->pm_flags &= ~MMC_PM_KEEP_POWER;
2504         mmc_bus_put(host);
2505
2506         return err;
2507 }
2508 EXPORT_SYMBOL(mmc_resume_host);
2509
2510 /* Do the card removal on suspend if card is assumed removeable
2511  * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2512    to sync the card.
2513 */
2514 int mmc_pm_notify(struct notifier_block *notify_block,
2515                                         unsigned long mode, void *unused)
2516 {
2517         struct mmc_host *host = container_of(
2518                 notify_block, struct mmc_host, pm_notify);
2519         unsigned long flags;
2520
2521
2522         switch (mode) {
2523         case PM_HIBERNATION_PREPARE:
2524         case PM_SUSPEND_PREPARE:
2525
2526                 spin_lock_irqsave(&host->lock, flags);
2527                 host->rescan_disable = 1;
2528                 host->power_notify_type = MMC_HOST_PW_NOTIFY_SHORT;
2529                 spin_unlock_irqrestore(&host->lock, flags);
2530                 cancel_delayed_work_sync(&host->detect);
2531
2532                 if (!host->bus_ops || host->bus_ops->suspend)
2533                         break;
2534
2535                 /* Calling bus_ops->remove() with a claimed host can deadlock */
2536                 if (host->bus_ops->remove)
2537                         host->bus_ops->remove(host);
2538
2539                 mmc_claim_host(host);
2540                 mmc_detach_bus(host);
2541                 mmc_power_off(host);
2542                 mmc_release_host(host);
2543                 host->pm_flags = 0;
2544                 break;
2545
2546         case PM_POST_SUSPEND:
2547         case PM_POST_HIBERNATION:
2548         case PM_POST_RESTORE:
2549
2550                 spin_lock_irqsave(&host->lock, flags);
2551                 host->rescan_disable = 0;
2552                 host->power_notify_type = MMC_HOST_PW_NOTIFY_LONG;
2553                 spin_unlock_irqrestore(&host->lock, flags);
2554                 mmc_detect_change(host, 0);
2555
2556         }
2557
2558         return 0;
2559 }
2560 #endif
2561
2562 static int __init mmc_init(void)
2563 {
2564         int ret;
2565
2566         workqueue = alloc_ordered_workqueue("kmmcd", 0);
2567         if (!workqueue)
2568                 return -ENOMEM;
2569
2570         ret = mmc_register_bus();
2571         if (ret)
2572                 goto destroy_workqueue;
2573
2574         ret = mmc_register_host_class();
2575         if (ret)
2576                 goto unregister_bus;
2577
2578         ret = sdio_register_bus();
2579         if (ret)
2580                 goto unregister_host_class;
2581
2582         return 0;
2583
2584 unregister_host_class:
2585         mmc_unregister_host_class();
2586 unregister_bus:
2587         mmc_unregister_bus();
2588 destroy_workqueue:
2589         destroy_workqueue(workqueue);
2590
2591         return ret;
2592 }
2593
2594 static void __exit mmc_exit(void)
2595 {
2596         sdio_unregister_bus();
2597         mmc_unregister_host_class();
2598         mmc_unregister_bus();
2599         destroy_workqueue(workqueue);
2600 }
2601
2602 subsys_initcall(mmc_init);
2603 module_exit(mmc_exit);
2604
2605 MODULE_LICENSE("GPL");