mmc: core: refactor asynchronous request finalization
[linux-block.git] / drivers / mmc / core / core.c
CommitLineData
1da177e4 1/*
aaac1b47 2 * linux/drivers/mmc/core/core.c
1da177e4
LT
3 *
4 * Copyright (C) 2003-2004 Russell King, All Rights Reserved.
5b4fd9ae 5 * SD support Copyright (C) 2004 Ian Molton, All Rights Reserved.
ad3868b2 6 * Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved.
bce40a36 7 * MMCv4 support Copyright (C) 2006 Philip Langdale, All Rights Reserved.
1da177e4
LT
8 *
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.
12 */
1da177e4
LT
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>
af8350c7 21#include <linux/leds.h>
b57c43ad 22#include <linux/scatterlist.h>
86e8286a 23#include <linux/log2.h>
5c13941a 24#include <linux/regulator/consumer.h>
e594573d 25#include <linux/pm_runtime.h>
bbd43682 26#include <linux/pm_wakeup.h>
35eb6db1 27#include <linux/suspend.h>
1b676f70
PF
28#include <linux/fault-inject.h>
29#include <linux/random.h>
950d56ac 30#include <linux/slab.h>
6e9e318b 31#include <linux/of.h>
1da177e4
LT
32
33#include <linux/mmc/card.h>
34#include <linux/mmc/host.h>
da7fbe58
PO
35#include <linux/mmc/mmc.h>
36#include <linux/mmc/sd.h>
740a221e 37#include <linux/mmc/slot-gpio.h>
1da177e4 38
7962fc37
BW
39#define CREATE_TRACE_POINTS
40#include <trace/events/mmc.h>
41
aaac1b47 42#include "core.h"
4facdde1 43#include "card.h"
ffce2e7e
PO
44#include "bus.h"
45#include "host.h"
e29a7d73 46#include "sdio_bus.h"
3aa8793f 47#include "pwrseq.h"
da7fbe58
PO
48
49#include "mmc_ops.h"
50#include "sd_ops.h"
5c4e6f13 51#include "sdio_ops.h"
1da177e4 52
8fee476b
TR
53/* If the device is not responding */
54#define MMC_CORE_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */
55
950d56ac
JC
56/*
57 * Background operations can take a long time, depending on the housekeeping
58 * operations the card has to perform.
59 */
60#define MMC_BKOPS_MAX_TIMEOUT (4 * 60 * 1000) /* max time to wait in ms */
61
12182aff
UH
62/* The max erase timeout, used when host->max_busy_timeout isn't specified */
63#define MMC_ERASE_TIMEOUT_MS (60 * 1000) /* 60 s */
64
fa550189 65static const unsigned freqs[] = { 400000, 300000, 200000, 100000 };
ffce2e7e 66
af517150
DB
67/*
68 * Enabling software CRCs on the data blocks can be a significant (30%)
69 * performance cost, and for other reasons may not always be desired.
70 * So we allow it it to be disabled.
71 */
90ab5ee9 72bool use_spi_crc = 1;
af517150
DB
73module_param(use_spi_crc, bool, 0);
74
ffce2e7e
PO
75static int mmc_schedule_delayed_work(struct delayed_work *work,
76 unsigned long delay)
77{
520bd7a8
UH
78 /*
79 * We use the system_freezable_wq, because of two reasons.
80 * First, it allows several works (not the same work item) to be
81 * executed simultaneously. Second, the queue becomes frozen when
82 * userspace becomes frozen during system PM.
83 */
84 return queue_delayed_work(system_freezable_wq, work, delay);
ffce2e7e
PO
85}
86
1b676f70
PF
87#ifdef CONFIG_FAIL_MMC_REQUEST
88
89/*
90 * Internal function. Inject random data errors.
91 * If mmc_data is NULL no errors are injected.
92 */
93static void mmc_should_fail_request(struct mmc_host *host,
94 struct mmc_request *mrq)
95{
96 struct mmc_command *cmd = mrq->cmd;
97 struct mmc_data *data = mrq->data;
98 static const int data_errors[] = {
99 -ETIMEDOUT,
100 -EILSEQ,
101 -EIO,
102 };
103
104 if (!data)
105 return;
106
107 if (cmd->error || data->error ||
108 !should_fail(&host->fail_mmc_request, data->blksz * data->blocks))
109 return;
110
2e744fcb
AM
111 data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)];
112 data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9;
1b676f70
PF
113}
114
115#else /* CONFIG_FAIL_MMC_REQUEST */
116
117static inline void mmc_should_fail_request(struct mmc_host *host,
118 struct mmc_request *mrq)
119{
120}
121
122#endif /* CONFIG_FAIL_MMC_REQUEST */
123
5163af5a
AH
124static inline void mmc_complete_cmd(struct mmc_request *mrq)
125{
126 if (mrq->cap_cmd_during_tfr && !completion_done(&mrq->cmd_completion))
127 complete_all(&mrq->cmd_completion);
128}
129
130void mmc_command_done(struct mmc_host *host, struct mmc_request *mrq)
131{
132 if (!mrq->cap_cmd_during_tfr)
133 return;
134
135 mmc_complete_cmd(mrq);
136
137 pr_debug("%s: cmd done, tfr ongoing (CMD%u)\n",
138 mmc_hostname(host), mrq->cmd->opcode);
139}
140EXPORT_SYMBOL(mmc_command_done);
141
1da177e4 142/**
fe10c6ab
RK
143 * mmc_request_done - finish processing an MMC request
144 * @host: MMC host which completed request
145 * @mrq: MMC request which request
1da177e4
LT
146 *
147 * MMC drivers should call this function when they have completed
fe10c6ab 148 * their processing of a request.
1da177e4
LT
149 */
150void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq)
151{
152 struct mmc_command *cmd = mrq->cmd;
920e70c5
RK
153 int err = cmd->error;
154
bd11e8bd 155 /* Flag re-tuning needed on CRC errors */
031277d4
CJ
156 if ((cmd->opcode != MMC_SEND_TUNING_BLOCK &&
157 cmd->opcode != MMC_SEND_TUNING_BLOCK_HS200) &&
158 (err == -EILSEQ || (mrq->sbc && mrq->sbc->error == -EILSEQ) ||
bd11e8bd 159 (mrq->data && mrq->data->error == -EILSEQ) ||
031277d4 160 (mrq->stop && mrq->stop->error == -EILSEQ)))
bd11e8bd
AH
161 mmc_retune_needed(host);
162
af517150
DB
163 if (err && cmd->retries && mmc_host_is_spi(host)) {
164 if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
165 cmd->retries = 0;
166 }
167
5163af5a
AH
168 if (host->ongoing_mrq == mrq)
169 host->ongoing_mrq = NULL;
170
171 mmc_complete_cmd(mrq);
172
7962fc37
BW
173 trace_mmc_request_done(host, mrq);
174
d3049504 175 if (err && cmd->retries && !mmc_card_removed(host->card)) {
08a7e1df
AH
176 /*
177 * Request starter must handle retries - see
178 * mmc_wait_for_req_done().
179 */
180 if (mrq->done)
181 mrq->done(mrq);
e4d21708 182 } else {
1b676f70
PF
183 mmc_should_fail_request(host, mrq);
184
5163af5a
AH
185 if (!host->ongoing_mrq)
186 led_trigger_event(host->led, LED_OFF);
af8350c7 187
fc75b708
AG
188 if (mrq->sbc) {
189 pr_debug("%s: req done <CMD%u>: %d: %08x %08x %08x %08x\n",
190 mmc_hostname(host), mrq->sbc->opcode,
191 mrq->sbc->error,
192 mrq->sbc->resp[0], mrq->sbc->resp[1],
193 mrq->sbc->resp[2], mrq->sbc->resp[3]);
194 }
195
e4d21708
PO
196 pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n",
197 mmc_hostname(host), cmd->opcode, err,
198 cmd->resp[0], cmd->resp[1],
199 cmd->resp[2], cmd->resp[3]);
200
201 if (mrq->data) {
202 pr_debug("%s: %d bytes transferred: %d\n",
203 mmc_hostname(host),
204 mrq->data->bytes_xfered, mrq->data->error);
205 }
206
207 if (mrq->stop) {
208 pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n",
209 mmc_hostname(host), mrq->stop->opcode,
210 mrq->stop->error,
211 mrq->stop->resp[0], mrq->stop->resp[1],
212 mrq->stop->resp[2], mrq->stop->resp[3]);
213 }
214
215 if (mrq->done)
216 mrq->done(mrq);
1da177e4
LT
217 }
218}
219
220EXPORT_SYMBOL(mmc_request_done);
221
90a81489
AH
222static void __mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
223{
224 int err;
225
226 /* Assumes host controller has been runtime resumed by mmc_claim_host */
227 err = mmc_retune(host);
228 if (err) {
229 mrq->cmd->error = err;
230 mmc_request_done(host, mrq);
231 return;
232 }
233
5d3f6ef0
HG
234 /*
235 * For sdio rw commands we must wait for card busy otherwise some
236 * sdio devices won't work properly.
237 */
238 if (mmc_is_io_op(mrq->cmd->opcode) && host->ops->card_busy) {
239 int tries = 500; /* Wait aprox 500ms at maximum */
240
241 while (host->ops->card_busy(host) && --tries)
242 mmc_delay(1);
243
244 if (tries == 0) {
245 mrq->cmd->error = -EBUSY;
246 mmc_request_done(host, mrq);
247 return;
248 }
249 }
250
5163af5a
AH
251 if (mrq->cap_cmd_during_tfr) {
252 host->ongoing_mrq = mrq;
253 /*
254 * Retry path could come through here without having waiting on
255 * cmd_completion, so ensure it is reinitialised.
256 */
257 reinit_completion(&mrq->cmd_completion);
258 }
259
7962fc37
BW
260 trace_mmc_request_start(host, mrq);
261
90a81489
AH
262 host->ops->request(host, mrq);
263}
264
4b67e63f 265static void mmc_mrq_pr_debug(struct mmc_host *host, struct mmc_request *mrq)
1da177e4 266{
7b2fd4f2
JC
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
4b67e63f
AH
273 if (mrq->cmd) {
274 pr_debug("%s: starting CMD%u arg %08x flags %08x\n",
275 mmc_hostname(host), mrq->cmd->opcode, mrq->cmd->arg,
276 mrq->cmd->flags);
277 }
1da177e4 278
e4d21708
PO
279 if (mrq->data) {
280 pr_debug("%s: blksz %d blocks %d flags %08x "
281 "tsac %d ms nsac %d\n",
282 mmc_hostname(host), mrq->data->blksz,
283 mrq->data->blocks, mrq->data->flags,
ce252edd 284 mrq->data->timeout_ns / 1000000,
e4d21708
PO
285 mrq->data->timeout_clks);
286 }
287
288 if (mrq->stop) {
289 pr_debug("%s: CMD%u arg %08x flags %08x\n",
290 mmc_hostname(host), mrq->stop->opcode,
291 mrq->stop->arg, mrq->stop->flags);
292 }
4b67e63f
AH
293}
294
f34bdd2f 295static int mmc_mrq_prep(struct mmc_host *host, struct mmc_request *mrq)
4b67e63f
AH
296{
297#ifdef CONFIG_MMC_DEBUG
298 unsigned int i, sz;
299 struct scatterlist *sg;
300#endif
1da177e4 301
f34bdd2f
AH
302 if (mrq->cmd) {
303 mrq->cmd->error = 0;
304 mrq->cmd->mrq = mrq;
305 mrq->cmd->data = mrq->data;
306 }
cce411e6
AG
307 if (mrq->sbc) {
308 mrq->sbc->error = 0;
309 mrq->sbc->mrq = mrq;
310 }
1da177e4 311 if (mrq->data) {
6ff897ff
SL
312 if (mrq->data->blksz > host->max_blk_size ||
313 mrq->data->blocks > host->max_blk_count ||
314 mrq->data->blocks * mrq->data->blksz > host->max_req_size)
315 return -EINVAL;
976d9276
PO
316#ifdef CONFIG_MMC_DEBUG
317 sz = 0;
a84756c5
PO
318 for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i)
319 sz += sg->length;
6ff897ff
SL
320 if (sz != mrq->data->blocks * mrq->data->blksz)
321 return -EINVAL;
976d9276 322#endif
1da177e4
LT
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 }
f34bdd2f
AH
331
332 return 0;
333}
334
335static int mmc_start_request(struct mmc_host *host, struct mmc_request *mrq)
336{
337 int err;
338
339 mmc_retune_hold(host);
340
341 if (mmc_card_removed(host->card))
342 return -ENOMEDIUM;
343
344 mmc_mrq_pr_debug(host, mrq);
345
346 WARN_ON(!host->claimed);
347
348 err = mmc_mrq_prep(host, mrq);
349 if (err)
350 return err;
351
66c036e0 352 led_trigger_event(host->led, LED_FULL);
90a81489 353 __mmc_start_request(host, mrq);
f100c1c2
AH
354
355 return 0;
1da177e4
LT
356}
357
950d56ac
JC
358/**
359 * mmc_start_bkops - start BKOPS for supported cards
360 * @card: MMC card to start BKOPS
361 * @form_exception: A flag to indicate if this function was
362 * called due to an exception raised by the card
363 *
364 * Start background operations whenever requested.
365 * When the urgent BKOPS bit is set in a R1 command response
366 * then background operations should be started immediately.
367*/
368void mmc_start_bkops(struct mmc_card *card, bool from_exception)
369{
370 int err;
371 int timeout;
372 bool use_busy_signal;
373
0501be64 374 if (!card->ext_csd.man_bkops_en || mmc_card_doing_bkops(card))
950d56ac
JC
375 return;
376
377 err = mmc_read_bkops_status(card);
378 if (err) {
379 pr_err("%s: Failed to read bkops status: %d\n",
380 mmc_hostname(card->host), err);
381 return;
382 }
383
384 if (!card->ext_csd.raw_bkops_status)
385 return;
386
387 if (card->ext_csd.raw_bkops_status < EXT_CSD_BKOPS_LEVEL_2 &&
388 from_exception)
389 return;
390
391 mmc_claim_host(card->host);
392 if (card->ext_csd.raw_bkops_status >= EXT_CSD_BKOPS_LEVEL_2) {
393 timeout = MMC_BKOPS_MAX_TIMEOUT;
394 use_busy_signal = true;
395 } else {
396 timeout = 0;
397 use_busy_signal = false;
398 }
399
66073d86
AH
400 mmc_retune_hold(card->host);
401
950d56ac 402 err = __mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
aa33ce3c 403 EXT_CSD_BKOPS_START, 1, timeout, 0,
4509f847 404 use_busy_signal, true, false);
950d56ac
JC
405 if (err) {
406 pr_warn("%s: Error %d starting bkops\n",
407 mmc_hostname(card->host), err);
66073d86 408 mmc_retune_release(card->host);
950d56ac
JC
409 goto out;
410 }
411
412 /*
413 * For urgent bkops status (LEVEL_2 and more)
414 * bkops executed synchronously, otherwise
415 * the operation is in progress
416 */
417 if (!use_busy_signal)
418 mmc_card_set_doing_bkops(card);
66073d86
AH
419 else
420 mmc_retune_release(card->host);
950d56ac
JC
421out:
422 mmc_release_host(card->host);
423}
424EXPORT_SYMBOL(mmc_start_bkops);
425
2220eedf
KD
426/*
427 * mmc_wait_data_done() - done callback for data request
428 * @mrq: done data request
429 *
430 * Wakes up mmc context, passed as a callback to host controller driver
431 */
432static void mmc_wait_data_done(struct mmc_request *mrq)
433{
71f8a4b8
JF
434 struct mmc_context_info *context_info = &mrq->host->context_info;
435
436 context_info->is_done_rcv = true;
437 wake_up_interruptible(&context_info->wait);
2220eedf
KD
438}
439
1da177e4
LT
440static void mmc_wait_done(struct mmc_request *mrq)
441{
aa8b683a
PF
442 complete(&mrq->completion);
443}
444
5163af5a
AH
445static inline void mmc_wait_ongoing_tfr_cmd(struct mmc_host *host)
446{
447 struct mmc_request *ongoing_mrq = READ_ONCE(host->ongoing_mrq);
448
449 /*
450 * If there is an ongoing transfer, wait for the command line to become
451 * available.
452 */
453 if (ongoing_mrq && !completion_done(&ongoing_mrq->cmd_completion))
454 wait_for_completion(&ongoing_mrq->cmd_completion);
455}
456
2220eedf
KD
457/*
458 *__mmc_start_data_req() - starts data request
459 * @host: MMC host to start the request
460 * @mrq: data request to start
461 *
462 * Sets the done callback to be called when request is completed by the card.
463 * Starts data mmc request execution
5163af5a
AH
464 * If an ongoing transfer is already in progress, wait for the command line
465 * to become available before sending another command.
2220eedf
KD
466 */
467static int __mmc_start_data_req(struct mmc_host *host, struct mmc_request *mrq)
468{
f100c1c2
AH
469 int err;
470
5163af5a
AH
471 mmc_wait_ongoing_tfr_cmd(host);
472
2220eedf
KD
473 mrq->done = mmc_wait_data_done;
474 mrq->host = host;
f100c1c2 475
5163af5a
AH
476 init_completion(&mrq->cmd_completion);
477
f100c1c2
AH
478 err = mmc_start_request(host, mrq);
479 if (err) {
480 mrq->cmd->error = err;
5163af5a 481 mmc_complete_cmd(mrq);
9b844961 482 mmc_wait_data_done(mrq);
2220eedf 483 }
2220eedf 484
f100c1c2 485 return err;
2220eedf
KD
486}
487
956d9fd5 488static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq)
aa8b683a 489{
f100c1c2
AH
490 int err;
491
5163af5a
AH
492 mmc_wait_ongoing_tfr_cmd(host);
493
aa8b683a
PF
494 init_completion(&mrq->completion);
495 mrq->done = mmc_wait_done;
f100c1c2 496
5163af5a
AH
497 init_completion(&mrq->cmd_completion);
498
f100c1c2
AH
499 err = mmc_start_request(host, mrq);
500 if (err) {
501 mrq->cmd->error = err;
5163af5a 502 mmc_complete_cmd(mrq);
d3049504 503 complete(&mrq->completion);
d3049504 504 }
f100c1c2
AH
505
506 return err;
aa8b683a
PF
507}
508
5163af5a 509void mmc_wait_for_req_done(struct mmc_host *host, struct mmc_request *mrq)
aa8b683a 510{
08a7e1df
AH
511 struct mmc_command *cmd;
512
513 while (1) {
514 wait_for_completion(&mrq->completion);
515
516 cmd = mrq->cmd;
775a9362
ME
517
518 /*
519 * If host has timed out waiting for the sanitize
520 * to complete, card might be still in programming state
521 * so let's try to bring the card out of programming
522 * state.
523 */
524 if (cmd->sanitize_busy && cmd->error == -ETIMEDOUT) {
525 if (!mmc_interrupt_hpi(host->card)) {
6606110d
JP
526 pr_warn("%s: %s: Interrupted sanitize\n",
527 mmc_hostname(host), __func__);
775a9362
ME
528 cmd->error = 0;
529 break;
530 } else {
531 pr_err("%s: %s: Failed to interrupt sanitize\n",
532 mmc_hostname(host), __func__);
533 }
534 }
d3049504
AH
535 if (!cmd->error || !cmd->retries ||
536 mmc_card_removed(host->card))
08a7e1df
AH
537 break;
538
90a81489
AH
539 mmc_retune_recheck(host);
540
08a7e1df
AH
541 pr_debug("%s: req failed (CMD%u): %d, retrying...\n",
542 mmc_hostname(host), cmd->opcode, cmd->error);
543 cmd->retries--;
544 cmd->error = 0;
90a81489 545 __mmc_start_request(host, mrq);
08a7e1df 546 }
90a81489
AH
547
548 mmc_retune_release(host);
aa8b683a 549}
5163af5a
AH
550EXPORT_SYMBOL(mmc_wait_for_req_done);
551
552/**
553 * mmc_is_req_done - Determine if a 'cap_cmd_during_tfr' request is done
554 * @host: MMC host
555 * @mrq: MMC request
556 *
557 * mmc_is_req_done() is used with requests that have
558 * mrq->cap_cmd_during_tfr = true. mmc_is_req_done() must be called after
559 * starting a request and before waiting for it to complete. That is,
560 * either in between calls to mmc_start_req(), or after mmc_wait_for_req()
561 * and before mmc_wait_for_req_done(). If it is called at other times the
562 * result is not meaningful.
563 */
564bool mmc_is_req_done(struct mmc_host *host, struct mmc_request *mrq)
565{
566 if (host->areq)
567 return host->context_info.is_done_rcv;
568 else
569 return completion_done(&mrq->completion);
570}
571EXPORT_SYMBOL(mmc_is_req_done);
aa8b683a
PF
572
573/**
574 * mmc_pre_req - Prepare for a new request
575 * @host: MMC host to prepare command
576 * @mrq: MMC request to prepare for
aa8b683a
PF
577 *
578 * mmc_pre_req() is called in prior to mmc_start_req() to let
579 * host prepare for the new request. Preparation of a request may be
580 * performed while another request is running on the host.
581 */
d3c6aac3 582static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq)
aa8b683a 583{
9eadcc05 584 if (host->ops->pre_req)
d3c6aac3 585 host->ops->pre_req(host, mrq);
aa8b683a
PF
586}
587
588/**
589 * mmc_post_req - Post process a completed request
590 * @host: MMC host to post process command
591 * @mrq: MMC request to post process for
592 * @err: Error, if non zero, clean up any resources made in pre_req
593 *
594 * Let the host post process a completed request. Post processing of
595 * a request may be performed while another reuqest is running.
596 */
597static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq,
598 int err)
599{
9eadcc05 600 if (host->ops->post_req)
aa8b683a 601 host->ops->post_req(host, mrq, err);
1da177e4
LT
602}
603
37dac068
LW
604/**
605 * mmc_finalize_areq() - finalize an asynchronous request
606 * @host: MMC host to finalize any ongoing request on
607 *
608 * Returns the status of the ongoing asynchronous request, but
609 * MMC_BLK_SUCCESS if no request was going on.
610 */
611static enum mmc_blk_status mmc_finalize_areq(struct mmc_host *host)
612{
0e72f95b 613 struct mmc_context_info *context_info = &host->context_info;
37dac068
LW
614 enum mmc_blk_status status;
615
616 if (!host->areq)
617 return MMC_BLK_SUCCESS;
618
0e72f95b
LW
619 while (1) {
620 wait_event_interruptible(context_info->wait,
621 (context_info->is_done_rcv ||
622 context_info->is_new_req));
623
624 if (context_info->is_done_rcv) {
625 struct mmc_command *cmd;
626
627 context_info->is_done_rcv = false;
628 cmd = host->areq->mrq->cmd;
629
630 if (!cmd->error || !cmd->retries ||
631 mmc_card_removed(host->card)) {
632 status = host->areq->err_check(host->card,
633 host->areq);
634 break; /* return status */
635 } else {
636 mmc_retune_recheck(host);
637 pr_info("%s: req failed (CMD%u): %d, retrying...\n",
638 mmc_hostname(host),
639 cmd->opcode, cmd->error);
640 cmd->retries--;
641 cmd->error = 0;
642 __mmc_start_request(host, host->areq->mrq);
643 continue; /* wait for done/new event again */
644 }
645 }
646
647 return MMC_BLK_NEW_REQUEST;
648 }
649
650 mmc_retune_release(host);
37dac068
LW
651
652 /*
653 * Check BKOPS urgency for each R1 response
654 */
655 if (host->card && mmc_card_mmc(host->card) &&
656 ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) ||
657 (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) &&
658 (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT)) {
659 mmc_start_bkops(host->card, true);
660 }
661
662 return status;
663}
664
aa8b683a 665/**
c3399ef5 666 * mmc_start_areq - start an asynchronous request
aa8b683a 667 * @host: MMC host to start command
c3399ef5
LW
668 * @areq: asynchronous request to start
669 * @ret_stat: out parameter for status
aa8b683a
PF
670 *
671 * Start a new MMC custom command request for a host.
672 * If there is on ongoing async request wait for completion
673 * of that request and start the new one and return.
674 * Does not wait for the new request to complete.
675 *
676 * Returns the completed request, NULL in case of none completed.
677 * Wait for the an ongoing request (previoulsy started) to complete and
678 * return the completed request. If there is no ongoing request, NULL
679 * is returned without waiting. NULL is not an error condition.
680 */
c3399ef5
LW
681struct mmc_async_req *mmc_start_areq(struct mmc_host *host,
682 struct mmc_async_req *areq,
683 enum mmc_blk_status *ret_stat)
aa8b683a 684{
37dac068 685 enum mmc_blk_status status;
956d9fd5 686 int start_err = 0;
5744d50d 687 struct mmc_async_req *previous = host->areq;
aa8b683a
PF
688
689 /* Prepare a new request */
690 if (areq)
d3c6aac3 691 mmc_pre_req(host, areq->mrq);
aa8b683a 692
37dac068
LW
693 /* Finalize previous request */
694 status = mmc_finalize_areq(host);
5744d50d
LW
695 if (ret_stat)
696 *ret_stat = status;
37dac068
LW
697
698 /* The previous request is still going on... */
5744d50d 699 if (status == MMC_BLK_NEW_REQUEST)
37dac068 700 return NULL;
aa8b683a 701
37dac068 702 /* Fine so far, start the new request! */
8e8b3f51 703 if (status == MMC_BLK_SUCCESS && areq)
2220eedf 704 start_err = __mmc_start_data_req(host, areq->mrq);
aa8b683a 705
37dac068 706 /* Postprocess the old request at this point */
aa8b683a
PF
707 if (host->areq)
708 mmc_post_req(host, host->areq->mrq, 0);
709
37dac068 710 /* Cancel a prepared request if it was not started. */
8e8b3f51 711 if ((status != MMC_BLK_SUCCESS || start_err) && areq)
f5c2758f 712 mmc_post_req(host, areq->mrq, -EINVAL);
956d9fd5 713
8e8b3f51 714 if (status != MMC_BLK_SUCCESS)
956d9fd5
UH
715 host->areq = NULL;
716 else
717 host->areq = areq;
718
5744d50d 719 return previous;
aa8b683a 720}
c3399ef5 721EXPORT_SYMBOL(mmc_start_areq);
aa8b683a 722
67a61c48
PO
723/**
724 * mmc_wait_for_req - start a request and wait for completion
725 * @host: MMC host to start command
726 * @mrq: MMC request to start
727 *
728 * Start a new MMC custom command request for a host, and wait
5163af5a
AH
729 * for the command to complete. In the case of 'cap_cmd_during_tfr'
730 * requests, the transfer is ongoing and the caller can issue further
731 * commands that do not use the data lines, and then wait by calling
732 * mmc_wait_for_req_done().
733 * Does not attempt to parse the response.
67a61c48
PO
734 */
735void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
1da177e4 736{
aa8b683a 737 __mmc_start_req(host, mrq);
5163af5a
AH
738
739 if (!mrq->cap_cmd_during_tfr)
740 mmc_wait_for_req_done(host, mrq);
1da177e4 741}
1da177e4
LT
742EXPORT_SYMBOL(mmc_wait_for_req);
743
eb0d8f13
JC
744/**
745 * mmc_interrupt_hpi - Issue for High priority Interrupt
746 * @card: the MMC card associated with the HPI transfer
747 *
748 * Issued High Priority Interrupt, and check for card status
950d56ac 749 * until out-of prg-state.
eb0d8f13
JC
750 */
751int mmc_interrupt_hpi(struct mmc_card *card)
752{
753 int err;
754 u32 status;
6af9e96e 755 unsigned long prg_wait;
eb0d8f13 756
eb0d8f13
JC
757 if (!card->ext_csd.hpi_en) {
758 pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host));
759 return 1;
760 }
761
762 mmc_claim_host(card->host);
763 err = mmc_send_status(card, &status);
764 if (err) {
765 pr_err("%s: Get card status fail\n", mmc_hostname(card->host));
766 goto out;
767 }
768
6af9e96e
V
769 switch (R1_CURRENT_STATE(status)) {
770 case R1_STATE_IDLE:
771 case R1_STATE_READY:
772 case R1_STATE_STBY:
211d4fe5 773 case R1_STATE_TRAN:
6af9e96e 774 /*
211d4fe5 775 * In idle and transfer states, HPI is not needed and the caller
6af9e96e
V
776 * can issue the next intended command immediately
777 */
778 goto out;
779 case R1_STATE_PRG:
780 break;
781 default:
782 /* In all other states, it's illegal to issue HPI */
783 pr_debug("%s: HPI cannot be sent. Card state=%d\n",
784 mmc_hostname(card->host), R1_CURRENT_STATE(status));
785 err = -EINVAL;
786 goto out;
787 }
788
789 err = mmc_send_hpi_cmd(card, &status);
790 if (err)
791 goto out;
792
793 prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time);
794 do {
795 err = mmc_send_status(card, &status);
796
797 if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN)
798 break;
799 if (time_after(jiffies, prg_wait))
800 err = -ETIMEDOUT;
801 } while (!err);
eb0d8f13
JC
802
803out:
804 mmc_release_host(card->host);
805 return err;
806}
807EXPORT_SYMBOL(mmc_interrupt_hpi);
808
1da177e4
LT
809/**
810 * mmc_wait_for_cmd - start a command and wait for completion
811 * @host: MMC host to start command
812 * @cmd: MMC command to start
813 * @retries: maximum number of retries
814 *
815 * Start a new MMC command for a host, and wait for the command
816 * to complete. Return any error that occurred while the command
817 * was executing. Do not attempt to parse the response.
818 */
819int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries)
820{
c7836d15 821 struct mmc_request mrq = {};
1da177e4 822
d84075c8 823 WARN_ON(!host->claimed);
1da177e4 824
1da177e4
LT
825 memset(cmd->resp, 0, sizeof(cmd->resp));
826 cmd->retries = retries;
827
828 mrq.cmd = cmd;
829 cmd->data = NULL;
830
831 mmc_wait_for_req(host, &mrq);
832
833 return cmd->error;
834}
835
836EXPORT_SYMBOL(mmc_wait_for_cmd);
837
950d56ac
JC
838/**
839 * mmc_stop_bkops - stop ongoing BKOPS
840 * @card: MMC card to check BKOPS
841 *
842 * Send HPI command to stop ongoing background operations to
843 * allow rapid servicing of foreground operations, e.g. read/
844 * writes. Wait until the card comes out of the programming state
845 * to avoid errors in servicing read/write requests.
846 */
847int mmc_stop_bkops(struct mmc_card *card)
848{
849 int err = 0;
850
950d56ac
JC
851 err = mmc_interrupt_hpi(card);
852
853 /*
854 * If err is EINVAL, we can't issue an HPI.
855 * It should complete the BKOPS.
856 */
857 if (!err || (err == -EINVAL)) {
858 mmc_card_clr_doing_bkops(card);
66073d86 859 mmc_retune_release(card->host);
950d56ac
JC
860 err = 0;
861 }
862
863 return err;
864}
865EXPORT_SYMBOL(mmc_stop_bkops);
866
867int mmc_read_bkops_status(struct mmc_card *card)
868{
869 int err;
870 u8 *ext_csd;
871
950d56ac 872 mmc_claim_host(card->host);
b2cada73 873 err = mmc_get_ext_csd(card, &ext_csd);
950d56ac
JC
874 mmc_release_host(card->host);
875 if (err)
b2cada73 876 return err;
950d56ac
JC
877
878 card->ext_csd.raw_bkops_status = ext_csd[EXT_CSD_BKOPS_STATUS];
879 card->ext_csd.raw_exception_status = ext_csd[EXT_CSD_EXP_EVENTS_STATUS];
950d56ac 880 kfree(ext_csd);
b2cada73 881 return 0;
950d56ac
JC
882}
883EXPORT_SYMBOL(mmc_read_bkops_status);
884
d773d725
RK
885/**
886 * mmc_set_data_timeout - set the timeout for a data command
887 * @data: data phase for command
888 * @card: the MMC card associated with the data transfer
67a61c48
PO
889 *
890 * Computes the data timeout parameters according to the
891 * correct algorithm given the card type.
d773d725 892 */
b146d26a 893void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card)
d773d725
RK
894{
895 unsigned int mult;
896
e6f918bf
PO
897 /*
898 * SDIO cards only define an upper 1 s limit on access.
899 */
900 if (mmc_card_sdio(card)) {
901 data->timeout_ns = 1000000000;
902 data->timeout_clks = 0;
903 return;
904 }
905
d773d725
RK
906 /*
907 * SD cards use a 100 multiplier rather than 10
908 */
909 mult = mmc_card_sd(card) ? 100 : 10;
910
911 /*
912 * Scale up the multiplier (and therefore the timeout) by
913 * the r2w factor for writes.
914 */
b146d26a 915 if (data->flags & MMC_DATA_WRITE)
d773d725
RK
916 mult <<= card->csd.r2w_factor;
917
918 data->timeout_ns = card->csd.tacc_ns * mult;
919 data->timeout_clks = card->csd.tacc_clks * mult;
920
921 /*
922 * SD cards also have an upper limit on the timeout.
923 */
924 if (mmc_card_sd(card)) {
925 unsigned int timeout_us, limit_us;
926
927 timeout_us = data->timeout_ns / 1000;
9eadcc05 928 if (card->host->ios.clock)
e9b86841 929 timeout_us += data->timeout_clks * 1000 /
9eadcc05 930 (card->host->ios.clock / 1000);
d773d725 931
b146d26a 932 if (data->flags & MMC_DATA_WRITE)
493890e7 933 /*
3bdc9ba8
PW
934 * The MMC spec "It is strongly recommended
935 * for hosts to implement more than 500ms
936 * timeout value even if the card indicates
937 * the 250ms maximum busy length." Even the
938 * previous value of 300ms is known to be
939 * insufficient for some cards.
493890e7 940 */
3bdc9ba8 941 limit_us = 3000000;
d773d725
RK
942 else
943 limit_us = 100000;
944
fba68bd2
PL
945 /*
946 * SDHC cards always use these fixed values.
947 */
948 if (timeout_us > limit_us || mmc_card_blockaddr(card)) {
d773d725
RK
949 data->timeout_ns = limit_us * 1000;
950 data->timeout_clks = 0;
951 }
f7bf11a3
SW
952
953 /* assign limit value if invalid */
954 if (timeout_us == 0)
955 data->timeout_ns = limit_us * 1000;
d773d725 956 }
6de5fc9c
SNX
957
958 /*
959 * Some cards require longer data read timeout than indicated in CSD.
960 * Address this by setting the read timeout to a "reasonably high"
32ecd320 961 * value. For the cards tested, 600ms has proven enough. If necessary,
6de5fc9c
SNX
962 * this value can be increased if other problematic cards require this.
963 */
964 if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) {
32ecd320 965 data->timeout_ns = 600000000;
6de5fc9c
SNX
966 data->timeout_clks = 0;
967 }
968
c0c88871
WM
969 /*
970 * Some cards need very high timeouts if driven in SPI mode.
971 * The worst observed timeout was 900ms after writing a
972 * continuous stream of data until the internal logic
973 * overflowed.
974 */
975 if (mmc_host_is_spi(card->host)) {
976 if (data->flags & MMC_DATA_WRITE) {
977 if (data->timeout_ns < 1000000000)
978 data->timeout_ns = 1000000000; /* 1s */
979 } else {
980 if (data->timeout_ns < 100000000)
981 data->timeout_ns = 100000000; /* 100ms */
982 }
983 }
d773d725
RK
984}
985EXPORT_SYMBOL(mmc_set_data_timeout);
986
ad3868b2
PO
987/**
988 * mmc_align_data_size - pads a transfer size to a more optimal value
989 * @card: the MMC card associated with the data transfer
990 * @sz: original transfer size
991 *
992 * Pads the original data size with a number of extra bytes in
993 * order to avoid controller bugs and/or performance hits
994 * (e.g. some controllers revert to PIO for certain sizes).
995 *
996 * Returns the improved size, which might be unmodified.
997 *
998 * Note that this function is only relevant when issuing a
999 * single scatter gather entry.
1000 */
1001unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz)
1002{
1003 /*
1004 * FIXME: We don't have a system for the controller to tell
1005 * the core about its problems yet, so for now we just 32-bit
1006 * align the size.
1007 */
1008 sz = ((sz + 3) / 4) * 4;
1009
1010 return sz;
1011}
1012EXPORT_SYMBOL(mmc_align_data_size);
1013
1da177e4 1014/**
2342f332 1015 * __mmc_claim_host - exclusively claim a host
1da177e4 1016 * @host: mmc host to claim
2342f332 1017 * @abort: whether or not the operation should be aborted
1da177e4 1018 *
2342f332
NP
1019 * Claim a host for a set of operations. If @abort is non null and
1020 * dereference a non-zero value then this will return prematurely with
1021 * that non-zero value without acquiring the lock. Returns zero
1022 * with the lock held otherwise.
1da177e4 1023 */
2342f332 1024int __mmc_claim_host(struct mmc_host *host, atomic_t *abort)
1da177e4
LT
1025{
1026 DECLARE_WAITQUEUE(wait, current);
1027 unsigned long flags;
2342f332 1028 int stop;
9250aea7 1029 bool pm = false;
1da177e4 1030
cf795bfb
PO
1031 might_sleep();
1032
1da177e4
LT
1033 add_wait_queue(&host->wq, &wait);
1034 spin_lock_irqsave(&host->lock, flags);
1035 while (1) {
1036 set_current_state(TASK_UNINTERRUPTIBLE);
2342f332 1037 stop = abort ? atomic_read(abort) : 0;
319a3f14 1038 if (stop || !host->claimed || host->claimer == current)
1da177e4
LT
1039 break;
1040 spin_unlock_irqrestore(&host->lock, flags);
1041 schedule();
1042 spin_lock_irqsave(&host->lock, flags);
1043 }
1044 set_current_state(TASK_RUNNING);
319a3f14 1045 if (!stop) {
2342f332 1046 host->claimed = 1;
319a3f14
AH
1047 host->claimer = current;
1048 host->claim_cnt += 1;
9250aea7
UH
1049 if (host->claim_cnt == 1)
1050 pm = true;
319a3f14 1051 } else
2342f332 1052 wake_up(&host->wq);
1da177e4
LT
1053 spin_unlock_irqrestore(&host->lock, flags);
1054 remove_wait_queue(&host->wq, &wait);
9250aea7
UH
1055
1056 if (pm)
1057 pm_runtime_get_sync(mmc_dev(host));
1058
2342f332 1059 return stop;
1da177e4 1060}
2342f332 1061EXPORT_SYMBOL(__mmc_claim_host);
8ea926b2 1062
ab1efd27 1063/**
907d2e7c 1064 * mmc_release_host - release a host
ab1efd27
UH
1065 * @host: mmc host to release
1066 *
907d2e7c
AH
1067 * Release a MMC host, allowing others to claim the host
1068 * for their operations.
ab1efd27 1069 */
907d2e7c 1070void mmc_release_host(struct mmc_host *host)
8ea926b2
AH
1071{
1072 unsigned long flags;
1073
907d2e7c
AH
1074 WARN_ON(!host->claimed);
1075
8ea926b2 1076 spin_lock_irqsave(&host->lock, flags);
319a3f14
AH
1077 if (--host->claim_cnt) {
1078 /* Release for nested claim */
1079 spin_unlock_irqrestore(&host->lock, flags);
1080 } else {
1081 host->claimed = 0;
1082 host->claimer = NULL;
1083 spin_unlock_irqrestore(&host->lock, flags);
1084 wake_up(&host->wq);
9250aea7
UH
1085 pm_runtime_mark_last_busy(mmc_dev(host));
1086 pm_runtime_put_autosuspend(mmc_dev(host));
319a3f14 1087 }
8ea926b2 1088}
1da177e4
LT
1089EXPORT_SYMBOL(mmc_release_host);
1090
e94cfef6
UH
1091/*
1092 * This is a helper function, which fetches a runtime pm reference for the
1093 * card device and also claims the host.
1094 */
1095void mmc_get_card(struct mmc_card *card)
1096{
1097 pm_runtime_get_sync(&card->dev);
1098 mmc_claim_host(card->host);
1099}
1100EXPORT_SYMBOL(mmc_get_card);
1101
1102/*
1103 * This is a helper function, which releases the host and drops the runtime
1104 * pm reference for the card device.
1105 */
1106void mmc_put_card(struct mmc_card *card)
1107{
1108 mmc_release_host(card->host);
1109 pm_runtime_mark_last_busy(&card->dev);
1110 pm_runtime_put_autosuspend(&card->dev);
1111}
1112EXPORT_SYMBOL(mmc_put_card);
1113
7ea239d9
PO
1114/*
1115 * Internal function that does the actual ios call to the host driver,
1116 * optionally printing some debug output.
1117 */
920e70c5
RK
1118static inline void mmc_set_ios(struct mmc_host *host)
1119{
1120 struct mmc_ios *ios = &host->ios;
1121
cd9277c0
PO
1122 pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u "
1123 "width %u timing %u\n",
920e70c5
RK
1124 mmc_hostname(host), ios->clock, ios->bus_mode,
1125 ios->power_mode, ios->chip_select, ios->vdd,
ed9feec7 1126 1 << ios->bus_width, ios->timing);
fba68bd2 1127
920e70c5
RK
1128 host->ops->set_ios(host, ios);
1129}
1130
7ea239d9
PO
1131/*
1132 * Control chip select pin on a host.
1133 */
da7fbe58 1134void mmc_set_chip_select(struct mmc_host *host, int mode)
1da177e4 1135{
da7fbe58
PO
1136 host->ios.chip_select = mode;
1137 mmc_set_ios(host);
1da177e4
LT
1138}
1139
7ea239d9
PO
1140/*
1141 * Sets the host clock to the highest possible frequency that
1142 * is below "hz".
1143 */
9eadcc05 1144void mmc_set_clock(struct mmc_host *host, unsigned int hz)
7ea239d9 1145{
6a98f1e8 1146 WARN_ON(hz && hz < host->f_min);
7ea239d9
PO
1147
1148 if (hz > host->f_max)
1149 hz = host->f_max;
1150
1151 host->ios.clock = hz;
1152 mmc_set_ios(host);
1153}
1154
63e415c6
AH
1155int mmc_execute_tuning(struct mmc_card *card)
1156{
1157 struct mmc_host *host = card->host;
1158 u32 opcode;
1159 int err;
1160
1161 if (!host->ops->execute_tuning)
1162 return 0;
1163
1164 if (mmc_card_mmc(card))
1165 opcode = MMC_SEND_TUNING_BLOCK_HS200;
1166 else
1167 opcode = MMC_SEND_TUNING_BLOCK;
1168
63e415c6 1169 err = host->ops->execute_tuning(host, opcode);
63e415c6
AH
1170
1171 if (err)
07d97d87
RK
1172 pr_err("%s: tuning execution failed: %d\n",
1173 mmc_hostname(host), err);
79d5a65a
AH
1174 else
1175 mmc_retune_enable(host);
63e415c6
AH
1176
1177 return err;
1178}
1179
7ea239d9
PO
1180/*
1181 * Change the bus mode (open drain/push-pull) of a host.
1182 */
1183void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode)
1184{
1185 host->ios.bus_mode = mode;
1186 mmc_set_ios(host);
1187}
1188
0f8d8ea6
AH
1189/*
1190 * Change data bus width of a host.
1191 */
1192void mmc_set_bus_width(struct mmc_host *host, unsigned int width)
1193{
4c4cb171
PR
1194 host->ios.bus_width = width;
1195 mmc_set_ios(host);
0f8d8ea6
AH
1196}
1197
2d079c43
JR
1198/*
1199 * Set initial state after a power cycle or a hw_reset.
1200 */
1201void mmc_set_initial_state(struct mmc_host *host)
1202{
79d5a65a
AH
1203 mmc_retune_disable(host);
1204
2d079c43
JR
1205 if (mmc_host_is_spi(host))
1206 host->ios.chip_select = MMC_CS_HIGH;
1207 else
1208 host->ios.chip_select = MMC_CS_DONTCARE;
1209 host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
1210 host->ios.bus_width = MMC_BUS_WIDTH_1;
1211 host->ios.timing = MMC_TIMING_LEGACY;
75e8a228 1212 host->ios.drv_type = 0;
81ac2af6
SL
1213 host->ios.enhanced_strobe = false;
1214
1215 /*
1216 * Make sure we are in non-enhanced strobe mode before we
1217 * actually enable it in ext_csd.
1218 */
1219 if ((host->caps2 & MMC_CAP2_HS400_ES) &&
1220 host->ops->hs400_enhanced_strobe)
1221 host->ops->hs400_enhanced_strobe(host, &host->ios);
2d079c43
JR
1222
1223 mmc_set_ios(host);
1224}
1225
86e8286a
AV
1226/**
1227 * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number
1228 * @vdd: voltage (mV)
1229 * @low_bits: prefer low bits in boundary cases
1230 *
1231 * This function returns the OCR bit number according to the provided @vdd
1232 * value. If conversion is not possible a negative errno value returned.
1233 *
1234 * Depending on the @low_bits flag the function prefers low or high OCR bits
1235 * on boundary voltages. For example,
1236 * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33);
1237 * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34);
1238 *
1239 * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21).
1240 */
1241static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits)
1242{
1243 const int max_bit = ilog2(MMC_VDD_35_36);
1244 int bit;
1245
1246 if (vdd < 1650 || vdd > 3600)
1247 return -EINVAL;
1248
1249 if (vdd >= 1650 && vdd <= 1950)
1250 return ilog2(MMC_VDD_165_195);
1251
1252 if (low_bits)
1253 vdd -= 1;
1254
1255 /* Base 2000 mV, step 100 mV, bit's base 8. */
1256 bit = (vdd - 2000) / 100 + 8;
1257 if (bit > max_bit)
1258 return max_bit;
1259 return bit;
1260}
1261
1262/**
1263 * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask
1264 * @vdd_min: minimum voltage value (mV)
1265 * @vdd_max: maximum voltage value (mV)
1266 *
1267 * This function returns the OCR mask bits according to the provided @vdd_min
1268 * and @vdd_max values. If conversion is not possible the function returns 0.
1269 *
1270 * Notes wrt boundary cases:
1271 * This function sets the OCR bits for all boundary voltages, for example
1272 * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 |
1273 * MMC_VDD_34_35 mask.
1274 */
1275u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max)
1276{
1277 u32 mask = 0;
1278
1279 if (vdd_max < vdd_min)
1280 return 0;
1281
1282 /* Prefer high bits for the boundary vdd_max values. */
1283 vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false);
1284 if (vdd_max < 0)
1285 return 0;
1286
1287 /* Prefer low bits for the boundary vdd_min values. */
1288 vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true);
1289 if (vdd_min < 0)
1290 return 0;
1291
1292 /* Fill the mask, from max bit to min bit. */
1293 while (vdd_max >= vdd_min)
1294 mask |= 1 << vdd_max--;
1295
1296 return mask;
1297}
1298EXPORT_SYMBOL(mmc_vddrange_to_ocrmask);
1299
6e9e318b
HZ
1300#ifdef CONFIG_OF
1301
1302/**
1303 * mmc_of_parse_voltage - return mask of supported voltages
1304 * @np: The device node need to be parsed.
1305 * @mask: mask of voltages available for MMC/SD/SDIO
1306 *
cf925747
RK
1307 * Parse the "voltage-ranges" DT property, returning zero if it is not
1308 * found, negative errno if the voltage-range specification is invalid,
1309 * or one if the voltage-range is specified and successfully parsed.
6e9e318b
HZ
1310 */
1311int mmc_of_parse_voltage(struct device_node *np, u32 *mask)
1312{
1313 const u32 *voltage_ranges;
1314 int num_ranges, i;
1315
1316 voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges);
1317 num_ranges = num_ranges / sizeof(*voltage_ranges) / 2;
10a16a01
RK
1318 if (!voltage_ranges) {
1319 pr_debug("%s: voltage-ranges unspecified\n", np->full_name);
cf925747 1320 return 0;
10a16a01
RK
1321 }
1322 if (!num_ranges) {
1323 pr_err("%s: voltage-ranges empty\n", np->full_name);
6e9e318b
HZ
1324 return -EINVAL;
1325 }
1326
1327 for (i = 0; i < num_ranges; i++) {
1328 const int j = i * 2;
1329 u32 ocr_mask;
1330
1331 ocr_mask = mmc_vddrange_to_ocrmask(
1332 be32_to_cpu(voltage_ranges[j]),
1333 be32_to_cpu(voltage_ranges[j + 1]));
1334 if (!ocr_mask) {
1335 pr_err("%s: voltage-range #%d is invalid\n",
1336 np->full_name, i);
1337 return -EINVAL;
1338 }
1339 *mask |= ocr_mask;
1340 }
1341
cf925747 1342 return 1;
6e9e318b
HZ
1343}
1344EXPORT_SYMBOL(mmc_of_parse_voltage);
1345
1346#endif /* CONFIG_OF */
1347
25185f3f
SH
1348static int mmc_of_get_func_num(struct device_node *node)
1349{
1350 u32 reg;
1351 int ret;
1352
1353 ret = of_property_read_u32(node, "reg", &reg);
1354 if (ret < 0)
1355 return ret;
1356
1357 return reg;
1358}
1359
1360struct device_node *mmc_of_find_child_device(struct mmc_host *host,
1361 unsigned func_num)
1362{
1363 struct device_node *node;
1364
1365 if (!host->parent || !host->parent->of_node)
1366 return NULL;
1367
1368 for_each_child_of_node(host->parent->of_node, node) {
1369 if (mmc_of_get_func_num(node) == func_num)
1370 return node;
1371 }
1372
1373 return NULL;
1374}
1375
5c13941a
DB
1376#ifdef CONFIG_REGULATOR
1377
310c805e
HS
1378/**
1379 * mmc_ocrbitnum_to_vdd - Convert a OCR bit number to its voltage
1380 * @vdd_bit: OCR bit number
1381 * @min_uV: minimum voltage value (mV)
1382 * @max_uV: maximum voltage value (mV)
1383 *
1384 * This function returns the voltage range according to the provided OCR
1385 * bit number. If conversion is not possible a negative errno value returned.
1386 */
1387static int mmc_ocrbitnum_to_vdd(int vdd_bit, int *min_uV, int *max_uV)
1388{
1389 int tmp;
1390
1391 if (!vdd_bit)
1392 return -EINVAL;
1393
1394 /*
1395 * REVISIT mmc_vddrange_to_ocrmask() may have set some
1396 * bits this regulator doesn't quite support ... don't
1397 * be too picky, most cards and regulators are OK with
1398 * a 0.1V range goof (it's a small error percentage).
1399 */
1400 tmp = vdd_bit - ilog2(MMC_VDD_165_195);
1401 if (tmp == 0) {
1402 *min_uV = 1650 * 1000;
1403 *max_uV = 1950 * 1000;
1404 } else {
1405 *min_uV = 1900 * 1000 + tmp * 100 * 1000;
1406 *max_uV = *min_uV + 100 * 1000;
1407 }
1408
1409 return 0;
1410}
1411
5c13941a
DB
1412/**
1413 * mmc_regulator_get_ocrmask - return mask of supported voltages
1414 * @supply: regulator to use
1415 *
1416 * This returns either a negative errno, or a mask of voltages that
1417 * can be provided to MMC/SD/SDIO devices using the specified voltage
1418 * regulator. This would normally be called before registering the
1419 * MMC host adapter.
1420 */
1421int mmc_regulator_get_ocrmask(struct regulator *supply)
1422{
1423 int result = 0;
1424 int count;
1425 int i;
9ed7ca89
JMC
1426 int vdd_uV;
1427 int vdd_mV;
5c13941a
DB
1428
1429 count = regulator_count_voltages(supply);
1430 if (count < 0)
1431 return count;
1432
1433 for (i = 0; i < count; i++) {
5c13941a
DB
1434 vdd_uV = regulator_list_voltage(supply, i);
1435 if (vdd_uV <= 0)
1436 continue;
1437
1438 vdd_mV = vdd_uV / 1000;
1439 result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1440 }
1441
9ed7ca89
JMC
1442 if (!result) {
1443 vdd_uV = regulator_get_voltage(supply);
1444 if (vdd_uV <= 0)
1445 return vdd_uV;
1446
1447 vdd_mV = vdd_uV / 1000;
1448 result = mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV);
1449 }
1450
5c13941a
DB
1451 return result;
1452}
45a6b32e 1453EXPORT_SYMBOL_GPL(mmc_regulator_get_ocrmask);
5c13941a
DB
1454
1455/**
1456 * mmc_regulator_set_ocr - set regulator to match host->ios voltage
99fc5131 1457 * @mmc: the host to regulate
5c13941a 1458 * @supply: regulator to use
99fc5131 1459 * @vdd_bit: zero for power off, else a bit number (host->ios.vdd)
5c13941a
DB
1460 *
1461 * Returns zero on success, else negative errno.
1462 *
1463 * MMC host drivers may use this to enable or disable a regulator using
1464 * a particular supply voltage. This would normally be called from the
1465 * set_ios() method.
1466 */
99fc5131
LW
1467int mmc_regulator_set_ocr(struct mmc_host *mmc,
1468 struct regulator *supply,
1469 unsigned short vdd_bit)
5c13941a
DB
1470{
1471 int result = 0;
1472 int min_uV, max_uV;
5c13941a
DB
1473
1474 if (vdd_bit) {
310c805e 1475 mmc_ocrbitnum_to_vdd(vdd_bit, &min_uV, &max_uV);
5c13941a 1476
ca6429d4 1477 result = regulator_set_voltage(supply, min_uV, max_uV);
99fc5131 1478 if (result == 0 && !mmc->regulator_enabled) {
5c13941a 1479 result = regulator_enable(supply);
99fc5131
LW
1480 if (!result)
1481 mmc->regulator_enabled = true;
1482 }
1483 } else if (mmc->regulator_enabled) {
5c13941a 1484 result = regulator_disable(supply);
99fc5131
LW
1485 if (result == 0)
1486 mmc->regulator_enabled = false;
5c13941a
DB
1487 }
1488
99fc5131
LW
1489 if (result)
1490 dev_err(mmc_dev(mmc),
1491 "could not set regulator OCR (%d)\n", result);
5c13941a
DB
1492 return result;
1493}
45a6b32e 1494EXPORT_SYMBOL_GPL(mmc_regulator_set_ocr);
5c13941a 1495
2086f801
DA
1496static int mmc_regulator_set_voltage_if_supported(struct regulator *regulator,
1497 int min_uV, int target_uV,
1498 int max_uV)
1499{
1500 /*
1501 * Check if supported first to avoid errors since we may try several
1502 * signal levels during power up and don't want to show errors.
1503 */
1504 if (!regulator_is_supported_voltage(regulator, min_uV, max_uV))
1505 return -EINVAL;
1506
1507 return regulator_set_voltage_triplet(regulator, min_uV, target_uV,
1508 max_uV);
1509}
1510
1511/**
1512 * mmc_regulator_set_vqmmc - Set VQMMC as per the ios
1513 *
1514 * For 3.3V signaling, we try to match VQMMC to VMMC as closely as possible.
1515 * That will match the behavior of old boards where VQMMC and VMMC were supplied
1516 * by the same supply. The Bus Operating conditions for 3.3V signaling in the
1517 * SD card spec also define VQMMC in terms of VMMC.
1518 * If this is not possible we'll try the full 2.7-3.6V of the spec.
1519 *
1520 * For 1.2V and 1.8V signaling we'll try to get as close as possible to the
1521 * requested voltage. This is definitely a good idea for UHS where there's a
1522 * separate regulator on the card that's trying to make 1.8V and it's best if
1523 * we match.
1524 *
1525 * This function is expected to be used by a controller's
1526 * start_signal_voltage_switch() function.
1527 */
1528int mmc_regulator_set_vqmmc(struct mmc_host *mmc, struct mmc_ios *ios)
1529{
1530 struct device *dev = mmc_dev(mmc);
1531 int ret, volt, min_uV, max_uV;
1532
1533 /* If no vqmmc supply then we can't change the voltage */
1534 if (IS_ERR(mmc->supply.vqmmc))
1535 return -EINVAL;
1536
1537 switch (ios->signal_voltage) {
1538 case MMC_SIGNAL_VOLTAGE_120:
1539 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1540 1100000, 1200000, 1300000);
1541 case MMC_SIGNAL_VOLTAGE_180:
1542 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1543 1700000, 1800000, 1950000);
1544 case MMC_SIGNAL_VOLTAGE_330:
1545 ret = mmc_ocrbitnum_to_vdd(mmc->ios.vdd, &volt, &max_uV);
1546 if (ret < 0)
1547 return ret;
1548
1549 dev_dbg(dev, "%s: found vmmc voltage range of %d-%duV\n",
1550 __func__, volt, max_uV);
1551
1552 min_uV = max(volt - 300000, 2700000);
1553 max_uV = min(max_uV + 200000, 3600000);
1554
1555 /*
1556 * Due to a limitation in the current implementation of
1557 * regulator_set_voltage_triplet() which is taking the lowest
1558 * voltage possible if below the target, search for a suitable
1559 * voltage in two steps and try to stay close to vmmc
1560 * with a 0.3V tolerance at first.
1561 */
1562 if (!mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1563 min_uV, volt, max_uV))
1564 return 0;
1565
1566 return mmc_regulator_set_voltage_if_supported(mmc->supply.vqmmc,
1567 2700000, volt, 3600000);
1568 default:
1569 return -EINVAL;
1570 }
1571}
1572EXPORT_SYMBOL_GPL(mmc_regulator_set_vqmmc);
1573
4d1f52f9
TK
1574#endif /* CONFIG_REGULATOR */
1575
e137788d
GL
1576int mmc_regulator_get_supply(struct mmc_host *mmc)
1577{
1578 struct device *dev = mmc_dev(mmc);
e137788d
GL
1579 int ret;
1580
4d1f52f9 1581 mmc->supply.vmmc = devm_regulator_get_optional(dev, "vmmc");
bc35d5ed 1582 mmc->supply.vqmmc = devm_regulator_get_optional(dev, "vqmmc");
e137788d 1583
4d1f52f9
TK
1584 if (IS_ERR(mmc->supply.vmmc)) {
1585 if (PTR_ERR(mmc->supply.vmmc) == -EPROBE_DEFER)
1586 return -EPROBE_DEFER;
6e1bbc51 1587 dev_dbg(dev, "No vmmc regulator found\n");
4d1f52f9
TK
1588 } else {
1589 ret = mmc_regulator_get_ocrmask(mmc->supply.vmmc);
1590 if (ret > 0)
1591 mmc->ocr_avail = ret;
1592 else
1593 dev_warn(dev, "Failed getting OCR mask: %d\n", ret);
1594 }
e137788d 1595
4d1f52f9
TK
1596 if (IS_ERR(mmc->supply.vqmmc)) {
1597 if (PTR_ERR(mmc->supply.vqmmc) == -EPROBE_DEFER)
1598 return -EPROBE_DEFER;
6e1bbc51 1599 dev_dbg(dev, "No vqmmc regulator found\n");
4d1f52f9 1600 }
e137788d
GL
1601
1602 return 0;
1603}
1604EXPORT_SYMBOL_GPL(mmc_regulator_get_supply);
1605
1da177e4
LT
1606/*
1607 * Mask off any voltages we don't support and select
1608 * the lowest voltage
1609 */
7ea239d9 1610u32 mmc_select_voltage(struct mmc_host *host, u32 ocr)
1da177e4
LT
1611{
1612 int bit;
1613
726d6f23
UH
1614 /*
1615 * Sanity check the voltages that the card claims to
1616 * support.
1617 */
1618 if (ocr & 0x7F) {
1619 dev_warn(mmc_dev(host),
1620 "card claims to support voltages below defined range\n");
1621 ocr &= ~0x7F;
1622 }
1623
1da177e4 1624 ocr &= host->ocr_avail;
ce69d37b
UH
1625 if (!ocr) {
1626 dev_warn(mmc_dev(host), "no support for card's volts\n");
1627 return 0;
1628 }
1da177e4 1629
ce69d37b
UH
1630 if (host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) {
1631 bit = ffs(ocr) - 1;
63ef731a 1632 ocr &= 3 << bit;
ce69d37b 1633 mmc_power_cycle(host, ocr);
1da177e4 1634 } else {
ce69d37b
UH
1635 bit = fls(ocr) - 1;
1636 ocr &= 3 << bit;
1637 if (bit != host->ios.vdd)
1638 dev_warn(mmc_dev(host), "exceeding card's volts\n");
1da177e4
LT
1639 }
1640
1641 return ocr;
1642}
1643
4e74b6b3 1644int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage)
567c8903
JR
1645{
1646 int err = 0;
1647 int old_signal_voltage = host->ios.signal_voltage;
1648
1649 host->ios.signal_voltage = signal_voltage;
9eadcc05 1650 if (host->ops->start_signal_voltage_switch)
567c8903 1651 err = host->ops->start_signal_voltage_switch(host, &host->ios);
567c8903
JR
1652
1653 if (err)
1654 host->ios.signal_voltage = old_signal_voltage;
1655
1656 return err;
1657
1658}
1659
2ed573b6 1660int mmc_set_uhs_voltage(struct mmc_host *host, u32 ocr)
f2119df6 1661{
c7836d15 1662 struct mmc_command cmd = {};
f2119df6 1663 int err = 0;
0797e5f1 1664 u32 clock;
f2119df6 1665
0797e5f1
JR
1666 /*
1667 * If we cannot switch voltages, return failure so the caller
1668 * can continue without UHS mode
1669 */
1670 if (!host->ops->start_signal_voltage_switch)
1671 return -EPERM;
1672 if (!host->ops->card_busy)
6606110d
JP
1673 pr_warn("%s: cannot verify signal voltage switch\n",
1674 mmc_hostname(host));
0797e5f1
JR
1675
1676 cmd.opcode = SD_SWITCH_VOLTAGE;
1677 cmd.arg = 0;
1678 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1679
1680 err = mmc_wait_for_cmd(host, &cmd, 0);
1681 if (err)
9eadcc05
UH
1682 return err;
1683
1684 if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR))
1685 return -EIO;
0797e5f1 1686
0797e5f1
JR
1687 /*
1688 * The card should drive cmd and dat[0:3] low immediately
1689 * after the response of cmd11, but wait 1 ms to be sure
1690 */
1691 mmc_delay(1);
1692 if (host->ops->card_busy && !host->ops->card_busy(host)) {
1693 err = -EAGAIN;
1694 goto power_cycle;
1695 }
1696 /*
1697 * During a signal voltage level switch, the clock must be gated
1698 * for 5 ms according to the SD spec
1699 */
1700 clock = host->ios.clock;
1701 host->ios.clock = 0;
1702 mmc_set_ios(host);
f2119df6 1703
4e74b6b3 1704 if (mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180)) {
0797e5f1
JR
1705 /*
1706 * Voltages may not have been switched, but we've already
1707 * sent CMD11, so a power cycle is required anyway
1708 */
1709 err = -EAGAIN;
1710 goto power_cycle;
f2119df6
AN
1711 }
1712
7c5209c3
DA
1713 /* Keep clock gated for at least 10 ms, though spec only says 5 ms */
1714 mmc_delay(10);
0797e5f1
JR
1715 host->ios.clock = clock;
1716 mmc_set_ios(host);
1717
1718 /* Wait for at least 1 ms according to spec */
1719 mmc_delay(1);
1720
1721 /*
1722 * Failure to switch is indicated by the card holding
1723 * dat[0:3] low
1724 */
1725 if (host->ops->card_busy && host->ops->card_busy(host))
1726 err = -EAGAIN;
1727
1728power_cycle:
1729 if (err) {
1730 pr_debug("%s: Signal voltage switch failed, "
1731 "power cycling card\n", mmc_hostname(host));
0f791fda 1732 mmc_power_cycle(host, ocr);
0797e5f1
JR
1733 }
1734
0797e5f1 1735 return err;
f2119df6
AN
1736}
1737
b57c43ad 1738/*
7ea239d9 1739 * Select timing parameters for host.
b57c43ad 1740 */
7ea239d9 1741void mmc_set_timing(struct mmc_host *host, unsigned int timing)
b57c43ad 1742{
7ea239d9
PO
1743 host->ios.timing = timing;
1744 mmc_set_ios(host);
b57c43ad
PO
1745}
1746
d6d50a15
AN
1747/*
1748 * Select appropriate driver type for host.
1749 */
1750void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type)
1751{
1752 host->ios.drv_type = drv_type;
1753 mmc_set_ios(host);
1754}
1755
e23350b3
AH
1756int mmc_select_drive_strength(struct mmc_card *card, unsigned int max_dtr,
1757 int card_drv_type, int *drv_type)
1758{
1759 struct mmc_host *host = card->host;
1760 int host_drv_type = SD_DRIVER_TYPE_B;
e23350b3
AH
1761
1762 *drv_type = 0;
1763
1764 if (!host->ops->select_drive_strength)
1765 return 0;
1766
1767 /* Use SD definition of driver strength for hosts */
1768 if (host->caps & MMC_CAP_DRIVER_TYPE_A)
1769 host_drv_type |= SD_DRIVER_TYPE_A;
1770
1771 if (host->caps & MMC_CAP_DRIVER_TYPE_C)
1772 host_drv_type |= SD_DRIVER_TYPE_C;
1773
1774 if (host->caps & MMC_CAP_DRIVER_TYPE_D)
1775 host_drv_type |= SD_DRIVER_TYPE_D;
1776
1777 /*
1778 * The drive strength that the hardware can support
1779 * depends on the board design. Pass the appropriate
1780 * information and let the hardware specific code
1781 * return what is possible given the options
1782 */
9eadcc05
UH
1783 return host->ops->select_drive_strength(card, max_dtr,
1784 host_drv_type,
1785 card_drv_type,
1786 drv_type);
e23350b3
AH
1787}
1788
1da177e4 1789/*
45f8245b
RK
1790 * Apply power to the MMC stack. This is a two-stage process.
1791 * First, we enable power to the card without the clock running.
1792 * We then wait a bit for the power to stabilise. Finally,
1793 * enable the bus drivers and clock to the card.
1794 *
1795 * We must _NOT_ enable the clock prior to power stablising.
1796 *
1797 * If a host does all the power sequencing itself, ignore the
1798 * initial MMC_POWER_UP stage.
1da177e4 1799 */
4a065193 1800void mmc_power_up(struct mmc_host *host, u32 ocr)
1da177e4 1801{
fa550189
UH
1802 if (host->ios.power_mode == MMC_POWER_ON)
1803 return;
1804
3aa8793f
UH
1805 mmc_pwrseq_pre_power_on(host);
1806
4a065193 1807 host->ios.vdd = fls(ocr) - 1;
1da177e4 1808 host->ios.power_mode = MMC_POWER_UP;
2d079c43
JR
1809 /* Set initial state and call mmc_set_ios */
1810 mmc_set_initial_state(host);
1da177e4 1811
ceae98f2 1812 /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */
4e74b6b3 1813 if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330))
ceae98f2 1814 dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n");
4e74b6b3 1815 else if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180))
ceae98f2 1816 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n");
4e74b6b3 1817 else if (!mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_120))
ceae98f2 1818 dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n");
108ecc4c 1819
f9996aee
PO
1820 /*
1821 * This delay should be sufficient to allow the power supply
1822 * to reach the minimum voltage.
1823 */
79bccc5a 1824 mmc_delay(10);
1da177e4 1825
4febb7e2
UH
1826 mmc_pwrseq_post_power_on(host);
1827
88ae8b86 1828 host->ios.clock = host->f_init;
8dfd0374 1829
1da177e4 1830 host->ios.power_mode = MMC_POWER_ON;
920e70c5 1831 mmc_set_ios(host);
1da177e4 1832
f9996aee
PO
1833 /*
1834 * This delay must be at least 74 clock sizes, or 1 ms, or the
1835 * time required to reach a stable voltage.
1836 */
79bccc5a 1837 mmc_delay(10);
1da177e4
LT
1838}
1839
7f7e4129 1840void mmc_power_off(struct mmc_host *host)
1da177e4 1841{
fa550189
UH
1842 if (host->ios.power_mode == MMC_POWER_OFF)
1843 return;
1844
3aa8793f
UH
1845 mmc_pwrseq_power_off(host);
1846
1da177e4
LT
1847 host->ios.clock = 0;
1848 host->ios.vdd = 0;
b33d46c3 1849
1da177e4 1850 host->ios.power_mode = MMC_POWER_OFF;
2d079c43
JR
1851 /* Set initial state and call mmc_set_ios */
1852 mmc_set_initial_state(host);
778e277c 1853
041beb1d
DD
1854 /*
1855 * Some configurations, such as the 802.11 SDIO card in the OLPC
1856 * XO-1.5, require a short delay after poweroff before the card
1857 * can be successfully turned on again.
1858 */
1859 mmc_delay(1);
1da177e4
LT
1860}
1861
4a065193 1862void mmc_power_cycle(struct mmc_host *host, u32 ocr)
276e090f
JR
1863{
1864 mmc_power_off(host);
1865 /* Wait at least 1 ms according to SD spec */
1866 mmc_delay(1);
4a065193 1867 mmc_power_up(host, ocr);
276e090f
JR
1868}
1869
39361851
AB
1870/*
1871 * Cleanup when the last reference to the bus operator is dropped.
1872 */
261172fd 1873static void __mmc_release_bus(struct mmc_host *host)
39361851 1874{
6ff897ff 1875 WARN_ON(!host->bus_dead);
39361851
AB
1876
1877 host->bus_ops = NULL;
1878}
1879
1880/*
1881 * Increase reference count of bus operator
1882 */
1883static inline void mmc_bus_get(struct mmc_host *host)
1884{
1885 unsigned long flags;
1886
1887 spin_lock_irqsave(&host->lock, flags);
1888 host->bus_refs++;
1889 spin_unlock_irqrestore(&host->lock, flags);
1890}
1891
1892/*
1893 * Decrease reference count of bus operator and free it if
1894 * it is the last reference.
1895 */
1896static inline void mmc_bus_put(struct mmc_host *host)
1897{
1898 unsigned long flags;
1899
1900 spin_lock_irqsave(&host->lock, flags);
1901 host->bus_refs--;
1902 if ((host->bus_refs == 0) && host->bus_ops)
1903 __mmc_release_bus(host);
1904 spin_unlock_irqrestore(&host->lock, flags);
1905}
1906
1da177e4 1907/*
7ea239d9
PO
1908 * Assign a mmc bus handler to a host. Only one bus handler may control a
1909 * host at any given time.
1da177e4 1910 */
7ea239d9 1911void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
1da177e4 1912{
7ea239d9 1913 unsigned long flags;
e45a1bd2 1914
d84075c8 1915 WARN_ON(!host->claimed);
bce40a36 1916
7ea239d9 1917 spin_lock_irqsave(&host->lock, flags);
bce40a36 1918
6ff897ff
SL
1919 WARN_ON(host->bus_ops);
1920 WARN_ON(host->bus_refs);
b57c43ad 1921
7ea239d9
PO
1922 host->bus_ops = ops;
1923 host->bus_refs = 1;
1924 host->bus_dead = 0;
b57c43ad 1925
7ea239d9 1926 spin_unlock_irqrestore(&host->lock, flags);
b57c43ad
PO
1927}
1928
7ea239d9 1929/*
7f7e4129 1930 * Remove the current bus handler from a host.
7ea239d9
PO
1931 */
1932void mmc_detach_bus(struct mmc_host *host)
7ccd266e 1933{
7ea239d9 1934 unsigned long flags;
7ccd266e 1935
d84075c8
PO
1936 WARN_ON(!host->claimed);
1937 WARN_ON(!host->bus_ops);
cd9277c0 1938
7ea239d9 1939 spin_lock_irqsave(&host->lock, flags);
7ccd266e 1940
7ea239d9 1941 host->bus_dead = 1;
7ccd266e 1942
7ea239d9 1943 spin_unlock_irqrestore(&host->lock, flags);
1da177e4 1944
7ea239d9 1945 mmc_bus_put(host);
1da177e4
LT
1946}
1947
bbd43682
UH
1948static void _mmc_detect_change(struct mmc_host *host, unsigned long delay,
1949 bool cd_irq)
1950{
1951#ifdef CONFIG_MMC_DEBUG
1952 unsigned long flags;
1953 spin_lock_irqsave(&host->lock, flags);
1954 WARN_ON(host->removed);
1955 spin_unlock_irqrestore(&host->lock, flags);
1956#endif
1957
1958 /*
1959 * If the device is configured as wakeup, we prevent a new sleep for
1960 * 5 s to give provision for user space to consume the event.
1961 */
1962 if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) &&
1963 device_can_wakeup(mmc_dev(host)))
1964 pm_wakeup_event(mmc_dev(host), 5000);
1965
1966 host->detect_change = 1;
1967 mmc_schedule_delayed_work(&host->detect, delay);
1968}
1969
1da177e4
LT
1970/**
1971 * mmc_detect_change - process change of state on a MMC socket
1972 * @host: host which changed state.
8dc00335 1973 * @delay: optional delay to wait before detection (jiffies)
1da177e4 1974 *
67a61c48
PO
1975 * MMC drivers should call this when they detect a card has been
1976 * inserted or removed. The MMC layer will confirm that any
1977 * present card is still functional, and initialize any newly
1978 * inserted.
1da177e4 1979 */
8dc00335 1980void mmc_detect_change(struct mmc_host *host, unsigned long delay)
1da177e4 1981{
bbd43682 1982 _mmc_detect_change(host, delay, true);
1da177e4 1983}
1da177e4
LT
1984EXPORT_SYMBOL(mmc_detect_change);
1985
dfe86cba
AH
1986void mmc_init_erase(struct mmc_card *card)
1987{
1988 unsigned int sz;
1989
1990 if (is_power_of_2(card->erase_size))
1991 card->erase_shift = ffs(card->erase_size) - 1;
1992 else
1993 card->erase_shift = 0;
1994
1995 /*
1996 * It is possible to erase an arbitrarily large area of an SD or MMC
1997 * card. That is not desirable because it can take a long time
1998 * (minutes) potentially delaying more important I/O, and also the
1999 * timeout calculations become increasingly hugely over-estimated.
2000 * Consequently, 'pref_erase' is defined as a guide to limit erases
2001 * to that size and alignment.
2002 *
2003 * For SD cards that define Allocation Unit size, limit erases to one
c6d8fd61
GG
2004 * Allocation Unit at a time.
2005 * For MMC, have a stab at ai good value and for modern cards it will
2006 * end up being 4MiB. Note that if the value is too small, it can end
2007 * up taking longer to erase. Also note, erase_size is already set to
2008 * High Capacity Erase Size if available when this function is called.
dfe86cba
AH
2009 */
2010 if (mmc_card_sd(card) && card->ssr.au) {
2011 card->pref_erase = card->ssr.au;
2012 card->erase_shift = ffs(card->ssr.au) - 1;
cc8aa7de 2013 } else if (card->erase_size) {
dfe86cba
AH
2014 sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11;
2015 if (sz < 128)
2016 card->pref_erase = 512 * 1024 / 512;
2017 else if (sz < 512)
2018 card->pref_erase = 1024 * 1024 / 512;
2019 else if (sz < 1024)
2020 card->pref_erase = 2 * 1024 * 1024 / 512;
2021 else
2022 card->pref_erase = 4 * 1024 * 1024 / 512;
2023 if (card->pref_erase < card->erase_size)
2024 card->pref_erase = card->erase_size;
2025 else {
2026 sz = card->pref_erase % card->erase_size;
2027 if (sz)
2028 card->pref_erase += card->erase_size - sz;
2029 }
cc8aa7de
CD
2030 } else
2031 card->pref_erase = 0;
dfe86cba
AH
2032}
2033
eaa02f75
AW
2034static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card,
2035 unsigned int arg, unsigned int qty)
dfe86cba
AH
2036{
2037 unsigned int erase_timeout;
2038
7194efb8
AH
2039 if (arg == MMC_DISCARD_ARG ||
2040 (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) {
2041 erase_timeout = card->ext_csd.trim_timeout;
2042 } else if (card->ext_csd.erase_group_def & 1) {
dfe86cba
AH
2043 /* High Capacity Erase Group Size uses HC timeouts */
2044 if (arg == MMC_TRIM_ARG)
2045 erase_timeout = card->ext_csd.trim_timeout;
2046 else
2047 erase_timeout = card->ext_csd.hc_erase_timeout;
2048 } else {
2049 /* CSD Erase Group Size uses write timeout */
2050 unsigned int mult = (10 << card->csd.r2w_factor);
2051 unsigned int timeout_clks = card->csd.tacc_clks * mult;
2052 unsigned int timeout_us;
2053
2054 /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */
2055 if (card->csd.tacc_ns < 1000000)
2056 timeout_us = (card->csd.tacc_ns * mult) / 1000;
2057 else
2058 timeout_us = (card->csd.tacc_ns / 1000) * mult;
2059
2060 /*
2061 * ios.clock is only a target. The real clock rate might be
2062 * less but not that much less, so fudge it by multiplying by 2.
2063 */
2064 timeout_clks <<= 1;
2065 timeout_us += (timeout_clks * 1000) /
9eadcc05 2066 (card->host->ios.clock / 1000);
dfe86cba
AH
2067
2068 erase_timeout = timeout_us / 1000;
2069
2070 /*
2071 * Theoretically, the calculation could underflow so round up
2072 * to 1ms in that case.
2073 */
2074 if (!erase_timeout)
2075 erase_timeout = 1;
2076 }
2077
2078 /* Multiplier for secure operations */
2079 if (arg & MMC_SECURE_ARGS) {
2080 if (arg == MMC_SECURE_ERASE_ARG)
2081 erase_timeout *= card->ext_csd.sec_erase_mult;
2082 else
2083 erase_timeout *= card->ext_csd.sec_trim_mult;
2084 }
2085
2086 erase_timeout *= qty;
2087
2088 /*
2089 * Ensure at least a 1 second timeout for SPI as per
2090 * 'mmc_set_data_timeout()'
2091 */
2092 if (mmc_host_is_spi(card->host) && erase_timeout < 1000)
2093 erase_timeout = 1000;
2094
eaa02f75 2095 return erase_timeout;
dfe86cba
AH
2096}
2097
eaa02f75
AW
2098static unsigned int mmc_sd_erase_timeout(struct mmc_card *card,
2099 unsigned int arg,
2100 unsigned int qty)
dfe86cba 2101{
eaa02f75
AW
2102 unsigned int erase_timeout;
2103
dfe86cba
AH
2104 if (card->ssr.erase_timeout) {
2105 /* Erase timeout specified in SD Status Register (SSR) */
eaa02f75
AW
2106 erase_timeout = card->ssr.erase_timeout * qty +
2107 card->ssr.erase_offset;
dfe86cba
AH
2108 } else {
2109 /*
2110 * Erase timeout not specified in SD Status Register (SSR) so
2111 * use 250ms per write block.
2112 */
eaa02f75 2113 erase_timeout = 250 * qty;
dfe86cba
AH
2114 }
2115
2116 /* Must not be less than 1 second */
eaa02f75
AW
2117 if (erase_timeout < 1000)
2118 erase_timeout = 1000;
2119
2120 return erase_timeout;
dfe86cba
AH
2121}
2122
eaa02f75
AW
2123static unsigned int mmc_erase_timeout(struct mmc_card *card,
2124 unsigned int arg,
2125 unsigned int qty)
dfe86cba
AH
2126{
2127 if (mmc_card_sd(card))
eaa02f75 2128 return mmc_sd_erase_timeout(card, arg, qty);
dfe86cba 2129 else
eaa02f75 2130 return mmc_mmc_erase_timeout(card, arg, qty);
dfe86cba
AH
2131}
2132
2133static int mmc_do_erase(struct mmc_card *card, unsigned int from,
2134 unsigned int to, unsigned int arg)
2135{
c7836d15 2136 struct mmc_command cmd = {};
bb4eecf2
BW
2137 unsigned int qty = 0, busy_timeout = 0;
2138 bool use_r1b_resp = false;
8fee476b 2139 unsigned long timeout;
dfe86cba
AH
2140 int err;
2141
8f11d106
AH
2142 mmc_retune_hold(card->host);
2143
dfe86cba
AH
2144 /*
2145 * qty is used to calculate the erase timeout which depends on how many
2146 * erase groups (or allocation units in SD terminology) are affected.
2147 * We count erasing part of an erase group as one erase group.
2148 * For SD, the allocation units are always a power of 2. For MMC, the
2149 * erase group size is almost certainly also power of 2, but it does not
2150 * seem to insist on that in the JEDEC standard, so we fall back to
2151 * division in that case. SD may not specify an allocation unit size,
2152 * in which case the timeout is based on the number of write blocks.
2153 *
2154 * Note that the timeout for secure trim 2 will only be correct if the
2155 * number of erase groups specified is the same as the total of all
2156 * preceding secure trim 1 commands. Since the power may have been
2157 * lost since the secure trim 1 commands occurred, it is generally
2158 * impossible to calculate the secure trim 2 timeout correctly.
2159 */
2160 if (card->erase_shift)
2161 qty += ((to >> card->erase_shift) -
2162 (from >> card->erase_shift)) + 1;
2163 else if (mmc_card_sd(card))
2164 qty += to - from + 1;
2165 else
2166 qty += ((to / card->erase_size) -
2167 (from / card->erase_size)) + 1;
2168
2169 if (!mmc_card_blockaddr(card)) {
2170 from <<= 9;
2171 to <<= 9;
2172 }
2173
dfe86cba
AH
2174 if (mmc_card_sd(card))
2175 cmd.opcode = SD_ERASE_WR_BLK_START;
2176 else
2177 cmd.opcode = MMC_ERASE_GROUP_START;
2178 cmd.arg = from;
2179 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2180 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2181 if (err) {
a3c76eb9 2182 pr_err("mmc_erase: group start error %d, "
dfe86cba 2183 "status %#x\n", err, cmd.resp[0]);
67716327 2184 err = -EIO;
dfe86cba
AH
2185 goto out;
2186 }
2187
2188 memset(&cmd, 0, sizeof(struct mmc_command));
2189 if (mmc_card_sd(card))
2190 cmd.opcode = SD_ERASE_WR_BLK_END;
2191 else
2192 cmd.opcode = MMC_ERASE_GROUP_END;
2193 cmd.arg = to;
2194 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2195 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2196 if (err) {
a3c76eb9 2197 pr_err("mmc_erase: group end error %d, status %#x\n",
dfe86cba 2198 err, cmd.resp[0]);
67716327 2199 err = -EIO;
dfe86cba
AH
2200 goto out;
2201 }
2202
2203 memset(&cmd, 0, sizeof(struct mmc_command));
2204 cmd.opcode = MMC_ERASE;
2205 cmd.arg = arg;
bb4eecf2
BW
2206 busy_timeout = mmc_erase_timeout(card, arg, qty);
2207 /*
2208 * If the host controller supports busy signalling and the timeout for
2209 * the erase operation does not exceed the max_busy_timeout, we should
2210 * use R1B response. Or we need to prevent the host from doing hw busy
2211 * detection, which is done by converting to a R1 response instead.
2212 */
2213 if (card->host->max_busy_timeout &&
2214 busy_timeout > card->host->max_busy_timeout) {
2215 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2216 } else {
2217 cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
2218 cmd.busy_timeout = busy_timeout;
2219 use_r1b_resp = true;
2220 }
2221
dfe86cba
AH
2222 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2223 if (err) {
a3c76eb9 2224 pr_err("mmc_erase: erase error %d, status %#x\n",
dfe86cba
AH
2225 err, cmd.resp[0]);
2226 err = -EIO;
2227 goto out;
2228 }
2229
2230 if (mmc_host_is_spi(card->host))
2231 goto out;
2232
bb4eecf2
BW
2233 /*
2234 * In case of when R1B + MMC_CAP_WAIT_WHILE_BUSY is used, the polling
2235 * shall be avoided.
2236 */
2237 if ((card->host->caps & MMC_CAP_WAIT_WHILE_BUSY) && use_r1b_resp)
2238 goto out;
2239
2240 timeout = jiffies + msecs_to_jiffies(busy_timeout);
dfe86cba
AH
2241 do {
2242 memset(&cmd, 0, sizeof(struct mmc_command));
2243 cmd.opcode = MMC_SEND_STATUS;
2244 cmd.arg = card->rca << 16;
2245 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
2246 /* Do not retry else we can't see errors */
2247 err = mmc_wait_for_cmd(card->host, &cmd, 0);
2248 if (err || (cmd.resp[0] & 0xFDF92000)) {
a3c76eb9 2249 pr_err("error %d requesting status %#x\n",
dfe86cba
AH
2250 err, cmd.resp[0]);
2251 err = -EIO;
2252 goto out;
2253 }
8fee476b
TR
2254
2255 /* Timeout if the device never becomes ready for data and
2256 * never leaves the program state.
2257 */
2258 if (time_after(jiffies, timeout)) {
2259 pr_err("%s: Card stuck in programming state! %s\n",
2260 mmc_hostname(card->host), __func__);
2261 err = -EIO;
2262 goto out;
2263 }
2264
dfe86cba 2265 } while (!(cmd.resp[0] & R1_READY_FOR_DATA) ||
8fee476b 2266 (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG));
dfe86cba 2267out:
8f11d106 2268 mmc_retune_release(card->host);
dfe86cba
AH
2269 return err;
2270}
2271
71085123
BW
2272static unsigned int mmc_align_erase_size(struct mmc_card *card,
2273 unsigned int *from,
2274 unsigned int *to,
2275 unsigned int nr)
2276{
2277 unsigned int from_new = *from, nr_new = nr, rem;
2278
6c689886
BW
2279 /*
2280 * When the 'card->erase_size' is power of 2, we can use round_up/down()
2281 * to align the erase size efficiently.
2282 */
2283 if (is_power_of_2(card->erase_size)) {
2284 unsigned int temp = from_new;
2285
2286 from_new = round_up(temp, card->erase_size);
2287 rem = from_new - temp;
2288
71085123
BW
2289 if (nr_new > rem)
2290 nr_new -= rem;
2291 else
2292 return 0;
71085123 2293
6c689886
BW
2294 nr_new = round_down(nr_new, card->erase_size);
2295 } else {
2296 rem = from_new % card->erase_size;
2297 if (rem) {
2298 rem = card->erase_size - rem;
2299 from_new += rem;
2300 if (nr_new > rem)
2301 nr_new -= rem;
2302 else
2303 return 0;
2304 }
2305
2306 rem = nr_new % card->erase_size;
2307 if (rem)
2308 nr_new -= rem;
2309 }
71085123
BW
2310
2311 if (nr_new == 0)
2312 return 0;
2313
2314 *to = from_new + nr_new;
2315 *from = from_new;
2316
2317 return nr_new;
2318}
2319
dfe86cba
AH
2320/**
2321 * mmc_erase - erase sectors.
2322 * @card: card to erase
2323 * @from: first sector to erase
2324 * @nr: number of sectors to erase
2325 * @arg: erase command argument (SD supports only %MMC_ERASE_ARG)
2326 *
2327 * Caller must claim host before calling this function.
2328 */
2329int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
2330 unsigned int arg)
2331{
2332 unsigned int rem, to = from + nr;
642c28ab 2333 int err;
dfe86cba
AH
2334
2335 if (!(card->host->caps & MMC_CAP_ERASE) ||
2336 !(card->csd.cmdclass & CCC_ERASE))
2337 return -EOPNOTSUPP;
2338
2339 if (!card->erase_size)
2340 return -EOPNOTSUPP;
2341
2342 if (mmc_card_sd(card) && arg != MMC_ERASE_ARG)
2343 return -EOPNOTSUPP;
2344
2345 if ((arg & MMC_SECURE_ARGS) &&
2346 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN))
2347 return -EOPNOTSUPP;
2348
2349 if ((arg & MMC_TRIM_ARGS) &&
2350 !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN))
2351 return -EOPNOTSUPP;
2352
2353 if (arg == MMC_SECURE_ERASE_ARG) {
2354 if (from % card->erase_size || nr % card->erase_size)
2355 return -EINVAL;
2356 }
2357
71085123
BW
2358 if (arg == MMC_ERASE_ARG)
2359 nr = mmc_align_erase_size(card, &from, &to, nr);
dfe86cba
AH
2360
2361 if (nr == 0)
2362 return 0;
2363
dfe86cba
AH
2364 if (to <= from)
2365 return -EINVAL;
2366
2367 /* 'from' and 'to' are inclusive */
2368 to -= 1;
2369
642c28ab
DJ
2370 /*
2371 * Special case where only one erase-group fits in the timeout budget:
2372 * If the region crosses an erase-group boundary on this particular
2373 * case, we will be trimming more than one erase-group which, does not
2374 * fit in the timeout budget of the controller, so we need to split it
2375 * and call mmc_do_erase() twice if necessary. This special case is
2376 * identified by the card->eg_boundary flag.
2377 */
22d7e85f
RG
2378 rem = card->erase_size - (from % card->erase_size);
2379 if ((arg & MMC_TRIM_ARGS) && (card->eg_boundary) && (nr > rem)) {
642c28ab
DJ
2380 err = mmc_do_erase(card, from, from + rem - 1, arg);
2381 from += rem;
2382 if ((err) || (to <= from))
2383 return err;
2384 }
2385
dfe86cba
AH
2386 return mmc_do_erase(card, from, to, arg);
2387}
2388EXPORT_SYMBOL(mmc_erase);
2389
2390int mmc_can_erase(struct mmc_card *card)
2391{
2392 if ((card->host->caps & MMC_CAP_ERASE) &&
2393 (card->csd.cmdclass & CCC_ERASE) && card->erase_size)
2394 return 1;
2395 return 0;
2396}
2397EXPORT_SYMBOL(mmc_can_erase);
2398
2399int mmc_can_trim(struct mmc_card *card)
2400{
b5b4ff0a
SL
2401 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN) &&
2402 (!(card->quirks & MMC_QUIRK_TRIM_BROKEN)))
dfe86cba
AH
2403 return 1;
2404 return 0;
2405}
2406EXPORT_SYMBOL(mmc_can_trim);
2407
b3bf9153
KP
2408int mmc_can_discard(struct mmc_card *card)
2409{
2410 /*
2411 * As there's no way to detect the discard support bit at v4.5
2412 * use the s/w feature support filed.
2413 */
2414 if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE)
2415 return 1;
2416 return 0;
2417}
2418EXPORT_SYMBOL(mmc_can_discard);
2419
d9ddd629
KP
2420int mmc_can_sanitize(struct mmc_card *card)
2421{
28302812
AH
2422 if (!mmc_can_trim(card) && !mmc_can_erase(card))
2423 return 0;
d9ddd629
KP
2424 if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE)
2425 return 1;
2426 return 0;
2427}
2428EXPORT_SYMBOL(mmc_can_sanitize);
2429
dfe86cba
AH
2430int mmc_can_secure_erase_trim(struct mmc_card *card)
2431{
5204d00f
LC
2432 if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) &&
2433 !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
dfe86cba
AH
2434 return 1;
2435 return 0;
2436}
2437EXPORT_SYMBOL(mmc_can_secure_erase_trim);
2438
2439int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from,
2440 unsigned int nr)
2441{
2442 if (!card->erase_size)
2443 return 0;
2444 if (from % card->erase_size || nr % card->erase_size)
2445 return 0;
2446 return 1;
2447}
2448EXPORT_SYMBOL(mmc_erase_group_aligned);
1da177e4 2449
e056a1b5
AH
2450static unsigned int mmc_do_calc_max_discard(struct mmc_card *card,
2451 unsigned int arg)
2452{
2453 struct mmc_host *host = card->host;
bb4eecf2 2454 unsigned int max_discard, x, y, qty = 0, max_qty, min_qty, timeout;
e056a1b5 2455 unsigned int last_timeout = 0;
12182aff
UH
2456 unsigned int max_busy_timeout = host->max_busy_timeout ?
2457 host->max_busy_timeout : MMC_ERASE_TIMEOUT_MS;
e056a1b5 2458
bb4eecf2 2459 if (card->erase_shift) {
e056a1b5 2460 max_qty = UINT_MAX >> card->erase_shift;
bb4eecf2
BW
2461 min_qty = card->pref_erase >> card->erase_shift;
2462 } else if (mmc_card_sd(card)) {
e056a1b5 2463 max_qty = UINT_MAX;
bb4eecf2
BW
2464 min_qty = card->pref_erase;
2465 } else {
e056a1b5 2466 max_qty = UINT_MAX / card->erase_size;
bb4eecf2
BW
2467 min_qty = card->pref_erase / card->erase_size;
2468 }
e056a1b5 2469
bb4eecf2
BW
2470 /*
2471 * We should not only use 'host->max_busy_timeout' as the limitation
2472 * when deciding the max discard sectors. We should set a balance value
2473 * to improve the erase speed, and it can not get too long timeout at
2474 * the same time.
2475 *
2476 * Here we set 'card->pref_erase' as the minimal discard sectors no
2477 * matter what size of 'host->max_busy_timeout', but if the
2478 * 'host->max_busy_timeout' is large enough for more discard sectors,
2479 * then we can continue to increase the max discard sectors until we
12182aff
UH
2480 * get a balance value. In cases when the 'host->max_busy_timeout'
2481 * isn't specified, use the default max erase timeout.
bb4eecf2 2482 */
e056a1b5
AH
2483 do {
2484 y = 0;
2485 for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) {
2486 timeout = mmc_erase_timeout(card, arg, qty + x);
bb4eecf2 2487
12182aff 2488 if (qty + x > min_qty && timeout > max_busy_timeout)
e056a1b5 2489 break;
bb4eecf2 2490
e056a1b5
AH
2491 if (timeout < last_timeout)
2492 break;
2493 last_timeout = timeout;
2494 y = x;
2495 }
2496 qty += y;
2497 } while (y);
2498
2499 if (!qty)
2500 return 0;
2501
642c28ab
DJ
2502 /*
2503 * When specifying a sector range to trim, chances are we might cross
2504 * an erase-group boundary even if the amount of sectors is less than
2505 * one erase-group.
2506 * If we can only fit one erase-group in the controller timeout budget,
2507 * we have to care that erase-group boundaries are not crossed by a
2508 * single trim operation. We flag that special case with "eg_boundary".
2509 * In all other cases we can just decrement qty and pretend that we
2510 * always touch (qty + 1) erase-groups as a simple optimization.
2511 */
e056a1b5 2512 if (qty == 1)
642c28ab
DJ
2513 card->eg_boundary = 1;
2514 else
2515 qty--;
e056a1b5
AH
2516
2517 /* Convert qty to sectors */
2518 if (card->erase_shift)
642c28ab 2519 max_discard = qty << card->erase_shift;
e056a1b5 2520 else if (mmc_card_sd(card))
642c28ab 2521 max_discard = qty + 1;
e056a1b5 2522 else
642c28ab 2523 max_discard = qty * card->erase_size;
e056a1b5
AH
2524
2525 return max_discard;
2526}
2527
2528unsigned int mmc_calc_max_discard(struct mmc_card *card)
2529{
2530 struct mmc_host *host = card->host;
2531 unsigned int max_discard, max_trim;
2532
e056a1b5
AH
2533 /*
2534 * Without erase_group_def set, MMC erase timeout depends on clock
2535 * frequence which can change. In that case, the best choice is
2536 * just the preferred erase size.
2537 */
2538 if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1))
2539 return card->pref_erase;
2540
2541 max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG);
2542 if (mmc_can_trim(card)) {
2543 max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG);
2544 if (max_trim < max_discard)
2545 max_discard = max_trim;
2546 } else if (max_discard < card->erase_size) {
2547 max_discard = 0;
2548 }
2549 pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n",
12182aff
UH
2550 mmc_hostname(host), max_discard, host->max_busy_timeout ?
2551 host->max_busy_timeout : MMC_ERASE_TIMEOUT_MS);
e056a1b5
AH
2552 return max_discard;
2553}
2554EXPORT_SYMBOL(mmc_calc_max_discard);
2555
0f8d8ea6
AH
2556int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
2557{
c7836d15 2558 struct mmc_command cmd = {};
0f8d8ea6 2559
1712c937
ZX
2560 if (mmc_card_blockaddr(card) || mmc_card_ddr52(card) ||
2561 mmc_card_hs400(card) || mmc_card_hs400es(card))
0f8d8ea6
AH
2562 return 0;
2563
0f8d8ea6
AH
2564 cmd.opcode = MMC_SET_BLOCKLEN;
2565 cmd.arg = blocklen;
2566 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2567 return mmc_wait_for_cmd(card->host, &cmd, 5);
2568}
2569EXPORT_SYMBOL(mmc_set_blocklen);
2570
67c79db8
LP
2571int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount,
2572 bool is_rel_write)
2573{
c7836d15 2574 struct mmc_command cmd = {};
67c79db8
LP
2575
2576 cmd.opcode = MMC_SET_BLOCK_COUNT;
2577 cmd.arg = blockcount & 0x0000FFFF;
2578 if (is_rel_write)
2579 cmd.arg |= 1 << 31;
2580 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
2581 return mmc_wait_for_cmd(card->host, &cmd, 5);
2582}
2583EXPORT_SYMBOL(mmc_set_blockcount);
2584
b2499518
AH
2585static void mmc_hw_reset_for_init(struct mmc_host *host)
2586{
2587 if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset)
2588 return;
b2499518 2589 host->ops->hw_reset(host);
b2499518
AH
2590}
2591
83533ab2 2592int mmc_hw_reset(struct mmc_host *host)
b2499518 2593{
f855a371 2594 int ret;
b2499518 2595
f855a371 2596 if (!host->card)
b2499518
AH
2597 return -EINVAL;
2598
f855a371
JR
2599 mmc_bus_get(host);
2600 if (!host->bus_ops || host->bus_dead || !host->bus_ops->reset) {
2601 mmc_bus_put(host);
b2499518 2602 return -EOPNOTSUPP;
b2499518
AH
2603 }
2604
f855a371
JR
2605 ret = host->bus_ops->reset(host);
2606 mmc_bus_put(host);
b2499518 2607
4e6c7178
GG
2608 if (ret)
2609 pr_warn("%s: tried to reset card, got error %d\n",
2610 mmc_hostname(host), ret);
b2499518 2611
f855a371 2612 return ret;
b2499518 2613}
b2499518
AH
2614EXPORT_SYMBOL(mmc_hw_reset);
2615
807e8e40
AR
2616static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq)
2617{
2618 host->f_init = freq;
2619
2620#ifdef CONFIG_MMC_DEBUG
2621 pr_info("%s: %s: trying to init card at %u Hz\n",
2622 mmc_hostname(host), __func__, host->f_init);
2623#endif
4a065193 2624 mmc_power_up(host, host->ocr_avail);
2f94e55a 2625
b2499518
AH
2626 /*
2627 * Some eMMCs (with VCCQ always on) may not be reset after power up, so
2628 * do a hardware reset if possible.
2629 */
2630 mmc_hw_reset_for_init(host);
2631
2f94e55a
PR
2632 /*
2633 * sdio_reset sends CMD52 to reset card. Since we do not know
2634 * if the card is being re-initialized, just send it. CMD52
2635 * should be ignored by SD/eMMC cards.
100a606d 2636 * Skip it if we already know that we do not support SDIO commands
2f94e55a 2637 */
100a606d
CC
2638 if (!(host->caps2 & MMC_CAP2_NO_SDIO))
2639 sdio_reset(host);
2640
807e8e40
AR
2641 mmc_go_idle(host);
2642
1b8d79c5
UH
2643 if (!(host->caps2 & MMC_CAP2_NO_SD))
2644 mmc_send_if_cond(host, host->ocr_avail);
807e8e40
AR
2645
2646 /* Order's important: probe SDIO, then SD, then MMC */
100a606d
CC
2647 if (!(host->caps2 & MMC_CAP2_NO_SDIO))
2648 if (!mmc_attach_sdio(host))
2649 return 0;
2650
1b8d79c5
UH
2651 if (!(host->caps2 & MMC_CAP2_NO_SD))
2652 if (!mmc_attach_sd(host))
2653 return 0;
2654
a0c3b68c
SL
2655 if (!(host->caps2 & MMC_CAP2_NO_MMC))
2656 if (!mmc_attach_mmc(host))
2657 return 0;
807e8e40
AR
2658
2659 mmc_power_off(host);
2660 return -EIO;
2661}
2662
d3049504
AH
2663int _mmc_detect_card_removed(struct mmc_host *host)
2664{
2665 int ret;
2666
d3049504
AH
2667 if (!host->card || mmc_card_removed(host->card))
2668 return 1;
2669
2670 ret = host->bus_ops->alive(host);
1450734e
KL
2671
2672 /*
2673 * Card detect status and alive check may be out of sync if card is
2674 * removed slowly, when card detect switch changes while card/slot
2675 * pads are still contacted in hardware (refer to "SD Card Mechanical
2676 * Addendum, Appendix C: Card Detection Switch"). So reschedule a
2677 * detect work 200ms later for this case.
2678 */
2679 if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) {
2680 mmc_detect_change(host, msecs_to_jiffies(200));
2681 pr_debug("%s: card removed too slowly\n", mmc_hostname(host));
2682 }
2683
d3049504
AH
2684 if (ret) {
2685 mmc_card_set_removed(host->card);
2686 pr_debug("%s: card remove detected\n", mmc_hostname(host));
2687 }
2688
2689 return ret;
2690}
2691
2692int mmc_detect_card_removed(struct mmc_host *host)
2693{
2694 struct mmc_card *card = host->card;
f0cc9cf9 2695 int ret;
d3049504
AH
2696
2697 WARN_ON(!host->claimed);
f0cc9cf9
UH
2698
2699 if (!card)
2700 return 1;
2701
6067bafe 2702 if (!mmc_card_is_removable(host))
1ff2575b
UH
2703 return 0;
2704
f0cc9cf9 2705 ret = mmc_card_removed(card);
d3049504
AH
2706 /*
2707 * The card will be considered unchanged unless we have been asked to
2708 * detect a change or host requires polling to provide card detection.
2709 */
b6891679 2710 if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL))
f0cc9cf9 2711 return ret;
d3049504
AH
2712
2713 host->detect_change = 0;
f0cc9cf9
UH
2714 if (!ret) {
2715 ret = _mmc_detect_card_removed(host);
b6891679 2716 if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) {
f0cc9cf9
UH
2717 /*
2718 * Schedule a detect work as soon as possible to let a
2719 * rescan handle the card removal.
2720 */
2721 cancel_delayed_work(&host->detect);
bbd43682 2722 _mmc_detect_change(host, 0, false);
f0cc9cf9
UH
2723 }
2724 }
d3049504 2725
f0cc9cf9 2726 return ret;
d3049504
AH
2727}
2728EXPORT_SYMBOL(mmc_detect_card_removed);
2729
b93931a6 2730void mmc_rescan(struct work_struct *work)
1da177e4 2731{
c4028958
DH
2732 struct mmc_host *host =
2733 container_of(work, struct mmc_host, detect.work);
88ae8b86 2734 int i;
4c2ef25f 2735
807e8e40 2736 if (host->rescan_disable)
4c2ef25f 2737 return;
1da177e4 2738
3339d1e3 2739 /* If there is a non-removable card registered, only scan once */
6067bafe 2740 if (!mmc_card_is_removable(host) && host->rescan_entered)
3339d1e3
JR
2741 return;
2742 host->rescan_entered = 1;
2743
86236813 2744 if (host->trigger_card_event && host->ops->card_event) {
d234d212 2745 mmc_claim_host(host);
86236813 2746 host->ops->card_event(host);
d234d212 2747 mmc_release_host(host);
86236813
UH
2748 host->trigger_card_event = false;
2749 }
2750
7ea239d9 2751 mmc_bus_get(host);
b855885e 2752
30201e7f
OBC
2753 /*
2754 * if there is a _removable_ card registered, check whether it is
2755 * still present
2756 */
6067bafe 2757 if (host->bus_ops && !host->bus_dead && mmc_card_is_removable(host))
94d89efb
JS
2758 host->bus_ops->detect(host);
2759
d3049504
AH
2760 host->detect_change = 0;
2761
c5841798
CB
2762 /*
2763 * Let mmc_bus_put() free the bus/bus_ops if we've found that
2764 * the card is no longer present.
2765 */
94d89efb 2766 mmc_bus_put(host);
94d89efb
JS
2767 mmc_bus_get(host);
2768
2769 /* if there still is a card present, stop here */
2770 if (host->bus_ops != NULL) {
7ea239d9 2771 mmc_bus_put(host);
94d89efb
JS
2772 goto out;
2773 }
1da177e4 2774
94d89efb
JS
2775 /*
2776 * Only we can add a new handler, so it's safe to
2777 * release the lock here.
2778 */
2779 mmc_bus_put(host);
1da177e4 2780
d234d212 2781 mmc_claim_host(host);
6067bafe 2782 if (mmc_card_is_removable(host) && host->ops->get_cd &&
c1b55bfc 2783 host->ops->get_cd(host) == 0) {
fa550189
UH
2784 mmc_power_off(host);
2785 mmc_release_host(host);
94d89efb 2786 goto out;
fa550189 2787 }
1da177e4 2788
88ae8b86 2789 for (i = 0; i < ARRAY_SIZE(freqs); i++) {
807e8e40
AR
2790 if (!mmc_rescan_try_freq(host, max(freqs[i], host->f_min)))
2791 break;
06b2233a 2792 if (freqs[i] <= host->f_min)
807e8e40 2793 break;
88ae8b86 2794 }
807e8e40
AR
2795 mmc_release_host(host);
2796
2797 out:
28f52482
AV
2798 if (host->caps & MMC_CAP_NEEDS_POLL)
2799 mmc_schedule_delayed_work(&host->detect, HZ);
1da177e4
LT
2800}
2801
b93931a6 2802void mmc_start_host(struct mmc_host *host)
1da177e4 2803{
fa550189 2804 host->f_init = max(freqs[0], host->f_min);
d9adcc12 2805 host->rescan_disable = 0;
8af465db 2806 host->ios.power_mode = MMC_POWER_UNDEFINED;
8d1ffc8c 2807
c2c24819
UH
2808 if (!(host->caps2 & MMC_CAP2_NO_PRESCAN_POWERUP)) {
2809 mmc_claim_host(host);
4a065193 2810 mmc_power_up(host, host->ocr_avail);
c2c24819
UH
2811 mmc_release_host(host);
2812 }
8d1ffc8c 2813
740a221e 2814 mmc_gpiod_request_cd_irq(host);
bbd43682 2815 _mmc_detect_change(host, 0, false);
1da177e4
LT
2816}
2817
b93931a6 2818void mmc_stop_host(struct mmc_host *host)
1da177e4 2819{
3b91e550 2820#ifdef CONFIG_MMC_DEBUG
1efd48b3
PO
2821 unsigned long flags;
2822 spin_lock_irqsave(&host->lock, flags);
3b91e550 2823 host->removed = 1;
1efd48b3 2824 spin_unlock_irqrestore(&host->lock, flags);
3b91e550 2825#endif
740a221e
AH
2826 if (host->slot.cd_irq >= 0)
2827 disable_irq(host->slot.cd_irq);
3b91e550 2828
d9adcc12 2829 host->rescan_disable = 1;
d9bcbf34 2830 cancel_delayed_work_sync(&host->detect);
3b91e550 2831
da68c4eb
NP
2832 /* clear pm flags now and let card drivers set them as needed */
2833 host->pm_flags = 0;
2834
7ea239d9
PO
2835 mmc_bus_get(host);
2836 if (host->bus_ops && !host->bus_dead) {
0db13fc2 2837 /* Calling bus_ops->remove() with a claimed host can deadlock */
58a8a4a1 2838 host->bus_ops->remove(host);
7ea239d9
PO
2839 mmc_claim_host(host);
2840 mmc_detach_bus(host);
7f7e4129 2841 mmc_power_off(host);
7ea239d9 2842 mmc_release_host(host);
53509f0f
DK
2843 mmc_bus_put(host);
2844 return;
1da177e4 2845 }
7ea239d9
PO
2846 mmc_bus_put(host);
2847
8d1ffc8c 2848 mmc_claim_host(host);
1da177e4 2849 mmc_power_off(host);
8d1ffc8c 2850 mmc_release_host(host);
1da177e4
LT
2851}
2852
12ae637f 2853int mmc_power_save_host(struct mmc_host *host)
eae1aeee 2854{
12ae637f
OBC
2855 int ret = 0;
2856
bb9cab94
DD
2857#ifdef CONFIG_MMC_DEBUG
2858 pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__);
2859#endif
2860
eae1aeee
AH
2861 mmc_bus_get(host);
2862
5601aaf7 2863 if (!host->bus_ops || host->bus_dead) {
eae1aeee 2864 mmc_bus_put(host);
12ae637f 2865 return -EINVAL;
eae1aeee
AH
2866 }
2867
2868 if (host->bus_ops->power_save)
12ae637f 2869 ret = host->bus_ops->power_save(host);
eae1aeee
AH
2870
2871 mmc_bus_put(host);
2872
2873 mmc_power_off(host);
12ae637f
OBC
2874
2875 return ret;
eae1aeee
AH
2876}
2877EXPORT_SYMBOL(mmc_power_save_host);
2878
12ae637f 2879int mmc_power_restore_host(struct mmc_host *host)
eae1aeee 2880{
12ae637f
OBC
2881 int ret;
2882
bb9cab94
DD
2883#ifdef CONFIG_MMC_DEBUG
2884 pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__);
2885#endif
2886
eae1aeee
AH
2887 mmc_bus_get(host);
2888
5601aaf7 2889 if (!host->bus_ops || host->bus_dead) {
eae1aeee 2890 mmc_bus_put(host);
12ae637f 2891 return -EINVAL;
eae1aeee
AH
2892 }
2893
69041150 2894 mmc_power_up(host, host->card->ocr);
12ae637f 2895 ret = host->bus_ops->power_restore(host);
eae1aeee
AH
2896
2897 mmc_bus_put(host);
12ae637f
OBC
2898
2899 return ret;
eae1aeee
AH
2900}
2901EXPORT_SYMBOL(mmc_power_restore_host);
2902
881d1c25
SJ
2903/*
2904 * Flush the cache to the non-volatile storage.
2905 */
2906int mmc_flush_cache(struct mmc_card *card)
2907{
881d1c25
SJ
2908 int err = 0;
2909
881d1c25
SJ
2910 if (mmc_card_mmc(card) &&
2911 (card->ext_csd.cache_size > 0) &&
2912 (card->ext_csd.cache_ctrl & 1)) {
2913 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
2914 EXT_CSD_FLUSH_CACHE, 1, 0);
2915 if (err)
2916 pr_err("%s: cache flush error %d\n",
2917 mmc_hostname(card->host), err);
2918 }
2919
2920 return err;
2921}
2922EXPORT_SYMBOL(mmc_flush_cache);
2923
8dede18e 2924#ifdef CONFIG_PM_SLEEP
4c2ef25f
ML
2925/* Do the card removal on suspend if card is assumed removeable
2926 * Do that in pm notifier while userspace isn't yet frozen, so we will be able
2927 to sync the card.
2928*/
8dede18e
UH
2929static int mmc_pm_notify(struct notifier_block *notify_block,
2930 unsigned long mode, void *unused)
4c2ef25f
ML
2931{
2932 struct mmc_host *host = container_of(
2933 notify_block, struct mmc_host, pm_notify);
2934 unsigned long flags;
810caddb 2935 int err = 0;
4c2ef25f
ML
2936
2937 switch (mode) {
2938 case PM_HIBERNATION_PREPARE:
2939 case PM_SUSPEND_PREPARE:
184af16b 2940 case PM_RESTORE_PREPARE:
4c2ef25f
ML
2941 spin_lock_irqsave(&host->lock, flags);
2942 host->rescan_disable = 1;
2943 spin_unlock_irqrestore(&host->lock, flags);
2944 cancel_delayed_work_sync(&host->detect);
2945
810caddb
UH
2946 if (!host->bus_ops)
2947 break;
2948
2949 /* Validate prerequisites for suspend */
2950 if (host->bus_ops->pre_suspend)
2951 err = host->bus_ops->pre_suspend(host);
5601aaf7 2952 if (!err)
4c2ef25f
ML
2953 break;
2954
0db13fc2 2955 /* Calling bus_ops->remove() with a claimed host can deadlock */
58a8a4a1 2956 host->bus_ops->remove(host);
0db13fc2 2957 mmc_claim_host(host);
4c2ef25f 2958 mmc_detach_bus(host);
7f7e4129 2959 mmc_power_off(host);
4c2ef25f
ML
2960 mmc_release_host(host);
2961 host->pm_flags = 0;
2962 break;
2963
2964 case PM_POST_SUSPEND:
2965 case PM_POST_HIBERNATION:
274476f8 2966 case PM_POST_RESTORE:
4c2ef25f
ML
2967
2968 spin_lock_irqsave(&host->lock, flags);
2969 host->rescan_disable = 0;
2970 spin_unlock_irqrestore(&host->lock, flags);
bbd43682 2971 _mmc_detect_change(host, 0, false);
4c2ef25f
ML
2972
2973 }
2974
2975 return 0;
2976}
8dede18e
UH
2977
2978void mmc_register_pm_notifier(struct mmc_host *host)
2979{
2980 host->pm_notify.notifier_call = mmc_pm_notify;
2981 register_pm_notifier(&host->pm_notify);
2982}
2983
2984void mmc_unregister_pm_notifier(struct mmc_host *host)
2985{
2986 unregister_pm_notifier(&host->pm_notify);
2987}
1da177e4
LT
2988#endif
2989
2220eedf
KD
2990/**
2991 * mmc_init_context_info() - init synchronization context
2992 * @host: mmc host
2993 *
2994 * Init struct context_info needed to implement asynchronous
2995 * request mechanism, used by mmc core, host driver and mmc requests
2996 * supplier.
2997 */
2998void mmc_init_context_info(struct mmc_host *host)
2999{
2220eedf
KD
3000 host->context_info.is_new_req = false;
3001 host->context_info.is_done_rcv = false;
3002 host->context_info.is_waiting_last_req = false;
3003 init_waitqueue_head(&host->context_info.wait);
3004}
3005
ffce2e7e
PO
3006static int __init mmc_init(void)
3007{
3008 int ret;
3009
ffce2e7e 3010 ret = mmc_register_bus();
e29a7d73 3011 if (ret)
520bd7a8 3012 return ret;
e29a7d73
PO
3013
3014 ret = mmc_register_host_class();
3015 if (ret)
3016 goto unregister_bus;
3017
3018 ret = sdio_register_bus();
3019 if (ret)
3020 goto unregister_host_class;
3021
3022 return 0;
3023
3024unregister_host_class:
3025 mmc_unregister_host_class();
3026unregister_bus:
3027 mmc_unregister_bus();
ffce2e7e
PO
3028 return ret;
3029}
3030
3031static void __exit mmc_exit(void)
3032{
e29a7d73 3033 sdio_unregister_bus();
ffce2e7e
PO
3034 mmc_unregister_host_class();
3035 mmc_unregister_bus();
ffce2e7e
PO
3036}
3037
26074962 3038subsys_initcall(mmc_init);
ffce2e7e
PO
3039module_exit(mmc_exit);
3040
1da177e4 3041MODULE_LICENSE("GPL");