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 */
66 static struct workqueue_struct *workqueue;
67 static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
70 * Enabling software CRCs on the data blocks can be a significant (30%)
71 * performance cost, and for other reasons may not always be desired.
72 * So we allow it it to be disabled.
75 module_param(use_spi_crc, bool, 0);
78 * Internal function. Schedule delayed work in the MMC work queue.
80 static int mmc_schedule_delayed_work(struct delayed_work *work,
83 return queue_delayed_work(workqueue, work, delay);
87 * Internal function. Flush all scheduled work from the MMC work queue.
89 static void mmc_flush_scheduled_work(void)
91 flush_workqueue(workqueue);
94 #ifdef CONFIG_FAIL_MMC_REQUEST
97 * Internal function. Inject random data errors.
98 * If mmc_data is NULL no errors are injected.
100 static void mmc_should_fail_request(struct mmc_host *host,
101 struct mmc_request *mrq)
103 struct mmc_command *cmd = mrq->cmd;
104 struct mmc_data *data = mrq->data;
105 static const int data_errors[] = {
114 if (cmd->error || data->error ||
115 !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
118 data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)];
119 data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9;
122 #else /* CONFIG_FAIL_MMC_REQUEST */
124 static inline void mmc_should_fail_request(struct mmc_host *host,
125 struct mmc_request *mrq)
129 #endif /* CONFIG_FAIL_MMC_REQUEST */
132 * mmc_request_done - finish processing an MMC request
133 * @host: MMC host which completed request
134 * @mrq: MMC request which request
136 * MMC drivers should call this function when they have completed
137 * their processing of a request.
139 void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
141 struct mmc_command *cmd = mrq->cmd;
142 int err = cmd->error;
144 /* Flag re-tuning needed on CRC errors */
145 if ((cmd->opcode != MMC_SEND_TUNING_BLOCK &&
146 cmd->opcode != MMC_SEND_TUNING_BLOCK_HS200) &&
147 (err == -EILSEQ || (mrq->sbc && mrq->sbc->error == -EILSEQ) ||
148 (mrq->data && mrq->data->error == -EILSEQ) ||
149 (mrq->stop && mrq->stop->error == -EILSEQ)))
150 mmc_retune_needed(host);
152 if (err && cmd->retries && mmc_host_is_spi(host)) {
153 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
157 if (err && cmd->retries && !mmc_card_removed(host->card)) {
159 * Request starter must handle retries - see
160 * mmc_wait_for_req_done().
165 mmc_should_fail_request(host, mrq);
167 led_trigger_event(host->led, LED_OFF);
170 pr_debug("%s: req done <CMD%u>: %d: %08x %08x %08x %08x\n",
171 mmc_hostname(host), mrq->sbc->opcode,
173 mrq->sbc->resp[0], mrq->sbc->resp[1],
174 mrq->sbc->resp[2], mrq->sbc->resp[3]);
177 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
178 mmc_hostname(host), cmd->opcode, err,
179 cmd->resp[0], cmd->resp[1],
180 cmd->resp[2], cmd->resp[3]);
183 pr_debug("%s: %d bytes transferred: %d\n",
185 mrq->data->bytes_xfered, mrq->data->error);
187 if (mrq->lat_hist_enabled) {
191 completion = ktime_get();
192 delta_us = ktime_us_delta(completion,
194 blk_update_latency_hist(&host->io_lat_s,
195 (mrq->data->flags & MMC_DATA_READ),
199 trace_mmc_blk_rw_end(cmd->opcode, cmd->arg, mrq->data);
203 pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n",
204 mmc_hostname(host), mrq->stop->opcode,
206 mrq->stop->resp[0], mrq->stop->resp[1],
207 mrq->stop->resp[2], mrq->stop->resp[3]);
215 EXPORT_SYMBOL(mmc_request_done);
217 static void __mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
221 /* Assumes host controller has been runtime resumed by mmc_claim_host */
222 err = mmc_retune(host);
224 mrq->cmd->error = err;
225 mmc_request_done(host, mrq);
230 * For sdio rw commands we must wait for card busy otherwise some
231 * sdio devices won't work properly.
233 if (mmc_is_io_op(mrq->cmd->opcode) && host->ops->card_busy) {
234 int tries = 500; /* Wait aprox 500ms at maximum */
236 while (host->ops->card_busy(host) && --tries)
240 mrq->cmd->error = -EBUSY;
241 mmc_request_done(host, mrq);
246 host->ops->request(host, mrq);
249 static int mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
251 #ifdef CONFIG_MMC_DEBUG
253 struct scatterlist *sg;
255 mmc_retune_hold(host);
257 if (mmc_card_removed(host->card))
261 pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n",
262 mmc_hostname(host), mrq->sbc->opcode,
263 mrq->sbc->arg, mrq->sbc->flags);
266 pr_debug("%s: starting CMD%u arg %08x flags %08x\n",
267 mmc_hostname(host), mrq->cmd->opcode,
268 mrq->cmd->arg, mrq->cmd->flags);
271 pr_debug("%s: blksz %d blocks %d flags %08x "
272 "tsac %d ms nsac %d\n",
273 mmc_hostname(host), mrq->data->blksz,
274 mrq->data->blocks, mrq->data->flags,
275 mrq->data->timeout_ns / 1000000,
276 mrq->data->timeout_clks);
280 pr_debug("%s: CMD%u arg %08x flags %08x\n",
281 mmc_hostname(host), mrq->stop->opcode,
282 mrq->stop->arg, mrq->stop->flags);
285 WARN_ON(!host->claimed);
294 BUG_ON(mrq->data->blksz > host->max_blk_size);
295 BUG_ON(mrq->data->blocks > host->max_blk_count);
296 BUG_ON(mrq->data->blocks * mrq->data->blksz >
299 #ifdef CONFIG_MMC_DEBUG
301 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
303 BUG_ON(sz != mrq->data->blocks * mrq->data->blksz);
306 mrq->cmd->data = mrq->data;
307 mrq->data->error = 0;
308 mrq->data->mrq = mrq;
310 mrq->data->stop = mrq->stop;
311 mrq->stop->error = 0;
312 mrq->stop->mrq = mrq;
315 led_trigger_event(host->led, LED_FULL);
316 __mmc_start_request(host, mrq);
322 * mmc_start_bkops - start BKOPS for supported cards
323 * @card: MMC card to start BKOPS
324 * @form_exception: A flag to indicate if this function was
325 * called due to an exception raised by the card
327 * Start background operations whenever requested.
328 * When the urgent BKOPS bit is set in a R1 command response
329 * then background operations should be started immediately.
331 void mmc_start_bkops(struct mmc_card *card, bool from_exception)
335 bool use_busy_signal;
339 if (!card->ext_csd.man_bkops_en || mmc_card_doing_bkops(card))
342 err = mmc_read_bkops_status(card);
344 pr_err("%s: Failed to read bkops status: %d\n",
345 mmc_hostname(card->host), err);
349 if (!card->ext_csd.raw_bkops_status)
352 if (card->ext_csd.raw_bkops_status < EXT_CSD_BKOPS_LEVEL_2 &&
356 mmc_claim_host(card->host);
357 if (card->ext_csd.raw_bkops_status >= EXT_CSD_BKOPS_LEVEL_2) {
358 timeout = MMC_BKOPS_MAX_TIMEOUT;
359 use_busy_signal = true;
362 use_busy_signal = false;
365 mmc_retune_hold(card->host);
367 err = __mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
368 EXT_CSD_BKOPS_START, 1, timeout,
369 use_busy_signal, true, false);
371 pr_warn("%s: Error %d starting bkops\n",
372 mmc_hostname(card->host), err);
373 mmc_retune_release(card->host);
378 * For urgent bkops status (LEVEL_2 and more)
379 * bkops executed synchronously, otherwise
380 * the operation is in progress
382 if (!use_busy_signal)
383 mmc_card_set_doing_bkops(card);
385 mmc_retune_release(card->host);
387 mmc_release_host(card->host);
389 EXPORT_SYMBOL(mmc_start_bkops);
392 * mmc_wait_data_done() - done callback for data request
393 * @mrq: done data request
395 * Wakes up mmc context, passed as a callback to host controller driver
397 static void mmc_wait_data_done(struct mmc_request *mrq)
399 struct mmc_context_info *context_info = &mrq->host->context_info;
401 context_info->is_done_rcv = true;
402 wake_up_interruptible(&context_info->wait);
405 static void mmc_wait_done(struct mmc_request *mrq)
407 complete(&mrq->completion);
411 *__mmc_start_data_req() - starts data request
412 * @host: MMC host to start the request
413 * @mrq: data request to start
415 * Sets the done callback to be called when request is completed by the card.
416 * Starts data mmc request execution
418 static int __mmc_start_data_req(struct mmc_host *host, struct mmc_request *mrq)
422 mrq->done = mmc_wait_data_done;
425 err = mmc_start_request(host, mrq);
427 mrq->cmd->error = err;
428 mmc_wait_data_done(mrq);
434 static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
438 init_completion(&mrq->completion);
439 mrq->done = mmc_wait_done;
441 err = mmc_start_request(host, mrq);
443 mrq->cmd->error = err;
444 complete(&mrq->completion);
451 * mmc_wait_for_data_req_done() - wait for request completed
452 * @host: MMC host to prepare the command.
453 * @mrq: MMC request to wait for
455 * Blocks MMC context till host controller will ack end of data request
456 * execution or new request notification arrives from the block layer.
457 * Handles command retries.
459 * Returns enum mmc_blk_status after checking errors.
461 static int mmc_wait_for_data_req_done(struct mmc_host *host,
462 struct mmc_request *mrq,
463 struct mmc_async_req *next_req)
465 struct mmc_command *cmd;
466 struct mmc_context_info *context_info = &host->context_info;
471 wait_event_interruptible(context_info->wait,
472 (context_info->is_done_rcv ||
473 context_info->is_new_req));
474 spin_lock_irqsave(&context_info->lock, flags);
475 context_info->is_waiting_last_req = false;
476 spin_unlock_irqrestore(&context_info->lock, flags);
477 if (context_info->is_done_rcv) {
478 context_info->is_done_rcv = false;
479 context_info->is_new_req = false;
482 if (!cmd->error || !cmd->retries ||
483 mmc_card_removed(host->card)) {
484 err = host->areq->err_check(host->card,
486 break; /* return err */
488 mmc_retune_recheck(host);
489 pr_info("%s: req failed (CMD%u): %d, retrying...\n",
491 cmd->opcode, cmd->error);
494 __mmc_start_request(host, mrq);
495 continue; /* wait for done/new event again */
497 } else if (context_info->is_new_req) {
498 context_info->is_new_req = false;
500 return MMC_BLK_NEW_REQUEST;
503 mmc_retune_release(host);
507 static void mmc_wait_for_req_done(struct mmc_host *host,
508 struct mmc_request *mrq)
510 struct mmc_command *cmd;
513 wait_for_completion(&mrq->completion);
518 * If host has timed out waiting for the sanitize
519 * to complete, card might be still in programming state
520 * so let's try to bring the card out of programming
523 if (cmd->sanitize_busy && cmd->error == -ETIMEDOUT) {
524 if (!mmc_interrupt_hpi(host->card)) {
525 pr_warn("%s: %s: Interrupted sanitize\n",
526 mmc_hostname(host), __func__);
530 pr_err("%s: %s: Failed to interrupt sanitize\n",
531 mmc_hostname(host), __func__);
534 if (!cmd->error || !cmd->retries ||
535 mmc_card_removed(host->card))
538 mmc_retune_recheck(host);
540 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
541 mmc_hostname(host), cmd->opcode, cmd->error);
544 __mmc_start_request(host, mrq);
547 mmc_retune_release(host);
551 * mmc_pre_req - Prepare for a new request
552 * @host: MMC host to prepare command
553 * @mrq: MMC request to prepare for
554 * @is_first_req: true if there is no previous started request
555 * that may run in parellel to this call, otherwise false
557 * mmc_pre_req() is called in prior to mmc_start_req() to let
558 * host prepare for the new request. Preparation of a request may be
559 * performed while another request is running on the host.
561 static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq,
564 if (host->ops->pre_req)
565 host->ops->pre_req(host, mrq, is_first_req);
569 * mmc_post_req - Post process a completed request
570 * @host: MMC host to post process command
571 * @mrq: MMC request to post process for
572 * @err: Error, if non zero, clean up any resources made in pre_req
574 * Let the host post process a completed request. Post processing of
575 * a request may be performed while another reuqest is running.
577 static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq,
580 if (host->ops->post_req)
581 host->ops->post_req(host, mrq, err);
585 * mmc_start_req - start a non-blocking request
586 * @host: MMC host to start command
587 * @areq: async request to start
588 * @error: out parameter returns 0 for success, otherwise non zero
590 * Start a new MMC custom command request for a host.
591 * If there is on ongoing async request wait for completion
592 * of that request and start the new one and return.
593 * Does not wait for the new request to complete.
595 * Returns the completed request, NULL in case of none completed.
596 * Wait for the an ongoing request (previoulsy started) to complete and
597 * return the completed request. If there is no ongoing request, NULL
598 * is returned without waiting. NULL is not an error condition.
600 struct mmc_async_req *mmc_start_req(struct mmc_host *host,
601 struct mmc_async_req *areq, int *error)
605 struct mmc_async_req *data = host->areq;
607 /* Prepare a new request */
609 mmc_pre_req(host, areq->mrq, !host->areq);
612 err = mmc_wait_for_data_req_done(host, host->areq->mrq, areq);
613 if (err == MMC_BLK_NEW_REQUEST) {
617 * The previous request was not completed,
623 * Check BKOPS urgency for each R1 response
625 if (host->card && mmc_card_mmc(host->card) &&
626 ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) ||
627 (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) &&
628 (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT)) {
630 /* Cancel the prepared request */
632 mmc_post_req(host, areq->mrq, -EINVAL);
634 mmc_start_bkops(host->card, true);
636 /* prepare the request again */
638 mmc_pre_req(host, areq->mrq, !host->areq);
644 if (host->latency_hist_enabled) {
645 areq->mrq->io_start = ktime_get();
646 areq->mrq->lat_hist_enabled = 1;
648 areq->mrq->lat_hist_enabled = 0;
650 trace_mmc_blk_rw_start(areq->mrq->cmd->opcode,
653 start_err = __mmc_start_data_req(host, areq->mrq);
657 mmc_post_req(host, host->areq->mrq, 0);
659 /* Cancel a prepared request if it was not started. */
660 if ((err || start_err) && areq)
661 mmc_post_req(host, areq->mrq, -EINVAL);
672 EXPORT_SYMBOL(mmc_start_req);
675 * mmc_wait_for_req - start a request and wait for completion
676 * @host: MMC host to start command
677 * @mrq: MMC request to start
679 * Start a new MMC custom command request for a host, and wait
680 * for the command to complete. Does not attempt to parse the
683 void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
685 __mmc_start_req(host, mrq);
686 mmc_wait_for_req_done(host, mrq);
688 EXPORT_SYMBOL(mmc_wait_for_req);
691 * mmc_interrupt_hpi - Issue for High priority Interrupt
692 * @card: the MMC card associated with the HPI transfer
694 * Issued High Priority Interrupt, and check for card status
695 * until out-of prg-state.
697 int mmc_interrupt_hpi(struct mmc_card *card)
701 unsigned long prg_wait;
705 if (!card->ext_csd.hpi_en) {
706 pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host));
710 mmc_claim_host(card->host);
711 err = mmc_send_status(card, &status);
713 pr_err("%s: Get card status fail\n", mmc_hostname(card->host));
717 switch (R1_CURRENT_STATE(status)) {
723 * In idle and transfer states, HPI is not needed and the caller
724 * can issue the next intended command immediately
730 /* In all other states, it's illegal to issue HPI */
731 pr_debug("%s: HPI cannot be sent. Card state=%d\n",
732 mmc_hostname(card->host), R1_CURRENT_STATE(status));
737 err = mmc_send_hpi_cmd(card, &status);
741 prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time);
743 err = mmc_send_status(card, &status);
745 if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN)
747 if (time_after(jiffies, prg_wait))
752 mmc_release_host(card->host);
755 EXPORT_SYMBOL(mmc_interrupt_hpi);
758 * mmc_wait_for_cmd - start a command and wait for completion
759 * @host: MMC host to start command
760 * @cmd: MMC command to start
761 * @retries: maximum number of retries
763 * Start a new MMC command for a host, and wait for the command
764 * to complete. Return any error that occurred while the command
765 * was executing. Do not attempt to parse the response.
767 int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
769 struct mmc_request mrq = {NULL};
771 WARN_ON(!host->claimed);
773 memset(cmd->resp, 0, sizeof(cmd->resp));
774 cmd->retries = retries;
779 mmc_wait_for_req(host, &mrq);
784 EXPORT_SYMBOL(mmc_wait_for_cmd);
787 * mmc_stop_bkops - stop ongoing BKOPS
788 * @card: MMC card to check BKOPS
790 * Send HPI command to stop ongoing background operations to
791 * allow rapid servicing of foreground operations, e.g. read/
792 * writes. Wait until the card comes out of the programming state
793 * to avoid errors in servicing read/write requests.
795 int mmc_stop_bkops(struct mmc_card *card)
800 err = mmc_interrupt_hpi(card);
803 * If err is EINVAL, we can't issue an HPI.
804 * It should complete the BKOPS.
806 if (!err || (err == -EINVAL)) {
807 mmc_card_clr_doing_bkops(card);
808 mmc_retune_release(card->host);
814 EXPORT_SYMBOL(mmc_stop_bkops);
816 int mmc_read_bkops_status(struct mmc_card *card)
821 mmc_claim_host(card->host);
822 err = mmc_get_ext_csd(card, &ext_csd);
823 mmc_release_host(card->host);
827 card->ext_csd.raw_bkops_status = ext_csd[EXT_CSD_BKOPS_STATUS];
828 card->ext_csd.raw_exception_status = ext_csd[EXT_CSD_EXP_EVENTS_STATUS];
832 EXPORT_SYMBOL(mmc_read_bkops_status);
835 * mmc_set_data_timeout - set the timeout for a data command
836 * @data: data phase for command
837 * @card: the MMC card associated with the data transfer
839 * Computes the data timeout parameters according to the
840 * correct algorithm given the card type.
842 void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
847 * SDIO cards only define an upper 1 s limit on access.
849 if (mmc_card_sdio(card)) {
850 data->timeout_ns = 1000000000;
851 data->timeout_clks = 0;
856 * SD cards use a 100 multiplier rather than 10
858 mult = mmc_card_sd(card) ? 100 : 10;
861 * Scale up the multiplier (and therefore the timeout) by
862 * the r2w factor for writes.
864 if (data->flags & MMC_DATA_WRITE)
865 mult <<= card->csd.r2w_factor;
867 data->timeout_ns = card->csd.tacc_ns * mult;
868 data->timeout_clks = card->csd.tacc_clks * mult;
871 * SD cards also have an upper limit on the timeout.
873 if (mmc_card_sd(card)) {
874 unsigned int timeout_us, limit_us;
876 timeout_us = data->timeout_ns / 1000;
877 if (card->host->ios.clock)
878 timeout_us += data->timeout_clks * 1000 /
879 (card->host->ios.clock / 1000);
881 if (data->flags & MMC_DATA_WRITE)
883 * The MMC spec "It is strongly recommended
884 * for hosts to implement more than 500ms
885 * timeout value even if the card indicates
886 * the 250ms maximum busy length." Even the
887 * previous value of 300ms is known to be
888 * insufficient for some cards.
895 * SDHC cards always use these fixed values.
897 if (timeout_us > limit_us || mmc_card_blockaddr(card)) {
898 data->timeout_ns = limit_us * 1000;
899 data->timeout_clks = 0;
902 /* assign limit value if invalid */
904 data->timeout_ns = limit_us * 1000;
908 * Some cards require longer data read timeout than indicated in CSD.
909 * Address this by setting the read timeout to a "reasonably high"
910 * value. For the cards tested, 600ms has proven enough. If necessary,
911 * this value can be increased if other problematic cards require this.
913 if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
914 data->timeout_ns = 600000000;
915 data->timeout_clks = 0;
919 * Some cards need very high timeouts if driven in SPI mode.
920 * The worst observed timeout was 900ms after writing a
921 * continuous stream of data until the internal logic
924 if (mmc_host_is_spi(card->host)) {
925 if (data->flags & MMC_DATA_WRITE) {
926 if (data->timeout_ns < 1000000000)
927 data->timeout_ns = 1000000000; /* 1s */
929 if (data->timeout_ns < 100000000)
930 data->timeout_ns = 100000000; /* 100ms */
934 EXPORT_SYMBOL(mmc_set_data_timeout);
937 * mmc_align_data_size - pads a transfer size to a more optimal value
938 * @card: the MMC card associated with the data transfer
939 * @sz: original transfer size
941 * Pads the original data size with a number of extra bytes in
942 * order to avoid controller bugs and/or performance hits
943 * (e.g. some controllers revert to PIO for certain sizes).
945 * Returns the improved size, which might be unmodified.
947 * Note that this function is only relevant when issuing a
948 * single scatter gather entry.
950 unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
953 * FIXME: We don't have a system for the controller to tell
954 * the core about its problems yet, so for now we just 32-bit
957 sz = ((sz + 3) / 4) * 4;
961 EXPORT_SYMBOL(mmc_align_data_size);
964 * __mmc_claim_host - exclusively claim a host
965 * @host: mmc host to claim
966 * @abort: whether or not the operation should be aborted
968 * Claim a host for a set of operations. If @abort is non null and
969 * dereference a non-zero value then this will return prematurely with
970 * that non-zero value without acquiring the lock. Returns zero
971 * with the lock held otherwise.
973 int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
975 DECLARE_WAITQUEUE(wait, current);
982 add_wait_queue(&host->wq, &wait);
983 spin_lock_irqsave(&host->lock, flags);
985 set_current_state(TASK_UNINTERRUPTIBLE);
986 stop = abort ? atomic_read(abort) : 0;
987 if (stop || !host->claimed || host->claimer == current)
989 spin_unlock_irqrestore(&host->lock, flags);
991 spin_lock_irqsave(&host->lock, flags);
993 set_current_state(TASK_RUNNING);
996 host->claimer = current;
997 host->claim_cnt += 1;
998 if (host->claim_cnt == 1)
1002 spin_unlock_irqrestore(&host->lock, flags);
1003 remove_wait_queue(&host->wq, &wait);
1006 pm_runtime_get_sync(mmc_dev(host));
1010 EXPORT_SYMBOL(__mmc_claim_host);
1013 * mmc_release_host - release a host
1014 * @host: mmc host to release
1016 * Release a MMC host, allowing others to claim the host
1017 * for their operations.
1019 void mmc_release_host(struct mmc_host *host)
1021 unsigned long flags;
1023 WARN_ON(!host->claimed);
1025 spin_lock_irqsave(&host->lock, flags);
1026 if (--host->claim_cnt) {
1027 /* Release for nested claim */
1028 spin_unlock_irqrestore(&host->lock, flags);
1031 host->claimer = NULL;
1032 spin_unlock_irqrestore(&host->lock, flags);
1034 pm_runtime_mark_last_busy(mmc_dev(host));
1035 pm_runtime_put_autosuspend(mmc_dev(host));
1038 EXPORT_SYMBOL(mmc_release_host);
1041 * This is a helper function, which fetches a runtime pm reference for the
1042 * card device and also claims the host.
1044 void mmc_get_card(struct mmc_card *card)
1046 pm_runtime_get_sync(&card->dev);
1047 mmc_claim_host(card->host);
1049 EXPORT_SYMBOL(mmc_get_card);
1052 * This is a helper function, which releases the host and drops the runtime
1053 * pm reference for the card device.
1055 void mmc_put_card(struct mmc_card *card)
1057 mmc_release_host(card->host);
1058 pm_runtime_mark_last_busy(&card->dev);
1059 pm_runtime_put_autosuspend(&card->dev);
1061 EXPORT_SYMBOL(mmc_put_card);
1064 * Internal function that does the actual ios call to the host driver,
1065 * optionally printing some debug output.
1067 static inline void mmc_set_ios(struct mmc_host *host)
1069 struct mmc_ios *ios = &host->ios;
1071 pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
1072 "width %u timing %u\n",
1073 mmc_hostname(host), ios->clock, ios->bus_mode,
1074 ios->power_mode, ios->chip_select, ios->vdd,
1075 ios->bus_width, ios->timing);
1077 host->ops->set_ios(host, ios);
1081 * Control chip select pin on a host.
1083 void mmc_set_chip_select(struct mmc_host *host, int mode)
1085 host->ios.chip_select = mode;
1090 * Sets the host clock to the highest possible frequency that
1093 void mmc_set_clock(struct mmc_host *host, unsigned int hz)
1095 WARN_ON(hz && hz < host->f_min);
1097 if (hz > host->f_max)
1100 host->ios.clock = hz;
1104 int mmc_execute_tuning(struct mmc_card *card)
1106 struct mmc_host *host = card->host;
1110 if (!host->ops->execute_tuning)
1113 if (mmc_card_mmc(card))
1114 opcode = MMC_SEND_TUNING_BLOCK_HS200;
1116 opcode = MMC_SEND_TUNING_BLOCK;
1118 err = host->ops->execute_tuning(host, opcode);
1121 pr_err("%s: tuning execution failed\n", mmc_hostname(host));
1123 mmc_retune_enable(host);
1129 * Change the bus mode (open drain/push-pull) of a host.
1131 void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
1133 host->ios.bus_mode = mode;
1138 * Change data bus width of a host.
1140 void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
1142 host->ios.bus_width = width;
1147 * Set initial state after a power cycle or a hw_reset.
1149 void mmc_set_initial_state(struct mmc_host *host)
1151 mmc_retune_disable(host);
1153 if (mmc_host_is_spi(host))
1154 host->ios.chip_select = MMC_CS_HIGH;
1156 host->ios.chip_select = MMC_CS_DONTCARE;
1157 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1158 host->ios.bus_width = MMC_BUS_WIDTH_1;
1159 host->ios.timing = MMC_TIMING_LEGACY;
1160 host->ios.drv_type = 0;
1166 * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
1167 * @vdd: voltage (mV)
1168 * @low_bits: prefer low bits in boundary cases
1170 * This function returns the OCR bit number according to the provided @vdd
1171 * value. If conversion is not possible a negative errno value returned.
1173 * Depending on the @low_bits flag the function prefers low or high OCR bits
1174 * on boundary voltages. For example,
1175 * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
1176 * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1178 * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1180 static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1182 const int max_bit = ilog2(MMC_VDD_35_36);
1185 if (vdd < 1650 || vdd > 3600)
1188 if (vdd >= 1650 && vdd <= 1950)
1189 return ilog2(MMC_VDD_165_195);
1194 /* Base 2000 mV, step 100 mV, bit's base 8. */
1195 bit = (vdd - 2000) / 100 + 8;
1202 * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1203 * @vdd_min: minimum voltage value (mV)
1204 * @vdd_max: maximum voltage value (mV)
1206 * This function returns the OCR mask bits according to the provided @vdd_min
1207 * and @vdd_max values. If conversion is not possible the function returns 0.
1209 * Notes wrt boundary cases:
1210 * This function sets the OCR bits for all boundary voltages, for example
1211 * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1212 * MMC_VDD_34_35 mask.
1214 u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1218 if (vdd_max < vdd_min)
1221 /* Prefer high bits for the boundary vdd_max values. */
1222 vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1226 /* Prefer low bits for the boundary vdd_min values. */
1227 vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1231 /* Fill the mask, from max bit to min bit. */
1232 while (vdd_max >= vdd_min)
1233 mask |= 1 << vdd_max--;
1237 EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
1242 * mmc_of_parse_voltage - return mask of supported voltages
1243 * @np: The device node need to be parsed.
1244 * @mask: mask of voltages available for MMC/SD/SDIO
1246 * 1. Return zero on success.
1247 * 2. Return negative errno: voltage-range is invalid.
1249 int mmc_of_parse_voltage(struct device_node *np, u32 *mask)
1251 const u32 *voltage_ranges;
1254 voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges);
1255 num_ranges = num_ranges / sizeof(*voltage_ranges) / 2;
1256 if (!voltage_ranges || !num_ranges) {
1257 pr_info("%s: voltage-ranges unspecified\n", np->full_name);
1261 for (i = 0; i < num_ranges; i++) {
1262 const int j = i * 2;
1265 ocr_mask = mmc_vddrange_to_ocrmask(
1266 be32_to_cpu(voltage_ranges[j]),
1267 be32_to_cpu(voltage_ranges[j + 1]));
1269 pr_err("%s: voltage-range #%d is invalid\n",
1278 EXPORT_SYMBOL(mmc_of_parse_voltage);
1280 #endif /* CONFIG_OF */
1282 static int mmc_of_get_func_num(struct device_node *node)
1287 ret = of_property_read_u32(node, "reg", ®);
1294 struct device_node *mmc_of_find_child_device(struct mmc_host *host,
1297 struct device_node *node;
1299 if (!host->parent || !host->parent->of_node)
1302 for_each_child_of_node(host->parent->of_node, node) {
1303 if (mmc_of_get_func_num(node) == func_num)
1310 #ifdef CONFIG_REGULATOR
1313 * mmc_ocrbitnum_to_vdd - Convert a OCR bit number to its voltage
1314 * @vdd_bit: OCR bit number
1315 * @min_uV: minimum voltage value (mV)
1316 * @max_uV: maximum voltage value (mV)
1318 * This function returns the voltage range according to the provided OCR
1319 * bit number. If conversion is not possible a negative errno value returned.
1321 static int mmc_ocrbitnum_to_vdd(int vdd_bit, int *min_uV, int *max_uV)
1329 * REVISIT mmc_vddrange_to_ocrmask() may have set some
1330 * bits this regulator doesn't quite support ... don't
1331 * be too picky, most cards and regulators are OK with
1332 * a 0.1V range goof (it's a small error percentage).
1334 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
1336 *min_uV = 1650 * 1000;
1337 *max_uV = 1950 * 1000;
1339 *min_uV = 1900 * 1000 + tmp * 100 * 1000;
1340 *max_uV = *min_uV + 100 * 1000;
1347 * mmc_regulator_get_ocrmask - return mask of supported voltages
1348 * @supply: regulator to use
1350 * This returns either a negative errno, or a mask of voltages that
1351 * can be provided to MMC/SD/SDIO devices using the specified voltage
1352 * regulator. This would normally be called before registering the
1355 int mmc_regulator_get_ocrmask(struct regulator *supply)
1363 count = regulator_count_voltages(supply);
1367 for (i = 0; i < count; i++) {
1368 vdd_uV = regulator_list_voltage(supply, i);
1372 vdd_mV = vdd_uV / 1000;
1373 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1377 vdd_uV = regulator_get_voltage(supply);
1381 vdd_mV = vdd_uV / 1000;
1382 result = mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1387 EXPORT_SYMBOL_GPL(mmc_regulator_get_ocrmask);
1390 * mmc_regulator_set_ocr - set regulator to match host->ios voltage
1391 * @mmc: the host to regulate
1392 * @supply: regulator to use
1393 * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
1395 * Returns zero on success, else negative errno.
1397 * MMC host drivers may use this to enable or disable a regulator using
1398 * a particular supply voltage. This would normally be called from the
1401 int mmc_regulator_set_ocr(struct mmc_host *mmc,
1402 struct regulator *supply,
1403 unsigned short vdd_bit)
1409 mmc_ocrbitnum_to_vdd(vdd_bit, &min_uV, &max_uV);
1411 result = regulator_set_voltage(supply, min_uV, max_uV);
1412 if (result == 0 && !mmc->regulator_enabled) {
1413 result = regulator_enable(supply);
1415 mmc->regulator_enabled = true;
1417 } else if (mmc->regulator_enabled) {
1418 result = regulator_disable(supply);
1420 mmc->regulator_enabled = false;
1424 dev_err(mmc_dev(mmc),
1425 "could not set regulator OCR (%d)\n", result);
1428 EXPORT_SYMBOL_GPL(mmc_regulator_set_ocr);
1430 static int mmc_regulator_set_voltage_if_supported(struct regulator *regulator,
1431 int min_uV, int target_uV,
1435 * Check if supported first to avoid errors since we may try several
1436 * signal levels during power up and don't want to show errors.
1438 if (!regulator_is_supported_voltage(regulator, min_uV, max_uV))
1441 return regulator_set_voltage_triplet(regulator, min_uV, target_uV,
1446 * mmc_regulator_set_vqmmc - Set VQMMC as per the ios
1448 * For 3.3V signaling, we try to match VQMMC to VMMC as closely as possible.
1449 * That will match the behavior of old boards where VQMMC and VMMC were supplied
1450 * by the same supply. The Bus Operating conditions for 3.3V signaling in the
1451 * SD card spec also define VQMMC in terms of VMMC.
1452 * If this is not possible we'll try the full 2.7-3.6V of the spec.
1454 * For 1.2V and 1.8V signaling we'll try to get as close as possible to the
1455 * requested voltage. This is definitely a good idea for UHS where there's a
1456 * separate regulator on the card that's trying to make 1.8V and it's best if
1459 * This function is expected to be used by a controller's
1460 * start_signal_voltage_switch() function.
1462 int mmc_regulator_set_vqmmc(struct mmc_host *mmc, struct mmc_ios *ios)
1464 struct device *dev = mmc_dev(mmc);
1465 int ret, volt, min_uV, max_uV;
1467 /* If no vqmmc supply then we can't change the voltage */
1468 if (IS_ERR(mmc->supply.vqmmc))
1471 switch (ios->signal_voltage) {
1472 case MMC_SIGNAL_VOLTAGE_120:
1473 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1474 1100000, 1200000, 1300000);
1475 case MMC_SIGNAL_VOLTAGE_180:
1476 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1477 1700000, 1800000, 1950000);
1478 case MMC_SIGNAL_VOLTAGE_330:
1479 ret = mmc_ocrbitnum_to_vdd(mmc->ios.vdd, &volt, &max_uV);
1483 dev_dbg(dev, "%s: found vmmc voltage range of %d-%duV\n",
1484 __func__, volt, max_uV);
1486 min_uV = max(volt - 300000, 2700000);
1487 max_uV = min(max_uV + 200000, 3600000);
1490 * Due to a limitation in the current implementation of
1491 * regulator_set_voltage_triplet() which is taking the lowest
1492 * voltage possible if below the target, search for a suitable
1493 * voltage in two steps and try to stay close to vmmc
1494 * with a 0.3V tolerance at first.
1496 if (!mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1497 min_uV, volt, max_uV))
1500 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1501 2700000, volt, 3600000);
1506 EXPORT_SYMBOL_GPL(mmc_regulator_set_vqmmc);
1508 #endif /* CONFIG_REGULATOR */
1510 int mmc_regulator_get_supply(struct mmc_host *mmc)
1512 struct device *dev = mmc_dev(mmc);
1515 mmc->supply.vmmc = devm_regulator_get_optional(dev, "vmmc");
1516 mmc->supply.vqmmc = devm_regulator_get_optional(dev, "vqmmc");
1518 if (IS_ERR(mmc->supply.vmmc)) {
1519 if (PTR_ERR(mmc->supply.vmmc) == -EPROBE_DEFER)
1520 return -EPROBE_DEFER;
1521 dev_info(dev, "No vmmc regulator found\n");
1523 ret = mmc_regulator_get_ocrmask(mmc->supply.vmmc);
1525 mmc->ocr_avail = ret;
1527 dev_warn(dev, "Failed getting OCR mask: %d\n", ret);
1530 if (IS_ERR(mmc->supply.vqmmc)) {
1531 if (PTR_ERR(mmc->supply.vqmmc) == -EPROBE_DEFER)
1532 return -EPROBE_DEFER;
1533 dev_info(dev, "No vqmmc regulator found\n");
1538 EXPORT_SYMBOL_GPL(mmc_regulator_get_supply);
1541 * Mask off any voltages we don't support and select
1542 * the lowest voltage
1544 u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1549 * Sanity check the voltages that the card claims to
1553 dev_warn(mmc_dev(host),
1554 "card claims to support voltages below defined range\n");
1558 ocr &= host->ocr_avail;
1560 dev_warn(mmc_dev(host), "no support for card's volts\n");
1564 if (host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) {
1567 mmc_power_cycle(host, ocr);
1571 if (bit != host->ios.vdd)
1572 dev_warn(mmc_dev(host), "exceeding card's volts\n");
1578 int __mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage)
1581 int old_signal_voltage = host->ios.signal_voltage;
1583 host->ios.signal_voltage = signal_voltage;
1584 if (host->ops->start_signal_voltage_switch)
1585 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1588 host->ios.signal_voltage = old_signal_voltage;
1594 int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, u32 ocr)
1596 struct mmc_command cmd = {0};
1603 * Send CMD11 only if the request is to switch the card to
1606 if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
1607 return __mmc_set_signal_voltage(host, signal_voltage);
1610 * If we cannot switch voltages, return failure so the caller
1611 * can continue without UHS mode
1613 if (!host->ops->start_signal_voltage_switch)
1615 if (!host->ops->card_busy)
1616 pr_warn("%s: cannot verify signal voltage switch\n",
1617 mmc_hostname(host));
1619 cmd.opcode = SD_SWITCH_VOLTAGE;
1621 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1623 err = mmc_wait_for_cmd(host, &cmd, 0);
1627 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1631 * The card should drive cmd and dat[0:3] low immediately
1632 * after the response of cmd11, but wait 1 ms to be sure
1635 if (host->ops->card_busy && !host->ops->card_busy(host)) {
1640 * During a signal voltage level switch, the clock must be gated
1641 * for 5 ms according to the SD spec
1643 clock = host->ios.clock;
1644 host->ios.clock = 0;
1647 if (__mmc_set_signal_voltage(host, signal_voltage)) {
1649 * Voltages may not have been switched, but we've already
1650 * sent CMD11, so a power cycle is required anyway
1656 /* Keep clock gated for at least 10 ms, though spec only says 5 ms */
1658 host->ios.clock = clock;
1661 /* Wait for at least 1 ms according to spec */
1665 * Failure to switch is indicated by the card holding
1668 if (host->ops->card_busy && host->ops->card_busy(host))
1673 pr_debug("%s: Signal voltage switch failed, "
1674 "power cycling card\n", mmc_hostname(host));
1675 mmc_power_cycle(host, ocr);
1682 * Select timing parameters for host.
1684 void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1686 host->ios.timing = timing;
1691 * Select appropriate driver type for host.
1693 void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1695 host->ios.drv_type = drv_type;
1699 int mmc_select_drive_strength(struct mmc_card *card, unsigned int max_dtr,
1700 int card_drv_type, int *drv_type)
1702 struct mmc_host *host = card->host;
1703 int host_drv_type = SD_DRIVER_TYPE_B;
1707 if (!host->ops->select_drive_strength)
1710 /* Use SD definition of driver strength for hosts */
1711 if (host->caps & MMC_CAP_DRIVER_TYPE_A)
1712 host_drv_type |= SD_DRIVER_TYPE_A;
1714 if (host->caps & MMC_CAP_DRIVER_TYPE_C)
1715 host_drv_type |= SD_DRIVER_TYPE_C;
1717 if (host->caps & MMC_CAP_DRIVER_TYPE_D)
1718 host_drv_type |= SD_DRIVER_TYPE_D;
1721 * The drive strength that the hardware can support
1722 * depends on the board design. Pass the appropriate
1723 * information and let the hardware specific code
1724 * return what is possible given the options
1726 return host->ops->select_drive_strength(card, max_dtr,
1733 * Apply power to the MMC stack. This is a two-stage process.
1734 * First, we enable power to the card without the clock running.
1735 * We then wait a bit for the power to stabilise. Finally,
1736 * enable the bus drivers and clock to the card.
1738 * We must _NOT_ enable the clock prior to power stablising.
1740 * If a host does all the power sequencing itself, ignore the
1741 * initial MMC_POWER_UP stage.
1743 void mmc_power_up(struct mmc_host *host, u32 ocr)
1745 if (host->ios.power_mode == MMC_POWER_ON)
1748 mmc_pwrseq_pre_power_on(host);
1750 host->ios.vdd = fls(ocr) - 1;
1751 host->ios.power_mode = MMC_POWER_UP;
1752 /* Set initial state and call mmc_set_ios */
1753 mmc_set_initial_state(host);
1755 /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */
1756 if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330) == 0)
1757 dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n");
1758 else if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180) == 0)
1759 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n");
1760 else if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_120) == 0)
1761 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n");
1764 * This delay should be sufficient to allow the power supply
1765 * to reach the minimum voltage.
1769 mmc_pwrseq_post_power_on(host);
1771 host->ios.clock = host->f_init;
1773 host->ios.power_mode = MMC_POWER_ON;
1777 * This delay must be at least 74 clock sizes, or 1 ms, or the
1778 * time required to reach a stable voltage.
1783 void mmc_power_off(struct mmc_host *host)
1785 if (host->ios.power_mode == MMC_POWER_OFF)
1788 mmc_pwrseq_power_off(host);
1790 host->ios.clock = 0;
1793 host->ios.power_mode = MMC_POWER_OFF;
1794 /* Set initial state and call mmc_set_ios */
1795 mmc_set_initial_state(host);
1798 * Some configurations, such as the 802.11 SDIO card in the OLPC
1799 * XO-1.5, require a short delay after poweroff before the card
1800 * can be successfully turned on again.
1805 void mmc_power_cycle(struct mmc_host *host, u32 ocr)
1807 mmc_power_off(host);
1808 /* Wait at least 1 ms according to SD spec */
1810 mmc_power_up(host, ocr);
1814 * Cleanup when the last reference to the bus operator is dropped.
1816 static void __mmc_release_bus(struct mmc_host *host)
1819 BUG_ON(host->bus_refs);
1820 BUG_ON(!host->bus_dead);
1822 host->bus_ops = NULL;
1826 * Increase reference count of bus operator
1828 static inline void mmc_bus_get(struct mmc_host *host)
1830 unsigned long flags;
1832 spin_lock_irqsave(&host->lock, flags);
1834 spin_unlock_irqrestore(&host->lock, flags);
1838 * Decrease reference count of bus operator and free it if
1839 * it is the last reference.
1841 static inline void mmc_bus_put(struct mmc_host *host)
1843 unsigned long flags;
1845 spin_lock_irqsave(&host->lock, flags);
1847 if ((host->bus_refs == 0) && host->bus_ops)
1848 __mmc_release_bus(host);
1849 spin_unlock_irqrestore(&host->lock, flags);
1853 * Assign a mmc bus handler to a host. Only one bus handler may control a
1854 * host at any given time.
1856 void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1858 unsigned long flags;
1863 WARN_ON(!host->claimed);
1865 spin_lock_irqsave(&host->lock, flags);
1867 BUG_ON(host->bus_ops);
1868 BUG_ON(host->bus_refs);
1870 host->bus_ops = ops;
1874 spin_unlock_irqrestore(&host->lock, flags);
1878 * Remove the current bus handler from a host.
1880 void mmc_detach_bus(struct mmc_host *host)
1882 unsigned long flags;
1886 WARN_ON(!host->claimed);
1887 WARN_ON(!host->bus_ops);
1889 spin_lock_irqsave(&host->lock, flags);
1893 spin_unlock_irqrestore(&host->lock, flags);
1898 static void _mmc_detect_change(struct mmc_host *host, unsigned long delay,
1901 #ifdef CONFIG_MMC_DEBUG
1902 unsigned long flags;
1903 spin_lock_irqsave(&host->lock, flags);
1904 WARN_ON(host->removed);
1905 spin_unlock_irqrestore(&host->lock, flags);
1909 * If the device is configured as wakeup, we prevent a new sleep for
1910 * 5 s to give provision for user space to consume the event.
1912 if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) &&
1913 device_can_wakeup(mmc_dev(host)))
1914 pm_wakeup_event(mmc_dev(host), 5000);
1916 host->detect_change = 1;
1917 mmc_schedule_delayed_work(&host->detect, delay);
1921 * mmc_detect_change - process change of state on a MMC socket
1922 * @host: host which changed state.
1923 * @delay: optional delay to wait before detection (jiffies)
1925 * MMC drivers should call this when they detect a card has been
1926 * inserted or removed. The MMC layer will confirm that any
1927 * present card is still functional, and initialize any newly
1930 void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1932 _mmc_detect_change(host, delay, true);
1934 EXPORT_SYMBOL(mmc_detect_change);
1936 void mmc_init_erase(struct mmc_card *card)
1940 if (is_power_of_2(card->erase_size))
1941 card->erase_shift = ffs(card->erase_size) - 1;
1943 card->erase_shift = 0;
1946 * It is possible to erase an arbitrarily large area of an SD or MMC
1947 * card. That is not desirable because it can take a long time
1948 * (minutes) potentially delaying more important I/O, and also the
1949 * timeout calculations become increasingly hugely over-estimated.
1950 * Consequently, 'pref_erase' is defined as a guide to limit erases
1951 * to that size and alignment.
1953 * For SD cards that define Allocation Unit size, limit erases to one
1954 * Allocation Unit at a time. For MMC cards that define High Capacity
1955 * Erase Size, whether it is switched on or not, limit to that size.
1956 * Otherwise just have a stab at a good value. For modern cards it
1957 * will end up being 4MiB. Note that if the value is too small, it
1958 * can end up taking longer to erase.
1960 if (mmc_card_sd(card) && card->ssr.au) {
1961 card->pref_erase = card->ssr.au;
1962 card->erase_shift = ffs(card->ssr.au) - 1;
1963 } else if (card->ext_csd.hc_erase_size) {
1964 card->pref_erase = card->ext_csd.hc_erase_size;
1965 } else if (card->erase_size) {
1966 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1968 card->pref_erase = 512 * 1024 / 512;
1970 card->pref_erase = 1024 * 1024 / 512;
1972 card->pref_erase = 2 * 1024 * 1024 / 512;
1974 card->pref_erase = 4 * 1024 * 1024 / 512;
1975 if (card->pref_erase < card->erase_size)
1976 card->pref_erase = card->erase_size;
1978 sz = card->pref_erase % card->erase_size;
1980 card->pref_erase += card->erase_size - sz;
1983 card->pref_erase = 0;
1986 static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1987 unsigned int arg, unsigned int qty)
1989 unsigned int erase_timeout;
1991 if (arg == MMC_DISCARD_ARG ||
1992 (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) {
1993 erase_timeout = card->ext_csd.trim_timeout;
1994 } else if (card->ext_csd.erase_group_def & 1) {
1995 /* High Capacity Erase Group Size uses HC timeouts */
1996 if (arg == MMC_TRIM_ARG)
1997 erase_timeout = card->ext_csd.trim_timeout;
1999 erase_timeout = card->ext_csd.hc_erase_timeout;
2001 /* CSD Erase Group Size uses write timeout */
2002 unsigned int mult = (10 << card->csd.r2w_factor);
2003 unsigned int timeout_clks = card->csd.tacc_clks * mult;
2004 unsigned int timeout_us;
2006 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
2007 if (card->csd.tacc_ns < 1000000)
2008 timeout_us = (card->csd.tacc_ns * mult) / 1000;
2010 timeout_us = (card->csd.tacc_ns / 1000) * mult;
2013 * ios.clock is only a target. The real clock rate might be
2014 * less but not that much less, so fudge it by multiplying by 2.
2017 timeout_us += (timeout_clks * 1000) /
2018 (card->host->ios.clock / 1000);
2020 erase_timeout = timeout_us / 1000;
2023 * Theoretically, the calculation could underflow so round up
2024 * to 1ms in that case.
2030 /* Multiplier for secure operations */
2031 if (arg & MMC_SECURE_ARGS) {
2032 if (arg == MMC_SECURE_ERASE_ARG)
2033 erase_timeout *= card->ext_csd.sec_erase_mult;
2035 erase_timeout *= card->ext_csd.sec_trim_mult;
2038 erase_timeout *= qty;
2041 * Ensure at least a 1 second timeout for SPI as per
2042 * 'mmc_set_data_timeout()'
2044 if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
2045 erase_timeout = 1000;
2047 return erase_timeout;
2050 static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
2054 unsigned int erase_timeout;
2056 if (card->ssr.erase_timeout) {
2057 /* Erase timeout specified in SD Status Register (SSR) */
2058 erase_timeout = card->ssr.erase_timeout * qty +
2059 card->ssr.erase_offset;
2062 * Erase timeout not specified in SD Status Register (SSR) so
2063 * use 250ms per write block.
2065 erase_timeout = 250 * qty;
2068 /* Must not be less than 1 second */
2069 if (erase_timeout < 1000)
2070 erase_timeout = 1000;
2072 return erase_timeout;
2075 static unsigned int mmc_erase_timeout(struct mmc_card *card,
2079 if (mmc_card_sd(card))
2080 return mmc_sd_erase_timeout(card, arg, qty);
2082 return mmc_mmc_erase_timeout(card, arg, qty);
2085 static int mmc_do_erase(struct mmc_card *card, unsigned int from,
2086 unsigned int to, unsigned int arg)
2088 struct mmc_command cmd = {0};
2089 unsigned int qty = 0;
2090 unsigned long timeout;
2091 unsigned int fr, nr;
2096 trace_mmc_blk_erase_start(arg, fr, nr);
2098 mmc_retune_hold(card->host);
2101 * qty is used to calculate the erase timeout which depends on how many
2102 * erase groups (or allocation units in SD terminology) are affected.
2103 * We count erasing part of an erase group as one erase group.
2104 * For SD, the allocation units are always a power of 2. For MMC, the
2105 * erase group size is almost certainly also power of 2, but it does not
2106 * seem to insist on that in the JEDEC standard, so we fall back to
2107 * division in that case. SD may not specify an allocation unit size,
2108 * in which case the timeout is based on the number of write blocks.
2110 * Note that the timeout for secure trim 2 will only be correct if the
2111 * number of erase groups specified is the same as the total of all
2112 * preceding secure trim 1 commands. Since the power may have been
2113 * lost since the secure trim 1 commands occurred, it is generally
2114 * impossible to calculate the secure trim 2 timeout correctly.
2116 if (card->erase_shift)
2117 qty += ((to >> card->erase_shift) -
2118 (from >> card->erase_shift)) + 1;
2119 else if (mmc_card_sd(card))
2120 qty += to - from + 1;
2122 qty += ((to / card->erase_size) -
2123 (from / card->erase_size)) + 1;
2125 if (!mmc_card_blockaddr(card)) {
2130 if (mmc_card_sd(card))
2131 cmd.opcode = SD_ERASE_WR_BLK_START;
2133 cmd.opcode = MMC_ERASE_GROUP_START;
2135 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2136 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2138 pr_err("mmc_erase: group start error %d, "
2139 "status %#x\n", err, cmd.resp[0]);
2144 memset(&cmd, 0, sizeof(struct mmc_command));
2145 if (mmc_card_sd(card))
2146 cmd.opcode = SD_ERASE_WR_BLK_END;
2148 cmd.opcode = MMC_ERASE_GROUP_END;
2150 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2151 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2153 pr_err("mmc_erase: group end error %d, status %#x\n",
2159 memset(&cmd, 0, sizeof(struct mmc_command));
2160 cmd.opcode = MMC_ERASE;
2162 cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
2163 cmd.busy_timeout = mmc_erase_timeout(card, arg, qty);
2164 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2166 pr_err("mmc_erase: erase error %d, status %#x\n",
2172 if (mmc_host_is_spi(card->host))
2175 timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS);
2177 memset(&cmd, 0, sizeof(struct mmc_command));
2178 cmd.opcode = MMC_SEND_STATUS;
2179 cmd.arg = card->rca << 16;
2180 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
2181 /* Do not retry else we can't see errors */
2182 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2183 if (err || (cmd.resp[0] & 0xFDF92000)) {
2184 pr_err("error %d requesting status %#x\n",
2190 /* Timeout if the device never becomes ready for data and
2191 * never leaves the program state.
2193 if (time_after(jiffies, timeout)) {
2194 pr_err("%s: Card stuck in programming state! %s\n",
2195 mmc_hostname(card->host), __func__);
2200 } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
2201 (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG));
2203 mmc_retune_release(card->host);
2204 trace_mmc_blk_erase_end(arg, fr, nr);
2209 * mmc_erase - erase sectors.
2210 * @card: card to erase
2211 * @from: first sector to erase
2212 * @nr: number of sectors to erase
2213 * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
2215 * Caller must claim host before calling this function.
2217 int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
2220 unsigned int rem, to = from + nr;
2223 if (!(card->host->caps & MMC_CAP_ERASE) ||
2224 !(card->csd.cmdclass & CCC_ERASE))
2227 if (!card->erase_size)
2230 if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
2233 if ((arg & MMC_SECURE_ARGS) &&
2234 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
2237 if ((arg & MMC_TRIM_ARGS) &&
2238 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
2241 if (arg == MMC_SECURE_ERASE_ARG) {
2242 if (from % card->erase_size || nr % card->erase_size)
2246 if (arg == MMC_ERASE_ARG) {
2247 rem = from % card->erase_size;
2249 rem = card->erase_size - rem;
2256 rem = nr % card->erase_size;
2269 /* 'from' and 'to' are inclusive */
2273 * Special case where only one erase-group fits in the timeout budget:
2274 * If the region crosses an erase-group boundary on this particular
2275 * case, we will be trimming more than one erase-group which, does not
2276 * fit in the timeout budget of the controller, so we need to split it
2277 * and call mmc_do_erase() twice if necessary. This special case is
2278 * identified by the card->eg_boundary flag.
2280 rem = card->erase_size - (from % card->erase_size);
2281 if ((arg & MMC_TRIM_ARGS) && (card->eg_boundary) && (nr > rem)) {
2282 err = mmc_do_erase(card, from, from + rem - 1, arg);
2284 if ((err) || (to <= from))
2288 return mmc_do_erase(card, from, to, arg);
2290 EXPORT_SYMBOL(mmc_erase);
2292 int mmc_can_erase(struct mmc_card *card)
2294 if ((card->host->caps & MMC_CAP_ERASE) &&
2295 (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
2299 EXPORT_SYMBOL(mmc_can_erase);
2301 int mmc_can_trim(struct mmc_card *card)
2303 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN) &&
2304 (!(card->quirks & MMC_QUIRK_TRIM_BROKEN)))
2308 EXPORT_SYMBOL(mmc_can_trim);
2310 int mmc_can_discard(struct mmc_card *card)
2313 * As there's no way to detect the discard support bit at v4.5
2314 * use the s/w feature support filed.
2316 if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
2320 EXPORT_SYMBOL(mmc_can_discard);
2322 int mmc_can_sanitize(struct mmc_card *card)
2324 if (!mmc_can_trim(card) && !mmc_can_erase(card))
2326 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
2330 EXPORT_SYMBOL(mmc_can_sanitize);
2332 int mmc_can_secure_erase_trim(struct mmc_card *card)
2334 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) &&
2335 !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
2339 EXPORT_SYMBOL(mmc_can_secure_erase_trim);
2341 int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
2344 if (!card->erase_size)
2346 if (from % card->erase_size || nr % card->erase_size)
2350 EXPORT_SYMBOL(mmc_erase_group_aligned);
2352 static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
2355 struct mmc_host *host = card->host;
2356 unsigned int max_discard, x, y, qty = 0, max_qty, timeout;
2357 unsigned int last_timeout = 0;
2359 if (card->erase_shift)
2360 max_qty = UINT_MAX >> card->erase_shift;
2361 else if (mmc_card_sd(card))
2364 max_qty = UINT_MAX / card->erase_size;
2366 /* Find the largest qty with an OK timeout */
2369 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
2370 timeout = mmc_erase_timeout(card, arg, qty + x);
2371 if (timeout > host->max_busy_timeout)
2373 if (timeout < last_timeout)
2375 last_timeout = timeout;
2385 * When specifying a sector range to trim, chances are we might cross
2386 * an erase-group boundary even if the amount of sectors is less than
2388 * If we can only fit one erase-group in the controller timeout budget,
2389 * we have to care that erase-group boundaries are not crossed by a
2390 * single trim operation. We flag that special case with "eg_boundary".
2391 * In all other cases we can just decrement qty and pretend that we
2392 * always touch (qty + 1) erase-groups as a simple optimization.
2395 card->eg_boundary = 1;
2399 /* Convert qty to sectors */
2400 if (card->erase_shift)
2401 max_discard = qty << card->erase_shift;
2402 else if (mmc_card_sd(card))
2403 max_discard = qty + 1;
2405 max_discard = qty * card->erase_size;
2410 unsigned int mmc_calc_max_discard(struct mmc_card *card)
2412 struct mmc_host *host = card->host;
2413 unsigned int max_discard, max_trim;
2415 if (!host->max_busy_timeout)
2419 * Without erase_group_def set, MMC erase timeout depends on clock
2420 * frequence which can change. In that case, the best choice is
2421 * just the preferred erase size.
2423 if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
2424 return card->pref_erase;
2426 max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
2427 if (mmc_can_trim(card)) {
2428 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
2429 if (max_trim < max_discard)
2430 max_discard = max_trim;
2431 } else if (max_discard < card->erase_size) {
2434 pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
2435 mmc_hostname(host), max_discard, host->max_busy_timeout);
2438 EXPORT_SYMBOL(mmc_calc_max_discard);
2440 int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
2442 struct mmc_command cmd = {0};
2444 if (mmc_card_blockaddr(card) || mmc_card_ddr52(card))
2447 cmd.opcode = MMC_SET_BLOCKLEN;
2449 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2450 return mmc_wait_for_cmd(card->host, &cmd, 5);
2452 EXPORT_SYMBOL(mmc_set_blocklen);
2454 int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount,
2457 struct mmc_command cmd = {0};
2459 cmd.opcode = MMC_SET_BLOCK_COUNT;
2460 cmd.arg = blockcount & 0x0000FFFF;
2463 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2464 return mmc_wait_for_cmd(card->host, &cmd, 5);
2466 EXPORT_SYMBOL(mmc_set_blockcount);
2468 static void mmc_hw_reset_for_init(struct mmc_host *host)
2470 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2472 host->ops->hw_reset(host);
2475 int mmc_hw_reset(struct mmc_host *host)
2483 if (!host->bus_ops || host->bus_dead || !host->bus_ops->reset) {
2488 ret = host->bus_ops->reset(host);
2491 if (ret != -EOPNOTSUPP)
2492 pr_warn("%s: tried to reset card\n", mmc_hostname(host));
2496 EXPORT_SYMBOL(mmc_hw_reset);
2498 static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2500 host->f_init = freq;
2502 #ifdef CONFIG_MMC_DEBUG
2503 pr_info("%s: %s: trying to init card at %u Hz\n",
2504 mmc_hostname(host), __func__, host->f_init);
2506 mmc_power_up(host, host->ocr_avail);
2509 * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2510 * do a hardware reset if possible.
2512 mmc_hw_reset_for_init(host);
2515 * sdio_reset sends CMD52 to reset card. Since we do not know
2516 * if the card is being re-initialized, just send it. CMD52
2517 * should be ignored by SD/eMMC cards.
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 mmc_power_off(host);
2536 int _mmc_detect_card_removed(struct mmc_host *host)
2540 if (host->caps & MMC_CAP_NONREMOVABLE)
2543 if (!host->card || mmc_card_removed(host->card))
2546 ret = host->bus_ops->alive(host);
2549 * Card detect status and alive check may be out of sync if card is
2550 * removed slowly, when card detect switch changes while card/slot
2551 * pads are still contacted in hardware (refer to "SD Card Mechanical
2552 * Addendum, Appendix C: Card Detection Switch"). So reschedule a
2553 * detect work 200ms later for this case.
2555 if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) {
2556 mmc_detect_change(host, msecs_to_jiffies(200));
2557 pr_debug("%s: card removed too slowly\n", mmc_hostname(host));
2561 mmc_card_set_removed(host->card);
2562 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2568 int mmc_detect_card_removed(struct mmc_host *host)
2570 struct mmc_card *card = host->card;
2573 WARN_ON(!host->claimed);
2578 ret = mmc_card_removed(card);
2580 * The card will be considered unchanged unless we have been asked to
2581 * detect a change or host requires polling to provide card detection.
2583 if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
2586 host->detect_change = 0;
2588 ret = _mmc_detect_card_removed(host);
2589 if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) {
2591 * Schedule a detect work as soon as possible to let a
2592 * rescan handle the card removal.
2594 cancel_delayed_work(&host->detect);
2595 _mmc_detect_change(host, 0, false);
2601 EXPORT_SYMBOL(mmc_detect_card_removed);
2603 void mmc_rescan(struct work_struct *work)
2605 struct mmc_host *host =
2606 container_of(work, struct mmc_host, detect.work);
2609 if (host->trigger_card_event && host->ops->card_event) {
2610 host->ops->card_event(host);
2611 host->trigger_card_event = false;
2614 if (host->rescan_disable)
2617 /* If there is a non-removable card registered, only scan once */
2618 if ((host->caps & MMC_CAP_NONREMOVABLE) && host->rescan_entered)
2620 host->rescan_entered = 1;
2625 * if there is a _removable_ card registered, check whether it is
2628 if (host->bus_ops && !host->bus_dead
2629 && !(host->caps & MMC_CAP_NONREMOVABLE))
2630 host->bus_ops->detect(host);
2632 host->detect_change = 0;
2635 * Let mmc_bus_put() free the bus/bus_ops if we've found that
2636 * the card is no longer present.
2641 /* if there still is a card present, stop here */
2642 if (host->bus_ops != NULL) {
2648 * Only we can add a new handler, so it's safe to
2649 * release the lock here.
2653 if (!(host->caps & MMC_CAP_NONREMOVABLE) && host->ops->get_cd &&
2654 host->ops->get_cd(host) == 0) {
2655 mmc_claim_host(host);
2656 mmc_power_off(host);
2657 mmc_release_host(host);
2661 mmc_claim_host(host);
2662 for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2663 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2665 if (freqs[i] <= host->f_min)
2668 mmc_release_host(host);
2671 if (host->caps & MMC_CAP_NEEDS_POLL)
2672 mmc_schedule_delayed_work(&host->detect, HZ);
2675 void mmc_start_host(struct mmc_host *host)
2677 host->f_init = max(freqs[0], host->f_min);
2678 host->rescan_disable = 0;
2679 host->ios.power_mode = MMC_POWER_UNDEFINED;
2681 mmc_claim_host(host);
2682 if (host->caps2 & MMC_CAP2_NO_PRESCAN_POWERUP)
2683 mmc_power_off(host);
2685 mmc_power_up(host, host->ocr_avail);
2686 mmc_release_host(host);
2688 mmc_gpiod_request_cd_irq(host);
2689 _mmc_detect_change(host, 0, false);
2692 void mmc_stop_host(struct mmc_host *host)
2694 #ifdef CONFIG_MMC_DEBUG
2695 unsigned long flags;
2696 spin_lock_irqsave(&host->lock, flags);
2698 spin_unlock_irqrestore(&host->lock, flags);
2700 if (host->slot.cd_irq >= 0)
2701 disable_irq(host->slot.cd_irq);
2703 host->rescan_disable = 1;
2704 cancel_delayed_work_sync(&host->detect);
2705 mmc_flush_scheduled_work();
2707 /* clear pm flags now and let card drivers set them as needed */
2711 if (host->bus_ops && !host->bus_dead) {
2712 /* Calling bus_ops->remove() with a claimed host can deadlock */
2713 host->bus_ops->remove(host);
2714 mmc_claim_host(host);
2715 mmc_detach_bus(host);
2716 mmc_power_off(host);
2717 mmc_release_host(host);
2725 mmc_claim_host(host);
2726 mmc_power_off(host);
2727 mmc_release_host(host);
2730 int mmc_power_save_host(struct mmc_host *host)
2734 #ifdef CONFIG_MMC_DEBUG
2735 pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__);
2740 if (!host->bus_ops || host->bus_dead) {
2745 if (host->bus_ops->power_save)
2746 ret = host->bus_ops->power_save(host);
2750 mmc_power_off(host);
2754 EXPORT_SYMBOL(mmc_power_save_host);
2756 int mmc_power_restore_host(struct mmc_host *host)
2760 #ifdef CONFIG_MMC_DEBUG
2761 pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__);
2766 if (!host->bus_ops || host->bus_dead) {
2771 mmc_power_up(host, host->card->ocr);
2772 ret = host->bus_ops->power_restore(host);
2778 EXPORT_SYMBOL(mmc_power_restore_host);
2781 * Flush the cache to the non-volatile storage.
2783 int mmc_flush_cache(struct mmc_card *card)
2787 if (mmc_card_mmc(card) &&
2788 (card->ext_csd.cache_size > 0) &&
2789 (card->ext_csd.cache_ctrl & 1)) {
2790 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2791 EXT_CSD_FLUSH_CACHE, 1, 0);
2793 pr_err("%s: cache flush error %d\n",
2794 mmc_hostname(card->host), err);
2799 EXPORT_SYMBOL(mmc_flush_cache);
2803 /* Do the card removal on suspend if card is assumed removeable
2804 * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2807 int mmc_pm_notify(struct notifier_block *notify_block,
2808 unsigned long mode, void *unused)
2810 struct mmc_host *host = container_of(
2811 notify_block, struct mmc_host, pm_notify);
2812 unsigned long flags;
2816 case PM_HIBERNATION_PREPARE:
2817 case PM_SUSPEND_PREPARE:
2818 case PM_RESTORE_PREPARE:
2819 spin_lock_irqsave(&host->lock, flags);
2820 host->rescan_disable = 1;
2821 spin_unlock_irqrestore(&host->lock, flags);
2822 cancel_delayed_work_sync(&host->detect);
2827 /* Validate prerequisites for suspend */
2828 if (host->bus_ops->pre_suspend)
2829 err = host->bus_ops->pre_suspend(host);
2833 /* Calling bus_ops->remove() with a claimed host can deadlock */
2834 host->bus_ops->remove(host);
2835 mmc_claim_host(host);
2836 mmc_detach_bus(host);
2837 mmc_power_off(host);
2838 mmc_release_host(host);
2842 case PM_POST_SUSPEND:
2843 case PM_POST_HIBERNATION:
2844 case PM_POST_RESTORE:
2846 spin_lock_irqsave(&host->lock, flags);
2847 host->rescan_disable = 0;
2848 spin_unlock_irqrestore(&host->lock, flags);
2849 _mmc_detect_change(host, 0, false);
2858 * mmc_init_context_info() - init synchronization context
2861 * Init struct context_info needed to implement asynchronous
2862 * request mechanism, used by mmc core, host driver and mmc requests
2865 void mmc_init_context_info(struct mmc_host *host)
2867 spin_lock_init(&host->context_info.lock);
2868 host->context_info.is_new_req = false;
2869 host->context_info.is_done_rcv = false;
2870 host->context_info.is_waiting_last_req = false;
2871 init_waitqueue_head(&host->context_info.wait);
2874 #ifdef CONFIG_MMC_EMBEDDED_SDIO
2875 void mmc_set_embedded_sdio_data(struct mmc_host *host,
2876 struct sdio_cis *cis,
2877 struct sdio_cccr *cccr,
2878 struct sdio_embedded_func *funcs,
2881 host->embedded_sdio_data.cis = cis;
2882 host->embedded_sdio_data.cccr = cccr;
2883 host->embedded_sdio_data.funcs = funcs;
2884 host->embedded_sdio_data.num_funcs = num_funcs;
2887 EXPORT_SYMBOL(mmc_set_embedded_sdio_data);
2890 static int __init mmc_init(void)
2894 workqueue = alloc_ordered_workqueue("kmmcd", 0);
2898 ret = mmc_register_bus();
2900 goto destroy_workqueue;
2902 ret = mmc_register_host_class();
2904 goto unregister_bus;
2906 ret = sdio_register_bus();
2908 goto unregister_host_class;
2912 unregister_host_class:
2913 mmc_unregister_host_class();
2915 mmc_unregister_bus();
2917 destroy_workqueue(workqueue);
2922 static void __exit mmc_exit(void)
2924 sdio_unregister_bus();
2925 mmc_unregister_host_class();
2926 mmc_unregister_bus();
2927 destroy_workqueue(workqueue);
2932 latency_hist_show(struct device *dev, struct device_attribute *attr, char *buf)
2934 struct mmc_host *host = cls_dev_to_mmc_host(dev);
2936 return blk_latency_hist_show(&host->io_lat_s, buf);
2940 * Values permitted 0, 1, 2.
2941 * 0 -> Disable IO latency histograms (default)
2942 * 1 -> Enable IO latency histograms
2943 * 2 -> Zero out IO latency histograms
2946 latency_hist_store(struct device *dev, struct device_attribute *attr,
2947 const char *buf, size_t count)
2949 struct mmc_host *host = cls_dev_to_mmc_host(dev);
2952 if (kstrtol(buf, 0, &value))
2954 if (value == BLK_IO_LAT_HIST_ZERO)
2955 blk_zero_latency_hist(&host->io_lat_s);
2956 else if (value == BLK_IO_LAT_HIST_ENABLE ||
2957 value == BLK_IO_LAT_HIST_DISABLE)
2958 host->latency_hist_enabled = value;
2962 static DEVICE_ATTR(latency_hist, S_IRUGO | S_IWUSR,
2963 latency_hist_show, latency_hist_store);
2966 mmc_latency_hist_sysfs_init(struct mmc_host *host)
2968 if (device_create_file(&host->class_dev, &dev_attr_latency_hist))
2969 dev_err(&host->class_dev,
2970 "Failed to create latency_hist sysfs entry\n");
2974 mmc_latency_hist_sysfs_exit(struct mmc_host *host)
2976 device_remove_file(&host->class_dev, &dev_attr_latency_hist);
2980 subsys_initcall(mmc_init);
2981 module_exit(mmc_exit);
2983 MODULE_LICENSE("GPL");