projects/linux·blob master · refs

2429 lines · 60.7 KiB

1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * linux/drivers/mmc/core/core.c
4 *
5 * Copyright (C) 2003-2004 Russell King, All Rights Reserved.
6 * SD support Copyright (C) 2004 Ian Molton, All Rights Reserved.
7 * Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved.
8 * MMCv4 support Copyright (C) 2006 Philip Langdale, All Rights Reserved.
9 */
10#include <linux/module.h>
11#include <linux/init.h>
12#include <linux/interrupt.h>
13#include <linux/completion.h>
14#include <linux/device.h>
15#include <linux/delay.h>
16#include <linux/pagemap.h>
17#include <linux/err.h>
18#include <linux/leds.h>
19#include <linux/scatterlist.h>
20#include <linux/log2.h>
21#include <linux/pm_runtime.h>
22#include <linux/suspend.h>
23#include <linux/fault-inject.h>
24#include <linux/random.h>
25#include <linux/slab.h>
26#include <linux/of.h>
27
28#include <linux/mmc/card.h>
29#include <linux/mmc/host.h>
30#include <linux/mmc/mmc.h>
31#include <linux/mmc/sd.h>
32#include <linux/mmc/slot-gpio.h>
33
34#define CREATE_TRACE_POINTS
35#include <trace/events/mmc.h>
36
37#include "core.h"
38#include "card.h"
39#include "crypto.h"
40#include "bus.h"
41#include "host.h"
42#include "sdio_bus.h"
43#include "pwrseq.h"
44
45#include "mmc_ops.h"
46#include "sd_ops.h"
47#include "sdio_ops.h"
48
49/* The max erase timeout, used when host->max_busy_timeout isn't specified */
50#define MMC_ERASE_TIMEOUT_MS (60 * 1000) /* 60 s */
51#define SD_DISCARD_TIMEOUT_MS (250)
52
53static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
54
55/*
56 * Enabling software CRCs on the data blocks can be a significant (30%)
57 * performance cost, and for other reasons may not always be desired.
58 * So we allow it to be disabled.
59 */
60bool use_spi_crc = 1;
61module_param(use_spi_crc, bool, 0);
62
63static int mmc_schedule_delayed_work(struct delayed_work *work,
64 unsigned long delay)
65{
66 /*
67 * We use the system_freezable_wq, because of two reasons.
68 * First, it allows several works (not the same work item) to be
69 * executed simultaneously. Second, the queue becomes frozen when
70 * userspace becomes frozen during system PM.
71 */
72 return queue_delayed_work(system_freezable_wq, work, delay);
73}
74
75#ifdef CONFIG_FAIL_MMC_REQUEST
76
77/*
78 * Internal function. Inject random data errors.
79 * If mmc_data is NULL no errors are injected.
80 */
81static void mmc_should_fail_request(struct mmc_host *host,
82 struct mmc_request *mrq)
83{
84 struct mmc_command *cmd = mrq->cmd;
85 struct mmc_data *data = mrq->data;
86 static const int data_errors[] = {
87 -ETIMEDOUT,
88 -EILSEQ,
89 -EIO,
90 };
91
92 if (!data)
93 return;
94
95 if ((cmd && cmd->error) || data->error ||
96 !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
97 return;
98
99 data->error = data_errors[get_random_u32_below(ARRAY_SIZE(data_errors))];
100 data->bytes_xfered = get_random_u32_below(data->bytes_xfered >> SECTOR_SHIFT)
101 << SECTOR_SHIFT;
102}
103
104#else /* CONFIG_FAIL_MMC_REQUEST */
105
106static inline void mmc_should_fail_request(struct mmc_host *host,
107 struct mmc_request *mrq)
108{
109}
110
111#endif /* CONFIG_FAIL_MMC_REQUEST */
112
113static inline void mmc_complete_cmd(struct mmc_request *mrq)
114{
115 if (mrq->cap_cmd_during_tfr && !completion_done(&mrq->cmd_completion))
116 complete_all(&mrq->cmd_completion);
117}
118
119void mmc_command_done(struct mmc_host *host, struct mmc_request *mrq)
120{
121 if (!mrq->cap_cmd_during_tfr)
122 return;
123
124 mmc_complete_cmd(mrq);
125
126 pr_debug("%s: cmd done, tfr ongoing (CMD%u)\n",
127 mmc_hostname(host), mrq->cmd->opcode);
128}
129EXPORT_SYMBOL(mmc_command_done);
130
131/**
132 * mmc_request_done - finish processing an MMC request
133 * @host: MMC host which completed request
134 * @mrq: MMC request which request
135 *
136 * MMC drivers should call this function when they have completed
137 * their processing of a request.
138 */
139void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
140{
141 struct mmc_command *cmd = mrq->cmd;
142 int err = cmd->error;
143
144 /* Flag re-tuning needed on CRC errors */
145 if (!mmc_op_tuning(cmd->opcode) &&
146 !host->retune_crc_disable &&
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);
151
152 if (err && cmd->retries && mmc_host_is_spi(host)) {
153 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
154 cmd->retries = 0;
155 }
156
157 if (host->ongoing_mrq == mrq)
158 host->ongoing_mrq = NULL;
159
160 mmc_complete_cmd(mrq);
161
162 trace_mmc_request_done(host, mrq);
163
164 /*
165 * We list various conditions for the command to be considered
166 * properly done:
167 *
168 * - There was no error, OK fine then
169 * - We are not doing some kind of retry
170 * - The card was removed (...so just complete everything no matter
171 * if there are errors or retries)
172 */
173 if (!err || !cmd->retries || mmc_card_removed(host->card)) {
174 mmc_should_fail_request(host, mrq);
175
176 if (!host->ongoing_mrq)
177 led_trigger_event(host->led, LED_OFF);
178
179 if (mrq->sbc) {
180 pr_debug("%s: req done <CMD%u>: %d: %08x %08x %08x %08x\n",
181 mmc_hostname(host), mrq->sbc->opcode,
182 mrq->sbc->error,
183 mrq->sbc->resp[0], mrq->sbc->resp[1],
184 mrq->sbc->resp[2], mrq->sbc->resp[3]);
185 }
186
187 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
188 mmc_hostname(host), cmd->opcode, err,
189 cmd->resp[0], cmd->resp[1],
190 cmd->resp[2], cmd->resp[3]);
191
192 if (mrq->data) {
193 pr_debug("%s: %d bytes transferred: %d\n",
194 mmc_hostname(host),
195 mrq->data->bytes_xfered, mrq->data->error);
196 }
197
198 if (mrq->stop) {
199 pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n",
200 mmc_hostname(host), mrq->stop->opcode,
201 mrq->stop->error,
202 mrq->stop->resp[0], mrq->stop->resp[1],
203 mrq->stop->resp[2], mrq->stop->resp[3]);
204 }
205 }
206 /*
207 * Request starter must handle retries - see
208 * mmc_wait_for_req_done().
209 */
210 if (mrq->done)
211 mrq->done(mrq);
212}
213
214EXPORT_SYMBOL(mmc_request_done);
215
216static void __mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
217{
218 int err;
219
220 /* Assumes host controller has been runtime resumed by mmc_claim_host */
221 err = mmc_retune(host);
222 if (err) {
223 mrq->cmd->error = err;
224 mmc_request_done(host, mrq);
225 return;
226 }
227
228 /*
229 * For sdio rw commands we must wait for card busy otherwise some
230 * sdio devices won't work properly.
231 * And bypass I/O abort, reset and bus suspend operations.
232 */
233 if (sdio_is_io_busy(mrq->cmd->opcode, mrq->cmd->arg) &&
234 host->ops->card_busy) {
235 int tries = 500; /* Wait aprox 500ms at maximum */
236
237 while (host->ops->card_busy(host) && --tries)
238 mmc_delay(1);
239
240 if (tries == 0) {
241 mrq->cmd->error = -EBUSY;
242 mmc_request_done(host, mrq);
243 return;
244 }
245 }
246
247 if (mrq->cap_cmd_during_tfr) {
248 host->ongoing_mrq = mrq;
249 /*
250 * Retry path could come through here without having waiting on
251 * cmd_completion, so ensure it is reinitialised.
252 */
253 reinit_completion(&mrq->cmd_completion);
254 }
255
256 trace_mmc_request_start(host, mrq);
257
258 if (host->cqe_on)
259 host->cqe_ops->cqe_off(host);
260
261 host->ops->request(host, mrq);
262}
263
264static void mmc_mrq_pr_debug(struct mmc_host *host, struct mmc_request *mrq,
265 bool cqe)
266{
267 if (mrq->sbc) {
268 pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n",
269 mmc_hostname(host), mrq->sbc->opcode,
270 mrq->sbc->arg, mrq->sbc->flags);
271 }
272
273 if (mrq->cmd) {
274 pr_debug("%s: starting %sCMD%u arg %08x flags %08x\n",
275 mmc_hostname(host), cqe ? "CQE direct " : "",
276 mrq->cmd->opcode, mrq->cmd->arg, mrq->cmd->flags);
277 } else if (cqe) {
278 pr_debug("%s: starting CQE transfer for tag %d blkaddr %u\n",
279 mmc_hostname(host), mrq->tag, mrq->data->blk_addr);
280 }
281
282 if (mrq->data) {
283 pr_debug("%s: blksz %d blocks %d flags %08x "
284 "tsac %d ms nsac %d\n",
285 mmc_hostname(host), mrq->data->blksz,
286 mrq->data->blocks, mrq->data->flags,
287 mrq->data->timeout_ns / 1000000,
288 mrq->data->timeout_clks);
289 }
290
291 if (mrq->stop) {
292 pr_debug("%s: CMD%u arg %08x flags %08x\n",
293 mmc_hostname(host), mrq->stop->opcode,
294 mrq->stop->arg, mrq->stop->flags);
295 }
296}
297
298static int mmc_mrq_prep(struct mmc_host *host, struct mmc_request *mrq)
299{
300 unsigned int i, sz = 0;
301 struct scatterlist *sg;
302
303 if (mrq->cmd) {
304 mrq->cmd->error = 0;
305 mrq->cmd->mrq = mrq;
306 mrq->cmd->data = mrq->data;
307 }
308 if (mrq->sbc) {
309 mrq->sbc->error = 0;
310 mrq->sbc->mrq = mrq;
311 }
312 if (mrq->data) {
313 if (mrq->data->blksz > host->max_blk_size ||
314 mrq->data->blocks > host->max_blk_count ||
315 mrq->data->blocks * mrq->data->blksz > host->max_req_size)
316 return -EINVAL;
317
318 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
319 sz += sg->length;
320 if (sz != mrq->data->blocks * mrq->data->blksz)
321 return -EINVAL;
322
323 mrq->data->error = 0;
324 mrq->data->mrq = mrq;
325 if (mrq->stop) {
326 mrq->data->stop = mrq->stop;
327 mrq->stop->error = 0;
328 mrq->stop->mrq = mrq;
329 }
330 }
331
332 return 0;
333}
334
335int mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
336{
337 int err;
338
339 if (mrq->cmd->has_ext_addr)
340 mmc_send_ext_addr(host, mrq->cmd->ext_addr);
341
342 init_completion(&mrq->cmd_completion);
343
344 mmc_retune_hold(host);
345
346 if (mmc_card_removed(host->card))
347 return -ENOMEDIUM;
348
349 mmc_mrq_pr_debug(host, mrq, false);
350
351 WARN_ON(!host->claimed);
352
353 err = mmc_mrq_prep(host, mrq);
354 if (err)
355 return err;
356
357 if (host->uhs2_sd_tran)
358 mmc_uhs2_prepare_cmd(host, mrq);
359
360 led_trigger_event(host->led, LED_FULL);
361 __mmc_start_request(host, mrq);
362
363 return 0;
364}
365EXPORT_SYMBOL(mmc_start_request);
366
367static void mmc_wait_done(struct mmc_request *mrq)
368{
369 complete(&mrq->completion);
370}
371
372static inline void mmc_wait_ongoing_tfr_cmd(struct mmc_host *host)
373{
374 struct mmc_request *ongoing_mrq = READ_ONCE(host->ongoing_mrq);
375
376 /*
377 * If there is an ongoing transfer, wait for the command line to become
378 * available.
379 */
380 if (ongoing_mrq && !completion_done(&ongoing_mrq->cmd_completion))
381 wait_for_completion(&ongoing_mrq->cmd_completion);
382}
383
384static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
385{
386 int err;
387
388 mmc_wait_ongoing_tfr_cmd(host);
389
390 init_completion(&mrq->completion);
391 mrq->done = mmc_wait_done;
392
393 err = mmc_start_request(host, mrq);
394 if (err) {
395 mrq->cmd->error = err;
396 mmc_complete_cmd(mrq);
397 complete(&mrq->completion);
398 }
399
400 return err;
401}
402
403void mmc_wait_for_req_done(struct mmc_host *host, struct mmc_request *mrq)
404{
405 struct mmc_command *cmd;
406
407 while (1) {
408 wait_for_completion(&mrq->completion);
409
410 cmd = mrq->cmd;
411
412 if (!cmd->error || !cmd->retries ||
413 mmc_card_removed(host->card))
414 break;
415
416 mmc_retune_recheck(host);
417
418 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
419 mmc_hostname(host), cmd->opcode, cmd->error);
420 cmd->retries--;
421 cmd->error = 0;
422 __mmc_start_request(host, mrq);
423 }
424
425 mmc_retune_release(host);
426}
427EXPORT_SYMBOL(mmc_wait_for_req_done);
428
429/*
430 * mmc_cqe_start_req - Start a CQE request.
431 * @host: MMC host to start the request
432 * @mrq: request to start
433 *
434 * Start the request, re-tuning if needed and it is possible. Returns an error
435 * code if the request fails to start or -EBUSY if CQE is busy.
436 */
437int mmc_cqe_start_req(struct mmc_host *host, struct mmc_request *mrq)
438{
439 int err;
440
441 /*
442 * CQE cannot process re-tuning commands. Caller must hold retuning
443 * while CQE is in use. Re-tuning can happen here only when CQE has no
444 * active requests i.e. this is the first. Note, re-tuning will call
445 * ->cqe_off().
446 */
447 err = mmc_retune(host);
448 if (err)
449 goto out_err;
450
451 mrq->host = host;
452
453 mmc_mrq_pr_debug(host, mrq, true);
454
455 err = mmc_mrq_prep(host, mrq);
456 if (err)
457 goto out_err;
458
459 if (host->uhs2_sd_tran)
460 mmc_uhs2_prepare_cmd(host, mrq);
461
462 err = host->cqe_ops->cqe_request(host, mrq);
463 if (err)
464 goto out_err;
465
466 trace_mmc_request_start(host, mrq);
467
468 return 0;
469
470out_err:
471 if (mrq->cmd) {
472 pr_debug("%s: failed to start CQE direct CMD%u, error %d\n",
473 mmc_hostname(host), mrq->cmd->opcode, err);
474 } else {
475 pr_debug("%s: failed to start CQE transfer for tag %d, error %d\n",
476 mmc_hostname(host), mrq->tag, err);
477 }
478 return err;
479}
480EXPORT_SYMBOL(mmc_cqe_start_req);
481
482/**
483 * mmc_cqe_request_done - CQE has finished processing an MMC request
484 * @host: MMC host which completed request
485 * @mrq: MMC request which completed
486 *
487 * CQE drivers should call this function when they have completed
488 * their processing of a request.
489 */
490void mmc_cqe_request_done(struct mmc_host *host, struct mmc_request *mrq)
491{
492 mmc_should_fail_request(host, mrq);
493
494 /* Flag re-tuning needed on CRC errors */
495 if ((mrq->cmd && mrq->cmd->error == -EILSEQ) ||
496 (mrq->data && mrq->data->error == -EILSEQ))
497 mmc_retune_needed(host);
498
499 trace_mmc_request_done(host, mrq);
500
501 if (mrq->cmd) {
502 pr_debug("%s: CQE req done (direct CMD%u): %d\n",
503 mmc_hostname(host), mrq->cmd->opcode, mrq->cmd->error);
504 } else {
505 pr_debug("%s: CQE transfer done tag %d\n",
506 mmc_hostname(host), mrq->tag);
507 }
508
509 if (mrq->data) {
510 pr_debug("%s: %d bytes transferred: %d\n",
511 mmc_hostname(host),
512 mrq->data->bytes_xfered, mrq->data->error);
513 }
514
515 mrq->done(mrq);
516}
517EXPORT_SYMBOL(mmc_cqe_request_done);
518
519/**
520 * mmc_cqe_post_req - CQE post process of a completed MMC request
521 * @host: MMC host
522 * @mrq: MMC request to be processed
523 */
524void mmc_cqe_post_req(struct mmc_host *host, struct mmc_request *mrq)
525{
526 if (host->cqe_ops->cqe_post_req)
527 host->cqe_ops->cqe_post_req(host, mrq);
528}
529EXPORT_SYMBOL(mmc_cqe_post_req);
530
531/* Arbitrary 1 second timeout */
532#define MMC_CQE_RECOVERY_TIMEOUT 1000
533
534/*
535 * mmc_cqe_recovery - Recover from CQE errors.
536 * @host: MMC host to recover
537 *
538 * Recovery consists of stopping CQE, stopping eMMC, discarding the queue
539 * in eMMC, and discarding the queue in CQE. CQE must call
540 * mmc_cqe_request_done() on all requests. An error is returned if the eMMC
541 * fails to discard its queue.
542 */
543int mmc_cqe_recovery(struct mmc_host *host)
544{
545 struct mmc_command cmd;
546 int err;
547
548 mmc_retune_hold_now(host);
549
550 /*
551 * Recovery is expected seldom, if at all, but it reduces performance,
552 * so make sure it is not completely silent.
553 */
554 pr_warn("%s: running CQE recovery\n", mmc_hostname(host));
555
556 host->cqe_ops->cqe_recovery_start(host);
557
558 memset(&cmd, 0, sizeof(cmd));
559 cmd.opcode = MMC_STOP_TRANSMISSION;
560 cmd.flags = MMC_RSP_R1B_NO_CRC | MMC_CMD_AC; /* Ignore CRC */
561 cmd.busy_timeout = MMC_CQE_RECOVERY_TIMEOUT;
562 mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
563
564 mmc_poll_for_busy(host->card, MMC_CQE_RECOVERY_TIMEOUT, true, MMC_BUSY_IO);
565
566 memset(&cmd, 0, sizeof(cmd));
567 cmd.opcode = MMC_CMDQ_TASK_MGMT;
568 cmd.arg = 1; /* Discard entire queue */
569 cmd.flags = MMC_RSP_R1B_NO_CRC | MMC_CMD_AC; /* Ignore CRC */
570 cmd.busy_timeout = MMC_CQE_RECOVERY_TIMEOUT;
571 err = mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
572
573 host->cqe_ops->cqe_recovery_finish(host);
574
575 if (err)
576 err = mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
577
578 mmc_retune_release(host);
579
580 return err;
581}
582EXPORT_SYMBOL(mmc_cqe_recovery);
583
584/**
585 * mmc_is_req_done - Determine if a 'cap_cmd_during_tfr' request is done
586 * @host: MMC host
587 * @mrq: MMC request
588 *
589 * mmc_is_req_done() is used with requests that have
590 * mrq->cap_cmd_during_tfr = true. mmc_is_req_done() must be called after
591 * starting a request and before waiting for it to complete. That is,
592 * either in between calls to mmc_start_req(), or after mmc_wait_for_req()
593 * and before mmc_wait_for_req_done(). If it is called at other times the
594 * result is not meaningful.
595 */
596bool mmc_is_req_done(struct mmc_host *host, struct mmc_request *mrq)
597{
598 return completion_done(&mrq->completion);
599}
600EXPORT_SYMBOL(mmc_is_req_done);
601
602/**
603 * mmc_wait_for_req - start a request and wait for completion
604 * @host: MMC host to start command
605 * @mrq: MMC request to start
606 *
607 * Start a new MMC custom command request for a host, and wait
608 * for the command to complete. In the case of 'cap_cmd_during_tfr'
609 * requests, the transfer is ongoing and the caller can issue further
610 * commands that do not use the data lines, and then wait by calling
611 * mmc_wait_for_req_done().
612 * Does not attempt to parse the response.
613 */
614void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
615{
616 __mmc_start_req(host, mrq);
617
618 if (!mrq->cap_cmd_during_tfr)
619 mmc_wait_for_req_done(host, mrq);
620}
621EXPORT_SYMBOL(mmc_wait_for_req);
622
623/**
624 * mmc_wait_for_cmd - start a command and wait for completion
625 * @host: MMC host to start command
626 * @cmd: MMC command to start
627 * @retries: maximum number of retries
628 *
629 * Start a new MMC command for a host, and wait for the command
630 * to complete. Return any error that occurred while the command
631 * was executing. Do not attempt to parse the response.
632 */
633int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
634{
635 struct mmc_request mrq = {};
636
637 WARN_ON(!host->claimed);
638
639 memset(cmd->resp, 0, sizeof(cmd->resp));
640 cmd->retries = retries;
641
642 mrq.cmd = cmd;
643 cmd->data = NULL;
644
645 mmc_wait_for_req(host, &mrq);
646
647 return cmd->error;
648}
649
650EXPORT_SYMBOL(mmc_wait_for_cmd);
651
652/**
653 * mmc_set_data_timeout - set the timeout for a data command
654 * @data: data phase for command
655 * @card: the MMC card associated with the data transfer
656 *
657 * Computes the data timeout parameters according to the
658 * correct algorithm given the card type.
659 */
660void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
661{
662 unsigned int mult;
663
664 /*
665 * SDIO cards only define an upper 1 s limit on access.
666 */
667 if (mmc_card_sdio(card)) {
668 data->timeout_ns = 1000000000;
669 data->timeout_clks = 0;
670 return;
671 }
672
673 /*
674 * SD cards use a 100 multiplier rather than 10
675 */
676 mult = mmc_card_sd(card) ? 100 : 10;
677
678 /*
679 * Scale up the multiplier (and therefore the timeout) by
680 * the r2w factor for writes.
681 */
682 if (data->flags & MMC_DATA_WRITE)
683 mult <<= card->csd.r2w_factor;
684
685 data->timeout_ns = card->csd.taac_ns * mult;
686 data->timeout_clks = card->csd.taac_clks * mult;
687
688 /*
689 * SD cards also have an upper limit on the timeout.
690 */
691 if (mmc_card_sd(card)) {
692 unsigned int timeout_us, limit_us;
693
694 timeout_us = data->timeout_ns / 1000;
695 if (card->host->ios.clock)
696 timeout_us += data->timeout_clks * 1000 /
697 (card->host->ios.clock / 1000);
698
699 if (data->flags & MMC_DATA_WRITE)
700 /*
701 * The MMC spec "It is strongly recommended
702 * for hosts to implement more than 500ms
703 * timeout value even if the card indicates
704 * the 250ms maximum busy length." Even the
705 * previous value of 300ms is known to be
706 * insufficient for some cards.
707 */
708 limit_us = 3000000;
709 else
710 limit_us = 100000;
711
712 /*
713 * SDHC cards always use these fixed values.
714 */
715 if (timeout_us > limit_us) {
716 data->timeout_ns = limit_us * 1000;
717 data->timeout_clks = 0;
718 }
719
720 /* assign limit value if invalid */
721 if (timeout_us == 0)
722 data->timeout_ns = limit_us * 1000;
723 }
724
725 /*
726 * Some cards require longer data read timeout than indicated in CSD.
727 * Address this by setting the read timeout to a "reasonably high"
728 * value. For the cards tested, 600ms has proven enough. If necessary,
729 * this value can be increased if other problematic cards require this.
730 */
731 if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
732 data->timeout_ns = 600000000;
733 data->timeout_clks = 0;
734 }
735
736 /*
737 * Some cards need very high timeouts if driven in SPI mode.
738 * The worst observed timeout was 900ms after writing a
739 * continuous stream of data until the internal logic
740 * overflowed.
741 */
742 if (mmc_host_is_spi(card->host)) {
743 if (data->flags & MMC_DATA_WRITE) {
744 if (data->timeout_ns < 1000000000)
745 data->timeout_ns = 1000000000; /* 1s */
746 } else {
747 if (data->timeout_ns < 100000000)
748 data->timeout_ns = 100000000; /* 100ms */
749 }
750 }
751}
752EXPORT_SYMBOL(mmc_set_data_timeout);
753
754/*
755 * Allow claiming an already claimed host if the context is the same or there is
756 * no context but the task is the same.
757 */
758static inline bool mmc_ctx_matches(struct mmc_host *host, struct mmc_ctx *ctx,
759 struct task_struct *task)
760{
761 return host->claimer == ctx ||
762 (!ctx && task && host->claimer->task == task);
763}
764
765static inline void mmc_ctx_set_claimer(struct mmc_host *host,
766 struct mmc_ctx *ctx,
767 struct task_struct *task)
768{
769 if (!host->claimer) {
770 if (ctx)
771 host->claimer = ctx;
772 else
773 host->claimer = &host->default_ctx;
774 }
775 if (task)
776 host->claimer->task = task;
777}
778
779/**
780 * __mmc_claim_host - exclusively claim a host
781 * @host: mmc host to claim
782 * @ctx: context that claims the host or NULL in which case the default
783 * context will be used
784 * @abort: whether or not the operation should be aborted
785 *
786 * Claim a host for a set of operations. If @abort is non null and
787 * dereference a non-zero value then this will return prematurely with
788 * that non-zero value without acquiring the lock. Returns zero
789 * with the lock held otherwise.
790 */
791int __mmc_claim_host(struct mmc_host *host, struct mmc_ctx *ctx,
792 atomic_t *abort)
793{
794 struct task_struct *task = ctx ? NULL : current;
795 DECLARE_WAITQUEUE(wait, current);
796 unsigned long flags;
797 int stop;
798 bool pm = false;
799
800 might_sleep();
801
802 add_wait_queue(&host->wq, &wait);
803 spin_lock_irqsave(&host->lock, flags);
804 while (1) {
805 set_current_state(TASK_UNINTERRUPTIBLE);
806 stop = abort ? atomic_read(abort) : 0;
807 if (stop || !host->claimed || mmc_ctx_matches(host, ctx, task))
808 break;
809 spin_unlock_irqrestore(&host->lock, flags);
810 schedule();
811 spin_lock_irqsave(&host->lock, flags);
812 }
813 set_current_state(TASK_RUNNING);
814 if (!stop) {
815 host->claimed = 1;
816 mmc_ctx_set_claimer(host, ctx, task);
817 host->claim_cnt += 1;
818 if (host->claim_cnt == 1)
819 pm = true;
820 } else
821 wake_up(&host->wq);
822 spin_unlock_irqrestore(&host->lock, flags);
823 remove_wait_queue(&host->wq, &wait);
824
825 if (pm)
826 pm_runtime_get_sync(mmc_dev(host));
827
828 return stop;
829}
830EXPORT_SYMBOL(__mmc_claim_host);
831
832/**
833 * mmc_release_host - release a host
834 * @host: mmc host to release
835 *
836 * Release a MMC host, allowing others to claim the host
837 * for their operations.
838 */
839void mmc_release_host(struct mmc_host *host)
840{
841 unsigned long flags;
842
843 WARN_ON(!host->claimed);
844
845 spin_lock_irqsave(&host->lock, flags);
846 if (--host->claim_cnt) {
847 /* Release for nested claim */
848 spin_unlock_irqrestore(&host->lock, flags);
849 } else {
850 host->claimed = 0;
851 host->claimer->task = NULL;
852 host->claimer = NULL;
853 spin_unlock_irqrestore(&host->lock, flags);
854 wake_up(&host->wq);
855 pm_runtime_mark_last_busy(mmc_dev(host));
856 if (host->caps & MMC_CAP_SYNC_RUNTIME_PM)
857 pm_runtime_put_sync_suspend(mmc_dev(host));
858 else
859 pm_runtime_put_autosuspend(mmc_dev(host));
860 }
861}
862EXPORT_SYMBOL(mmc_release_host);
863
864/*
865 * This is a helper function, which fetches a runtime pm reference for the
866 * card device and also claims the host.
867 */
868void mmc_get_card(struct mmc_card *card, struct mmc_ctx *ctx)
869{
870 pm_runtime_get_sync(&card->dev);
871 __mmc_claim_host(card->host, ctx, NULL);
872}
873EXPORT_SYMBOL(mmc_get_card);
874
875/*
876 * This is a helper function, which releases the host and drops the runtime
877 * pm reference for the card device.
878 */
879void mmc_put_card(struct mmc_card *card, struct mmc_ctx *ctx)
880{
881 struct mmc_host *host = card->host;
882
883 WARN_ON(ctx && host->claimer != ctx);
884
885 mmc_release_host(host);
886 pm_runtime_put_autosuspend(&card->dev);
887}
888EXPORT_SYMBOL(mmc_put_card);
889
890/*
891 * Internal function that does the actual ios call to the host driver,
892 * optionally printing some debug output.
893 */
894static inline void mmc_set_ios(struct mmc_host *host)
895{
896 struct mmc_ios *ios = &host->ios;
897
898 pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
899 "width %u timing %u\n",
900 mmc_hostname(host), ios->clock, ios->bus_mode,
901 ios->power_mode, ios->chip_select, ios->vdd,
902 1 << ios->bus_width, ios->timing);
903
904 host->ops->set_ios(host, ios);
905}
906
907/*
908 * Control chip select pin on a host.
909 */
910void mmc_set_chip_select(struct mmc_host *host, int mode)
911{
912 host->ios.chip_select = mode;
913 mmc_set_ios(host);
914}
915
916/*
917 * Sets the host clock to the highest possible frequency that
918 * is below "hz".
919 */
920void mmc_set_clock(struct mmc_host *host, unsigned int hz)
921{
922 WARN_ON(hz && hz < host->f_min);
923
924 if (hz > host->f_max)
925 hz = host->f_max;
926
927 host->ios.clock = hz;
928 mmc_set_ios(host);
929}
930
931int mmc_execute_tuning(struct mmc_card *card)
932{
933 struct mmc_host *host = card->host;
934 u32 opcode;
935 int err;
936
937 if (!host->ops->execute_tuning)
938 return 0;
939
940 if (host->cqe_on)
941 host->cqe_ops->cqe_off(host);
942
943 if (mmc_card_mmc(card))
944 opcode = MMC_SEND_TUNING_BLOCK_HS200;
945 else
946 opcode = MMC_SEND_TUNING_BLOCK;
947
948 err = host->ops->execute_tuning(host, opcode);
949 if (!err) {
950 mmc_retune_clear(host);
951 mmc_retune_enable(host);
952 return 0;
953 }
954
955 /* Only print error when we don't check for card removal */
956 if (!host->detect_change) {
957 pr_err("%s: tuning execution failed: %d\n",
958 mmc_hostname(host), err);
959 mmc_debugfs_err_stats_inc(host, MMC_ERR_TUNING);
960 }
961
962 return err;
963}
964
965/*
966 * Change the bus mode (open drain/push-pull) of a host.
967 */
968void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
969{
970 host->ios.bus_mode = mode;
971 mmc_set_ios(host);
972}
973
974/*
975 * Change data bus width of a host.
976 */
977void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
978{
979 host->ios.bus_width = width;
980 mmc_set_ios(host);
981}
982
983/*
984 * Set initial state after a power cycle or a hw_reset.
985 */
986void mmc_set_initial_state(struct mmc_host *host)
987{
988 if (host->cqe_on)
989 host->cqe_ops->cqe_off(host);
990
991 mmc_retune_disable(host);
992
993 if (mmc_host_is_spi(host))
994 host->ios.chip_select = MMC_CS_HIGH;
995 else
996 host->ios.chip_select = MMC_CS_DONTCARE;
997 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
998 host->ios.bus_width = MMC_BUS_WIDTH_1;
999 host->ios.timing = MMC_TIMING_LEGACY;
1000 host->ios.drv_type = 0;
1001 host->ios.enhanced_strobe = false;
1002
1003 /*
1004 * Make sure we are in non-enhanced strobe mode before we
1005 * actually enable it in ext_csd.
1006 */
1007 if ((host->caps2 & MMC_CAP2_HS400_ES) &&
1008 host->ops->hs400_enhanced_strobe)
1009 host->ops->hs400_enhanced_strobe(host, &host->ios);
1010
1011 mmc_set_ios(host);
1012
1013 mmc_crypto_set_initial_state(host);
1014}
1015
1016/**
1017 * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
1018 * @vdd: voltage (mV)
1019 * @low_bits: prefer low bits in boundary cases
1020 *
1021 * This function returns the OCR bit number according to the provided @vdd
1022 * value. If conversion is not possible a negative errno value returned.
1023 *
1024 * Depending on the @low_bits flag the function prefers low or high OCR bits
1025 * on boundary voltages. For example,
1026 * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
1027 * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1028 *
1029 * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1030 */
1031static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1032{
1033 const int max_bit = ilog2(MMC_VDD_35_36);
1034 int bit;
1035
1036 if (vdd < 1650 || vdd > 3600)
1037 return -EINVAL;
1038
1039 if (vdd >= 1650 && vdd <= 1950)
1040 return ilog2(MMC_VDD_165_195);
1041
1042 if (low_bits)
1043 vdd -= 1;
1044
1045 /* Base 2000 mV, step 100 mV, bit's base 8. */
1046 bit = (vdd - 2000) / 100 + 8;
1047 if (bit > max_bit)
1048 return max_bit;
1049 return bit;
1050}
1051
1052/**
1053 * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1054 * @vdd_min: minimum voltage value (mV)
1055 * @vdd_max: maximum voltage value (mV)
1056 *
1057 * This function returns the OCR mask bits according to the provided @vdd_min
1058 * and @vdd_max values. If conversion is not possible the function returns 0.
1059 *
1060 * Notes wrt boundary cases:
1061 * This function sets the OCR bits for all boundary voltages, for example
1062 * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1063 * MMC_VDD_34_35 mask.
1064 */
1065u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1066{
1067 u32 mask = 0;
1068
1069 if (vdd_max < vdd_min)
1070 return 0;
1071
1072 /* Prefer high bits for the boundary vdd_max values. */
1073 vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1074 if (vdd_max < 0)
1075 return 0;
1076
1077 /* Prefer low bits for the boundary vdd_min values. */
1078 vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1079 if (vdd_min < 0)
1080 return 0;
1081
1082 /* Fill the mask, from max bit to min bit. */
1083 while (vdd_max >= vdd_min)
1084 mask |= 1 << vdd_max--;
1085
1086 return mask;
1087}
1088
1089static int mmc_of_get_func_num(struct device_node *node)
1090{
1091 u32 reg;
1092 int ret;
1093
1094 ret = of_property_read_u32(node, "reg", &reg);
1095 if (ret < 0)
1096 return ret;
1097
1098 return reg;
1099}
1100
1101struct device_node *mmc_of_find_child_device(struct mmc_host *host,
1102 unsigned func_num)
1103{
1104 struct device_node *node;
1105
1106 if (!host->parent || !host->parent->of_node)
1107 return NULL;
1108
1109 for_each_child_of_node(host->parent->of_node, node) {
1110 if (mmc_of_get_func_num(node) == func_num)
1111 return node;
1112 }
1113
1114 return NULL;
1115}
1116
1117/*
1118 * Mask off any voltages we don't support and select
1119 * the lowest voltage
1120 */
1121u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1122{
1123 int bit;
1124
1125 /*
1126 * Sanity check the voltages that the card claims to
1127 * support.
1128 */
1129 if (ocr & 0x7F) {
1130 dev_warn(mmc_dev(host),
1131 "card claims to support voltages below defined range\n");
1132 ocr &= ~0x7F;
1133 }
1134
1135 ocr &= host->ocr_avail;
1136 if (!ocr) {
1137 dev_warn(mmc_dev(host), "no support for card's volts\n");
1138 return 0;
1139 }
1140
1141 if (!mmc_card_uhs2(host) && host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) {
1142 bit = ffs(ocr) - 1;
1143 ocr &= 3 << bit;
1144 mmc_power_cycle(host, ocr);
1145 } else {
1146 bit = fls(ocr) - 1;
1147 /*
1148 * The bit variable represents the highest voltage bit set in
1149 * the OCR register.
1150 * To keep a range of 2 values (e.g. 3.2V/3.3V and 3.3V/3.4V),
1151 * we must shift the mask '3' with (bit - 1).
1152 */
1153 ocr &= 3 << (bit - 1);
1154 if (bit != host->ios.vdd)
1155 dev_warn(mmc_dev(host), "exceeding card's volts\n");
1156 }
1157
1158 return ocr;
1159}
1160
1161int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage)
1162{
1163 int err = 0;
1164 int old_signal_voltage = host->ios.signal_voltage;
1165
1166 host->ios.signal_voltage = signal_voltage;
1167 if (host->ops->start_signal_voltage_switch)
1168 err = host->ops->start_signal_voltage_switch(host, &host->ios);
1169
1170 if (err)
1171 host->ios.signal_voltage = old_signal_voltage;
1172
1173 return err;
1174
1175}
1176
1177void mmc_set_initial_signal_voltage(struct mmc_host *host)
1178{
1179 /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */
1180 if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330))
1181 dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n");
1182 else if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180))
1183 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n");
1184 else if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_120))
1185 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n");
1186}
1187
1188int mmc_host_set_uhs_voltage(struct mmc_host *host)
1189{
1190 u32 clock;
1191
1192 /*
1193 * During a signal voltage level switch, the clock must be gated
1194 * for 5 ms according to the SD spec
1195 */
1196 clock = host->ios.clock;
1197 host->ios.clock = 0;
1198 mmc_set_ios(host);
1199
1200 if (mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180))
1201 return -EAGAIN;
1202
1203 /* Keep clock gated for at least 10 ms, though spec only says 5 ms */
1204 mmc_delay(10);
1205 host->ios.clock = clock;
1206 mmc_set_ios(host);
1207
1208 return 0;
1209}
1210
1211int mmc_set_uhs_voltage(struct mmc_host *host, u32 ocr)
1212{
1213 struct mmc_command cmd = {};
1214 int err = 0;
1215
1216 /*
1217 * If we cannot switch voltages, return failure so the caller
1218 * can continue without UHS mode
1219 */
1220 if (!host->ops->start_signal_voltage_switch)
1221 return -EPERM;
1222 if (!host->ops->card_busy)
1223 pr_warn("%s: cannot verify signal voltage switch\n",
1224 mmc_hostname(host));
1225
1226 cmd.opcode = SD_SWITCH_VOLTAGE;
1227 cmd.arg = 0;
1228 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1229
1230 err = mmc_wait_for_cmd(host, &cmd, 0);
1231 if (err)
1232 goto power_cycle;
1233
1234 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1235 return -EIO;
1236
1237 /*
1238 * The card should drive cmd and dat[0:3] low immediately
1239 * after the response of cmd11, but wait 1 ms to be sure
1240 */
1241 mmc_delay(1);
1242 if (host->ops->card_busy && !host->ops->card_busy(host)) {
1243 err = -EAGAIN;
1244 goto power_cycle;
1245 }
1246
1247 if (mmc_host_set_uhs_voltage(host)) {
1248 /*
1249 * Voltages may not have been switched, but we've already
1250 * sent CMD11, so a power cycle is required anyway
1251 */
1252 err = -EAGAIN;
1253 goto power_cycle;
1254 }
1255
1256 /* Wait for at least 1 ms according to spec */
1257 mmc_delay(1);
1258
1259 /*
1260 * Failure to switch is indicated by the card holding
1261 * dat[0:3] low
1262 */
1263 if (host->ops->card_busy && host->ops->card_busy(host))
1264 err = -EAGAIN;
1265
1266power_cycle:
1267 if (err) {
1268 pr_debug("%s: Signal voltage switch failed, "
1269 "power cycling card\n", mmc_hostname(host));
1270 mmc_power_cycle(host, ocr);
1271 }
1272
1273 return err;
1274}
1275
1276/*
1277 * Select timing parameters for host.
1278 */
1279void mmc_set_timing(struct mmc_host *host, unsigned int timing)
1280{
1281 host->ios.timing = timing;
1282 mmc_set_ios(host);
1283}
1284
1285/*
1286 * Select appropriate driver type for host.
1287 */
1288void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1289{
1290 host->ios.drv_type = drv_type;
1291 mmc_set_ios(host);
1292}
1293
1294int mmc_select_drive_strength(struct mmc_card *card, unsigned int max_dtr,
1295 int card_drv_type, int *drv_type)
1296{
1297 struct mmc_host *host = card->host;
1298 int host_drv_type = SD_DRIVER_TYPE_B;
1299
1300 *drv_type = 0;
1301
1302 if (!host->ops->select_drive_strength)
1303 return 0;
1304
1305 /* Use SD definition of driver strength for hosts */
1306 if (host->caps & MMC_CAP_DRIVER_TYPE_A)
1307 host_drv_type |= SD_DRIVER_TYPE_A;
1308
1309 if (host->caps & MMC_CAP_DRIVER_TYPE_C)
1310 host_drv_type |= SD_DRIVER_TYPE_C;
1311
1312 if (host->caps & MMC_CAP_DRIVER_TYPE_D)
1313 host_drv_type |= SD_DRIVER_TYPE_D;
1314
1315 /*
1316 * The drive strength that the hardware can support
1317 * depends on the board design. Pass the appropriate
1318 * information and let the hardware specific code
1319 * return what is possible given the options
1320 */
1321 return host->ops->select_drive_strength(card, max_dtr,
1322 host_drv_type,
1323 card_drv_type,
1324 drv_type);
1325}
1326
1327/*
1328 * Apply power to the MMC stack. This is a two-stage process.
1329 * First, we enable power to the card without the clock running.
1330 * We then wait a bit for the power to stabilise. Finally,
1331 * enable the bus drivers and clock to the card.
1332 *
1333 * We must _NOT_ enable the clock prior to power stablising.
1334 *
1335 * If a host does all the power sequencing itself, ignore the
1336 * initial MMC_POWER_UP stage.
1337 */
1338void mmc_power_up(struct mmc_host *host, u32 ocr)
1339{
1340 if (host->ios.power_mode == MMC_POWER_ON)
1341 return;
1342
1343 mmc_pwrseq_pre_power_on(host);
1344
1345 host->ios.vdd = fls(ocr) - 1;
1346 host->ios.power_mode = MMC_POWER_UP;
1347 /* Set initial state and call mmc_set_ios */
1348 mmc_set_initial_state(host);
1349
1350 mmc_set_initial_signal_voltage(host);
1351
1352 /*
1353 * This delay should be sufficient to allow the power supply
1354 * to reach the minimum voltage.
1355 */
1356 mmc_delay(host->ios.power_delay_ms);
1357
1358 mmc_pwrseq_post_power_on(host);
1359
1360 host->ios.clock = host->f_init;
1361
1362 host->ios.power_mode = MMC_POWER_ON;
1363 mmc_set_ios(host);
1364
1365 /*
1366 * This delay must be at least 74 clock sizes, or 1 ms, or the
1367 * time required to reach a stable voltage.
1368 */
1369 mmc_delay(host->ios.power_delay_ms);
1370}
1371
1372void mmc_power_off(struct mmc_host *host)
1373{
1374 if (host->ios.power_mode == MMC_POWER_OFF)
1375 return;
1376
1377 mmc_pwrseq_power_off(host);
1378
1379 host->ios.clock = 0;
1380 host->ios.vdd = 0;
1381
1382 host->ios.power_mode = MMC_POWER_OFF;
1383 /* Set initial state and call mmc_set_ios */
1384 mmc_set_initial_state(host);
1385
1386 /*
1387 * Some configurations, such as the 802.11 SDIO card in the OLPC
1388 * XO-1.5, require a short delay after poweroff before the card
1389 * can be successfully turned on again.
1390 */
1391 mmc_delay(1);
1392}
1393
1394void mmc_power_cycle(struct mmc_host *host, u32 ocr)
1395{
1396 mmc_power_off(host);
1397 /* Wait at least 1 ms according to SD spec */
1398 mmc_delay(1);
1399 mmc_power_up(host, ocr);
1400}
1401
1402/**
1403 * mmc_handle_undervoltage - Handle an undervoltage event on the MMC bus
1404 * @host: The MMC host that detected the undervoltage condition
1405 *
1406 * This function is called when an undervoltage event is detected on one of
1407 * the MMC regulators.
1408 *
1409 * Returns: 0 on success or a negative error code on failure.
1410 */
1411int mmc_handle_undervoltage(struct mmc_host *host)
1412{
1413 /* Stop the host to prevent races with card removal */
1414 __mmc_stop_host(host);
1415
1416 if (!host->bus_ops || !host->bus_ops->handle_undervoltage)
1417 return 0;
1418
1419 dev_warn(mmc_dev(host), "%s: Undervoltage detected, initiating emergency stop\n",
1420 mmc_hostname(host));
1421
1422 return host->bus_ops->handle_undervoltage(host);
1423}
1424
1425/*
1426 * Assign a mmc bus handler to a host. Only one bus handler may control a
1427 * host at any given time.
1428 */
1429void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1430{
1431 host->bus_ops = ops;
1432}
1433
1434/*
1435 * Remove the current bus handler from a host.
1436 */
1437void mmc_detach_bus(struct mmc_host *host)
1438{
1439 host->bus_ops = NULL;
1440}
1441
1442void _mmc_detect_change(struct mmc_host *host, unsigned long delay, bool cd_irq)
1443{
1444 /*
1445 * Prevent system sleep for 5s to allow user space to consume the
1446 * corresponding uevent. This is especially useful, when CD irq is used
1447 * as a system wakeup, but doesn't hurt in other cases.
1448 */
1449 if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL))
1450 __pm_wakeup_event(host->ws, 5000);
1451
1452 host->detect_change = 1;
1453 mmc_schedule_delayed_work(&host->detect, delay);
1454}
1455
1456/**
1457 * mmc_detect_change - process change of state on a MMC socket
1458 * @host: host which changed state.
1459 * @delay: optional delay to wait before detection (jiffies)
1460 *
1461 * MMC drivers should call this when they detect a card has been
1462 * inserted or removed. The MMC layer will confirm that any
1463 * present card is still functional, and initialize any newly
1464 * inserted.
1465 */
1466void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1467{
1468 _mmc_detect_change(host, delay, true);
1469}
1470EXPORT_SYMBOL(mmc_detect_change);
1471
1472void mmc_init_erase(struct mmc_card *card)
1473{
1474 unsigned int sz;
1475
1476 if (is_power_of_2(card->erase_size))
1477 card->erase_shift = ffs(card->erase_size) - 1;
1478 else
1479 card->erase_shift = 0;
1480
1481 /*
1482 * It is possible to erase an arbitrarily large area of an SD or MMC
1483 * card. That is not desirable because it can take a long time
1484 * (minutes) potentially delaying more important I/O, and also the
1485 * timeout calculations become increasingly hugely over-estimated.
1486 * Consequently, 'pref_erase' is defined as a guide to limit erases
1487 * to that size and alignment.
1488 *
1489 * For SD cards that define Allocation Unit size, limit erases to one
1490 * Allocation Unit at a time.
1491 * For MMC, have a stab at ai good value and for modern cards it will
1492 * end up being 4MiB. Note that if the value is too small, it can end
1493 * up taking longer to erase. Also note, erase_size is already set to
1494 * High Capacity Erase Size if available when this function is called.
1495 */
1496 if (mmc_card_sd(card) && card->ssr.au) {
1497 card->pref_erase = card->ssr.au;
1498 card->erase_shift = ffs(card->ssr.au) - 1;
1499 } else if (card->erase_size) {
1500 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
1501 if (sz < 128)
1502 card->pref_erase = 512 * 1024 / 512;
1503 else if (sz < 512)
1504 card->pref_erase = 1024 * 1024 / 512;
1505 else if (sz < 1024)
1506 card->pref_erase = 2 * 1024 * 1024 / 512;
1507 else
1508 card->pref_erase = 4 * 1024 * 1024 / 512;
1509 if (card->pref_erase < card->erase_size)
1510 card->pref_erase = card->erase_size;
1511 else {
1512 sz = card->pref_erase % card->erase_size;
1513 if (sz)
1514 card->pref_erase += card->erase_size - sz;
1515 }
1516 } else
1517 card->pref_erase = 0;
1518}
1519
1520static bool is_trim_arg(unsigned int arg)
1521{
1522 return (arg & MMC_TRIM_OR_DISCARD_ARGS) && arg != MMC_DISCARD_ARG;
1523}
1524
1525static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
1526 unsigned int arg, unsigned int qty)
1527{
1528 unsigned int erase_timeout;
1529
1530 if (arg == MMC_DISCARD_ARG ||
1531 (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) {
1532 erase_timeout = card->ext_csd.trim_timeout;
1533 } else if (card->ext_csd.erase_group_def & 1) {
1534 /* High Capacity Erase Group Size uses HC timeouts */
1535 if (arg == MMC_TRIM_ARG)
1536 erase_timeout = card->ext_csd.trim_timeout;
1537 else
1538 erase_timeout = card->ext_csd.hc_erase_timeout;
1539 } else {
1540 /* CSD Erase Group Size uses write timeout */
1541 unsigned int mult = (10 << card->csd.r2w_factor);
1542 unsigned int timeout_clks = card->csd.taac_clks * mult;
1543 unsigned int timeout_us;
1544
1545 /* Avoid overflow: e.g. taac_ns=80000000 mult=1280 */
1546 if (card->csd.taac_ns < 1000000)
1547 timeout_us = (card->csd.taac_ns * mult) / 1000;
1548 else
1549 timeout_us = (card->csd.taac_ns / 1000) * mult;
1550
1551 /*
1552 * ios.clock is only a target. The real clock rate might be
1553 * less but not that much less, so fudge it by multiplying by 2.
1554 */
1555 timeout_clks <<= 1;
1556 timeout_us += (timeout_clks * 1000) /
1557 (card->host->ios.clock / 1000);
1558
1559 erase_timeout = timeout_us / 1000;
1560
1561 /*
1562 * Theoretically, the calculation could underflow so round up
1563 * to 1ms in that case.
1564 */
1565 if (!erase_timeout)
1566 erase_timeout = 1;
1567 }
1568
1569 /* Multiplier for secure operations */
1570 if (arg & MMC_SECURE_ARGS) {
1571 if (arg == MMC_SECURE_ERASE_ARG)
1572 erase_timeout *= card->ext_csd.sec_erase_mult;
1573 else
1574 erase_timeout *= card->ext_csd.sec_trim_mult;
1575 }
1576
1577 erase_timeout *= qty;
1578
1579 /*
1580 * Ensure at least a 1 second timeout for SPI as per
1581 * 'mmc_set_data_timeout()'
1582 */
1583 if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
1584 erase_timeout = 1000;
1585
1586 return erase_timeout;
1587}
1588
1589static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
1590 unsigned int arg,
1591 unsigned int qty)
1592{
1593 unsigned int erase_timeout;
1594
1595 /* for DISCARD none of the below calculation applies.
1596 * the busy timeout is 250msec per discard command.
1597 */
1598 if (arg == SD_DISCARD_ARG)
1599 return SD_DISCARD_TIMEOUT_MS;
1600
1601 if (card->ssr.erase_timeout) {
1602 /* Erase timeout specified in SD Status Register (SSR) */
1603 erase_timeout = card->ssr.erase_timeout * qty +
1604 card->ssr.erase_offset;
1605 } else {
1606 /*
1607 * Erase timeout not specified in SD Status Register (SSR) so
1608 * use 250ms per write block.
1609 */
1610 erase_timeout = 250 * qty;
1611 }
1612
1613 /* Must not be less than 1 second */
1614 if (erase_timeout < 1000)
1615 erase_timeout = 1000;
1616
1617 return erase_timeout;
1618}
1619
1620static unsigned int mmc_erase_timeout(struct mmc_card *card,
1621 unsigned int arg,
1622 unsigned int qty)
1623{
1624 if (mmc_card_sd(card))
1625 return mmc_sd_erase_timeout(card, arg, qty);
1626 else
1627 return mmc_mmc_erase_timeout(card, arg, qty);
1628}
1629
1630static int mmc_do_erase(struct mmc_card *card, sector_t from,
1631 sector_t to, unsigned int arg)
1632{
1633 struct mmc_command cmd = {};
1634 unsigned int qty = 0, busy_timeout = 0;
1635 bool use_r1b_resp;
1636 int err;
1637
1638 mmc_retune_hold(card->host);
1639
1640 /*
1641 * qty is used to calculate the erase timeout which depends on how many
1642 * erase groups (or allocation units in SD terminology) are affected.
1643 * We count erasing part of an erase group as one erase group.
1644 * For SD, the allocation units are always a power of 2. For MMC, the
1645 * erase group size is almost certainly also power of 2, but it does not
1646 * seem to insist on that in the JEDEC standard, so we fall back to
1647 * division in that case. SD may not specify an allocation unit size,
1648 * in which case the timeout is based on the number of write blocks.
1649 *
1650 * Note that the timeout for secure trim 2 will only be correct if the
1651 * number of erase groups specified is the same as the total of all
1652 * preceding secure trim 1 commands. Since the power may have been
1653 * lost since the secure trim 1 commands occurred, it is generally
1654 * impossible to calculate the secure trim 2 timeout correctly.
1655 */
1656 if (card->erase_shift)
1657 qty += ((to >> card->erase_shift) -
1658 (from >> card->erase_shift)) + 1;
1659 else if (mmc_card_sd(card))
1660 qty += to - from + 1;
1661 else
1662 qty += (mmc_sector_div(to, card->erase_size) -
1663 mmc_sector_div(from, card->erase_size)) + 1;
1664
1665 if (!mmc_card_blockaddr(card)) {
1666 from <<= 9;
1667 to <<= 9;
1668 }
1669
1670 if (mmc_card_sd(card))
1671 cmd.opcode = SD_ERASE_WR_BLK_START;
1672 else
1673 cmd.opcode = MMC_ERASE_GROUP_START;
1674 cmd.arg = from;
1675 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1676
1677 if (mmc_card_ult_capacity(card)) {
1678 cmd.ext_addr = from >> 32;
1679 cmd.has_ext_addr = true;
1680 }
1681
1682 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1683 if (err) {
1684 pr_err("mmc_erase: group start error %d, "
1685 "status %#x\n", err, cmd.resp[0]);
1686 err = -EIO;
1687 goto out;
1688 }
1689
1690 memset(&cmd, 0, sizeof(struct mmc_command));
1691 if (mmc_card_sd(card))
1692 cmd.opcode = SD_ERASE_WR_BLK_END;
1693 else
1694 cmd.opcode = MMC_ERASE_GROUP_END;
1695 cmd.arg = to;
1696 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1697
1698 if (mmc_card_ult_capacity(card)) {
1699 cmd.ext_addr = to >> 32;
1700 cmd.has_ext_addr = true;
1701 }
1702
1703 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1704 if (err) {
1705 pr_err("mmc_erase: group end error %d, status %#x\n",
1706 err, cmd.resp[0]);
1707 err = -EIO;
1708 goto out;
1709 }
1710
1711 memset(&cmd, 0, sizeof(struct mmc_command));
1712 cmd.opcode = MMC_ERASE;
1713 cmd.arg = arg;
1714 busy_timeout = mmc_erase_timeout(card, arg, qty);
1715 use_r1b_resp = mmc_prepare_busy_cmd(card->host, &cmd, busy_timeout);
1716
1717 err = mmc_wait_for_cmd(card->host, &cmd, 0);
1718 if (err) {
1719 pr_err("mmc_erase: erase error %d, status %#x\n",
1720 err, cmd.resp[0]);
1721 err = -EIO;
1722 goto out;
1723 }
1724
1725 if (mmc_host_is_spi(card->host))
1726 goto out;
1727
1728 /*
1729 * In case of when R1B + MMC_CAP_WAIT_WHILE_BUSY is used, the polling
1730 * shall be avoided.
1731 */
1732 if ((card->host->caps & MMC_CAP_WAIT_WHILE_BUSY) && use_r1b_resp)
1733 goto out;
1734
1735 /* Let's poll to find out when the erase operation completes. */
1736 err = mmc_poll_for_busy(card, busy_timeout, false, MMC_BUSY_ERASE);
1737
1738out:
1739 mmc_retune_release(card->host);
1740 return err;
1741}
1742
1743static unsigned int mmc_align_erase_size(struct mmc_card *card,
1744 sector_t *from,
1745 sector_t *to,
1746 unsigned int nr)
1747{
1748 sector_t from_new = *from;
1749 unsigned int nr_new = nr, rem;
1750
1751 /*
1752 * When the 'card->erase_size' is power of 2, we can use round_up/down()
1753 * to align the erase size efficiently.
1754 */
1755 if (is_power_of_2(card->erase_size)) {
1756 sector_t temp = from_new;
1757
1758 from_new = round_up(temp, card->erase_size);
1759 rem = from_new - temp;
1760
1761 if (nr_new > rem)
1762 nr_new -= rem;
1763 else
1764 return 0;
1765
1766 nr_new = round_down(nr_new, card->erase_size);
1767 } else {
1768 rem = mmc_sector_mod(from_new, card->erase_size);
1769 if (rem) {
1770 rem = card->erase_size - rem;
1771 from_new += rem;
1772 if (nr_new > rem)
1773 nr_new -= rem;
1774 else
1775 return 0;
1776 }
1777
1778 rem = nr_new % card->erase_size;
1779 if (rem)
1780 nr_new -= rem;
1781 }
1782
1783 if (nr_new == 0)
1784 return 0;
1785
1786 *to = from_new + nr_new;
1787 *from = from_new;
1788
1789 return nr_new;
1790}
1791
1792/**
1793 * mmc_erase - erase sectors.
1794 * @card: card to erase
1795 * @from: first sector to erase
1796 * @nr: number of sectors to erase
1797 * @arg: erase command argument
1798 *
1799 * Caller must claim host before calling this function.
1800 */
1801int mmc_erase(struct mmc_card *card, sector_t from, unsigned int nr,
1802 unsigned int arg)
1803{
1804 unsigned int rem;
1805 sector_t to = from + nr;
1806
1807 int err;
1808
1809 if (!(card->csd.cmdclass & CCC_ERASE))
1810 return -EOPNOTSUPP;
1811
1812 if (!card->erase_size)
1813 return -EOPNOTSUPP;
1814
1815 if (mmc_card_sd(card) && arg != SD_ERASE_ARG && arg != SD_DISCARD_ARG)
1816 return -EOPNOTSUPP;
1817
1818 if (mmc_card_mmc(card) && (arg & MMC_SECURE_ARGS) &&
1819 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
1820 return -EOPNOTSUPP;
1821
1822 if (mmc_card_mmc(card) && is_trim_arg(arg) &&
1823 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
1824 return -EOPNOTSUPP;
1825
1826 if (arg == MMC_SECURE_ERASE_ARG) {
1827 if (mmc_sector_mod(from, card->erase_size) || nr % card->erase_size)
1828 return -EINVAL;
1829 }
1830
1831 if (arg == MMC_ERASE_ARG)
1832 nr = mmc_align_erase_size(card, &from, &to, nr);
1833
1834 if (nr == 0)
1835 return 0;
1836
1837 if (to <= from)
1838 return -EINVAL;
1839
1840 /* 'from' and 'to' are inclusive */
1841 to -= 1;
1842
1843 /*
1844 * Special case where only one erase-group fits in the timeout budget:
1845 * If the region crosses an erase-group boundary on this particular
1846 * case, we will be trimming more than one erase-group which, does not
1847 * fit in the timeout budget of the controller, so we need to split it
1848 * and call mmc_do_erase() twice if necessary. This special case is
1849 * identified by the card->eg_boundary flag.
1850 */
1851 rem = card->erase_size - mmc_sector_mod(from, card->erase_size);
1852 if ((arg & MMC_TRIM_OR_DISCARD_ARGS) && card->eg_boundary && nr > rem) {
1853 err = mmc_do_erase(card, from, from + rem - 1, arg);
1854 from += rem;
1855 if ((err) || (to <= from))
1856 return err;
1857 }
1858
1859 return mmc_do_erase(card, from, to, arg);
1860}
1861EXPORT_SYMBOL(mmc_erase);
1862
1863bool mmc_card_can_erase(struct mmc_card *card)
1864{
1865 return (card->csd.cmdclass & CCC_ERASE && card->erase_size);
1866}
1867EXPORT_SYMBOL(mmc_card_can_erase);
1868
1869bool mmc_card_can_trim(struct mmc_card *card)
1870{
1871 return ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN) &&
1872 (!(card->quirks & MMC_QUIRK_TRIM_BROKEN)));
1873}
1874EXPORT_SYMBOL(mmc_card_can_trim);
1875
1876bool mmc_card_can_discard(struct mmc_card *card)
1877{
1878 /*
1879 * As there's no way to detect the discard support bit at v4.5
1880 * use the s/w feature support filed.
1881 */
1882 return (card->ext_csd.feature_support & MMC_DISCARD_FEATURE);
1883}
1884EXPORT_SYMBOL(mmc_card_can_discard);
1885
1886bool mmc_card_can_sanitize(struct mmc_card *card)
1887{
1888 if (!mmc_card_can_trim(card) && !mmc_card_can_erase(card))
1889 return false;
1890 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
1891 return true;
1892 return false;
1893}
1894
1895bool mmc_card_can_secure_erase_trim(struct mmc_card *card)
1896{
1897 return ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) &&
1898 !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN));
1899}
1900EXPORT_SYMBOL(mmc_card_can_secure_erase_trim);
1901
1902bool mmc_card_can_cmd23(struct mmc_card *card)
1903{
1904 return ((mmc_card_mmc(card) &&
1905 card->csd.mmca_vsn >= CSD_SPEC_VER_3) ||
1906 (mmc_card_sd(card) && !mmc_card_ult_capacity(card) &&
1907 card->scr.cmds & SD_SCR_CMD23_SUPPORT));
1908}
1909EXPORT_SYMBOL(mmc_card_can_cmd23);
1910
1911int mmc_erase_group_aligned(struct mmc_card *card, sector_t from,
1912 unsigned int nr)
1913{
1914 if (!card->erase_size)
1915 return 0;
1916 if (mmc_sector_mod(from, card->erase_size) || nr % card->erase_size)
1917 return 0;
1918 return 1;
1919}
1920EXPORT_SYMBOL(mmc_erase_group_aligned);
1921
1922static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
1923 unsigned int arg)
1924{
1925 struct mmc_host *host = card->host;
1926 unsigned int max_discard, x, y, qty = 0, max_qty, min_qty, timeout;
1927 unsigned int last_timeout = 0;
1928 unsigned int max_busy_timeout = host->max_busy_timeout ?
1929 host->max_busy_timeout : MMC_ERASE_TIMEOUT_MS;
1930
1931 if (card->erase_shift) {
1932 max_qty = UINT_MAX >> card->erase_shift;
1933 min_qty = card->pref_erase >> card->erase_shift;
1934 } else if (mmc_card_sd(card)) {
1935 max_qty = UINT_MAX;
1936 min_qty = card->pref_erase;
1937 } else {
1938 max_qty = UINT_MAX / card->erase_size;
1939 min_qty = card->pref_erase / card->erase_size;
1940 }
1941
1942 /*
1943 * We should not only use 'host->max_busy_timeout' as the limitation
1944 * when deciding the max discard sectors. We should set a balance value
1945 * to improve the erase speed, and it can not get too long timeout at
1946 * the same time.
1947 *
1948 * Here we set 'card->pref_erase' as the minimal discard sectors no
1949 * matter what size of 'host->max_busy_timeout', but if the
1950 * 'host->max_busy_timeout' is large enough for more discard sectors,
1951 * then we can continue to increase the max discard sectors until we
1952 * get a balance value. In cases when the 'host->max_busy_timeout'
1953 * isn't specified, use the default max erase timeout.
1954 */
1955 do {
1956 y = 0;
1957 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
1958 timeout = mmc_erase_timeout(card, arg, qty + x);
1959
1960 if (qty + x > min_qty && timeout > max_busy_timeout)
1961 break;
1962
1963 if (timeout < last_timeout)
1964 break;
1965 last_timeout = timeout;
1966 y = x;
1967 }
1968 qty += y;
1969 } while (y);
1970
1971 if (!qty)
1972 return 0;
1973
1974 /*
1975 * When specifying a sector range to trim, chances are we might cross
1976 * an erase-group boundary even if the amount of sectors is less than
1977 * one erase-group.
1978 * If we can only fit one erase-group in the controller timeout budget,
1979 * we have to care that erase-group boundaries are not crossed by a
1980 * single trim operation. We flag that special case with "eg_boundary".
1981 * In all other cases we can just decrement qty and pretend that we
1982 * always touch (qty + 1) erase-groups as a simple optimization.
1983 */
1984 if (qty == 1)
1985 card->eg_boundary = 1;
1986 else
1987 qty--;
1988
1989 /* Convert qty to sectors */
1990 if (card->erase_shift)
1991 max_discard = qty << card->erase_shift;
1992 else if (mmc_card_sd(card))
1993 max_discard = qty + 1;
1994 else
1995 max_discard = qty * card->erase_size;
1996
1997 return max_discard;
1998}
1999
2000unsigned int mmc_calc_max_discard(struct mmc_card *card)
2001{
2002 struct mmc_host *host = card->host;
2003 unsigned int max_discard, max_trim;
2004
2005 /*
2006 * Without erase_group_def set, MMC erase timeout depends on clock
2007 * frequence which can change. In that case, the best choice is
2008 * just the preferred erase size.
2009 */
2010 if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
2011 return card->pref_erase;
2012
2013 max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
2014 if (mmc_card_can_trim(card)) {
2015 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
2016 if (max_trim < max_discard || max_discard == 0)
2017 max_discard = max_trim;
2018 } else if (max_discard < card->erase_size) {
2019 max_discard = 0;
2020 }
2021 pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
2022 mmc_hostname(host), max_discard, host->max_busy_timeout ?
2023 host->max_busy_timeout : MMC_ERASE_TIMEOUT_MS);
2024 return max_discard;
2025}
2026EXPORT_SYMBOL(mmc_calc_max_discard);
2027
2028bool mmc_card_is_blockaddr(struct mmc_card *card)
2029{
2030 return card ? mmc_card_blockaddr(card) : false;
2031}
2032EXPORT_SYMBOL(mmc_card_is_blockaddr);
2033
2034int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
2035{
2036 struct mmc_command cmd = {};
2037
2038 if (mmc_card_blockaddr(card) || mmc_card_ddr52(card) ||
2039 mmc_card_hs400(card) || mmc_card_hs400es(card))
2040 return 0;
2041
2042 cmd.opcode = MMC_SET_BLOCKLEN;
2043 cmd.arg = blocklen;
2044 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2045 return mmc_wait_for_cmd(card->host, &cmd, 5);
2046}
2047EXPORT_SYMBOL(mmc_set_blocklen);
2048
2049static void mmc_hw_reset_for_init(struct mmc_host *host)
2050{
2051 mmc_pwrseq_reset(host);
2052
2053 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->card_hw_reset)
2054 return;
2055 host->ops->card_hw_reset(host);
2056}
2057
2058/**
2059 * mmc_hw_reset - reset the card in hardware
2060 * @card: card to be reset
2061 *
2062 * Hard reset the card. This function is only for upper layers, like the
2063 * block layer or card drivers. You cannot use it in host drivers (struct
2064 * mmc_card might be gone then).
2065 *
2066 * Return: 0 on success, -errno on failure
2067 */
2068int mmc_hw_reset(struct mmc_card *card)
2069{
2070 struct mmc_host *host = card->host;
2071 int ret;
2072
2073 ret = host->bus_ops->hw_reset(host);
2074 if (ret < 0)
2075 pr_warn("%s: tried to HW reset card, got error %d\n",
2076 mmc_hostname(host), ret);
2077
2078 return ret;
2079}
2080EXPORT_SYMBOL(mmc_hw_reset);
2081
2082int mmc_sw_reset(struct mmc_card *card)
2083{
2084 struct mmc_host *host = card->host;
2085 int ret;
2086
2087 if (!host->bus_ops->sw_reset)
2088 return -EOPNOTSUPP;
2089
2090 ret = host->bus_ops->sw_reset(host);
2091 if (ret)
2092 pr_warn("%s: tried to SW reset card, got error %d\n",
2093 mmc_hostname(host), ret);
2094
2095 return ret;
2096}
2097EXPORT_SYMBOL(mmc_sw_reset);
2098
2099static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2100{
2101 host->f_init = freq;
2102
2103 pr_debug("%s: %s: trying to init card at %u Hz\n",
2104 mmc_hostname(host), __func__, host->f_init);
2105
2106 mmc_power_up(host, host->ocr_avail);
2107
2108 /*
2109 * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2110 * do a hardware reset if possible.
2111 */
2112 mmc_hw_reset_for_init(host);
2113
2114 /*
2115 * sdio_reset sends CMD52 to reset card. Since we do not know
2116 * if the card is being re-initialized, just send it. CMD52
2117 * should be ignored by SD/eMMC cards.
2118 * Skip it if we already know that we do not support SDIO commands
2119 */
2120 if (!(host->caps2 & MMC_CAP2_NO_SDIO))
2121 sdio_reset(host);
2122
2123 mmc_go_idle(host);
2124
2125 if (!(host->caps2 & MMC_CAP2_NO_SD)) {
2126 if (mmc_send_if_cond_pcie(host, host->ocr_avail))
2127 goto out;
2128 if (mmc_card_sd_express(host))
2129 return 0;
2130 }
2131
2132 /* Order's important: probe SDIO, then SD, then MMC */
2133 if (!(host->caps2 & MMC_CAP2_NO_SDIO))
2134 if (!mmc_attach_sdio(host))
2135 return 0;
2136
2137 if (!(host->caps2 & MMC_CAP2_NO_SD))
2138 if (!mmc_attach_sd(host))
2139 return 0;
2140
2141 if (!(host->caps2 & MMC_CAP2_NO_MMC))
2142 if (!mmc_attach_mmc(host))
2143 return 0;
2144
2145out:
2146 mmc_power_off(host);
2147 return -EIO;
2148}
2149
2150int _mmc_detect_card_removed(struct mmc_host *host)
2151{
2152 int ret;
2153
2154 if (!host->card || mmc_card_removed(host->card))
2155 return 1;
2156
2157 ret = host->bus_ops->alive(host);
2158
2159 /*
2160 * Card detect status and alive check may be out of sync if card is
2161 * removed slowly, when card detect switch changes while card/slot
2162 * pads are still contacted in hardware (refer to "SD Card Mechanical
2163 * Addendum, Appendix C: Card Detection Switch"). So reschedule a
2164 * detect work 200ms later for this case.
2165 */
2166 if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) {
2167 mmc_detect_change(host, msecs_to_jiffies(200));
2168 pr_debug("%s: card removed too slowly\n", mmc_hostname(host));
2169 }
2170
2171 if (ret) {
2172 mmc_card_set_removed(host->card);
2173 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2174 }
2175
2176 return ret;
2177}
2178
2179int mmc_detect_card_removed(struct mmc_host *host)
2180{
2181 struct mmc_card *card = host->card;
2182 int ret;
2183
2184 WARN_ON(!host->claimed);
2185
2186 if (!card)
2187 return 1;
2188
2189 if (!mmc_card_is_removable(host))
2190 return 0;
2191
2192 ret = mmc_card_removed(card);
2193 /*
2194 * The card will be considered unchanged unless we have been asked to
2195 * detect a change or host requires polling to provide card detection.
2196 */
2197 if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
2198 return ret;
2199
2200 host->detect_change = 0;
2201 if (!ret) {
2202 ret = _mmc_detect_card_removed(host);
2203 if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) {
2204 /*
2205 * Schedule a detect work as soon as possible to let a
2206 * rescan handle the card removal.
2207 */
2208 cancel_delayed_work(&host->detect);
2209 _mmc_detect_change(host, 0, false);
2210 }
2211 }
2212
2213 return ret;
2214}
2215EXPORT_SYMBOL(mmc_detect_card_removed);
2216
2217int mmc_card_alternative_gpt_sector(struct mmc_card *card, sector_t *gpt_sector)
2218{
2219 unsigned int boot_sectors_num;
2220
2221 if ((!(card->host->caps2 & MMC_CAP2_ALT_GPT_TEGRA)))
2222 return -EOPNOTSUPP;
2223
2224 /* filter out unrelated cards */
2225 if (card->ext_csd.rev < 3 ||
2226 !mmc_card_mmc(card) ||
2227 !mmc_card_is_blockaddr(card) ||
2228 mmc_card_is_removable(card->host))
2229 return -ENOENT;
2230
2231 /*
2232 * eMMC storage has two special boot partitions in addition to the
2233 * main one. NVIDIA's bootloader linearizes eMMC boot0->boot1->main
2234 * accesses, this means that the partition table addresses are shifted
2235 * by the size of boot partitions. In accordance with the eMMC
2236 * specification, the boot partition size is calculated as follows:
2237 *
2238 * boot partition size = 128K byte x BOOT_SIZE_MULT
2239 *
2240 * Calculate number of sectors occupied by the both boot partitions.
2241 */
2242 boot_sectors_num = card->ext_csd.raw_boot_mult * SZ_128K /
2243 SZ_512 * MMC_NUM_BOOT_PARTITION;
2244
2245 /* Defined by NVIDIA and used by Android devices. */
2246 *gpt_sector = card->ext_csd.sectors - boot_sectors_num - 1;
2247
2248 return 0;
2249}
2250EXPORT_SYMBOL(mmc_card_alternative_gpt_sector);
2251
2252void mmc_rescan(struct work_struct *work)
2253{
2254 struct mmc_host *host =
2255 container_of(work, struct mmc_host, detect.work);
2256 int i;
2257
2258 if (host->rescan_disable)
2259 return;
2260
2261 /* If there is a non-removable card registered, only scan once */
2262 if (!mmc_card_is_removable(host) && host->rescan_entered)
2263 return;
2264 host->rescan_entered = 1;
2265
2266 if (host->trigger_card_event && host->ops->card_event) {
2267 mmc_claim_host(host);
2268 host->ops->card_event(host);
2269 mmc_release_host(host);
2270 host->trigger_card_event = false;
2271 }
2272
2273 /* Verify a registered card to be functional, else remove it. */
2274 if (host->bus_ops)
2275 host->bus_ops->detect(host);
2276
2277 host->detect_change = 0;
2278
2279 /* if there still is a card present, stop here */
2280 if (host->bus_ops != NULL)
2281 goto out;
2282
2283 mmc_claim_host(host);
2284 if (mmc_card_is_removable(host) && host->ops->get_cd &&
2285 host->ops->get_cd(host) == 0) {
2286 mmc_power_off(host);
2287 mmc_release_host(host);
2288 goto out;
2289 }
2290
2291 /* If an SD express card is present, then leave it as is. */
2292 if (mmc_card_sd_express(host)) {
2293 mmc_release_host(host);
2294 goto out;
2295 }
2296
2297 /*
2298 * Ideally we should favor initialization of legacy SD cards and defer
2299 * UHS-II enumeration. However, it seems like cards doesn't reliably
2300 * announce their support for UHS-II in the response to the ACMD41,
2301 * while initializing the legacy SD interface. Therefore, let's start
2302 * with UHS-II for now.
2303 */
2304 if (!mmc_attach_sd_uhs2(host)) {
2305 mmc_release_host(host);
2306 goto out;
2307 }
2308
2309 for (i = 0; i < ARRAY_SIZE(freqs); i++) {
2310 unsigned int freq = freqs[i];
2311 if (freq > host->f_max) {
2312 if (i + 1 < ARRAY_SIZE(freqs))
2313 continue;
2314 freq = host->f_max;
2315 }
2316 if (!mmc_rescan_try_freq(host, max(freq, host->f_min)))
2317 break;
2318 if (freqs[i] <= host->f_min)
2319 break;
2320 }
2321
2322 /* A non-removable card should have been detected by now. */
2323 if (!mmc_card_is_removable(host) && !host->bus_ops)
2324 pr_info("%s: Failed to initialize a non-removable card",
2325 mmc_hostname(host));
2326
2327 /*
2328 * Ignore the command timeout errors observed during
2329 * the card init as those are excepted.
2330 */
2331 host->err_stats[MMC_ERR_CMD_TIMEOUT] = 0;
2332 mmc_release_host(host);
2333
2334 out:
2335 if (host->caps & MMC_CAP_NEEDS_POLL)
2336 mmc_schedule_delayed_work(&host->detect, HZ);
2337}
2338
2339void mmc_start_host(struct mmc_host *host)
2340{
2341 bool power_up = !(host->caps2 &
2342 (MMC_CAP2_NO_PRESCAN_POWERUP | MMC_CAP2_SD_UHS2));
2343
2344 host->f_init = max(min(freqs[0], host->f_max), host->f_min);
2345 host->rescan_disable = 0;
2346
2347 if (power_up) {
2348 mmc_claim_host(host);
2349 mmc_power_up(host, host->ocr_avail);
2350 mmc_release_host(host);
2351 }
2352
2353 mmc_gpiod_request_cd_irq(host);
2354 _mmc_detect_change(host, 0, false);
2355}
2356
2357void __mmc_stop_host(struct mmc_host *host)
2358{
2359 if (host->rescan_disable)
2360 return;
2361
2362 if (host->slot.cd_irq >= 0) {
2363 mmc_gpio_set_cd_wake(host, false);
2364 disable_irq(host->slot.cd_irq);
2365 }
2366
2367 host->rescan_disable = 1;
2368 cancel_delayed_work_sync(&host->detect);
2369}
2370
2371void mmc_stop_host(struct mmc_host *host)
2372{
2373 __mmc_stop_host(host);
2374
2375 /* clear pm flags now and let card drivers set them as needed */
2376 host->pm_flags = 0;
2377
2378 if (host->bus_ops) {
2379 /* Calling bus_ops->remove() with a claimed host can deadlock */
2380 host->bus_ops->remove(host);
2381 mmc_claim_host(host);
2382 mmc_detach_bus(host);
2383 mmc_power_off(host);
2384 mmc_release_host(host);
2385 return;
2386 }
2387
2388 mmc_claim_host(host);
2389 mmc_power_off(host);
2390 mmc_release_host(host);
2391}
2392
2393static int __init mmc_init(void)
2394{
2395 int ret;
2396
2397 ret = mmc_register_bus();
2398 if (ret)
2399 return ret;
2400
2401 ret = mmc_register_host_class();
2402 if (ret)
2403 goto unregister_bus;
2404
2405 ret = sdio_register_bus();
2406 if (ret)
2407 goto unregister_host_class;
2408
2409 return 0;
2410
2411unregister_host_class:
2412 mmc_unregister_host_class();
2413unregister_bus:
2414 mmc_unregister_bus();
2415 return ret;
2416}
2417
2418static void __exit mmc_exit(void)
2419{
2420 sdio_unregister_bus();
2421 mmc_unregister_host_class();
2422 mmc_unregister_bus();
2423}
2424
2425subsys_initcall(mmc_init);
2426module_exit(mmc_exit);
2427
2428MODULE_DESCRIPTION("MMC core driver");
2429MODULE_LICENSE("GPL");