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