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