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