Merge branch 'linux-linaro-lsk-v3.10' into linux-linaro-lsk-v3.10-android
[firefly-linux-kernel-4.4.55.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 #define CREATE_TRACE_POINTS
39 #include <trace/events/mmc.h>
40
41 #include <linux/mmc/ioctl.h>
42 #include <linux/mmc/card.h>
43 #include <linux/mmc/host.h>
44 #include <linux/mmc/mmc.h>
45 #include <linux/mmc/sd.h>
46
47 #include <asm/uaccess.h>
48
49 #include "queue.h"
50
51 MODULE_ALIAS("mmc:block");
52 #ifdef MODULE_PARAM_PREFIX
53 #undef MODULE_PARAM_PREFIX
54 #endif
55 #define MODULE_PARAM_PREFIX "mmcblk."
56
57 #define INAND_CMD38_ARG_EXT_CSD  113
58 #define INAND_CMD38_ARG_ERASE    0x00
59 #define INAND_CMD38_ARG_TRIM     0x01
60 #define INAND_CMD38_ARG_SECERASE 0x80
61 #define INAND_CMD38_ARG_SECTRIM1 0x81
62 #define INAND_CMD38_ARG_SECTRIM2 0x88
63 #define MMC_BLK_TIMEOUT_MS  (10 * 60 * 1000)        /* 10 minute timeout */
64
65 #define mmc_req_rel_wr(req)     (((req->cmd_flags & REQ_FUA) || \
66                                   (req->cmd_flags & REQ_META)) && \
67                                   (rq_data_dir(req) == WRITE))
68 #define PACKED_CMD_VER  0x01
69 #define PACKED_CMD_WR   0x02
70
71 static DEFINE_MUTEX(block_mutex);
72
73 /*
74  * The defaults come from config options but can be overriden by module
75  * or bootarg options.
76  */
77 static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
78
79 /*
80  * We've only got one major, so number of mmcblk devices is
81  * limited to 256 / number of minors per device.
82  */
83 static int max_devices;
84
85 /* 256 minors, so at most 256 separate devices */
86 static DECLARE_BITMAP(dev_use, 256);
87 static DECLARE_BITMAP(name_use, 256);
88
89 /*
90  * There is one mmc_blk_data per slot.
91  */
92 struct mmc_blk_data {
93         spinlock_t      lock;
94         struct gendisk  *disk;
95         struct mmc_queue queue;
96         struct list_head part;
97
98         unsigned int    flags;
99 #define MMC_BLK_CMD23   (1 << 0)        /* Can do SET_BLOCK_COUNT for multiblock */
100 #define MMC_BLK_REL_WR  (1 << 1)        /* MMC Reliable write support */
101 #define MMC_BLK_PACKED_CMD      (1 << 2)        /* MMC packed command support */
102
103         unsigned int    usage;
104         unsigned int    read_only;
105         unsigned int    part_type;
106         unsigned int    name_idx;
107         unsigned int    reset_done;
108 #define MMC_BLK_READ            BIT(0)
109 #define MMC_BLK_WRITE           BIT(1)
110 #define MMC_BLK_DISCARD         BIT(2)
111 #define MMC_BLK_SECDISCARD      BIT(3)
112
113         /*
114          * Only set in main mmc_blk_data associated
115          * with mmc_card with mmc_set_drvdata, and keeps
116          * track of the current selected device partition.
117          */
118         unsigned int    part_curr;
119         struct device_attribute force_ro;
120         struct device_attribute power_ro_lock;
121         int     area_type;
122 };
123
124 static DEFINE_MUTEX(open_lock);
125
126 enum {
127         MMC_PACKED_NR_IDX = -1,
128         MMC_PACKED_NR_ZERO,
129         MMC_PACKED_NR_SINGLE,
130 };
131
132 module_param(perdev_minors, int, 0444);
133 MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
134
135 static inline int mmc_blk_part_switch(struct mmc_card *card,
136                                       struct mmc_blk_data *md);
137 static int get_card_status(struct mmc_card *card, u32 *status, int retries);
138
139 static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq)
140 {
141         struct mmc_packed *packed = mqrq->packed;
142
143         BUG_ON(!packed);
144
145         mqrq->cmd_type = MMC_PACKED_NONE;
146         packed->nr_entries = MMC_PACKED_NR_ZERO;
147         packed->idx_failure = MMC_PACKED_NR_IDX;
148         packed->retries = 0;
149         packed->blocks = 0;
150 }
151
152 static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
153 {
154         struct mmc_blk_data *md;
155
156         mutex_lock(&open_lock);
157         md = disk->private_data;
158         if (md && md->usage == 0)
159                 md = NULL;
160         if (md)
161                 md->usage++;
162         mutex_unlock(&open_lock);
163
164         return md;
165 }
166
167 static inline int mmc_get_devidx(struct gendisk *disk)
168 {
169         int devidx = disk->first_minor / perdev_minors;
170         return devidx;
171 }
172
173 static void mmc_blk_put(struct mmc_blk_data *md)
174 {
175         mutex_lock(&open_lock);
176         md->usage--;
177         if (md->usage == 0) {
178                 int devidx = mmc_get_devidx(md->disk);
179                 blk_cleanup_queue(md->queue.queue);
180
181                 __clear_bit(devidx, dev_use);
182
183                 put_disk(md->disk);
184                 kfree(md);
185         }
186         mutex_unlock(&open_lock);
187 }
188
189 static ssize_t power_ro_lock_show(struct device *dev,
190                 struct device_attribute *attr, char *buf)
191 {
192         int ret;
193         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
194         struct mmc_card *card = md->queue.card;
195         int locked = 0;
196
197         if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN)
198                 locked = 2;
199         else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN)
200                 locked = 1;
201
202         ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
203
204         mmc_blk_put(md);
205
206         return ret;
207 }
208
209 static ssize_t power_ro_lock_store(struct device *dev,
210                 struct device_attribute *attr, const char *buf, size_t count)
211 {
212         int ret;
213         struct mmc_blk_data *md, *part_md;
214         struct mmc_card *card;
215         unsigned long set;
216
217         if (kstrtoul(buf, 0, &set))
218                 return -EINVAL;
219
220         if (set != 1)
221                 return count;
222
223         md = mmc_blk_get(dev_to_disk(dev));
224         card = md->queue.card;
225
226         mmc_claim_host(card->host);
227
228         ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP,
229                                 card->ext_csd.boot_ro_lock |
230                                 EXT_CSD_BOOT_WP_B_PWR_WP_EN,
231                                 card->ext_csd.part_time);
232         if (ret)
233                 pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret);
234         else
235                 card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN;
236
237         mmc_release_host(card->host);
238
239         if (!ret) {
240                 pr_info("%s: Locking boot partition ro until next power on\n",
241                         md->disk->disk_name);
242                 set_disk_ro(md->disk, 1);
243
244                 list_for_each_entry(part_md, &md->part, part)
245                         if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) {
246                                 pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
247                                 set_disk_ro(part_md->disk, 1);
248                         }
249         }
250
251         mmc_blk_put(md);
252         return count;
253 }
254
255 static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
256                              char *buf)
257 {
258         int ret;
259         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
260
261         ret = snprintf(buf, PAGE_SIZE, "%d\n",
262                        get_disk_ro(dev_to_disk(dev)) ^
263                        md->read_only);
264         mmc_blk_put(md);
265         return ret;
266 }
267
268 static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
269                               const char *buf, size_t count)
270 {
271         int ret;
272         char *end;
273         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
274         unsigned long set = simple_strtoul(buf, &end, 0);
275         if (end == buf) {
276                 ret = -EINVAL;
277                 goto out;
278         }
279
280         set_disk_ro(dev_to_disk(dev), set || md->read_only);
281         ret = count;
282 out:
283         mmc_blk_put(md);
284         return ret;
285 }
286
287 static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
288 {
289         struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
290         int ret = -ENXIO;
291
292         mutex_lock(&block_mutex);
293         if (md) {
294                 if (md->usage == 2)
295                         check_disk_change(bdev);
296                 ret = 0;
297
298                 if ((mode & FMODE_WRITE) && md->read_only) {
299                         mmc_blk_put(md);
300                         ret = -EROFS;
301                 }
302         }
303         mutex_unlock(&block_mutex);
304
305         return ret;
306 }
307
308 static void mmc_blk_release(struct gendisk *disk, fmode_t mode)
309 {
310         struct mmc_blk_data *md = disk->private_data;
311
312         mutex_lock(&block_mutex);
313         mmc_blk_put(md);
314         mutex_unlock(&block_mutex);
315 }
316
317 static int
318 mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
319 {
320         geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
321         geo->heads = 4;
322         geo->sectors = 16;
323         return 0;
324 }
325
326 struct mmc_blk_ioc_data {
327         struct mmc_ioc_cmd ic;
328         unsigned char *buf;
329         u64 buf_bytes;
330 };
331
332 static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
333         struct mmc_ioc_cmd __user *user)
334 {
335         struct mmc_blk_ioc_data *idata;
336         int err;
337
338         idata = kzalloc(sizeof(*idata), GFP_KERNEL);
339         if (!idata) {
340                 err = -ENOMEM;
341                 goto out;
342         }
343
344         if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
345                 err = -EFAULT;
346                 goto idata_err;
347         }
348
349         idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
350         if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
351                 err = -EOVERFLOW;
352                 goto idata_err;
353         }
354
355         if (!idata->buf_bytes)
356                 return idata;
357
358         idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
359         if (!idata->buf) {
360                 err = -ENOMEM;
361                 goto idata_err;
362         }
363
364         if (copy_from_user(idata->buf, (void __user *)(unsigned long)
365                                         idata->ic.data_ptr, idata->buf_bytes)) {
366                 err = -EFAULT;
367                 goto copy_err;
368         }
369
370         return idata;
371
372 copy_err:
373         kfree(idata->buf);
374 idata_err:
375         kfree(idata);
376 out:
377         return ERR_PTR(err);
378 }
379
380 static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status,
381                                        u32 retries_max)
382 {
383         int err;
384         u32 retry_count = 0;
385
386         if (!status || !retries_max)
387                 return -EINVAL;
388
389         do {
390                 err = get_card_status(card, status, 5);
391                 if (err)
392                         break;
393
394                 if (!R1_STATUS(*status) &&
395                                 (R1_CURRENT_STATE(*status) != R1_STATE_PRG))
396                         break; /* RPMB programming operation complete */
397
398                 /*
399                  * Rechedule to give the MMC device a chance to continue
400                  * processing the previous command without being polled too
401                  * frequently.
402                  */
403                 usleep_range(1000, 5000);
404         } while (++retry_count < retries_max);
405
406         if (retry_count == retries_max)
407                 err = -EPERM;
408
409         return err;
410 }
411
412 static int mmc_blk_ioctl_cmd(struct block_device *bdev,
413         struct mmc_ioc_cmd __user *ic_ptr)
414 {
415         struct mmc_blk_ioc_data *idata;
416         struct mmc_blk_data *md;
417         struct mmc_card *card;
418         struct mmc_command cmd = {0};
419         struct mmc_data data = {0};
420         struct mmc_request mrq = {NULL};
421         struct scatterlist sg;
422         int err;
423         int is_rpmb = false;
424         u32 status = 0;
425
426         /*
427          * The caller must have CAP_SYS_RAWIO, and must be calling this on the
428          * whole block device, not on a partition.  This prevents overspray
429          * between sibling partitions.
430          */
431         if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
432                 return -EPERM;
433
434         idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
435         if (IS_ERR(idata))
436                 return PTR_ERR(idata);
437
438         md = mmc_blk_get(bdev->bd_disk);
439         if (!md) {
440                 err = -EINVAL;
441                 goto cmd_err;
442         }
443
444         if (md->area_type & MMC_BLK_DATA_AREA_RPMB)
445                 is_rpmb = true;
446
447         card = md->queue.card;
448         if (IS_ERR(card)) {
449                 err = PTR_ERR(card);
450                 goto cmd_done;
451         }
452
453         cmd.opcode = idata->ic.opcode;
454         cmd.arg = idata->ic.arg;
455         cmd.flags = idata->ic.flags;
456
457         if (idata->buf_bytes) {
458                 data.sg = &sg;
459                 data.sg_len = 1;
460                 data.blksz = idata->ic.blksz;
461                 data.blocks = idata->ic.blocks;
462
463                 sg_init_one(data.sg, idata->buf, idata->buf_bytes);
464
465                 if (idata->ic.write_flag)
466                         data.flags = MMC_DATA_WRITE;
467                 else
468                         data.flags = MMC_DATA_READ;
469
470                 /* data.flags must already be set before doing this. */
471                 mmc_set_data_timeout(&data, card);
472
473                 /* Allow overriding the timeout_ns for empirical tuning. */
474                 if (idata->ic.data_timeout_ns)
475                         data.timeout_ns = idata->ic.data_timeout_ns;
476
477                 if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
478                         /*
479                          * Pretend this is a data transfer and rely on the
480                          * host driver to compute timeout.  When all host
481                          * drivers support cmd.cmd_timeout for R1B, this
482                          * can be changed to:
483                          *
484                          *     mrq.data = NULL;
485                          *     cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
486                          */
487                         data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
488                 }
489
490                 mrq.data = &data;
491         }
492
493         mrq.cmd = &cmd;
494
495         mmc_claim_host(card->host);
496
497         err = mmc_blk_part_switch(card, md);
498         if (err)
499                 goto cmd_rel_host;
500
501         if (idata->ic.is_acmd) {
502                 err = mmc_app_cmd(card->host, card);
503                 if (err)
504                         goto cmd_rel_host;
505         }
506
507         if (is_rpmb) {
508                 err = mmc_set_blockcount(card, data.blocks,
509                         idata->ic.write_flag & (1 << 31));
510                 if (err)
511                         goto cmd_rel_host;
512         }
513
514         mmc_wait_for_req(card->host, &mrq);
515
516         if (cmd.error) {
517                 dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
518                                                 __func__, cmd.error);
519                 err = cmd.error;
520                 goto cmd_rel_host;
521         }
522         if (data.error) {
523                 dev_err(mmc_dev(card->host), "%s: data error %d\n",
524                                                 __func__, data.error);
525                 err = data.error;
526                 goto cmd_rel_host;
527         }
528
529         /*
530          * According to the SD specs, some commands require a delay after
531          * issuing the command.
532          */
533         if (idata->ic.postsleep_min_us)
534                 usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
535
536         if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) {
537                 err = -EFAULT;
538                 goto cmd_rel_host;
539         }
540
541         if (!idata->ic.write_flag) {
542                 if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr,
543                                                 idata->buf, idata->buf_bytes)) {
544                         err = -EFAULT;
545                         goto cmd_rel_host;
546                 }
547         }
548
549         if (is_rpmb) {
550                 /*
551                  * Ensure RPMB command has completed by polling CMD13
552                  * "Send Status".
553                  */
554                 err = ioctl_rpmb_card_status_poll(card, &status, 5);
555                 if (err)
556                         dev_err(mmc_dev(card->host),
557                                         "%s: Card Status=0x%08X, error %d\n",
558                                         __func__, status, err);
559         }
560
561 cmd_rel_host:
562         mmc_release_host(card->host);
563
564 cmd_done:
565         mmc_blk_put(md);
566 cmd_err:
567         kfree(idata->buf);
568         kfree(idata);
569         return err;
570 }
571
572 static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
573         unsigned int cmd, unsigned long arg)
574 {
575         int ret = -EINVAL;
576         if (cmd == MMC_IOC_CMD)
577                 ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
578         return ret;
579 }
580
581 #ifdef CONFIG_COMPAT
582 static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
583         unsigned int cmd, unsigned long arg)
584 {
585         return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
586 }
587 #endif
588
589 static const struct block_device_operations mmc_bdops = {
590         .open                   = mmc_blk_open,
591         .release                = mmc_blk_release,
592         .getgeo                 = mmc_blk_getgeo,
593         .owner                  = THIS_MODULE,
594         .ioctl                  = mmc_blk_ioctl,
595 #ifdef CONFIG_COMPAT
596         .compat_ioctl           = mmc_blk_compat_ioctl,
597 #endif
598 };
599
600 static inline int mmc_blk_part_switch(struct mmc_card *card,
601                                       struct mmc_blk_data *md)
602 {
603         int ret;
604         struct mmc_blk_data *main_md = mmc_get_drvdata(card);
605
606         if (main_md->part_curr == md->part_type)
607                 return 0;
608
609         if (mmc_card_mmc(card)) {
610                 u8 part_config = card->ext_csd.part_config;
611
612                 part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
613                 part_config |= md->part_type;
614
615                 ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
616                                  EXT_CSD_PART_CONFIG, part_config,
617                                  card->ext_csd.part_time);
618                 if (ret)
619                         return ret;
620
621                 card->ext_csd.part_config = part_config;
622         }
623
624         main_md->part_curr = md->part_type;
625         return 0;
626 }
627
628 static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
629 {
630         int err;
631         u32 result;
632         __be32 *blocks;
633
634         struct mmc_request mrq = {NULL};
635         struct mmc_command cmd = {0};
636         struct mmc_data data = {0};
637
638         struct scatterlist sg;
639
640         cmd.opcode = MMC_APP_CMD;
641         cmd.arg = card->rca << 16;
642         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
643
644         err = mmc_wait_for_cmd(card->host, &cmd, 0);
645         if (err)
646                 return (u32)-1;
647         if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
648                 return (u32)-1;
649
650         memset(&cmd, 0, sizeof(struct mmc_command));
651
652         cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
653         cmd.arg = 0;
654         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
655
656         data.blksz = 4;
657         data.blocks = 1;
658         data.flags = MMC_DATA_READ;
659         data.sg = &sg;
660         data.sg_len = 1;
661         mmc_set_data_timeout(&data, card);
662
663         mrq.cmd = &cmd;
664         mrq.data = &data;
665
666         blocks = kmalloc(4, GFP_KERNEL);
667         if (!blocks)
668                 return (u32)-1;
669
670         sg_init_one(&sg, blocks, 4);
671
672         mmc_wait_for_req(card->host, &mrq);
673
674         result = ntohl(*blocks);
675         kfree(blocks);
676
677         if (cmd.error || data.error)
678                 result = (u32)-1;
679
680         return result;
681 }
682
683 static int send_stop(struct mmc_card *card, u32 *status)
684 {
685         struct mmc_command cmd = {0};
686         int err;
687
688         cmd.opcode = MMC_STOP_TRANSMISSION;
689         cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
690         err = mmc_wait_for_cmd(card->host, &cmd, 5);
691         if (err == 0)
692                 *status = cmd.resp[0];
693         return err;
694 }
695
696 static int get_card_status(struct mmc_card *card, u32 *status, int retries)
697 {
698         struct mmc_command cmd = {0};
699         int err;
700
701         cmd.opcode = MMC_SEND_STATUS;
702         if (!mmc_host_is_spi(card->host))
703                 cmd.arg = card->rca << 16;
704         cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
705         err = mmc_wait_for_cmd(card->host, &cmd, retries);
706         if (err == 0)
707                 *status = cmd.resp[0];
708         return err;
709 }
710
711 #define ERR_NOMEDIUM    3
712 #define ERR_RETRY       2
713 #define ERR_ABORT       1
714 #define ERR_CONTINUE    0
715
716 static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
717         bool status_valid, u32 status)
718 {
719         switch (error) {
720         case -EILSEQ:
721                 /* response crc error, retry the r/w cmd */
722                 pr_err("%s: %s sending %s command, card status %#x\n",
723                         req->rq_disk->disk_name, "response CRC error",
724                         name, status);
725                 return ERR_RETRY;
726
727         case -ETIMEDOUT:
728                 pr_err("%s: %s sending %s command, card status %#x\n",
729                         req->rq_disk->disk_name, "timed out", name, status);
730
731                 /* If the status cmd initially failed, retry the r/w cmd */
732                 if (!status_valid) {
733                         pr_err("%s: status not valid, retrying timeout\n", req->rq_disk->disk_name);
734                         return ERR_RETRY;
735                 }
736                 /*
737                  * If it was a r/w cmd crc error, or illegal command
738                  * (eg, issued in wrong state) then retry - we should
739                  * have corrected the state problem above.
740                  */
741                 if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) {
742                         pr_err("%s: command error, retrying timeout\n", req->rq_disk->disk_name);
743                         return ERR_RETRY;
744                 }
745
746                 /* Otherwise abort the command */
747                 pr_err("%s: not retrying timeout\n", req->rq_disk->disk_name);
748                 return ERR_ABORT;
749
750         default:
751                 /* We don't understand the error code the driver gave us */
752                 pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
753                        req->rq_disk->disk_name, error, status);
754                 return ERR_ABORT;
755         }
756 }
757
758 /*
759  * Initial r/w and stop cmd error recovery.
760  * We don't know whether the card received the r/w cmd or not, so try to
761  * restore things back to a sane state.  Essentially, we do this as follows:
762  * - Obtain card status.  If the first attempt to obtain card status fails,
763  *   the status word will reflect the failed status cmd, not the failed
764  *   r/w cmd.  If we fail to obtain card status, it suggests we can no
765  *   longer communicate with the card.
766  * - Check the card state.  If the card received the cmd but there was a
767  *   transient problem with the response, it might still be in a data transfer
768  *   mode.  Try to send it a stop command.  If this fails, we can't recover.
769  * - If the r/w cmd failed due to a response CRC error, it was probably
770  *   transient, so retry the cmd.
771  * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
772  * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
773  *   illegal cmd, retry.
774  * Otherwise we don't understand what happened, so abort.
775  */
776 static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
777         struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
778 {
779         bool prev_cmd_status_valid = true;
780         u32 status, stop_status = 0;
781         int err, retry;
782
783         if (mmc_card_removed(card))
784                 return ERR_NOMEDIUM;
785
786         /*
787          * Try to get card status which indicates both the card state
788          * and why there was no response.  If the first attempt fails,
789          * we can't be sure the returned status is for the r/w command.
790          */
791         for (retry = 2; retry >= 0; retry--) {
792                 err = get_card_status(card, &status, 0);
793                 if (!err)
794                         break;
795
796                 prev_cmd_status_valid = false;
797                 pr_err("%s: error %d sending status command, %sing\n",
798                        req->rq_disk->disk_name, err, retry ? "retry" : "abort");
799         }
800
801         /* We couldn't get a response from the card.  Give up. */
802         if (err) {
803                 /* Check if the card is removed */
804                 if (mmc_detect_card_removed(card->host))
805                         return ERR_NOMEDIUM;
806                 return ERR_ABORT;
807         }
808
809         /* Flag ECC errors */
810         if ((status & R1_CARD_ECC_FAILED) ||
811             (brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
812             (brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
813                 *ecc_err = 1;
814
815         /* Flag General errors */
816         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
817                 if ((status & R1_ERROR) ||
818                         (brq->stop.resp[0] & R1_ERROR)) {
819                         pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
820                                req->rq_disk->disk_name, __func__,
821                                brq->stop.resp[0], status);
822                         *gen_err = 1;
823                 }
824
825         /*
826          * Check the current card state.  If it is in some data transfer
827          * mode, tell it to stop (and hopefully transition back to TRAN.)
828          */
829         if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
830             R1_CURRENT_STATE(status) == R1_STATE_RCV) {
831                 err = send_stop(card, &stop_status);
832                 if (err)
833                         pr_err("%s: error %d sending stop command\n",
834                                req->rq_disk->disk_name, err);
835
836                 /*
837                  * If the stop cmd also timed out, the card is probably
838                  * not present, so abort.  Other errors are bad news too.
839                  */
840                 if (err)
841                         return ERR_ABORT;
842                 if (stop_status & R1_CARD_ECC_FAILED)
843                         *ecc_err = 1;
844                 if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
845                         if (stop_status & R1_ERROR) {
846                                 pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
847                                        req->rq_disk->disk_name, __func__,
848                                        stop_status);
849                                 *gen_err = 1;
850                         }
851         }
852
853         /* Check for set block count errors */
854         if (brq->sbc.error)
855                 return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
856                                 prev_cmd_status_valid, status);
857
858         /* Check for r/w command errors */
859         if (brq->cmd.error)
860                 return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
861                                 prev_cmd_status_valid, status);
862
863         /* Data errors */
864         if (!brq->stop.error)
865                 return ERR_CONTINUE;
866
867         /* Now for stop errors.  These aren't fatal to the transfer. */
868         pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
869                req->rq_disk->disk_name, brq->stop.error,
870                brq->cmd.resp[0], status);
871
872         /*
873          * Subsitute in our own stop status as this will give the error
874          * state which happened during the execution of the r/w command.
875          */
876         if (stop_status) {
877                 brq->stop.resp[0] = stop_status;
878                 brq->stop.error = 0;
879         }
880         return ERR_CONTINUE;
881 }
882
883 static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
884                          int type)
885 {
886         int err;
887
888         if (md->reset_done & type)
889                 return -EEXIST;
890
891         md->reset_done |= type;
892         err = mmc_hw_reset(host);
893         /* Ensure we switch back to the correct partition */
894         if (err != -EOPNOTSUPP) {
895                 struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
896                 int part_err;
897
898                 main_md->part_curr = main_md->part_type;
899                 part_err = mmc_blk_part_switch(host->card, md);
900                 if (part_err) {
901                         /*
902                          * We have failed to get back into the correct
903                          * partition, so we need to abort the whole request.
904                          */
905                         return -ENODEV;
906                 }
907         }
908         return err;
909 }
910
911 static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
912 {
913         md->reset_done &= ~type;
914 }
915
916 int mmc_access_rpmb(struct mmc_queue *mq)
917 {
918         struct mmc_blk_data *md = mq->data;
919         /*
920          * If this is a RPMB partition access, return ture
921          */
922         if (md && md->part_type == EXT_CSD_PART_CONFIG_ACC_RPMB)
923                 return true;
924
925         return false;
926 }
927
928 static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
929 {
930         struct mmc_blk_data *md = mq->data;
931         struct mmc_card *card = md->queue.card;
932         unsigned int from, nr, arg;
933         int err = 0, type = MMC_BLK_DISCARD;
934
935         if (!mmc_can_erase(card)) {
936                 err = -EOPNOTSUPP;
937                 goto out;
938         }
939
940         from = blk_rq_pos(req);
941         nr = blk_rq_sectors(req);
942
943         if (mmc_can_discard(card))
944                 arg = MMC_DISCARD_ARG;
945         else if (mmc_can_trim(card))
946                 arg = MMC_TRIM_ARG;
947         else
948                 arg = MMC_ERASE_ARG;
949 retry:
950         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
951                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
952                                  INAND_CMD38_ARG_EXT_CSD,
953                                  arg == MMC_TRIM_ARG ?
954                                  INAND_CMD38_ARG_TRIM :
955                                  INAND_CMD38_ARG_ERASE,
956                                  0);
957                 if (err)
958                         goto out;
959         }
960         err = mmc_erase(card, from, nr, arg);
961 out:
962         if (err == -EIO && !mmc_blk_reset(md, card->host, type))
963                 goto retry;
964         if (!err)
965                 mmc_blk_reset_success(md, type);
966         blk_end_request(req, err, blk_rq_bytes(req));
967
968         return err ? 0 : 1;
969 }
970
971 static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
972                                        struct request *req)
973 {
974         struct mmc_blk_data *md = mq->data;
975         struct mmc_card *card = md->queue.card;
976         unsigned int from, nr, arg, trim_arg, erase_arg;
977         int err = 0, type = MMC_BLK_SECDISCARD;
978
979         if (!(mmc_can_secure_erase_trim(card) || mmc_can_sanitize(card))) {
980                 err = -EOPNOTSUPP;
981                 goto out;
982         }
983
984         from = blk_rq_pos(req);
985         nr = blk_rq_sectors(req);
986
987         /* The sanitize operation is supported at v4.5 only */
988         if (mmc_can_sanitize(card)) {
989                 erase_arg = MMC_ERASE_ARG;
990                 trim_arg = MMC_TRIM_ARG;
991         } else {
992                 erase_arg = MMC_SECURE_ERASE_ARG;
993                 trim_arg = MMC_SECURE_TRIM1_ARG;
994         }
995
996         if (mmc_erase_group_aligned(card, from, nr))
997                 arg = erase_arg;
998         else if (mmc_can_trim(card))
999                 arg = trim_arg;
1000         else {
1001                 err = -EINVAL;
1002                 goto out;
1003         }
1004 retry:
1005         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1006                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1007                                  INAND_CMD38_ARG_EXT_CSD,
1008                                  arg == MMC_SECURE_TRIM1_ARG ?
1009                                  INAND_CMD38_ARG_SECTRIM1 :
1010                                  INAND_CMD38_ARG_SECERASE,
1011                                  0);
1012                 if (err)
1013                         goto out_retry;
1014         }
1015
1016         err = mmc_erase(card, from, nr, arg);
1017         if (err == -EIO)
1018                 goto out_retry;
1019         if (err)
1020                 goto out;
1021
1022         if (arg == MMC_SECURE_TRIM1_ARG) {
1023                 if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1024                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1025                                          INAND_CMD38_ARG_EXT_CSD,
1026                                          INAND_CMD38_ARG_SECTRIM2,
1027                                          0);
1028                         if (err)
1029                                 goto out_retry;
1030                 }
1031
1032                 err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
1033                 if (err == -EIO)
1034                         goto out_retry;
1035                 if (err)
1036                         goto out;
1037         }
1038
1039         if (mmc_can_sanitize(card)) {
1040                 trace_mmc_blk_erase_start(EXT_CSD_SANITIZE_START, 0, 0);
1041                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1042                                  EXT_CSD_SANITIZE_START, 1, 0);
1043                 trace_mmc_blk_erase_end(EXT_CSD_SANITIZE_START, 0, 0);
1044         }
1045 out_retry:
1046         if (err && !mmc_blk_reset(md, card->host, type))
1047                 goto retry;
1048         if (!err)
1049                 mmc_blk_reset_success(md, type);
1050 out:
1051         blk_end_request(req, err, blk_rq_bytes(req));
1052
1053         return err ? 0 : 1;
1054 }
1055
1056 static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
1057 {
1058         struct mmc_blk_data *md = mq->data;
1059         struct mmc_card *card = md->queue.card;
1060         int ret = 0;
1061
1062         ret = mmc_flush_cache(card);
1063         if (ret)
1064                 ret = -EIO;
1065
1066         blk_end_request_all(req, ret);
1067
1068         return ret ? 0 : 1;
1069 }
1070
1071 /*
1072  * Reformat current write as a reliable write, supporting
1073  * both legacy and the enhanced reliable write MMC cards.
1074  * In each transfer we'll handle only as much as a single
1075  * reliable write can handle, thus finish the request in
1076  * partial completions.
1077  */
1078 static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
1079                                     struct mmc_card *card,
1080                                     struct request *req)
1081 {
1082         if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
1083                 /* Legacy mode imposes restrictions on transfers. */
1084                 if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
1085                         brq->data.blocks = 1;
1086
1087                 if (brq->data.blocks > card->ext_csd.rel_sectors)
1088                         brq->data.blocks = card->ext_csd.rel_sectors;
1089                 else if (brq->data.blocks < card->ext_csd.rel_sectors)
1090                         brq->data.blocks = 1;
1091         }
1092 }
1093
1094 #define CMD_ERRORS                                                      \
1095         (R1_OUT_OF_RANGE |      /* Command argument out of range */     \
1096          R1_ADDRESS_ERROR |     /* Misaligned address */                \
1097          R1_BLOCK_LEN_ERROR |   /* Transferred block length incorrect */\
1098          R1_WP_VIOLATION |      /* Tried to write to protected block */ \
1099          R1_CC_ERROR |          /* Card controller error */             \
1100          R1_ERROR)              /* General/unknown error */
1101
1102 static int mmc_blk_err_check(struct mmc_card *card,
1103                              struct mmc_async_req *areq)
1104 {
1105         struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
1106                                                     mmc_active);
1107         struct mmc_blk_request *brq = &mq_mrq->brq;
1108         struct request *req = mq_mrq->req;
1109         int ecc_err = 0, gen_err = 0;
1110
1111         /*
1112          * sbc.error indicates a problem with the set block count
1113          * command.  No data will have been transferred.
1114          *
1115          * cmd.error indicates a problem with the r/w command.  No
1116          * data will have been transferred.
1117          *
1118          * stop.error indicates a problem with the stop command.  Data
1119          * may have been transferred, or may still be transferring.
1120          */
1121         if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
1122             brq->data.error) {
1123                 switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
1124                 case ERR_RETRY:
1125                         return MMC_BLK_RETRY;
1126                 case ERR_ABORT:
1127                         return MMC_BLK_ABORT;
1128                 case ERR_NOMEDIUM:
1129                         return MMC_BLK_NOMEDIUM;
1130                 case ERR_CONTINUE:
1131                         break;
1132                 }
1133         }
1134
1135         /*
1136          * Check for errors relating to the execution of the
1137          * initial command - such as address errors.  No data
1138          * has been transferred.
1139          */
1140         if (brq->cmd.resp[0] & CMD_ERRORS) {
1141                 pr_err("%s: r/w command failed, status = %#x\n",
1142                        req->rq_disk->disk_name, brq->cmd.resp[0]);
1143                 return MMC_BLK_ABORT;
1144         }
1145
1146         /*
1147          * Everything else is either success, or a data error of some
1148          * kind.  If it was a write, we may have transitioned to
1149          * program mode, which we have to wait for it to complete.
1150          */
1151         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
1152                 u32 status;
1153                 unsigned long timeout;
1154
1155                 /* Check stop command response */
1156                 if (brq->stop.resp[0] & R1_ERROR) {
1157                         pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
1158                                req->rq_disk->disk_name, __func__,
1159                                brq->stop.resp[0]);
1160                         gen_err = 1;
1161                 }
1162
1163                 timeout = jiffies + msecs_to_jiffies(MMC_BLK_TIMEOUT_MS);
1164                 do {
1165                         int err = get_card_status(card, &status, 5);
1166                         if (err) {
1167                                 pr_err("%s: error %d requesting status\n",
1168                                        req->rq_disk->disk_name, err);
1169                                 return MMC_BLK_CMD_ERR;
1170                         }
1171
1172                         if (status & R1_ERROR) {
1173                                 pr_err("%s: %s: general error sending status command, card status %#x\n",
1174                                        req->rq_disk->disk_name, __func__,
1175                                        status);
1176                                 gen_err = 1;
1177                         }
1178
1179                         /* Timeout if the device never becomes ready for data
1180                          * and never leaves the program state.
1181                          */
1182                         if (time_after(jiffies, timeout)) {
1183                                 pr_err("%s: Card stuck in programming state!"\
1184                                         " %s %s\n", mmc_hostname(card->host),
1185                                         req->rq_disk->disk_name, __func__);
1186
1187                                 return MMC_BLK_CMD_ERR;
1188                         }
1189                         /*
1190                          * Some cards mishandle the status bits,
1191                          * so make sure to check both the busy
1192                          * indication and the card state.
1193                          */
1194                 } while (!(status & R1_READY_FOR_DATA) ||
1195                          (R1_CURRENT_STATE(status) == R1_STATE_PRG));
1196         }
1197
1198         /* if general error occurs, retry the write operation. */
1199         if (gen_err) {
1200                 pr_warn("%s: retrying write for general error\n",
1201                                 req->rq_disk->disk_name);
1202                 return MMC_BLK_RETRY;
1203         }
1204
1205         if (brq->data.error) {
1206                 pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
1207                        req->rq_disk->disk_name, brq->data.error,
1208                        (unsigned)blk_rq_pos(req),
1209                        (unsigned)blk_rq_sectors(req),
1210                        brq->cmd.resp[0], brq->stop.resp[0]);
1211
1212                 if (rq_data_dir(req) == READ) {
1213                         if (ecc_err)
1214                                 return MMC_BLK_ECC_ERR;
1215                         return MMC_BLK_DATA_ERR;
1216                 } else {
1217                         return MMC_BLK_CMD_ERR;
1218                 }
1219         }
1220
1221         if (!brq->data.bytes_xfered)
1222                 return MMC_BLK_RETRY;
1223
1224         if (mmc_packed_cmd(mq_mrq->cmd_type)) {
1225                 if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered))
1226                         return MMC_BLK_PARTIAL;
1227                 else
1228                         return MMC_BLK_SUCCESS;
1229         }
1230
1231         if (blk_rq_bytes(req) != brq->data.bytes_xfered)
1232                 return MMC_BLK_PARTIAL;
1233
1234         return MMC_BLK_SUCCESS;
1235 }
1236
1237 static int mmc_blk_packed_err_check(struct mmc_card *card,
1238                                     struct mmc_async_req *areq)
1239 {
1240         struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
1241                         mmc_active);
1242         struct request *req = mq_rq->req;
1243         struct mmc_packed *packed = mq_rq->packed;
1244         int err, check, status;
1245         u8 *ext_csd;
1246
1247         BUG_ON(!packed);
1248
1249         packed->retries--;
1250         check = mmc_blk_err_check(card, areq);
1251         err = get_card_status(card, &status, 0);
1252         if (err) {
1253                 pr_err("%s: error %d sending status command\n",
1254                        req->rq_disk->disk_name, err);
1255                 return MMC_BLK_ABORT;
1256         }
1257
1258         if (status & R1_EXCEPTION_EVENT) {
1259                 ext_csd = kzalloc(512, GFP_KERNEL);
1260                 if (!ext_csd) {
1261                         pr_err("%s: unable to allocate buffer for ext_csd\n",
1262                                req->rq_disk->disk_name);
1263                         return -ENOMEM;
1264                 }
1265
1266                 err = mmc_send_ext_csd(card, ext_csd);
1267                 if (err) {
1268                         pr_err("%s: error %d sending ext_csd\n",
1269                                req->rq_disk->disk_name, err);
1270                         check = MMC_BLK_ABORT;
1271                         goto free;
1272                 }
1273
1274                 if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] &
1275                      EXT_CSD_PACKED_FAILURE) &&
1276                     (ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
1277                      EXT_CSD_PACKED_GENERIC_ERROR)) {
1278                         if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
1279                             EXT_CSD_PACKED_INDEXED_ERROR) {
1280                                 packed->idx_failure =
1281                                   ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1;
1282                                 check = MMC_BLK_PARTIAL;
1283                         }
1284                         pr_err("%s: packed cmd failed, nr %u, sectors %u, "
1285                                "failure index: %d\n",
1286                                req->rq_disk->disk_name, packed->nr_entries,
1287                                packed->blocks, packed->idx_failure);
1288                 }
1289 free:
1290                 kfree(ext_csd);
1291         }
1292
1293         return check;
1294 }
1295
1296 static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1297                                struct mmc_card *card,
1298                                int disable_multi,
1299                                struct mmc_queue *mq)
1300 {
1301         u32 readcmd, writecmd;
1302         struct mmc_blk_request *brq = &mqrq->brq;
1303         struct request *req = mqrq->req;
1304         struct mmc_blk_data *md = mq->data;
1305         bool do_data_tag;
1306
1307         /*
1308          * Reliable writes are used to implement Forced Unit Access and
1309          * REQ_META accesses, and are supported only on MMCs.
1310          *
1311          * XXX: this really needs a good explanation of why REQ_META
1312          * is treated special.
1313          */
1314         bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
1315                           (req->cmd_flags & REQ_META)) &&
1316                 (rq_data_dir(req) == WRITE) &&
1317                 (md->flags & MMC_BLK_REL_WR);
1318
1319         memset(brq, 0, sizeof(struct mmc_blk_request));
1320         brq->mrq.cmd = &brq->cmd;
1321         brq->mrq.data = &brq->data;
1322
1323         brq->cmd.arg = blk_rq_pos(req);
1324         if (!mmc_card_blockaddr(card))
1325                 brq->cmd.arg <<= 9;
1326         brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1327         brq->data.blksz = 512;
1328         brq->stop.opcode = MMC_STOP_TRANSMISSION;
1329         brq->stop.arg = 0;
1330         brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1331         brq->data.blocks = blk_rq_sectors(req);
1332
1333         /*
1334          * The block layer doesn't support all sector count
1335          * restrictions, so we need to be prepared for too big
1336          * requests.
1337          */
1338         if (brq->data.blocks > card->host->max_blk_count)
1339                 brq->data.blocks = card->host->max_blk_count;
1340
1341         if (brq->data.blocks > 1) {
1342                 /*
1343                  * After a read error, we redo the request one sector
1344                  * at a time in order to accurately determine which
1345                  * sectors can be read successfully.
1346                  */
1347                 if (disable_multi)
1348                         brq->data.blocks = 1;
1349
1350                 /* Some controllers can't do multiblock reads due to hw bugs */
1351                 if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
1352                     rq_data_dir(req) == READ)
1353                         brq->data.blocks = 1;
1354         }
1355
1356         if (brq->data.blocks > 1 || do_rel_wr) {
1357                 /* SPI multiblock writes terminate using a special
1358                  * token, not a STOP_TRANSMISSION request.
1359                  */
1360                 if (!mmc_host_is_spi(card->host) ||
1361                     rq_data_dir(req) == READ)
1362                         brq->mrq.stop = &brq->stop;
1363                 readcmd = MMC_READ_MULTIPLE_BLOCK;
1364                 writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1365         } else {
1366                 brq->mrq.stop = NULL;
1367                 readcmd = MMC_READ_SINGLE_BLOCK;
1368                 writecmd = MMC_WRITE_BLOCK;
1369         }
1370         if (rq_data_dir(req) == READ) {
1371                 brq->cmd.opcode = readcmd;
1372                 brq->data.flags |= MMC_DATA_READ;
1373         } else {
1374                 brq->cmd.opcode = writecmd;
1375                 brq->data.flags |= MMC_DATA_WRITE;
1376         }
1377
1378         if (do_rel_wr)
1379                 mmc_apply_rel_rw(brq, card, req);
1380
1381         /*
1382          * Data tag is used only during writing meta data to speed
1383          * up write and any subsequent read of this meta data
1384          */
1385         do_data_tag = (card->ext_csd.data_tag_unit_size) &&
1386                 (req->cmd_flags & REQ_META) &&
1387                 (rq_data_dir(req) == WRITE) &&
1388                 ((brq->data.blocks * brq->data.blksz) >=
1389                  card->ext_csd.data_tag_unit_size);
1390
1391         /*
1392          * Pre-defined multi-block transfers are preferable to
1393          * open ended-ones (and necessary for reliable writes).
1394          * However, it is not sufficient to just send CMD23,
1395          * and avoid the final CMD12, as on an error condition
1396          * CMD12 (stop) needs to be sent anyway. This, coupled
1397          * with Auto-CMD23 enhancements provided by some
1398          * hosts, means that the complexity of dealing
1399          * with this is best left to the host. If CMD23 is
1400          * supported by card and host, we'll fill sbc in and let
1401          * the host deal with handling it correctly. This means
1402          * that for hosts that don't expose MMC_CAP_CMD23, no
1403          * change of behavior will be observed.
1404          *
1405          * N.B: Some MMC cards experience perf degradation.
1406          * We'll avoid using CMD23-bounded multiblock writes for
1407          * these, while retaining features like reliable writes.
1408          */
1409         if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
1410             (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) ||
1411              do_data_tag)) {
1412                 brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1413                 brq->sbc.arg = brq->data.blocks |
1414                         (do_rel_wr ? (1 << 31) : 0) |
1415                         (do_data_tag ? (1 << 29) : 0);
1416                 brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1417                 brq->mrq.sbc = &brq->sbc;
1418         }
1419
1420         mmc_set_data_timeout(&brq->data, card);
1421
1422         brq->data.sg = mqrq->sg;
1423         brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1424
1425         /*
1426          * Adjust the sg list so it is the same size as the
1427          * request.
1428          */
1429         if (brq->data.blocks != blk_rq_sectors(req)) {
1430                 int i, data_size = brq->data.blocks << 9;
1431                 struct scatterlist *sg;
1432
1433                 for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1434                         data_size -= sg->length;
1435                         if (data_size <= 0) {
1436                                 sg->length += data_size;
1437                                 i++;
1438                                 break;
1439                         }
1440                 }
1441                 brq->data.sg_len = i;
1442         }
1443
1444         mqrq->mmc_active.mrq = &brq->mrq;
1445         mqrq->mmc_active.err_check = mmc_blk_err_check;
1446
1447         mmc_queue_bounce_pre(mqrq);
1448 }
1449
1450 static inline u8 mmc_calc_packed_hdr_segs(struct request_queue *q,
1451                                           struct mmc_card *card)
1452 {
1453         unsigned int hdr_sz = mmc_large_sector(card) ? 4096 : 512;
1454         unsigned int max_seg_sz = queue_max_segment_size(q);
1455         unsigned int len, nr_segs = 0;
1456
1457         do {
1458                 len = min(hdr_sz, max_seg_sz);
1459                 hdr_sz -= len;
1460                 nr_segs++;
1461         } while (hdr_sz);
1462
1463         return nr_segs;
1464 }
1465
1466 static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req)
1467 {
1468         struct request_queue *q = mq->queue;
1469         struct mmc_card *card = mq->card;
1470         struct request *cur = req, *next = NULL;
1471         struct mmc_blk_data *md = mq->data;
1472         struct mmc_queue_req *mqrq = mq->mqrq_cur;
1473         bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN;
1474         unsigned int req_sectors = 0, phys_segments = 0;
1475         unsigned int max_blk_count, max_phys_segs;
1476         bool put_back = true;
1477         u8 max_packed_rw = 0;
1478         u8 reqs = 0;
1479
1480         if (!(md->flags & MMC_BLK_PACKED_CMD))
1481                 goto no_packed;
1482
1483         if ((rq_data_dir(cur) == WRITE) &&
1484             mmc_host_packed_wr(card->host))
1485                 max_packed_rw = card->ext_csd.max_packed_writes;
1486
1487         if (max_packed_rw == 0)
1488                 goto no_packed;
1489
1490         if (mmc_req_rel_wr(cur) &&
1491             (md->flags & MMC_BLK_REL_WR) && !en_rel_wr)
1492                 goto no_packed;
1493
1494         if (mmc_large_sector(card) &&
1495             !IS_ALIGNED(blk_rq_sectors(cur), 8))
1496                 goto no_packed;
1497
1498         mmc_blk_clear_packed(mqrq);
1499
1500         max_blk_count = min(card->host->max_blk_count,
1501                             card->host->max_req_size >> 9);
1502         if (unlikely(max_blk_count > 0xffff))
1503                 max_blk_count = 0xffff;
1504
1505         max_phys_segs = queue_max_segments(q);
1506         req_sectors += blk_rq_sectors(cur);
1507         phys_segments += cur->nr_phys_segments;
1508
1509         if (rq_data_dir(cur) == WRITE) {
1510                 req_sectors += mmc_large_sector(card) ? 8 : 1;
1511                 phys_segments += mmc_calc_packed_hdr_segs(q, card);
1512         }
1513
1514         do {
1515                 if (reqs >= max_packed_rw - 1) {
1516                         put_back = false;
1517                         break;
1518                 }
1519
1520                 spin_lock_irq(q->queue_lock);
1521                 next = blk_fetch_request(q);
1522                 spin_unlock_irq(q->queue_lock);
1523                 if (!next) {
1524                         put_back = false;
1525                         break;
1526                 }
1527
1528                 if (mmc_large_sector(card) &&
1529                     !IS_ALIGNED(blk_rq_sectors(next), 8))
1530                         break;
1531
1532                 if (next->cmd_flags & REQ_DISCARD ||
1533                     next->cmd_flags & REQ_FLUSH)
1534                         break;
1535
1536                 if (rq_data_dir(cur) != rq_data_dir(next))
1537                         break;
1538
1539                 if (mmc_req_rel_wr(next) &&
1540                     (md->flags & MMC_BLK_REL_WR) && !en_rel_wr)
1541                         break;
1542
1543                 req_sectors += blk_rq_sectors(next);
1544                 if (req_sectors > max_blk_count)
1545                         break;
1546
1547                 phys_segments +=  next->nr_phys_segments;
1548                 if (phys_segments > max_phys_segs)
1549                         break;
1550
1551                 list_add_tail(&next->queuelist, &mqrq->packed->list);
1552                 cur = next;
1553                 reqs++;
1554         } while (1);
1555
1556         if (put_back) {
1557                 spin_lock_irq(q->queue_lock);
1558                 blk_requeue_request(q, next);
1559                 spin_unlock_irq(q->queue_lock);
1560         }
1561
1562         if (reqs > 0) {
1563                 list_add(&req->queuelist, &mqrq->packed->list);
1564                 mqrq->packed->nr_entries = ++reqs;
1565                 mqrq->packed->retries = reqs;
1566                 return reqs;
1567         }
1568
1569 no_packed:
1570         mqrq->cmd_type = MMC_PACKED_NONE;
1571         return 0;
1572 }
1573
1574 static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq,
1575                                         struct mmc_card *card,
1576                                         struct mmc_queue *mq)
1577 {
1578         struct mmc_blk_request *brq = &mqrq->brq;
1579         struct request *req = mqrq->req;
1580         struct request *prq;
1581         struct mmc_blk_data *md = mq->data;
1582         struct mmc_packed *packed = mqrq->packed;
1583         bool do_rel_wr, do_data_tag;
1584         u32 *packed_cmd_hdr;
1585         u8 hdr_blocks;
1586         u8 i = 1;
1587
1588         BUG_ON(!packed);
1589
1590         mqrq->cmd_type = MMC_PACKED_WRITE;
1591         packed->blocks = 0;
1592         packed->idx_failure = MMC_PACKED_NR_IDX;
1593
1594         packed_cmd_hdr = packed->cmd_hdr;
1595         memset(packed_cmd_hdr, 0, sizeof(packed->cmd_hdr));
1596         packed_cmd_hdr[0] = (packed->nr_entries << 16) |
1597                 (PACKED_CMD_WR << 8) | PACKED_CMD_VER;
1598         hdr_blocks = mmc_large_sector(card) ? 8 : 1;
1599
1600         /*
1601          * Argument for each entry of packed group
1602          */
1603         list_for_each_entry(prq, &packed->list, queuelist) {
1604                 do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR);
1605                 do_data_tag = (card->ext_csd.data_tag_unit_size) &&
1606                         (prq->cmd_flags & REQ_META) &&
1607                         (rq_data_dir(prq) == WRITE) &&
1608                         ((brq->data.blocks * brq->data.blksz) >=
1609                          card->ext_csd.data_tag_unit_size);
1610                 /* Argument of CMD23 */
1611                 packed_cmd_hdr[(i * 2)] =
1612                         (do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) |
1613                         (do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) |
1614                         blk_rq_sectors(prq);
1615                 /* Argument of CMD18 or CMD25 */
1616                 packed_cmd_hdr[((i * 2)) + 1] =
1617                         mmc_card_blockaddr(card) ?
1618                         blk_rq_pos(prq) : blk_rq_pos(prq) << 9;
1619                 packed->blocks += blk_rq_sectors(prq);
1620                 i++;
1621         }
1622
1623         memset(brq, 0, sizeof(struct mmc_blk_request));
1624         brq->mrq.cmd = &brq->cmd;
1625         brq->mrq.data = &brq->data;
1626         brq->mrq.sbc = &brq->sbc;
1627         brq->mrq.stop = &brq->stop;
1628
1629         brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1630         brq->sbc.arg = MMC_CMD23_ARG_PACKED | (packed->blocks + hdr_blocks);
1631         brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1632
1633         brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
1634         brq->cmd.arg = blk_rq_pos(req);
1635         if (!mmc_card_blockaddr(card))
1636                 brq->cmd.arg <<= 9;
1637         brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1638
1639         brq->data.blksz = 512;
1640         brq->data.blocks = packed->blocks + hdr_blocks;
1641         brq->data.flags |= MMC_DATA_WRITE;
1642
1643         brq->stop.opcode = MMC_STOP_TRANSMISSION;
1644         brq->stop.arg = 0;
1645         brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1646
1647         mmc_set_data_timeout(&brq->data, card);
1648
1649         brq->data.sg = mqrq->sg;
1650         brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1651
1652         mqrq->mmc_active.mrq = &brq->mrq;
1653         mqrq->mmc_active.err_check = mmc_blk_packed_err_check;
1654
1655         mmc_queue_bounce_pre(mqrq);
1656 }
1657
1658 static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
1659                            struct mmc_blk_request *brq, struct request *req,
1660                            int ret)
1661 {
1662         struct mmc_queue_req *mq_rq;
1663         mq_rq = container_of(brq, struct mmc_queue_req, brq);
1664
1665         /*
1666          * If this is an SD card and we're writing, we can first
1667          * mark the known good sectors as ok.
1668          *
1669          * If the card is not SD, we can still ok written sectors
1670          * as reported by the controller (which might be less than
1671          * the real number of written sectors, but never more).
1672          */
1673         if (mmc_card_sd(card)) {
1674                 u32 blocks;
1675
1676                 blocks = mmc_sd_num_wr_blocks(card);
1677                 if (blocks != (u32)-1) {
1678                         ret = blk_end_request(req, 0, blocks << 9);
1679                 }
1680         } else {
1681                 if (!mmc_packed_cmd(mq_rq->cmd_type))
1682                         ret = blk_end_request(req, 0, brq->data.bytes_xfered);
1683         }
1684         return ret;
1685 }
1686
1687 static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq)
1688 {
1689         struct request *prq;
1690         struct mmc_packed *packed = mq_rq->packed;
1691         int idx = packed->idx_failure, i = 0;
1692         int ret = 0;
1693
1694         BUG_ON(!packed);
1695
1696         while (!list_empty(&packed->list)) {
1697                 prq = list_entry_rq(packed->list.next);
1698                 if (idx == i) {
1699                         /* retry from error index */
1700                         packed->nr_entries -= idx;
1701                         mq_rq->req = prq;
1702                         ret = 1;
1703
1704                         if (packed->nr_entries == MMC_PACKED_NR_SINGLE) {
1705                                 list_del_init(&prq->queuelist);
1706                                 mmc_blk_clear_packed(mq_rq);
1707                         }
1708                         return ret;
1709                 }
1710                 list_del_init(&prq->queuelist);
1711                 blk_end_request(prq, 0, blk_rq_bytes(prq));
1712                 i++;
1713         }
1714
1715         mmc_blk_clear_packed(mq_rq);
1716         return ret;
1717 }
1718
1719 static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq)
1720 {
1721         struct request *prq;
1722         struct mmc_packed *packed = mq_rq->packed;
1723
1724         BUG_ON(!packed);
1725
1726         while (!list_empty(&packed->list)) {
1727                 prq = list_entry_rq(packed->list.next);
1728                 list_del_init(&prq->queuelist);
1729                 blk_end_request(prq, -EIO, blk_rq_bytes(prq));
1730         }
1731
1732         mmc_blk_clear_packed(mq_rq);
1733 }
1734
1735 static void mmc_blk_revert_packed_req(struct mmc_queue *mq,
1736                                       struct mmc_queue_req *mq_rq)
1737 {
1738         struct request *prq;
1739         struct request_queue *q = mq->queue;
1740         struct mmc_packed *packed = mq_rq->packed;
1741
1742         BUG_ON(!packed);
1743
1744         while (!list_empty(&packed->list)) {
1745                 prq = list_entry_rq(packed->list.prev);
1746                 if (prq->queuelist.prev != &packed->list) {
1747                         list_del_init(&prq->queuelist);
1748                         spin_lock_irq(q->queue_lock);
1749                         blk_requeue_request(mq->queue, prq);
1750                         spin_unlock_irq(q->queue_lock);
1751                 } else {
1752                         list_del_init(&prq->queuelist);
1753                 }
1754         }
1755
1756         mmc_blk_clear_packed(mq_rq);
1757 }
1758
1759 static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
1760 {
1761         struct mmc_blk_data *md = mq->data;
1762         struct mmc_card *card = md->queue.card;
1763         struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
1764         int ret = 1, disable_multi = 0, retry = 0, type;
1765         enum mmc_blk_status status;
1766         struct mmc_queue_req *mq_rq;
1767         struct request *req = rqc;
1768         struct mmc_async_req *areq;
1769         const u8 packed_nr = 2;
1770         u8 reqs = 0;
1771
1772         if (!rqc && !mq->mqrq_prev->req)
1773                 return 0;
1774
1775         if (rqc)
1776                 reqs = mmc_blk_prep_packed_list(mq, rqc);
1777
1778         do {
1779                 if (rqc) {
1780                         /*
1781                          * When 4KB native sector is enabled, only 8 blocks
1782                          * multiple read or write is allowed
1783                          */
1784                         if ((brq->data.blocks & 0x07) &&
1785                             (card->ext_csd.data_sector_size == 4096)) {
1786                                 pr_err("%s: Transfer size is not 4KB sector size aligned\n",
1787                                         req->rq_disk->disk_name);
1788                                 mq_rq = mq->mqrq_cur;
1789                                 goto cmd_abort;
1790                         }
1791
1792                         if (reqs >= packed_nr)
1793                                 mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur,
1794                                                             card, mq);
1795                         else
1796                                 mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1797                         areq = &mq->mqrq_cur->mmc_active;
1798                 } else
1799                         areq = NULL;
1800                 areq = mmc_start_req(card->host, areq, (int *) &status);
1801                 if (!areq) {
1802                         if (status == MMC_BLK_NEW_REQUEST)
1803                                 mq->flags |= MMC_QUEUE_NEW_REQUEST;
1804                         return 0;
1805                 }
1806
1807                 mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
1808                 brq = &mq_rq->brq;
1809                 req = mq_rq->req;
1810                 type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1811                 mmc_queue_bounce_post(mq_rq);
1812
1813                 switch (status) {
1814                 case MMC_BLK_SUCCESS:
1815                 case MMC_BLK_PARTIAL:
1816                         /*
1817                          * A block was successfully transferred.
1818                          */
1819                         mmc_blk_reset_success(md, type);
1820
1821                         if (mmc_packed_cmd(mq_rq->cmd_type)) {
1822                                 ret = mmc_blk_end_packed_req(mq_rq);
1823                                 break;
1824                         } else {
1825                                 ret = blk_end_request(req, 0,
1826                                                 brq->data.bytes_xfered);
1827                         }
1828
1829                         /*
1830                          * If the blk_end_request function returns non-zero even
1831                          * though all data has been transferred and no errors
1832                          * were returned by the host controller, it's a bug.
1833                          */
1834                         if (status == MMC_BLK_SUCCESS && ret) {
1835                                 pr_err("%s BUG rq_tot %d d_xfer %d\n",
1836                                        __func__, blk_rq_bytes(req),
1837                                        brq->data.bytes_xfered);
1838                                 rqc = NULL;
1839                                 goto cmd_abort;
1840                         }
1841                         break;
1842                 case MMC_BLK_CMD_ERR:
1843                         ret = mmc_blk_cmd_err(md, card, brq, req, ret);
1844                         if (mmc_blk_reset(md, card->host, type))
1845                                 goto cmd_abort;
1846                         if (!ret)
1847                                 goto start_new_req;
1848                         break;
1849                 case MMC_BLK_RETRY:
1850                         if (retry++ < 5)
1851                                 break;
1852                         /* Fall through */
1853                 case MMC_BLK_ABORT:
1854                         if (!mmc_blk_reset(md, card->host, type))
1855                                 break;
1856                         goto cmd_abort;
1857                 case MMC_BLK_DATA_ERR: {
1858                         int err;
1859
1860                         err = mmc_blk_reset(md, card->host, type);
1861                         if (!err)
1862                                 break;
1863                         if (err == -ENODEV ||
1864                                 mmc_packed_cmd(mq_rq->cmd_type))
1865                                 goto cmd_abort;
1866                         /* Fall through */
1867                 }
1868                 case MMC_BLK_ECC_ERR:
1869                         if (brq->data.blocks > 1) {
1870                                 /* Redo read one sector at a time */
1871                                 pr_warning("%s: retrying using single block read\n",
1872                                            req->rq_disk->disk_name);
1873                                 disable_multi = 1;
1874                                 break;
1875                         }
1876                         /*
1877                          * After an error, we redo I/O one sector at a
1878                          * time, so we only reach here after trying to
1879                          * read a single sector.
1880                          */
1881                         ret = blk_end_request(req, -EIO,
1882                                                 brq->data.blksz);
1883                         if (!ret)
1884                                 goto start_new_req;
1885                         break;
1886                 case MMC_BLK_NOMEDIUM:
1887                         goto cmd_abort;
1888                 default:
1889                         pr_err("%s: Unhandled return value (%d)",
1890                                         req->rq_disk->disk_name, status);
1891                         goto cmd_abort;
1892                 }
1893
1894                 if (ret) {
1895                         if (mmc_packed_cmd(mq_rq->cmd_type)) {
1896                                 if (!mq_rq->packed->retries)
1897                                         goto cmd_abort;
1898                                 mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq);
1899                                 mmc_start_req(card->host,
1900                                               &mq_rq->mmc_active, NULL);
1901                         } else {
1902
1903                                 /*
1904                                  * In case of a incomplete request
1905                                  * prepare it again and resend.
1906                                  */
1907                                 mmc_blk_rw_rq_prep(mq_rq, card,
1908                                                 disable_multi, mq);
1909                                 mmc_start_req(card->host,
1910                                                 &mq_rq->mmc_active, NULL);
1911                         }
1912                 }
1913         } while (ret);
1914
1915         return 1;
1916
1917  cmd_abort:
1918         if (mmc_packed_cmd(mq_rq->cmd_type)) {
1919                 mmc_blk_abort_packed_req(mq_rq);
1920         } else {
1921                 if (mmc_card_removed(card))
1922                         req->cmd_flags |= REQ_QUIET;
1923                 while (ret)
1924                         ret = blk_end_request(req, -EIO,
1925                                         blk_rq_cur_bytes(req));
1926         }
1927
1928  start_new_req:
1929         if (rqc) {
1930                 if (mmc_card_removed(card)) {
1931                         rqc->cmd_flags |= REQ_QUIET;
1932                         blk_end_request_all(rqc, -EIO);
1933                 } else {
1934                         /*
1935                          * If current request is packed, it needs to put back.
1936                          */
1937                         if (mmc_packed_cmd(mq->mqrq_cur->cmd_type))
1938                                 mmc_blk_revert_packed_req(mq, mq->mqrq_cur);
1939
1940                         mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1941                         mmc_start_req(card->host,
1942                                       &mq->mqrq_cur->mmc_active, NULL);
1943                 }
1944         }
1945
1946         return 0;
1947 }
1948
1949 static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
1950 {
1951         int ret;
1952         struct mmc_blk_data *md = mq->data;
1953         struct mmc_card *card = md->queue.card;
1954         struct mmc_host *host = card->host;
1955         unsigned long flags;
1956         unsigned int cmd_flags = req ? req->cmd_flags : 0;
1957
1958 #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
1959         if (mmc_bus_needs_resume(card->host))
1960                 mmc_resume_bus(card->host);
1961 #endif
1962
1963         if (req && !mq->mqrq_prev->req)
1964                 /* claim host only for the first request */
1965                 mmc_claim_host(card->host);
1966
1967         ret = mmc_blk_part_switch(card, md);
1968         if (ret) {
1969                 if (req) {
1970                         blk_end_request_all(req, -EIO);
1971                 }
1972                 ret = 0;
1973                 goto out;
1974         }
1975
1976         mq->flags &= ~MMC_QUEUE_NEW_REQUEST;
1977         if (cmd_flags & REQ_DISCARD) {
1978                 /* complete ongoing async transfer before issuing discard */
1979                 if (card->host->areq)
1980                         mmc_blk_issue_rw_rq(mq, NULL);
1981                 if (req->cmd_flags & REQ_SECURE &&
1982                         !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
1983                         ret = mmc_blk_issue_secdiscard_rq(mq, req);
1984                 else
1985                         ret = mmc_blk_issue_discard_rq(mq, req);
1986         } else if (cmd_flags & REQ_FLUSH) {
1987                 /* complete ongoing async transfer before issuing flush */
1988                 if (card->host->areq)
1989                         mmc_blk_issue_rw_rq(mq, NULL);
1990                 ret = mmc_blk_issue_flush(mq, req);
1991         } else {
1992                 if (!req && host->areq) {
1993                         spin_lock_irqsave(&host->context_info.lock, flags);
1994                         host->context_info.is_waiting_last_req = true;
1995                         spin_unlock_irqrestore(&host->context_info.lock, flags);
1996                 }
1997                 ret = mmc_blk_issue_rw_rq(mq, req);
1998         }
1999
2000 out:
2001         if ((!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) ||
2002              (cmd_flags & MMC_REQ_SPECIAL_MASK))
2003                 /*
2004                  * Release host when there are no more requests
2005                  * and after special request(discard, flush) is done.
2006                  * In case sepecial request, there is no reentry to
2007                  * the 'mmc_blk_issue_rq' with 'mqrq_prev->req'.
2008                  */
2009                 mmc_release_host(card->host);
2010         return ret;
2011 }
2012
2013 static inline int mmc_blk_readonly(struct mmc_card *card)
2014 {
2015         return mmc_card_readonly(card) ||
2016                !(card->csd.cmdclass & CCC_BLOCK_WRITE);
2017 }
2018
2019 static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
2020                                               struct device *parent,
2021                                               sector_t size,
2022                                               bool default_ro,
2023                                               const char *subname,
2024                                               int area_type)
2025 {
2026         struct mmc_blk_data *md;
2027         int devidx, ret;
2028
2029         devidx = find_first_zero_bit(dev_use, max_devices);
2030         if (devidx >= max_devices)
2031                 return ERR_PTR(-ENOSPC);
2032         __set_bit(devidx, dev_use);
2033
2034         md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
2035         if (!md) {
2036                 ret = -ENOMEM;
2037                 goto out;
2038         }
2039
2040         /*
2041          * !subname implies we are creating main mmc_blk_data that will be
2042          * associated with mmc_card with mmc_set_drvdata. Due to device
2043          * partitions, devidx will not coincide with a per-physical card
2044          * index anymore so we keep track of a name index.
2045          */
2046         if (!subname) {
2047                 md->name_idx = find_first_zero_bit(name_use, max_devices);
2048                 __set_bit(md->name_idx, name_use);
2049         } else
2050                 md->name_idx = ((struct mmc_blk_data *)
2051                                 dev_to_disk(parent)->private_data)->name_idx;
2052
2053         md->area_type = area_type;
2054
2055         /*
2056          * Set the read-only status based on the supported commands
2057          * and the write protect switch.
2058          */
2059         md->read_only = mmc_blk_readonly(card);
2060
2061         md->disk = alloc_disk(perdev_minors);
2062         if (md->disk == NULL) {
2063                 ret = -ENOMEM;
2064                 goto err_kfree;
2065         }
2066
2067         spin_lock_init(&md->lock);
2068         INIT_LIST_HEAD(&md->part);
2069         md->usage = 1;
2070
2071         ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
2072         if (ret)
2073                 goto err_putdisk;
2074
2075         md->queue.issue_fn = mmc_blk_issue_rq;
2076         md->queue.data = md;
2077
2078         md->disk->major = MMC_BLOCK_MAJOR;
2079         md->disk->first_minor = devidx * perdev_minors;
2080         md->disk->fops = &mmc_bdops;
2081         md->disk->private_data = md;
2082         md->disk->queue = md->queue.queue;
2083         md->disk->driverfs_dev = parent;
2084         set_disk_ro(md->disk, md->read_only || default_ro);
2085         md->disk->flags = GENHD_FL_EXT_DEVT;
2086         if (area_type & MMC_BLK_DATA_AREA_RPMB)
2087                 md->disk->flags |= GENHD_FL_NO_PART_SCAN;
2088
2089         /*
2090          * As discussed on lkml, GENHD_FL_REMOVABLE should:
2091          *
2092          * - be set for removable media with permanent block devices
2093          * - be unset for removable block devices with permanent media
2094          *
2095          * Since MMC block devices clearly fall under the second
2096          * case, we do not set GENHD_FL_REMOVABLE.  Userspace
2097          * should use the block device creation/destruction hotplug
2098          * messages to tell when the card is present.
2099          */
2100
2101         snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
2102                  "mmcblk%d%s", md->name_idx, subname ? subname : "");
2103
2104         if (mmc_card_mmc(card))
2105                 blk_queue_logical_block_size(md->queue.queue,
2106                                              card->ext_csd.data_sector_size);
2107         else
2108                 blk_queue_logical_block_size(md->queue.queue, 512);
2109
2110         set_capacity(md->disk, size);
2111
2112         if (mmc_host_cmd23(card->host)) {
2113                 if (mmc_card_mmc(card) ||
2114                     (mmc_card_sd(card) &&
2115                      card->scr.cmds & SD_SCR_CMD23_SUPPORT))
2116                         md->flags |= MMC_BLK_CMD23;
2117         }
2118
2119         if (mmc_card_mmc(card) &&
2120             md->flags & MMC_BLK_CMD23 &&
2121             ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
2122              card->ext_csd.rel_sectors)) {
2123                 md->flags |= MMC_BLK_REL_WR;
2124                 blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
2125         }
2126
2127         if (mmc_card_mmc(card) &&
2128             (area_type == MMC_BLK_DATA_AREA_MAIN) &&
2129             (md->flags & MMC_BLK_CMD23) &&
2130             card->ext_csd.packed_event_en) {
2131                 if (!mmc_packed_init(&md->queue, card))
2132                         md->flags |= MMC_BLK_PACKED_CMD;
2133         }
2134
2135         return md;
2136
2137  err_putdisk:
2138         put_disk(md->disk);
2139  err_kfree:
2140         kfree(md);
2141  out:
2142         return ERR_PTR(ret);
2143 }
2144
2145 static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
2146 {
2147         sector_t size;
2148         struct mmc_blk_data *md;
2149
2150         if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
2151                 /*
2152                  * The EXT_CSD sector count is in number or 512 byte
2153                  * sectors.
2154                  */
2155                 size = card->ext_csd.sectors;
2156         } else {
2157                 /*
2158                  * The CSD capacity field is in units of read_blkbits.
2159                  * set_capacity takes units of 512 bytes.
2160                  */
2161                 size = card->csd.capacity << (card->csd.read_blkbits - 9);
2162         }
2163
2164         md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
2165                                         MMC_BLK_DATA_AREA_MAIN);
2166         return md;
2167 }
2168
2169 static int mmc_blk_alloc_part(struct mmc_card *card,
2170                               struct mmc_blk_data *md,
2171                               unsigned int part_type,
2172                               sector_t size,
2173                               bool default_ro,
2174                               const char *subname,
2175                               int area_type)
2176 {
2177         char cap_str[10];
2178         struct mmc_blk_data *part_md;
2179
2180         part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
2181                                     subname, area_type);
2182         if (IS_ERR(part_md))
2183                 return PTR_ERR(part_md);
2184         part_md->part_type = part_type;
2185         list_add(&part_md->part, &md->part);
2186
2187         string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
2188                         cap_str, sizeof(cap_str));
2189         pr_info("%s: %s %s partition %u %s\n",
2190                part_md->disk->disk_name, mmc_card_id(card),
2191                mmc_card_name(card), part_md->part_type, cap_str);
2192         return 0;
2193 }
2194
2195 /* MMC Physical partitions consist of two boot partitions and
2196  * up to four general purpose partitions.
2197  * For each partition enabled in EXT_CSD a block device will be allocatedi
2198  * to provide access to the partition.
2199  */
2200
2201 static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
2202 {
2203         int idx, ret = 0;
2204
2205         if (!mmc_card_mmc(card))
2206                 return 0;
2207
2208         for (idx = 0; idx < card->nr_parts; idx++) {
2209                 if (card->part[idx].size) {
2210                         ret = mmc_blk_alloc_part(card, md,
2211                                 card->part[idx].part_cfg,
2212                                 card->part[idx].size >> 9,
2213                                 card->part[idx].force_ro,
2214                                 card->part[idx].name,
2215                                 card->part[idx].area_type);
2216                         if (ret)
2217                                 return ret;
2218                 }
2219         }
2220
2221         return ret;
2222 }
2223
2224 static void mmc_blk_remove_req(struct mmc_blk_data *md)
2225 {
2226         struct mmc_card *card;
2227
2228         if (md) {
2229                 card = md->queue.card;
2230                 if (md->disk->flags & GENHD_FL_UP) {
2231                         device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2232                         if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2233                                         card->ext_csd.boot_ro_lockable)
2234                                 device_remove_file(disk_to_dev(md->disk),
2235                                         &md->power_ro_lock);
2236
2237                         /* Stop new requests from getting into the queue */
2238                         del_gendisk(md->disk);
2239                 }
2240
2241                 /* Then flush out any already in there */
2242                 mmc_cleanup_queue(&md->queue);
2243                 if (md->flags & MMC_BLK_PACKED_CMD)
2244                         mmc_packed_clean(&md->queue);
2245                 mmc_blk_put(md);
2246         }
2247 }
2248
2249 static void mmc_blk_remove_parts(struct mmc_card *card,
2250                                  struct mmc_blk_data *md)
2251 {
2252         struct list_head *pos, *q;
2253         struct mmc_blk_data *part_md;
2254
2255         __clear_bit(md->name_idx, name_use);
2256         list_for_each_safe(pos, q, &md->part) {
2257                 part_md = list_entry(pos, struct mmc_blk_data, part);
2258                 list_del(pos);
2259                 mmc_blk_remove_req(part_md);
2260         }
2261 }
2262
2263 static int mmc_add_disk(struct mmc_blk_data *md)
2264 {
2265         int ret;
2266         struct mmc_card *card = md->queue.card;
2267
2268         add_disk(md->disk);
2269         md->force_ro.show = force_ro_show;
2270         md->force_ro.store = force_ro_store;
2271         sysfs_attr_init(&md->force_ro.attr);
2272         md->force_ro.attr.name = "force_ro";
2273         md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
2274         ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
2275         if (ret)
2276                 goto force_ro_fail;
2277
2278         if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2279              card->ext_csd.boot_ro_lockable) {
2280                 umode_t mode;
2281
2282                 if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS)
2283                         mode = S_IRUGO;
2284                 else
2285                         mode = S_IRUGO | S_IWUSR;
2286
2287                 md->power_ro_lock.show = power_ro_lock_show;
2288                 md->power_ro_lock.store = power_ro_lock_store;
2289                 sysfs_attr_init(&md->power_ro_lock.attr);
2290                 md->power_ro_lock.attr.mode = mode;
2291                 md->power_ro_lock.attr.name =
2292                                         "ro_lock_until_next_power_on";
2293                 ret = device_create_file(disk_to_dev(md->disk),
2294                                 &md->power_ro_lock);
2295                 if (ret)
2296                         goto power_ro_lock_fail;
2297         }
2298         return ret;
2299
2300 power_ro_lock_fail:
2301         device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2302 force_ro_fail:
2303         del_gendisk(md->disk);
2304
2305         return ret;
2306 }
2307
2308 #define CID_MANFID_SANDISK      0x2
2309 #define CID_MANFID_TOSHIBA      0x11
2310 #define CID_MANFID_MICRON       0x13
2311 #define CID_MANFID_SAMSUNG      0x15
2312
2313 static const struct mmc_fixup blk_fixups[] =
2314 {
2315         MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk,
2316                   MMC_QUIRK_INAND_CMD38),
2317         MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk,
2318                   MMC_QUIRK_INAND_CMD38),
2319         MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk,
2320                   MMC_QUIRK_INAND_CMD38),
2321         MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk,
2322                   MMC_QUIRK_INAND_CMD38),
2323         MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk,
2324                   MMC_QUIRK_INAND_CMD38),
2325
2326         /*
2327          * Some MMC cards experience performance degradation with CMD23
2328          * instead of CMD12-bounded multiblock transfers. For now we'll
2329          * black list what's bad...
2330          * - Certain Toshiba cards.
2331          *
2332          * N.B. This doesn't affect SD cards.
2333          */
2334         MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2335                   MMC_QUIRK_BLK_NO_CMD23),
2336         MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2337                   MMC_QUIRK_BLK_NO_CMD23),
2338         MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2339                   MMC_QUIRK_BLK_NO_CMD23),
2340
2341         /*
2342          * Some Micron MMC cards needs longer data read timeout than
2343          * indicated in CSD.
2344          */
2345         MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc,
2346                   MMC_QUIRK_LONG_READ_TIME),
2347
2348         /*
2349          * On these Samsung MoviNAND parts, performing secure erase or
2350          * secure trim can result in unrecoverable corruption due to a
2351          * firmware bug.
2352          */
2353         MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2354                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2355         MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2356                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2357         MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2358                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2359         MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2360                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2361         MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2362                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2363         MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2364                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2365         MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2366                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2367         MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2368                   MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2369
2370         END_FIXUP
2371 };
2372
2373 static int mmc_blk_probe(struct mmc_card *card)
2374 {
2375         struct mmc_blk_data *md, *part_md;
2376         char cap_str[10];
2377
2378         /*
2379          * Check that the card supports the command class(es) we need.
2380          */
2381         if (!(card->csd.cmdclass & CCC_BLOCK_READ))
2382                 return -ENODEV;
2383
2384         md = mmc_blk_alloc(card);
2385         if (IS_ERR(md))
2386                 return PTR_ERR(md);
2387
2388         string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
2389                         cap_str, sizeof(cap_str));
2390         pr_info("%s: %s %s %s %s\n",
2391                 md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
2392                 cap_str, md->read_only ? "(ro)" : "");
2393
2394         if (mmc_blk_alloc_parts(card, md))
2395                 goto out;
2396
2397         mmc_set_drvdata(card, md);
2398         mmc_fixup_device(card, blk_fixups);
2399
2400 #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
2401         mmc_set_bus_resume_policy(card->host, 1);
2402 #endif
2403         if (mmc_add_disk(md))
2404                 goto out;
2405
2406         list_for_each_entry(part_md, &md->part, part) {
2407                 if (mmc_add_disk(part_md))
2408                         goto out;
2409         }
2410         return 0;
2411
2412  out:
2413         mmc_blk_remove_parts(card, md);
2414         mmc_blk_remove_req(md);
2415         return 0;
2416 }
2417
2418 static void mmc_blk_remove(struct mmc_card *card)
2419 {
2420         struct mmc_blk_data *md = mmc_get_drvdata(card);
2421
2422         mmc_blk_remove_parts(card, md);
2423         mmc_claim_host(card->host);
2424         mmc_blk_part_switch(card, md);
2425         mmc_release_host(card->host);
2426         mmc_blk_remove_req(md);
2427         mmc_set_drvdata(card, NULL);
2428 #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
2429         mmc_set_bus_resume_policy(card->host, 0);
2430 #endif
2431 }
2432
2433 #ifdef CONFIG_PM
2434 static int mmc_blk_suspend(struct mmc_card *card)
2435 {
2436         struct mmc_blk_data *part_md;
2437         struct mmc_blk_data *md = mmc_get_drvdata(card);
2438
2439         if (md) {
2440                 mmc_queue_suspend(&md->queue);
2441                 list_for_each_entry(part_md, &md->part, part) {
2442                         mmc_queue_suspend(&part_md->queue);
2443                 }
2444         }
2445         return 0;
2446 }
2447
2448 static int mmc_blk_resume(struct mmc_card *card)
2449 {
2450         struct mmc_blk_data *part_md;
2451         struct mmc_blk_data *md = mmc_get_drvdata(card);
2452
2453         if (md) {
2454                 /*
2455                  * Resume involves the card going into idle state,
2456                  * so current partition is always the main one.
2457                  */
2458                 md->part_curr = md->part_type;
2459                 mmc_queue_resume(&md->queue);
2460                 list_for_each_entry(part_md, &md->part, part) {
2461                         mmc_queue_resume(&part_md->queue);
2462                 }
2463         }
2464         return 0;
2465 }
2466 #else
2467 #define mmc_blk_suspend NULL
2468 #define mmc_blk_resume  NULL
2469 #endif
2470
2471 static struct mmc_driver mmc_driver = {
2472         .drv            = {
2473                 .name   = "mmcblk",
2474         },
2475         .probe          = mmc_blk_probe,
2476         .remove         = mmc_blk_remove,
2477         .suspend        = mmc_blk_suspend,
2478         .resume         = mmc_blk_resume,
2479 };
2480
2481 static int __init mmc_blk_init(void)
2482 {
2483         int res;
2484
2485         if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
2486                 pr_info("mmcblk: using %d minors per device\n", perdev_minors);
2487
2488         max_devices = 256 / perdev_minors;
2489
2490         res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
2491         if (res)
2492                 goto out;
2493
2494         res = mmc_register_driver(&mmc_driver);
2495         if (res)
2496                 goto out2;
2497
2498         return 0;
2499  out2:
2500         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
2501  out:
2502         return res;
2503 }
2504
2505 static void __exit mmc_blk_exit(void)
2506 {
2507         mmc_unregister_driver(&mmc_driver);
2508         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
2509 }
2510
2511 module_init(mmc_blk_init);
2512 module_exit(mmc_blk_exit);
2513
2514 MODULE_LICENSE("GPL");
2515 MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
2516