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