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