330f0158e573c3d943c7867df55066390cac639f
[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_err;
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 cmd_err:
422         kfree(idata->buf);
423         kfree(idata);
424         return err;
425 }
426
427 static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
428         unsigned int cmd, unsigned long arg)
429 {
430         int ret = -EINVAL;
431         if (cmd == MMC_IOC_CMD)
432                 ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
433         return ret;
434 }
435
436 #ifdef CONFIG_COMPAT
437 static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
438         unsigned int cmd, unsigned long arg)
439 {
440         return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
441 }
442 #endif
443
444 static const struct block_device_operations mmc_bdops = {
445         .open                   = mmc_blk_open,
446         .release                = mmc_blk_release,
447         .getgeo                 = mmc_blk_getgeo,
448         .owner                  = THIS_MODULE,
449         .ioctl                  = mmc_blk_ioctl,
450 #ifdef CONFIG_COMPAT
451         .compat_ioctl           = mmc_blk_compat_ioctl,
452 #endif
453 };
454
455 static inline int mmc_blk_part_switch(struct mmc_card *card,
456                                       struct mmc_blk_data *md)
457 {
458         int ret;
459         struct mmc_blk_data *main_md = mmc_get_drvdata(card);
460
461         if (main_md->part_curr == md->part_type)
462                 return 0;
463
464         if (mmc_card_mmc(card)) {
465                 u8 part_config = card->ext_csd.part_config;
466
467                 part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
468                 part_config |= md->part_type;
469
470                 ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
471                                  EXT_CSD_PART_CONFIG, part_config,
472                                  card->ext_csd.part_time);
473                 if (ret)
474                         return ret;
475
476                 card->ext_csd.part_config = part_config;
477         }
478
479         main_md->part_curr = md->part_type;
480         return 0;
481 }
482
483 static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
484 {
485         int err;
486         u32 result;
487         __be32 *blocks;
488
489         struct mmc_request mrq = {NULL};
490         struct mmc_command cmd = {0};
491         struct mmc_data data = {0};
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.blksz = 4;
512         data.blocks = 1;
513         data.flags = MMC_DATA_READ;
514         data.sg = &sg;
515         data.sg_len = 1;
516         mmc_set_data_timeout(&data, card);
517
518         mrq.cmd = &cmd;
519         mrq.data = &data;
520
521         blocks = kmalloc(4, GFP_KERNEL);
522         if (!blocks)
523                 return (u32)-1;
524
525         sg_init_one(&sg, blocks, 4);
526
527         mmc_wait_for_req(card->host, &mrq);
528
529         result = ntohl(*blocks);
530         kfree(blocks);
531
532         if (cmd.error || data.error)
533                 result = (u32)-1;
534
535         return result;
536 }
537
538 static int send_stop(struct mmc_card *card, u32 *status)
539 {
540         struct mmc_command cmd = {0};
541         int err;
542
543         cmd.opcode = MMC_STOP_TRANSMISSION;
544         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
545         err = mmc_wait_for_cmd(card->host, &cmd, 5);
546         if (err == 0)
547                 *status = cmd.resp[0];
548         return err;
549 }
550
551 static int get_card_status(struct mmc_card *card, u32 *status, int retries)
552 {
553         struct mmc_command cmd = {0};
554         int err;
555
556         cmd.opcode = MMC_SEND_STATUS;
557         if (!mmc_host_is_spi(card->host))
558                 cmd.arg = card->rca << 16;
559         cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
560         err = mmc_wait_for_cmd(card->host, &cmd, retries);
561         if (err == 0)
562                 *status = cmd.resp[0];
563         return err;
564 }
565
566 #define ERR_NOMEDIUM    3
567 #define ERR_RETRY       2
568 #define ERR_ABORT       1
569 #define ERR_CONTINUE    0
570
571 static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
572         bool status_valid, u32 status)
573 {
574         switch (error) {
575         case -EILSEQ:
576                 /* response crc error, retry the r/w cmd */
577                 pr_err("%s: %s sending %s command, card status %#x\n",
578                         req->rq_disk->disk_name, "response CRC error",
579                         name, status);
580                 return ERR_RETRY;
581
582         case -ETIMEDOUT:
583                 pr_err("%s: %s sending %s command, card status %#x\n",
584                         req->rq_disk->disk_name, "timed out", name, status);
585
586                 /* If the status cmd initially failed, retry the r/w cmd */
587                 if (!status_valid)
588                         return ERR_RETRY;
589
590                 /*
591                  * If it was a r/w cmd crc error, or illegal command
592                  * (eg, issued in wrong state) then retry - we should
593                  * have corrected the state problem above.
594                  */
595                 if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND))
596                         return ERR_RETRY;
597
598                 /* Otherwise abort the command */
599                 return ERR_ABORT;
600
601         default:
602                 /* We don't understand the error code the driver gave us */
603                 pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
604                        req->rq_disk->disk_name, error, status);
605                 return ERR_ABORT;
606         }
607 }
608
609 /*
610  * Initial r/w and stop cmd error recovery.
611  * We don't know whether the card received the r/w cmd or not, so try to
612  * restore things back to a sane state.  Essentially, we do this as follows:
613  * - Obtain card status.  If the first attempt to obtain card status fails,
614  *   the status word will reflect the failed status cmd, not the failed
615  *   r/w cmd.  If we fail to obtain card status, it suggests we can no
616  *   longer communicate with the card.
617  * - Check the card state.  If the card received the cmd but there was a
618  *   transient problem with the response, it might still be in a data transfer
619  *   mode.  Try to send it a stop command.  If this fails, we can't recover.
620  * - If the r/w cmd failed due to a response CRC error, it was probably
621  *   transient, so retry the cmd.
622  * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
623  * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
624  *   illegal cmd, retry.
625  * Otherwise we don't understand what happened, so abort.
626  */
627 static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
628         struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
629 {
630         bool prev_cmd_status_valid = true;
631         u32 status, stop_status = 0;
632         int err, retry;
633
634         if (mmc_card_removed(card))
635                 return ERR_NOMEDIUM;
636
637         /*
638          * Try to get card status which indicates both the card state
639          * and why there was no response.  If the first attempt fails,
640          * we can't be sure the returned status is for the r/w command.
641          */
642         for (retry = 2; retry >= 0; retry--) {
643                 err = get_card_status(card, &status, 0);
644                 if (!err)
645                         break;
646
647                 prev_cmd_status_valid = false;
648                 pr_err("%s: error %d sending status command, %sing\n",
649                        req->rq_disk->disk_name, err, retry ? "retry" : "abort");
650         }
651
652         /* We couldn't get a response from the card.  Give up. */
653         if (err) {
654                 /* Check if the card is removed */
655                 if (mmc_detect_card_removed(card->host))
656                         return ERR_NOMEDIUM;
657                 return ERR_ABORT;
658         }
659
660         /* Flag ECC errors */
661         if ((status & R1_CARD_ECC_FAILED) ||
662             (brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
663             (brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
664                 *ecc_err = 1;
665
666         /* Flag General errors */
667         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
668                 if ((status & R1_ERROR) ||
669                         (brq->stop.resp[0] & R1_ERROR)) {
670                         pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
671                                req->rq_disk->disk_name, __func__,
672                                brq->stop.resp[0], status);
673                         *gen_err = 1;
674                 }
675
676         /*
677          * Check the current card state.  If it is in some data transfer
678          * mode, tell it to stop (and hopefully transition back to TRAN.)
679          */
680         if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
681             R1_CURRENT_STATE(status) == R1_STATE_RCV) {
682                 err = send_stop(card, &stop_status);
683                 if (err)
684                         pr_err("%s: error %d sending stop command\n",
685                                req->rq_disk->disk_name, err);
686
687                 /*
688                  * If the stop cmd also timed out, the card is probably
689                  * not present, so abort.  Other errors are bad news too.
690                  */
691                 if (err)
692                         return ERR_ABORT;
693                 if (stop_status & R1_CARD_ECC_FAILED)
694                         *ecc_err = 1;
695                 if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
696                         if (stop_status & R1_ERROR) {
697                                 pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
698                                        req->rq_disk->disk_name, __func__,
699                                        stop_status);
700                                 *gen_err = 1;
701                         }
702         }
703
704         /* Check for set block count errors */
705         if (brq->sbc.error)
706                 return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
707                                 prev_cmd_status_valid, status);
708
709         /* Check for r/w command errors */
710         if (brq->cmd.error)
711                 return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
712                                 prev_cmd_status_valid, status);
713
714         /* Data errors */
715         if (!brq->stop.error)
716                 return ERR_CONTINUE;
717
718         /* Now for stop errors.  These aren't fatal to the transfer. */
719         pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
720                req->rq_disk->disk_name, brq->stop.error,
721                brq->cmd.resp[0], status);
722
723         /*
724          * Subsitute in our own stop status as this will give the error
725          * state which happened during the execution of the r/w command.
726          */
727         if (stop_status) {
728                 brq->stop.resp[0] = stop_status;
729                 brq->stop.error = 0;
730         }
731         return ERR_CONTINUE;
732 }
733
734 static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
735                          int type)
736 {
737         int err;
738
739         if (md->reset_done & type)
740                 return -EEXIST;
741
742         md->reset_done |= type;
743         err = mmc_hw_reset(host);
744         /* Ensure we switch back to the correct partition */
745         if (err != -EOPNOTSUPP) {
746                 struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
747                 int part_err;
748
749                 main_md->part_curr = main_md->part_type;
750                 part_err = mmc_blk_part_switch(host->card, md);
751                 if (part_err) {
752                         /*
753                          * We have failed to get back into the correct
754                          * partition, so we need to abort the whole request.
755                          */
756                         return -ENODEV;
757                 }
758         }
759         return err;
760 }
761
762 static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
763 {
764         md->reset_done &= ~type;
765 }
766
767 static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
768 {
769         struct mmc_blk_data *md = mq->data;
770         struct mmc_card *card = md->queue.card;
771         unsigned int from, nr, arg;
772         int err = 0, type = MMC_BLK_DISCARD;
773
774         if (!mmc_can_erase(card)) {
775                 err = -EOPNOTSUPP;
776                 goto out;
777         }
778
779         from = blk_rq_pos(req);
780         nr = blk_rq_sectors(req);
781
782         if (mmc_can_discard(card))
783                 arg = MMC_DISCARD_ARG;
784         else if (mmc_can_trim(card))
785                 arg = MMC_TRIM_ARG;
786         else
787                 arg = MMC_ERASE_ARG;
788 retry:
789         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
790                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
791                                  INAND_CMD38_ARG_EXT_CSD,
792                                  arg == MMC_TRIM_ARG ?
793                                  INAND_CMD38_ARG_TRIM :
794                                  INAND_CMD38_ARG_ERASE,
795                                  0);
796                 if (err)
797                         goto out;
798         }
799         err = mmc_erase(card, from, nr, arg);
800 out:
801         if (err == -EIO && !mmc_blk_reset(md, card->host, type))
802                 goto retry;
803         if (!err)
804                 mmc_blk_reset_success(md, type);
805         spin_lock_irq(&md->lock);
806         __blk_end_request(req, err, blk_rq_bytes(req));
807         spin_unlock_irq(&md->lock);
808
809         return err ? 0 : 1;
810 }
811
812 static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
813                                        struct request *req)
814 {
815         struct mmc_blk_data *md = mq->data;
816         struct mmc_card *card = md->queue.card;
817         unsigned int from, nr, arg, trim_arg, erase_arg;
818         int err = 0, type = MMC_BLK_SECDISCARD;
819
820         if (!(mmc_can_secure_erase_trim(card) || mmc_can_sanitize(card))) {
821                 err = -EOPNOTSUPP;
822                 goto out;
823         }
824
825         from = blk_rq_pos(req);
826         nr = blk_rq_sectors(req);
827
828         /* The sanitize operation is supported at v4.5 only */
829         if (mmc_can_sanitize(card)) {
830                 erase_arg = MMC_ERASE_ARG;
831                 trim_arg = MMC_TRIM_ARG;
832         } else {
833                 erase_arg = MMC_SECURE_ERASE_ARG;
834                 trim_arg = MMC_SECURE_TRIM1_ARG;
835         }
836
837         if (mmc_erase_group_aligned(card, from, nr))
838                 arg = erase_arg;
839         else if (mmc_can_trim(card))
840                 arg = trim_arg;
841         else {
842                 err = -EINVAL;
843                 goto out;
844         }
845 retry:
846         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
847                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
848                                  INAND_CMD38_ARG_EXT_CSD,
849                                  arg == MMC_SECURE_TRIM1_ARG ?
850                                  INAND_CMD38_ARG_SECTRIM1 :
851                                  INAND_CMD38_ARG_SECERASE,
852                                  0);
853                 if (err)
854                         goto out_retry;
855         }
856
857         err = mmc_erase(card, from, nr, arg);
858         if (err == -EIO)
859                 goto out_retry;
860         if (err)
861                 goto out;
862
863         if (arg == MMC_SECURE_TRIM1_ARG) {
864                 if (card->quirks & MMC_QUIRK_INAND_CMD38) {
865                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
866                                          INAND_CMD38_ARG_EXT_CSD,
867                                          INAND_CMD38_ARG_SECTRIM2,
868                                          0);
869                         if (err)
870                                 goto out_retry;
871                 }
872
873                 err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
874                 if (err == -EIO)
875                         goto out_retry;
876                 if (err)
877                         goto out;
878         }
879
880         if (mmc_can_sanitize(card))
881                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
882                                  EXT_CSD_SANITIZE_START, 1, 0);
883 out_retry:
884         if (err && !mmc_blk_reset(md, card->host, type))
885                 goto retry;
886         if (!err)
887                 mmc_blk_reset_success(md, type);
888 out:
889         spin_lock_irq(&md->lock);
890         __blk_end_request(req, err, blk_rq_bytes(req));
891         spin_unlock_irq(&md->lock);
892
893         return err ? 0 : 1;
894 }
895
896 static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
897 {
898         struct mmc_blk_data *md = mq->data;
899         struct mmc_card *card = md->queue.card;
900         int ret = 0;
901
902         ret = mmc_flush_cache(card);
903         if (ret)
904                 ret = -EIO;
905
906         spin_lock_irq(&md->lock);
907         __blk_end_request_all(req, ret);
908         spin_unlock_irq(&md->lock);
909
910         return ret ? 0 : 1;
911 }
912
913 /*
914  * Reformat current write as a reliable write, supporting
915  * both legacy and the enhanced reliable write MMC cards.
916  * In each transfer we'll handle only as much as a single
917  * reliable write can handle, thus finish the request in
918  * partial completions.
919  */
920 static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
921                                     struct mmc_card *card,
922                                     struct request *req)
923 {
924         if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
925                 /* Legacy mode imposes restrictions on transfers. */
926                 if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
927                         brq->data.blocks = 1;
928
929                 if (brq->data.blocks > card->ext_csd.rel_sectors)
930                         brq->data.blocks = card->ext_csd.rel_sectors;
931                 else if (brq->data.blocks < card->ext_csd.rel_sectors)
932                         brq->data.blocks = 1;
933         }
934 }
935
936 #define CMD_ERRORS                                                      \
937         (R1_OUT_OF_RANGE |      /* Command argument out of range */     \
938          R1_ADDRESS_ERROR |     /* Misaligned address */                \
939          R1_BLOCK_LEN_ERROR |   /* Transferred block length incorrect */\
940          R1_WP_VIOLATION |      /* Tried to write to protected block */ \
941          R1_CC_ERROR |          /* Card controller error */             \
942          R1_ERROR)              /* General/unknown error */
943
944 static int mmc_blk_err_check(struct mmc_card *card,
945                              struct mmc_async_req *areq)
946 {
947         struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
948                                                     mmc_active);
949         struct mmc_blk_request *brq = &mq_mrq->brq;
950         struct request *req = mq_mrq->req;
951         int ecc_err = 0, gen_err = 0;
952
953         /*
954          * sbc.error indicates a problem with the set block count
955          * command.  No data will have been transferred.
956          *
957          * cmd.error indicates a problem with the r/w command.  No
958          * data will have been transferred.
959          *
960          * stop.error indicates a problem with the stop command.  Data
961          * may have been transferred, or may still be transferring.
962          */
963         if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
964             brq->data.error) {
965                 switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
966                 case ERR_RETRY:
967                         return MMC_BLK_RETRY;
968                 case ERR_ABORT:
969                         return MMC_BLK_ABORT;
970                 case ERR_NOMEDIUM:
971                         return MMC_BLK_NOMEDIUM;
972                 case ERR_CONTINUE:
973                         break;
974                 }
975         }
976
977         /*
978          * Check for errors relating to the execution of the
979          * initial command - such as address errors.  No data
980          * has been transferred.
981          */
982         if (brq->cmd.resp[0] & CMD_ERRORS) {
983                 pr_err("%s: r/w command failed, status = %#x\n",
984                        req->rq_disk->disk_name, brq->cmd.resp[0]);
985                 return MMC_BLK_ABORT;
986         }
987
988         /*
989          * Everything else is either success, or a data error of some
990          * kind.  If it was a write, we may have transitioned to
991          * program mode, which we have to wait for it to complete.
992          */
993         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
994                 u32 status;
995
996                 /* Check stop command response */
997                 if (brq->stop.resp[0] & R1_ERROR) {
998                         pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
999                                req->rq_disk->disk_name, __func__,
1000                                brq->stop.resp[0]);
1001                         gen_err = 1;
1002                 }
1003
1004                 do {
1005                         int err = get_card_status(card, &status, 5);
1006                         if (err) {
1007                                 pr_err("%s: error %d requesting status\n",
1008                                        req->rq_disk->disk_name, err);
1009                                 return MMC_BLK_CMD_ERR;
1010                         }
1011
1012                         if (status & R1_ERROR) {
1013                                 pr_err("%s: %s: general error sending status command, card status %#x\n",
1014                                        req->rq_disk->disk_name, __func__,
1015                                        status);
1016                                 gen_err = 1;
1017                         }
1018
1019                         /*
1020                          * Some cards mishandle the status bits,
1021                          * so make sure to check both the busy
1022                          * indication and the card state.
1023                          */
1024                 } while (!(status & R1_READY_FOR_DATA) ||
1025                          (R1_CURRENT_STATE(status) == R1_STATE_PRG));
1026         }
1027
1028         /* if general error occurs, retry the write operation. */
1029         if (gen_err) {
1030                 pr_warning("%s: retrying write for general error\n",
1031                                 req->rq_disk->disk_name);
1032                 return MMC_BLK_RETRY;
1033         }
1034
1035         if (brq->data.error) {
1036                 pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
1037                        req->rq_disk->disk_name, brq->data.error,
1038                        (unsigned)blk_rq_pos(req),
1039                        (unsigned)blk_rq_sectors(req),
1040                        brq->cmd.resp[0], brq->stop.resp[0]);
1041
1042                 if (rq_data_dir(req) == READ) {
1043                         if (ecc_err)
1044                                 return MMC_BLK_ECC_ERR;
1045                         return MMC_BLK_DATA_ERR;
1046                 } else {
1047                         return MMC_BLK_CMD_ERR;
1048                 }
1049         }
1050
1051         if (!brq->data.bytes_xfered)
1052                 return MMC_BLK_RETRY;
1053
1054         if (blk_rq_bytes(req) != brq->data.bytes_xfered)
1055                 return MMC_BLK_PARTIAL;
1056
1057         return MMC_BLK_SUCCESS;
1058 }
1059
1060 static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1061                                struct mmc_card *card,
1062                                int disable_multi,
1063                                struct mmc_queue *mq)
1064 {
1065         u32 readcmd, writecmd;
1066         struct mmc_blk_request *brq = &mqrq->brq;
1067         struct request *req = mqrq->req;
1068         struct mmc_blk_data *md = mq->data;
1069
1070         /*
1071          * Reliable writes are used to implement Forced Unit Access and
1072          * REQ_META accesses, and are supported only on MMCs.
1073          *
1074          * XXX: this really needs a good explanation of why REQ_META
1075          * is treated special.
1076          */
1077         bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
1078                           (req->cmd_flags & REQ_META)) &&
1079                 (rq_data_dir(req) == WRITE) &&
1080                 (md->flags & MMC_BLK_REL_WR);
1081
1082         memset(brq, 0, sizeof(struct mmc_blk_request));
1083         brq->mrq.cmd = &brq->cmd;
1084         brq->mrq.data = &brq->data;
1085
1086         brq->cmd.arg = blk_rq_pos(req);
1087         if (!mmc_card_blockaddr(card))
1088                 brq->cmd.arg <<= 9;
1089         brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1090         brq->data.blksz = 512;
1091         brq->stop.opcode = MMC_STOP_TRANSMISSION;
1092         brq->stop.arg = 0;
1093         brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1094         brq->data.blocks = blk_rq_sectors(req);
1095
1096         /*
1097          * The block layer doesn't support all sector count
1098          * restrictions, so we need to be prepared for too big
1099          * requests.
1100          */
1101         if (brq->data.blocks > card->host->max_blk_count)
1102                 brq->data.blocks = card->host->max_blk_count;
1103
1104         if (brq->data.blocks > 1) {
1105                 /*
1106                  * After a read error, we redo the request one sector
1107                  * at a time in order to accurately determine which
1108                  * sectors can be read successfully.
1109                  */
1110                 if (disable_multi)
1111                         brq->data.blocks = 1;
1112
1113                 /* Some controllers can't do multiblock reads due to hw bugs */
1114                 if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
1115                     rq_data_dir(req) == READ)
1116                         brq->data.blocks = 1;
1117         }
1118
1119         if (brq->data.blocks > 1 || do_rel_wr) {
1120                 /* SPI multiblock writes terminate using a special
1121                  * token, not a STOP_TRANSMISSION request.
1122                  */
1123                 if (!mmc_host_is_spi(card->host) ||
1124                     rq_data_dir(req) == READ)
1125                         brq->mrq.stop = &brq->stop;
1126                 readcmd = MMC_READ_MULTIPLE_BLOCK;
1127                 writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1128         } else {
1129                 brq->mrq.stop = NULL;
1130                 readcmd = MMC_READ_SINGLE_BLOCK;
1131                 writecmd = MMC_WRITE_BLOCK;
1132         }
1133         if (rq_data_dir(req) == READ) {
1134                 brq->cmd.opcode = readcmd;
1135                 brq->data.flags |= MMC_DATA_READ;
1136         } else {
1137                 brq->cmd.opcode = writecmd;
1138                 brq->data.flags |= MMC_DATA_WRITE;
1139         }
1140
1141         if (do_rel_wr)
1142                 mmc_apply_rel_rw(brq, card, req);
1143
1144         /*
1145          * Pre-defined multi-block transfers are preferable to
1146          * open ended-ones (and necessary for reliable writes).
1147          * However, it is not sufficient to just send CMD23,
1148          * and avoid the final CMD12, as on an error condition
1149          * CMD12 (stop) needs to be sent anyway. This, coupled
1150          * with Auto-CMD23 enhancements provided by some
1151          * hosts, means that the complexity of dealing
1152          * with this is best left to the host. If CMD23 is
1153          * supported by card and host, we'll fill sbc in and let
1154          * the host deal with handling it correctly. This means
1155          * that for hosts that don't expose MMC_CAP_CMD23, no
1156          * change of behavior will be observed.
1157          *
1158          * N.B: Some MMC cards experience perf degradation.
1159          * We'll avoid using CMD23-bounded multiblock writes for
1160          * these, while retaining features like reliable writes.
1161          */
1162
1163         if ((md->flags & MMC_BLK_CMD23) &&
1164             mmc_op_multi(brq->cmd.opcode) &&
1165             (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23))) {
1166                 brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1167                 brq->sbc.arg = brq->data.blocks |
1168                         (do_rel_wr ? (1 << 31) : 0);
1169                 brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1170                 brq->mrq.sbc = &brq->sbc;
1171         }
1172
1173         mmc_set_data_timeout(&brq->data, card);
1174
1175         brq->data.sg = mqrq->sg;
1176         brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1177
1178         /*
1179          * Adjust the sg list so it is the same size as the
1180          * request.
1181          */
1182         if (brq->data.blocks != blk_rq_sectors(req)) {
1183                 int i, data_size = brq->data.blocks << 9;
1184                 struct scatterlist *sg;
1185
1186                 for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1187                         data_size -= sg->length;
1188                         if (data_size <= 0) {
1189                                 sg->length += data_size;
1190                                 i++;
1191                                 break;
1192                         }
1193                 }
1194                 brq->data.sg_len = i;
1195         }
1196
1197         mqrq->mmc_active.mrq = &brq->mrq;
1198         mqrq->mmc_active.err_check = mmc_blk_err_check;
1199
1200         mmc_queue_bounce_pre(mqrq);
1201 }
1202
1203 static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
1204                            struct mmc_blk_request *brq, struct request *req,
1205                            int ret)
1206 {
1207         /*
1208          * If this is an SD card and we're writing, we can first
1209          * mark the known good sectors as ok.
1210          *
1211          * If the card is not SD, we can still ok written sectors
1212          * as reported by the controller (which might be less than
1213          * the real number of written sectors, but never more).
1214          */
1215         if (mmc_card_sd(card)) {
1216                 u32 blocks;
1217
1218                 blocks = mmc_sd_num_wr_blocks(card);
1219                 if (blocks != (u32)-1) {
1220                         spin_lock_irq(&md->lock);
1221                         ret = __blk_end_request(req, 0, blocks << 9);
1222                         spin_unlock_irq(&md->lock);
1223                 }
1224         } else {
1225                 spin_lock_irq(&md->lock);
1226                 ret = __blk_end_request(req, 0, brq->data.bytes_xfered);
1227                 spin_unlock_irq(&md->lock);
1228         }
1229         return ret;
1230 }
1231
1232 static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
1233 {
1234         struct mmc_blk_data *md = mq->data;
1235         struct mmc_card *card = md->queue.card;
1236         struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
1237         int ret = 1, disable_multi = 0, retry = 0, type;
1238         enum mmc_blk_status status;
1239         struct mmc_queue_req *mq_rq;
1240         struct request *req;
1241         struct mmc_async_req *areq;
1242
1243         if (!rqc && !mq->mqrq_prev->req)
1244                 return 0;
1245
1246         do {
1247                 if (rqc) {
1248                         mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1249                         areq = &mq->mqrq_cur->mmc_active;
1250                 } else
1251                         areq = NULL;
1252                 areq = mmc_start_req(card->host, areq, (int *) &status);
1253                 if (!areq)
1254                         return 0;
1255
1256                 mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
1257                 brq = &mq_rq->brq;
1258                 req = mq_rq->req;
1259                 type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1260                 mmc_queue_bounce_post(mq_rq);
1261
1262                 switch (status) {
1263                 case MMC_BLK_SUCCESS:
1264                 case MMC_BLK_PARTIAL:
1265                         /*
1266                          * A block was successfully transferred.
1267                          */
1268                         mmc_blk_reset_success(md, type);
1269                         spin_lock_irq(&md->lock);
1270                         ret = __blk_end_request(req, 0,
1271                                                 brq->data.bytes_xfered);
1272                         spin_unlock_irq(&md->lock);
1273                         /*
1274                          * If the blk_end_request function returns non-zero even
1275                          * though all data has been transferred and no errors
1276                          * were returned by the host controller, it's a bug.
1277                          */
1278                         if (status == MMC_BLK_SUCCESS && ret) {
1279                                 pr_err("%s BUG rq_tot %d d_xfer %d\n",
1280                                        __func__, blk_rq_bytes(req),
1281                                        brq->data.bytes_xfered);
1282                                 rqc = NULL;
1283                                 goto cmd_abort;
1284                         }
1285                         break;
1286                 case MMC_BLK_CMD_ERR:
1287                         ret = mmc_blk_cmd_err(md, card, brq, req, ret);
1288                         if (!mmc_blk_reset(md, card->host, type))
1289                                 break;
1290                         goto cmd_abort;
1291                 case MMC_BLK_RETRY:
1292                         if (retry++ < 5)
1293                                 break;
1294                         /* Fall through */
1295                 case MMC_BLK_ABORT:
1296                         if (!mmc_blk_reset(md, card->host, type))
1297                                 break;
1298                         goto cmd_abort;
1299                 case MMC_BLK_DATA_ERR: {
1300                         int err;
1301
1302                         err = mmc_blk_reset(md, card->host, type);
1303                         if (!err)
1304                                 break;
1305                         if (err == -ENODEV)
1306                                 goto cmd_abort;
1307                         /* Fall through */
1308                 }
1309                 case MMC_BLK_ECC_ERR:
1310                         if (brq->data.blocks > 1) {
1311                                 /* Redo read one sector at a time */
1312                                 pr_warning("%s: retrying using single block read\n",
1313                                            req->rq_disk->disk_name);
1314                                 disable_multi = 1;
1315                                 break;
1316                         }
1317                         /*
1318                          * After an error, we redo I/O one sector at a
1319                          * time, so we only reach here after trying to
1320                          * read a single sector.
1321                          */
1322                         spin_lock_irq(&md->lock);
1323                         ret = __blk_end_request(req, -EIO,
1324                                                 brq->data.blksz);
1325                         spin_unlock_irq(&md->lock);
1326                         if (!ret)
1327                                 goto start_new_req;
1328                         break;
1329                 case MMC_BLK_NOMEDIUM:
1330                         goto cmd_abort;
1331                 }
1332
1333                 if (ret) {
1334                         /*
1335                          * In case of a incomplete request
1336                          * prepare it again and resend.
1337                          */
1338                         mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq);
1339                         mmc_start_req(card->host, &mq_rq->mmc_active, NULL);
1340                 }
1341         } while (ret);
1342
1343         return 1;
1344
1345  cmd_abort:
1346         spin_lock_irq(&md->lock);
1347         if (mmc_card_removed(card))
1348                 req->cmd_flags |= REQ_QUIET;
1349         while (ret)
1350                 ret = __blk_end_request(req, -EIO, blk_rq_cur_bytes(req));
1351         spin_unlock_irq(&md->lock);
1352
1353  start_new_req:
1354         if (rqc) {
1355                 mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1356                 mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL);
1357         }
1358
1359         return 0;
1360 }
1361
1362 static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
1363 {
1364         int ret;
1365         struct mmc_blk_data *md = mq->data;
1366         struct mmc_card *card = md->queue.card;
1367
1368         if (req && !mq->mqrq_prev->req)
1369                 /* claim host only for the first request */
1370                 mmc_claim_host(card->host);
1371
1372         ret = mmc_blk_part_switch(card, md);
1373         if (ret) {
1374                 if (req) {
1375                         spin_lock_irq(&md->lock);
1376                         __blk_end_request_all(req, -EIO);
1377                         spin_unlock_irq(&md->lock);
1378                 }
1379                 ret = 0;
1380                 goto out;
1381         }
1382
1383         if (req && req->cmd_flags & REQ_DISCARD) {
1384                 /* complete ongoing async transfer before issuing discard */
1385                 if (card->host->areq)
1386                         mmc_blk_issue_rw_rq(mq, NULL);
1387                 if (req->cmd_flags & REQ_SECURE &&
1388                         !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
1389                         ret = mmc_blk_issue_secdiscard_rq(mq, req);
1390                 else
1391                         ret = mmc_blk_issue_discard_rq(mq, req);
1392         } else if (req && req->cmd_flags & REQ_FLUSH) {
1393                 /* complete ongoing async transfer before issuing flush */
1394                 if (card->host->areq)
1395                         mmc_blk_issue_rw_rq(mq, NULL);
1396                 ret = mmc_blk_issue_flush(mq, req);
1397         } else {
1398                 ret = mmc_blk_issue_rw_rq(mq, req);
1399         }
1400
1401 out:
1402         if (!req)
1403                 /* release host only when there are no more requests */
1404                 mmc_release_host(card->host);
1405         return ret;
1406 }
1407
1408 static inline int mmc_blk_readonly(struct mmc_card *card)
1409 {
1410         return mmc_card_readonly(card) ||
1411                !(card->csd.cmdclass & CCC_BLOCK_WRITE);
1412 }
1413
1414 static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
1415                                               struct device *parent,
1416                                               sector_t size,
1417                                               bool default_ro,
1418                                               const char *subname)
1419 {
1420         struct mmc_blk_data *md;
1421         int devidx, ret;
1422
1423         devidx = find_first_zero_bit(dev_use, max_devices);
1424         if (devidx >= max_devices)
1425                 return ERR_PTR(-ENOSPC);
1426         __set_bit(devidx, dev_use);
1427
1428         md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
1429         if (!md) {
1430                 ret = -ENOMEM;
1431                 goto out;
1432         }
1433
1434         /*
1435          * !subname implies we are creating main mmc_blk_data that will be
1436          * associated with mmc_card with mmc_set_drvdata. Due to device
1437          * partitions, devidx will not coincide with a per-physical card
1438          * index anymore so we keep track of a name index.
1439          */
1440         if (!subname) {
1441                 md->name_idx = find_first_zero_bit(name_use, max_devices);
1442                 __set_bit(md->name_idx, name_use);
1443         }
1444         else
1445                 md->name_idx = ((struct mmc_blk_data *)
1446                                 dev_to_disk(parent)->private_data)->name_idx;
1447
1448         /*
1449          * Set the read-only status based on the supported commands
1450          * and the write protect switch.
1451          */
1452         md->read_only = mmc_blk_readonly(card);
1453
1454         md->disk = alloc_disk(perdev_minors);
1455         if (md->disk == NULL) {
1456                 ret = -ENOMEM;
1457                 goto err_kfree;
1458         }
1459
1460         spin_lock_init(&md->lock);
1461         INIT_LIST_HEAD(&md->part);
1462         md->usage = 1;
1463
1464         ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
1465         if (ret)
1466                 goto err_putdisk;
1467
1468         md->queue.issue_fn = mmc_blk_issue_rq;
1469         md->queue.data = md;
1470
1471         md->disk->major = MMC_BLOCK_MAJOR;
1472         md->disk->first_minor = devidx * perdev_minors;
1473         md->disk->fops = &mmc_bdops;
1474         md->disk->private_data = md;
1475         md->disk->queue = md->queue.queue;
1476         md->disk->driverfs_dev = parent;
1477         set_disk_ro(md->disk, md->read_only || default_ro);
1478
1479         /*
1480          * As discussed on lkml, GENHD_FL_REMOVABLE should:
1481          *
1482          * - be set for removable media with permanent block devices
1483          * - be unset for removable block devices with permanent media
1484          *
1485          * Since MMC block devices clearly fall under the second
1486          * case, we do not set GENHD_FL_REMOVABLE.  Userspace
1487          * should use the block device creation/destruction hotplug
1488          * messages to tell when the card is present.
1489          */
1490
1491         snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
1492                  "mmcblk%d%s", md->name_idx, subname ? subname : "");
1493
1494         blk_queue_logical_block_size(md->queue.queue, 512);
1495         set_capacity(md->disk, size);
1496
1497         if (mmc_host_cmd23(card->host)) {
1498                 if (mmc_card_mmc(card) ||
1499                     (mmc_card_sd(card) &&
1500                      card->scr.cmds & SD_SCR_CMD23_SUPPORT))
1501                         md->flags |= MMC_BLK_CMD23;
1502         }
1503
1504         if (mmc_card_mmc(card) &&
1505             md->flags & MMC_BLK_CMD23 &&
1506             ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
1507              card->ext_csd.rel_sectors)) {
1508                 md->flags |= MMC_BLK_REL_WR;
1509                 blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
1510         }
1511
1512         return md;
1513
1514  err_putdisk:
1515         put_disk(md->disk);
1516  err_kfree:
1517         kfree(md);
1518  out:
1519         return ERR_PTR(ret);
1520 }
1521
1522 static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
1523 {
1524         sector_t size;
1525         struct mmc_blk_data *md;
1526
1527         if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
1528                 /*
1529                  * The EXT_CSD sector count is in number or 512 byte
1530                  * sectors.
1531                  */
1532                 size = card->ext_csd.sectors;
1533         } else {
1534                 /*
1535                  * The CSD capacity field is in units of read_blkbits.
1536                  * set_capacity takes units of 512 bytes.
1537                  */
1538                 size = card->csd.capacity << (card->csd.read_blkbits - 9);
1539         }
1540
1541         md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL);
1542         return md;
1543 }
1544
1545 static int mmc_blk_alloc_part(struct mmc_card *card,
1546                               struct mmc_blk_data *md,
1547                               unsigned int part_type,
1548                               sector_t size,
1549                               bool default_ro,
1550                               const char *subname)
1551 {
1552         char cap_str[10];
1553         struct mmc_blk_data *part_md;
1554
1555         part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
1556                                     subname);
1557         if (IS_ERR(part_md))
1558                 return PTR_ERR(part_md);
1559         part_md->part_type = part_type;
1560         list_add(&part_md->part, &md->part);
1561
1562         string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
1563                         cap_str, sizeof(cap_str));
1564         pr_info("%s: %s %s partition %u %s\n",
1565                part_md->disk->disk_name, mmc_card_id(card),
1566                mmc_card_name(card), part_md->part_type, cap_str);
1567         return 0;
1568 }
1569
1570 /* MMC Physical partitions consist of two boot partitions and
1571  * up to four general purpose partitions.
1572  * For each partition enabled in EXT_CSD a block device will be allocatedi
1573  * to provide access to the partition.
1574  */
1575
1576 static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
1577 {
1578         int idx, ret = 0;
1579
1580         if (!mmc_card_mmc(card))
1581                 return 0;
1582
1583         for (idx = 0; idx < card->nr_parts; idx++) {
1584                 if (card->part[idx].size) {
1585                         ret = mmc_blk_alloc_part(card, md,
1586                                 card->part[idx].part_cfg,
1587                                 card->part[idx].size >> 9,
1588                                 card->part[idx].force_ro,
1589                                 card->part[idx].name);
1590                         if (ret)
1591                                 return ret;
1592                 }
1593         }
1594
1595         return ret;
1596 }
1597
1598 static int
1599 mmc_blk_set_blksize(struct mmc_blk_data *md, struct mmc_card *card)
1600 {
1601         int err;
1602
1603         mmc_claim_host(card->host);
1604         err = mmc_set_blocklen(card, 512);
1605         mmc_release_host(card->host);
1606
1607         if (err) {
1608                 pr_err("%s: unable to set block size to 512: %d\n",
1609                         md->disk->disk_name, err);
1610                 return -EINVAL;
1611         }
1612
1613         return 0;
1614 }
1615
1616 static void mmc_blk_remove_req(struct mmc_blk_data *md)
1617 {
1618         if (md) {
1619                 if (md->disk->flags & GENHD_FL_UP) {
1620                         device_remove_file(disk_to_dev(md->disk), &md->force_ro);
1621
1622                         /* Stop new requests from getting into the queue */
1623                         del_gendisk(md->disk);
1624                 }
1625
1626                 /* Then flush out any already in there */
1627                 mmc_cleanup_queue(&md->queue);
1628                 mmc_blk_put(md);
1629         }
1630 }
1631
1632 static void mmc_blk_remove_parts(struct mmc_card *card,
1633                                  struct mmc_blk_data *md)
1634 {
1635         struct list_head *pos, *q;
1636         struct mmc_blk_data *part_md;
1637
1638         __clear_bit(md->name_idx, name_use);
1639         list_for_each_safe(pos, q, &md->part) {
1640                 part_md = list_entry(pos, struct mmc_blk_data, part);
1641                 list_del(pos);
1642                 mmc_blk_remove_req(part_md);
1643         }
1644 }
1645
1646 static int mmc_add_disk(struct mmc_blk_data *md)
1647 {
1648         int ret;
1649
1650         add_disk(md->disk);
1651         md->force_ro.show = force_ro_show;
1652         md->force_ro.store = force_ro_store;
1653         sysfs_attr_init(&md->force_ro.attr);
1654         md->force_ro.attr.name = "force_ro";
1655         md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
1656         ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
1657         if (ret)
1658                 del_gendisk(md->disk);
1659
1660         return ret;
1661 }
1662
1663 #define CID_MANFID_SAMSUNG      0x15
1664
1665 static const struct mmc_fixup blk_fixups[] =
1666 {
1667         MMC_FIXUP("SEM02G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1668         MMC_FIXUP("SEM04G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1669         MMC_FIXUP("SEM08G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1670         MMC_FIXUP("SEM16G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1671         MMC_FIXUP("SEM32G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
1672
1673         /*
1674          * Some MMC cards experience performance degradation with CMD23
1675          * instead of CMD12-bounded multiblock transfers. For now we'll
1676          * black list what's bad...
1677          * - Certain Toshiba cards.
1678          *
1679          * N.B. This doesn't affect SD cards.
1680          */
1681         MMC_FIXUP("MMC08G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
1682                   MMC_QUIRK_BLK_NO_CMD23),
1683         MMC_FIXUP("MMC16G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
1684                   MMC_QUIRK_BLK_NO_CMD23),
1685         MMC_FIXUP("MMC32G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
1686                   MMC_QUIRK_BLK_NO_CMD23),
1687
1688         /*
1689          * Some Micron MMC cards needs longer data read timeout than
1690          * indicated in CSD.
1691          */
1692         MMC_FIXUP(CID_NAME_ANY, 0x13, 0x200, add_quirk_mmc,
1693                   MMC_QUIRK_LONG_READ_TIME),
1694
1695         /*
1696          * On these Samsung MoviNAND parts, performing secure erase or
1697          * secure trim can result in unrecoverable corruption due to a
1698          * firmware bug.
1699          */
1700         MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1701                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1702         MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1703                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1704         MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1705                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1706         MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1707                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1708         MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1709                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1710         MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1711                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1712         MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1713                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1714         MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
1715                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
1716
1717         END_FIXUP
1718 };
1719
1720 static int mmc_blk_probe(struct mmc_card *card)
1721 {
1722         struct mmc_blk_data *md, *part_md;
1723         int err;
1724         char cap_str[10];
1725
1726         /*
1727          * Check that the card supports the command class(es) we need.
1728          */
1729         if (!(card->csd.cmdclass & CCC_BLOCK_READ))
1730                 return -ENODEV;
1731
1732         md = mmc_blk_alloc(card);
1733         if (IS_ERR(md))
1734                 return PTR_ERR(md);
1735
1736         err = mmc_blk_set_blksize(md, card);
1737         if (err)
1738                 goto out;
1739
1740         string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
1741                         cap_str, sizeof(cap_str));
1742         pr_info("%s: %s %s %s %s\n",
1743                 md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
1744                 cap_str, md->read_only ? "(ro)" : "");
1745
1746         if (mmc_blk_alloc_parts(card, md))
1747                 goto out;
1748
1749         mmc_set_drvdata(card, md);
1750         mmc_fixup_device(card, blk_fixups);
1751
1752         if (mmc_add_disk(md))
1753                 goto out;
1754
1755         list_for_each_entry(part_md, &md->part, part) {
1756                 if (mmc_add_disk(part_md))
1757                         goto out;
1758         }
1759         return 0;
1760
1761  out:
1762         mmc_blk_remove_parts(card, md);
1763         mmc_blk_remove_req(md);
1764         return err;
1765 }
1766
1767 static void mmc_blk_remove(struct mmc_card *card)
1768 {
1769         struct mmc_blk_data *md = mmc_get_drvdata(card);
1770
1771         mmc_blk_remove_parts(card, md);
1772         mmc_claim_host(card->host);
1773         mmc_blk_part_switch(card, md);
1774         mmc_release_host(card->host);
1775         mmc_blk_remove_req(md);
1776         mmc_set_drvdata(card, NULL);
1777 }
1778
1779 #ifdef CONFIG_PM
1780 static int mmc_blk_suspend(struct mmc_card *card)
1781 {
1782         struct mmc_blk_data *part_md;
1783         struct mmc_blk_data *md = mmc_get_drvdata(card);
1784
1785         if (md) {
1786                 mmc_queue_suspend(&md->queue);
1787                 list_for_each_entry(part_md, &md->part, part) {
1788                         mmc_queue_suspend(&part_md->queue);
1789                 }
1790         }
1791         return 0;
1792 }
1793
1794 static int mmc_blk_resume(struct mmc_card *card)
1795 {
1796         struct mmc_blk_data *part_md;
1797         struct mmc_blk_data *md = mmc_get_drvdata(card);
1798
1799         if (md) {
1800                 mmc_blk_set_blksize(md, card);
1801
1802                 /*
1803                  * Resume involves the card going into idle state,
1804                  * so current partition is always the main one.
1805                  */
1806                 md->part_curr = md->part_type;
1807                 mmc_queue_resume(&md->queue);
1808                 list_for_each_entry(part_md, &md->part, part) {
1809                         mmc_queue_resume(&part_md->queue);
1810                 }
1811         }
1812         return 0;
1813 }
1814 #else
1815 #define mmc_blk_suspend NULL
1816 #define mmc_blk_resume  NULL
1817 #endif
1818
1819 static struct mmc_driver mmc_driver = {
1820         .drv            = {
1821                 .name   = "mmcblk",
1822         },
1823         .probe          = mmc_blk_probe,
1824         .remove         = mmc_blk_remove,
1825         .suspend        = mmc_blk_suspend,
1826         .resume         = mmc_blk_resume,
1827 };
1828
1829 static int __init mmc_blk_init(void)
1830 {
1831         int res;
1832
1833         if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
1834                 pr_info("mmcblk: using %d minors per device\n", perdev_minors);
1835
1836         max_devices = 256 / perdev_minors;
1837
1838         res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
1839         if (res)
1840                 goto out;
1841
1842         res = mmc_register_driver(&mmc_driver);
1843         if (res)
1844                 goto out2;
1845
1846         return 0;
1847  out2:
1848         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
1849  out:
1850         return res;
1851 }
1852
1853 static void __exit mmc_blk_exit(void)
1854 {
1855         mmc_unregister_driver(&mmc_driver);
1856         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
1857 }
1858
1859 module_init(mmc_blk_init);
1860 module_exit(mmc_blk_exit);
1861
1862 MODULE_LICENSE("GPL");
1863 MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
1864