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