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