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