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