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