mmc: card: Kill block requests if card is removed
[pandora-kernel.git] / drivers / mmc / card / block.c
1 /*
2  * Block driver for media (i.e., flash cards)
3  *
4  * Copyright 2002 Hewlett-Packard Company
5  * Copyright 2005-2008 Pierre Ossman
6  *
7  * Use consistent with the GNU GPL is permitted,
8  * provided that this copyright notice is
9  * preserved in its entirety in all copies and derived works.
10  *
11  * HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED,
12  * AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS
13  * FITNESS FOR ANY PARTICULAR PURPOSE.
14  *
15  * Many thanks to Alessandro Rubini and Jonathan Corbet!
16  *
17  * Author:  Andrew Christian
18  *          28 May 2002
19  */
20 #include <linux/moduleparam.h>
21 #include <linux/module.h>
22 #include <linux/init.h>
23
24 #include <linux/kernel.h>
25 #include <linux/fs.h>
26 #include <linux/slab.h>
27 #include <linux/errno.h>
28 #include <linux/hdreg.h>
29 #include <linux/kdev_t.h>
30 #include <linux/blkdev.h>
31 #include <linux/mutex.h>
32 #include <linux/scatterlist.h>
33 #include <linux/string_helpers.h>
34 #include <linux/delay.h>
35 #include <linux/capability.h>
36 #include <linux/compat.h>
37
38 #include <linux/mmc/ioctl.h>
39 #include <linux/mmc/card.h>
40 #include <linux/mmc/host.h>
41 #include <linux/mmc/mmc.h>
42 #include <linux/mmc/sd.h>
43
44 #include <asm/system.h>
45 #include <asm/uaccess.h>
46
47 #include "queue.h"
48
49 MODULE_ALIAS("mmc:block");
50 #ifdef MODULE_PARAM_PREFIX
51 #undef MODULE_PARAM_PREFIX
52 #endif
53 #define MODULE_PARAM_PREFIX "mmcblk."
54
55 #define INAND_CMD38_ARG_EXT_CSD  113
56 #define INAND_CMD38_ARG_ERASE    0x00
57 #define INAND_CMD38_ARG_TRIM     0x01
58 #define INAND_CMD38_ARG_SECERASE 0x80
59 #define INAND_CMD38_ARG_SECTRIM1 0x81
60 #define INAND_CMD38_ARG_SECTRIM2 0x88
61
62 static DEFINE_MUTEX(block_mutex);
63
64 /*
65  * The defaults come from config options but can be overriden by module
66  * or bootarg options.
67  */
68 static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
69
70 /*
71  * We've only got one major, so number of mmcblk devices is
72  * limited to 256 / number of minors per device.
73  */
74 static int max_devices;
75
76 /* 256 minors, so at most 256 separate devices */
77 static DECLARE_BITMAP(dev_use, 256);
78 static DECLARE_BITMAP(name_use, 256);
79
80 /*
81  * There is one mmc_blk_data per slot.
82  */
83 struct mmc_blk_data {
84         spinlock_t      lock;
85         struct gendisk  *disk;
86         struct mmc_queue queue;
87         struct list_head part;
88
89         unsigned int    flags;
90 #define MMC_BLK_CMD23   (1 << 0)        /* Can do SET_BLOCK_COUNT for multiblock */
91 #define MMC_BLK_REL_WR  (1 << 1)        /* MMC Reliable write support */
92
93         unsigned int    usage;
94         unsigned int    read_only;
95         unsigned int    part_type;
96         unsigned int    name_idx;
97         unsigned int    reset_done;
98 #define MMC_BLK_READ            BIT(0)
99 #define MMC_BLK_WRITE           BIT(1)
100 #define MMC_BLK_DISCARD         BIT(2)
101 #define MMC_BLK_SECDISCARD      BIT(3)
102
103         /*
104          * Only set in main mmc_blk_data associated
105          * with mmc_card with mmc_set_drvdata, and keeps
106          * track of the current selected device partition.
107          */
108         unsigned int    part_curr;
109         struct device_attribute force_ro;
110 };
111
112 static DEFINE_MUTEX(open_lock);
113
114 enum mmc_blk_status {
115         MMC_BLK_SUCCESS = 0,
116         MMC_BLK_PARTIAL,
117         MMC_BLK_CMD_ERR,
118         MMC_BLK_RETRY,
119         MMC_BLK_ABORT,
120         MMC_BLK_DATA_ERR,
121         MMC_BLK_ECC_ERR,
122         MMC_BLK_NOMEDIUM,
123 };
124
125 module_param(perdev_minors, int, 0444);
126 MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
127
128 static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
129 {
130         struct mmc_blk_data *md;
131
132         mutex_lock(&open_lock);
133         md = disk->private_data;
134         if (md && md->usage == 0)
135                 md = NULL;
136         if (md)
137                 md->usage++;
138         mutex_unlock(&open_lock);
139
140         return md;
141 }
142
143 static inline int mmc_get_devidx(struct gendisk *disk)
144 {
145         int devmaj = MAJOR(disk_devt(disk));
146         int devidx = MINOR(disk_devt(disk)) / perdev_minors;
147
148         if (!devmaj)
149                 devidx = disk->first_minor / perdev_minors;
150         return devidx;
151 }
152
153 static void mmc_blk_put(struct mmc_blk_data *md)
154 {
155         mutex_lock(&open_lock);
156         md->usage--;
157         if (md->usage == 0) {
158                 int devidx = mmc_get_devidx(md->disk);
159                 blk_cleanup_queue(md->queue.queue);
160
161                 __clear_bit(devidx, dev_use);
162
163                 put_disk(md->disk);
164                 kfree(md);
165         }
166         mutex_unlock(&open_lock);
167 }
168
169 static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
170                              char *buf)
171 {
172         int ret;
173         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
174
175         ret = snprintf(buf, PAGE_SIZE, "%d",
176                        get_disk_ro(dev_to_disk(dev)) ^
177                        md->read_only);
178         mmc_blk_put(md);
179         return ret;
180 }
181
182 static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
183                               const char *buf, size_t count)
184 {
185         int ret;
186         char *end;
187         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
188         unsigned long set = simple_strtoul(buf, &end, 0);
189         if (end == buf) {
190                 ret = -EINVAL;
191                 goto out;
192         }
193
194         set_disk_ro(dev_to_disk(dev), set || md->read_only);
195         ret = count;
196 out:
197         mmc_blk_put(md);
198         return ret;
199 }
200
201 static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
202 {
203         struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
204         int ret = -ENXIO;
205
206         mutex_lock(&block_mutex);
207         if (md) {
208                 if (md->usage == 2)
209                         check_disk_change(bdev);
210                 ret = 0;
211
212                 if ((mode & FMODE_WRITE) && md->read_only) {
213                         mmc_blk_put(md);
214                         ret = -EROFS;
215                 }
216         }
217         mutex_unlock(&block_mutex);
218
219         return ret;
220 }
221
222 static int mmc_blk_release(struct gendisk *disk, fmode_t mode)
223 {
224         struct mmc_blk_data *md = disk->private_data;
225
226         mutex_lock(&block_mutex);
227         mmc_blk_put(md);
228         mutex_unlock(&block_mutex);
229         return 0;
230 }
231
232 static int
233 mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
234 {
235         geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
236         geo->heads = 4;
237         geo->sectors = 16;
238         return 0;
239 }
240
241 struct mmc_blk_ioc_data {
242         struct mmc_ioc_cmd ic;
243         unsigned char *buf;
244         u64 buf_bytes;
245 };
246
247 static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
248         struct mmc_ioc_cmd __user *user)
249 {
250         struct mmc_blk_ioc_data *idata;
251         int err;
252
253         idata = kzalloc(sizeof(*idata), GFP_KERNEL);
254         if (!idata) {
255                 err = -ENOMEM;
256                 goto out;
257         }
258
259         if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
260                 err = -EFAULT;
261                 goto idata_err;
262         }
263
264         idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
265         if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
266                 err = -EOVERFLOW;
267                 goto idata_err;
268         }
269
270         if (!idata->buf_bytes)
271                 return idata;
272
273         idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
274         if (!idata->buf) {
275                 err = -ENOMEM;
276                 goto idata_err;
277         }
278
279         if (copy_from_user(idata->buf, (void __user *)(unsigned long)
280                                         idata->ic.data_ptr, idata->buf_bytes)) {
281                 err = -EFAULT;
282                 goto copy_err;
283         }
284
285         return idata;
286
287 copy_err:
288         kfree(idata->buf);
289 idata_err:
290         kfree(idata);
291 out:
292         return ERR_PTR(err);
293 }
294
295 static int mmc_blk_ioctl_cmd(struct block_device *bdev,
296         struct mmc_ioc_cmd __user *ic_ptr)
297 {
298         struct mmc_blk_ioc_data *idata;
299         struct mmc_blk_data *md;
300         struct mmc_card *card;
301         struct mmc_command cmd = {0};
302         struct mmc_data data = {0};
303         struct mmc_request mrq = {NULL};
304         struct scatterlist sg;
305         int err;
306
307         /*
308          * The caller must have CAP_SYS_RAWIO, and must be calling this on the
309          * whole block device, not on a partition.  This prevents overspray
310          * between sibling partitions.
311          */
312         if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
313                 return -EPERM;
314
315         idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
316         if (IS_ERR(idata))
317                 return PTR_ERR(idata);
318
319         md = mmc_blk_get(bdev->bd_disk);
320         if (!md) {
321                 err = -EINVAL;
322                 goto cmd_done;
323         }
324
325         card = md->queue.card;
326         if (IS_ERR(card)) {
327                 err = PTR_ERR(card);
328                 goto cmd_done;
329         }
330
331         cmd.opcode = idata->ic.opcode;
332         cmd.arg = idata->ic.arg;
333         cmd.flags = idata->ic.flags;
334
335         if (idata->buf_bytes) {
336                 data.sg = &sg;
337                 data.sg_len = 1;
338                 data.blksz = idata->ic.blksz;
339                 data.blocks = idata->ic.blocks;
340
341                 sg_init_one(data.sg, idata->buf, idata->buf_bytes);
342
343                 if (idata->ic.write_flag)
344                         data.flags = MMC_DATA_WRITE;
345                 else
346                         data.flags = MMC_DATA_READ;
347
348                 /* data.flags must already be set before doing this. */
349                 mmc_set_data_timeout(&data, card);
350
351                 /* Allow overriding the timeout_ns for empirical tuning. */
352                 if (idata->ic.data_timeout_ns)
353                         data.timeout_ns = idata->ic.data_timeout_ns;
354
355                 if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
356                         /*
357                          * Pretend this is a data transfer and rely on the
358                          * host driver to compute timeout.  When all host
359                          * drivers support cmd.cmd_timeout for R1B, this
360                          * can be changed to:
361                          *
362                          *     mrq.data = NULL;
363                          *     cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
364                          */
365                         data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
366                 }
367
368                 mrq.data = &data;
369         }
370
371         mrq.cmd = &cmd;
372
373         mmc_claim_host(card->host);
374
375         if (idata->ic.is_acmd) {
376                 err = mmc_app_cmd(card->host, card);
377                 if (err)
378                         goto cmd_rel_host;
379         }
380
381         mmc_wait_for_req(card->host, &mrq);
382
383         if (cmd.error) {
384                 dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
385                                                 __func__, cmd.error);
386                 err = cmd.error;
387                 goto cmd_rel_host;
388         }
389         if (data.error) {
390                 dev_err(mmc_dev(card->host), "%s: data error %d\n",
391                                                 __func__, data.error);
392                 err = data.error;
393                 goto cmd_rel_host;
394         }
395
396         /*
397          * According to the SD specs, some commands require a delay after
398          * issuing the command.
399          */
400         if (idata->ic.postsleep_min_us)
401                 usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
402
403         if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) {
404                 err = -EFAULT;
405                 goto cmd_rel_host;
406         }
407
408         if (!idata->ic.write_flag) {
409                 if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr,
410                                                 idata->buf, idata->buf_bytes)) {
411                         err = -EFAULT;
412                         goto cmd_rel_host;
413                 }
414         }
415
416 cmd_rel_host:
417         mmc_release_host(card->host);
418
419 cmd_done:
420         mmc_blk_put(md);
421         kfree(idata->buf);
422         kfree(idata);
423         return err;
424 }
425
426 static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
427         unsigned int cmd, unsigned long arg)
428 {
429         int ret = -EINVAL;
430         if (cmd == MMC_IOC_CMD)
431                 ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
432         return ret;
433 }
434
435 #ifdef CONFIG_COMPAT
436 static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
437         unsigned int cmd, unsigned long arg)
438 {
439         return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
440 }
441 #endif
442
443 static const struct block_device_operations mmc_bdops = {
444         .open                   = mmc_blk_open,
445         .release                = mmc_blk_release,
446         .getgeo                 = mmc_blk_getgeo,
447         .owner                  = THIS_MODULE,
448         .ioctl                  = mmc_blk_ioctl,
449 #ifdef CONFIG_COMPAT
450         .compat_ioctl           = mmc_blk_compat_ioctl,
451 #endif
452 };
453
454 static inline int mmc_blk_part_switch(struct mmc_card *card,
455                                       struct mmc_blk_data *md)
456 {
457         int ret;
458         struct mmc_blk_data *main_md = mmc_get_drvdata(card);
459
460         if (main_md->part_curr == md->part_type)
461                 return 0;
462
463         if (mmc_card_mmc(card)) {
464                 u8 part_config = card->ext_csd.part_config;
465
466                 part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
467                 part_config |= md->part_type;
468
469                 ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
470                                  EXT_CSD_PART_CONFIG, part_config,
471                                  card->ext_csd.part_time);
472                 if (ret)
473                         return ret;
474
475                 card->ext_csd.part_config = part_config;
476         }
477
478         main_md->part_curr = md->part_type;
479         return 0;
480 }
481
482 static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
483 {
484         int err;
485         u32 result;
486         __be32 *blocks;
487
488         struct mmc_request mrq = {NULL};
489         struct mmc_command cmd = {0};
490         struct mmc_data data = {0};
491         unsigned int timeout_us;
492
493         struct scatterlist sg;
494
495         cmd.opcode = MMC_APP_CMD;
496         cmd.arg = card->rca << 16;
497         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
498
499         err = mmc_wait_for_cmd(card->host, &cmd, 0);
500         if (err)
501                 return (u32)-1;
502         if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
503                 return (u32)-1;
504
505         memset(&cmd, 0, sizeof(struct mmc_command));
506
507         cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
508         cmd.arg = 0;
509         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
510
511         data.timeout_ns = card->csd.tacc_ns * 100;
512         data.timeout_clks = card->csd.tacc_clks * 100;
513
514         timeout_us = data.timeout_ns / 1000;
515         timeout_us += data.timeout_clks * 1000 /
516                 (card->host->ios.clock / 1000);
517
518         if (timeout_us > 100000) {
519                 data.timeout_ns = 100000000;
520                 data.timeout_clks = 0;
521         }
522
523         data.blksz = 4;
524         data.blocks = 1;
525         data.flags = MMC_DATA_READ;
526         data.sg = &sg;
527         data.sg_len = 1;
528
529         mrq.cmd = &cmd;
530         mrq.data = &data;
531
532         blocks = kmalloc(4, GFP_KERNEL);
533         if (!blocks)
534                 return (u32)-1;
535
536         sg_init_one(&sg, blocks, 4);
537
538         mmc_wait_for_req(card->host, &mrq);
539
540         result = ntohl(*blocks);
541         kfree(blocks);
542
543         if (cmd.error || data.error)
544                 result = (u32)-1;
545
546         return result;
547 }
548
549 static int send_stop(struct mmc_card *card, u32 *status)
550 {
551         struct mmc_command cmd = {0};
552         int err;
553
554         cmd.opcode = MMC_STOP_TRANSMISSION;
555         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
556         err = mmc_wait_for_cmd(card->host, &cmd, 5);
557         if (err == 0)
558                 *status = cmd.resp[0];
559         return err;
560 }
561
562 static int get_card_status(struct mmc_card *card, u32 *status, int retries)
563 {
564         struct mmc_command cmd = {0};
565         int err;
566
567         cmd.opcode = MMC_SEND_STATUS;
568         if (!mmc_host_is_spi(card->host))
569                 cmd.arg = card->rca << 16;
570         cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
571         err = mmc_wait_for_cmd(card->host, &cmd, retries);
572         if (err == 0)
573                 *status = cmd.resp[0];
574         return err;
575 }
576
577 #define ERR_NOMEDIUM    3
578 #define ERR_RETRY       2
579 #define ERR_ABORT       1
580 #define ERR_CONTINUE    0
581
582 static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
583         bool status_valid, u32 status)
584 {
585         switch (error) {
586         case -EILSEQ:
587                 /* response crc error, retry the r/w cmd */
588                 pr_err("%s: %s sending %s command, card status %#x\n",
589                         req->rq_disk->disk_name, "response CRC error",
590                         name, status);
591                 return ERR_RETRY;
592
593         case -ETIMEDOUT:
594                 pr_err("%s: %s sending %s command, card status %#x\n",
595                         req->rq_disk->disk_name, "timed out", name, status);
596
597                 /* If the status cmd initially failed, retry the r/w cmd */
598                 if (!status_valid)
599                         return ERR_RETRY;
600
601                 /*
602                  * If it was a r/w cmd crc error, or illegal command
603                  * (eg, issued in wrong state) then retry - we should
604                  * have corrected the state problem above.
605                  */
606                 if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND))
607                         return ERR_RETRY;
608
609                 /* Otherwise abort the command */
610                 return ERR_ABORT;
611
612         default:
613                 /* We don't understand the error code the driver gave us */
614                 pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
615                        req->rq_disk->disk_name, error, status);
616                 return ERR_ABORT;
617         }
618 }
619
620 /*
621  * Initial r/w and stop cmd error recovery.
622  * We don't know whether the card received the r/w cmd or not, so try to
623  * restore things back to a sane state.  Essentially, we do this as follows:
624  * - Obtain card status.  If the first attempt to obtain card status fails,
625  *   the status word will reflect the failed status cmd, not the failed
626  *   r/w cmd.  If we fail to obtain card status, it suggests we can no
627  *   longer communicate with the card.
628  * - Check the card state.  If the card received the cmd but there was a
629  *   transient problem with the response, it might still be in a data transfer
630  *   mode.  Try to send it a stop command.  If this fails, we can't recover.
631  * - If the r/w cmd failed due to a response CRC error, it was probably
632  *   transient, so retry the cmd.
633  * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
634  * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
635  *   illegal cmd, retry.
636  * Otherwise we don't understand what happened, so abort.
637  */
638 static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
639         struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
640 {
641         bool prev_cmd_status_valid = true;
642         u32 status, stop_status = 0;
643         int err, retry;
644
645         if (mmc_card_removed(card))
646                 return ERR_NOMEDIUM;
647
648         /*
649          * Try to get card status which indicates both the card state
650          * and why there was no response.  If the first attempt fails,
651          * we can't be sure the returned status is for the r/w command.
652          */
653         for (retry = 2; retry >= 0; retry--) {
654                 err = get_card_status(card, &status, 0);
655                 if (!err)
656                         break;
657
658                 prev_cmd_status_valid = false;
659                 pr_err("%s: error %d sending status command, %sing\n",
660                        req->rq_disk->disk_name, err, retry ? "retry" : "abort");
661         }
662
663         /* We couldn't get a response from the card.  Give up. */
664         if (err) {
665                 /* Check if the card is removed */
666                 if (mmc_detect_card_removed(card->host))
667                         return ERR_NOMEDIUM;
668                 return ERR_ABORT;
669         }
670
671         /* Flag ECC errors */
672         if ((status & R1_CARD_ECC_FAILED) ||
673             (brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
674             (brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
675                 *ecc_err = 1;
676
677         /* Flag General errors */
678         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
679                 if ((status & R1_ERROR) ||
680                         (brq->stop.resp[0] & R1_ERROR)) {
681                         pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
682                                req->rq_disk->disk_name, __func__,
683                                brq->stop.resp[0], status);
684                         *gen_err = 1;
685                 }
686
687         /*
688          * Check the current card state.  If it is in some data transfer
689          * mode, tell it to stop (and hopefully transition back to TRAN.)
690          */
691         if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
692             R1_CURRENT_STATE(status) == R1_STATE_RCV) {
693                 err = send_stop(card, &stop_status);
694                 if (err)
695                         pr_err("%s: error %d sending stop command\n",
696                                req->rq_disk->disk_name, err);
697
698                 /*
699                  * If the stop cmd also timed out, the card is probably
700                  * not present, so abort.  Other errors are bad news too.
701                  */
702                 if (err)
703                         return ERR_ABORT;
704                 if (stop_status & R1_CARD_ECC_FAILED)
705                         *ecc_err = 1;
706                 if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
707                         if (stop_status & R1_ERROR) {
708                                 pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
709                                        req->rq_disk->disk_name, __func__,
710                                        stop_status);
711                                 *gen_err = 1;
712                         }
713         }
714
715         /* Check for set block count errors */
716         if (brq->sbc.error)
717                 return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
718                                 prev_cmd_status_valid, status);
719
720         /* Check for r/w command errors */
721         if (brq->cmd.error)
722                 return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
723                                 prev_cmd_status_valid, status);
724
725         /* Data errors */
726         if (!brq->stop.error)
727                 return ERR_CONTINUE;
728
729         /* Now for stop errors.  These aren't fatal to the transfer. */
730         pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
731                req->rq_disk->disk_name, brq->stop.error,
732                brq->cmd.resp[0], status);
733
734         /*
735          * Subsitute in our own stop status as this will give the error
736          * state which happened during the execution of the r/w command.
737          */
738         if (stop_status) {
739                 brq->stop.resp[0] = stop_status;
740                 brq->stop.error = 0;
741         }
742         return ERR_CONTINUE;
743 }
744
745 static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
746                          int type)
747 {
748         int err;
749
750         if (md->reset_done & type)
751                 return -EEXIST;
752
753         md->reset_done |= type;
754         err = mmc_hw_reset(host);
755         /* Ensure we switch back to the correct partition */
756         if (err != -EOPNOTSUPP) {
757                 struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
758                 int part_err;
759
760                 main_md->part_curr = main_md->part_type;
761                 part_err = mmc_blk_part_switch(host->card, md);
762                 if (part_err) {
763                         /*
764                          * We have failed to get back into the correct
765                          * partition, so we need to abort the whole request.
766                          */
767                         return -ENODEV;
768                 }
769         }
770         return err;
771 }
772
773 static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
774 {
775         md->reset_done &= ~type;
776 }
777
778 static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
779 {
780         struct mmc_blk_data *md = mq->data;
781         struct mmc_card *card = md->queue.card;
782         unsigned int from, nr, arg;
783         int err = 0, type = MMC_BLK_DISCARD;
784
785         if (!mmc_can_erase(card)) {
786                 err = -EOPNOTSUPP;
787                 goto out;
788         }
789
790         from = blk_rq_pos(req);
791         nr = blk_rq_sectors(req);
792
793         if (mmc_can_discard(card))
794                 arg = MMC_DISCARD_ARG;
795         else if (mmc_can_trim(card))
796                 arg = MMC_TRIM_ARG;
797         else
798                 arg = MMC_ERASE_ARG;
799 retry:
800         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
801                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
802                                  INAND_CMD38_ARG_EXT_CSD,
803                                  arg == MMC_TRIM_ARG ?
804                                  INAND_CMD38_ARG_TRIM :
805                                  INAND_CMD38_ARG_ERASE,
806                                  0);
807                 if (err)
808                         goto out;
809         }
810         err = mmc_erase(card, from, nr, arg);
811 out:
812         if (err == -EIO && !mmc_blk_reset(md, card->host, type))
813                 goto retry;
814         if (!err)
815                 mmc_blk_reset_success(md, type);
816         spin_lock_irq(&md->lock);
817         __blk_end_request(req, err, blk_rq_bytes(req));
818         spin_unlock_irq(&md->lock);
819
820         return err ? 0 : 1;
821 }
822
823 static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
824                                        struct request *req)
825 {
826         struct mmc_blk_data *md = mq->data;
827         struct mmc_card *card = md->queue.card;
828         unsigned int from, nr, arg, trim_arg, erase_arg;
829         int err = 0, type = MMC_BLK_SECDISCARD;
830
831         if (!(mmc_can_secure_erase_trim(card) || mmc_can_sanitize(card))) {
832                 err = -EOPNOTSUPP;
833                 goto out;
834         }
835
836         from = blk_rq_pos(req);
837         nr = blk_rq_sectors(req);
838
839         /* The sanitize operation is supported at v4.5 only */
840         if (mmc_can_sanitize(card)) {
841                 erase_arg = MMC_ERASE_ARG;
842                 trim_arg = MMC_TRIM_ARG;
843         } else {
844                 erase_arg = MMC_SECURE_ERASE_ARG;
845                 trim_arg = MMC_SECURE_TRIM1_ARG;
846         }
847
848         if (mmc_erase_group_aligned(card, from, nr))
849                 arg = erase_arg;
850         else if (mmc_can_trim(card))
851                 arg = trim_arg;
852         else {
853                 err = -EINVAL;
854                 goto out;
855         }
856 retry:
857         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
858                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
859                                  INAND_CMD38_ARG_EXT_CSD,
860                                  arg == MMC_SECURE_TRIM1_ARG ?
861                                  INAND_CMD38_ARG_SECTRIM1 :
862                                  INAND_CMD38_ARG_SECERASE,
863                                  0);
864                 if (err)
865                         goto out_retry;
866         }
867
868         err = mmc_erase(card, from, nr, arg);
869         if (err == -EIO)
870                 goto out_retry;
871         if (err)
872                 goto out;
873
874         if (arg == MMC_SECURE_TRIM1_ARG) {
875                 if (card->quirks & MMC_QUIRK_INAND_CMD38) {
876                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
877                                          INAND_CMD38_ARG_EXT_CSD,
878                                          INAND_CMD38_ARG_SECTRIM2,
879                                          0);
880                         if (err)
881                                 goto out_retry;
882                 }
883
884                 err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
885                 if (err == -EIO)
886                         goto out_retry;
887                 if (err)
888                         goto out;
889         }
890
891         if (mmc_can_sanitize(card))
892                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
893                                  EXT_CSD_SANITIZE_START, 1, 0);
894 out_retry:
895         if (err && !mmc_blk_reset(md, card->host, type))
896                 goto retry;
897         if (!err)
898                 mmc_blk_reset_success(md, type);
899 out:
900         spin_lock_irq(&md->lock);
901         __blk_end_request(req, err, blk_rq_bytes(req));
902         spin_unlock_irq(&md->lock);
903
904         return err ? 0 : 1;
905 }
906
907 static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
908 {
909         struct mmc_blk_data *md = mq->data;
910         struct mmc_card *card = md->queue.card;
911         int ret = 0;
912
913         ret = mmc_flush_cache(card);
914         if (ret)
915                 ret = -EIO;
916
917         spin_lock_irq(&md->lock);
918         __blk_end_request_all(req, ret);
919         spin_unlock_irq(&md->lock);
920
921         return ret ? 0 : 1;
922 }
923
924 /*
925  * Reformat current write as a reliable write, supporting
926  * both legacy and the enhanced reliable write MMC cards.
927  * In each transfer we'll handle only as much as a single
928  * reliable write can handle, thus finish the request in
929  * partial completions.
930  */
931 static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
932                                     struct mmc_card *card,
933                                     struct request *req)
934 {
935         if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
936                 /* Legacy mode imposes restrictions on transfers. */
937                 if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
938                         brq->data.blocks = 1;
939
940                 if (brq->data.blocks > card->ext_csd.rel_sectors)
941                         brq->data.blocks = card->ext_csd.rel_sectors;
942                 else if (brq->data.blocks < card->ext_csd.rel_sectors)
943                         brq->data.blocks = 1;
944         }
945 }
946
947 #define CMD_ERRORS                                                      \
948         (R1_OUT_OF_RANGE |      /* Command argument out of range */     \
949          R1_ADDRESS_ERROR |     /* Misaligned address */                \
950          R1_BLOCK_LEN_ERROR |   /* Transferred block length incorrect */\
951          R1_WP_VIOLATION |      /* Tried to write to protected block */ \
952          R1_CC_ERROR |          /* Card controller error */             \
953          R1_ERROR)              /* General/unknown error */
954
955 static int mmc_blk_err_check(struct mmc_card *card,
956                              struct mmc_async_req *areq)
957 {
958         struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
959                                                     mmc_active);
960         struct mmc_blk_request *brq = &mq_mrq->brq;
961         struct request *req = mq_mrq->req;
962         int ecc_err = 0, gen_err = 0;
963
964         /*
965          * sbc.error indicates a problem with the set block count
966          * command.  No data will have been transferred.
967          *
968          * cmd.error indicates a problem with the r/w command.  No
969          * data will have been transferred.
970          *
971          * stop.error indicates a problem with the stop command.  Data
972          * may have been transferred, or may still be transferring.
973          */
974         if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
975             brq->data.error) {
976                 switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
977                 case ERR_RETRY:
978                         return MMC_BLK_RETRY;
979                 case ERR_ABORT:
980                         return MMC_BLK_ABORT;
981                 case ERR_NOMEDIUM:
982                         return MMC_BLK_NOMEDIUM;
983                 case ERR_CONTINUE:
984                         break;
985                 }
986         }
987
988         /*
989          * Check for errors relating to the execution of the
990          * initial command - such as address errors.  No data
991          * has been transferred.
992          */
993         if (brq->cmd.resp[0] & CMD_ERRORS) {
994                 pr_err("%s: r/w command failed, status = %#x\n",
995                        req->rq_disk->disk_name, brq->cmd.resp[0]);
996                 return MMC_BLK_ABORT;
997         }
998
999         /*
1000          * Everything else is either success, or a data error of some
1001          * kind.  If it was a write, we may have transitioned to
1002          * program mode, which we have to wait for it to complete.
1003          */
1004         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
1005                 u32 status;
1006
1007                 /* Check stop command response */
1008                 if (brq->stop.resp[0] & R1_ERROR) {
1009                         pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
1010                                req->rq_disk->disk_name, __func__,
1011                                brq->stop.resp[0]);
1012                         gen_err = 1;
1013                 }
1014
1015                 do {
1016                         int err = get_card_status(card, &status, 5);
1017                         if (err) {
1018                                 pr_err("%s: error %d requesting status\n",
1019                                        req->rq_disk->disk_name, err);
1020                                 return MMC_BLK_CMD_ERR;
1021                         }
1022
1023                         if (status & R1_ERROR) {
1024                                 pr_err("%s: %s: general error sending status command, card status %#x\n",
1025                                        req->rq_disk->disk_name, __func__,
1026                                        status);
1027                                 gen_err = 1;
1028                         }
1029
1030                         /*
1031                          * Some cards mishandle the status bits,
1032                          * so make sure to check both the busy
1033                          * indication and the card state.
1034                          */
1035                 } while (!(status & R1_READY_FOR_DATA) ||
1036                          (R1_CURRENT_STATE(status) == R1_STATE_PRG));
1037         }
1038
1039         /* if general error occurs, retry the write operation. */
1040         if (gen_err) {
1041                 pr_warning("%s: retrying write for general error\n",
1042                                 req->rq_disk->disk_name);
1043                 return MMC_BLK_RETRY;
1044         }
1045
1046         if (brq->data.error) {
1047                 pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
1048                        req->rq_disk->disk_name, brq->data.error,
1049                        (unsigned)blk_rq_pos(req),
1050                        (unsigned)blk_rq_sectors(req),
1051                        brq->cmd.resp[0], brq->stop.resp[0]);
1052
1053                 if (rq_data_dir(req) == READ) {
1054                         if (ecc_err)
1055                                 return MMC_BLK_ECC_ERR;
1056                         return MMC_BLK_DATA_ERR;
1057                 } else {
1058                         return MMC_BLK_CMD_ERR;
1059                 }
1060         }
1061
1062         if (!brq->data.bytes_xfered)
1063                 return MMC_BLK_RETRY;
1064
1065         if (blk_rq_bytes(req) != brq->data.bytes_xfered)
1066                 return MMC_BLK_PARTIAL;
1067
1068         return MMC_BLK_SUCCESS;
1069 }
1070
1071 static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1072                                struct mmc_card *card,
1073                                int disable_multi,
1074                                struct mmc_queue *mq)
1075 {
1076         u32 readcmd, writecmd;
1077         struct mmc_blk_request *brq = &mqrq->brq;
1078         struct request *req = mqrq->req;
1079         struct mmc_blk_data *md = mq->data;
1080
1081         /*
1082          * Reliable writes are used to implement Forced Unit Access and
1083          * REQ_META accesses, and are supported only on MMCs.
1084          *
1085          * XXX: this really needs a good explanation of why REQ_META
1086          * is treated special.
1087          */
1088         bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
1089                           (req->cmd_flags & REQ_META)) &&
1090                 (rq_data_dir(req) == WRITE) &&
1091                 (md->flags & MMC_BLK_REL_WR);
1092
1093         memset(brq, 0, sizeof(struct mmc_blk_request));
1094         brq->mrq.cmd = &brq->cmd;
1095         brq->mrq.data = &brq->data;
1096
1097         brq->cmd.arg = blk_rq_pos(req);
1098         if (!mmc_card_blockaddr(card))
1099                 brq->cmd.arg <<= 9;
1100         brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1101         brq->data.blksz = 512;
1102         brq->stop.opcode = MMC_STOP_TRANSMISSION;
1103         brq->stop.arg = 0;
1104         brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1105         brq->data.blocks = blk_rq_sectors(req);
1106
1107         /*
1108          * The block layer doesn't support all sector count
1109          * restrictions, so we need to be prepared for too big
1110          * requests.
1111          */
1112         if (brq->data.blocks > card->host->max_blk_count)
1113                 brq->data.blocks = card->host->max_blk_count;
1114
1115         if (brq->data.blocks > 1) {
1116                 /*
1117                  * After a read error, we redo the request one sector
1118                  * at a time in order to accurately determine which
1119                  * sectors can be read successfully.
1120                  */
1121                 if (disable_multi)
1122                         brq->data.blocks = 1;
1123
1124                 /* Some controllers can't do multiblock reads due to hw bugs */
1125                 if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
1126                     rq_data_dir(req) == READ)
1127                         brq->data.blocks = 1;
1128         }
1129
1130         if (brq->data.blocks > 1 || do_rel_wr) {
1131                 /* SPI multiblock writes terminate using a special
1132                  * token, not a STOP_TRANSMISSION request.
1133                  */
1134                 if (!mmc_host_is_spi(card->host) ||
1135                     rq_data_dir(req) == READ)
1136                         brq->mrq.stop = &brq->stop;
1137                 readcmd = MMC_READ_MULTIPLE_BLOCK;
1138                 writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1139         } else {
1140                 brq->mrq.stop = NULL;
1141                 readcmd = MMC_READ_SINGLE_BLOCK;
1142                 writecmd = MMC_WRITE_BLOCK;
1143         }
1144         if (rq_data_dir(req) == READ) {
1145                 brq->cmd.opcode = readcmd;
1146                 brq->data.flags |= MMC_DATA_READ;
1147         } else {
1148                 brq->cmd.opcode = writecmd;
1149                 brq->data.flags |= MMC_DATA_WRITE;
1150         }
1151
1152         if (do_rel_wr)
1153                 mmc_apply_rel_rw(brq, card, req);
1154
1155         /*
1156          * Pre-defined multi-block transfers are preferable to
1157          * open ended-ones (and necessary for reliable writes).
1158          * However, it is not sufficient to just send CMD23,
1159          * and avoid the final CMD12, as on an error condition
1160          * CMD12 (stop) needs to be sent anyway. This, coupled
1161          * with Auto-CMD23 enhancements provided by some
1162          * hosts, means that the complexity of dealing
1163          * with this is best left to the host. If CMD23 is
1164          * supported by card and host, we'll fill sbc in and let
1165          * the host deal with handling it correctly. This means
1166          * that for hosts that don't expose MMC_CAP_CMD23, no
1167          * change of behavior will be observed.
1168          *
1169          * N.B: Some MMC cards experience perf degradation.
1170          * We'll avoid using CMD23-bounded multiblock writes for
1171          * these, while retaining features like reliable writes.
1172          */
1173
1174         if ((md->flags & MMC_BLK_CMD23) &&
1175             mmc_op_multi(brq->cmd.opcode) &&
1176             (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23))) {
1177                 brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1178                 brq->sbc.arg = brq->data.blocks |
1179                         (do_rel_wr ? (1 << 31) : 0);
1180                 brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1181                 brq->mrq.sbc = &brq->sbc;
1182         }
1183
1184         mmc_set_data_timeout(&brq->data, card);
1185
1186         brq->data.sg = mqrq->sg;
1187         brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1188
1189         /*
1190          * Adjust the sg list so it is the same size as the
1191          * request.
1192          */
1193         if (brq->data.blocks != blk_rq_sectors(req)) {
1194                 int i, data_size = brq->data.blocks << 9;
1195                 struct scatterlist *sg;
1196
1197                 for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1198                         data_size -= sg->length;
1199                         if (data_size <= 0) {
1200                                 sg->length += data_size;
1201                                 i++;
1202                                 break;
1203                         }
1204                 }
1205                 brq->data.sg_len = i;
1206         }
1207
1208         mqrq->mmc_active.mrq = &brq->mrq;
1209         mqrq->mmc_active.err_check = mmc_blk_err_check;
1210
1211         mmc_queue_bounce_pre(mqrq);
1212 }
1213
1214 static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
1215                            struct mmc_blk_request *brq, struct request *req,
1216                            int ret)
1217 {
1218         /*
1219          * If this is an SD card and we're writing, we can first
1220          * mark the known good sectors as ok.
1221          *
1222          * If the card is not SD, we can still ok written sectors
1223          * as reported by the controller (which might be less than
1224          * the real number of written sectors, but never more).
1225          */
1226         if (mmc_card_sd(card)) {
1227                 u32 blocks;
1228
1229                 blocks = mmc_sd_num_wr_blocks(card);
1230                 if (blocks != (u32)-1) {
1231                         spin_lock_irq(&md->lock);
1232                         ret = __blk_end_request(req, 0, blocks << 9);
1233                         spin_unlock_irq(&md->lock);
1234                 }
1235         } else {
1236                 spin_lock_irq(&md->lock);
1237                 ret = __blk_end_request(req, 0, brq->data.bytes_xfered);
1238                 spin_unlock_irq(&md->lock);
1239         }
1240         return ret;
1241 }
1242
1243 static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
1244 {
1245         struct mmc_blk_data *md = mq->data;
1246         struct mmc_card *card = md->queue.card;
1247         struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
1248         int ret = 1, disable_multi = 0, retry = 0, type;
1249         enum mmc_blk_status status;
1250         struct mmc_queue_req *mq_rq;
1251         struct request *req;
1252         struct mmc_async_req *areq;
1253
1254         if (!rqc && !mq->mqrq_prev->req)
1255                 return 0;
1256
1257         do {
1258                 if (rqc) {
1259                         mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1260                         areq = &mq->mqrq_cur->mmc_active;
1261                 } else
1262                         areq = NULL;
1263                 areq = mmc_start_req(card->host, areq, (int *) &status);
1264                 if (!areq)
1265                         return 0;
1266
1267                 mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
1268                 brq = &mq_rq->brq;
1269                 req = mq_rq->req;
1270                 type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1271                 mmc_queue_bounce_post(mq_rq);
1272
1273                 switch (status) {
1274                 case MMC_BLK_SUCCESS:
1275                 case MMC_BLK_PARTIAL:
1276                         /*
1277                          * A block was successfully transferred.
1278                          */
1279                         mmc_blk_reset_success(md, type);
1280                         spin_lock_irq(&md->lock);
1281                         ret = __blk_end_request(req, 0,
1282                                                 brq->data.bytes_xfered);
1283                         spin_unlock_irq(&md->lock);
1284                         /*
1285                          * If the blk_end_request function returns non-zero even
1286                          * though all data has been transferred and no errors
1287                          * were returned by the host controller, it's a bug.
1288                          */
1289                         if (status == MMC_BLK_SUCCESS && ret) {
1290                                 pr_err("%s BUG rq_tot %d d_xfer %d\n",
1291                                        __func__, blk_rq_bytes(req),
1292                                        brq->data.bytes_xfered);
1293                                 rqc = NULL;
1294                                 goto cmd_abort;
1295                         }
1296                         break;
1297                 case MMC_BLK_CMD_ERR:
1298                         ret = mmc_blk_cmd_err(md, card, brq, req, ret);
1299                         if (!mmc_blk_reset(md, card->host, type))
1300                                 break;
1301                         goto cmd_abort;
1302                 case MMC_BLK_RETRY:
1303                         if (retry++ < 5)
1304                                 break;
1305                         /* Fall through */
1306                 case MMC_BLK_ABORT:
1307                         if (!mmc_blk_reset(md, card->host, type))
1308                                 break;
1309                         goto cmd_abort;
1310                 case MMC_BLK_DATA_ERR: {
1311                         int err;
1312
1313                         err = mmc_blk_reset(md, card->host, type);
1314                         if (!err)
1315                                 break;
1316                         if (err == -ENODEV)
1317                                 goto cmd_abort;
1318                         /* Fall through */
1319                 }
1320                 case MMC_BLK_ECC_ERR:
1321                         if (brq->data.blocks > 1) {
1322                                 /* Redo read one sector at a time */
1323                                 pr_warning("%s: retrying using single block read\n",
1324                                            req->rq_disk->disk_name);
1325                                 disable_multi = 1;
1326                                 break;
1327                         }
1328                         /*
1329                          * After an error, we redo I/O one sector at a
1330                          * time, so we only reach here after trying to
1331                          * read a single sector.
1332                          */
1333                         spin_lock_irq(&md->lock);
1334                         ret = __blk_end_request(req, -EIO,
1335                                                 brq->data.blksz);
1336                         spin_unlock_irq(&md->lock);
1337                         if (!ret)
1338                                 goto start_new_req;
1339                         break;
1340                 case MMC_BLK_NOMEDIUM:
1341                         goto cmd_abort;
1342                 }
1343
1344                 if (ret) {
1345                         /*
1346                          * In case of a incomplete request
1347                          * prepare it again and resend.
1348                          */
1349                         mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq);
1350                         mmc_start_req(card->host, &mq_rq->mmc_active, NULL);
1351                 }
1352         } while (ret);
1353
1354         return 1;
1355
1356  cmd_abort:
1357         spin_lock_irq(&md->lock);
1358         if (mmc_card_removed(card))
1359                 req->cmd_flags |= REQ_QUIET;
1360         while (ret)
1361                 ret = __blk_end_request(req, -EIO, blk_rq_cur_bytes(req));
1362         spin_unlock_irq(&md->lock);
1363
1364  start_new_req:
1365         if (rqc) {
1366                 mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1367                 mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL);
1368         }
1369
1370         return 0;
1371 }
1372
1373 static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
1374 {
1375         int ret;
1376         struct mmc_blk_data *md = mq->data;
1377         struct mmc_card *card = md->queue.card;
1378
1379         if (req && !mq->mqrq_prev->req)
1380                 /* claim host only for the first request */
1381                 mmc_claim_host(card->host);
1382
1383         ret = mmc_blk_part_switch(card, md);
1384         if (ret) {
1385                 if (req) {
1386                         spin_lock_irq(&md->lock);
1387                         __blk_end_request_all(req, -EIO);
1388                         spin_unlock_irq(&md->lock);
1389                 }
1390                 ret = 0;
1391                 goto out;
1392         }
1393
1394         if (req && req->cmd_flags & REQ_DISCARD) {
1395                 /* complete ongoing async transfer before issuing discard */
1396                 if (card->host->areq)
1397                         mmc_blk_issue_rw_rq(mq, NULL);
1398                 if (req->cmd_flags & REQ_SECURE &&
1399                         !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
1400                         ret = mmc_blk_issue_secdiscard_rq(mq, req);
1401                 else
1402                         ret = mmc_blk_issue_discard_rq(mq, req);
1403         } else if (req && req->cmd_flags & REQ_FLUSH) {
1404                 /* complete ongoing async transfer before issuing flush */
1405                 if (card->host->areq)
1406                         mmc_blk_issue_rw_rq(mq, NULL);
1407                 ret = mmc_blk_issue_flush(mq, req);
1408         } else {
1409                 ret = mmc_blk_issue_rw_rq(mq, req);
1410         }
1411
1412 out:
1413         if (!req)
1414                 /* release host only when there are no more requests */
1415                 mmc_release_host(card->host);
1416         return ret;
1417 }
1418
1419 static inline int mmc_blk_readonly(struct mmc_card *card)
1420 {
1421         return mmc_card_readonly(card) ||
1422                !(card->csd.cmdclass & CCC_BLOCK_WRITE);
1423 }
1424
1425 static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
1426                                               struct device *parent,
1427                                               sector_t size,
1428                                               bool default_ro,
1429                                               const char *subname)
1430 {
1431         struct mmc_blk_data *md;
1432         int devidx, ret;
1433
1434         devidx = find_first_zero_bit(dev_use, max_devices);
1435         if (devidx >= max_devices)
1436                 return ERR_PTR(-ENOSPC);
1437         __set_bit(devidx, dev_use);
1438
1439         md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
1440         if (!md) {
1441                 ret = -ENOMEM;
1442                 goto out;
1443         }
1444
1445         /*
1446          * !subname implies we are creating main mmc_blk_data that will be
1447          * associated with mmc_card with mmc_set_drvdata. Due to device
1448          * partitions, devidx will not coincide with a per-physical card
1449          * index anymore so we keep track of a name index.
1450          */
1451         if (!subname) {
1452                 md->name_idx = find_first_zero_bit(name_use, max_devices);
1453                 __set_bit(md->name_idx, name_use);
1454         }
1455         else
1456                 md->name_idx = ((struct mmc_blk_data *)
1457                                 dev_to_disk(parent)->private_data)->name_idx;
1458
1459         /*
1460          * Set the read-only status based on the supported commands
1461          * and the write protect switch.
1462          */
1463         md->read_only = mmc_blk_readonly(card);
1464
1465         md->disk = alloc_disk(perdev_minors);
1466         if (md->disk == NULL) {
1467                 ret = -ENOMEM;
1468                 goto err_kfree;
1469         }
1470
1471         spin_lock_init(&md->lock);
1472         INIT_LIST_HEAD(&md->part);
1473         md->usage = 1;
1474
1475         ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
1476         if (ret)
1477                 goto err_putdisk;
1478
1479         md->queue.issue_fn = mmc_blk_issue_rq;
1480         md->queue.data = md;
1481
1482         md->disk->major = MMC_BLOCK_MAJOR;
1483         md->disk->first_minor = devidx * perdev_minors;
1484         md->disk->fops = &mmc_bdops;
1485         md->disk->private_data = md;
1486         md->disk->queue = md->queue.queue;
1487         md->disk->driverfs_dev = parent;
1488         set_disk_ro(md->disk, md->read_only || default_ro);
1489
1490         /*
1491          * As discussed on lkml, GENHD_FL_REMOVABLE should:
1492          *
1493          * - be set for removable media with permanent block devices
1494          * - be unset for removable block devices with permanent media
1495          *
1496          * Since MMC block devices clearly fall under the second
1497          * case, we do not set GENHD_FL_REMOVABLE.  Userspace
1498          * should use the block device creation/destruction hotplug
1499          * messages to tell when the card is present.
1500          */
1501
1502         snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
1503                  "mmcblk%d%s", md->name_idx, subname ? subname : "");
1504
1505         blk_queue_logical_block_size(md->queue.queue, 512);
1506         set_capacity(md->disk, size);
1507
1508         if (mmc_host_cmd23(card->host)) {
1509                 if (mmc_card_mmc(card) ||
1510                     (mmc_card_sd(card) &&
1511                      card->scr.cmds & SD_SCR_CMD23_SUPPORT))
1512                         md->flags |= MMC_BLK_CMD23;
1513         }
1514
1515         if (mmc_card_mmc(card) &&
1516             md->flags & MMC_BLK_CMD23 &&
1517             ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
1518              card->ext_csd.rel_sectors)) {
1519                 md->flags |= MMC_BLK_REL_WR;
1520                 blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
1521         }
1522
1523         return md;
1524
1525  err_putdisk:
1526         put_disk(md->disk);
1527  err_kfree:
1528         kfree(md);
1529  out:
1530         return ERR_PTR(ret);
1531 }
1532
1533 static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
1534 {
1535         sector_t size;
1536         struct mmc_blk_data *md;
1537
1538         if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
1539                 /*
1540                  * The EXT_CSD sector count is in number or 512 byte
1541                  * sectors.
1542                  */
1543                 size = card->ext_csd.sectors;
1544         } else {
1545                 /*
1546                  * The CSD capacity field is in units of read_blkbits.
1547                  * set_capacity takes units of 512 bytes.
1548                  */
1549                 size = card->csd.capacity << (card->csd.read_blkbits - 9);
1550         }
1551
1552         md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL);
1553         return md;
1554 }
1555
1556 static int mmc_blk_alloc_part(struct mmc_card *card,
1557                               struct mmc_blk_data *md,
1558                               unsigned int part_type,
1559                               sector_t size,
1560                               bool default_ro,
1561                               const char *subname)
1562 {
1563         char cap_str[10];
1564         struct mmc_blk_data *part_md;
1565
1566         part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
1567                                     subname);
1568         if (IS_ERR(part_md))
1569                 return PTR_ERR(part_md);
1570         part_md->part_type = part_type;
1571         list_add(&part_md->part, &md->part);
1572
1573         string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
1574                         cap_str, sizeof(cap_str));
1575         pr_info("%s: %s %s partition %u %s\n",
1576                part_md->disk->disk_name, mmc_card_id(card),
1577                mmc_card_name(card), part_md->part_type, cap_str);
1578         return 0;
1579 }
1580
1581 /* MMC Physical partitions consist of two boot partitions and
1582  * up to four general purpose partitions.
1583  * For each partition enabled in EXT_CSD a block device will be allocatedi
1584  * to provide access to the partition.
1585  */
1586
1587 static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
1588 {
1589         int idx, ret = 0;
1590
1591         if (!mmc_card_mmc(card))
1592                 return 0;
1593
1594         for (idx = 0; idx < card->nr_parts; idx++) {
1595                 if (card->part[idx].size) {
1596                         ret = mmc_blk_alloc_part(card, md,
1597                                 card->part[idx].part_cfg,
1598                                 card->part[idx].size >> 9,
1599                                 card->part[idx].force_ro,
1600                                 card->part[idx].name);
1601                         if (ret)
1602                                 return ret;
1603                 }
1604         }
1605
1606         return ret;
1607 }
1608
1609 static int
1610 mmc_blk_set_blksize(struct mmc_blk_data *md, struct mmc_card *card)
1611 {
1612         int err;
1613
1614         mmc_claim_host(card->host);
1615         err = mmc_set_blocklen(card, 512);
1616         mmc_release_host(card->host);
1617
1618         if (err) {
1619                 pr_err("%s: unable to set block size to 512: %d\n",
1620                         md->disk->disk_name, err);
1621                 return -EINVAL;
1622         }
1623
1624         return 0;
1625 }
1626
1627 static void mmc_blk_remove_req(struct mmc_blk_data *md)
1628 {
1629         if (md) {
1630                 if (md->disk->flags & GENHD_FL_UP) {
1631                         device_remove_file(disk_to_dev(md->disk), &md->force_ro);
1632
1633                         /* Stop new requests from getting into the queue */
1634                         del_gendisk(md->disk);
1635                 }
1636
1637                 /* Then flush out any already in there */
1638                 mmc_cleanup_queue(&md->queue);
1639                 mmc_blk_put(md);
1640         }
1641 }
1642
1643 static void mmc_blk_remove_parts(struct mmc_card *card,
1644                                  struct mmc_blk_data *md)
1645 {
1646         struct list_head *pos, *q;
1647         struct mmc_blk_data *part_md;
1648
1649         __clear_bit(md->name_idx, name_use);
1650         list_for_each_safe(pos, q, &md->part) {
1651                 part_md = list_entry(pos, struct mmc_blk_data, part);
1652                 list_del(pos);
1653                 mmc_blk_remove_req(part_md);
1654         }
1655 }
1656
1657 static int mmc_add_disk(struct mmc_blk_data *md)
1658 {
1659         int ret;
1660
1661         add_disk(md->disk);
1662         md->force_ro.show = force_ro_show;
1663         md->force_ro.store = force_ro_store;
1664         sysfs_attr_init(&md->force_ro.attr);
1665         md->force_ro.attr.name = "force_ro";
1666         md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
1667         ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
1668         if (ret)
1669                 del_gendisk(md->disk);
1670
1671         return ret;
1672 }
1673
1674 #define CID_MANFID_SAMSUNG      0x15
1675
1676 static const struct mmc_fixup blk_fixups[] =
1677 {
1678         MMC_FIXUP("SEM02G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1679         MMC_FIXUP("SEM04G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1680         MMC_FIXUP("SEM08G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1681         MMC_FIXUP("SEM16G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1682         MMC_FIXUP("SEM32G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1683
1684         /*
1685          * Some MMC cards experience performance degradation with CMD23
1686          * instead of CMD12-bounded multiblock transfers. For now we'll
1687          * black list what's bad...
1688          * - Certain Toshiba cards.
1689          *
1690          * N.B. This doesn't affect SD cards.
1691          */
1692         MMC_FIXUP("MMC08G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
1693                   MMC_QUIRK_BLK_NO_CMD23),
1694         MMC_FIXUP("MMC16G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
1695                   MMC_QUIRK_BLK_NO_CMD23),
1696         MMC_FIXUP("MMC32G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
1697                   MMC_QUIRK_BLK_NO_CMD23),
1698
1699         /*
1700          * Some Micron MMC cards needs longer data read timeout than
1701          * indicated in CSD.
1702          */
1703         MMC_FIXUP(CID_NAME_ANY, 0x13, 0x200, add_quirk_mmc,
1704                   MMC_QUIRK_LONG_READ_TIME),
1705
1706         /*
1707          * On these Samsung MoviNAND parts, performing secure erase or
1708          * secure trim can result in unrecoverable corruption due to a
1709          * firmware bug.
1710          */
1711         MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1712                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1713         MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1714                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1715         MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1716                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1717         MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1718                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1719         MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1720                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1721         MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1722                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1723         MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1724                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1725         MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1726                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1727
1728         END_FIXUP
1729 };
1730
1731 static int mmc_blk_probe(struct mmc_card *card)
1732 {
1733         struct mmc_blk_data *md, *part_md;
1734         int err;
1735         char cap_str[10];
1736
1737         /*
1738          * Check that the card supports the command class(es) we need.
1739          */
1740         if (!(card->csd.cmdclass & CCC_BLOCK_READ))
1741                 return -ENODEV;
1742
1743         md = mmc_blk_alloc(card);
1744         if (IS_ERR(md))
1745                 return PTR_ERR(md);
1746
1747         err = mmc_blk_set_blksize(md, card);
1748         if (err)
1749                 goto out;
1750
1751         string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
1752                         cap_str, sizeof(cap_str));
1753         pr_info("%s: %s %s %s %s\n",
1754                 md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
1755                 cap_str, md->read_only ? "(ro)" : "");
1756
1757         if (mmc_blk_alloc_parts(card, md))
1758                 goto out;
1759
1760         mmc_set_drvdata(card, md);
1761         mmc_fixup_device(card, blk_fixups);
1762
1763         if (mmc_add_disk(md))
1764                 goto out;
1765
1766         list_for_each_entry(part_md, &md->part, part) {
1767                 if (mmc_add_disk(part_md))
1768                         goto out;
1769         }
1770         return 0;
1771
1772  out:
1773         mmc_blk_remove_parts(card, md);
1774         mmc_blk_remove_req(md);
1775         return err;
1776 }
1777
1778 static void mmc_blk_remove(struct mmc_card *card)
1779 {
1780         struct mmc_blk_data *md = mmc_get_drvdata(card);
1781
1782         mmc_blk_remove_parts(card, md);
1783         mmc_claim_host(card->host);
1784         mmc_blk_part_switch(card, md);
1785         mmc_release_host(card->host);
1786         mmc_blk_remove_req(md);
1787         mmc_set_drvdata(card, NULL);
1788 }
1789
1790 #ifdef CONFIG_PM
1791 static int mmc_blk_suspend(struct mmc_card *card)
1792 {
1793         struct mmc_blk_data *part_md;
1794         struct mmc_blk_data *md = mmc_get_drvdata(card);
1795
1796         if (md) {
1797                 mmc_queue_suspend(&md->queue);
1798                 list_for_each_entry(part_md, &md->part, part) {
1799                         mmc_queue_suspend(&part_md->queue);
1800                 }
1801         }
1802         return 0;
1803 }
1804
1805 static int mmc_blk_resume(struct mmc_card *card)
1806 {
1807         struct mmc_blk_data *part_md;
1808         struct mmc_blk_data *md = mmc_get_drvdata(card);
1809
1810         if (md) {
1811                 mmc_blk_set_blksize(md, card);
1812
1813                 /*
1814                  * Resume involves the card going into idle state,
1815                  * so current partition is always the main one.
1816                  */
1817                 md->part_curr = md->part_type;
1818                 mmc_queue_resume(&md->queue);
1819                 list_for_each_entry(part_md, &md->part, part) {
1820                         mmc_queue_resume(&part_md->queue);
1821                 }
1822         }
1823         return 0;
1824 }
1825 #else
1826 #define mmc_blk_suspend NULL
1827 #define mmc_blk_resume  NULL
1828 #endif
1829
1830 static struct mmc_driver mmc_driver = {
1831         .drv            = {
1832                 .name   = "mmcblk",
1833         },
1834         .probe          = mmc_blk_probe,
1835         .remove         = mmc_blk_remove,
1836         .suspend        = mmc_blk_suspend,
1837         .resume         = mmc_blk_resume,
1838 };
1839
1840 static int __init mmc_blk_init(void)
1841 {
1842         int res;
1843
1844         if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
1845                 pr_info("mmcblk: using %d minors per device\n", perdev_minors);
1846
1847         max_devices = 256 / perdev_minors;
1848
1849         res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
1850         if (res)
1851                 goto out;
1852
1853         res = mmc_register_driver(&mmc_driver);
1854         if (res)
1855                 goto out2;
1856
1857         return 0;
1858  out2:
1859         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
1860  out:
1861         return res;
1862 }
1863
1864 static void __exit mmc_blk_exit(void)
1865 {
1866         mmc_unregister_driver(&mmc_driver);
1867         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
1868 }
1869
1870 module_init(mmc_blk_init);
1871 module_exit(mmc_blk_exit);
1872
1873 MODULE_LICENSE("GPL");
1874 MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
1875