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