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