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