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