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