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