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