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