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