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