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