mmc: core: Move regulator helpers to separate file
[linux/fpc-iii.git] / drivers / mmc / core / core.c
blobf796a6afb19bfa830b6774c01d1a66d476f049d4
1 /*
2 * linux/drivers/mmc/core/core.c
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.
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.
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/pm_runtime.h>
25 #include <linux/pm_wakeup.h>
26 #include <linux/suspend.h>
27 #include <linux/fault-inject.h>
28 #include <linux/random.h>
29 #include <linux/slab.h>
30 #include <linux/of.h>
32 #include <linux/mmc/card.h>
33 #include <linux/mmc/host.h>
34 #include <linux/mmc/mmc.h>
35 #include <linux/mmc/sd.h>
36 #include <linux/mmc/slot-gpio.h>
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/mmc.h>
41 #include "core.h"
42 #include "card.h"
43 #include "bus.h"
44 #include "host.h"
45 #include "sdio_bus.h"
46 #include "pwrseq.h"
48 #include "mmc_ops.h"
49 #include "sd_ops.h"
50 #include "sdio_ops.h"
52 /* The max erase timeout, used when host->max_busy_timeout isn't specified */
53 #define MMC_ERASE_TIMEOUT_MS (60 * 1000) /* 60 s */
55 static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
58 * Enabling software CRCs on the data blocks can be a significant (30%)
59 * performance cost, and for other reasons may not always be desired.
60 * So we allow it it to be disabled.
62 bool use_spi_crc = 1;
63 module_param(use_spi_crc, bool, 0);
65 static int mmc_schedule_delayed_work(struct delayed_work *work,
66 unsigned long delay)
69 * We use the system_freezable_wq, because of two reasons.
70 * First, it allows several works (not the same work item) to be
71 * executed simultaneously. Second, the queue becomes frozen when
72 * userspace becomes frozen during system PM.
74 return queue_delayed_work(system_freezable_wq, work, delay);
77 #ifdef CONFIG_FAIL_MMC_REQUEST
80 * Internal function. Inject random data errors.
81 * If mmc_data is NULL no errors are injected.
83 static void mmc_should_fail_request(struct mmc_host *host,
84 struct mmc_request *mrq)
86 struct mmc_command *cmd = mrq->cmd;
87 struct mmc_data *data = mrq->data;
88 static const int data_errors[] = {
89 -ETIMEDOUT,
90 -EILSEQ,
91 -EIO,
94 if (!data)
95 return;
97 if (cmd->error || data->error ||
98 !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
99 return;
101 data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)];
102 data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9;
105 #else /* CONFIG_FAIL_MMC_REQUEST */
107 static inline void mmc_should_fail_request(struct mmc_host *host,
108 struct mmc_request *mrq)
112 #endif /* CONFIG_FAIL_MMC_REQUEST */
114 static inline void mmc_complete_cmd(struct mmc_request *mrq)
116 if (mrq->cap_cmd_during_tfr && !completion_done(&mrq->cmd_completion))
117 complete_all(&mrq->cmd_completion);
120 void mmc_command_done(struct mmc_host *host, struct mmc_request *mrq)
122 if (!mrq->cap_cmd_during_tfr)
123 return;
125 mmc_complete_cmd(mrq);
127 pr_debug("%s: cmd done, tfr ongoing (CMD%u)\n",
128 mmc_hostname(host), mrq->cmd->opcode);
130 EXPORT_SYMBOL(mmc_command_done);
133 * mmc_request_done - finish processing an MMC request
134 * @host: MMC host which completed request
135 * @mrq: MMC request which request
137 * MMC drivers should call this function when they have completed
138 * their processing of a request.
140 void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
142 struct mmc_command *cmd = mrq->cmd;
143 int err = cmd->error;
145 /* Flag re-tuning needed on CRC errors */
146 if ((cmd->opcode != MMC_SEND_TUNING_BLOCK &&
147 cmd->opcode != MMC_SEND_TUNING_BLOCK_HS200) &&
148 (err == -EILSEQ || (mrq->sbc && mrq->sbc->error == -EILSEQ) ||
149 (mrq->data && mrq->data->error == -EILSEQ) ||
150 (mrq->stop && mrq->stop->error == -EILSEQ)))
151 mmc_retune_needed(host);
153 if (err && cmd->retries && mmc_host_is_spi(host)) {
154 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
155 cmd->retries = 0;
158 if (host->ongoing_mrq == mrq)
159 host->ongoing_mrq = NULL;
161 mmc_complete_cmd(mrq);
163 trace_mmc_request_done(host, mrq);
166 * We list various conditions for the command to be considered
167 * properly done:
169 * - There was no error, OK fine then
170 * - We are not doing some kind of retry
171 * - The card was removed (...so just complete everything no matter
172 * if there are errors or retries)
174 if (!err || !cmd->retries || mmc_card_removed(host->card)) {
175 mmc_should_fail_request(host, mrq);
177 if (!host->ongoing_mrq)
178 led_trigger_event(host->led, LED_OFF);
180 if (mrq->sbc) {
181 pr_debug("%s: req done <CMD%u>: %d: %08x %08x %08x %08x\n",
182 mmc_hostname(host), mrq->sbc->opcode,
183 mrq->sbc->error,
184 mrq->sbc->resp[0], mrq->sbc->resp[1],
185 mrq->sbc->resp[2], mrq->sbc->resp[3]);
188 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
189 mmc_hostname(host), cmd->opcode, err,
190 cmd->resp[0], cmd->resp[1],
191 cmd->resp[2], cmd->resp[3]);
193 if (mrq->data) {
194 pr_debug("%s: %d bytes transferred: %d\n",
195 mmc_hostname(host),
196 mrq->data->bytes_xfered, mrq->data->error);
199 if (mrq->stop) {
200 pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n",
201 mmc_hostname(host), mrq->stop->opcode,
202 mrq->stop->error,
203 mrq->stop->resp[0], mrq->stop->resp[1],
204 mrq->stop->resp[2], mrq->stop->resp[3]);
208 * Request starter must handle retries - see
209 * mmc_wait_for_req_done().
211 if (mrq->done)
212 mrq->done(mrq);
215 EXPORT_SYMBOL(mmc_request_done);
217 static void __mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
219 int err;
221 /* Assumes host controller has been runtime resumed by mmc_claim_host */
222 err = mmc_retune(host);
223 if (err) {
224 mrq->cmd->error = err;
225 mmc_request_done(host, mrq);
226 return;
230 * For sdio rw commands we must wait for card busy otherwise some
231 * sdio devices won't work properly.
232 * And bypass I/O abort, reset and bus suspend operations.
234 if (sdio_is_io_busy(mrq->cmd->opcode, mrq->cmd->arg) &&
235 host->ops->card_busy) {
236 int tries = 500; /* Wait aprox 500ms at maximum */
238 while (host->ops->card_busy(host) && --tries)
239 mmc_delay(1);
241 if (tries == 0) {
242 mrq->cmd->error = -EBUSY;
243 mmc_request_done(host, mrq);
244 return;
248 if (mrq->cap_cmd_during_tfr) {
249 host->ongoing_mrq = mrq;
251 * Retry path could come through here without having waiting on
252 * cmd_completion, so ensure it is reinitialised.
254 reinit_completion(&mrq->cmd_completion);
257 trace_mmc_request_start(host, mrq);
259 if (host->cqe_on)
260 host->cqe_ops->cqe_off(host);
262 host->ops->request(host, mrq);
265 static void mmc_mrq_pr_debug(struct mmc_host *host, struct mmc_request *mrq,
266 bool cqe)
268 if (mrq->sbc) {
269 pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n",
270 mmc_hostname(host), mrq->sbc->opcode,
271 mrq->sbc->arg, mrq->sbc->flags);
274 if (mrq->cmd) {
275 pr_debug("%s: starting %sCMD%u arg %08x flags %08x\n",
276 mmc_hostname(host), cqe ? "CQE direct " : "",
277 mrq->cmd->opcode, mrq->cmd->arg, mrq->cmd->flags);
278 } else if (cqe) {
279 pr_debug("%s: starting CQE transfer for tag %d blkaddr %u\n",
280 mmc_hostname(host), mrq->tag, mrq->data->blk_addr);
283 if (mrq->data) {
284 pr_debug("%s: blksz %d blocks %d flags %08x "
285 "tsac %d ms nsac %d\n",
286 mmc_hostname(host), mrq->data->blksz,
287 mrq->data->blocks, mrq->data->flags,
288 mrq->data->timeout_ns / 1000000,
289 mrq->data->timeout_clks);
292 if (mrq->stop) {
293 pr_debug("%s: CMD%u arg %08x flags %08x\n",
294 mmc_hostname(host), mrq->stop->opcode,
295 mrq->stop->arg, mrq->stop->flags);
299 static int mmc_mrq_prep(struct mmc_host *host, struct mmc_request *mrq)
301 unsigned int i, sz = 0;
302 struct scatterlist *sg;
304 if (mrq->cmd) {
305 mrq->cmd->error = 0;
306 mrq->cmd->mrq = mrq;
307 mrq->cmd->data = mrq->data;
309 if (mrq->sbc) {
310 mrq->sbc->error = 0;
311 mrq->sbc->mrq = mrq;
313 if (mrq->data) {
314 if (mrq->data->blksz > host->max_blk_size ||
315 mrq->data->blocks > host->max_blk_count ||
316 mrq->data->blocks * mrq->data->blksz > host->max_req_size)
317 return -EINVAL;
319 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
320 sz += sg->length;
321 if (sz != mrq->data->blocks * mrq->data->blksz)
322 return -EINVAL;
324 mrq->data->error = 0;
325 mrq->data->mrq = mrq;
326 if (mrq->stop) {
327 mrq->data->stop = mrq->stop;
328 mrq->stop->error = 0;
329 mrq->stop->mrq = mrq;
333 return 0;
336 int mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
338 int err;
340 init_completion(&mrq->cmd_completion);
342 mmc_retune_hold(host);
344 if (mmc_card_removed(host->card))
345 return -ENOMEDIUM;
347 mmc_mrq_pr_debug(host, mrq, false);
349 WARN_ON(!host->claimed);
351 err = mmc_mrq_prep(host, mrq);
352 if (err)
353 return err;
355 led_trigger_event(host->led, LED_FULL);
356 __mmc_start_request(host, mrq);
358 return 0;
360 EXPORT_SYMBOL(mmc_start_request);
362 static void mmc_wait_done(struct mmc_request *mrq)
364 complete(&mrq->completion);
367 static inline void mmc_wait_ongoing_tfr_cmd(struct mmc_host *host)
369 struct mmc_request *ongoing_mrq = READ_ONCE(host->ongoing_mrq);
372 * If there is an ongoing transfer, wait for the command line to become
373 * available.
375 if (ongoing_mrq && !completion_done(&ongoing_mrq->cmd_completion))
376 wait_for_completion(&ongoing_mrq->cmd_completion);
379 static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
381 int err;
383 mmc_wait_ongoing_tfr_cmd(host);
385 init_completion(&mrq->completion);
386 mrq->done = mmc_wait_done;
388 err = mmc_start_request(host, mrq);
389 if (err) {
390 mrq->cmd->error = err;
391 mmc_complete_cmd(mrq);
392 complete(&mrq->completion);
395 return err;
398 void mmc_wait_for_req_done(struct mmc_host *host, struct mmc_request *mrq)
400 struct mmc_command *cmd;
402 while (1) {
403 wait_for_completion(&mrq->completion);
405 cmd = mrq->cmd;
408 * If host has timed out waiting for the sanitize
409 * to complete, card might be still in programming state
410 * so let's try to bring the card out of programming
411 * state.
413 if (cmd->sanitize_busy && cmd->error == -ETIMEDOUT) {
414 if (!mmc_interrupt_hpi(host->card)) {
415 pr_warn("%s: %s: Interrupted sanitize\n",
416 mmc_hostname(host), __func__);
417 cmd->error = 0;
418 break;
419 } else {
420 pr_err("%s: %s: Failed to interrupt sanitize\n",
421 mmc_hostname(host), __func__);
424 if (!cmd->error || !cmd->retries ||
425 mmc_card_removed(host->card))
426 break;
428 mmc_retune_recheck(host);
430 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
431 mmc_hostname(host), cmd->opcode, cmd->error);
432 cmd->retries--;
433 cmd->error = 0;
434 __mmc_start_request(host, mrq);
437 mmc_retune_release(host);
439 EXPORT_SYMBOL(mmc_wait_for_req_done);
442 * mmc_cqe_start_req - Start a CQE request.
443 * @host: MMC host to start the request
444 * @mrq: request to start
446 * Start the request, re-tuning if needed and it is possible. Returns an error
447 * code if the request fails to start or -EBUSY if CQE is busy.
449 int mmc_cqe_start_req(struct mmc_host *host, struct mmc_request *mrq)
451 int err;
454 * CQE cannot process re-tuning commands. Caller must hold retuning
455 * while CQE is in use. Re-tuning can happen here only when CQE has no
456 * active requests i.e. this is the first. Note, re-tuning will call
457 * ->cqe_off().
459 err = mmc_retune(host);
460 if (err)
461 goto out_err;
463 mrq->host = host;
465 mmc_mrq_pr_debug(host, mrq, true);
467 err = mmc_mrq_prep(host, mrq);
468 if (err)
469 goto out_err;
471 err = host->cqe_ops->cqe_request(host, mrq);
472 if (err)
473 goto out_err;
475 trace_mmc_request_start(host, mrq);
477 return 0;
479 out_err:
480 if (mrq->cmd) {
481 pr_debug("%s: failed to start CQE direct CMD%u, error %d\n",
482 mmc_hostname(host), mrq->cmd->opcode, err);
483 } else {
484 pr_debug("%s: failed to start CQE transfer for tag %d, error %d\n",
485 mmc_hostname(host), mrq->tag, err);
487 return err;
489 EXPORT_SYMBOL(mmc_cqe_start_req);
492 * mmc_cqe_request_done - CQE has finished processing an MMC request
493 * @host: MMC host which completed request
494 * @mrq: MMC request which completed
496 * CQE drivers should call this function when they have completed
497 * their processing of a request.
499 void mmc_cqe_request_done(struct mmc_host *host, struct mmc_request *mrq)
501 mmc_should_fail_request(host, mrq);
503 /* Flag re-tuning needed on CRC errors */
504 if ((mrq->cmd && mrq->cmd->error == -EILSEQ) ||
505 (mrq->data && mrq->data->error == -EILSEQ))
506 mmc_retune_needed(host);
508 trace_mmc_request_done(host, mrq);
510 if (mrq->cmd) {
511 pr_debug("%s: CQE req done (direct CMD%u): %d\n",
512 mmc_hostname(host), mrq->cmd->opcode, mrq->cmd->error);
513 } else {
514 pr_debug("%s: CQE transfer done tag %d\n",
515 mmc_hostname(host), mrq->tag);
518 if (mrq->data) {
519 pr_debug("%s: %d bytes transferred: %d\n",
520 mmc_hostname(host),
521 mrq->data->bytes_xfered, mrq->data->error);
524 mrq->done(mrq);
526 EXPORT_SYMBOL(mmc_cqe_request_done);
529 * mmc_cqe_post_req - CQE post process of a completed MMC request
530 * @host: MMC host
531 * @mrq: MMC request to be processed
533 void mmc_cqe_post_req(struct mmc_host *host, struct mmc_request *mrq)
535 if (host->cqe_ops->cqe_post_req)
536 host->cqe_ops->cqe_post_req(host, mrq);
538 EXPORT_SYMBOL(mmc_cqe_post_req);
540 /* Arbitrary 1 second timeout */
541 #define MMC_CQE_RECOVERY_TIMEOUT 1000
544 * mmc_cqe_recovery - Recover from CQE errors.
545 * @host: MMC host to recover
547 * Recovery consists of stopping CQE, stopping eMMC, discarding the queue in
548 * in eMMC, and discarding the queue in CQE. CQE must call
549 * mmc_cqe_request_done() on all requests. An error is returned if the eMMC
550 * fails to discard its queue.
552 int mmc_cqe_recovery(struct mmc_host *host)
554 struct mmc_command cmd;
555 int err;
557 mmc_retune_hold_now(host);
560 * Recovery is expected seldom, if at all, but it reduces performance,
561 * so make sure it is not completely silent.
563 pr_warn("%s: running CQE recovery\n", mmc_hostname(host));
565 host->cqe_ops->cqe_recovery_start(host);
567 memset(&cmd, 0, sizeof(cmd));
568 cmd.opcode = MMC_STOP_TRANSMISSION,
569 cmd.flags = MMC_RSP_R1B | MMC_CMD_AC,
570 cmd.flags &= ~MMC_RSP_CRC; /* Ignore CRC */
571 cmd.busy_timeout = MMC_CQE_RECOVERY_TIMEOUT,
572 mmc_wait_for_cmd(host, &cmd, 0);
574 memset(&cmd, 0, sizeof(cmd));
575 cmd.opcode = MMC_CMDQ_TASK_MGMT;
576 cmd.arg = 1; /* Discard entire queue */
577 cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
578 cmd.flags &= ~MMC_RSP_CRC; /* Ignore CRC */
579 cmd.busy_timeout = MMC_CQE_RECOVERY_TIMEOUT,
580 err = mmc_wait_for_cmd(host, &cmd, 0);
582 host->cqe_ops->cqe_recovery_finish(host);
584 mmc_retune_release(host);
586 return err;
588 EXPORT_SYMBOL(mmc_cqe_recovery);
591 * mmc_is_req_done - Determine if a 'cap_cmd_during_tfr' request is done
592 * @host: MMC host
593 * @mrq: MMC request
595 * mmc_is_req_done() is used with requests that have
596 * mrq->cap_cmd_during_tfr = true. mmc_is_req_done() must be called after
597 * starting a request and before waiting for it to complete. That is,
598 * either in between calls to mmc_start_req(), or after mmc_wait_for_req()
599 * and before mmc_wait_for_req_done(). If it is called at other times the
600 * result is not meaningful.
602 bool mmc_is_req_done(struct mmc_host *host, struct mmc_request *mrq)
604 return completion_done(&mrq->completion);
606 EXPORT_SYMBOL(mmc_is_req_done);
609 * mmc_wait_for_req - start a request and wait for completion
610 * @host: MMC host to start command
611 * @mrq: MMC request to start
613 * Start a new MMC custom command request for a host, and wait
614 * for the command to complete. In the case of 'cap_cmd_during_tfr'
615 * requests, the transfer is ongoing and the caller can issue further
616 * commands that do not use the data lines, and then wait by calling
617 * mmc_wait_for_req_done().
618 * Does not attempt to parse the response.
620 void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
622 __mmc_start_req(host, mrq);
624 if (!mrq->cap_cmd_during_tfr)
625 mmc_wait_for_req_done(host, mrq);
627 EXPORT_SYMBOL(mmc_wait_for_req);
630 * mmc_wait_for_cmd - start a command and wait for completion
631 * @host: MMC host to start command
632 * @cmd: MMC command to start
633 * @retries: maximum number of retries
635 * Start a new MMC command for a host, and wait for the command
636 * to complete. Return any error that occurred while the command
637 * was executing. Do not attempt to parse the response.
639 int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
641 struct mmc_request mrq = {};
643 WARN_ON(!host->claimed);
645 memset(cmd->resp, 0, sizeof(cmd->resp));
646 cmd->retries = retries;
648 mrq.cmd = cmd;
649 cmd->data = NULL;
651 mmc_wait_for_req(host, &mrq);
653 return cmd->error;
656 EXPORT_SYMBOL(mmc_wait_for_cmd);
659 * mmc_set_data_timeout - set the timeout for a data command
660 * @data: data phase for command
661 * @card: the MMC card associated with the data transfer
663 * Computes the data timeout parameters according to the
664 * correct algorithm given the card type.
666 void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
668 unsigned int mult;
671 * SDIO cards only define an upper 1 s limit on access.
673 if (mmc_card_sdio(card)) {
674 data->timeout_ns = 1000000000;
675 data->timeout_clks = 0;
676 return;
680 * SD cards use a 100 multiplier rather than 10
682 mult = mmc_card_sd(card) ? 100 : 10;
685 * Scale up the multiplier (and therefore the timeout) by
686 * the r2w factor for writes.
688 if (data->flags & MMC_DATA_WRITE)
689 mult <<= card->csd.r2w_factor;
691 data->timeout_ns = card->csd.taac_ns * mult;
692 data->timeout_clks = card->csd.taac_clks * mult;
695 * SD cards also have an upper limit on the timeout.
697 if (mmc_card_sd(card)) {
698 unsigned int timeout_us, limit_us;
700 timeout_us = data->timeout_ns / 1000;
701 if (card->host->ios.clock)
702 timeout_us += data->timeout_clks * 1000 /
703 (card->host->ios.clock / 1000);
705 if (data->flags & MMC_DATA_WRITE)
707 * The MMC spec "It is strongly recommended
708 * for hosts to implement more than 500ms
709 * timeout value even if the card indicates
710 * the 250ms maximum busy length." Even the
711 * previous value of 300ms is known to be
712 * insufficient for some cards.
714 limit_us = 3000000;
715 else
716 limit_us = 100000;
719 * SDHC cards always use these fixed values.
721 if (timeout_us > limit_us) {
722 data->timeout_ns = limit_us * 1000;
723 data->timeout_clks = 0;
726 /* assign limit value if invalid */
727 if (timeout_us == 0)
728 data->timeout_ns = limit_us * 1000;
732 * Some cards require longer data read timeout than indicated in CSD.
733 * Address this by setting the read timeout to a "reasonably high"
734 * value. For the cards tested, 600ms has proven enough. If necessary,
735 * this value can be increased if other problematic cards require this.
737 if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
738 data->timeout_ns = 600000000;
739 data->timeout_clks = 0;
743 * Some cards need very high timeouts if driven in SPI mode.
744 * The worst observed timeout was 900ms after writing a
745 * continuous stream of data until the internal logic
746 * overflowed.
748 if (mmc_host_is_spi(card->host)) {
749 if (data->flags & MMC_DATA_WRITE) {
750 if (data->timeout_ns < 1000000000)
751 data->timeout_ns = 1000000000; /* 1s */
752 } else {
753 if (data->timeout_ns < 100000000)
754 data->timeout_ns = 100000000; /* 100ms */
758 EXPORT_SYMBOL(mmc_set_data_timeout);
761 * mmc_align_data_size - pads a transfer size to a more optimal value
762 * @card: the MMC card associated with the data transfer
763 * @sz: original transfer size
765 * Pads the original data size with a number of extra bytes in
766 * order to avoid controller bugs and/or performance hits
767 * (e.g. some controllers revert to PIO for certain sizes).
769 * Returns the improved size, which might be unmodified.
771 * Note that this function is only relevant when issuing a
772 * single scatter gather entry.
774 unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
777 * FIXME: We don't have a system for the controller to tell
778 * the core about its problems yet, so for now we just 32-bit
779 * align the size.
781 sz = ((sz + 3) / 4) * 4;
783 return sz;
785 EXPORT_SYMBOL(mmc_align_data_size);
788 * Allow claiming an already claimed host if the context is the same or there is
789 * no context but the task is the same.
791 static inline bool mmc_ctx_matches(struct mmc_host *host, struct mmc_ctx *ctx,
792 struct task_struct *task)
794 return host->claimer == ctx ||
795 (!ctx && task && host->claimer->task == task);
798 static inline void mmc_ctx_set_claimer(struct mmc_host *host,
799 struct mmc_ctx *ctx,
800 struct task_struct *task)
802 if (!host->claimer) {
803 if (ctx)
804 host->claimer = ctx;
805 else
806 host->claimer = &host->default_ctx;
808 if (task)
809 host->claimer->task = task;
813 * __mmc_claim_host - exclusively claim a host
814 * @host: mmc host to claim
815 * @ctx: context that claims the host or NULL in which case the default
816 * context will be used
817 * @abort: whether or not the operation should be aborted
819 * Claim a host for a set of operations. If @abort is non null and
820 * dereference a non-zero value then this will return prematurely with
821 * that non-zero value without acquiring the lock. Returns zero
822 * with the lock held otherwise.
824 int __mmc_claim_host(struct mmc_host *host, struct mmc_ctx *ctx,
825 atomic_t *abort)
827 struct task_struct *task = ctx ? NULL : current;
828 DECLARE_WAITQUEUE(wait, current);
829 unsigned long flags;
830 int stop;
831 bool pm = false;
833 might_sleep();
835 add_wait_queue(&host->wq, &wait);
836 spin_lock_irqsave(&host->lock, flags);
837 while (1) {
838 set_current_state(TASK_UNINTERRUPTIBLE);
839 stop = abort ? atomic_read(abort) : 0;
840 if (stop || !host->claimed || mmc_ctx_matches(host, ctx, task))
841 break;
842 spin_unlock_irqrestore(&host->lock, flags);
843 schedule();
844 spin_lock_irqsave(&host->lock, flags);
846 set_current_state(TASK_RUNNING);
847 if (!stop) {
848 host->claimed = 1;
849 mmc_ctx_set_claimer(host, ctx, task);
850 host->claim_cnt += 1;
851 if (host->claim_cnt == 1)
852 pm = true;
853 } else
854 wake_up(&host->wq);
855 spin_unlock_irqrestore(&host->lock, flags);
856 remove_wait_queue(&host->wq, &wait);
858 if (pm)
859 pm_runtime_get_sync(mmc_dev(host));
861 return stop;
863 EXPORT_SYMBOL(__mmc_claim_host);
866 * mmc_release_host - release a host
867 * @host: mmc host to release
869 * Release a MMC host, allowing others to claim the host
870 * for their operations.
872 void mmc_release_host(struct mmc_host *host)
874 unsigned long flags;
876 WARN_ON(!host->claimed);
878 spin_lock_irqsave(&host->lock, flags);
879 if (--host->claim_cnt) {
880 /* Release for nested claim */
881 spin_unlock_irqrestore(&host->lock, flags);
882 } else {
883 host->claimed = 0;
884 host->claimer->task = NULL;
885 host->claimer = NULL;
886 spin_unlock_irqrestore(&host->lock, flags);
887 wake_up(&host->wq);
888 pm_runtime_mark_last_busy(mmc_dev(host));
889 if (host->caps & MMC_CAP_SYNC_RUNTIME_PM)
890 pm_runtime_put_sync_suspend(mmc_dev(host));
891 else
892 pm_runtime_put_autosuspend(mmc_dev(host));
895 EXPORT_SYMBOL(mmc_release_host);
898 * This is a helper function, which fetches a runtime pm reference for the
899 * card device and also claims the host.
901 void mmc_get_card(struct mmc_card *card, struct mmc_ctx *ctx)
903 pm_runtime_get_sync(&card->dev);
904 __mmc_claim_host(card->host, ctx, NULL);
906 EXPORT_SYMBOL(mmc_get_card);
909 * This is a helper function, which releases the host and drops the runtime
910 * pm reference for the card device.
912 void mmc_put_card(struct mmc_card *card, struct mmc_ctx *ctx)
914 struct mmc_host *host = card->host;
916 WARN_ON(ctx && host->claimer != ctx);
918 mmc_release_host(host);
919 pm_runtime_mark_last_busy(&card->dev);
920 pm_runtime_put_autosuspend(&card->dev);
922 EXPORT_SYMBOL(mmc_put_card);
925 * Internal function that does the actual ios call to the host driver,
926 * optionally printing some debug output.
928 static inline void mmc_set_ios(struct mmc_host *host)
930 struct mmc_ios *ios = &host->ios;
932 pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
933 "width %u timing %u\n",
934 mmc_hostname(host), ios->clock, ios->bus_mode,
935 ios->power_mode, ios->chip_select, ios->vdd,
936 1 << ios->bus_width, ios->timing);
938 host->ops->set_ios(host, ios);
942 * Control chip select pin on a host.
944 void mmc_set_chip_select(struct mmc_host *host, int mode)
946 host->ios.chip_select = mode;
947 mmc_set_ios(host);
951 * Sets the host clock to the highest possible frequency that
952 * is below "hz".
954 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
956 WARN_ON(hz && hz < host->f_min);
958 if (hz > host->f_max)
959 hz = host->f_max;
961 host->ios.clock = hz;
962 mmc_set_ios(host);
965 int mmc_execute_tuning(struct mmc_card *card)
967 struct mmc_host *host = card->host;
968 u32 opcode;
969 int err;
971 if (!host->ops->execute_tuning)
972 return 0;
974 if (host->cqe_on)
975 host->cqe_ops->cqe_off(host);
977 if (mmc_card_mmc(card))
978 opcode = MMC_SEND_TUNING_BLOCK_HS200;
979 else
980 opcode = MMC_SEND_TUNING_BLOCK;
982 err = host->ops->execute_tuning(host, opcode);
984 if (err)
985 pr_err("%s: tuning execution failed: %d\n",
986 mmc_hostname(host), err);
987 else
988 mmc_retune_enable(host);
990 return err;
994 * Change the bus mode (open drain/push-pull) of a host.
996 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
998 host->ios.bus_mode = mode;
999 mmc_set_ios(host);
1003 * Change data bus width of a host.
1005 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
1007 host->ios.bus_width = width;
1008 mmc_set_ios(host);
1012 * Set initial state after a power cycle or a hw_reset.
1014 void mmc_set_initial_state(struct mmc_host *host)
1016 if (host->cqe_on)
1017 host->cqe_ops->cqe_off(host);
1019 mmc_retune_disable(host);
1021 if (mmc_host_is_spi(host))
1022 host->ios.chip_select = MMC_CS_HIGH;
1023 else
1024 host->ios.chip_select = MMC_CS_DONTCARE;
1025 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1026 host->ios.bus_width = MMC_BUS_WIDTH_1;
1027 host->ios.timing = MMC_TIMING_LEGACY;
1028 host->ios.drv_type = 0;
1029 host->ios.enhanced_strobe = false;
1032 * Make sure we are in non-enhanced strobe mode before we
1033 * actually enable it in ext_csd.
1035 if ((host->caps2 & MMC_CAP2_HS400_ES) &&
1036 host->ops->hs400_enhanced_strobe)
1037 host->ops->hs400_enhanced_strobe(host, &host->ios);
1039 mmc_set_ios(host);
1043 * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
1044 * @vdd: voltage (mV)
1045 * @low_bits: prefer low bits in boundary cases
1047 * This function returns the OCR bit number according to the provided @vdd
1048 * value. If conversion is not possible a negative errno value returned.
1050 * Depending on the @low_bits flag the function prefers low or high OCR bits
1051 * on boundary voltages. For example,
1052 * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
1053 * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1055 * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1057 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1059 const int max_bit = ilog2(MMC_VDD_35_36);
1060 int bit;
1062 if (vdd < 1650 || vdd > 3600)
1063 return -EINVAL;
1065 if (vdd >= 1650 && vdd <= 1950)
1066 return ilog2(MMC_VDD_165_195);
1068 if (low_bits)
1069 vdd -= 1;
1071 /* Base 2000 mV, step 100 mV, bit's base 8. */
1072 bit = (vdd - 2000) / 100 + 8;
1073 if (bit > max_bit)
1074 return max_bit;
1075 return bit;
1079 * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1080 * @vdd_min: minimum voltage value (mV)
1081 * @vdd_max: maximum voltage value (mV)
1083 * This function returns the OCR mask bits according to the provided @vdd_min
1084 * and @vdd_max values. If conversion is not possible the function returns 0.
1086 * Notes wrt boundary cases:
1087 * This function sets the OCR bits for all boundary voltages, for example
1088 * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1089 * MMC_VDD_34_35 mask.
1091 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1093 u32 mask = 0;
1095 if (vdd_max < vdd_min)
1096 return 0;
1098 /* Prefer high bits for the boundary vdd_max values. */
1099 vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1100 if (vdd_max < 0)
1101 return 0;
1103 /* Prefer low bits for the boundary vdd_min values. */
1104 vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1105 if (vdd_min < 0)
1106 return 0;
1108 /* Fill the mask, from max bit to min bit. */
1109 while (vdd_max >= vdd_min)
1110 mask |= 1 << vdd_max--;
1112 return mask;
1115 #ifdef CONFIG_OF
1118 * mmc_of_parse_voltage - return mask of supported voltages
1119 * @np: The device node need to be parsed.
1120 * @mask: mask of voltages available for MMC/SD/SDIO
1122 * Parse the "voltage-ranges" DT property, returning zero if it is not
1123 * found, negative errno if the voltage-range specification is invalid,
1124 * or one if the voltage-range is specified and successfully parsed.
1126 int mmc_of_parse_voltage(struct device_node *np, u32 *mask)
1128 const u32 *voltage_ranges;
1129 int num_ranges, i;
1131 voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges);
1132 num_ranges = num_ranges / sizeof(*voltage_ranges) / 2;
1133 if (!voltage_ranges) {
1134 pr_debug("%pOF: voltage-ranges unspecified\n", np);
1135 return 0;
1137 if (!num_ranges) {
1138 pr_err("%pOF: voltage-ranges empty\n", np);
1139 return -EINVAL;
1142 for (i = 0; i < num_ranges; i++) {
1143 const int j = i * 2;
1144 u32 ocr_mask;
1146 ocr_mask = mmc_vddrange_to_ocrmask(
1147 be32_to_cpu(voltage_ranges[j]),
1148 be32_to_cpu(voltage_ranges[j + 1]));
1149 if (!ocr_mask) {
1150 pr_err("%pOF: voltage-range #%d is invalid\n",
1151 np, i);
1152 return -EINVAL;
1154 *mask |= ocr_mask;
1157 return 1;
1159 EXPORT_SYMBOL(mmc_of_parse_voltage);
1161 #endif /* CONFIG_OF */
1163 static int mmc_of_get_func_num(struct device_node *node)
1165 u32 reg;
1166 int ret;
1168 ret = of_property_read_u32(node, "reg", &reg);
1169 if (ret < 0)
1170 return ret;
1172 return reg;
1175 struct device_node *mmc_of_find_child_device(struct mmc_host *host,
1176 unsigned func_num)
1178 struct device_node *node;
1180 if (!host->parent || !host->parent->of_node)
1181 return NULL;
1183 for_each_child_of_node(host->parent->of_node, node) {
1184 if (mmc_of_get_func_num(node) == func_num)
1185 return node;
1188 return NULL;
1192 * Mask off any voltages we don't support and select
1193 * the lowest voltage
1195 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1197 int bit;
1200 * Sanity check the voltages that the card claims to
1201 * support.
1203 if (ocr & 0x7F) {
1204 dev_warn(mmc_dev(host),
1205 "card claims to support voltages below defined range\n");
1206 ocr &= ~0x7F;
1209 ocr &= host->ocr_avail;
1210 if (!ocr) {
1211 dev_warn(mmc_dev(host), "no support for card's volts\n");
1212 return 0;
1215 if (host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) {
1216 bit = ffs(ocr) - 1;
1217 ocr &= 3 << bit;
1218 mmc_power_cycle(host, ocr);
1219 } else {
1220 bit = fls(ocr) - 1;
1221 ocr &= 3 << bit;
1222 if (bit != host->ios.vdd)
1223 dev_warn(mmc_dev(host), "exceeding card's volts\n");
1226 return ocr;
1229 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage)
1231 int err = 0;
1232 int old_signal_voltage = host->ios.signal_voltage;
1234 host->ios.signal_voltage = signal_voltage;
1235 if (host->ops->start_signal_voltage_switch)
1236 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1238 if (err)
1239 host->ios.signal_voltage = old_signal_voltage;
1241 return err;
1245 void mmc_set_initial_signal_voltage(struct mmc_host *host)
1247 /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */
1248 if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330))
1249 dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n");
1250 else if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180))
1251 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n");
1252 else if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_120))
1253 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n");
1256 int mmc_host_set_uhs_voltage(struct mmc_host *host)
1258 u32 clock;
1261 * During a signal voltage level switch, the clock must be gated
1262 * for 5 ms according to the SD spec
1264 clock = host->ios.clock;
1265 host->ios.clock = 0;
1266 mmc_set_ios(host);
1268 if (mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180))
1269 return -EAGAIN;
1271 /* Keep clock gated for at least 10 ms, though spec only says 5 ms */
1272 mmc_delay(10);
1273 host->ios.clock = clock;
1274 mmc_set_ios(host);
1276 return 0;
1279 int mmc_set_uhs_voltage(struct mmc_host *host, u32 ocr)
1281 struct mmc_command cmd = {};
1282 int err = 0;
1285 * If we cannot switch voltages, return failure so the caller
1286 * can continue without UHS mode
1288 if (!host->ops->start_signal_voltage_switch)
1289 return -EPERM;
1290 if (!host->ops->card_busy)
1291 pr_warn("%s: cannot verify signal voltage switch\n",
1292 mmc_hostname(host));
1294 cmd.opcode = SD_SWITCH_VOLTAGE;
1295 cmd.arg = 0;
1296 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1298 err = mmc_wait_for_cmd(host, &cmd, 0);
1299 if (err)
1300 return err;
1302 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1303 return -EIO;
1306 * The card should drive cmd and dat[0:3] low immediately
1307 * after the response of cmd11, but wait 1 ms to be sure
1309 mmc_delay(1);
1310 if (host->ops->card_busy && !host->ops->card_busy(host)) {
1311 err = -EAGAIN;
1312 goto power_cycle;
1315 if (mmc_host_set_uhs_voltage(host)) {
1317 * Voltages may not have been switched, but we've already
1318 * sent CMD11, so a power cycle is required anyway
1320 err = -EAGAIN;
1321 goto power_cycle;
1324 /* Wait for at least 1 ms according to spec */
1325 mmc_delay(1);
1328 * Failure to switch is indicated by the card holding
1329 * dat[0:3] low
1331 if (host->ops->card_busy && host->ops->card_busy(host))
1332 err = -EAGAIN;
1334 power_cycle:
1335 if (err) {
1336 pr_debug("%s: Signal voltage switch failed, "
1337 "power cycling card\n", mmc_hostname(host));
1338 mmc_power_cycle(host, ocr);
1341 return err;
1345 * Select timing parameters for host.
1347 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1349 host->ios.timing = timing;
1350 mmc_set_ios(host);
1354 * Select appropriate driver type for host.
1356 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1358 host->ios.drv_type = drv_type;
1359 mmc_set_ios(host);
1362 int mmc_select_drive_strength(struct mmc_card *card, unsigned int max_dtr,
1363 int card_drv_type, int *drv_type)
1365 struct mmc_host *host = card->host;
1366 int host_drv_type = SD_DRIVER_TYPE_B;
1368 *drv_type = 0;
1370 if (!host->ops->select_drive_strength)
1371 return 0;
1373 /* Use SD definition of driver strength for hosts */
1374 if (host->caps & MMC_CAP_DRIVER_TYPE_A)
1375 host_drv_type |= SD_DRIVER_TYPE_A;
1377 if (host->caps & MMC_CAP_DRIVER_TYPE_C)
1378 host_drv_type |= SD_DRIVER_TYPE_C;
1380 if (host->caps & MMC_CAP_DRIVER_TYPE_D)
1381 host_drv_type |= SD_DRIVER_TYPE_D;
1384 * The drive strength that the hardware can support
1385 * depends on the board design. Pass the appropriate
1386 * information and let the hardware specific code
1387 * return what is possible given the options
1389 return host->ops->select_drive_strength(card, max_dtr,
1390 host_drv_type,
1391 card_drv_type,
1392 drv_type);
1396 * Apply power to the MMC stack. This is a two-stage process.
1397 * First, we enable power to the card without the clock running.
1398 * We then wait a bit for the power to stabilise. Finally,
1399 * enable the bus drivers and clock to the card.
1401 * We must _NOT_ enable the clock prior to power stablising.
1403 * If a host does all the power sequencing itself, ignore the
1404 * initial MMC_POWER_UP stage.
1406 void mmc_power_up(struct mmc_host *host, u32 ocr)
1408 if (host->ios.power_mode == MMC_POWER_ON)
1409 return;
1411 mmc_pwrseq_pre_power_on(host);
1413 host->ios.vdd = fls(ocr) - 1;
1414 host->ios.power_mode = MMC_POWER_UP;
1415 /* Set initial state and call mmc_set_ios */
1416 mmc_set_initial_state(host);
1418 mmc_set_initial_signal_voltage(host);
1421 * This delay should be sufficient to allow the power supply
1422 * to reach the minimum voltage.
1424 mmc_delay(host->ios.power_delay_ms);
1426 mmc_pwrseq_post_power_on(host);
1428 host->ios.clock = host->f_init;
1430 host->ios.power_mode = MMC_POWER_ON;
1431 mmc_set_ios(host);
1434 * This delay must be at least 74 clock sizes, or 1 ms, or the
1435 * time required to reach a stable voltage.
1437 mmc_delay(host->ios.power_delay_ms);
1440 void mmc_power_off(struct mmc_host *host)
1442 if (host->ios.power_mode == MMC_POWER_OFF)
1443 return;
1445 mmc_pwrseq_power_off(host);
1447 host->ios.clock = 0;
1448 host->ios.vdd = 0;
1450 host->ios.power_mode = MMC_POWER_OFF;
1451 /* Set initial state and call mmc_set_ios */
1452 mmc_set_initial_state(host);
1455 * Some configurations, such as the 802.11 SDIO card in the OLPC
1456 * XO-1.5, require a short delay after poweroff before the card
1457 * can be successfully turned on again.
1459 mmc_delay(1);
1462 void mmc_power_cycle(struct mmc_host *host, u32 ocr)
1464 mmc_power_off(host);
1465 /* Wait at least 1 ms according to SD spec */
1466 mmc_delay(1);
1467 mmc_power_up(host, ocr);
1471 * Cleanup when the last reference to the bus operator is dropped.
1473 static void __mmc_release_bus(struct mmc_host *host)
1475 WARN_ON(!host->bus_dead);
1477 host->bus_ops = NULL;
1481 * Increase reference count of bus operator
1483 static inline void mmc_bus_get(struct mmc_host *host)
1485 unsigned long flags;
1487 spin_lock_irqsave(&host->lock, flags);
1488 host->bus_refs++;
1489 spin_unlock_irqrestore(&host->lock, flags);
1493 * Decrease reference count of bus operator and free it if
1494 * it is the last reference.
1496 static inline void mmc_bus_put(struct mmc_host *host)
1498 unsigned long flags;
1500 spin_lock_irqsave(&host->lock, flags);
1501 host->bus_refs--;
1502 if ((host->bus_refs == 0) && host->bus_ops)
1503 __mmc_release_bus(host);
1504 spin_unlock_irqrestore(&host->lock, flags);
1508 * Assign a mmc bus handler to a host. Only one bus handler may control a
1509 * host at any given time.
1511 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1513 unsigned long flags;
1515 WARN_ON(!host->claimed);
1517 spin_lock_irqsave(&host->lock, flags);
1519 WARN_ON(host->bus_ops);
1520 WARN_ON(host->bus_refs);
1522 host->bus_ops = ops;
1523 host->bus_refs = 1;
1524 host->bus_dead = 0;
1526 spin_unlock_irqrestore(&host->lock, flags);
1530 * Remove the current bus handler from a host.
1532 void mmc_detach_bus(struct mmc_host *host)
1534 unsigned long flags;
1536 WARN_ON(!host->claimed);
1537 WARN_ON(!host->bus_ops);
1539 spin_lock_irqsave(&host->lock, flags);
1541 host->bus_dead = 1;
1543 spin_unlock_irqrestore(&host->lock, flags);
1545 mmc_bus_put(host);
1548 static void _mmc_detect_change(struct mmc_host *host, unsigned long delay,
1549 bool cd_irq)
1552 * If the device is configured as wakeup, we prevent a new sleep for
1553 * 5 s to give provision for user space to consume the event.
1555 if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) &&
1556 device_can_wakeup(mmc_dev(host)))
1557 pm_wakeup_event(mmc_dev(host), 5000);
1559 host->detect_change = 1;
1560 mmc_schedule_delayed_work(&host->detect, delay);
1564 * mmc_detect_change - process change of state on a MMC socket
1565 * @host: host which changed state.
1566 * @delay: optional delay to wait before detection (jiffies)
1568 * MMC drivers should call this when they detect a card has been
1569 * inserted or removed. The MMC layer will confirm that any
1570 * present card is still functional, and initialize any newly
1571 * inserted.
1573 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1575 _mmc_detect_change(host, delay, true);
1577 EXPORT_SYMBOL(mmc_detect_change);
1579 void mmc_init_erase(struct mmc_card *card)
1581 unsigned int sz;
1583 if (is_power_of_2(card->erase_size))
1584 card->erase_shift = ffs(card->erase_size) - 1;
1585 else
1586 card->erase_shift = 0;
1589 * It is possible to erase an arbitrarily large area of an SD or MMC
1590 * card. That is not desirable because it can take a long time
1591 * (minutes) potentially delaying more important I/O, and also the
1592 * timeout calculations become increasingly hugely over-estimated.
1593 * Consequently, 'pref_erase' is defined as a guide to limit erases
1594 * to that size and alignment.
1596 * For SD cards that define Allocation Unit size, limit erases to one
1597 * Allocation Unit at a time.
1598 * For MMC, have a stab at ai good value and for modern cards it will
1599 * end up being 4MiB. Note that if the value is too small, it can end
1600 * up taking longer to erase. Also note, erase_size is already set to
1601 * High Capacity Erase Size if available when this function is called.
1603 if (mmc_card_sd(card) && card->ssr.au) {
1604 card->pref_erase = card->ssr.au;
1605 card->erase_shift = ffs(card->ssr.au) - 1;
1606 } else if (card->erase_size) {
1607 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1608 if (sz < 128)
1609 card->pref_erase = 512 * 1024 / 512;
1610 else if (sz < 512)
1611 card->pref_erase = 1024 * 1024 / 512;
1612 else if (sz < 1024)
1613 card->pref_erase = 2 * 1024 * 1024 / 512;
1614 else
1615 card->pref_erase = 4 * 1024 * 1024 / 512;
1616 if (card->pref_erase < card->erase_size)
1617 card->pref_erase = card->erase_size;
1618 else {
1619 sz = card->pref_erase % card->erase_size;
1620 if (sz)
1621 card->pref_erase += card->erase_size - sz;
1623 } else
1624 card->pref_erase = 0;
1627 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1628 unsigned int arg, unsigned int qty)
1630 unsigned int erase_timeout;
1632 if (arg == MMC_DISCARD_ARG ||
1633 (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) {
1634 erase_timeout = card->ext_csd.trim_timeout;
1635 } else if (card->ext_csd.erase_group_def & 1) {
1636 /* High Capacity Erase Group Size uses HC timeouts */
1637 if (arg == MMC_TRIM_ARG)
1638 erase_timeout = card->ext_csd.trim_timeout;
1639 else
1640 erase_timeout = card->ext_csd.hc_erase_timeout;
1641 } else {
1642 /* CSD Erase Group Size uses write timeout */
1643 unsigned int mult = (10 << card->csd.r2w_factor);
1644 unsigned int timeout_clks = card->csd.taac_clks * mult;
1645 unsigned int timeout_us;
1647 /* Avoid overflow: e.g. taac_ns=80000000 mult=1280 */
1648 if (card->csd.taac_ns < 1000000)
1649 timeout_us = (card->csd.taac_ns * mult) / 1000;
1650 else
1651 timeout_us = (card->csd.taac_ns / 1000) * mult;
1654 * ios.clock is only a target. The real clock rate might be
1655 * less but not that much less, so fudge it by multiplying by 2.
1657 timeout_clks <<= 1;
1658 timeout_us += (timeout_clks * 1000) /
1659 (card->host->ios.clock / 1000);
1661 erase_timeout = timeout_us / 1000;
1664 * Theoretically, the calculation could underflow so round up
1665 * to 1ms in that case.
1667 if (!erase_timeout)
1668 erase_timeout = 1;
1671 /* Multiplier for secure operations */
1672 if (arg & MMC_SECURE_ARGS) {
1673 if (arg == MMC_SECURE_ERASE_ARG)
1674 erase_timeout *= card->ext_csd.sec_erase_mult;
1675 else
1676 erase_timeout *= card->ext_csd.sec_trim_mult;
1679 erase_timeout *= qty;
1682 * Ensure at least a 1 second timeout for SPI as per
1683 * 'mmc_set_data_timeout()'
1685 if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
1686 erase_timeout = 1000;
1688 return erase_timeout;
1691 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
1692 unsigned int arg,
1693 unsigned int qty)
1695 unsigned int erase_timeout;
1697 if (card->ssr.erase_timeout) {
1698 /* Erase timeout specified in SD Status Register (SSR) */
1699 erase_timeout = card->ssr.erase_timeout * qty +
1700 card->ssr.erase_offset;
1701 } else {
1703 * Erase timeout not specified in SD Status Register (SSR) so
1704 * use 250ms per write block.
1706 erase_timeout = 250 * qty;
1709 /* Must not be less than 1 second */
1710 if (erase_timeout < 1000)
1711 erase_timeout = 1000;
1713 return erase_timeout;
1716 static unsigned int mmc_erase_timeout(struct mmc_card *card,
1717 unsigned int arg,
1718 unsigned int qty)
1720 if (mmc_card_sd(card))
1721 return mmc_sd_erase_timeout(card, arg, qty);
1722 else
1723 return mmc_mmc_erase_timeout(card, arg, qty);
1726 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
1727 unsigned int to, unsigned int arg)
1729 struct mmc_command cmd = {};
1730 unsigned int qty = 0, busy_timeout = 0;
1731 bool use_r1b_resp = false;
1732 unsigned long timeout;
1733 int loop_udelay=64, udelay_max=32768;
1734 int err;
1736 mmc_retune_hold(card->host);
1739 * qty is used to calculate the erase timeout which depends on how many
1740 * erase groups (or allocation units in SD terminology) are affected.
1741 * We count erasing part of an erase group as one erase group.
1742 * For SD, the allocation units are always a power of 2. For MMC, the
1743 * erase group size is almost certainly also power of 2, but it does not
1744 * seem to insist on that in the JEDEC standard, so we fall back to
1745 * division in that case. SD may not specify an allocation unit size,
1746 * in which case the timeout is based on the number of write blocks.
1748 * Note that the timeout for secure trim 2 will only be correct if the
1749 * number of erase groups specified is the same as the total of all
1750 * preceding secure trim 1 commands. Since the power may have been
1751 * lost since the secure trim 1 commands occurred, it is generally
1752 * impossible to calculate the secure trim 2 timeout correctly.
1754 if (card->erase_shift)
1755 qty += ((to >> card->erase_shift) -
1756 (from >> card->erase_shift)) + 1;
1757 else if (mmc_card_sd(card))
1758 qty += to - from + 1;
1759 else
1760 qty += ((to / card->erase_size) -
1761 (from / card->erase_size)) + 1;
1763 if (!mmc_card_blockaddr(card)) {
1764 from <<= 9;
1765 to <<= 9;
1768 if (mmc_card_sd(card))
1769 cmd.opcode = SD_ERASE_WR_BLK_START;
1770 else
1771 cmd.opcode = MMC_ERASE_GROUP_START;
1772 cmd.arg = from;
1773 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1774 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1775 if (err) {
1776 pr_err("mmc_erase: group start error %d, "
1777 "status %#x\n", err, cmd.resp[0]);
1778 err = -EIO;
1779 goto out;
1782 memset(&cmd, 0, sizeof(struct mmc_command));
1783 if (mmc_card_sd(card))
1784 cmd.opcode = SD_ERASE_WR_BLK_END;
1785 else
1786 cmd.opcode = MMC_ERASE_GROUP_END;
1787 cmd.arg = to;
1788 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1789 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1790 if (err) {
1791 pr_err("mmc_erase: group end error %d, status %#x\n",
1792 err, cmd.resp[0]);
1793 err = -EIO;
1794 goto out;
1797 memset(&cmd, 0, sizeof(struct mmc_command));
1798 cmd.opcode = MMC_ERASE;
1799 cmd.arg = arg;
1800 busy_timeout = mmc_erase_timeout(card, arg, qty);
1802 * If the host controller supports busy signalling and the timeout for
1803 * the erase operation does not exceed the max_busy_timeout, we should
1804 * use R1B response. Or we need to prevent the host from doing hw busy
1805 * detection, which is done by converting to a R1 response instead.
1807 if (card->host->max_busy_timeout &&
1808 busy_timeout > card->host->max_busy_timeout) {
1809 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1810 } else {
1811 cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1812 cmd.busy_timeout = busy_timeout;
1813 use_r1b_resp = true;
1816 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1817 if (err) {
1818 pr_err("mmc_erase: erase error %d, status %#x\n",
1819 err, cmd.resp[0]);
1820 err = -EIO;
1821 goto out;
1824 if (mmc_host_is_spi(card->host))
1825 goto out;
1828 * In case of when R1B + MMC_CAP_WAIT_WHILE_BUSY is used, the polling
1829 * shall be avoided.
1831 if ((card->host->caps & MMC_CAP_WAIT_WHILE_BUSY) && use_r1b_resp)
1832 goto out;
1834 timeout = jiffies + msecs_to_jiffies(busy_timeout);
1835 do {
1836 memset(&cmd, 0, sizeof(struct mmc_command));
1837 cmd.opcode = MMC_SEND_STATUS;
1838 cmd.arg = card->rca << 16;
1839 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1840 /* Do not retry else we can't see errors */
1841 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1842 if (err || R1_STATUS(cmd.resp[0])) {
1843 pr_err("error %d requesting status %#x\n",
1844 err, cmd.resp[0]);
1845 err = -EIO;
1846 goto out;
1849 /* Timeout if the device never becomes ready for data and
1850 * never leaves the program state.
1852 if (time_after(jiffies, timeout)) {
1853 pr_err("%s: Card stuck in programming state! %s\n",
1854 mmc_hostname(card->host), __func__);
1855 err = -EIO;
1856 goto out;
1858 if ((cmd.resp[0] & R1_READY_FOR_DATA) &&
1859 R1_CURRENT_STATE(cmd.resp[0]) != R1_STATE_PRG)
1860 break;
1862 usleep_range(loop_udelay, loop_udelay*2);
1863 if (loop_udelay < udelay_max)
1864 loop_udelay *= 2;
1865 } while (1);
1867 out:
1868 mmc_retune_release(card->host);
1869 return err;
1872 static unsigned int mmc_align_erase_size(struct mmc_card *card,
1873 unsigned int *from,
1874 unsigned int *to,
1875 unsigned int nr)
1877 unsigned int from_new = *from, nr_new = nr, rem;
1880 * When the 'card->erase_size' is power of 2, we can use round_up/down()
1881 * to align the erase size efficiently.
1883 if (is_power_of_2(card->erase_size)) {
1884 unsigned int temp = from_new;
1886 from_new = round_up(temp, card->erase_size);
1887 rem = from_new - temp;
1889 if (nr_new > rem)
1890 nr_new -= rem;
1891 else
1892 return 0;
1894 nr_new = round_down(nr_new, card->erase_size);
1895 } else {
1896 rem = from_new % card->erase_size;
1897 if (rem) {
1898 rem = card->erase_size - rem;
1899 from_new += rem;
1900 if (nr_new > rem)
1901 nr_new -= rem;
1902 else
1903 return 0;
1906 rem = nr_new % card->erase_size;
1907 if (rem)
1908 nr_new -= rem;
1911 if (nr_new == 0)
1912 return 0;
1914 *to = from_new + nr_new;
1915 *from = from_new;
1917 return nr_new;
1921 * mmc_erase - erase sectors.
1922 * @card: card to erase
1923 * @from: first sector to erase
1924 * @nr: number of sectors to erase
1925 * @arg: erase command argument (SD supports only %SD_ERASE_ARG)
1927 * Caller must claim host before calling this function.
1929 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
1930 unsigned int arg)
1932 unsigned int rem, to = from + nr;
1933 int err;
1935 if (!(card->host->caps & MMC_CAP_ERASE) ||
1936 !(card->csd.cmdclass & CCC_ERASE))
1937 return -EOPNOTSUPP;
1939 if (!card->erase_size)
1940 return -EOPNOTSUPP;
1942 if (mmc_card_sd(card) && arg != SD_ERASE_ARG)
1943 return -EOPNOTSUPP;
1945 if ((arg & MMC_SECURE_ARGS) &&
1946 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
1947 return -EOPNOTSUPP;
1949 if ((arg & MMC_TRIM_ARGS) &&
1950 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
1951 return -EOPNOTSUPP;
1953 if (arg == MMC_SECURE_ERASE_ARG) {
1954 if (from % card->erase_size || nr % card->erase_size)
1955 return -EINVAL;
1958 if (arg == MMC_ERASE_ARG)
1959 nr = mmc_align_erase_size(card, &from, &to, nr);
1961 if (nr == 0)
1962 return 0;
1964 if (to <= from)
1965 return -EINVAL;
1967 /* 'from' and 'to' are inclusive */
1968 to -= 1;
1971 * Special case where only one erase-group fits in the timeout budget:
1972 * If the region crosses an erase-group boundary on this particular
1973 * case, we will be trimming more than one erase-group which, does not
1974 * fit in the timeout budget of the controller, so we need to split it
1975 * and call mmc_do_erase() twice if necessary. This special case is
1976 * identified by the card->eg_boundary flag.
1978 rem = card->erase_size - (from % card->erase_size);
1979 if ((arg & MMC_TRIM_ARGS) && (card->eg_boundary) && (nr > rem)) {
1980 err = mmc_do_erase(card, from, from + rem - 1, arg);
1981 from += rem;
1982 if ((err) || (to <= from))
1983 return err;
1986 return mmc_do_erase(card, from, to, arg);
1988 EXPORT_SYMBOL(mmc_erase);
1990 int mmc_can_erase(struct mmc_card *card)
1992 if ((card->host->caps & MMC_CAP_ERASE) &&
1993 (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
1994 return 1;
1995 return 0;
1997 EXPORT_SYMBOL(mmc_can_erase);
1999 int mmc_can_trim(struct mmc_card *card)
2001 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN) &&
2002 (!(card->quirks & MMC_QUIRK_TRIM_BROKEN)))
2003 return 1;
2004 return 0;
2006 EXPORT_SYMBOL(mmc_can_trim);
2008 int mmc_can_discard(struct mmc_card *card)
2011 * As there's no way to detect the discard support bit at v4.5
2012 * use the s/w feature support filed.
2014 if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
2015 return 1;
2016 return 0;
2018 EXPORT_SYMBOL(mmc_can_discard);
2020 int mmc_can_sanitize(struct mmc_card *card)
2022 if (!mmc_can_trim(card) && !mmc_can_erase(card))
2023 return 0;
2024 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
2025 return 1;
2026 return 0;
2028 EXPORT_SYMBOL(mmc_can_sanitize);
2030 int mmc_can_secure_erase_trim(struct mmc_card *card)
2032 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) &&
2033 !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
2034 return 1;
2035 return 0;
2037 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
2039 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
2040 unsigned int nr)
2042 if (!card->erase_size)
2043 return 0;
2044 if (from % card->erase_size || nr % card->erase_size)
2045 return 0;
2046 return 1;
2048 EXPORT_SYMBOL(mmc_erase_group_aligned);
2050 static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
2051 unsigned int arg)
2053 struct mmc_host *host = card->host;
2054 unsigned int max_discard, x, y, qty = 0, max_qty, min_qty, timeout;
2055 unsigned int last_timeout = 0;
2056 unsigned int max_busy_timeout = host->max_busy_timeout ?
2057 host->max_busy_timeout : MMC_ERASE_TIMEOUT_MS;
2059 if (card->erase_shift) {
2060 max_qty = UINT_MAX >> card->erase_shift;
2061 min_qty = card->pref_erase >> card->erase_shift;
2062 } else if (mmc_card_sd(card)) {
2063 max_qty = UINT_MAX;
2064 min_qty = card->pref_erase;
2065 } else {
2066 max_qty = UINT_MAX / card->erase_size;
2067 min_qty = card->pref_erase / card->erase_size;
2071 * We should not only use 'host->max_busy_timeout' as the limitation
2072 * when deciding the max discard sectors. We should set a balance value
2073 * to improve the erase speed, and it can not get too long timeout at
2074 * the same time.
2076 * Here we set 'card->pref_erase' as the minimal discard sectors no
2077 * matter what size of 'host->max_busy_timeout', but if the
2078 * 'host->max_busy_timeout' is large enough for more discard sectors,
2079 * then we can continue to increase the max discard sectors until we
2080 * get a balance value. In cases when the 'host->max_busy_timeout'
2081 * isn't specified, use the default max erase timeout.
2083 do {
2084 y = 0;
2085 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
2086 timeout = mmc_erase_timeout(card, arg, qty + x);
2088 if (qty + x > min_qty && timeout > max_busy_timeout)
2089 break;
2091 if (timeout < last_timeout)
2092 break;
2093 last_timeout = timeout;
2094 y = x;
2096 qty += y;
2097 } while (y);
2099 if (!qty)
2100 return 0;
2103 * When specifying a sector range to trim, chances are we might cross
2104 * an erase-group boundary even if the amount of sectors is less than
2105 * one erase-group.
2106 * If we can only fit one erase-group in the controller timeout budget,
2107 * we have to care that erase-group boundaries are not crossed by a
2108 * single trim operation. We flag that special case with "eg_boundary".
2109 * In all other cases we can just decrement qty and pretend that we
2110 * always touch (qty + 1) erase-groups as a simple optimization.
2112 if (qty == 1)
2113 card->eg_boundary = 1;
2114 else
2115 qty--;
2117 /* Convert qty to sectors */
2118 if (card->erase_shift)
2119 max_discard = qty << card->erase_shift;
2120 else if (mmc_card_sd(card))
2121 max_discard = qty + 1;
2122 else
2123 max_discard = qty * card->erase_size;
2125 return max_discard;
2128 unsigned int mmc_calc_max_discard(struct mmc_card *card)
2130 struct mmc_host *host = card->host;
2131 unsigned int max_discard, max_trim;
2134 * Without erase_group_def set, MMC erase timeout depends on clock
2135 * frequence which can change. In that case, the best choice is
2136 * just the preferred erase size.
2138 if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
2139 return card->pref_erase;
2141 max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
2142 if (max_discard && mmc_can_trim(card)) {
2143 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
2144 if (max_trim < max_discard)
2145 max_discard = max_trim;
2146 } else if (max_discard < card->erase_size) {
2147 max_discard = 0;
2149 pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
2150 mmc_hostname(host), max_discard, host->max_busy_timeout ?
2151 host->max_busy_timeout : MMC_ERASE_TIMEOUT_MS);
2152 return max_discard;
2154 EXPORT_SYMBOL(mmc_calc_max_discard);
2156 bool mmc_card_is_blockaddr(struct mmc_card *card)
2158 return card ? mmc_card_blockaddr(card) : false;
2160 EXPORT_SYMBOL(mmc_card_is_blockaddr);
2162 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
2164 struct mmc_command cmd = {};
2166 if (mmc_card_blockaddr(card) || mmc_card_ddr52(card) ||
2167 mmc_card_hs400(card) || mmc_card_hs400es(card))
2168 return 0;
2170 cmd.opcode = MMC_SET_BLOCKLEN;
2171 cmd.arg = blocklen;
2172 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2173 return mmc_wait_for_cmd(card->host, &cmd, 5);
2175 EXPORT_SYMBOL(mmc_set_blocklen);
2177 static void mmc_hw_reset_for_init(struct mmc_host *host)
2179 mmc_pwrseq_reset(host);
2181 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2182 return;
2183 host->ops->hw_reset(host);
2186 int mmc_hw_reset(struct mmc_host *host)
2188 int ret;
2190 if (!host->card)
2191 return -EINVAL;
2193 mmc_bus_get(host);
2194 if (!host->bus_ops || host->bus_dead || !host->bus_ops->hw_reset) {
2195 mmc_bus_put(host);
2196 return -EOPNOTSUPP;
2199 ret = host->bus_ops->hw_reset(host);
2200 mmc_bus_put(host);
2202 if (ret)
2203 pr_warn("%s: tried to HW reset card, got error %d\n",
2204 mmc_hostname(host), ret);
2206 return ret;
2208 EXPORT_SYMBOL(mmc_hw_reset);
2210 int mmc_sw_reset(struct mmc_host *host)
2212 int ret;
2214 if (!host->card)
2215 return -EINVAL;
2217 mmc_bus_get(host);
2218 if (!host->bus_ops || host->bus_dead || !host->bus_ops->sw_reset) {
2219 mmc_bus_put(host);
2220 return -EOPNOTSUPP;
2223 ret = host->bus_ops->sw_reset(host);
2224 mmc_bus_put(host);
2226 if (ret)
2227 pr_warn("%s: tried to SW reset card, got error %d\n",
2228 mmc_hostname(host), ret);
2230 return ret;
2232 EXPORT_SYMBOL(mmc_sw_reset);
2234 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2236 host->f_init = freq;
2238 pr_debug("%s: %s: trying to init card at %u Hz\n",
2239 mmc_hostname(host), __func__, host->f_init);
2241 mmc_power_up(host, host->ocr_avail);
2244 * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2245 * do a hardware reset if possible.
2247 mmc_hw_reset_for_init(host);
2250 * sdio_reset sends CMD52 to reset card. Since we do not know
2251 * if the card is being re-initialized, just send it. CMD52
2252 * should be ignored by SD/eMMC cards.
2253 * Skip it if we already know that we do not support SDIO commands
2255 if (!(host->caps2 & MMC_CAP2_NO_SDIO))
2256 sdio_reset(host);
2258 mmc_go_idle(host);
2260 if (!(host->caps2 & MMC_CAP2_NO_SD))
2261 mmc_send_if_cond(host, host->ocr_avail);
2263 /* Order's important: probe SDIO, then SD, then MMC */
2264 if (!(host->caps2 & MMC_CAP2_NO_SDIO))
2265 if (!mmc_attach_sdio(host))
2266 return 0;
2268 if (!(host->caps2 & MMC_CAP2_NO_SD))
2269 if (!mmc_attach_sd(host))
2270 return 0;
2272 if (!(host->caps2 & MMC_CAP2_NO_MMC))
2273 if (!mmc_attach_mmc(host))
2274 return 0;
2276 mmc_power_off(host);
2277 return -EIO;
2280 int _mmc_detect_card_removed(struct mmc_host *host)
2282 int ret;
2284 if (!host->card || mmc_card_removed(host->card))
2285 return 1;
2287 ret = host->bus_ops->alive(host);
2290 * Card detect status and alive check may be out of sync if card is
2291 * removed slowly, when card detect switch changes while card/slot
2292 * pads are still contacted in hardware (refer to "SD Card Mechanical
2293 * Addendum, Appendix C: Card Detection Switch"). So reschedule a
2294 * detect work 200ms later for this case.
2296 if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) {
2297 mmc_detect_change(host, msecs_to_jiffies(200));
2298 pr_debug("%s: card removed too slowly\n", mmc_hostname(host));
2301 if (ret) {
2302 mmc_card_set_removed(host->card);
2303 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2306 return ret;
2309 int mmc_detect_card_removed(struct mmc_host *host)
2311 struct mmc_card *card = host->card;
2312 int ret;
2314 WARN_ON(!host->claimed);
2316 if (!card)
2317 return 1;
2319 if (!mmc_card_is_removable(host))
2320 return 0;
2322 ret = mmc_card_removed(card);
2324 * The card will be considered unchanged unless we have been asked to
2325 * detect a change or host requires polling to provide card detection.
2327 if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
2328 return ret;
2330 host->detect_change = 0;
2331 if (!ret) {
2332 ret = _mmc_detect_card_removed(host);
2333 if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) {
2335 * Schedule a detect work as soon as possible to let a
2336 * rescan handle the card removal.
2338 cancel_delayed_work(&host->detect);
2339 _mmc_detect_change(host, 0, false);
2343 return ret;
2345 EXPORT_SYMBOL(mmc_detect_card_removed);
2347 void mmc_rescan(struct work_struct *work)
2349 struct mmc_host *host =
2350 container_of(work, struct mmc_host, detect.work);
2351 int i;
2353 if (host->rescan_disable)
2354 return;
2356 /* If there is a non-removable card registered, only scan once */
2357 if (!mmc_card_is_removable(host) && host->rescan_entered)
2358 return;
2359 host->rescan_entered = 1;
2361 if (host->trigger_card_event && host->ops->card_event) {
2362 mmc_claim_host(host);
2363 host->ops->card_event(host);
2364 mmc_release_host(host);
2365 host->trigger_card_event = false;
2368 mmc_bus_get(host);
2371 * if there is a _removable_ card registered, check whether it is
2372 * still present
2374 if (host->bus_ops && !host->bus_dead && mmc_card_is_removable(host))
2375 host->bus_ops->detect(host);
2377 host->detect_change = 0;
2380 * Let mmc_bus_put() free the bus/bus_ops if we've found that
2381 * the card is no longer present.
2383 mmc_bus_put(host);
2384 mmc_bus_get(host);
2386 /* if there still is a card present, stop here */
2387 if (host->bus_ops != NULL) {
2388 mmc_bus_put(host);
2389 goto out;
2393 * Only we can add a new handler, so it's safe to
2394 * release the lock here.
2396 mmc_bus_put(host);
2398 mmc_claim_host(host);
2399 if (mmc_card_is_removable(host) && host->ops->get_cd &&
2400 host->ops->get_cd(host) == 0) {
2401 mmc_power_off(host);
2402 mmc_release_host(host);
2403 goto out;
2406 for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2407 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2408 break;
2409 if (freqs[i] <= host->f_min)
2410 break;
2412 mmc_release_host(host);
2414 out:
2415 if (host->caps & MMC_CAP_NEEDS_POLL)
2416 mmc_schedule_delayed_work(&host->detect, HZ);
2419 void mmc_start_host(struct mmc_host *host)
2421 host->f_init = max(freqs[0], host->f_min);
2422 host->rescan_disable = 0;
2423 host->ios.power_mode = MMC_POWER_UNDEFINED;
2425 if (!(host->caps2 & MMC_CAP2_NO_PRESCAN_POWERUP)) {
2426 mmc_claim_host(host);
2427 mmc_power_up(host, host->ocr_avail);
2428 mmc_release_host(host);
2431 mmc_gpiod_request_cd_irq(host);
2432 _mmc_detect_change(host, 0, false);
2435 void mmc_stop_host(struct mmc_host *host)
2437 if (host->slot.cd_irq >= 0) {
2438 mmc_gpio_set_cd_wake(host, false);
2439 disable_irq(host->slot.cd_irq);
2442 host->rescan_disable = 1;
2443 cancel_delayed_work_sync(&host->detect);
2445 /* clear pm flags now and let card drivers set them as needed */
2446 host->pm_flags = 0;
2448 mmc_bus_get(host);
2449 if (host->bus_ops && !host->bus_dead) {
2450 /* Calling bus_ops->remove() with a claimed host can deadlock */
2451 host->bus_ops->remove(host);
2452 mmc_claim_host(host);
2453 mmc_detach_bus(host);
2454 mmc_power_off(host);
2455 mmc_release_host(host);
2456 mmc_bus_put(host);
2457 return;
2459 mmc_bus_put(host);
2461 mmc_claim_host(host);
2462 mmc_power_off(host);
2463 mmc_release_host(host);
2466 #ifdef CONFIG_PM_SLEEP
2467 /* Do the card removal on suspend if card is assumed removeable
2468 * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2469 to sync the card.
2471 static int mmc_pm_notify(struct notifier_block *notify_block,
2472 unsigned long mode, void *unused)
2474 struct mmc_host *host = container_of(
2475 notify_block, struct mmc_host, pm_notify);
2476 unsigned long flags;
2477 int err = 0;
2479 switch (mode) {
2480 case PM_HIBERNATION_PREPARE:
2481 case PM_SUSPEND_PREPARE:
2482 case PM_RESTORE_PREPARE:
2483 spin_lock_irqsave(&host->lock, flags);
2484 host->rescan_disable = 1;
2485 spin_unlock_irqrestore(&host->lock, flags);
2486 cancel_delayed_work_sync(&host->detect);
2488 if (!host->bus_ops)
2489 break;
2491 /* Validate prerequisites for suspend */
2492 if (host->bus_ops->pre_suspend)
2493 err = host->bus_ops->pre_suspend(host);
2494 if (!err)
2495 break;
2497 if (!mmc_card_is_removable(host)) {
2498 dev_warn(mmc_dev(host),
2499 "pre_suspend failed for non-removable host: "
2500 "%d\n", err);
2501 /* Avoid removing non-removable hosts */
2502 break;
2505 /* Calling bus_ops->remove() with a claimed host can deadlock */
2506 host->bus_ops->remove(host);
2507 mmc_claim_host(host);
2508 mmc_detach_bus(host);
2509 mmc_power_off(host);
2510 mmc_release_host(host);
2511 host->pm_flags = 0;
2512 break;
2514 case PM_POST_SUSPEND:
2515 case PM_POST_HIBERNATION:
2516 case PM_POST_RESTORE:
2518 spin_lock_irqsave(&host->lock, flags);
2519 host->rescan_disable = 0;
2520 spin_unlock_irqrestore(&host->lock, flags);
2521 _mmc_detect_change(host, 0, false);
2525 return 0;
2528 void mmc_register_pm_notifier(struct mmc_host *host)
2530 host->pm_notify.notifier_call = mmc_pm_notify;
2531 register_pm_notifier(&host->pm_notify);
2534 void mmc_unregister_pm_notifier(struct mmc_host *host)
2536 unregister_pm_notifier(&host->pm_notify);
2538 #endif
2540 static int __init mmc_init(void)
2542 int ret;
2544 ret = mmc_register_bus();
2545 if (ret)
2546 return ret;
2548 ret = mmc_register_host_class();
2549 if (ret)
2550 goto unregister_bus;
2552 ret = sdio_register_bus();
2553 if (ret)
2554 goto unregister_host_class;
2556 return 0;
2558 unregister_host_class:
2559 mmc_unregister_host_class();
2560 unregister_bus:
2561 mmc_unregister_bus();
2562 return ret;
2565 static void __exit mmc_exit(void)
2567 sdio_unregister_bus();
2568 mmc_unregister_host_class();
2569 mmc_unregister_bus();
2572 subsys_initcall(mmc_init);
2573 module_exit(mmc_exit);
2575 MODULE_LICENSE("GPL");