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 #define CREATE_TRACE_POINTS
34 #include <trace/events/mmc.h>
36 #include <linux/mmc/card.h>
37 #include <linux/mmc/host.h>
38 #include <linux/mmc/mmc.h>
39 #include <linux/mmc/sd.h>
40 #include <linux/mmc/slot-gpio.h>
52 EXPORT_TRACEPOINT_SYMBOL_GPL(mmc_blk_erase_start);
53 EXPORT_TRACEPOINT_SYMBOL_GPL(mmc_blk_erase_end);
54 EXPORT_TRACEPOINT_SYMBOL_GPL(mmc_blk_rw_start);
55 EXPORT_TRACEPOINT_SYMBOL_GPL(mmc_blk_rw_end);
57 /* If the device is not responding */
58 #define MMC_CORE_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */
61 * Background operations can take a long time, depending on the housekeeping
62 * operations the card has to perform.
64 #define MMC_BKOPS_MAX_TIMEOUT (4 * 60 * 1000) /* max time to wait in ms */
67 * Enabling software CRCs on the data blocks can be a significant (30%)
68 * performance cost, and for other reasons may not always be desired.
69 * So we allow it it to be disabled.
72 module_param(use_spi_crc, bool, 0);
74 static int mmc_schedule_delayed_work(struct delayed_work *work,
78 * We use the system_freezable_wq, because of two reasons.
79 * First, it allows several works (not the same work item) to be
80 * executed simultaneously. Second, the queue becomes frozen when
81 * userspace becomes frozen during system PM.
83 return queue_delayed_work(system_freezable_wq, work, delay);
86 #ifdef CONFIG_FAIL_MMC_REQUEST
89 * Internal function. Inject random data errors.
90 * If mmc_data is NULL no errors are injected.
92 static void mmc_should_fail_request(struct mmc_host *host,
93 struct mmc_request *mrq)
95 struct mmc_command *cmd = mrq->cmd;
96 struct mmc_data *data = mrq->data;
97 static const int data_errors[] = {
106 if (cmd->error || data->error ||
107 !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
110 data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)];
111 data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9;
114 #else /* CONFIG_FAIL_MMC_REQUEST */
116 static inline void mmc_should_fail_request(struct mmc_host *host,
117 struct mmc_request *mrq)
121 #endif /* CONFIG_FAIL_MMC_REQUEST */
124 * mmc_request_done - finish processing an MMC request
125 * @host: MMC host which completed request
126 * @mrq: MMC request which request
128 * MMC drivers should call this function when they have completed
129 * their processing of a request.
131 void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
133 struct mmc_command *cmd = mrq->cmd;
134 int err = cmd->error;
136 /* Flag re-tuning needed on CRC errors */
137 if ((cmd->opcode != MMC_SEND_TUNING_BLOCK &&
138 cmd->opcode != MMC_SEND_TUNING_BLOCK_HS200) &&
139 (err == -EIO || err == -EILSEQ ||
140 (mrq->sbc && mrq->sbc->error == -EILSEQ) ||
141 (mrq->data && mrq->data->error == -EILSEQ) ||
142 (mrq->stop && mrq->stop->error == -EILSEQ)))
143 mmc_retune_needed(host);
145 if (err && cmd->retries && mmc_host_is_spi(host)) {
146 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
150 if (err && cmd->retries && !mmc_card_removed(host->card)) {
152 * Request starter must handle retries - see
153 * mmc_wait_for_req_done().
158 mmc_should_fail_request(host, mrq);
160 led_trigger_event(host->led, LED_OFF);
163 pr_debug("%s: req done <CMD%u>: %d: %08x %08x %08x %08x\n",
164 mmc_hostname(host), mrq->sbc->opcode,
166 mrq->sbc->resp[0], mrq->sbc->resp[1],
167 mrq->sbc->resp[2], mrq->sbc->resp[3]);
170 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
171 mmc_hostname(host), cmd->opcode, err,
172 cmd->resp[0], cmd->resp[1],
173 cmd->resp[2], cmd->resp[3]);
176 pr_debug("%s: %d bytes transferred: %d\n",
178 mrq->data->bytes_xfered, mrq->data->error);
180 if (mrq->lat_hist_enabled) {
184 completion = ktime_get();
185 delta_us = ktime_us_delta(completion,
187 blk_update_latency_hist(&host->io_lat_s,
188 (mrq->data->flags & MMC_DATA_READ),
192 trace_mmc_blk_rw_end(cmd->opcode, cmd->arg, mrq->data);
196 pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n",
197 mmc_hostname(host), mrq->stop->opcode,
199 mrq->stop->resp[0], mrq->stop->resp[1],
200 mrq->stop->resp[2], mrq->stop->resp[3]);
208 EXPORT_SYMBOL(mmc_request_done);
210 static void __mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
214 /* Assumes host controller has been runtime resumed by mmc_claim_host */
215 err = mmc_retune(host);
217 mrq->cmd->error = err;
218 mmc_request_done(host, mrq);
223 * For sdio rw commands we must wait for card busy otherwise some
224 * sdio devices won't work properly.
226 if (mmc_is_io_op(mrq->cmd->opcode) && host->ops->card_busy) {
227 int tries = 500; /* Wait aprox 500ms at maximum */
229 while (host->ops->card_busy(host) && --tries)
233 mrq->cmd->error = -EBUSY;
234 mmc_request_done(host, mrq);
239 host->ops->request(host, mrq);
242 static int mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
244 #ifdef CONFIG_MMC_DEBUG
246 struct scatterlist *sg;
248 mmc_retune_hold(host);
250 if (mmc_card_removed(host->card))
254 pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n",
255 mmc_hostname(host), mrq->sbc->opcode,
256 mrq->sbc->arg, mrq->sbc->flags);
259 pr_debug("%s: starting CMD%u arg %08x flags %08x\n",
260 mmc_hostname(host), mrq->cmd->opcode,
261 mrq->cmd->arg, mrq->cmd->flags);
264 pr_debug("%s: blksz %d blocks %d flags %08x "
265 "tsac %d ms nsac %d\n",
266 mmc_hostname(host), mrq->data->blksz,
267 mrq->data->blocks, mrq->data->flags,
268 mrq->data->timeout_ns / 1000000,
269 mrq->data->timeout_clks);
273 pr_debug("%s: CMD%u arg %08x flags %08x\n",
274 mmc_hostname(host), mrq->stop->opcode,
275 mrq->stop->arg, mrq->stop->flags);
278 WARN_ON(!host->claimed);
287 BUG_ON(mrq->data->blksz > host->max_blk_size);
288 BUG_ON(mrq->data->blocks > host->max_blk_count);
289 BUG_ON(mrq->data->blocks * mrq->data->blksz >
292 #ifdef CONFIG_MMC_DEBUG
294 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
296 BUG_ON(sz != mrq->data->blocks * mrq->data->blksz);
299 mrq->cmd->data = mrq->data;
300 mrq->data->error = 0;
301 mrq->data->mrq = mrq;
303 mrq->data->stop = mrq->stop;
304 mrq->stop->error = 0;
305 mrq->stop->mrq = mrq;
308 led_trigger_event(host->led, LED_FULL);
309 __mmc_start_request(host, mrq);
315 * mmc_start_bkops - start BKOPS for supported cards
316 * @card: MMC card to start BKOPS
317 * @form_exception: A flag to indicate if this function was
318 * called due to an exception raised by the card
320 * Start background operations whenever requested.
321 * When the urgent BKOPS bit is set in a R1 command response
322 * then background operations should be started immediately.
324 void mmc_start_bkops(struct mmc_card *card, bool from_exception)
328 bool use_busy_signal;
332 if (!card->ext_csd.man_bkops_en || mmc_card_doing_bkops(card))
335 err = mmc_read_bkops_status(card);
337 pr_err("%s: Failed to read bkops status: %d\n",
338 mmc_hostname(card->host), err);
342 if (!card->ext_csd.raw_bkops_status)
345 if (card->ext_csd.raw_bkops_status < EXT_CSD_BKOPS_LEVEL_2 &&
349 mmc_claim_host(card->host);
350 if (card->ext_csd.raw_bkops_status >= EXT_CSD_BKOPS_LEVEL_2) {
351 timeout = MMC_BKOPS_MAX_TIMEOUT;
352 use_busy_signal = true;
355 use_busy_signal = false;
358 mmc_retune_hold(card->host);
360 err = __mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
361 EXT_CSD_BKOPS_START, 1, timeout,
362 use_busy_signal, true, false);
364 pr_warn("%s: Error %d starting bkops\n",
365 mmc_hostname(card->host), err);
366 mmc_retune_release(card->host);
371 * For urgent bkops status (LEVEL_2 and more)
372 * bkops executed synchronously, otherwise
373 * the operation is in progress
375 if (!use_busy_signal)
376 mmc_card_set_doing_bkops(card);
378 mmc_retune_release(card->host);
380 mmc_release_host(card->host);
382 EXPORT_SYMBOL(mmc_start_bkops);
385 * mmc_wait_data_done() - done callback for data request
386 * @mrq: done data request
388 * Wakes up mmc context, passed as a callback to host controller driver
390 static void mmc_wait_data_done(struct mmc_request *mrq)
392 struct mmc_context_info *context_info = &mrq->host->context_info;
394 context_info->is_done_rcv = true;
395 wake_up_interruptible(&context_info->wait);
398 static void mmc_wait_done(struct mmc_request *mrq)
400 complete(&mrq->completion);
404 *__mmc_start_data_req() - starts data request
405 * @host: MMC host to start the request
406 * @mrq: data request to start
408 * Sets the done callback to be called when request is completed by the card.
409 * Starts data mmc request execution
411 static int __mmc_start_data_req(struct mmc_host *host, struct mmc_request *mrq)
415 mrq->done = mmc_wait_data_done;
418 err = mmc_start_request(host, mrq);
420 mrq->cmd->error = err;
421 mmc_wait_data_done(mrq);
427 static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
431 init_completion(&mrq->completion);
432 mrq->done = mmc_wait_done;
434 err = mmc_start_request(host, mrq);
436 mrq->cmd->error = err;
437 complete(&mrq->completion);
444 * mmc_wait_for_data_req_done() - wait for request completed
445 * @host: MMC host to prepare the command.
446 * @mrq: MMC request to wait for
448 * Blocks MMC context till host controller will ack end of data request
449 * execution or new request notification arrives from the block layer.
450 * Handles command retries.
452 * Returns enum mmc_blk_status after checking errors.
454 static int mmc_wait_for_data_req_done(struct mmc_host *host,
455 struct mmc_request *mrq,
456 struct mmc_async_req *next_req)
458 struct mmc_command *cmd;
459 struct mmc_context_info *context_info = &host->context_info;
464 wait_event_interruptible(context_info->wait,
465 (context_info->is_done_rcv ||
466 context_info->is_new_req));
467 spin_lock_irqsave(&context_info->lock, flags);
468 context_info->is_waiting_last_req = false;
469 spin_unlock_irqrestore(&context_info->lock, flags);
470 if (context_info->is_done_rcv) {
471 context_info->is_done_rcv = false;
472 context_info->is_new_req = false;
475 if (!cmd->error || !cmd->retries ||
476 mmc_card_removed(host->card)) {
477 err = host->areq->err_check(host->card,
479 break; /* return err */
481 mmc_retune_recheck(host);
482 pr_info("%s: req failed (CMD%u): %d, retrying...\n",
484 cmd->opcode, cmd->error);
487 __mmc_start_request(host, mrq);
488 continue; /* wait for done/new event again */
490 } else if (context_info->is_new_req) {
491 context_info->is_new_req = false;
493 return MMC_BLK_NEW_REQUEST;
496 mmc_retune_release(host);
500 static void mmc_wait_for_req_done(struct mmc_host *host,
501 struct mmc_request *mrq)
503 struct mmc_command *cmd;
506 wait_for_completion(&mrq->completion);
511 * If host has timed out waiting for the sanitize
512 * to complete, card might be still in programming state
513 * so let's try to bring the card out of programming
516 if (cmd->sanitize_busy && cmd->error == -ETIMEDOUT) {
517 if (!mmc_interrupt_hpi(host->card)) {
518 pr_warn("%s: %s: Interrupted sanitize\n",
519 mmc_hostname(host), __func__);
523 pr_err("%s: %s: Failed to interrupt sanitize\n",
524 mmc_hostname(host), __func__);
527 if (!cmd->error || !cmd->retries ||
528 mmc_card_removed(host->card))
531 mmc_retune_recheck(host);
533 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
534 mmc_hostname(host), cmd->opcode, cmd->error);
537 __mmc_start_request(host, mrq);
540 mmc_retune_release(host);
544 * mmc_pre_req - Prepare for a new request
545 * @host: MMC host to prepare command
546 * @mrq: MMC request to prepare for
547 * @is_first_req: true if there is no previous started request
548 * that may run in parellel to this call, otherwise false
550 * mmc_pre_req() is called in prior to mmc_start_req() to let
551 * host prepare for the new request. Preparation of a request may be
552 * performed while another request is running on the host.
554 static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq,
557 if (host->ops->pre_req)
558 host->ops->pre_req(host, mrq, is_first_req);
562 * mmc_post_req - Post process a completed request
563 * @host: MMC host to post process command
564 * @mrq: MMC request to post process for
565 * @err: Error, if non zero, clean up any resources made in pre_req
567 * Let the host post process a completed request. Post processing of
568 * a request may be performed while another reuqest is running.
570 static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq,
573 if (host->ops->post_req)
574 host->ops->post_req(host, mrq, err);
578 * mmc_start_req - start a non-blocking request
579 * @host: MMC host to start command
580 * @areq: async request to start
581 * @error: out parameter returns 0 for success, otherwise non zero
583 * Start a new MMC custom command request for a host.
584 * If there is on ongoing async request wait for completion
585 * of that request and start the new one and return.
586 * Does not wait for the new request to complete.
588 * Returns the completed request, NULL in case of none completed.
589 * Wait for the an ongoing request (previoulsy started) to complete and
590 * return the completed request. If there is no ongoing request, NULL
591 * is returned without waiting. NULL is not an error condition.
593 struct mmc_async_req *mmc_start_req(struct mmc_host *host,
594 struct mmc_async_req *areq, int *error)
598 struct mmc_async_req *data = host->areq;
600 /* Prepare a new request */
602 mmc_pre_req(host, areq->mrq, !host->areq);
605 err = mmc_wait_for_data_req_done(host, host->areq->mrq, areq);
606 if (err == MMC_BLK_NEW_REQUEST) {
610 * The previous request was not completed,
616 * Check BKOPS urgency for each R1 response
618 if (host->card && mmc_card_mmc(host->card) &&
619 ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) ||
620 (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) &&
621 (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT)) {
623 /* Cancel the prepared request */
625 mmc_post_req(host, areq->mrq, -EINVAL);
627 mmc_start_bkops(host->card, true);
629 /* prepare the request again */
631 mmc_pre_req(host, areq->mrq, !host->areq);
637 if (host->latency_hist_enabled) {
638 areq->mrq->io_start = ktime_get();
639 areq->mrq->lat_hist_enabled = 1;
641 areq->mrq->lat_hist_enabled = 0;
643 trace_mmc_blk_rw_start(areq->mrq->cmd->opcode,
646 start_err = __mmc_start_data_req(host, areq->mrq);
650 mmc_post_req(host, host->areq->mrq, 0);
652 /* Cancel a prepared request if it was not started. */
653 if ((err || start_err) && areq)
654 mmc_post_req(host, areq->mrq, -EINVAL);
665 EXPORT_SYMBOL(mmc_start_req);
668 * mmc_wait_for_req - start a request and wait for completion
669 * @host: MMC host to start command
670 * @mrq: MMC request to start
672 * Start a new MMC custom command request for a host, and wait
673 * for the command to complete. Does not attempt to parse the
676 void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
678 __mmc_start_req(host, mrq);
679 mmc_wait_for_req_done(host, mrq);
681 EXPORT_SYMBOL(mmc_wait_for_req);
684 * mmc_interrupt_hpi - Issue for High priority Interrupt
685 * @card: the MMC card associated with the HPI transfer
687 * Issued High Priority Interrupt, and check for card status
688 * until out-of prg-state.
690 int mmc_interrupt_hpi(struct mmc_card *card)
694 unsigned long prg_wait;
698 if (!card->ext_csd.hpi_en) {
699 pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host));
703 mmc_claim_host(card->host);
704 err = mmc_send_status(card, &status);
706 pr_err("%s: Get card status fail\n", mmc_hostname(card->host));
710 switch (R1_CURRENT_STATE(status)) {
716 * In idle and transfer states, HPI is not needed and the caller
717 * can issue the next intended command immediately
723 /* In all other states, it's illegal to issue HPI */
724 pr_debug("%s: HPI cannot be sent. Card state=%d\n",
725 mmc_hostname(card->host), R1_CURRENT_STATE(status));
730 err = mmc_send_hpi_cmd(card, &status);
734 prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time);
736 err = mmc_send_status(card, &status);
738 if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN)
740 if (time_after(jiffies, prg_wait))
745 mmc_release_host(card->host);
748 EXPORT_SYMBOL(mmc_interrupt_hpi);
751 * mmc_wait_for_cmd - start a command and wait for completion
752 * @host: MMC host to start command
753 * @cmd: MMC command to start
754 * @retries: maximum number of retries
756 * Start a new MMC command for a host, and wait for the command
757 * to complete. Return any error that occurred while the command
758 * was executing. Do not attempt to parse the response.
760 int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
762 struct mmc_request mrq = {NULL};
764 WARN_ON(!host->claimed);
766 memset(cmd->resp, 0, sizeof(cmd->resp));
767 cmd->retries = retries;
772 mmc_wait_for_req(host, &mrq);
777 EXPORT_SYMBOL(mmc_wait_for_cmd);
780 * mmc_stop_bkops - stop ongoing BKOPS
781 * @card: MMC card to check BKOPS
783 * Send HPI command to stop ongoing background operations to
784 * allow rapid servicing of foreground operations, e.g. read/
785 * writes. Wait until the card comes out of the programming state
786 * to avoid errors in servicing read/write requests.
788 int mmc_stop_bkops(struct mmc_card *card)
793 err = mmc_interrupt_hpi(card);
796 * If err is EINVAL, we can't issue an HPI.
797 * It should complete the BKOPS.
799 if (!err || (err == -EINVAL)) {
800 mmc_card_clr_doing_bkops(card);
801 mmc_retune_release(card->host);
807 EXPORT_SYMBOL(mmc_stop_bkops);
809 int mmc_read_bkops_status(struct mmc_card *card)
814 mmc_claim_host(card->host);
815 err = mmc_get_ext_csd(card, &ext_csd);
816 mmc_release_host(card->host);
820 card->ext_csd.raw_bkops_status = ext_csd[EXT_CSD_BKOPS_STATUS];
821 card->ext_csd.raw_exception_status = ext_csd[EXT_CSD_EXP_EVENTS_STATUS];
825 EXPORT_SYMBOL(mmc_read_bkops_status);
828 * mmc_set_data_timeout - set the timeout for a data command
829 * @data: data phase for command
830 * @card: the MMC card associated with the data transfer
832 * Computes the data timeout parameters according to the
833 * correct algorithm given the card type.
835 void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
840 * SDIO cards only define an upper 1 s limit on access.
842 if (mmc_card_sdio(card)) {
843 data->timeout_ns = 1000000000;
844 data->timeout_clks = 0;
849 * SD cards use a 100 multiplier rather than 10
851 mult = mmc_card_sd(card) ? 100 : 10;
854 * Scale up the multiplier (and therefore the timeout) by
855 * the r2w factor for writes.
857 if (data->flags & MMC_DATA_WRITE)
858 mult <<= card->csd.r2w_factor;
860 data->timeout_ns = card->csd.tacc_ns * mult;
861 data->timeout_clks = card->csd.tacc_clks * mult;
864 * SD cards also have an upper limit on the timeout.
866 if (mmc_card_sd(card)) {
867 unsigned int timeout_us, limit_us;
869 timeout_us = data->timeout_ns / 1000;
870 if (card->host->ios.clock)
871 timeout_us += data->timeout_clks * 1000 /
872 (card->host->ios.clock / 1000);
874 if (data->flags & MMC_DATA_WRITE)
876 * The MMC spec "It is strongly recommended
877 * for hosts to implement more than 500ms
878 * timeout value even if the card indicates
879 * the 250ms maximum busy length." Even the
880 * previous value of 300ms is known to be
881 * insufficient for some cards.
888 * SDHC cards always use these fixed values.
890 if (timeout_us > limit_us || mmc_card_blockaddr(card)) {
891 data->timeout_ns = limit_us * 1000;
892 data->timeout_clks = 0;
895 /* assign limit value if invalid */
897 data->timeout_ns = limit_us * 1000;
901 * Some cards require longer data read timeout than indicated in CSD.
902 * Address this by setting the read timeout to a "reasonably high"
903 * value. For the cards tested, 600ms has proven enough. If necessary,
904 * this value can be increased if other problematic cards require this.
906 if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
907 data->timeout_ns = 600000000;
908 data->timeout_clks = 0;
912 * Some cards need very high timeouts if driven in SPI mode.
913 * The worst observed timeout was 900ms after writing a
914 * continuous stream of data until the internal logic
917 if (mmc_host_is_spi(card->host)) {
918 if (data->flags & MMC_DATA_WRITE) {
919 if (data->timeout_ns < 1000000000)
920 data->timeout_ns = 1000000000; /* 1s */
922 if (data->timeout_ns < 100000000)
923 data->timeout_ns = 100000000; /* 100ms */
927 EXPORT_SYMBOL(mmc_set_data_timeout);
930 * mmc_align_data_size - pads a transfer size to a more optimal value
931 * @card: the MMC card associated with the data transfer
932 * @sz: original transfer size
934 * Pads the original data size with a number of extra bytes in
935 * order to avoid controller bugs and/or performance hits
936 * (e.g. some controllers revert to PIO for certain sizes).
938 * Returns the improved size, which might be unmodified.
940 * Note that this function is only relevant when issuing a
941 * single scatter gather entry.
943 unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
946 * FIXME: We don't have a system for the controller to tell
947 * the core about its problems yet, so for now we just 32-bit
950 sz = ((sz + 3) / 4) * 4;
954 EXPORT_SYMBOL(mmc_align_data_size);
957 * __mmc_claim_host - exclusively claim a host
958 * @host: mmc host to claim
959 * @abort: whether or not the operation should be aborted
961 * Claim a host for a set of operations. If @abort is non null and
962 * dereference a non-zero value then this will return prematurely with
963 * that non-zero value without acquiring the lock. Returns zero
964 * with the lock held otherwise.
966 int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
968 DECLARE_WAITQUEUE(wait, current);
975 add_wait_queue(&host->wq, &wait);
976 spin_lock_irqsave(&host->lock, flags);
978 set_current_state(TASK_UNINTERRUPTIBLE);
979 stop = abort ? atomic_read(abort) : 0;
980 if (stop || !host->claimed || host->claimer == current)
982 spin_unlock_irqrestore(&host->lock, flags);
984 spin_lock_irqsave(&host->lock, flags);
986 set_current_state(TASK_RUNNING);
989 host->claimer = current;
990 host->claim_cnt += 1;
991 if (host->claim_cnt == 1)
995 spin_unlock_irqrestore(&host->lock, flags);
996 remove_wait_queue(&host->wq, &wait);
999 pm_runtime_get_sync(mmc_dev(host));
1003 EXPORT_SYMBOL(__mmc_claim_host);
1006 * mmc_release_host - release a host
1007 * @host: mmc host to release
1009 * Release a MMC host, allowing others to claim the host
1010 * for their operations.
1012 void mmc_release_host(struct mmc_host *host)
1014 unsigned long flags;
1016 WARN_ON(!host->claimed);
1018 spin_lock_irqsave(&host->lock, flags);
1019 if (--host->claim_cnt) {
1020 /* Release for nested claim */
1021 spin_unlock_irqrestore(&host->lock, flags);
1024 host->claimer = NULL;
1025 spin_unlock_irqrestore(&host->lock, flags);
1027 pm_runtime_mark_last_busy(mmc_dev(host));
1028 pm_runtime_put_autosuspend(mmc_dev(host));
1031 EXPORT_SYMBOL(mmc_release_host);
1034 * This is a helper function, which fetches a runtime pm reference for the
1035 * card device and also claims the host.
1037 void mmc_get_card(struct mmc_card *card)
1039 pm_runtime_get_sync(&card->dev);
1040 mmc_claim_host(card->host);
1042 EXPORT_SYMBOL(mmc_get_card);
1045 * This is a helper function, which releases the host and drops the runtime
1046 * pm reference for the card device.
1048 void mmc_put_card(struct mmc_card *card)
1050 mmc_release_host(card->host);
1051 pm_runtime_mark_last_busy(&card->dev);
1052 pm_runtime_put_autosuspend(&card->dev);
1054 EXPORT_SYMBOL(mmc_put_card);
1057 * Internal function that does the actual ios call to the host driver,
1058 * optionally printing some debug output.
1060 static inline void mmc_set_ios(struct mmc_host *host)
1062 struct mmc_ios *ios = &host->ios;
1064 pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
1065 "width %u timing %u\n",
1066 mmc_hostname(host), ios->clock, ios->bus_mode,
1067 ios->power_mode, ios->chip_select, ios->vdd,
1068 ios->bus_width, ios->timing);
1070 host->ops->set_ios(host, ios);
1074 * Control chip select pin on a host.
1076 void mmc_set_chip_select(struct mmc_host *host, int mode)
1078 host->ios.chip_select = mode;
1083 * Sets the host clock to the highest possible frequency that
1086 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
1088 WARN_ON(hz && hz < host->f_min);
1090 if (hz > host->f_max)
1093 host->ios.clock = hz;
1097 int mmc_execute_tuning(struct mmc_card *card)
1099 struct mmc_host *host = card->host;
1103 if (!host->ops->execute_tuning)
1106 if (mmc_card_mmc(card))
1107 opcode = MMC_SEND_TUNING_BLOCK_HS200;
1109 opcode = MMC_SEND_TUNING_BLOCK;
1111 err = host->ops->execute_tuning(host, opcode);
1114 pr_err("%s: tuning execution failed\n", mmc_hostname(host));
1116 mmc_retune_enable(host);
1122 * Change the bus mode (open drain/push-pull) of a host.
1124 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
1126 host->ios.bus_mode = mode;
1131 * Change data bus width of a host.
1133 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
1135 host->ios.bus_width = width;
1140 * Set initial state after a power cycle or a hw_reset.
1142 void mmc_set_initial_state(struct mmc_host *host)
1144 mmc_retune_disable(host);
1146 if (mmc_host_is_spi(host))
1147 host->ios.chip_select = MMC_CS_HIGH;
1149 host->ios.chip_select = MMC_CS_DONTCARE;
1150 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1151 host->ios.bus_width = MMC_BUS_WIDTH_1;
1152 host->ios.timing = MMC_TIMING_LEGACY;
1153 host->ios.drv_type = 0;
1154 host->ios.enhanced_strobe = false;
1156 if ((host->caps2 & MMC_CAP2_HS400_ES) &&
1157 host->ops->hs400_enhanced_strobe)
1158 host->ops->hs400_enhanced_strobe(host, &host->ios);
1164 * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
1165 * @vdd: voltage (mV)
1166 * @low_bits: prefer low bits in boundary cases
1168 * This function returns the OCR bit number according to the provided @vdd
1169 * value. If conversion is not possible a negative errno value returned.
1171 * Depending on the @low_bits flag the function prefers low or high OCR bits
1172 * on boundary voltages. For example,
1173 * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
1174 * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1176 * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1178 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1180 const int max_bit = ilog2(MMC_VDD_35_36);
1183 if (vdd < 1650 || vdd > 3600)
1186 if (vdd >= 1650 && vdd <= 1950)
1187 return ilog2(MMC_VDD_165_195);
1192 /* Base 2000 mV, step 100 mV, bit's base 8. */
1193 bit = (vdd - 2000) / 100 + 8;
1200 * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1201 * @vdd_min: minimum voltage value (mV)
1202 * @vdd_max: maximum voltage value (mV)
1204 * This function returns the OCR mask bits according to the provided @vdd_min
1205 * and @vdd_max values. If conversion is not possible the function returns 0.
1207 * Notes wrt boundary cases:
1208 * This function sets the OCR bits for all boundary voltages, for example
1209 * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1210 * MMC_VDD_34_35 mask.
1212 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1216 if (vdd_max < vdd_min)
1219 /* Prefer high bits for the boundary vdd_max values. */
1220 vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1224 /* Prefer low bits for the boundary vdd_min values. */
1225 vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1229 /* Fill the mask, from max bit to min bit. */
1230 while (vdd_max >= vdd_min)
1231 mask |= 1 << vdd_max--;
1235 EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
1240 * mmc_of_parse_voltage - return mask of supported voltages
1241 * @np: The device node need to be parsed.
1242 * @mask: mask of voltages available for MMC/SD/SDIO
1244 * 1. Return zero on success.
1245 * 2. Return negative errno: voltage-range is invalid.
1247 int mmc_of_parse_voltage(struct device_node *np, u32 *mask)
1249 const u32 *voltage_ranges;
1252 voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges);
1253 num_ranges = num_ranges / sizeof(*voltage_ranges) / 2;
1254 if (!voltage_ranges || !num_ranges) {
1255 pr_info("%s: voltage-ranges unspecified\n", np->full_name);
1259 for (i = 0; i < num_ranges; i++) {
1260 const int j = i * 2;
1263 ocr_mask = mmc_vddrange_to_ocrmask(
1264 be32_to_cpu(voltage_ranges[j]),
1265 be32_to_cpu(voltage_ranges[j + 1]));
1267 pr_err("%s: voltage-range #%d is invalid\n",
1276 EXPORT_SYMBOL(mmc_of_parse_voltage);
1278 #endif /* CONFIG_OF */
1280 static int mmc_of_get_func_num(struct device_node *node)
1285 ret = of_property_read_u32(node, "reg", ®);
1292 struct device_node *mmc_of_find_child_device(struct mmc_host *host,
1295 struct device_node *node;
1297 if (!host->parent || !host->parent->of_node)
1300 for_each_child_of_node(host->parent->of_node, node) {
1301 if (mmc_of_get_func_num(node) == func_num)
1308 #ifdef CONFIG_REGULATOR
1311 * mmc_ocrbitnum_to_vdd - Convert a OCR bit number to its voltage
1312 * @vdd_bit: OCR bit number
1313 * @min_uV: minimum voltage value (mV)
1314 * @max_uV: maximum voltage value (mV)
1316 * This function returns the voltage range according to the provided OCR
1317 * bit number. If conversion is not possible a negative errno value returned.
1319 static int mmc_ocrbitnum_to_vdd(int vdd_bit, int *min_uV, int *max_uV)
1327 * REVISIT mmc_vddrange_to_ocrmask() may have set some
1328 * bits this regulator doesn't quite support ... don't
1329 * be too picky, most cards and regulators are OK with
1330 * a 0.1V range goof (it's a small error percentage).
1332 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
1334 *min_uV = 1650 * 1000;
1335 *max_uV = 1950 * 1000;
1337 *min_uV = 1900 * 1000 + tmp * 100 * 1000;
1338 *max_uV = *min_uV + 100 * 1000;
1345 * mmc_regulator_get_ocrmask - return mask of supported voltages
1346 * @supply: regulator to use
1348 * This returns either a negative errno, or a mask of voltages that
1349 * can be provided to MMC/SD/SDIO devices using the specified voltage
1350 * regulator. This would normally be called before registering the
1353 int mmc_regulator_get_ocrmask(struct regulator *supply)
1361 count = regulator_count_voltages(supply);
1365 for (i = 0; i < count; i++) {
1366 vdd_uV = regulator_list_voltage(supply, i);
1370 vdd_mV = vdd_uV / 1000;
1371 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1375 vdd_uV = regulator_get_voltage(supply);
1379 vdd_mV = vdd_uV / 1000;
1380 result = mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1385 EXPORT_SYMBOL_GPL(mmc_regulator_get_ocrmask);
1388 * mmc_regulator_set_ocr - set regulator to match host->ios voltage
1389 * @mmc: the host to regulate
1390 * @supply: regulator to use
1391 * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
1393 * Returns zero on success, else negative errno.
1395 * MMC host drivers may use this to enable or disable a regulator using
1396 * a particular supply voltage. This would normally be called from the
1399 int mmc_regulator_set_ocr(struct mmc_host *mmc,
1400 struct regulator *supply,
1401 unsigned short vdd_bit)
1407 mmc_ocrbitnum_to_vdd(vdd_bit, &min_uV, &max_uV);
1409 result = regulator_set_voltage(supply, min_uV, max_uV);
1410 if (result == 0 && !mmc->regulator_enabled) {
1411 result = regulator_enable(supply);
1413 mmc->regulator_enabled = true;
1415 } else if (mmc->regulator_enabled) {
1416 result = regulator_disable(supply);
1418 mmc->regulator_enabled = false;
1422 dev_err(mmc_dev(mmc),
1423 "could not set regulator OCR (%d)\n", result);
1426 EXPORT_SYMBOL_GPL(mmc_regulator_set_ocr);
1428 static int mmc_regulator_set_voltage_if_supported(struct regulator *regulator,
1429 int min_uV, int target_uV,
1433 * Check if supported first to avoid errors since we may try several
1434 * signal levels during power up and don't want to show errors.
1436 if (!regulator_is_supported_voltage(regulator, min_uV, max_uV))
1439 return regulator_set_voltage_triplet(regulator, min_uV, target_uV,
1444 * mmc_regulator_set_vqmmc - Set VQMMC as per the ios
1446 * For 3.3V signaling, we try to match VQMMC to VMMC as closely as possible.
1447 * That will match the behavior of old boards where VQMMC and VMMC were supplied
1448 * by the same supply. The Bus Operating conditions for 3.3V signaling in the
1449 * SD card spec also define VQMMC in terms of VMMC.
1450 * If this is not possible we'll try the full 2.7-3.6V of the spec.
1452 * For 1.2V and 1.8V signaling we'll try to get as close as possible to the
1453 * requested voltage. This is definitely a good idea for UHS where there's a
1454 * separate regulator on the card that's trying to make 1.8V and it's best if
1457 * This function is expected to be used by a controller's
1458 * start_signal_voltage_switch() function.
1460 int mmc_regulator_set_vqmmc(struct mmc_host *mmc, struct mmc_ios *ios)
1462 struct device *dev = mmc_dev(mmc);
1463 int ret, volt, min_uV, max_uV;
1465 /* If no vqmmc supply then we can't change the voltage */
1466 if (IS_ERR(mmc->supply.vqmmc))
1469 switch (ios->signal_voltage) {
1470 case MMC_SIGNAL_VOLTAGE_120:
1471 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1472 1100000, 1200000, 1300000);
1473 case MMC_SIGNAL_VOLTAGE_180:
1474 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1475 1700000, 1800000, 1950000);
1476 case MMC_SIGNAL_VOLTAGE_330:
1477 ret = mmc_ocrbitnum_to_vdd(mmc->ios.vdd, &volt, &max_uV);
1481 dev_dbg(dev, "%s: found vmmc voltage range of %d-%duV\n",
1482 __func__, volt, max_uV);
1484 min_uV = max(volt - 300000, 2700000);
1485 max_uV = min(max_uV + 200000, 3600000);
1488 * Due to a limitation in the current implementation of
1489 * regulator_set_voltage_triplet() which is taking the lowest
1490 * voltage possible if below the target, search for a suitable
1491 * voltage in two steps and try to stay close to vmmc
1492 * with a 0.3V tolerance at first.
1494 if (!mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1495 min_uV, volt, max_uV))
1498 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1499 2700000, volt, 3600000);
1504 EXPORT_SYMBOL_GPL(mmc_regulator_set_vqmmc);
1506 #endif /* CONFIG_REGULATOR */
1508 int mmc_regulator_get_supply(struct mmc_host *mmc)
1510 struct device *dev = mmc_dev(mmc);
1513 mmc->supply.vmmc = devm_regulator_get_optional(dev, "vmmc");
1514 mmc->supply.vqmmc = devm_regulator_get_optional(dev, "vqmmc");
1516 if (IS_ERR(mmc->supply.vmmc)) {
1517 if (PTR_ERR(mmc->supply.vmmc) == -EPROBE_DEFER)
1518 return -EPROBE_DEFER;
1519 dev_info(dev, "No vmmc regulator found\n");
1521 ret = mmc_regulator_get_ocrmask(mmc->supply.vmmc);
1523 mmc->ocr_avail = ret;
1525 dev_warn(dev, "Failed getting OCR mask: %d\n", ret);
1528 if (IS_ERR(mmc->supply.vqmmc)) {
1529 if (PTR_ERR(mmc->supply.vqmmc) == -EPROBE_DEFER)
1530 return -EPROBE_DEFER;
1531 dev_info(dev, "No vqmmc regulator found\n");
1536 EXPORT_SYMBOL_GPL(mmc_regulator_get_supply);
1539 * Mask off any voltages we don't support and select
1540 * the lowest voltage
1542 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1547 * Sanity check the voltages that the card claims to
1551 dev_warn(mmc_dev(host),
1552 "card claims to support voltages below defined range\n");
1556 ocr &= host->ocr_avail;
1558 dev_warn(mmc_dev(host), "no support for card's volts\n");
1562 if (host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) {
1565 mmc_power_cycle(host, ocr);
1569 if (bit != host->ios.vdd)
1570 dev_warn(mmc_dev(host), "exceeding card's volts\n");
1576 int __mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage)
1579 int old_signal_voltage = host->ios.signal_voltage;
1581 host->ios.signal_voltage = signal_voltage;
1582 if (host->ops->start_signal_voltage_switch)
1583 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1586 host->ios.signal_voltage = old_signal_voltage;
1592 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, u32 ocr)
1594 struct mmc_command cmd = {0};
1601 * Send CMD11 only if the request is to switch the card to
1604 if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
1605 return __mmc_set_signal_voltage(host, signal_voltage);
1608 * If we cannot switch voltages, return failure so the caller
1609 * can continue without UHS mode
1611 if (!host->ops->start_signal_voltage_switch)
1613 if (!host->ops->card_busy)
1614 pr_warn("%s: cannot verify signal voltage switch\n",
1615 mmc_hostname(host));
1617 cmd.opcode = SD_SWITCH_VOLTAGE;
1619 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1621 err = mmc_wait_for_cmd(host, &cmd, 0);
1625 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1629 * The card should drive cmd and dat[0:3] low immediately
1630 * after the response of cmd11, but wait 1 ms to be sure
1633 if (host->ops->card_busy && !host->ops->card_busy(host)) {
1638 * During a signal voltage level switch, the clock must be gated
1639 * for 5 ms according to the SD spec
1641 clock = host->ios.clock;
1642 host->ios.clock = 0;
1645 if (__mmc_set_signal_voltage(host, signal_voltage)) {
1647 * Voltages may not have been switched, but we've already
1648 * sent CMD11, so a power cycle is required anyway
1654 /* Keep clock gated for at least 10 ms, though spec only says 5 ms */
1656 host->ios.clock = clock;
1659 /* Wait for at least 1 ms according to spec */
1663 * Failure to switch is indicated by the card holding
1666 if (host->ops->card_busy && host->ops->card_busy(host))
1671 pr_debug("%s: Signal voltage switch failed, "
1672 "power cycling card\n", mmc_hostname(host));
1673 mmc_power_cycle(host, ocr);
1680 * Select timing parameters for host.
1682 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1684 host->ios.timing = timing;
1689 * Select appropriate driver type for host.
1691 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1693 host->ios.drv_type = drv_type;
1697 int mmc_select_drive_strength(struct mmc_card *card, unsigned int max_dtr,
1698 int card_drv_type, int *drv_type)
1700 struct mmc_host *host = card->host;
1701 int host_drv_type = SD_DRIVER_TYPE_B;
1705 if (!host->ops->select_drive_strength)
1708 /* Use SD definition of driver strength for hosts */
1709 if (host->caps & MMC_CAP_DRIVER_TYPE_A)
1710 host_drv_type |= SD_DRIVER_TYPE_A;
1712 if (host->caps & MMC_CAP_DRIVER_TYPE_C)
1713 host_drv_type |= SD_DRIVER_TYPE_C;
1715 if (host->caps & MMC_CAP_DRIVER_TYPE_D)
1716 host_drv_type |= SD_DRIVER_TYPE_D;
1719 * The drive strength that the hardware can support
1720 * depends on the board design. Pass the appropriate
1721 * information and let the hardware specific code
1722 * return what is possible given the options
1724 return host->ops->select_drive_strength(card, max_dtr,
1731 * Apply power to the MMC stack. This is a two-stage process.
1732 * First, we enable power to the card without the clock running.
1733 * We then wait a bit for the power to stabilise. Finally,
1734 * enable the bus drivers and clock to the card.
1736 * We must _NOT_ enable the clock prior to power stablising.
1738 * If a host does all the power sequencing itself, ignore the
1739 * initial MMC_POWER_UP stage.
1741 void mmc_power_up(struct mmc_host *host, u32 ocr)
1743 if (host->ios.power_mode == MMC_POWER_ON)
1746 mmc_pwrseq_pre_power_on(host);
1748 host->ios.vdd = fls(ocr) - 1;
1749 host->ios.power_mode = MMC_POWER_UP;
1750 /* Set initial state and call mmc_set_ios */
1751 mmc_set_initial_state(host);
1753 /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */
1754 if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330) == 0)
1755 dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n");
1756 else if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180) == 0)
1757 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n");
1758 else if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_120) == 0)
1759 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n");
1762 * This delay should be sufficient to allow the power supply
1763 * to reach the minimum voltage.
1767 mmc_pwrseq_post_power_on(host);
1769 host->ios.clock = host->f_init;
1771 host->ios.power_mode = MMC_POWER_ON;
1775 * This delay must be at least 74 clock sizes, or 1 ms, or the
1776 * time required to reach a stable voltage.
1781 void mmc_power_off(struct mmc_host *host)
1783 if (host->ios.power_mode == MMC_POWER_OFF)
1786 mmc_pwrseq_power_off(host);
1788 host->ios.clock = 0;
1791 host->ios.power_mode = MMC_POWER_OFF;
1792 /* Set initial state and call mmc_set_ios */
1793 mmc_set_initial_state(host);
1796 * Some configurations, such as the 802.11 SDIO card in the OLPC
1797 * XO-1.5, require a short delay after poweroff before the card
1798 * can be successfully turned on again.
1803 void mmc_power_cycle(struct mmc_host *host, u32 ocr)
1805 mmc_power_off(host);
1806 /* Wait at least 1 ms according to SD spec */
1808 mmc_power_up(host, ocr);
1812 * Cleanup when the last reference to the bus operator is dropped.
1814 static void __mmc_release_bus(struct mmc_host *host)
1817 BUG_ON(host->bus_refs);
1818 BUG_ON(!host->bus_dead);
1820 host->bus_ops = NULL;
1824 * Increase reference count of bus operator
1826 static inline void mmc_bus_get(struct mmc_host *host)
1828 unsigned long flags;
1830 spin_lock_irqsave(&host->lock, flags);
1832 spin_unlock_irqrestore(&host->lock, flags);
1836 * Decrease reference count of bus operator and free it if
1837 * it is the last reference.
1839 static inline void mmc_bus_put(struct mmc_host *host)
1841 unsigned long flags;
1843 spin_lock_irqsave(&host->lock, flags);
1845 if ((host->bus_refs == 0) && host->bus_ops)
1846 __mmc_release_bus(host);
1847 spin_unlock_irqrestore(&host->lock, flags);
1851 * Assign a mmc bus handler to a host. Only one bus handler may control a
1852 * host at any given time.
1854 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1856 unsigned long flags;
1861 WARN_ON(!host->claimed);
1863 spin_lock_irqsave(&host->lock, flags);
1865 BUG_ON(host->bus_ops);
1866 BUG_ON(host->bus_refs);
1868 host->bus_ops = ops;
1872 spin_unlock_irqrestore(&host->lock, flags);
1876 * Remove the current bus handler from a host.
1878 void mmc_detach_bus(struct mmc_host *host)
1880 unsigned long flags;
1884 WARN_ON(!host->claimed);
1885 WARN_ON(!host->bus_ops);
1887 spin_lock_irqsave(&host->lock, flags);
1891 spin_unlock_irqrestore(&host->lock, flags);
1896 static void _mmc_detect_change(struct mmc_host *host, unsigned long delay,
1899 #ifdef CONFIG_MMC_DEBUG
1900 unsigned long flags;
1901 spin_lock_irqsave(&host->lock, flags);
1902 WARN_ON(host->removed);
1903 spin_unlock_irqrestore(&host->lock, flags);
1907 * If the device is configured as wakeup, we prevent a new sleep for
1908 * 5 s to give provision for user space to consume the event.
1910 if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) &&
1911 device_can_wakeup(mmc_dev(host)))
1912 pm_wakeup_event(mmc_dev(host), 5000);
1914 host->detect_change = 1;
1915 mmc_schedule_delayed_work(&host->detect, delay);
1919 * mmc_detect_change - process change of state on a MMC socket
1920 * @host: host which changed state.
1921 * @delay: optional delay to wait before detection (jiffies)
1923 * MMC drivers should call this when they detect a card has been
1924 * inserted or removed. The MMC layer will confirm that any
1925 * present card is still functional, and initialize any newly
1928 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1930 _mmc_detect_change(host, delay, true);
1932 EXPORT_SYMBOL(mmc_detect_change);
1934 void mmc_init_erase(struct mmc_card *card)
1938 if (is_power_of_2(card->erase_size))
1939 card->erase_shift = ffs(card->erase_size) - 1;
1941 card->erase_shift = 0;
1944 * It is possible to erase an arbitrarily large area of an SD or MMC
1945 * card. That is not desirable because it can take a long time
1946 * (minutes) potentially delaying more important I/O, and also the
1947 * timeout calculations become increasingly hugely over-estimated.
1948 * Consequently, 'pref_erase' is defined as a guide to limit erases
1949 * to that size and alignment.
1951 * For SD cards that define Allocation Unit size, limit erases to one
1952 * Allocation Unit at a time. For MMC cards that define High Capacity
1953 * Erase Size, whether it is switched on or not, limit to that size.
1954 * Otherwise just have a stab at a good value. For modern cards it
1955 * will end up being 4MiB. Note that if the value is too small, it
1956 * can end up taking longer to erase.
1958 if (mmc_card_sd(card) && card->ssr.au) {
1959 card->pref_erase = card->ssr.au;
1960 card->erase_shift = ffs(card->ssr.au) - 1;
1961 } else if (card->ext_csd.hc_erase_size) {
1962 card->pref_erase = card->ext_csd.hc_erase_size;
1963 } else if (card->erase_size) {
1964 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1966 card->pref_erase = 512 * 1024 / 512;
1968 card->pref_erase = 1024 * 1024 / 512;
1970 card->pref_erase = 2 * 1024 * 1024 / 512;
1972 card->pref_erase = 4 * 1024 * 1024 / 512;
1973 if (card->pref_erase < card->erase_size)
1974 card->pref_erase = card->erase_size;
1976 sz = card->pref_erase % card->erase_size;
1978 card->pref_erase += card->erase_size - sz;
1981 card->pref_erase = 0;
1984 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1985 unsigned int arg, unsigned int qty)
1987 unsigned int erase_timeout;
1989 if (arg == MMC_DISCARD_ARG ||
1990 (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) {
1991 erase_timeout = card->ext_csd.trim_timeout;
1992 } else if (card->ext_csd.erase_group_def & 1) {
1993 /* High Capacity Erase Group Size uses HC timeouts */
1994 if (arg == MMC_TRIM_ARG)
1995 erase_timeout = card->ext_csd.trim_timeout;
1997 erase_timeout = card->ext_csd.hc_erase_timeout;
1999 /* CSD Erase Group Size uses write timeout */
2000 unsigned int mult = (10 << card->csd.r2w_factor);
2001 unsigned int timeout_clks = card->csd.tacc_clks * mult;
2002 unsigned int timeout_us;
2004 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
2005 if (card->csd.tacc_ns < 1000000)
2006 timeout_us = (card->csd.tacc_ns * mult) / 1000;
2008 timeout_us = (card->csd.tacc_ns / 1000) * mult;
2011 * ios.clock is only a target. The real clock rate might be
2012 * less but not that much less, so fudge it by multiplying by 2.
2015 timeout_us += (timeout_clks * 1000) /
2016 (card->host->ios.clock / 1000);
2018 erase_timeout = timeout_us / 1000;
2021 * Theoretically, the calculation could underflow so round up
2022 * to 1ms in that case.
2028 /* Multiplier for secure operations */
2029 if (arg & MMC_SECURE_ARGS) {
2030 if (arg == MMC_SECURE_ERASE_ARG)
2031 erase_timeout *= card->ext_csd.sec_erase_mult;
2033 erase_timeout *= card->ext_csd.sec_trim_mult;
2036 erase_timeout *= qty;
2039 * Ensure at least a 1 second timeout for SPI as per
2040 * 'mmc_set_data_timeout()'
2042 if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
2043 erase_timeout = 1000;
2045 return erase_timeout;
2048 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
2052 unsigned int erase_timeout;
2054 if (card->ssr.erase_timeout) {
2055 /* Erase timeout specified in SD Status Register (SSR) */
2056 erase_timeout = card->ssr.erase_timeout * qty +
2057 card->ssr.erase_offset;
2060 * Erase timeout not specified in SD Status Register (SSR) so
2061 * use 250ms per write block.
2063 erase_timeout = 250 * qty;
2066 /* Must not be less than 1 second */
2067 if (erase_timeout < 1000)
2068 erase_timeout = 1000;
2070 return erase_timeout;
2073 static unsigned int mmc_erase_timeout(struct mmc_card *card,
2077 if (mmc_card_sd(card))
2078 return mmc_sd_erase_timeout(card, arg, qty);
2080 return mmc_mmc_erase_timeout(card, arg, qty);
2083 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
2084 unsigned int to, unsigned int arg)
2086 struct mmc_command cmd = {0};
2087 unsigned int qty = 0;
2088 unsigned long timeout;
2089 unsigned int fr, nr;
2094 trace_mmc_blk_erase_start(arg, fr, nr);
2096 mmc_retune_hold(card->host);
2099 * qty is used to calculate the erase timeout which depends on how many
2100 * erase groups (or allocation units in SD terminology) are affected.
2101 * We count erasing part of an erase group as one erase group.
2102 * For SD, the allocation units are always a power of 2. For MMC, the
2103 * erase group size is almost certainly also power of 2, but it does not
2104 * seem to insist on that in the JEDEC standard, so we fall back to
2105 * division in that case. SD may not specify an allocation unit size,
2106 * in which case the timeout is based on the number of write blocks.
2108 * Note that the timeout for secure trim 2 will only be correct if the
2109 * number of erase groups specified is the same as the total of all
2110 * preceding secure trim 1 commands. Since the power may have been
2111 * lost since the secure trim 1 commands occurred, it is generally
2112 * impossible to calculate the secure trim 2 timeout correctly.
2114 if (card->erase_shift)
2115 qty += ((to >> card->erase_shift) -
2116 (from >> card->erase_shift)) + 1;
2117 else if (mmc_card_sd(card))
2118 qty += to - from + 1;
2120 qty += ((to / card->erase_size) -
2121 (from / card->erase_size)) + 1;
2123 if (!mmc_card_blockaddr(card)) {
2128 if (mmc_card_sd(card))
2129 cmd.opcode = SD_ERASE_WR_BLK_START;
2131 cmd.opcode = MMC_ERASE_GROUP_START;
2133 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2134 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2136 pr_err("mmc_erase: group start error %d, "
2137 "status %#x\n", err, cmd.resp[0]);
2142 memset(&cmd, 0, sizeof(struct mmc_command));
2143 if (mmc_card_sd(card))
2144 cmd.opcode = SD_ERASE_WR_BLK_END;
2146 cmd.opcode = MMC_ERASE_GROUP_END;
2148 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2149 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2151 pr_err("mmc_erase: group end error %d, status %#x\n",
2157 memset(&cmd, 0, sizeof(struct mmc_command));
2158 cmd.opcode = MMC_ERASE;
2160 cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
2161 cmd.busy_timeout = mmc_erase_timeout(card, arg, qty);
2162 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2164 pr_err("mmc_erase: erase error %d, status %#x\n",
2170 if (mmc_host_is_spi(card->host))
2173 timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS);
2175 memset(&cmd, 0, sizeof(struct mmc_command));
2176 cmd.opcode = MMC_SEND_STATUS;
2177 cmd.arg = card->rca << 16;
2178 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
2179 /* Do not retry else we can't see errors */
2180 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2181 if (err || (cmd.resp[0] & 0xFDF92000)) {
2182 pr_err("error %d requesting status %#x\n",
2188 /* Timeout if the device never becomes ready for data and
2189 * never leaves the program state.
2191 if (time_after(jiffies, timeout)) {
2192 pr_err("%s: Card stuck in programming state! %s\n",
2193 mmc_hostname(card->host), __func__);
2198 } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
2199 (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG));
2201 mmc_retune_release(card->host);
2202 trace_mmc_blk_erase_end(arg, fr, nr);
2207 * mmc_erase - erase sectors.
2208 * @card: card to erase
2209 * @from: first sector to erase
2210 * @nr: number of sectors to erase
2211 * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
2213 * Caller must claim host before calling this function.
2215 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
2218 unsigned int rem, to = from + nr;
2221 if (!(card->host->caps & MMC_CAP_ERASE) ||
2222 !(card->csd.cmdclass & CCC_ERASE))
2225 if (!card->erase_size)
2228 if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
2231 if ((arg & MMC_SECURE_ARGS) &&
2232 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
2235 if ((arg & MMC_TRIM_ARGS) &&
2236 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
2239 if (arg == MMC_SECURE_ERASE_ARG) {
2240 if (from % card->erase_size || nr % card->erase_size)
2244 if (arg == MMC_ERASE_ARG) {
2245 rem = from % card->erase_size;
2247 rem = card->erase_size - rem;
2254 rem = nr % card->erase_size;
2267 /* 'from' and 'to' are inclusive */
2271 * Special case where only one erase-group fits in the timeout budget:
2272 * If the region crosses an erase-group boundary on this particular
2273 * case, we will be trimming more than one erase-group which, does not
2274 * fit in the timeout budget of the controller, so we need to split it
2275 * and call mmc_do_erase() twice if necessary. This special case is
2276 * identified by the card->eg_boundary flag.
2278 rem = card->erase_size - (from % card->erase_size);
2279 if ((arg & MMC_TRIM_ARGS) && (card->eg_boundary) && (nr > rem)) {
2280 err = mmc_do_erase(card, from, from + rem - 1, arg);
2282 if ((err) || (to <= from))
2286 return mmc_do_erase(card, from, to, arg);
2288 EXPORT_SYMBOL(mmc_erase);
2290 int mmc_can_erase(struct mmc_card *card)
2292 if ((card->host->caps & MMC_CAP_ERASE) &&
2293 (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
2297 EXPORT_SYMBOL(mmc_can_erase);
2299 int mmc_can_trim(struct mmc_card *card)
2301 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN) &&
2302 (!(card->quirks & MMC_QUIRK_TRIM_BROKEN)))
2306 EXPORT_SYMBOL(mmc_can_trim);
2308 int mmc_can_discard(struct mmc_card *card)
2311 * As there's no way to detect the discard support bit at v4.5
2312 * use the s/w feature support filed.
2314 if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
2318 EXPORT_SYMBOL(mmc_can_discard);
2320 int mmc_can_sanitize(struct mmc_card *card)
2322 if (!mmc_can_trim(card) && !mmc_can_erase(card))
2324 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
2328 EXPORT_SYMBOL(mmc_can_sanitize);
2330 int mmc_can_secure_erase_trim(struct mmc_card *card)
2332 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) &&
2333 !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
2337 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
2339 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
2342 if (!card->erase_size)
2344 if (from % card->erase_size || nr % card->erase_size)
2348 EXPORT_SYMBOL(mmc_erase_group_aligned);
2350 static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
2353 struct mmc_host *host = card->host;
2354 unsigned int max_discard, x, y, qty = 0, max_qty, timeout;
2355 unsigned int last_timeout = 0;
2357 if (card->erase_shift)
2358 max_qty = UINT_MAX >> card->erase_shift;
2359 else if (mmc_card_sd(card))
2362 max_qty = UINT_MAX / card->erase_size;
2364 /* Find the largest qty with an OK timeout */
2367 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
2368 timeout = mmc_erase_timeout(card, arg, qty + x);
2369 if (timeout > host->max_busy_timeout)
2371 if (timeout < last_timeout)
2373 last_timeout = timeout;
2383 * When specifying a sector range to trim, chances are we might cross
2384 * an erase-group boundary even if the amount of sectors is less than
2386 * If we can only fit one erase-group in the controller timeout budget,
2387 * we have to care that erase-group boundaries are not crossed by a
2388 * single trim operation. We flag that special case with "eg_boundary".
2389 * In all other cases we can just decrement qty and pretend that we
2390 * always touch (qty + 1) erase-groups as a simple optimization.
2393 card->eg_boundary = 1;
2397 /* Convert qty to sectors */
2398 if (card->erase_shift)
2399 max_discard = qty << card->erase_shift;
2400 else if (mmc_card_sd(card))
2401 max_discard = qty + 1;
2403 max_discard = qty * card->erase_size;
2408 unsigned int mmc_calc_max_discard(struct mmc_card *card)
2410 struct mmc_host *host = card->host;
2411 unsigned int max_discard, max_trim;
2413 if (!host->max_busy_timeout)
2417 * Without erase_group_def set, MMC erase timeout depends on clock
2418 * frequence which can change. In that case, the best choice is
2419 * just the preferred erase size.
2421 if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
2422 return card->pref_erase;
2424 max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
2425 if (mmc_can_trim(card)) {
2426 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
2427 if (max_trim < max_discard)
2428 max_discard = max_trim;
2429 } else if (max_discard < card->erase_size) {
2432 pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
2433 mmc_hostname(host), max_discard, host->max_busy_timeout);
2436 EXPORT_SYMBOL(mmc_calc_max_discard);
2438 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
2440 struct mmc_command cmd = {0};
2442 if (mmc_card_blockaddr(card) || mmc_card_ddr52(card) ||
2443 mmc_card_hs400(card) || mmc_card_hs400es(card))
2446 cmd.opcode = MMC_SET_BLOCKLEN;
2448 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2449 return mmc_wait_for_cmd(card->host, &cmd, 5);
2451 EXPORT_SYMBOL(mmc_set_blocklen);
2453 int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount,
2456 struct mmc_command cmd = {0};
2458 cmd.opcode = MMC_SET_BLOCK_COUNT;
2459 cmd.arg = blockcount & 0x0000FFFF;
2462 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2463 return mmc_wait_for_cmd(card->host, &cmd, 5);
2465 EXPORT_SYMBOL(mmc_set_blockcount);
2467 static void mmc_hw_reset_for_init(struct mmc_host *host)
2469 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2471 host->ops->hw_reset(host);
2474 int mmc_hw_reset(struct mmc_host *host)
2482 if (!host->bus_ops || host->bus_dead || !host->bus_ops->reset) {
2487 ret = host->bus_ops->reset(host);
2490 if (ret != -EOPNOTSUPP)
2491 pr_warn("%s: tried to reset card\n", mmc_hostname(host));
2495 EXPORT_SYMBOL(mmc_hw_reset);
2497 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2499 host->f_init = freq;
2501 #ifdef CONFIG_MMC_DEBUG
2502 pr_info("%s: %s: trying to init card at %u Hz\n",
2503 mmc_hostname(host), __func__, host->f_init);
2505 mmc_power_up(host, host->ocr_avail);
2508 * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2509 * do a hardware reset if possible.
2511 mmc_hw_reset_for_init(host);
2514 * sdio_reset sends CMD52 to reset card. Since we do not know
2515 * if the card is being re-initialized, just send it. CMD52
2516 * should be ignored by SD/eMMC cards.
2518 #ifdef MMC_STANDARD_PROBE
2522 mmc_send_if_cond(host, host->ocr_avail);
2524 /* Order's important: probe SDIO, then SD, then MMC */
2525 if (!mmc_attach_sdio(host))
2527 if (!mmc_attach_sd(host))
2529 if (!mmc_attach_mmc(host))
2532 if (host->restrict_caps & RESTRICT_CARD_TYPE_SDIO)
2537 if (host->restrict_caps &
2538 (RESTRICT_CARD_TYPE_SDIO | RESTRICT_CARD_TYPE_SD))
2539 mmc_send_if_cond(host, host->ocr_avail);
2540 /* Order's important: probe SDIO, then SD, then MMC */
2541 if ((host->restrict_caps & RESTRICT_CARD_TYPE_SDIO) &&
2542 !mmc_attach_sdio(host))
2544 if ((host->restrict_caps & RESTRICT_CARD_TYPE_SD) &&
2545 !mmc_attach_sd(host))
2547 if ((host->restrict_caps & RESTRICT_CARD_TYPE_EMMC) &&
2548 !mmc_attach_mmc(host))
2551 mmc_power_off(host);
2555 int _mmc_detect_card_removed(struct mmc_host *host)
2559 if (host->caps & MMC_CAP_NONREMOVABLE)
2562 if (!host->card || mmc_card_removed(host->card))
2565 ret = host->bus_ops->alive(host);
2568 * Card detect status and alive check may be out of sync if card is
2569 * removed slowly, when card detect switch changes while card/slot
2570 * pads are still contacted in hardware (refer to "SD Card Mechanical
2571 * Addendum, Appendix C: Card Detection Switch"). So reschedule a
2572 * detect work 200ms later for this case.
2574 if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) {
2575 mmc_detect_change(host, msecs_to_jiffies(200));
2576 pr_debug("%s: card removed too slowly\n", mmc_hostname(host));
2580 mmc_card_set_removed(host->card);
2581 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2587 int mmc_detect_card_removed(struct mmc_host *host)
2589 struct mmc_card *card = host->card;
2592 WARN_ON(!host->claimed);
2597 ret = mmc_card_removed(card);
2599 * The card will be considered unchanged unless we have been asked to
2600 * detect a change or host requires polling to provide card detection.
2602 if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
2605 host->detect_change = 0;
2607 ret = _mmc_detect_card_removed(host);
2608 if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) {
2610 * Schedule a detect work as soon as possible to let a
2611 * rescan handle the card removal.
2613 cancel_delayed_work(&host->detect);
2614 _mmc_detect_change(host, 0, false);
2620 EXPORT_SYMBOL(mmc_detect_card_removed);
2622 void mmc_rescan(struct work_struct *work)
2624 struct mmc_host *host =
2625 container_of(work, struct mmc_host, detect.work);
2628 if (host->trigger_card_event && host->ops->card_event) {
2629 host->ops->card_event(host);
2630 host->trigger_card_event = false;
2633 if (host->rescan_disable)
2636 /* If there is a non-removable card registered, only scan once */
2637 if ((host->caps & MMC_CAP_NONREMOVABLE) && host->rescan_entered)
2639 host->rescan_entered = 1;
2644 * if there is a _removable_ card registered, check whether it is
2647 if (host->bus_ops && !host->bus_dead
2648 && !(host->caps & MMC_CAP_NONREMOVABLE))
2649 host->bus_ops->detect(host);
2651 host->detect_change = 0;
2654 * Let mmc_bus_put() free the bus/bus_ops if we've found that
2655 * the card is no longer present.
2660 /* if there still is a card present, stop here */
2661 if (host->bus_ops != NULL) {
2667 * Only we can add a new handler, so it's safe to
2668 * release the lock here.
2672 if (!(host->caps & MMC_CAP_NONREMOVABLE) && host->ops->get_cd &&
2673 host->ops->get_cd(host) == 0) {
2674 mmc_claim_host(host);
2675 mmc_power_off(host);
2676 mmc_release_host(host);
2680 mmc_claim_host(host);
2681 for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2682 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2684 if (freqs[i] <= host->f_min)
2687 mmc_release_host(host);
2690 if (host->caps & MMC_CAP_NEEDS_POLL)
2691 mmc_schedule_delayed_work(&host->detect, HZ);
2694 void mmc_start_host(struct mmc_host *host)
2696 host->f_init = max(freqs[0], host->f_min);
2697 host->rescan_disable = 0;
2698 host->ios.power_mode = MMC_POWER_UNDEFINED;
2700 mmc_claim_host(host);
2701 if (host->caps2 & MMC_CAP2_NO_PRESCAN_POWERUP)
2702 mmc_power_off(host);
2704 mmc_power_up(host, host->ocr_avail);
2705 mmc_release_host(host);
2707 mmc_gpiod_request_cd_irq(host);
2708 _mmc_detect_change(host, 0, false);
2711 void mmc_stop_host(struct mmc_host *host)
2713 #ifdef CONFIG_MMC_DEBUG
2714 unsigned long flags;
2715 spin_lock_irqsave(&host->lock, flags);
2717 spin_unlock_irqrestore(&host->lock, flags);
2719 if (host->slot.cd_irq >= 0)
2720 disable_irq(host->slot.cd_irq);
2722 host->rescan_disable = 1;
2723 cancel_delayed_work_sync(&host->detect);
2725 /* clear pm flags now and let card drivers set them as needed */
2729 if (host->bus_ops && !host->bus_dead) {
2730 /* Calling bus_ops->remove() with a claimed host can deadlock */
2731 host->bus_ops->remove(host);
2732 mmc_claim_host(host);
2733 mmc_detach_bus(host);
2734 mmc_power_off(host);
2735 mmc_release_host(host);
2743 mmc_claim_host(host);
2744 mmc_power_off(host);
2745 mmc_release_host(host);
2748 int mmc_power_save_host(struct mmc_host *host)
2752 #ifdef CONFIG_MMC_DEBUG
2753 pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__);
2758 if (!host->bus_ops || host->bus_dead) {
2763 if (host->bus_ops->power_save)
2764 ret = host->bus_ops->power_save(host);
2768 mmc_power_off(host);
2772 EXPORT_SYMBOL(mmc_power_save_host);
2774 int mmc_power_restore_host(struct mmc_host *host)
2778 #ifdef CONFIG_MMC_DEBUG
2779 pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__);
2784 if (!host->bus_ops || host->bus_dead) {
2789 mmc_power_up(host, host->card->ocr);
2790 ret = host->bus_ops->power_restore(host);
2796 EXPORT_SYMBOL(mmc_power_restore_host);
2799 * Flush the cache to the non-volatile storage.
2801 int mmc_flush_cache(struct mmc_card *card)
2805 if (mmc_card_mmc(card) &&
2806 (card->ext_csd.cache_size > 0) &&
2807 (card->ext_csd.cache_ctrl & 1)) {
2808 err = __mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2809 EXT_CSD_FLUSH_CACHE, 1, 0,
2810 true, false, false);
2812 pr_err("%s: cache flush error %d\n",
2813 mmc_hostname(card->host), err);
2818 EXPORT_SYMBOL(mmc_flush_cache);
2822 /* Do the card removal on suspend if card is assumed removeable
2823 * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2826 int mmc_pm_notify(struct notifier_block *notify_block,
2827 unsigned long mode, void *unused)
2829 struct mmc_host *host = container_of(
2830 notify_block, struct mmc_host, pm_notify);
2831 unsigned long flags;
2835 case PM_HIBERNATION_PREPARE:
2836 case PM_SUSPEND_PREPARE:
2837 case PM_RESTORE_PREPARE:
2838 spin_lock_irqsave(&host->lock, flags);
2839 host->rescan_disable = 1;
2840 spin_unlock_irqrestore(&host->lock, flags);
2841 cancel_delayed_work_sync(&host->detect);
2846 /* Validate prerequisites for suspend */
2847 if (host->bus_ops->pre_suspend)
2848 err = host->bus_ops->pre_suspend(host);
2852 /* Calling bus_ops->remove() with a claimed host can deadlock */
2853 host->bus_ops->remove(host);
2854 mmc_claim_host(host);
2855 mmc_detach_bus(host);
2856 mmc_power_off(host);
2857 mmc_release_host(host);
2861 case PM_POST_SUSPEND:
2862 case PM_POST_HIBERNATION:
2863 case PM_POST_RESTORE:
2865 spin_lock_irqsave(&host->lock, flags);
2866 host->rescan_disable = 0;
2867 spin_unlock_irqrestore(&host->lock, flags);
2868 _mmc_detect_change(host, 0, false);
2877 * mmc_init_context_info() - init synchronization context
2880 * Init struct context_info needed to implement asynchronous
2881 * request mechanism, used by mmc core, host driver and mmc requests
2884 void mmc_init_context_info(struct mmc_host *host)
2886 spin_lock_init(&host->context_info.lock);
2887 host->context_info.is_new_req = false;
2888 host->context_info.is_done_rcv = false;
2889 host->context_info.is_waiting_last_req = false;
2890 init_waitqueue_head(&host->context_info.wait);
2893 #ifdef CONFIG_MMC_EMBEDDED_SDIO
2894 void mmc_set_embedded_sdio_data(struct mmc_host *host,
2895 struct sdio_cis *cis,
2896 struct sdio_cccr *cccr,
2897 struct sdio_embedded_func *funcs,
2900 host->embedded_sdio_data.cis = cis;
2901 host->embedded_sdio_data.cccr = cccr;
2902 host->embedded_sdio_data.funcs = funcs;
2903 host->embedded_sdio_data.num_funcs = num_funcs;
2906 EXPORT_SYMBOL(mmc_set_embedded_sdio_data);
2909 static int __init mmc_init(void)
2913 ret = mmc_register_bus();
2917 ret = mmc_register_host_class();
2919 goto unregister_bus;
2921 ret = sdio_register_bus();
2923 goto unregister_host_class;
2927 unregister_host_class:
2928 mmc_unregister_host_class();
2930 mmc_unregister_bus();
2934 static void __exit mmc_exit(void)
2936 sdio_unregister_bus();
2937 mmc_unregister_host_class();
2938 mmc_unregister_bus();
2943 latency_hist_show(struct device *dev, struct device_attribute *attr, char *buf)
2945 struct mmc_host *host = cls_dev_to_mmc_host(dev);
2947 return blk_latency_hist_show(&host->io_lat_s, buf);
2951 * Values permitted 0, 1, 2.
2952 * 0 -> Disable IO latency histograms (default)
2953 * 1 -> Enable IO latency histograms
2954 * 2 -> Zero out IO latency histograms
2957 latency_hist_store(struct device *dev, struct device_attribute *attr,
2958 const char *buf, size_t count)
2960 struct mmc_host *host = cls_dev_to_mmc_host(dev);
2963 if (kstrtol(buf, 0, &value))
2965 if (value == BLK_IO_LAT_HIST_ZERO)
2966 blk_zero_latency_hist(&host->io_lat_s);
2967 else if (value == BLK_IO_LAT_HIST_ENABLE ||
2968 value == BLK_IO_LAT_HIST_DISABLE)
2969 host->latency_hist_enabled = value;
2973 static DEVICE_ATTR(latency_hist, S_IRUGO | S_IWUSR,
2974 latency_hist_show, latency_hist_store);
2977 mmc_latency_hist_sysfs_init(struct mmc_host *host)
2979 if (device_create_file(&host->class_dev, &dev_attr_latency_hist))
2980 dev_err(&host->class_dev,
2981 "Failed to create latency_hist sysfs entry\n");
2985 mmc_latency_hist_sysfs_exit(struct mmc_host *host)
2987 device_remove_file(&host->class_dev, &dev_attr_latency_hist);
2991 subsys_initcall(mmc_init);
2992 module_exit(mmc_exit);
2994 MODULE_LICENSE("GPL");