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