71db040dd4cdedd8929528cf8907a4d1ad5a8785
[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         unsigned int timeout_us;
493
494         struct scatterlist sg;
495
496         cmd.opcode = MMC_APP_CMD;
497         cmd.arg = card->rca << 16;
498         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
499
500         err = mmc_wait_for_cmd(card->host, &cmd, 0);
501         if (err)
502                 return (u32)-1;
503         if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
504                 return (u32)-1;
505
506         memset(&cmd, 0, sizeof(struct mmc_command));
507
508         cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
509         cmd.arg = 0;
510         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
511
512         data.timeout_ns = card->csd.tacc_ns * 100;
513         data.timeout_clks = card->csd.tacc_clks * 100;
514
515         timeout_us = data.timeout_ns / 1000;
516         timeout_us += data.timeout_clks * 1000 /
517                 (card->host->ios.clock / 1000);
518
519         if (timeout_us > 100000) {
520                 data.timeout_ns = 100000000;
521                 data.timeout_clks = 0;
522         }
523
524         data.blksz = 4;
525         data.blocks = 1;
526         data.flags = MMC_DATA_READ;
527         data.sg = &sg;
528         data.sg_len = 1;
529
530         mrq.cmd = &cmd;
531         mrq.data = &data;
532
533         blocks = kmalloc(4, GFP_KERNEL);
534         if (!blocks)
535                 return (u32)-1;
536
537         sg_init_one(&sg, blocks, 4);
538
539         mmc_wait_for_req(card->host, &mrq);
540
541         result = ntohl(*blocks);
542         kfree(blocks);
543
544         if (cmd.error || data.error)
545                 result = (u32)-1;
546
547         return result;
548 }
549
550 static int send_stop(struct mmc_card *card, u32 *status)
551 {
552         struct mmc_command cmd = {0};
553         int err;
554
555         cmd.opcode = MMC_STOP_TRANSMISSION;
556         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
557         err = mmc_wait_for_cmd(card->host, &cmd, 5);
558         if (err == 0)
559                 *status = cmd.resp[0];
560         return err;
561 }
562
563 static int get_card_status(struct mmc_card *card, u32 *status, int retries)
564 {
565         struct mmc_command cmd = {0};
566         int err;
567
568         cmd.opcode = MMC_SEND_STATUS;
569         if (!mmc_host_is_spi(card->host))
570                 cmd.arg = card->rca << 16;
571         cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
572         err = mmc_wait_for_cmd(card->host, &cmd, retries);
573         if (err == 0)
574                 *status = cmd.resp[0];
575         return err;
576 }
577
578 #define ERR_NOMEDIUM    3
579 #define ERR_RETRY       2
580 #define ERR_ABORT       1
581 #define ERR_CONTINUE    0
582
583 static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
584         bool status_valid, u32 status)
585 {
586         switch (error) {
587         case -EILSEQ:
588                 /* response crc error, retry the r/w cmd */
589                 pr_err("%s: %s sending %s command, card status %#x\n",
590                         req->rq_disk->disk_name, "response CRC error",
591                         name, status);
592                 return ERR_RETRY;
593
594         case -ETIMEDOUT:
595                 pr_err("%s: %s sending %s command, card status %#x\n",
596                         req->rq_disk->disk_name, "timed out", name, status);
597
598                 /* If the status cmd initially failed, retry the r/w cmd */
599                 if (!status_valid)
600                         return ERR_RETRY;
601
602                 /*
603                  * If it was a r/w cmd crc error, or illegal command
604                  * (eg, issued in wrong state) then retry - we should
605                  * have corrected the state problem above.
606                  */
607                 if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND))
608                         return ERR_RETRY;
609
610                 /* Otherwise abort the command */
611                 return ERR_ABORT;
612
613         default:
614                 /* We don't understand the error code the driver gave us */
615                 pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
616                        req->rq_disk->disk_name, error, status);
617                 return ERR_ABORT;
618         }
619 }
620
621 /*
622  * Initial r/w and stop cmd error recovery.
623  * We don't know whether the card received the r/w cmd or not, so try to
624  * restore things back to a sane state.  Essentially, we do this as follows:
625  * - Obtain card status.  If the first attempt to obtain card status fails,
626  *   the status word will reflect the failed status cmd, not the failed
627  *   r/w cmd.  If we fail to obtain card status, it suggests we can no
628  *   longer communicate with the card.
629  * - Check the card state.  If the card received the cmd but there was a
630  *   transient problem with the response, it might still be in a data transfer
631  *   mode.  Try to send it a stop command.  If this fails, we can't recover.
632  * - If the r/w cmd failed due to a response CRC error, it was probably
633  *   transient, so retry the cmd.
634  * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
635  * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
636  *   illegal cmd, retry.
637  * Otherwise we don't understand what happened, so abort.
638  */
639 static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
640         struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
641 {
642         bool prev_cmd_status_valid = true;
643         u32 status, stop_status = 0;
644         int err, retry;
645
646         if (mmc_card_removed(card))
647                 return ERR_NOMEDIUM;
648
649         /*
650          * Try to get card status which indicates both the card state
651          * and why there was no response.  If the first attempt fails,
652          * we can't be sure the returned status is for the r/w command.
653          */
654         for (retry = 2; retry >= 0; retry--) {
655                 err = get_card_status(card, &status, 0);
656                 if (!err)
657                         break;
658
659                 prev_cmd_status_valid = false;
660                 pr_err("%s: error %d sending status command, %sing\n",
661                        req->rq_disk->disk_name, err, retry ? "retry" : "abort");
662         }
663
664         /* We couldn't get a response from the card.  Give up. */
665         if (err) {
666                 /* Check if the card is removed */
667                 if (mmc_detect_card_removed(card->host))
668                         return ERR_NOMEDIUM;
669                 return ERR_ABORT;
670         }
671
672         /* Flag ECC errors */
673         if ((status & R1_CARD_ECC_FAILED) ||
674             (brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
675             (brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
676                 *ecc_err = 1;
677
678         /* Flag General errors */
679         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
680                 if ((status & R1_ERROR) ||
681                         (brq->stop.resp[0] & R1_ERROR)) {
682                         pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
683                                req->rq_disk->disk_name, __func__,
684                                brq->stop.resp[0], status);
685                         *gen_err = 1;
686                 }
687
688         /*
689          * Check the current card state.  If it is in some data transfer
690          * mode, tell it to stop (and hopefully transition back to TRAN.)
691          */
692         if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
693             R1_CURRENT_STATE(status) == R1_STATE_RCV) {
694                 err = send_stop(card, &stop_status);
695                 if (err)
696                         pr_err("%s: error %d sending stop command\n",
697                                req->rq_disk->disk_name, err);
698
699                 /*
700                  * If the stop cmd also timed out, the card is probably
701                  * not present, so abort.  Other errors are bad news too.
702                  */
703                 if (err)
704                         return ERR_ABORT;
705                 if (stop_status & R1_CARD_ECC_FAILED)
706                         *ecc_err = 1;
707                 if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
708                         if (stop_status & R1_ERROR) {
709                                 pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
710                                        req->rq_disk->disk_name, __func__,
711                                        stop_status);
712                                 *gen_err = 1;
713                         }
714         }
715
716         /* Check for set block count errors */
717         if (brq->sbc.error)
718                 return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
719                                 prev_cmd_status_valid, status);
720
721         /* Check for r/w command errors */
722         if (brq->cmd.error)
723                 return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
724                                 prev_cmd_status_valid, status);
725
726         /* Data errors */
727         if (!brq->stop.error)
728                 return ERR_CONTINUE;
729
730         /* Now for stop errors.  These aren't fatal to the transfer. */
731         pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
732                req->rq_disk->disk_name, brq->stop.error,
733                brq->cmd.resp[0], status);
734
735         /*
736          * Subsitute in our own stop status as this will give the error
737          * state which happened during the execution of the r/w command.
738          */
739         if (stop_status) {
740                 brq->stop.resp[0] = stop_status;
741                 brq->stop.error = 0;
742         }
743         return ERR_CONTINUE;
744 }
745
746 static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
747                          int type)
748 {
749         int err;
750
751         if (md->reset_done & type)
752                 return -EEXIST;
753
754         md->reset_done |= type;
755         err = mmc_hw_reset(host);
756         /* Ensure we switch back to the correct partition */
757         if (err != -EOPNOTSUPP) {
758                 struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
759                 int part_err;
760
761                 main_md->part_curr = main_md->part_type;
762                 part_err = mmc_blk_part_switch(host->card, md);
763                 if (part_err) {
764                         /*
765                          * We have failed to get back into the correct
766                          * partition, so we need to abort the whole request.
767                          */
768                         return -ENODEV;
769                 }
770         }
771         return err;
772 }
773
774 static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
775 {
776         md->reset_done &= ~type;
777 }
778
779 static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
780 {
781         struct mmc_blk_data *md = mq->data;
782         struct mmc_card *card = md->queue.card;
783         unsigned int from, nr, arg;
784         int err = 0, type = MMC_BLK_DISCARD;
785
786         if (!mmc_can_erase(card)) {
787                 err = -EOPNOTSUPP;
788                 goto out;
789         }
790
791         from = blk_rq_pos(req);
792         nr = blk_rq_sectors(req);
793
794         if (mmc_can_discard(card))
795                 arg = MMC_DISCARD_ARG;
796         else if (mmc_can_trim(card))
797                 arg = MMC_TRIM_ARG;
798         else
799                 arg = MMC_ERASE_ARG;
800 retry:
801         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
802                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
803                                  INAND_CMD38_ARG_EXT_CSD,
804                                  arg == MMC_TRIM_ARG ?
805                                  INAND_CMD38_ARG_TRIM :
806                                  INAND_CMD38_ARG_ERASE,
807                                  0);
808                 if (err)
809                         goto out;
810         }
811         err = mmc_erase(card, from, nr, arg);
812 out:
813         if (err == -EIO && !mmc_blk_reset(md, card->host, type))
814                 goto retry;
815         if (!err)
816                 mmc_blk_reset_success(md, type);
817         spin_lock_irq(&md->lock);
818         __blk_end_request(req, err, blk_rq_bytes(req));
819         spin_unlock_irq(&md->lock);
820
821         return err ? 0 : 1;
822 }
823
824 static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
825                                        struct request *req)
826 {
827         struct mmc_blk_data *md = mq->data;
828         struct mmc_card *card = md->queue.card;
829         unsigned int from, nr, arg, trim_arg, erase_arg;
830         int err = 0, type = MMC_BLK_SECDISCARD;
831
832         if (!(mmc_can_secure_erase_trim(card) || mmc_can_sanitize(card))) {
833                 err = -EOPNOTSUPP;
834                 goto out;
835         }
836
837         from = blk_rq_pos(req);
838         nr = blk_rq_sectors(req);
839
840         /* The sanitize operation is supported at v4.5 only */
841         if (mmc_can_sanitize(card)) {
842                 erase_arg = MMC_ERASE_ARG;
843                 trim_arg = MMC_TRIM_ARG;
844         } else {
845                 erase_arg = MMC_SECURE_ERASE_ARG;
846                 trim_arg = MMC_SECURE_TRIM1_ARG;
847         }
848
849         if (mmc_erase_group_aligned(card, from, nr))
850                 arg = erase_arg;
851         else if (mmc_can_trim(card))
852                 arg = trim_arg;
853         else {
854                 err = -EINVAL;
855                 goto out;
856         }
857 retry:
858         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
859                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
860                                  INAND_CMD38_ARG_EXT_CSD,
861                                  arg == MMC_SECURE_TRIM1_ARG ?
862                                  INAND_CMD38_ARG_SECTRIM1 :
863                                  INAND_CMD38_ARG_SECERASE,
864                                  0);
865                 if (err)
866                         goto out_retry;
867         }
868
869         err = mmc_erase(card, from, nr, arg);
870         if (err == -EIO)
871                 goto out_retry;
872         if (err)
873                 goto out;
874
875         if (arg == MMC_SECURE_TRIM1_ARG) {
876                 if (card->quirks & MMC_QUIRK_INAND_CMD38) {
877                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
878                                          INAND_CMD38_ARG_EXT_CSD,
879                                          INAND_CMD38_ARG_SECTRIM2,
880                                          0);
881                         if (err)
882                                 goto out_retry;
883                 }
884
885                 err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
886                 if (err == -EIO)
887                         goto out_retry;
888                 if (err)
889                         goto out;
890         }
891
892         if (mmc_can_sanitize(card))
893                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
894                                  EXT_CSD_SANITIZE_START, 1, 0);
895 out_retry:
896         if (err && !mmc_blk_reset(md, card->host, type))
897                 goto retry;
898         if (!err)
899                 mmc_blk_reset_success(md, type);
900 out:
901         spin_lock_irq(&md->lock);
902         __blk_end_request(req, err, blk_rq_bytes(req));
903         spin_unlock_irq(&md->lock);
904
905         return err ? 0 : 1;
906 }
907
908 static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
909 {
910         struct mmc_blk_data *md = mq->data;
911         struct mmc_card *card = md->queue.card;
912         int ret = 0;
913
914         ret = mmc_flush_cache(card);
915         if (ret)
916                 ret = -EIO;
917
918         spin_lock_irq(&md->lock);
919         __blk_end_request_all(req, ret);
920         spin_unlock_irq(&md->lock);
921
922         return ret ? 0 : 1;
923 }
924
925 /*
926  * Reformat current write as a reliable write, supporting
927  * both legacy and the enhanced reliable write MMC cards.
928  * In each transfer we'll handle only as much as a single
929  * reliable write can handle, thus finish the request in
930  * partial completions.
931  */
932 static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
933                                     struct mmc_card *card,
934                                     struct request *req)
935 {
936         if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
937                 /* Legacy mode imposes restrictions on transfers. */
938                 if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
939                         brq->data.blocks = 1;
940
941                 if (brq->data.blocks > card->ext_csd.rel_sectors)
942                         brq->data.blocks = card->ext_csd.rel_sectors;
943                 else if (brq->data.blocks < card->ext_csd.rel_sectors)
944                         brq->data.blocks = 1;
945         }
946 }
947
948 #define CMD_ERRORS                                                      \
949         (R1_OUT_OF_RANGE |      /* Command argument out of range */     \
950          R1_ADDRESS_ERROR |     /* Misaligned address */                \
951          R1_BLOCK_LEN_ERROR |   /* Transferred block length incorrect */\
952          R1_WP_VIOLATION |      /* Tried to write to protected block */ \
953          R1_CC_ERROR |          /* Card controller error */             \
954          R1_ERROR)              /* General/unknown error */
955
956 static int mmc_blk_err_check(struct mmc_card *card,
957                              struct mmc_async_req *areq)
958 {
959         struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
960                                                     mmc_active);
961         struct mmc_blk_request *brq = &mq_mrq->brq;
962         struct request *req = mq_mrq->req;
963         int ecc_err = 0, gen_err = 0;
964
965         /*
966          * sbc.error indicates a problem with the set block count
967          * command.  No data will have been transferred.
968          *
969          * cmd.error indicates a problem with the r/w command.  No
970          * data will have been transferred.
971          *
972          * stop.error indicates a problem with the stop command.  Data
973          * may have been transferred, or may still be transferring.
974          */
975         if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
976             brq->data.error) {
977                 switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
978                 case ERR_RETRY:
979                         return MMC_BLK_RETRY;
980                 case ERR_ABORT:
981                         return MMC_BLK_ABORT;
982                 case ERR_NOMEDIUM:
983                         return MMC_BLK_NOMEDIUM;
984                 case ERR_CONTINUE:
985                         break;
986                 }
987         }
988
989         /*
990          * Check for errors relating to the execution of the
991          * initial command - such as address errors.  No data
992          * has been transferred.
993          */
994         if (brq->cmd.resp[0] & CMD_ERRORS) {
995                 pr_err("%s: r/w command failed, status = %#x\n",
996                        req->rq_disk->disk_name, brq->cmd.resp[0]);
997                 return MMC_BLK_ABORT;
998         }
999
1000         /*
1001          * Everything else is either success, or a data error of some
1002          * kind.  If it was a write, we may have transitioned to
1003          * program mode, which we have to wait for it to complete.
1004          */
1005         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
1006                 u32 status;
1007
1008                 /* Check stop command response */
1009                 if (brq->stop.resp[0] & R1_ERROR) {
1010                         pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
1011                                req->rq_disk->disk_name, __func__,
1012                                brq->stop.resp[0]);
1013                         gen_err = 1;
1014                 }
1015
1016                 do {
1017                         int err = get_card_status(card, &status, 5);
1018                         if (err) {
1019                                 pr_err("%s: error %d requesting status\n",
1020                                        req->rq_disk->disk_name, err);
1021                                 return MMC_BLK_CMD_ERR;
1022                         }
1023
1024                         if (status & R1_ERROR) {
1025                                 pr_err("%s: %s: general error sending status command, card status %#x\n",
1026                                        req->rq_disk->disk_name, __func__,
1027                                        status);
1028                                 gen_err = 1;
1029                         }
1030
1031                         /*
1032                          * Some cards mishandle the status bits,
1033                          * so make sure to check both the busy
1034                          * indication and the card state.
1035                          */
1036                 } while (!(status & R1_READY_FOR_DATA) ||
1037                          (R1_CURRENT_STATE(status) == R1_STATE_PRG));
1038         }
1039
1040         /* if general error occurs, retry the write operation. */
1041         if (gen_err) {
1042                 pr_warning("%s: retrying write for general error\n",
1043                                 req->rq_disk->disk_name);
1044                 return MMC_BLK_RETRY;
1045         }
1046
1047         if (brq->data.error) {
1048                 pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
1049                        req->rq_disk->disk_name, brq->data.error,
1050                        (unsigned)blk_rq_pos(req),
1051                        (unsigned)blk_rq_sectors(req),
1052                        brq->cmd.resp[0], brq->stop.resp[0]);
1053
1054                 if (rq_data_dir(req) == READ) {
1055                         if (ecc_err)
1056                                 return MMC_BLK_ECC_ERR;
1057                         return MMC_BLK_DATA_ERR;
1058                 } else {
1059                         return MMC_BLK_CMD_ERR;
1060                 }
1061         }
1062
1063         if (!brq->data.bytes_xfered)
1064                 return MMC_BLK_RETRY;
1065
1066         if (blk_rq_bytes(req) != brq->data.bytes_xfered)
1067                 return MMC_BLK_PARTIAL;
1068
1069         return MMC_BLK_SUCCESS;
1070 }
1071
1072 static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1073                                struct mmc_card *card,
1074                                int disable_multi,
1075                                struct mmc_queue *mq)
1076 {
1077         u32 readcmd, writecmd;
1078         struct mmc_blk_request *brq = &mqrq->brq;
1079         struct request *req = mqrq->req;
1080         struct mmc_blk_data *md = mq->data;
1081
1082         /*
1083          * Reliable writes are used to implement Forced Unit Access and
1084          * REQ_META accesses, and are supported only on MMCs.
1085          *
1086          * XXX: this really needs a good explanation of why REQ_META
1087          * is treated special.
1088          */
1089         bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
1090                           (req->cmd_flags & REQ_META)) &&
1091                 (rq_data_dir(req) == WRITE) &&
1092                 (md->flags & MMC_BLK_REL_WR);
1093
1094         memset(brq, 0, sizeof(struct mmc_blk_request));
1095         brq->mrq.cmd = &brq->cmd;
1096         brq->mrq.data = &brq->data;
1097
1098         brq->cmd.arg = blk_rq_pos(req);
1099         if (!mmc_card_blockaddr(card))
1100                 brq->cmd.arg <<= 9;
1101         brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1102         brq->data.blksz = 512;
1103         brq->stop.opcode = MMC_STOP_TRANSMISSION;
1104         brq->stop.arg = 0;
1105         brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1106         brq->data.blocks = blk_rq_sectors(req);
1107
1108         /*
1109          * The block layer doesn't support all sector count
1110          * restrictions, so we need to be prepared for too big
1111          * requests.
1112          */
1113         if (brq->data.blocks > card->host->max_blk_count)
1114                 brq->data.blocks = card->host->max_blk_count;
1115
1116         if (brq->data.blocks > 1) {
1117                 /*
1118                  * After a read error, we redo the request one sector
1119                  * at a time in order to accurately determine which
1120                  * sectors can be read successfully.
1121                  */
1122                 if (disable_multi)
1123                         brq->data.blocks = 1;
1124
1125                 /* Some controllers can't do multiblock reads due to hw bugs */
1126                 if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
1127                     rq_data_dir(req) == READ)
1128                         brq->data.blocks = 1;
1129         }
1130
1131         if (brq->data.blocks > 1 || do_rel_wr) {
1132                 /* SPI multiblock writes terminate using a special
1133                  * token, not a STOP_TRANSMISSION request.
1134                  */
1135                 if (!mmc_host_is_spi(card->host) ||
1136                     rq_data_dir(req) == READ)
1137                         brq->mrq.stop = &brq->stop;
1138                 readcmd = MMC_READ_MULTIPLE_BLOCK;
1139                 writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1140         } else {
1141                 brq->mrq.stop = NULL;
1142                 readcmd = MMC_READ_SINGLE_BLOCK;
1143                 writecmd = MMC_WRITE_BLOCK;
1144         }
1145         if (rq_data_dir(req) == READ) {
1146                 brq->cmd.opcode = readcmd;
1147                 brq->data.flags |= MMC_DATA_READ;
1148         } else {
1149                 brq->cmd.opcode = writecmd;
1150                 brq->data.flags |= MMC_DATA_WRITE;
1151         }
1152
1153         if (do_rel_wr)
1154                 mmc_apply_rel_rw(brq, card, req);
1155
1156         /*
1157          * Pre-defined multi-block transfers are preferable to
1158          * open ended-ones (and necessary for reliable writes).
1159          * However, it is not sufficient to just send CMD23,
1160          * and avoid the final CMD12, as on an error condition
1161          * CMD12 (stop) needs to be sent anyway. This, coupled
1162          * with Auto-CMD23 enhancements provided by some
1163          * hosts, means that the complexity of dealing
1164          * with this is best left to the host. If CMD23 is
1165          * supported by card and host, we'll fill sbc in and let
1166          * the host deal with handling it correctly. This means
1167          * that for hosts that don't expose MMC_CAP_CMD23, no
1168          * change of behavior will be observed.
1169          *
1170          * N.B: Some MMC cards experience perf degradation.
1171          * We'll avoid using CMD23-bounded multiblock writes for
1172          * these, while retaining features like reliable writes.
1173          */
1174
1175         if ((md->flags & MMC_BLK_CMD23) &&
1176             mmc_op_multi(brq->cmd.opcode) &&
1177             (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23))) {
1178                 brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1179                 brq->sbc.arg = brq->data.blocks |
1180                         (do_rel_wr ? (1 << 31) : 0);
1181                 brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1182                 brq->mrq.sbc = &brq->sbc;
1183         }
1184
1185         mmc_set_data_timeout(&brq->data, card);
1186
1187         brq->data.sg = mqrq->sg;
1188         brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1189
1190         /*
1191          * Adjust the sg list so it is the same size as the
1192          * request.
1193          */
1194         if (brq->data.blocks != blk_rq_sectors(req)) {
1195                 int i, data_size = brq->data.blocks << 9;
1196                 struct scatterlist *sg;
1197
1198                 for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1199                         data_size -= sg->length;
1200                         if (data_size <= 0) {
1201                                 sg->length += data_size;
1202                                 i++;
1203                                 break;
1204                         }
1205                 }
1206                 brq->data.sg_len = i;
1207         }
1208
1209         mqrq->mmc_active.mrq = &brq->mrq;
1210         mqrq->mmc_active.err_check = mmc_blk_err_check;
1211
1212         mmc_queue_bounce_pre(mqrq);
1213 }
1214
1215 static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
1216                            struct mmc_blk_request *brq, struct request *req,
1217                            int ret)
1218 {
1219         /*
1220          * If this is an SD card and we're writing, we can first
1221          * mark the known good sectors as ok.
1222          *
1223          * If the card is not SD, we can still ok written sectors
1224          * as reported by the controller (which might be less than
1225          * the real number of written sectors, but never more).
1226          */
1227         if (mmc_card_sd(card)) {
1228                 u32 blocks;
1229
1230                 blocks = mmc_sd_num_wr_blocks(card);
1231                 if (blocks != (u32)-1) {
1232                         spin_lock_irq(&md->lock);
1233                         ret = __blk_end_request(req, 0, blocks << 9);
1234                         spin_unlock_irq(&md->lock);
1235                 }
1236         } else {
1237                 spin_lock_irq(&md->lock);
1238                 ret = __blk_end_request(req, 0, brq->data.bytes_xfered);
1239                 spin_unlock_irq(&md->lock);
1240         }
1241         return ret;
1242 }
1243
1244 static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
1245 {
1246         struct mmc_blk_data *md = mq->data;
1247         struct mmc_card *card = md->queue.card;
1248         struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
1249         int ret = 1, disable_multi = 0, retry = 0, type;
1250         enum mmc_blk_status status;
1251         struct mmc_queue_req *mq_rq;
1252         struct request *req;
1253         struct mmc_async_req *areq;
1254
1255         if (!rqc && !mq->mqrq_prev->req)
1256                 return 0;
1257
1258         do {
1259                 if (rqc) {
1260                         mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1261                         areq = &mq->mqrq_cur->mmc_active;
1262                 } else
1263                         areq = NULL;
1264                 areq = mmc_start_req(card->host, areq, (int *) &status);
1265                 if (!areq)
1266                         return 0;
1267
1268                 mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
1269                 brq = &mq_rq->brq;
1270                 req = mq_rq->req;
1271                 type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1272                 mmc_queue_bounce_post(mq_rq);
1273
1274                 switch (status) {
1275                 case MMC_BLK_SUCCESS:
1276                 case MMC_BLK_PARTIAL:
1277                         /*
1278                          * A block was successfully transferred.
1279                          */
1280                         mmc_blk_reset_success(md, type);
1281                         spin_lock_irq(&md->lock);
1282                         ret = __blk_end_request(req, 0,
1283                                                 brq->data.bytes_xfered);
1284                         spin_unlock_irq(&md->lock);
1285                         /*
1286                          * If the blk_end_request function returns non-zero even
1287                          * though all data has been transferred and no errors
1288                          * were returned by the host controller, it's a bug.
1289                          */
1290                         if (status == MMC_BLK_SUCCESS && ret) {
1291                                 pr_err("%s BUG rq_tot %d d_xfer %d\n",
1292                                        __func__, blk_rq_bytes(req),
1293                                        brq->data.bytes_xfered);
1294                                 rqc = NULL;
1295                                 goto cmd_abort;
1296                         }
1297                         break;
1298                 case MMC_BLK_CMD_ERR:
1299                         ret = mmc_blk_cmd_err(md, card, brq, req, ret);
1300                         if (!mmc_blk_reset(md, card->host, type))
1301                                 break;
1302                         goto cmd_abort;
1303                 case MMC_BLK_RETRY:
1304                         if (retry++ < 5)
1305                                 break;
1306                         /* Fall through */
1307                 case MMC_BLK_ABORT:
1308                         if (!mmc_blk_reset(md, card->host, type))
1309                                 break;
1310                         goto cmd_abort;
1311                 case MMC_BLK_DATA_ERR: {
1312                         int err;
1313
1314                         err = mmc_blk_reset(md, card->host, type);
1315                         if (!err)
1316                                 break;
1317                         if (err == -ENODEV)
1318                                 goto cmd_abort;
1319                         /* Fall through */
1320                 }
1321                 case MMC_BLK_ECC_ERR:
1322                         if (brq->data.blocks > 1) {
1323                                 /* Redo read one sector at a time */
1324                                 pr_warning("%s: retrying using single block read\n",
1325                                            req->rq_disk->disk_name);
1326                                 disable_multi = 1;
1327                                 break;
1328                         }
1329                         /*
1330                          * After an error, we redo I/O one sector at a
1331                          * time, so we only reach here after trying to
1332                          * read a single sector.
1333                          */
1334                         spin_lock_irq(&md->lock);
1335                         ret = __blk_end_request(req, -EIO,
1336                                                 brq->data.blksz);
1337                         spin_unlock_irq(&md->lock);
1338                         if (!ret)
1339                                 goto start_new_req;
1340                         break;
1341                 case MMC_BLK_NOMEDIUM:
1342                         goto cmd_abort;
1343                 }
1344
1345                 if (ret) {
1346                         /*
1347                          * In case of a incomplete request
1348                          * prepare it again and resend.
1349                          */
1350                         mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq);
1351                         mmc_start_req(card->host, &mq_rq->mmc_active, NULL);
1352                 }
1353         } while (ret);
1354
1355         return 1;
1356
1357  cmd_abort:
1358         spin_lock_irq(&md->lock);
1359         if (mmc_card_removed(card))
1360                 req->cmd_flags |= REQ_QUIET;
1361         while (ret)
1362                 ret = __blk_end_request(req, -EIO, blk_rq_cur_bytes(req));
1363         spin_unlock_irq(&md->lock);
1364
1365  start_new_req:
1366         if (rqc) {
1367                 mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1368                 mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL);
1369         }
1370
1371         return 0;
1372 }
1373
1374 static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
1375 {
1376         int ret;
1377         struct mmc_blk_data *md = mq->data;
1378         struct mmc_card *card = md->queue.card;
1379
1380         if (req && !mq->mqrq_prev->req)
1381                 /* claim host only for the first request */
1382                 mmc_claim_host(card->host);
1383
1384         ret = mmc_blk_part_switch(card, md);
1385         if (ret) {
1386                 if (req) {
1387                         spin_lock_irq(&md->lock);
1388                         __blk_end_request_all(req, -EIO);
1389                         spin_unlock_irq(&md->lock);
1390                 }
1391                 ret = 0;
1392                 goto out;
1393         }
1394
1395         if (req && req->cmd_flags & REQ_DISCARD) {
1396                 /* complete ongoing async transfer before issuing discard */
1397                 if (card->host->areq)
1398                         mmc_blk_issue_rw_rq(mq, NULL);
1399                 if (req->cmd_flags & REQ_SECURE &&
1400                         !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
1401                         ret = mmc_blk_issue_secdiscard_rq(mq, req);
1402                 else
1403                         ret = mmc_blk_issue_discard_rq(mq, req);
1404         } else if (req && req->cmd_flags & REQ_FLUSH) {
1405                 /* complete ongoing async transfer before issuing flush */
1406                 if (card->host->areq)
1407                         mmc_blk_issue_rw_rq(mq, NULL);
1408                 ret = mmc_blk_issue_flush(mq, req);
1409         } else {
1410                 ret = mmc_blk_issue_rw_rq(mq, req);
1411         }
1412
1413 out:
1414         if (!req)
1415                 /* release host only when there are no more requests */
1416                 mmc_release_host(card->host);
1417         return ret;
1418 }
1419
1420 static inline int mmc_blk_readonly(struct mmc_card *card)
1421 {
1422         return mmc_card_readonly(card) ||
1423                !(card->csd.cmdclass & CCC_BLOCK_WRITE);
1424 }
1425
1426 static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
1427                                               struct device *parent,
1428                                               sector_t size,
1429                                               bool default_ro,
1430                                               const char *subname)
1431 {
1432         struct mmc_blk_data *md;
1433         int devidx, ret;
1434
1435         devidx = find_first_zero_bit(dev_use, max_devices);
1436         if (devidx >= max_devices)
1437                 return ERR_PTR(-ENOSPC);
1438         __set_bit(devidx, dev_use);
1439
1440         md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
1441         if (!md) {
1442                 ret = -ENOMEM;
1443                 goto out;
1444         }
1445
1446         /*
1447          * !subname implies we are creating main mmc_blk_data that will be
1448          * associated with mmc_card with mmc_set_drvdata. Due to device
1449          * partitions, devidx will not coincide with a per-physical card
1450          * index anymore so we keep track of a name index.
1451          */
1452         if (!subname) {
1453                 md->name_idx = find_first_zero_bit(name_use, max_devices);
1454                 __set_bit(md->name_idx, name_use);
1455         }
1456         else
1457                 md->name_idx = ((struct mmc_blk_data *)
1458                                 dev_to_disk(parent)->private_data)->name_idx;
1459
1460         /*
1461          * Set the read-only status based on the supported commands
1462          * and the write protect switch.
1463          */
1464         md->read_only = mmc_blk_readonly(card);
1465
1466         md->disk = alloc_disk(perdev_minors);
1467         if (md->disk == NULL) {
1468                 ret = -ENOMEM;
1469                 goto err_kfree;
1470         }
1471
1472         spin_lock_init(&md->lock);
1473         INIT_LIST_HEAD(&md->part);
1474         md->usage = 1;
1475
1476         ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
1477         if (ret)
1478                 goto err_putdisk;
1479
1480         md->queue.issue_fn = mmc_blk_issue_rq;
1481         md->queue.data = md;
1482
1483         md->disk->major = MMC_BLOCK_MAJOR;
1484         md->disk->first_minor = devidx * perdev_minors;
1485         md->disk->fops = &mmc_bdops;
1486         md->disk->private_data = md;
1487         md->disk->queue = md->queue.queue;
1488         md->disk->driverfs_dev = parent;
1489         set_disk_ro(md->disk, md->read_only || default_ro);
1490
1491         /*
1492          * As discussed on lkml, GENHD_FL_REMOVABLE should:
1493          *
1494          * - be set for removable media with permanent block devices
1495          * - be unset for removable block devices with permanent media
1496          *
1497          * Since MMC block devices clearly fall under the second
1498          * case, we do not set GENHD_FL_REMOVABLE.  Userspace
1499          * should use the block device creation/destruction hotplug
1500          * messages to tell when the card is present.
1501          */
1502
1503         snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
1504                  "mmcblk%d%s", md->name_idx, subname ? subname : "");
1505
1506         blk_queue_logical_block_size(md->queue.queue, 512);
1507         set_capacity(md->disk, size);
1508
1509         if (mmc_host_cmd23(card->host)) {
1510                 if (mmc_card_mmc(card) ||
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