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