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/regulator/consumer.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/pm_wakeup.h>
27 #include <linux/suspend.h>
28 #include <linux/fault-inject.h>
29 #include <linux/random.h>
30 #include <linux/slab.h>
33 #include <linux/mmc/card.h>
34 #include <linux/mmc/host.h>
35 #include <linux/mmc/mmc.h>
36 #include <linux/mmc/sd.h>
47 /* If the device is not responding */
48 #define MMC_CORE_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */
51 * Background operations can take a long time, depending on the housekeeping
52 * operations the card has to perform.
54 #define MMC_BKOPS_MAX_TIMEOUT (4 * 60 * 1000) /* max time to wait in ms */
56 static struct workqueue_struct *workqueue;
57 static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
60 * Enabling software CRCs on the data blocks can be a significant (30%)
61 * performance cost, and for other reasons may not always be desired.
62 * So we allow it it to be disabled.
65 module_param(use_spi_crc, bool, 0);
68 * Internal function. Schedule delayed work in the MMC work queue.
70 static int mmc_schedule_delayed_work(struct delayed_work *work,
73 return queue_delayed_work(workqueue, work, delay);
77 * Internal function. Flush all scheduled work from the MMC work queue.
79 static void mmc_flush_scheduled_work(void)
81 flush_workqueue(workqueue);
84 #ifdef CONFIG_FAIL_MMC_REQUEST
87 * Internal function. Inject random data errors.
88 * If mmc_data is NULL no errors are injected.
90 static void mmc_should_fail_request(struct mmc_host *host,
91 struct mmc_request *mrq)
93 struct mmc_command *cmd = mrq->cmd;
94 struct mmc_data *data = mrq->data;
95 static const int data_errors[] = {
104 if (cmd->error || data->error ||
105 !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
108 data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)];
109 data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9;
112 #else /* CONFIG_FAIL_MMC_REQUEST */
114 static inline void mmc_should_fail_request(struct mmc_host *host,
115 struct mmc_request *mrq)
119 #endif /* CONFIG_FAIL_MMC_REQUEST */
122 * mmc_request_done - finish processing an MMC request
123 * @host: MMC host which completed request
124 * @mrq: MMC request which request
126 * MMC drivers should call this function when they have completed
127 * their processing of a request.
129 void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
131 struct mmc_command *cmd = mrq->cmd;
132 int err = cmd->error;
134 if (err && cmd->retries && mmc_host_is_spi(host)) {
135 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
139 if (err && cmd->retries && !mmc_card_removed(host->card)) {
141 * Request starter must handle retries - see
142 * mmc_wait_for_req_done().
147 mmc_should_fail_request(host, mrq);
149 led_trigger_event(host->led, LED_OFF);
151 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
152 mmc_hostname(host), cmd->opcode, err,
153 cmd->resp[0], cmd->resp[1],
154 cmd->resp[2], cmd->resp[3]);
157 pr_debug("%s: %d bytes transferred: %d\n",
159 mrq->data->bytes_xfered, mrq->data->error);
163 pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n",
164 mmc_hostname(host), mrq->stop->opcode,
166 mrq->stop->resp[0], mrq->stop->resp[1],
167 mrq->stop->resp[2], mrq->stop->resp[3]);
173 mmc_host_clk_release(host);
177 EXPORT_SYMBOL(mmc_request_done);
180 mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
182 #ifdef CONFIG_MMC_DEBUG
184 struct scatterlist *sg;
188 pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n",
189 mmc_hostname(host), mrq->sbc->opcode,
190 mrq->sbc->arg, mrq->sbc->flags);
193 pr_debug("%s: starting CMD%u arg %08x flags %08x\n",
194 mmc_hostname(host), mrq->cmd->opcode,
195 mrq->cmd->arg, mrq->cmd->flags);
198 pr_debug("%s: blksz %d blocks %d flags %08x "
199 "tsac %d ms nsac %d\n",
200 mmc_hostname(host), mrq->data->blksz,
201 mrq->data->blocks, mrq->data->flags,
202 mrq->data->timeout_ns / 1000000,
203 mrq->data->timeout_clks);
207 pr_debug("%s: CMD%u arg %08x flags %08x\n",
208 mmc_hostname(host), mrq->stop->opcode,
209 mrq->stop->arg, mrq->stop->flags);
212 WARN_ON(!host->claimed);
217 BUG_ON(mrq->data->blksz > host->max_blk_size);
218 BUG_ON(mrq->data->blocks > host->max_blk_count);
219 BUG_ON(mrq->data->blocks * mrq->data->blksz >
222 #ifdef CONFIG_MMC_DEBUG
224 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
226 BUG_ON(sz != mrq->data->blocks * mrq->data->blksz);
229 mrq->cmd->data = mrq->data;
230 mrq->data->error = 0;
231 mrq->data->mrq = mrq;
233 mrq->data->stop = mrq->stop;
234 mrq->stop->error = 0;
235 mrq->stop->mrq = mrq;
238 mmc_host_clk_hold(host);
239 led_trigger_event(host->led, LED_FULL);
240 host->ops->request(host, mrq);
244 * mmc_start_bkops - start BKOPS for supported cards
245 * @card: MMC card to start BKOPS
246 * @form_exception: A flag to indicate if this function was
247 * called due to an exception raised by the card
249 * Start background operations whenever requested.
250 * When the urgent BKOPS bit is set in a R1 command response
251 * then background operations should be started immediately.
253 void mmc_start_bkops(struct mmc_card *card, bool from_exception)
257 bool use_busy_signal;
261 if (!card->ext_csd.bkops_en || mmc_card_doing_bkops(card))
264 err = mmc_read_bkops_status(card);
266 pr_err("%s: Failed to read bkops status: %d\n",
267 mmc_hostname(card->host), err);
271 if (!card->ext_csd.raw_bkops_status)
274 if (card->ext_csd.raw_bkops_status < EXT_CSD_BKOPS_LEVEL_2 &&
278 mmc_claim_host(card->host);
279 if (card->ext_csd.raw_bkops_status >= EXT_CSD_BKOPS_LEVEL_2) {
280 timeout = MMC_BKOPS_MAX_TIMEOUT;
281 use_busy_signal = true;
284 use_busy_signal = false;
287 err = __mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
288 EXT_CSD_BKOPS_START, 1, timeout, use_busy_signal, true);
290 pr_warn("%s: Error %d starting bkops\n",
291 mmc_hostname(card->host), err);
296 * For urgent bkops status (LEVEL_2 and more)
297 * bkops executed synchronously, otherwise
298 * the operation is in progress
300 if (!use_busy_signal)
301 mmc_card_set_doing_bkops(card);
303 mmc_release_host(card->host);
305 EXPORT_SYMBOL(mmc_start_bkops);
308 * mmc_wait_data_done() - done callback for data request
309 * @mrq: done data request
311 * Wakes up mmc context, passed as a callback to host controller driver
313 static void mmc_wait_data_done(struct mmc_request *mrq)
315 mrq->host->context_info.is_done_rcv = true;
316 wake_up_interruptible(&mrq->host->context_info.wait);
319 static void mmc_wait_done(struct mmc_request *mrq)
321 complete(&mrq->completion);
325 *__mmc_start_data_req() - starts data request
326 * @host: MMC host to start the request
327 * @mrq: data request to start
329 * Sets the done callback to be called when request is completed by the card.
330 * Starts data mmc request execution
332 static int __mmc_start_data_req(struct mmc_host *host, struct mmc_request *mrq)
334 mrq->done = mmc_wait_data_done;
336 if (mmc_card_removed(host->card)) {
337 mrq->cmd->error = -ENOMEDIUM;
338 mmc_wait_data_done(mrq);
341 mmc_start_request(host, mrq);
346 static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
348 init_completion(&mrq->completion);
349 mrq->done = mmc_wait_done;
350 if (mmc_card_removed(host->card)) {
351 mrq->cmd->error = -ENOMEDIUM;
352 complete(&mrq->completion);
355 mmc_start_request(host, mrq);
360 * mmc_wait_for_data_req_done() - wait for request completed
361 * @host: MMC host to prepare the command.
362 * @mrq: MMC request to wait for
364 * Blocks MMC context till host controller will ack end of data request
365 * execution or new request notification arrives from the block layer.
366 * Handles command retries.
368 * Returns enum mmc_blk_status after checking errors.
370 static int mmc_wait_for_data_req_done(struct mmc_host *host,
371 struct mmc_request *mrq,
372 struct mmc_async_req *next_req)
374 struct mmc_command *cmd;
375 struct mmc_context_info *context_info = &host->context_info;
380 wait_event_interruptible(context_info->wait,
381 (context_info->is_done_rcv ||
382 context_info->is_new_req));
383 spin_lock_irqsave(&context_info->lock, flags);
384 context_info->is_waiting_last_req = false;
385 spin_unlock_irqrestore(&context_info->lock, flags);
386 if (context_info->is_done_rcv) {
387 context_info->is_done_rcv = false;
388 context_info->is_new_req = false;
391 if (!cmd->error || !cmd->retries ||
392 mmc_card_removed(host->card)) {
393 err = host->areq->err_check(host->card,
395 break; /* return err */
397 pr_info("%s: req failed (CMD%u): %d, retrying...\n",
399 cmd->opcode, cmd->error);
402 host->ops->request(host, mrq);
403 continue; /* wait for done/new event again */
405 } else if (context_info->is_new_req) {
406 context_info->is_new_req = false;
408 err = MMC_BLK_NEW_REQUEST;
409 break; /* return err */
416 static void mmc_wait_for_req_done(struct mmc_host *host,
417 struct mmc_request *mrq)
419 struct mmc_command *cmd;
422 wait_for_completion(&mrq->completion);
427 * If host has timed out waiting for the sanitize
428 * to complete, card might be still in programming state
429 * so let's try to bring the card out of programming
432 if (cmd->sanitize_busy && cmd->error == -ETIMEDOUT) {
433 if (!mmc_interrupt_hpi(host->card)) {
434 pr_warning("%s: %s: Interrupted sanitize\n",
435 mmc_hostname(host), __func__);
439 pr_err("%s: %s: Failed to interrupt sanitize\n",
440 mmc_hostname(host), __func__);
443 if (!cmd->error || !cmd->retries ||
444 mmc_card_removed(host->card))
447 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
448 mmc_hostname(host), cmd->opcode, cmd->error);
451 host->ops->request(host, mrq);
456 * mmc_pre_req - Prepare for a new request
457 * @host: MMC host to prepare command
458 * @mrq: MMC request to prepare for
459 * @is_first_req: true if there is no previous started request
460 * that may run in parellel to this call, otherwise false
462 * mmc_pre_req() is called in prior to mmc_start_req() to let
463 * host prepare for the new request. Preparation of a request may be
464 * performed while another request is running on the host.
466 static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq,
469 if (host->ops->pre_req) {
470 mmc_host_clk_hold(host);
471 host->ops->pre_req(host, mrq, is_first_req);
472 mmc_host_clk_release(host);
477 * mmc_post_req - Post process a completed request
478 * @host: MMC host to post process command
479 * @mrq: MMC request to post process for
480 * @err: Error, if non zero, clean up any resources made in pre_req
482 * Let the host post process a completed request. Post processing of
483 * a request may be performed while another reuqest is running.
485 static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq,
488 if (host->ops->post_req) {
489 mmc_host_clk_hold(host);
490 host->ops->post_req(host, mrq, err);
491 mmc_host_clk_release(host);
496 * mmc_start_req - start a non-blocking request
497 * @host: MMC host to start command
498 * @areq: async request to start
499 * @error: out parameter returns 0 for success, otherwise non zero
501 * Start a new MMC custom command request for a host.
502 * If there is on ongoing async request wait for completion
503 * of that request and start the new one and return.
504 * Does not wait for the new request to complete.
506 * Returns the completed request, NULL in case of none completed.
507 * Wait for the an ongoing request (previoulsy started) to complete and
508 * return the completed request. If there is no ongoing request, NULL
509 * is returned without waiting. NULL is not an error condition.
511 struct mmc_async_req *mmc_start_req(struct mmc_host *host,
512 struct mmc_async_req *areq, int *error)
516 struct mmc_async_req *data = host->areq;
518 /* Prepare a new request */
520 mmc_pre_req(host, areq->mrq, !host->areq);
523 err = mmc_wait_for_data_req_done(host, host->areq->mrq, areq);
524 if (err == MMC_BLK_NEW_REQUEST) {
528 * The previous request was not completed,
534 * Check BKOPS urgency for each R1 response
536 if (host->card && mmc_card_mmc(host->card) &&
537 ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) ||
538 (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) &&
539 (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT))
540 mmc_start_bkops(host->card, true);
544 start_err = __mmc_start_data_req(host, areq->mrq);
547 mmc_post_req(host, host->areq->mrq, 0);
549 /* Cancel a prepared request if it was not started. */
550 if ((err || start_err) && areq)
551 mmc_post_req(host, areq->mrq, -EINVAL);
562 EXPORT_SYMBOL(mmc_start_req);
565 * mmc_wait_for_req - start a request and wait for completion
566 * @host: MMC host to start command
567 * @mrq: MMC request to start
569 * Start a new MMC custom command request for a host, and wait
570 * for the command to complete. Does not attempt to parse the
573 void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
575 __mmc_start_req(host, mrq);
576 mmc_wait_for_req_done(host, mrq);
578 EXPORT_SYMBOL(mmc_wait_for_req);
581 * mmc_interrupt_hpi - Issue for High priority Interrupt
582 * @card: the MMC card associated with the HPI transfer
584 * Issued High Priority Interrupt, and check for card status
585 * until out-of prg-state.
587 int mmc_interrupt_hpi(struct mmc_card *card)
591 unsigned long prg_wait;
595 if (!card->ext_csd.hpi_en) {
596 pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host));
600 mmc_claim_host(card->host);
601 err = mmc_send_status(card, &status);
603 pr_err("%s: Get card status fail\n", mmc_hostname(card->host));
607 switch (R1_CURRENT_STATE(status)) {
613 * In idle and transfer states, HPI is not needed and the caller
614 * can issue the next intended command immediately
620 /* In all other states, it's illegal to issue HPI */
621 pr_debug("%s: HPI cannot be sent. Card state=%d\n",
622 mmc_hostname(card->host), R1_CURRENT_STATE(status));
627 err = mmc_send_hpi_cmd(card, &status);
631 prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time);
633 err = mmc_send_status(card, &status);
635 if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN)
637 if (time_after(jiffies, prg_wait))
642 mmc_release_host(card->host);
645 EXPORT_SYMBOL(mmc_interrupt_hpi);
648 * mmc_wait_for_cmd - start a command and wait for completion
649 * @host: MMC host to start command
650 * @cmd: MMC command to start
651 * @retries: maximum number of retries
653 * Start a new MMC command for a host, and wait for the command
654 * to complete. Return any error that occurred while the command
655 * was executing. Do not attempt to parse the response.
657 int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
659 struct mmc_request mrq = {NULL};
661 WARN_ON(!host->claimed);
663 memset(cmd->resp, 0, sizeof(cmd->resp));
664 cmd->retries = retries;
669 mmc_wait_for_req(host, &mrq);
674 EXPORT_SYMBOL(mmc_wait_for_cmd);
677 * mmc_stop_bkops - stop ongoing BKOPS
678 * @card: MMC card to check BKOPS
680 * Send HPI command to stop ongoing background operations to
681 * allow rapid servicing of foreground operations, e.g. read/
682 * writes. Wait until the card comes out of the programming state
683 * to avoid errors in servicing read/write requests.
685 int mmc_stop_bkops(struct mmc_card *card)
690 err = mmc_interrupt_hpi(card);
693 * If err is EINVAL, we can't issue an HPI.
694 * It should complete the BKOPS.
696 if (!err || (err == -EINVAL)) {
697 mmc_card_clr_doing_bkops(card);
703 EXPORT_SYMBOL(mmc_stop_bkops);
705 int mmc_read_bkops_status(struct mmc_card *card)
711 * In future work, we should consider storing the entire ext_csd.
713 ext_csd = kmalloc(512, GFP_KERNEL);
715 pr_err("%s: could not allocate buffer to receive the ext_csd.\n",
716 mmc_hostname(card->host));
720 mmc_claim_host(card->host);
721 err = mmc_send_ext_csd(card, ext_csd);
722 mmc_release_host(card->host);
726 card->ext_csd.raw_bkops_status = ext_csd[EXT_CSD_BKOPS_STATUS];
727 card->ext_csd.raw_exception_status = ext_csd[EXT_CSD_EXP_EVENTS_STATUS];
732 EXPORT_SYMBOL(mmc_read_bkops_status);
735 * mmc_set_data_timeout - set the timeout for a data command
736 * @data: data phase for command
737 * @card: the MMC card associated with the data transfer
739 * Computes the data timeout parameters according to the
740 * correct algorithm given the card type.
742 void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
747 * SDIO cards only define an upper 1 s limit on access.
749 if (mmc_card_sdio(card)) {
750 data->timeout_ns = 1000000000;
751 data->timeout_clks = 0;
756 * SD cards use a 100 multiplier rather than 10
758 mult = mmc_card_sd(card) ? 100 : 10;
761 * Scale up the multiplier (and therefore the timeout) by
762 * the r2w factor for writes.
764 if (data->flags & MMC_DATA_WRITE)
765 mult <<= card->csd.r2w_factor;
767 data->timeout_ns = card->csd.tacc_ns * mult;
768 data->timeout_clks = card->csd.tacc_clks * mult;
771 * SD cards also have an upper limit on the timeout.
773 if (mmc_card_sd(card)) {
774 unsigned int timeout_us, limit_us;
776 timeout_us = data->timeout_ns / 1000;
777 if (mmc_host_clk_rate(card->host))
778 timeout_us += data->timeout_clks * 1000 /
779 (mmc_host_clk_rate(card->host) / 1000);
781 if (data->flags & MMC_DATA_WRITE)
783 * The MMC spec "It is strongly recommended
784 * for hosts to implement more than 500ms
785 * timeout value even if the card indicates
786 * the 250ms maximum busy length." Even the
787 * previous value of 300ms is known to be
788 * insufficient for some cards.
795 * SDHC cards always use these fixed values.
797 if (timeout_us > limit_us || mmc_card_blockaddr(card)) {
798 data->timeout_ns = limit_us * 1000;
799 data->timeout_clks = 0;
804 * Some cards require longer data read timeout than indicated in CSD.
805 * Address this by setting the read timeout to a "reasonably high"
806 * value. For the cards tested, 300ms has proven enough. If necessary,
807 * this value can be increased if other problematic cards require this.
809 if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
810 data->timeout_ns = 300000000;
811 data->timeout_clks = 0;
815 * Some cards need very high timeouts if driven in SPI mode.
816 * The worst observed timeout was 900ms after writing a
817 * continuous stream of data until the internal logic
820 if (mmc_host_is_spi(card->host)) {
821 if (data->flags & MMC_DATA_WRITE) {
822 if (data->timeout_ns < 1000000000)
823 data->timeout_ns = 1000000000; /* 1s */
825 if (data->timeout_ns < 100000000)
826 data->timeout_ns = 100000000; /* 100ms */
830 EXPORT_SYMBOL(mmc_set_data_timeout);
833 * mmc_align_data_size - pads a transfer size to a more optimal value
834 * @card: the MMC card associated with the data transfer
835 * @sz: original transfer size
837 * Pads the original data size with a number of extra bytes in
838 * order to avoid controller bugs and/or performance hits
839 * (e.g. some controllers revert to PIO for certain sizes).
841 * Returns the improved size, which might be unmodified.
843 * Note that this function is only relevant when issuing a
844 * single scatter gather entry.
846 unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
849 * FIXME: We don't have a system for the controller to tell
850 * the core about its problems yet, so for now we just 32-bit
853 sz = ((sz + 3) / 4) * 4;
857 EXPORT_SYMBOL(mmc_align_data_size);
860 * __mmc_claim_host - exclusively claim a host
861 * @host: mmc host to claim
862 * @abort: whether or not the operation should be aborted
864 * Claim a host for a set of operations. If @abort is non null and
865 * dereference a non-zero value then this will return prematurely with
866 * that non-zero value without acquiring the lock. Returns zero
867 * with the lock held otherwise.
869 int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
871 DECLARE_WAITQUEUE(wait, current);
877 add_wait_queue(&host->wq, &wait);
878 spin_lock_irqsave(&host->lock, flags);
880 set_current_state(TASK_UNINTERRUPTIBLE);
881 stop = abort ? atomic_read(abort) : 0;
882 if (stop || !host->claimed || host->claimer == current)
884 spin_unlock_irqrestore(&host->lock, flags);
886 spin_lock_irqsave(&host->lock, flags);
888 set_current_state(TASK_RUNNING);
891 host->claimer = current;
892 host->claim_cnt += 1;
895 spin_unlock_irqrestore(&host->lock, flags);
896 remove_wait_queue(&host->wq, &wait);
897 if (host->ops->enable && !stop && host->claim_cnt == 1)
898 host->ops->enable(host);
902 EXPORT_SYMBOL(__mmc_claim_host);
905 * mmc_release_host - release a host
906 * @host: mmc host to release
908 * Release a MMC host, allowing others to claim the host
909 * for their operations.
911 void mmc_release_host(struct mmc_host *host)
915 WARN_ON(!host->claimed);
917 if (host->ops->disable && host->claim_cnt == 1)
918 host->ops->disable(host);
920 spin_lock_irqsave(&host->lock, flags);
921 if (--host->claim_cnt) {
922 /* Release for nested claim */
923 spin_unlock_irqrestore(&host->lock, flags);
926 host->claimer = NULL;
927 spin_unlock_irqrestore(&host->lock, flags);
931 EXPORT_SYMBOL(mmc_release_host);
934 * This is a helper function, which fetches a runtime pm reference for the
935 * card device and also claims the host.
937 void mmc_get_card(struct mmc_card *card)
939 pm_runtime_get_sync(&card->dev);
940 mmc_claim_host(card->host);
942 EXPORT_SYMBOL(mmc_get_card);
945 * This is a helper function, which releases the host and drops the runtime
946 * pm reference for the card device.
948 void mmc_put_card(struct mmc_card *card)
950 mmc_release_host(card->host);
951 pm_runtime_mark_last_busy(&card->dev);
952 pm_runtime_put_autosuspend(&card->dev);
954 EXPORT_SYMBOL(mmc_put_card);
957 * Internal function that does the actual ios call to the host driver,
958 * optionally printing some debug output.
960 static inline void mmc_set_ios(struct mmc_host *host)
962 struct mmc_ios *ios = &host->ios;
964 pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
965 "width %u timing %u\n",
966 mmc_hostname(host), ios->clock, ios->bus_mode,
967 ios->power_mode, ios->chip_select, ios->vdd,
968 ios->bus_width, ios->timing);
971 mmc_set_ungated(host);
972 host->ops->set_ios(host, ios);
976 * Control chip select pin on a host.
978 void mmc_set_chip_select(struct mmc_host *host, int mode)
980 mmc_host_clk_hold(host);
981 host->ios.chip_select = mode;
983 mmc_host_clk_release(host);
987 * Sets the host clock to the highest possible frequency that
990 static void __mmc_set_clock(struct mmc_host *host, unsigned int hz)
992 WARN_ON(hz < host->f_min);
994 if (hz > host->f_max)
997 host->ios.clock = hz;
1001 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
1003 mmc_host_clk_hold(host);
1004 __mmc_set_clock(host, hz);
1005 mmc_host_clk_release(host);
1008 #ifdef CONFIG_MMC_CLKGATE
1010 * This gates the clock by setting it to 0 Hz.
1012 void mmc_gate_clock(struct mmc_host *host)
1014 unsigned long flags;
1016 spin_lock_irqsave(&host->clk_lock, flags);
1017 host->clk_old = host->ios.clock;
1018 host->ios.clock = 0;
1019 host->clk_gated = true;
1020 spin_unlock_irqrestore(&host->clk_lock, flags);
1025 * This restores the clock from gating by using the cached
1028 void mmc_ungate_clock(struct mmc_host *host)
1031 * We should previously have gated the clock, so the clock shall
1032 * be 0 here! The clock may however be 0 during initialization,
1033 * when some request operations are performed before setting
1034 * the frequency. When ungate is requested in that situation
1035 * we just ignore the call.
1037 if (host->clk_old) {
1038 BUG_ON(host->ios.clock);
1039 /* This call will also set host->clk_gated to false */
1040 __mmc_set_clock(host, host->clk_old);
1044 void mmc_set_ungated(struct mmc_host *host)
1046 unsigned long flags;
1049 * We've been given a new frequency while the clock is gated,
1050 * so make sure we regard this as ungating it.
1052 spin_lock_irqsave(&host->clk_lock, flags);
1053 host->clk_gated = false;
1054 spin_unlock_irqrestore(&host->clk_lock, flags);
1058 void mmc_set_ungated(struct mmc_host *host)
1064 * Change the bus mode (open drain/push-pull) of a host.
1066 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
1068 mmc_host_clk_hold(host);
1069 host->ios.bus_mode = mode;
1071 mmc_host_clk_release(host);
1075 * Change data bus width of a host.
1077 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
1079 mmc_host_clk_hold(host);
1080 host->ios.bus_width = width;
1082 mmc_host_clk_release(host);
1086 * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
1087 * @vdd: voltage (mV)
1088 * @low_bits: prefer low bits in boundary cases
1090 * This function returns the OCR bit number according to the provided @vdd
1091 * value. If conversion is not possible a negative errno value returned.
1093 * Depending on the @low_bits flag the function prefers low or high OCR bits
1094 * on boundary voltages. For example,
1095 * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
1096 * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1098 * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1100 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1102 const int max_bit = ilog2(MMC_VDD_35_36);
1105 if (vdd < 1650 || vdd > 3600)
1108 if (vdd >= 1650 && vdd <= 1950)
1109 return ilog2(MMC_VDD_165_195);
1114 /* Base 2000 mV, step 100 mV, bit's base 8. */
1115 bit = (vdd - 2000) / 100 + 8;
1122 * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1123 * @vdd_min: minimum voltage value (mV)
1124 * @vdd_max: maximum voltage value (mV)
1126 * This function returns the OCR mask bits according to the provided @vdd_min
1127 * and @vdd_max values. If conversion is not possible the function returns 0.
1129 * Notes wrt boundary cases:
1130 * This function sets the OCR bits for all boundary voltages, for example
1131 * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1132 * MMC_VDD_34_35 mask.
1134 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1138 if (vdd_max < vdd_min)
1141 /* Prefer high bits for the boundary vdd_max values. */
1142 vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1146 /* Prefer low bits for the boundary vdd_min values. */
1147 vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1151 /* Fill the mask, from max bit to min bit. */
1152 while (vdd_max >= vdd_min)
1153 mask |= 1 << vdd_max--;
1157 EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
1162 * mmc_of_parse_voltage - return mask of supported voltages
1163 * @np: The device node need to be parsed.
1164 * @mask: mask of voltages available for MMC/SD/SDIO
1166 * 1. Return zero on success.
1167 * 2. Return negative errno: voltage-range is invalid.
1169 int mmc_of_parse_voltage(struct device_node *np, u32 *mask)
1171 const u32 *voltage_ranges;
1174 voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges);
1175 num_ranges = num_ranges / sizeof(*voltage_ranges) / 2;
1176 if (!voltage_ranges || !num_ranges) {
1177 pr_info("%s: voltage-ranges unspecified\n", np->full_name);
1181 for (i = 0; i < num_ranges; i++) {
1182 const int j = i * 2;
1185 ocr_mask = mmc_vddrange_to_ocrmask(
1186 be32_to_cpu(voltage_ranges[j]),
1187 be32_to_cpu(voltage_ranges[j + 1]));
1189 pr_err("%s: voltage-range #%d is invalid\n",
1198 EXPORT_SYMBOL(mmc_of_parse_voltage);
1200 #endif /* CONFIG_OF */
1202 #ifdef CONFIG_REGULATOR
1205 * mmc_regulator_get_ocrmask - return mask of supported voltages
1206 * @supply: regulator to use
1208 * This returns either a negative errno, or a mask of voltages that
1209 * can be provided to MMC/SD/SDIO devices using the specified voltage
1210 * regulator. This would normally be called before registering the
1213 int mmc_regulator_get_ocrmask(struct regulator *supply)
1219 count = regulator_count_voltages(supply);
1223 for (i = 0; i < count; i++) {
1227 vdd_uV = regulator_list_voltage(supply, i);
1231 vdd_mV = vdd_uV / 1000;
1232 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1237 EXPORT_SYMBOL_GPL(mmc_regulator_get_ocrmask);
1240 * mmc_regulator_set_ocr - set regulator to match host->ios voltage
1241 * @mmc: the host to regulate
1242 * @supply: regulator to use
1243 * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
1245 * Returns zero on success, else negative errno.
1247 * MMC host drivers may use this to enable or disable a regulator using
1248 * a particular supply voltage. This would normally be called from the
1251 int mmc_regulator_set_ocr(struct mmc_host *mmc,
1252 struct regulator *supply,
1253 unsigned short vdd_bit)
1263 * REVISIT mmc_vddrange_to_ocrmask() may have set some
1264 * bits this regulator doesn't quite support ... don't
1265 * be too picky, most cards and regulators are OK with
1266 * a 0.1V range goof (it's a small error percentage).
1268 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
1270 min_uV = 1650 * 1000;
1271 max_uV = 1950 * 1000;
1273 min_uV = 1900 * 1000 + tmp * 100 * 1000;
1274 max_uV = min_uV + 100 * 1000;
1278 * If we're using a fixed/static regulator, don't call
1279 * regulator_set_voltage; it would fail.
1281 voltage = regulator_get_voltage(supply);
1283 if (!regulator_can_change_voltage(supply))
1284 min_uV = max_uV = voltage;
1288 else if (voltage < min_uV || voltage > max_uV)
1289 result = regulator_set_voltage(supply, min_uV, max_uV);
1293 if (result == 0 && !mmc->regulator_enabled) {
1294 result = regulator_enable(supply);
1296 mmc->regulator_enabled = true;
1298 } else if (mmc->regulator_enabled) {
1299 result = regulator_disable(supply);
1301 mmc->regulator_enabled = false;
1305 dev_err(mmc_dev(mmc),
1306 "could not set regulator OCR (%d)\n", result);
1309 EXPORT_SYMBOL_GPL(mmc_regulator_set_ocr);
1311 int mmc_regulator_get_supply(struct mmc_host *mmc)
1313 struct device *dev = mmc_dev(mmc);
1314 struct regulator *supply;
1317 supply = devm_regulator_get(dev, "vmmc");
1318 mmc->supply.vmmc = supply;
1319 mmc->supply.vqmmc = devm_regulator_get_optional(dev, "vqmmc");
1322 return PTR_ERR(supply);
1324 ret = mmc_regulator_get_ocrmask(supply);
1326 mmc->ocr_avail = ret;
1328 dev_warn(mmc_dev(mmc), "Failed getting OCR mask: %d\n", ret);
1332 EXPORT_SYMBOL_GPL(mmc_regulator_get_supply);
1334 #endif /* CONFIG_REGULATOR */
1337 * Mask off any voltages we don't support and select
1338 * the lowest voltage
1340 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1345 * Sanity check the voltages that the card claims to
1349 dev_warn(mmc_dev(host),
1350 "card claims to support voltages below defined range\n");
1354 ocr &= host->ocr_avail;
1356 dev_warn(mmc_dev(host), "no support for card's volts\n");
1360 if (host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) {
1363 mmc_power_cycle(host, ocr);
1367 if (bit != host->ios.vdd)
1368 dev_warn(mmc_dev(host), "exceeding card's volts\n");
1374 int __mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage)
1377 int old_signal_voltage = host->ios.signal_voltage;
1379 host->ios.signal_voltage = signal_voltage;
1380 if (host->ops->start_signal_voltage_switch) {
1381 mmc_host_clk_hold(host);
1382 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1383 mmc_host_clk_release(host);
1387 host->ios.signal_voltage = old_signal_voltage;
1393 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, u32 ocr)
1395 struct mmc_command cmd = {0};
1402 * Send CMD11 only if the request is to switch the card to
1405 if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
1406 return __mmc_set_signal_voltage(host, signal_voltage);
1409 * If we cannot switch voltages, return failure so the caller
1410 * can continue without UHS mode
1412 if (!host->ops->start_signal_voltage_switch)
1414 if (!host->ops->card_busy)
1415 pr_warning("%s: cannot verify signal voltage switch\n",
1416 mmc_hostname(host));
1418 cmd.opcode = SD_SWITCH_VOLTAGE;
1420 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1422 err = mmc_wait_for_cmd(host, &cmd, 0);
1426 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1429 mmc_host_clk_hold(host);
1431 * The card should drive cmd and dat[0:3] low immediately
1432 * after the response of cmd11, but wait 1 ms to be sure
1435 if (host->ops->card_busy && !host->ops->card_busy(host)) {
1440 * During a signal voltage level switch, the clock must be gated
1441 * for 5 ms according to the SD spec
1443 clock = host->ios.clock;
1444 host->ios.clock = 0;
1447 if (__mmc_set_signal_voltage(host, signal_voltage)) {
1449 * Voltages may not have been switched, but we've already
1450 * sent CMD11, so a power cycle is required anyway
1456 /* Keep clock gated for at least 5 ms */
1458 host->ios.clock = clock;
1461 /* Wait for at least 1 ms according to spec */
1465 * Failure to switch is indicated by the card holding
1468 if (host->ops->card_busy && host->ops->card_busy(host))
1473 pr_debug("%s: Signal voltage switch failed, "
1474 "power cycling card\n", mmc_hostname(host));
1475 mmc_power_cycle(host, ocr);
1478 mmc_host_clk_release(host);
1484 * Select timing parameters for host.
1486 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1488 mmc_host_clk_hold(host);
1489 host->ios.timing = timing;
1491 mmc_host_clk_release(host);
1495 * Select appropriate driver type for host.
1497 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1499 mmc_host_clk_hold(host);
1500 host->ios.drv_type = drv_type;
1502 mmc_host_clk_release(host);
1506 * Apply power to the MMC stack. This is a two-stage process.
1507 * First, we enable power to the card without the clock running.
1508 * We then wait a bit for the power to stabilise. Finally,
1509 * enable the bus drivers and clock to the card.
1511 * We must _NOT_ enable the clock prior to power stablising.
1513 * If a host does all the power sequencing itself, ignore the
1514 * initial MMC_POWER_UP stage.
1516 void mmc_power_up(struct mmc_host *host, u32 ocr)
1518 if (host->ios.power_mode == MMC_POWER_ON)
1521 mmc_host_clk_hold(host);
1523 host->ios.vdd = fls(ocr) - 1;
1524 if (mmc_host_is_spi(host))
1525 host->ios.chip_select = MMC_CS_HIGH;
1527 host->ios.chip_select = MMC_CS_DONTCARE;
1528 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1529 host->ios.power_mode = MMC_POWER_UP;
1530 host->ios.bus_width = MMC_BUS_WIDTH_1;
1531 host->ios.timing = MMC_TIMING_LEGACY;
1534 /* Set signal voltage to 3.3V */
1535 __mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330);
1538 * This delay should be sufficient to allow the power supply
1539 * to reach the minimum voltage.
1543 host->ios.clock = host->f_init;
1545 host->ios.power_mode = MMC_POWER_ON;
1549 * This delay must be at least 74 clock sizes, or 1 ms, or the
1550 * time required to reach a stable voltage.
1554 mmc_host_clk_release(host);
1557 void mmc_power_off(struct mmc_host *host)
1559 if (host->ios.power_mode == MMC_POWER_OFF)
1562 mmc_host_clk_hold(host);
1564 host->ios.clock = 0;
1567 if (!mmc_host_is_spi(host)) {
1568 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
1569 host->ios.chip_select = MMC_CS_DONTCARE;
1571 host->ios.power_mode = MMC_POWER_OFF;
1572 host->ios.bus_width = MMC_BUS_WIDTH_1;
1573 host->ios.timing = MMC_TIMING_LEGACY;
1577 * Some configurations, such as the 802.11 SDIO card in the OLPC
1578 * XO-1.5, require a short delay after poweroff before the card
1579 * can be successfully turned on again.
1583 mmc_host_clk_release(host);
1586 void mmc_power_cycle(struct mmc_host *host, u32 ocr)
1588 mmc_power_off(host);
1589 /* Wait at least 1 ms according to SD spec */
1591 mmc_power_up(host, ocr);
1595 * Cleanup when the last reference to the bus operator is dropped.
1597 static void __mmc_release_bus(struct mmc_host *host)
1600 BUG_ON(host->bus_refs);
1601 BUG_ON(!host->bus_dead);
1603 host->bus_ops = NULL;
1607 * Increase reference count of bus operator
1609 static inline void mmc_bus_get(struct mmc_host *host)
1611 unsigned long flags;
1613 spin_lock_irqsave(&host->lock, flags);
1615 spin_unlock_irqrestore(&host->lock, flags);
1619 * Decrease reference count of bus operator and free it if
1620 * it is the last reference.
1622 static inline void mmc_bus_put(struct mmc_host *host)
1624 unsigned long flags;
1626 spin_lock_irqsave(&host->lock, flags);
1628 if ((host->bus_refs == 0) && host->bus_ops)
1629 __mmc_release_bus(host);
1630 spin_unlock_irqrestore(&host->lock, flags);
1634 * Assign a mmc bus handler to a host. Only one bus handler may control a
1635 * host at any given time.
1637 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1639 unsigned long flags;
1644 WARN_ON(!host->claimed);
1646 spin_lock_irqsave(&host->lock, flags);
1648 BUG_ON(host->bus_ops);
1649 BUG_ON(host->bus_refs);
1651 host->bus_ops = ops;
1655 spin_unlock_irqrestore(&host->lock, flags);
1659 * Remove the current bus handler from a host.
1661 void mmc_detach_bus(struct mmc_host *host)
1663 unsigned long flags;
1667 WARN_ON(!host->claimed);
1668 WARN_ON(!host->bus_ops);
1670 spin_lock_irqsave(&host->lock, flags);
1674 spin_unlock_irqrestore(&host->lock, flags);
1679 static void _mmc_detect_change(struct mmc_host *host, unsigned long delay,
1682 #ifdef CONFIG_MMC_DEBUG
1683 unsigned long flags;
1684 spin_lock_irqsave(&host->lock, flags);
1685 WARN_ON(host->removed);
1686 spin_unlock_irqrestore(&host->lock, flags);
1690 * If the device is configured as wakeup, we prevent a new sleep for
1691 * 5 s to give provision for user space to consume the event.
1693 if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) &&
1694 device_can_wakeup(mmc_dev(host)))
1695 pm_wakeup_event(mmc_dev(host), 5000);
1697 host->detect_change = 1;
1698 mmc_schedule_delayed_work(&host->detect, delay);
1702 * mmc_detect_change - process change of state on a MMC socket
1703 * @host: host which changed state.
1704 * @delay: optional delay to wait before detection (jiffies)
1706 * MMC drivers should call this when they detect a card has been
1707 * inserted or removed. The MMC layer will confirm that any
1708 * present card is still functional, and initialize any newly
1711 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1713 _mmc_detect_change(host, delay, true);
1715 EXPORT_SYMBOL(mmc_detect_change);
1717 void mmc_init_erase(struct mmc_card *card)
1721 if (is_power_of_2(card->erase_size))
1722 card->erase_shift = ffs(card->erase_size) - 1;
1724 card->erase_shift = 0;
1727 * It is possible to erase an arbitrarily large area of an SD or MMC
1728 * card. That is not desirable because it can take a long time
1729 * (minutes) potentially delaying more important I/O, and also the
1730 * timeout calculations become increasingly hugely over-estimated.
1731 * Consequently, 'pref_erase' is defined as a guide to limit erases
1732 * to that size and alignment.
1734 * For SD cards that define Allocation Unit size, limit erases to one
1735 * Allocation Unit at a time. For MMC cards that define High Capacity
1736 * Erase Size, whether it is switched on or not, limit to that size.
1737 * Otherwise just have a stab at a good value. For modern cards it
1738 * will end up being 4MiB. Note that if the value is too small, it
1739 * can end up taking longer to erase.
1741 if (mmc_card_sd(card) && card->ssr.au) {
1742 card->pref_erase = card->ssr.au;
1743 card->erase_shift = ffs(card->ssr.au) - 1;
1744 } else if (card->ext_csd.hc_erase_size) {
1745 card->pref_erase = card->ext_csd.hc_erase_size;
1747 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1749 card->pref_erase = 512 * 1024 / 512;
1751 card->pref_erase = 1024 * 1024 / 512;
1753 card->pref_erase = 2 * 1024 * 1024 / 512;
1755 card->pref_erase = 4 * 1024 * 1024 / 512;
1756 if (card->pref_erase < card->erase_size)
1757 card->pref_erase = card->erase_size;
1759 sz = card->pref_erase % card->erase_size;
1761 card->pref_erase += card->erase_size - sz;
1766 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1767 unsigned int arg, unsigned int qty)
1769 unsigned int erase_timeout;
1771 if (arg == MMC_DISCARD_ARG ||
1772 (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) {
1773 erase_timeout = card->ext_csd.trim_timeout;
1774 } else if (card->ext_csd.erase_group_def & 1) {
1775 /* High Capacity Erase Group Size uses HC timeouts */
1776 if (arg == MMC_TRIM_ARG)
1777 erase_timeout = card->ext_csd.trim_timeout;
1779 erase_timeout = card->ext_csd.hc_erase_timeout;
1781 /* CSD Erase Group Size uses write timeout */
1782 unsigned int mult = (10 << card->csd.r2w_factor);
1783 unsigned int timeout_clks = card->csd.tacc_clks * mult;
1784 unsigned int timeout_us;
1786 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
1787 if (card->csd.tacc_ns < 1000000)
1788 timeout_us = (card->csd.tacc_ns * mult) / 1000;
1790 timeout_us = (card->csd.tacc_ns / 1000) * mult;
1793 * ios.clock is only a target. The real clock rate might be
1794 * less but not that much less, so fudge it by multiplying by 2.
1797 timeout_us += (timeout_clks * 1000) /
1798 (mmc_host_clk_rate(card->host) / 1000);
1800 erase_timeout = timeout_us / 1000;
1803 * Theoretically, the calculation could underflow so round up
1804 * to 1ms in that case.
1810 /* Multiplier for secure operations */
1811 if (arg & MMC_SECURE_ARGS) {
1812 if (arg == MMC_SECURE_ERASE_ARG)
1813 erase_timeout *= card->ext_csd.sec_erase_mult;
1815 erase_timeout *= card->ext_csd.sec_trim_mult;
1818 erase_timeout *= qty;
1821 * Ensure at least a 1 second timeout for SPI as per
1822 * 'mmc_set_data_timeout()'
1824 if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
1825 erase_timeout = 1000;
1827 return erase_timeout;
1830 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
1834 unsigned int erase_timeout;
1836 if (card->ssr.erase_timeout) {
1837 /* Erase timeout specified in SD Status Register (SSR) */
1838 erase_timeout = card->ssr.erase_timeout * qty +
1839 card->ssr.erase_offset;
1842 * Erase timeout not specified in SD Status Register (SSR) so
1843 * use 250ms per write block.
1845 erase_timeout = 250 * qty;
1848 /* Must not be less than 1 second */
1849 if (erase_timeout < 1000)
1850 erase_timeout = 1000;
1852 return erase_timeout;
1855 static unsigned int mmc_erase_timeout(struct mmc_card *card,
1859 if (mmc_card_sd(card))
1860 return mmc_sd_erase_timeout(card, arg, qty);
1862 return mmc_mmc_erase_timeout(card, arg, qty);
1865 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
1866 unsigned int to, unsigned int arg)
1868 struct mmc_command cmd = {0};
1869 unsigned int qty = 0;
1870 unsigned long timeout;
1874 * qty is used to calculate the erase timeout which depends on how many
1875 * erase groups (or allocation units in SD terminology) are affected.
1876 * We count erasing part of an erase group as one erase group.
1877 * For SD, the allocation units are always a power of 2. For MMC, the
1878 * erase group size is almost certainly also power of 2, but it does not
1879 * seem to insist on that in the JEDEC standard, so we fall back to
1880 * division in that case. SD may not specify an allocation unit size,
1881 * in which case the timeout is based on the number of write blocks.
1883 * Note that the timeout for secure trim 2 will only be correct if the
1884 * number of erase groups specified is the same as the total of all
1885 * preceding secure trim 1 commands. Since the power may have been
1886 * lost since the secure trim 1 commands occurred, it is generally
1887 * impossible to calculate the secure trim 2 timeout correctly.
1889 if (card->erase_shift)
1890 qty += ((to >> card->erase_shift) -
1891 (from >> card->erase_shift)) + 1;
1892 else if (mmc_card_sd(card))
1893 qty += to - from + 1;
1895 qty += ((to / card->erase_size) -
1896 (from / card->erase_size)) + 1;
1898 if (!mmc_card_blockaddr(card)) {
1903 if (mmc_card_sd(card))
1904 cmd.opcode = SD_ERASE_WR_BLK_START;
1906 cmd.opcode = MMC_ERASE_GROUP_START;
1908 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1909 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1911 pr_err("mmc_erase: group start error %d, "
1912 "status %#x\n", err, cmd.resp[0]);
1917 memset(&cmd, 0, sizeof(struct mmc_command));
1918 if (mmc_card_sd(card))
1919 cmd.opcode = SD_ERASE_WR_BLK_END;
1921 cmd.opcode = MMC_ERASE_GROUP_END;
1923 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1924 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1926 pr_err("mmc_erase: group end error %d, status %#x\n",
1932 memset(&cmd, 0, sizeof(struct mmc_command));
1933 cmd.opcode = MMC_ERASE;
1935 cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1936 cmd.cmd_timeout_ms = mmc_erase_timeout(card, arg, qty);
1937 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1939 pr_err("mmc_erase: erase error %d, status %#x\n",
1945 if (mmc_host_is_spi(card->host))
1948 timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS);
1950 memset(&cmd, 0, sizeof(struct mmc_command));
1951 cmd.opcode = MMC_SEND_STATUS;
1952 cmd.arg = card->rca << 16;
1953 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1954 /* Do not retry else we can't see errors */
1955 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1956 if (err || (cmd.resp[0] & 0xFDF92000)) {
1957 pr_err("error %d requesting status %#x\n",
1963 /* Timeout if the device never becomes ready for data and
1964 * never leaves the program state.
1966 if (time_after(jiffies, timeout)) {
1967 pr_err("%s: Card stuck in programming state! %s\n",
1968 mmc_hostname(card->host), __func__);
1973 } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
1974 (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG));
1980 * mmc_erase - erase sectors.
1981 * @card: card to erase
1982 * @from: first sector to erase
1983 * @nr: number of sectors to erase
1984 * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
1986 * Caller must claim host before calling this function.
1988 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
1991 unsigned int rem, to = from + nr;
1993 if (!(card->host->caps & MMC_CAP_ERASE) ||
1994 !(card->csd.cmdclass & CCC_ERASE))
1997 if (!card->erase_size)
2000 if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
2003 if ((arg & MMC_SECURE_ARGS) &&
2004 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
2007 if ((arg & MMC_TRIM_ARGS) &&
2008 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
2011 if (arg == MMC_SECURE_ERASE_ARG) {
2012 if (from % card->erase_size || nr % card->erase_size)
2016 if (arg == MMC_ERASE_ARG) {
2017 rem = from % card->erase_size;
2019 rem = card->erase_size - rem;
2026 rem = nr % card->erase_size;
2039 /* 'from' and 'to' are inclusive */
2042 return mmc_do_erase(card, from, to, arg);
2044 EXPORT_SYMBOL(mmc_erase);
2046 int mmc_can_erase(struct mmc_card *card)
2048 if ((card->host->caps & MMC_CAP_ERASE) &&
2049 (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
2053 EXPORT_SYMBOL(mmc_can_erase);
2055 int mmc_can_trim(struct mmc_card *card)
2057 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN)
2061 EXPORT_SYMBOL(mmc_can_trim);
2063 int mmc_can_discard(struct mmc_card *card)
2066 * As there's no way to detect the discard support bit at v4.5
2067 * use the s/w feature support filed.
2069 if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
2073 EXPORT_SYMBOL(mmc_can_discard);
2075 int mmc_can_sanitize(struct mmc_card *card)
2077 if (!mmc_can_trim(card) && !mmc_can_erase(card))
2079 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
2083 EXPORT_SYMBOL(mmc_can_sanitize);
2085 int mmc_can_secure_erase_trim(struct mmc_card *card)
2087 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)
2091 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
2093 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
2096 if (!card->erase_size)
2098 if (from % card->erase_size || nr % card->erase_size)
2102 EXPORT_SYMBOL(mmc_erase_group_aligned);
2104 static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
2107 struct mmc_host *host = card->host;
2108 unsigned int max_discard, x, y, qty = 0, max_qty, timeout;
2109 unsigned int last_timeout = 0;
2111 if (card->erase_shift)
2112 max_qty = UINT_MAX >> card->erase_shift;
2113 else if (mmc_card_sd(card))
2116 max_qty = UINT_MAX / card->erase_size;
2118 /* Find the largest qty with an OK timeout */
2121 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
2122 timeout = mmc_erase_timeout(card, arg, qty + x);
2123 if (timeout > host->max_discard_to)
2125 if (timeout < last_timeout)
2127 last_timeout = timeout;
2139 /* Convert qty to sectors */
2140 if (card->erase_shift)
2141 max_discard = --qty << card->erase_shift;
2142 else if (mmc_card_sd(card))
2145 max_discard = --qty * card->erase_size;
2150 unsigned int mmc_calc_max_discard(struct mmc_card *card)
2152 struct mmc_host *host = card->host;
2153 unsigned int max_discard, max_trim;
2155 if (!host->max_discard_to)
2159 * Without erase_group_def set, MMC erase timeout depends on clock
2160 * frequence which can change. In that case, the best choice is
2161 * just the preferred erase size.
2163 if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
2164 return card->pref_erase;
2166 max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
2167 if (mmc_can_trim(card)) {
2168 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
2169 if (max_trim < max_discard)
2170 max_discard = max_trim;
2171 } else if (max_discard < card->erase_size) {
2174 pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
2175 mmc_hostname(host), max_discard, host->max_discard_to);
2178 EXPORT_SYMBOL(mmc_calc_max_discard);
2180 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
2182 struct mmc_command cmd = {0};
2184 if (mmc_card_blockaddr(card) || mmc_card_ddr_mode(card))
2187 cmd.opcode = MMC_SET_BLOCKLEN;
2189 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2190 return mmc_wait_for_cmd(card->host, &cmd, 5);
2192 EXPORT_SYMBOL(mmc_set_blocklen);
2194 int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount,
2197 struct mmc_command cmd = {0};
2199 cmd.opcode = MMC_SET_BLOCK_COUNT;
2200 cmd.arg = blockcount & 0x0000FFFF;
2203 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2204 return mmc_wait_for_cmd(card->host, &cmd, 5);
2206 EXPORT_SYMBOL(mmc_set_blockcount);
2208 static void mmc_hw_reset_for_init(struct mmc_host *host)
2210 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2212 mmc_host_clk_hold(host);
2213 host->ops->hw_reset(host);
2214 mmc_host_clk_release(host);
2217 int mmc_can_reset(struct mmc_card *card)
2221 if (!mmc_card_mmc(card))
2223 rst_n_function = card->ext_csd.rst_n_function;
2224 if ((rst_n_function & EXT_CSD_RST_N_EN_MASK) != EXT_CSD_RST_N_ENABLED)
2228 EXPORT_SYMBOL(mmc_can_reset);
2230 static int mmc_do_hw_reset(struct mmc_host *host, int check)
2232 struct mmc_card *card = host->card;
2234 if (!host->bus_ops->power_restore)
2237 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2243 if (!mmc_can_reset(card))
2246 mmc_host_clk_hold(host);
2247 mmc_set_clock(host, host->f_init);
2249 host->ops->hw_reset(host);
2251 /* If the reset has happened, then a status command will fail */
2253 struct mmc_command cmd = {0};
2256 cmd.opcode = MMC_SEND_STATUS;
2257 if (!mmc_host_is_spi(card->host))
2258 cmd.arg = card->rca << 16;
2259 cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
2260 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2262 mmc_host_clk_release(host);
2267 host->card->state &= ~(MMC_STATE_HIGHSPEED | MMC_STATE_HIGHSPEED_DDR);
2268 if (mmc_host_is_spi(host)) {
2269 host->ios.chip_select = MMC_CS_HIGH;
2270 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
2272 host->ios.chip_select = MMC_CS_DONTCARE;
2273 host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
2275 host->ios.bus_width = MMC_BUS_WIDTH_1;
2276 host->ios.timing = MMC_TIMING_LEGACY;
2279 mmc_host_clk_release(host);
2281 return host->bus_ops->power_restore(host);
2284 int mmc_hw_reset(struct mmc_host *host)
2286 return mmc_do_hw_reset(host, 0);
2288 EXPORT_SYMBOL(mmc_hw_reset);
2290 int mmc_hw_reset_check(struct mmc_host *host)
2292 return mmc_do_hw_reset(host, 1);
2294 EXPORT_SYMBOL(mmc_hw_reset_check);
2296 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2298 host->f_init = freq;
2300 #ifdef CONFIG_MMC_DEBUG
2301 pr_info("%s: %s: trying to init card at %u Hz\n",
2302 mmc_hostname(host), __func__, host->f_init);
2304 mmc_power_up(host, host->ocr_avail);
2307 * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2308 * do a hardware reset if possible.
2310 mmc_hw_reset_for_init(host);
2313 * sdio_reset sends CMD52 to reset card. Since we do not know
2314 * if the card is being re-initialized, just send it. CMD52
2315 * should be ignored by SD/eMMC cards.
2320 mmc_send_if_cond(host, host->ocr_avail);
2322 /* Order's important: probe SDIO, then SD, then MMC */
2323 if (!mmc_attach_sdio(host))
2325 if (!mmc_attach_sd(host))
2327 if (!mmc_attach_mmc(host))
2330 mmc_power_off(host);
2334 int _mmc_detect_card_removed(struct mmc_host *host)
2338 if ((host->caps & MMC_CAP_NONREMOVABLE) || !host->bus_ops->alive)
2341 if (!host->card || mmc_card_removed(host->card))
2344 ret = host->bus_ops->alive(host);
2347 * Card detect status and alive check may be out of sync if card is
2348 * removed slowly, when card detect switch changes while card/slot
2349 * pads are still contacted in hardware (refer to "SD Card Mechanical
2350 * Addendum, Appendix C: Card Detection Switch"). So reschedule a
2351 * detect work 200ms later for this case.
2353 if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) {
2354 mmc_detect_change(host, msecs_to_jiffies(200));
2355 pr_debug("%s: card removed too slowly\n", mmc_hostname(host));
2359 mmc_card_set_removed(host->card);
2360 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2366 int mmc_detect_card_removed(struct mmc_host *host)
2368 struct mmc_card *card = host->card;
2371 WARN_ON(!host->claimed);
2376 ret = mmc_card_removed(card);
2378 * The card will be considered unchanged unless we have been asked to
2379 * detect a change or host requires polling to provide card detection.
2381 if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
2384 host->detect_change = 0;
2386 ret = _mmc_detect_card_removed(host);
2387 if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) {
2389 * Schedule a detect work as soon as possible to let a
2390 * rescan handle the card removal.
2392 cancel_delayed_work(&host->detect);
2393 _mmc_detect_change(host, 0, false);
2399 EXPORT_SYMBOL(mmc_detect_card_removed);
2401 void mmc_rescan(struct work_struct *work)
2403 struct mmc_host *host =
2404 container_of(work, struct mmc_host, detect.work);
2407 if (host->rescan_disable)
2410 /* If there is a non-removable card registered, only scan once */
2411 if ((host->caps & MMC_CAP_NONREMOVABLE) && host->rescan_entered)
2413 host->rescan_entered = 1;
2418 * if there is a _removable_ card registered, check whether it is
2421 if (host->bus_ops && host->bus_ops->detect && !host->bus_dead
2422 && !(host->caps & MMC_CAP_NONREMOVABLE))
2423 host->bus_ops->detect(host);
2425 host->detect_change = 0;
2428 * Let mmc_bus_put() free the bus/bus_ops if we've found that
2429 * the card is no longer present.
2434 /* if there still is a card present, stop here */
2435 if (host->bus_ops != NULL) {
2441 * Only we can add a new handler, so it's safe to
2442 * release the lock here.
2446 if (!(host->caps & MMC_CAP_NONREMOVABLE) && host->ops->get_cd &&
2447 host->ops->get_cd(host) == 0) {
2448 mmc_claim_host(host);
2449 mmc_power_off(host);
2450 mmc_release_host(host);
2454 mmc_claim_host(host);
2455 for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2456 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2458 if (freqs[i] <= host->f_min)
2461 mmc_release_host(host);
2464 if (host->caps & MMC_CAP_NEEDS_POLL)
2465 mmc_schedule_delayed_work(&host->detect, HZ);
2468 void mmc_start_host(struct mmc_host *host)
2470 host->f_init = max(freqs[0], host->f_min);
2471 host->rescan_disable = 0;
2472 if (host->caps2 & MMC_CAP2_NO_PRESCAN_POWERUP)
2473 mmc_power_off(host);
2475 mmc_power_up(host, host->ocr_avail);
2476 _mmc_detect_change(host, 0, false);
2479 void mmc_stop_host(struct mmc_host *host)
2481 #ifdef CONFIG_MMC_DEBUG
2482 unsigned long flags;
2483 spin_lock_irqsave(&host->lock, flags);
2485 spin_unlock_irqrestore(&host->lock, flags);
2488 host->rescan_disable = 1;
2489 cancel_delayed_work_sync(&host->detect);
2490 mmc_flush_scheduled_work();
2492 /* clear pm flags now and let card drivers set them as needed */
2496 if (host->bus_ops && !host->bus_dead) {
2497 /* Calling bus_ops->remove() with a claimed host can deadlock */
2498 host->bus_ops->remove(host);
2499 mmc_claim_host(host);
2500 mmc_detach_bus(host);
2501 mmc_power_off(host);
2502 mmc_release_host(host);
2510 mmc_power_off(host);
2513 int mmc_power_save_host(struct mmc_host *host)
2517 #ifdef CONFIG_MMC_DEBUG
2518 pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__);
2523 if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
2528 if (host->bus_ops->power_save)
2529 ret = host->bus_ops->power_save(host);
2533 mmc_power_off(host);
2537 EXPORT_SYMBOL(mmc_power_save_host);
2539 int mmc_power_restore_host(struct mmc_host *host)
2543 #ifdef CONFIG_MMC_DEBUG
2544 pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__);
2549 if (!host->bus_ops || host->bus_dead || !host->bus_ops->power_restore) {
2554 mmc_power_up(host, host->card->ocr);
2555 ret = host->bus_ops->power_restore(host);
2561 EXPORT_SYMBOL(mmc_power_restore_host);
2564 * Flush the cache to the non-volatile storage.
2566 int mmc_flush_cache(struct mmc_card *card)
2568 struct mmc_host *host = card->host;
2571 if (!(host->caps2 & MMC_CAP2_CACHE_CTRL))
2574 if (mmc_card_mmc(card) &&
2575 (card->ext_csd.cache_size > 0) &&
2576 (card->ext_csd.cache_ctrl & 1)) {
2577 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2578 EXT_CSD_FLUSH_CACHE, 1, 0);
2580 pr_err("%s: cache flush error %d\n",
2581 mmc_hostname(card->host), err);
2586 EXPORT_SYMBOL(mmc_flush_cache);
2589 * Turn the cache ON/OFF.
2590 * Turning the cache OFF shall trigger flushing of the data
2591 * to the non-volatile storage.
2592 * This function should be called with host claimed
2594 int mmc_cache_ctrl(struct mmc_host *host, u8 enable)
2596 struct mmc_card *card = host->card;
2597 unsigned int timeout;
2600 if (!(host->caps2 & MMC_CAP2_CACHE_CTRL) ||
2601 mmc_card_is_removable(host))
2604 if (card && mmc_card_mmc(card) &&
2605 (card->ext_csd.cache_size > 0)) {
2608 if (card->ext_csd.cache_ctrl ^ enable) {
2609 timeout = enable ? card->ext_csd.generic_cmd6_time : 0;
2610 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2611 EXT_CSD_CACHE_CTRL, enable, timeout);
2613 pr_err("%s: cache %s error %d\n",
2614 mmc_hostname(card->host),
2615 enable ? "on" : "off",
2618 card->ext_csd.cache_ctrl = enable;
2624 EXPORT_SYMBOL(mmc_cache_ctrl);
2628 /* Do the card removal on suspend if card is assumed removeable
2629 * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2632 int mmc_pm_notify(struct notifier_block *notify_block,
2633 unsigned long mode, void *unused)
2635 struct mmc_host *host = container_of(
2636 notify_block, struct mmc_host, pm_notify);
2637 unsigned long flags;
2641 case PM_HIBERNATION_PREPARE:
2642 case PM_SUSPEND_PREPARE:
2643 spin_lock_irqsave(&host->lock, flags);
2644 host->rescan_disable = 1;
2645 spin_unlock_irqrestore(&host->lock, flags);
2646 cancel_delayed_work_sync(&host->detect);
2651 /* Validate prerequisites for suspend */
2652 if (host->bus_ops->pre_suspend)
2653 err = host->bus_ops->pre_suspend(host);
2654 if (!err && host->bus_ops->suspend)
2657 /* Calling bus_ops->remove() with a claimed host can deadlock */
2658 host->bus_ops->remove(host);
2659 mmc_claim_host(host);
2660 mmc_detach_bus(host);
2661 mmc_power_off(host);
2662 mmc_release_host(host);
2666 case PM_POST_SUSPEND:
2667 case PM_POST_HIBERNATION:
2668 case PM_POST_RESTORE:
2670 spin_lock_irqsave(&host->lock, flags);
2671 host->rescan_disable = 0;
2672 spin_unlock_irqrestore(&host->lock, flags);
2673 _mmc_detect_change(host, 0, false);
2682 * mmc_init_context_info() - init synchronization context
2685 * Init struct context_info needed to implement asynchronous
2686 * request mechanism, used by mmc core, host driver and mmc requests
2689 void mmc_init_context_info(struct mmc_host *host)
2691 spin_lock_init(&host->context_info.lock);
2692 host->context_info.is_new_req = false;
2693 host->context_info.is_done_rcv = false;
2694 host->context_info.is_waiting_last_req = false;
2695 init_waitqueue_head(&host->context_info.wait);
2698 static int __init mmc_init(void)
2702 workqueue = alloc_ordered_workqueue("kmmcd", 0);
2706 ret = mmc_register_bus();
2708 goto destroy_workqueue;
2710 ret = mmc_register_host_class();
2712 goto unregister_bus;
2714 ret = sdio_register_bus();
2716 goto unregister_host_class;
2720 unregister_host_class:
2721 mmc_unregister_host_class();
2723 mmc_unregister_bus();
2725 destroy_workqueue(workqueue);
2730 static void __exit mmc_exit(void)
2732 sdio_unregister_bus();
2733 mmc_unregister_host_class();
2734 mmc_unregister_bus();
2735 destroy_workqueue(workqueue);
2738 subsys_initcall(mmc_init);
2739 module_exit(mmc_exit);
2741 MODULE_LICENSE("GPL");