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