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