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