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