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