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