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/mutex.h>
32 #include <linux/scatterlist.h>
33 #include <linux/string_helpers.h>
34 #include <linux/delay.h>
35 #include <linux/capability.h>
36 #include <linux/compat.h>
37 #include <linux/pm_runtime.h>
38 
39 #include <linux/mmc/ioctl.h>
40 #include <linux/mmc/card.h>
41 #include <linux/mmc/host.h>
42 #include <linux/mmc/mmc.h>
43 #include <linux/mmc/sd.h>
44 
45 #include <asm/uaccess.h>
46 
47 #include "queue.h"
48 
49 MODULE_ALIAS("mmc:block");
50 
51 #ifdef KERNEL
52 #ifdef MODULE_PARAM_PREFIX
53 #undef MODULE_PARAM_PREFIX
54 #endif
55 #define MODULE_PARAM_PREFIX "mmcblk."
56 #endif
57 
58 #define INAND_CMD38_ARG_EXT_CSD  113
59 #define INAND_CMD38_ARG_ERASE    0x00
60 #define INAND_CMD38_ARG_TRIM     0x01
61 #define INAND_CMD38_ARG_SECERASE 0x80
62 #define INAND_CMD38_ARG_SECTRIM1 0x81
63 #define INAND_CMD38_ARG_SECTRIM2 0x88
64 #define MMC_BLK_TIMEOUT_MS  (10 * 60 * 1000)        /* 10 minute timeout */
65 #define MMC_SANITIZE_REQ_TIMEOUT 240000
66 #define MMC_EXTRACT_INDEX_FROM_ARG(x) ((x & 0x00FF0000) >> 16)
67 
68 #define mmc_req_rel_wr(req)	((req->cmd_flags & REQ_FUA) && \
69 				  (rq_data_dir(req) == WRITE))
70 #define PACKED_CMD_VER	0x01
71 #define PACKED_CMD_WR	0x02
72 
73 static DEFINE_MUTEX(block_mutex);
74 
75 /*
76  * The defaults come from config options but can be overriden by module
77  * or bootarg options.
78  */
79 static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
80 
81 /*
82  * We've only got one major, so number of mmcblk devices is
83  * limited to (1 << 20) / number of minors per device.  It is also
84  * currently limited by the size of the static bitmaps below.
85  */
86 static int max_devices;
87 
88 #define MAX_DEVICES 256
89 
90 /* TODO: Replace these with struct ida */
91 static DECLARE_BITMAP(dev_use, MAX_DEVICES);
92 static DECLARE_BITMAP(name_use, MAX_DEVICES);
93 
94 /*
95  * There is one mmc_blk_data per slot.
96  */
97 struct mmc_blk_data {
98 	spinlock_t	lock;
99 	struct gendisk	*disk;
100 	struct mmc_queue queue;
101 	struct list_head part;
102 
103 	unsigned int	flags;
104 #define MMC_BLK_CMD23	(1 << 0)	/* Can do SET_BLOCK_COUNT for multiblock */
105 #define MMC_BLK_REL_WR	(1 << 1)	/* MMC Reliable write support */
106 #define MMC_BLK_PACKED_CMD	(1 << 2)	/* MMC packed command support */
107 
108 	unsigned int	usage;
109 	unsigned int	read_only;
110 	unsigned int	part_type;
111 	unsigned int	name_idx;
112 	unsigned int	reset_done;
113 #define MMC_BLK_READ		BIT(0)
114 #define MMC_BLK_WRITE		BIT(1)
115 #define MMC_BLK_DISCARD		BIT(2)
116 #define MMC_BLK_SECDISCARD	BIT(3)
117 
118 	/*
119 	 * Only set in main mmc_blk_data associated
120 	 * with mmc_card with dev_set_drvdata, and keeps
121 	 * track of the current selected device partition.
122 	 */
123 	unsigned int	part_curr;
124 	struct device_attribute force_ro;
125 	struct device_attribute power_ro_lock;
126 	int	area_type;
127 };
128 
129 static DEFINE_MUTEX(open_lock);
130 
131 enum {
132 	MMC_PACKED_NR_IDX = -1,
133 	MMC_PACKED_NR_ZERO,
134 	MMC_PACKED_NR_SINGLE,
135 };
136 
137 module_param(perdev_minors, int, 0444);
138 MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
139 
140 static inline int mmc_blk_part_switch(struct mmc_card *card,
141 				      struct mmc_blk_data *md);
142 static int get_card_status(struct mmc_card *card, u32 *status, int retries);
143 
mmc_blk_clear_packed(struct mmc_queue_req * mqrq)144 static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq)
145 {
146 	struct mmc_packed *packed = mqrq->packed;
147 
148 	BUG_ON(!packed);
149 
150 	mqrq->cmd_type = MMC_PACKED_NONE;
151 	packed->nr_entries = MMC_PACKED_NR_ZERO;
152 	packed->idx_failure = MMC_PACKED_NR_IDX;
153 	packed->retries = 0;
154 	packed->blocks = 0;
155 }
156 
mmc_blk_get(struct gendisk * disk)157 static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
158 {
159 	struct mmc_blk_data *md;
160 
161 	mutex_lock(&open_lock);
162 	md = disk->private_data;
163 	if (md && md->usage == 0)
164 		md = NULL;
165 	if (md)
166 		md->usage++;
167 	mutex_unlock(&open_lock);
168 
169 	return md;
170 }
171 
mmc_get_devidx(struct gendisk * disk)172 static inline int mmc_get_devidx(struct gendisk *disk)
173 {
174 	int devmaj = MAJOR(disk_devt(disk));
175 	int devidx = MINOR(disk_devt(disk)) / perdev_minors;
176 
177 	if (!devmaj)
178 		devidx = disk->first_minor / perdev_minors;
179 	return devidx;
180 }
181 
mmc_blk_put(struct mmc_blk_data * md)182 static void mmc_blk_put(struct mmc_blk_data *md)
183 {
184 	mutex_lock(&open_lock);
185 	md->usage--;
186 	if (md->usage == 0) {
187 		int devidx = mmc_get_devidx(md->disk);
188 		blk_cleanup_queue(md->queue.queue);
189 
190 		__clear_bit(devidx, dev_use);
191 
192 		put_disk(md->disk);
193 		kfree(md);
194 	}
195 	mutex_unlock(&open_lock);
196 }
197 
power_ro_lock_show(struct device * dev,struct device_attribute * attr,char * buf)198 static ssize_t power_ro_lock_show(struct device *dev,
199 		struct device_attribute *attr, char *buf)
200 {
201 	int ret;
202 	struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
203 	struct mmc_card *card = md->queue.card;
204 	int locked = 0;
205 
206 	if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN)
207 		locked = 2;
208 	else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN)
209 		locked = 1;
210 
211 	ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
212 
213 	mmc_blk_put(md);
214 
215 	return ret;
216 }
217 
power_ro_lock_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)218 static ssize_t power_ro_lock_store(struct device *dev,
219 		struct device_attribute *attr, const char *buf, size_t count)
220 {
221 	int ret;
222 	struct mmc_blk_data *md, *part_md;
223 	struct mmc_card *card;
224 	unsigned long set;
225 
226 	if (kstrtoul(buf, 0, &set))
227 		return -EINVAL;
228 
229 	if (set != 1)
230 		return count;
231 
232 	md = mmc_blk_get(dev_to_disk(dev));
233 	card = md->queue.card;
234 
235 	mmc_get_card(card);
236 
237 	ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP,
238 				card->ext_csd.boot_ro_lock |
239 				EXT_CSD_BOOT_WP_B_PWR_WP_EN,
240 				card->ext_csd.part_time);
241 	if (ret)
242 		pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret);
243 	else
244 		card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN;
245 
246 	mmc_put_card(card);
247 
248 	if (!ret) {
249 		pr_info("%s: Locking boot partition ro until next power on\n",
250 			md->disk->disk_name);
251 		set_disk_ro(md->disk, 1);
252 
253 		list_for_each_entry(part_md, &md->part, part)
254 			if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) {
255 				pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
256 				set_disk_ro(part_md->disk, 1);
257 			}
258 	}
259 
260 	mmc_blk_put(md);
261 	return count;
262 }
263 
force_ro_show(struct device * dev,struct device_attribute * attr,char * buf)264 static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
265 			     char *buf)
266 {
267 	int ret;
268 	struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
269 
270 	ret = snprintf(buf, PAGE_SIZE, "%d\n",
271 		       get_disk_ro(dev_to_disk(dev)) ^
272 		       md->read_only);
273 	mmc_blk_put(md);
274 	return ret;
275 }
276 
force_ro_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)277 static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
278 			      const char *buf, size_t count)
279 {
280 	int ret;
281 	char *end;
282 	struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
283 	unsigned long set = simple_strtoul(buf, &end, 0);
284 	if (end == buf) {
285 		ret = -EINVAL;
286 		goto out;
287 	}
288 
289 	set_disk_ro(dev_to_disk(dev), set || md->read_only);
290 	ret = count;
291 out:
292 	mmc_blk_put(md);
293 	return ret;
294 }
295 
mmc_blk_open(struct block_device * bdev,fmode_t mode)296 static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
297 {
298 	struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
299 	int ret = -ENXIO;
300 
301 	mutex_lock(&block_mutex);
302 	if (md) {
303 		if (md->usage == 2)
304 			check_disk_change(bdev);
305 		ret = 0;
306 
307 		if ((mode & FMODE_WRITE) && md->read_only) {
308 			mmc_blk_put(md);
309 			ret = -EROFS;
310 		}
311 	}
312 	mutex_unlock(&block_mutex);
313 
314 	return ret;
315 }
316 
mmc_blk_release(struct gendisk * disk,fmode_t mode)317 static void mmc_blk_release(struct gendisk *disk, fmode_t mode)
318 {
319 	struct mmc_blk_data *md = disk->private_data;
320 
321 	mutex_lock(&block_mutex);
322 	mmc_blk_put(md);
323 	mutex_unlock(&block_mutex);
324 }
325 
326 static int
mmc_blk_getgeo(struct block_device * bdev,struct hd_geometry * geo)327 mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
328 {
329 	geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
330 	geo->heads = 4;
331 	geo->sectors = 16;
332 	return 0;
333 }
334 
335 struct mmc_blk_ioc_data {
336 	struct mmc_ioc_cmd ic;
337 	unsigned char *buf;
338 	u64 buf_bytes;
339 };
340 
mmc_blk_ioctl_copy_from_user(struct mmc_ioc_cmd __user * user)341 static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
342 	struct mmc_ioc_cmd __user *user)
343 {
344 	struct mmc_blk_ioc_data *idata;
345 	int err;
346 
347 	idata = kzalloc(sizeof(*idata), GFP_KERNEL);
348 	if (!idata) {
349 		err = -ENOMEM;
350 		goto out;
351 	}
352 
353 	if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
354 		err = -EFAULT;
355 		goto idata_err;
356 	}
357 
358 	idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
359 	if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
360 		err = -EOVERFLOW;
361 		goto idata_err;
362 	}
363 
364 	if (!idata->buf_bytes)
365 		return idata;
366 
367 	idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
368 	if (!idata->buf) {
369 		err = -ENOMEM;
370 		goto idata_err;
371 	}
372 
373 	if (copy_from_user(idata->buf, (void __user *)(unsigned long)
374 					idata->ic.data_ptr, idata->buf_bytes)) {
375 		err = -EFAULT;
376 		goto copy_err;
377 	}
378 
379 	return idata;
380 
381 copy_err:
382 	kfree(idata->buf);
383 idata_err:
384 	kfree(idata);
385 out:
386 	return ERR_PTR(err);
387 }
388 
mmc_blk_ioctl_copy_to_user(struct mmc_ioc_cmd __user * ic_ptr,struct mmc_blk_ioc_data * idata)389 static int mmc_blk_ioctl_copy_to_user(struct mmc_ioc_cmd __user *ic_ptr,
390 				      struct mmc_blk_ioc_data *idata)
391 {
392 	struct mmc_ioc_cmd *ic = &idata->ic;
393 
394 	if (copy_to_user(&(ic_ptr->response), ic->response,
395 			 sizeof(ic->response)))
396 		return -EFAULT;
397 
398 	if (!idata->ic.write_flag) {
399 		if (copy_to_user((void __user *)(unsigned long)ic->data_ptr,
400 				 idata->buf, idata->buf_bytes))
401 			return -EFAULT;
402 	}
403 
404 	return 0;
405 }
406 
ioctl_rpmb_card_status_poll(struct mmc_card * card,u32 * status,u32 retries_max)407 static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status,
408 				       u32 retries_max)
409 {
410 	int err;
411 	u32 retry_count = 0;
412 
413 	if (!status || !retries_max)
414 		return -EINVAL;
415 
416 	do {
417 		err = get_card_status(card, status, 5);
418 		if (err)
419 			break;
420 
421 		if (!R1_STATUS(*status) &&
422 				(R1_CURRENT_STATE(*status) != R1_STATE_PRG))
423 			break; /* RPMB programming operation complete */
424 
425 		/*
426 		 * Rechedule to give the MMC device a chance to continue
427 		 * processing the previous command without being polled too
428 		 * frequently.
429 		 */
430 		usleep_range(1000, 5000);
431 	} while (++retry_count < retries_max);
432 
433 	if (retry_count == retries_max)
434 		err = -EPERM;
435 
436 	return err;
437 }
438 
ioctl_do_sanitize(struct mmc_card * card)439 static int ioctl_do_sanitize(struct mmc_card *card)
440 {
441 	int err;
442 
443 	if (!mmc_can_sanitize(card)) {
444 			pr_warn("%s: %s - SANITIZE is not supported\n",
445 				mmc_hostname(card->host), __func__);
446 			err = -EOPNOTSUPP;
447 			goto out;
448 	}
449 
450 	pr_debug("%s: %s - SANITIZE IN PROGRESS...\n",
451 		mmc_hostname(card->host), __func__);
452 
453 	err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
454 					EXT_CSD_SANITIZE_START, 1,
455 					MMC_SANITIZE_REQ_TIMEOUT);
456 
457 	if (err)
458 		pr_err("%s: %s - EXT_CSD_SANITIZE_START failed. err=%d\n",
459 		       mmc_hostname(card->host), __func__, err);
460 
461 	pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host),
462 					     __func__);
463 out:
464 	return err;
465 }
466 
__mmc_blk_ioctl_cmd(struct mmc_card * card,struct mmc_blk_data * md,struct mmc_blk_ioc_data * idata)467 static int __mmc_blk_ioctl_cmd(struct mmc_card *card, struct mmc_blk_data *md,
468 			       struct mmc_blk_ioc_data *idata)
469 {
470 	struct mmc_command cmd = {0};
471 	struct mmc_data data = {0};
472 	struct mmc_request mrq = {NULL};
473 	struct scatterlist sg;
474 	int err;
475 	int is_rpmb = false;
476 	u32 status = 0;
477 
478 	if (!card || !md || !idata)
479 		return -EINVAL;
480 
481 	if (md->area_type & MMC_BLK_DATA_AREA_RPMB)
482 		is_rpmb = true;
483 
484 	cmd.opcode = idata->ic.opcode;
485 	cmd.arg = idata->ic.arg;
486 	cmd.flags = idata->ic.flags;
487 
488 	if (idata->buf_bytes) {
489 		data.sg = &sg;
490 		data.sg_len = 1;
491 		data.blksz = idata->ic.blksz;
492 		data.blocks = idata->ic.blocks;
493 
494 		sg_init_one(data.sg, idata->buf, idata->buf_bytes);
495 
496 		if (idata->ic.write_flag)
497 			data.flags = MMC_DATA_WRITE;
498 		else
499 			data.flags = MMC_DATA_READ;
500 
501 		/* data.flags must already be set before doing this. */
502 		mmc_set_data_timeout(&data, card);
503 
504 		/* Allow overriding the timeout_ns for empirical tuning. */
505 		if (idata->ic.data_timeout_ns)
506 			data.timeout_ns = idata->ic.data_timeout_ns;
507 
508 		if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
509 			/*
510 			 * Pretend this is a data transfer and rely on the
511 			 * host driver to compute timeout.  When all host
512 			 * drivers support cmd.cmd_timeout for R1B, this
513 			 * can be changed to:
514 			 *
515 			 *     mrq.data = NULL;
516 			 *     cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
517 			 */
518 			data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
519 		}
520 
521 		mrq.data = &data;
522 	}
523 
524 	mrq.cmd = &cmd;
525 
526 	err = mmc_blk_part_switch(card, md);
527 	if (err)
528 		return err;
529 
530 	if (idata->ic.is_acmd) {
531 		err = mmc_app_cmd(card->host, card);
532 		if (err)
533 			return err;
534 	}
535 
536 	if (is_rpmb) {
537 		err = mmc_set_blockcount(card, data.blocks,
538 			idata->ic.write_flag & (1 << 31));
539 		if (err)
540 			return err;
541 	}
542 
543 	if ((MMC_EXTRACT_INDEX_FROM_ARG(cmd.arg) == EXT_CSD_SANITIZE_START) &&
544 	    (cmd.opcode == MMC_SWITCH)) {
545 		err = ioctl_do_sanitize(card);
546 
547 		if (err)
548 			pr_err("%s: ioctl_do_sanitize() failed. err = %d",
549 			       __func__, err);
550 
551 		return err;
552 	}
553 
554 	mmc_wait_for_req(card->host, &mrq);
555 
556 	if (cmd.error) {
557 		dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
558 						__func__, cmd.error);
559 		return cmd.error;
560 	}
561 	if (data.error) {
562 		dev_err(mmc_dev(card->host), "%s: data error %d\n",
563 						__func__, data.error);
564 		return data.error;
565 	}
566 
567 	/*
568 	 * According to the SD specs, some commands require a delay after
569 	 * issuing the command.
570 	 */
571 	if (idata->ic.postsleep_min_us)
572 		usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
573 
574 	memcpy(&(idata->ic.response), cmd.resp, sizeof(cmd.resp));
575 
576 	if (is_rpmb) {
577 		/*
578 		 * Ensure RPMB command has completed by polling CMD13
579 		 * "Send Status".
580 		 */
581 		err = ioctl_rpmb_card_status_poll(card, &status, 5);
582 		if (err)
583 			dev_err(mmc_dev(card->host),
584 					"%s: Card Status=0x%08X, error %d\n",
585 					__func__, status, err);
586 	}
587 
588 	return err;
589 }
590 
mmc_blk_ioctl_cmd(struct block_device * bdev,struct mmc_ioc_cmd __user * ic_ptr)591 static int mmc_blk_ioctl_cmd(struct block_device *bdev,
592 			     struct mmc_ioc_cmd __user *ic_ptr)
593 {
594 	struct mmc_blk_ioc_data *idata;
595 	struct mmc_blk_data *md;
596 	struct mmc_card *card;
597 	int err = 0, ioc_err = 0;
598 
599 	/*
600 	 * The caller must have CAP_SYS_RAWIO, and must be calling this on the
601 	 * whole block device, not on a partition.  This prevents overspray
602 	 * between sibling partitions.
603 	 */
604 	if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
605 		return -EPERM;
606 
607 	idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
608 	if (IS_ERR(idata))
609 		return PTR_ERR(idata);
610 
611 	md = mmc_blk_get(bdev->bd_disk);
612 	if (!md) {
613 		err = -EINVAL;
614 		goto cmd_err;
615 	}
616 
617 	card = md->queue.card;
618 	if (IS_ERR(card)) {
619 		err = PTR_ERR(card);
620 		goto cmd_done;
621 	}
622 
623 	mmc_get_card(card);
624 
625 	ioc_err = __mmc_blk_ioctl_cmd(card, md, idata);
626 
627 	mmc_put_card(card);
628 
629 	err = mmc_blk_ioctl_copy_to_user(ic_ptr, idata);
630 
631 cmd_done:
632 	mmc_blk_put(md);
633 cmd_err:
634 	kfree(idata->buf);
635 	kfree(idata);
636 	return ioc_err ? ioc_err : err;
637 }
638 
mmc_blk_ioctl_multi_cmd(struct block_device * bdev,struct mmc_ioc_multi_cmd __user * user)639 static int mmc_blk_ioctl_multi_cmd(struct block_device *bdev,
640 				   struct mmc_ioc_multi_cmd __user *user)
641 {
642 	struct mmc_blk_ioc_data **idata = NULL;
643 	struct mmc_ioc_cmd __user *cmds = user->cmds;
644 	struct mmc_card *card;
645 	struct mmc_blk_data *md;
646 	int i, err = 0, ioc_err = 0;
647 	__u64 num_of_cmds;
648 
649 	/*
650 	 * The caller must have CAP_SYS_RAWIO, and must be calling this on the
651 	 * whole block device, not on a partition.  This prevents overspray
652 	 * between sibling partitions.
653 	 */
654 	if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
655 		return -EPERM;
656 
657 	if (copy_from_user(&num_of_cmds, &user->num_of_cmds,
658 			   sizeof(num_of_cmds)))
659 		return -EFAULT;
660 
661 	if (num_of_cmds > MMC_IOC_MAX_CMDS)
662 		return -EINVAL;
663 
664 	idata = kcalloc(num_of_cmds, sizeof(*idata), GFP_KERNEL);
665 	if (!idata)
666 		return -ENOMEM;
667 
668 	for (i = 0; i < num_of_cmds; i++) {
669 		idata[i] = mmc_blk_ioctl_copy_from_user(&cmds[i]);
670 		if (IS_ERR(idata[i])) {
671 			err = PTR_ERR(idata[i]);
672 			num_of_cmds = i;
673 			goto cmd_err;
674 		}
675 	}
676 
677 	md = mmc_blk_get(bdev->bd_disk);
678 	if (!md)
679 		goto cmd_err;
680 
681 	card = md->queue.card;
682 	if (IS_ERR(card)) {
683 		err = PTR_ERR(card);
684 		goto cmd_done;
685 	}
686 
687 	mmc_get_card(card);
688 
689 	for (i = 0; i < num_of_cmds && !ioc_err; i++)
690 		ioc_err = __mmc_blk_ioctl_cmd(card, md, idata[i]);
691 
692 	mmc_put_card(card);
693 
694 	/* copy to user if data and response */
695 	for (i = 0; i < num_of_cmds && !err; i++)
696 		err = mmc_blk_ioctl_copy_to_user(&cmds[i], idata[i]);
697 
698 cmd_done:
699 	mmc_blk_put(md);
700 cmd_err:
701 	for (i = 0; i < num_of_cmds; i++) {
702 		kfree(idata[i]->buf);
703 		kfree(idata[i]);
704 	}
705 	kfree(idata);
706 	return ioc_err ? ioc_err : err;
707 }
708 
mmc_blk_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)709 static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
710 	unsigned int cmd, unsigned long arg)
711 {
712 	switch (cmd) {
713 	case MMC_IOC_CMD:
714 		return mmc_blk_ioctl_cmd(bdev,
715 				(struct mmc_ioc_cmd __user *)arg);
716 	case MMC_IOC_MULTI_CMD:
717 		return mmc_blk_ioctl_multi_cmd(bdev,
718 				(struct mmc_ioc_multi_cmd __user *)arg);
719 	default:
720 		return -EINVAL;
721 	}
722 }
723 
724 #ifdef CONFIG_COMPAT
mmc_blk_compat_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)725 static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
726 	unsigned int cmd, unsigned long arg)
727 {
728 	return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
729 }
730 #endif
731 
732 static const struct block_device_operations mmc_bdops = {
733 	.open			= mmc_blk_open,
734 	.release		= mmc_blk_release,
735 	.getgeo			= mmc_blk_getgeo,
736 	.owner			= THIS_MODULE,
737 	.ioctl			= mmc_blk_ioctl,
738 #ifdef CONFIG_COMPAT
739 	.compat_ioctl		= mmc_blk_compat_ioctl,
740 #endif
741 };
742 
mmc_blk_part_switch(struct mmc_card * card,struct mmc_blk_data * md)743 static inline int mmc_blk_part_switch(struct mmc_card *card,
744 				      struct mmc_blk_data *md)
745 {
746 	int ret;
747 	struct mmc_blk_data *main_md = dev_get_drvdata(&card->dev);
748 
749 	if (main_md->part_curr == md->part_type)
750 		return 0;
751 
752 	if (mmc_card_mmc(card)) {
753 		u8 part_config = card->ext_csd.part_config;
754 
755 		part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
756 		part_config |= md->part_type;
757 
758 		ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
759 				 EXT_CSD_PART_CONFIG, part_config,
760 				 card->ext_csd.part_time);
761 		if (ret)
762 			return ret;
763 
764 		card->ext_csd.part_config = part_config;
765 	}
766 
767 	main_md->part_curr = md->part_type;
768 	return 0;
769 }
770 
mmc_sd_num_wr_blocks(struct mmc_card * card)771 static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
772 {
773 	int err;
774 	u32 result;
775 	__be32 *blocks;
776 
777 	struct mmc_request mrq = {NULL};
778 	struct mmc_command cmd = {0};
779 	struct mmc_data data = {0};
780 
781 	struct scatterlist sg;
782 
783 	cmd.opcode = MMC_APP_CMD;
784 	cmd.arg = card->rca << 16;
785 	cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
786 
787 	err = mmc_wait_for_cmd(card->host, &cmd, 0);
788 	if (err)
789 		return (u32)-1;
790 	if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
791 		return (u32)-1;
792 
793 	memset(&cmd, 0, sizeof(struct mmc_command));
794 
795 	cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
796 	cmd.arg = 0;
797 	cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
798 
799 	data.blksz = 4;
800 	data.blocks = 1;
801 	data.flags = MMC_DATA_READ;
802 	data.sg = &sg;
803 	data.sg_len = 1;
804 	mmc_set_data_timeout(&data, card);
805 
806 	mrq.cmd = &cmd;
807 	mrq.data = &data;
808 
809 	blocks = kmalloc(4, GFP_KERNEL);
810 	if (!blocks)
811 		return (u32)-1;
812 
813 	sg_init_one(&sg, blocks, 4);
814 
815 	mmc_wait_for_req(card->host, &mrq);
816 
817 	result = ntohl(*blocks);
818 	kfree(blocks);
819 
820 	if (cmd.error || data.error)
821 		result = (u32)-1;
822 
823 	return result;
824 }
825 
get_card_status(struct mmc_card * card,u32 * status,int retries)826 static int get_card_status(struct mmc_card *card, u32 *status, int retries)
827 {
828 	struct mmc_command cmd = {0};
829 	int err;
830 
831 	cmd.opcode = MMC_SEND_STATUS;
832 	if (!mmc_host_is_spi(card->host))
833 		cmd.arg = card->rca << 16;
834 	cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
835 	err = mmc_wait_for_cmd(card->host, &cmd, retries);
836 	if (err == 0)
837 		*status = cmd.resp[0];
838 	return err;
839 }
840 
card_busy_detect(struct mmc_card * card,unsigned int timeout_ms,bool hw_busy_detect,struct request * req,int * gen_err)841 static int card_busy_detect(struct mmc_card *card, unsigned int timeout_ms,
842 		bool hw_busy_detect, struct request *req, int *gen_err)
843 {
844 	unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
845 	int err = 0;
846 	u32 status;
847 
848 	do {
849 		err = get_card_status(card, &status, 5);
850 		if (err) {
851 			pr_err("%s: error %d requesting status\n",
852 			       req->rq_disk->disk_name, err);
853 			return err;
854 		}
855 
856 		if (status & R1_ERROR) {
857 			pr_err("%s: %s: error sending status cmd, status %#x\n",
858 				req->rq_disk->disk_name, __func__, status);
859 			*gen_err = 1;
860 		}
861 
862 		/* We may rely on the host hw to handle busy detection.*/
863 		if ((card->host->caps & MMC_CAP_WAIT_WHILE_BUSY) &&
864 			hw_busy_detect)
865 			break;
866 
867 		/*
868 		 * Timeout if the device never becomes ready for data and never
869 		 * leaves the program state.
870 		 */
871 		if (time_after(jiffies, timeout)) {
872 			pr_err("%s: Card stuck in programming state! %s %s\n",
873 				mmc_hostname(card->host),
874 				req->rq_disk->disk_name, __func__);
875 			return -ETIMEDOUT;
876 		}
877 
878 		/*
879 		 * Some cards mishandle the status bits,
880 		 * so make sure to check both the busy
881 		 * indication and the card state.
882 		 */
883 	} while (!(status & R1_READY_FOR_DATA) ||
884 		 (R1_CURRENT_STATE(status) == R1_STATE_PRG));
885 
886 	return err;
887 }
888 
send_stop(struct mmc_card * card,unsigned int timeout_ms,struct request * req,int * gen_err,u32 * stop_status)889 static int send_stop(struct mmc_card *card, unsigned int timeout_ms,
890 		struct request *req, int *gen_err, u32 *stop_status)
891 {
892 	struct mmc_host *host = card->host;
893 	struct mmc_command cmd = {0};
894 	int err;
895 	bool use_r1b_resp = rq_data_dir(req) == WRITE;
896 
897 	/*
898 	 * Normally we use R1B responses for WRITE, but in cases where the host
899 	 * has specified a max_busy_timeout we need to validate it. A failure
900 	 * means we need to prevent the host from doing hw busy detection, which
901 	 * is done by converting to a R1 response instead.
902 	 */
903 	if (host->max_busy_timeout && (timeout_ms > host->max_busy_timeout))
904 		use_r1b_resp = false;
905 
906 	cmd.opcode = MMC_STOP_TRANSMISSION;
907 	if (use_r1b_resp) {
908 		cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
909 		cmd.busy_timeout = timeout_ms;
910 	} else {
911 		cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
912 	}
913 
914 	err = mmc_wait_for_cmd(host, &cmd, 5);
915 	if (err)
916 		return err;
917 
918 	*stop_status = cmd.resp[0];
919 
920 	/* No need to check card status in case of READ. */
921 	if (rq_data_dir(req) == READ)
922 		return 0;
923 
924 	if (!mmc_host_is_spi(host) &&
925 		(*stop_status & R1_ERROR)) {
926 		pr_err("%s: %s: general error sending stop command, resp %#x\n",
927 			req->rq_disk->disk_name, __func__, *stop_status);
928 		*gen_err = 1;
929 	}
930 
931 	return card_busy_detect(card, timeout_ms, use_r1b_resp, req, gen_err);
932 }
933 
934 #define ERR_NOMEDIUM	3
935 #define ERR_RETRY	2
936 #define ERR_ABORT	1
937 #define ERR_CONTINUE	0
938 
mmc_blk_cmd_error(struct request * req,const char * name,int error,bool status_valid,u32 status)939 static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
940 	bool status_valid, u32 status)
941 {
942 	switch (error) {
943 	case -EILSEQ:
944 		/* response crc error, retry the r/w cmd */
945 		pr_err("%s: %s sending %s command, card status %#x\n",
946 			req->rq_disk->disk_name, "response CRC error",
947 			name, status);
948 		return ERR_RETRY;
949 
950 	case -ETIMEDOUT:
951 		pr_err("%s: %s sending %s command, card status %#x\n",
952 			req->rq_disk->disk_name, "timed out", name, status);
953 
954 		/* If the status cmd initially failed, retry the r/w cmd */
955 		if (!status_valid)
956 			return ERR_RETRY;
957 
958 		/*
959 		 * If it was a r/w cmd crc error, or illegal command
960 		 * (eg, issued in wrong state) then retry - we should
961 		 * have corrected the state problem above.
962 		 */
963 		if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND))
964 			return ERR_RETRY;
965 
966 		/* Otherwise abort the command */
967 		return ERR_ABORT;
968 
969 	default:
970 		/* We don't understand the error code the driver gave us */
971 		pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
972 		       req->rq_disk->disk_name, error, status);
973 		return ERR_ABORT;
974 	}
975 }
976 
977 /*
978  * Initial r/w and stop cmd error recovery.
979  * We don't know whether the card received the r/w cmd or not, so try to
980  * restore things back to a sane state.  Essentially, we do this as follows:
981  * - Obtain card status.  If the first attempt to obtain card status fails,
982  *   the status word will reflect the failed status cmd, not the failed
983  *   r/w cmd.  If we fail to obtain card status, it suggests we can no
984  *   longer communicate with the card.
985  * - Check the card state.  If the card received the cmd but there was a
986  *   transient problem with the response, it might still be in a data transfer
987  *   mode.  Try to send it a stop command.  If this fails, we can't recover.
988  * - If the r/w cmd failed due to a response CRC error, it was probably
989  *   transient, so retry the cmd.
990  * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
991  * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
992  *   illegal cmd, retry.
993  * Otherwise we don't understand what happened, so abort.
994  */
mmc_blk_cmd_recovery(struct mmc_card * card,struct request * req,struct mmc_blk_request * brq,int * ecc_err,int * gen_err)995 static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
996 	struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
997 {
998 	bool prev_cmd_status_valid = true;
999 	u32 status, stop_status = 0;
1000 	int err, retry;
1001 
1002 	if (mmc_card_removed(card))
1003 		return ERR_NOMEDIUM;
1004 
1005 	/*
1006 	 * Try to get card status which indicates both the card state
1007 	 * and why there was no response.  If the first attempt fails,
1008 	 * we can't be sure the returned status is for the r/w command.
1009 	 */
1010 	for (retry = 2; retry >= 0; retry--) {
1011 		err = get_card_status(card, &status, 0);
1012 		if (!err)
1013 			break;
1014 
1015 		/* Re-tune if needed */
1016 		mmc_retune_recheck(card->host);
1017 
1018 		prev_cmd_status_valid = false;
1019 		pr_err("%s: error %d sending status command, %sing\n",
1020 		       req->rq_disk->disk_name, err, retry ? "retry" : "abort");
1021 	}
1022 
1023 	/* We couldn't get a response from the card.  Give up. */
1024 	if (err) {
1025 		/* Check if the card is removed */
1026 		if (mmc_detect_card_removed(card->host))
1027 			return ERR_NOMEDIUM;
1028 		return ERR_ABORT;
1029 	}
1030 
1031 	/* Flag ECC errors */
1032 	if ((status & R1_CARD_ECC_FAILED) ||
1033 	    (brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
1034 	    (brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
1035 		*ecc_err = 1;
1036 
1037 	/* Flag General errors */
1038 	if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
1039 		if ((status & R1_ERROR) ||
1040 			(brq->stop.resp[0] & R1_ERROR)) {
1041 			pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
1042 			       req->rq_disk->disk_name, __func__,
1043 			       brq->stop.resp[0], status);
1044 			*gen_err = 1;
1045 		}
1046 
1047 	/*
1048 	 * Check the current card state.  If it is in some data transfer
1049 	 * mode, tell it to stop (and hopefully transition back to TRAN.)
1050 	 */
1051 	if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
1052 	    R1_CURRENT_STATE(status) == R1_STATE_RCV) {
1053 		err = send_stop(card,
1054 			DIV_ROUND_UP(brq->data.timeout_ns, 1000000),
1055 			req, gen_err, &stop_status);
1056 		if (err) {
1057 			pr_err("%s: error %d sending stop command\n",
1058 			       req->rq_disk->disk_name, err);
1059 			/*
1060 			 * If the stop cmd also timed out, the card is probably
1061 			 * not present, so abort. Other errors are bad news too.
1062 			 */
1063 			return ERR_ABORT;
1064 		}
1065 
1066 		if (stop_status & R1_CARD_ECC_FAILED)
1067 			*ecc_err = 1;
1068 	}
1069 
1070 	/* Check for set block count errors */
1071 	if (brq->sbc.error)
1072 		return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
1073 				prev_cmd_status_valid, status);
1074 
1075 	/* Check for r/w command errors */
1076 	if (brq->cmd.error)
1077 		return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
1078 				prev_cmd_status_valid, status);
1079 
1080 	/* Data errors */
1081 	if (!brq->stop.error)
1082 		return ERR_CONTINUE;
1083 
1084 	/* Now for stop errors.  These aren't fatal to the transfer. */
1085 	pr_info("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
1086 	       req->rq_disk->disk_name, brq->stop.error,
1087 	       brq->cmd.resp[0], status);
1088 
1089 	/*
1090 	 * Subsitute in our own stop status as this will give the error
1091 	 * state which happened during the execution of the r/w command.
1092 	 */
1093 	if (stop_status) {
1094 		brq->stop.resp[0] = stop_status;
1095 		brq->stop.error = 0;
1096 	}
1097 	return ERR_CONTINUE;
1098 }
1099 
mmc_blk_reset(struct mmc_blk_data * md,struct mmc_host * host,int type)1100 static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
1101 			 int type)
1102 {
1103 	int err;
1104 
1105 	if (md->reset_done & type)
1106 		return -EEXIST;
1107 
1108 	md->reset_done |= type;
1109 	err = mmc_hw_reset(host);
1110 	/* Ensure we switch back to the correct partition */
1111 	if (err != -EOPNOTSUPP) {
1112 		struct mmc_blk_data *main_md =
1113 			dev_get_drvdata(&host->card->dev);
1114 		int part_err;
1115 
1116 		main_md->part_curr = main_md->part_type;
1117 		part_err = mmc_blk_part_switch(host->card, md);
1118 		if (part_err) {
1119 			/*
1120 			 * We have failed to get back into the correct
1121 			 * partition, so we need to abort the whole request.
1122 			 */
1123 			return -ENODEV;
1124 		}
1125 	}
1126 	return err;
1127 }
1128 
mmc_blk_reset_success(struct mmc_blk_data * md,int type)1129 static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
1130 {
1131 	md->reset_done &= ~type;
1132 }
1133 
mmc_access_rpmb(struct mmc_queue * mq)1134 int mmc_access_rpmb(struct mmc_queue *mq)
1135 {
1136 	struct mmc_blk_data *md = mq->data;
1137 	/*
1138 	 * If this is a RPMB partition access, return ture
1139 	 */
1140 	if (md && md->part_type == EXT_CSD_PART_CONFIG_ACC_RPMB)
1141 		return true;
1142 
1143 	return false;
1144 }
1145 
mmc_blk_issue_discard_rq(struct mmc_queue * mq,struct request * req)1146 static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
1147 {
1148 	struct mmc_blk_data *md = mq->data;
1149 	struct mmc_card *card = md->queue.card;
1150 	unsigned int from, nr, arg;
1151 	int err = 0, type = MMC_BLK_DISCARD;
1152 
1153 	if (!mmc_can_erase(card)) {
1154 		err = -EOPNOTSUPP;
1155 		goto out;
1156 	}
1157 
1158 	from = blk_rq_pos(req);
1159 	nr = blk_rq_sectors(req);
1160 
1161 	if (mmc_can_discard(card))
1162 		arg = MMC_DISCARD_ARG;
1163 	else if (mmc_can_trim(card))
1164 		arg = MMC_TRIM_ARG;
1165 	else
1166 		arg = MMC_ERASE_ARG;
1167 retry:
1168 	if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1169 		err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1170 				 INAND_CMD38_ARG_EXT_CSD,
1171 				 arg == MMC_TRIM_ARG ?
1172 				 INAND_CMD38_ARG_TRIM :
1173 				 INAND_CMD38_ARG_ERASE,
1174 				 0);
1175 		if (err)
1176 			goto out;
1177 	}
1178 	err = mmc_erase(card, from, nr, arg);
1179 out:
1180 	if (err == -EIO && !mmc_blk_reset(md, card->host, type))
1181 		goto retry;
1182 	if (!err)
1183 		mmc_blk_reset_success(md, type);
1184 	blk_end_request(req, err, blk_rq_bytes(req));
1185 
1186 	return err ? 0 : 1;
1187 }
1188 
mmc_blk_issue_secdiscard_rq(struct mmc_queue * mq,struct request * req)1189 static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
1190 				       struct request *req)
1191 {
1192 	struct mmc_blk_data *md = mq->data;
1193 	struct mmc_card *card = md->queue.card;
1194 	unsigned int from, nr, arg;
1195 	int err = 0, type = MMC_BLK_SECDISCARD;
1196 
1197 	if (!(mmc_can_secure_erase_trim(card))) {
1198 		err = -EOPNOTSUPP;
1199 		goto out;
1200 	}
1201 
1202 	from = blk_rq_pos(req);
1203 	nr = blk_rq_sectors(req);
1204 
1205 	if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr))
1206 		arg = MMC_SECURE_TRIM1_ARG;
1207 	else
1208 		arg = MMC_SECURE_ERASE_ARG;
1209 
1210 retry:
1211 	if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1212 		err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1213 				 INAND_CMD38_ARG_EXT_CSD,
1214 				 arg == MMC_SECURE_TRIM1_ARG ?
1215 				 INAND_CMD38_ARG_SECTRIM1 :
1216 				 INAND_CMD38_ARG_SECERASE,
1217 				 0);
1218 		if (err)
1219 			goto out_retry;
1220 	}
1221 
1222 	err = mmc_erase(card, from, nr, arg);
1223 	if (err == -EIO)
1224 		goto out_retry;
1225 	if (err)
1226 		goto out;
1227 
1228 	if (arg == MMC_SECURE_TRIM1_ARG) {
1229 		if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1230 			err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1231 					 INAND_CMD38_ARG_EXT_CSD,
1232 					 INAND_CMD38_ARG_SECTRIM2,
1233 					 0);
1234 			if (err)
1235 				goto out_retry;
1236 		}
1237 
1238 		err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
1239 		if (err == -EIO)
1240 			goto out_retry;
1241 		if (err)
1242 			goto out;
1243 	}
1244 
1245 out_retry:
1246 	if (err && !mmc_blk_reset(md, card->host, type))
1247 		goto retry;
1248 	if (!err)
1249 		mmc_blk_reset_success(md, type);
1250 out:
1251 	blk_end_request(req, err, blk_rq_bytes(req));
1252 
1253 	return err ? 0 : 1;
1254 }
1255 
mmc_blk_issue_flush(struct mmc_queue * mq,struct request * req)1256 static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
1257 {
1258 	struct mmc_blk_data *md = mq->data;
1259 	struct mmc_card *card = md->queue.card;
1260 	int ret = 0;
1261 
1262 	ret = mmc_flush_cache(card);
1263 	if (ret)
1264 		ret = -EIO;
1265 
1266 	blk_end_request_all(req, ret);
1267 
1268 	return ret ? 0 : 1;
1269 }
1270 
1271 /*
1272  * Reformat current write as a reliable write, supporting
1273  * both legacy and the enhanced reliable write MMC cards.
1274  * In each transfer we'll handle only as much as a single
1275  * reliable write can handle, thus finish the request in
1276  * partial completions.
1277  */
mmc_apply_rel_rw(struct mmc_blk_request * brq,struct mmc_card * card,struct request * req)1278 static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
1279 				    struct mmc_card *card,
1280 				    struct request *req)
1281 {
1282 	if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
1283 		/* Legacy mode imposes restrictions on transfers. */
1284 		if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
1285 			brq->data.blocks = 1;
1286 
1287 		if (brq->data.blocks > card->ext_csd.rel_sectors)
1288 			brq->data.blocks = card->ext_csd.rel_sectors;
1289 		else if (brq->data.blocks < card->ext_csd.rel_sectors)
1290 			brq->data.blocks = 1;
1291 	}
1292 }
1293 
1294 #define CMD_ERRORS							\
1295 	(R1_OUT_OF_RANGE |	/* Command argument out of range */	\
1296 	 R1_ADDRESS_ERROR |	/* Misaligned address */		\
1297 	 R1_BLOCK_LEN_ERROR |	/* Transferred block length incorrect */\
1298 	 R1_WP_VIOLATION |	/* Tried to write to protected block */	\
1299 	 R1_CC_ERROR |		/* Card controller error */		\
1300 	 R1_ERROR)		/* General/unknown error */
1301 
mmc_blk_err_check(struct mmc_card * card,struct mmc_async_req * areq)1302 static int mmc_blk_err_check(struct mmc_card *card,
1303 			     struct mmc_async_req *areq)
1304 {
1305 	struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
1306 						    mmc_active);
1307 	struct mmc_blk_request *brq = &mq_mrq->brq;
1308 	struct request *req = mq_mrq->req;
1309 	int need_retune = card->host->need_retune;
1310 	int ecc_err = 0, gen_err = 0;
1311 
1312 	/*
1313 	 * sbc.error indicates a problem with the set block count
1314 	 * command.  No data will have been transferred.
1315 	 *
1316 	 * cmd.error indicates a problem with the r/w command.  No
1317 	 * data will have been transferred.
1318 	 *
1319 	 * stop.error indicates a problem with the stop command.  Data
1320 	 * may have been transferred, or may still be transferring.
1321 	 */
1322 	if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
1323 	    brq->data.error) {
1324 		switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
1325 		case ERR_RETRY:
1326 			return MMC_BLK_RETRY;
1327 		case ERR_ABORT:
1328 			return MMC_BLK_ABORT;
1329 		case ERR_NOMEDIUM:
1330 			return MMC_BLK_NOMEDIUM;
1331 		case ERR_CONTINUE:
1332 			break;
1333 		}
1334 	}
1335 
1336 	/*
1337 	 * Check for errors relating to the execution of the
1338 	 * initial command - such as address errors.  No data
1339 	 * has been transferred.
1340 	 */
1341 	if (brq->cmd.resp[0] & CMD_ERRORS) {
1342 		pr_err("%s: r/w command failed, status = %#x\n",
1343 		       req->rq_disk->disk_name, brq->cmd.resp[0]);
1344 		return MMC_BLK_ABORT;
1345 	}
1346 
1347 	/*
1348 	 * Everything else is either success, or a data error of some
1349 	 * kind.  If it was a write, we may have transitioned to
1350 	 * program mode, which we have to wait for it to complete.
1351 	 */
1352 	if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
1353 		int err;
1354 
1355 		/* Check stop command response */
1356 		if (brq->stop.resp[0] & R1_ERROR) {
1357 			pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
1358 			       req->rq_disk->disk_name, __func__,
1359 			       brq->stop.resp[0]);
1360 			gen_err = 1;
1361 		}
1362 
1363 		err = card_busy_detect(card, MMC_BLK_TIMEOUT_MS, false, req,
1364 					&gen_err);
1365 		if (err)
1366 			return MMC_BLK_CMD_ERR;
1367 	}
1368 
1369 	/* if general error occurs, retry the write operation. */
1370 	if (gen_err) {
1371 		pr_warn("%s: retrying write for general error\n",
1372 				req->rq_disk->disk_name);
1373 		return MMC_BLK_RETRY;
1374 	}
1375 
1376 	if (brq->data.error) {
1377 		if (need_retune && !brq->retune_retry_done) {
1378 			pr_info("%s: retrying because a re-tune was needed\n",
1379 				req->rq_disk->disk_name);
1380 			brq->retune_retry_done = 1;
1381 			return MMC_BLK_RETRY;
1382 		}
1383 		pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
1384 		       req->rq_disk->disk_name, brq->data.error,
1385 		       (unsigned)blk_rq_pos(req),
1386 		       (unsigned)blk_rq_sectors(req),
1387 		       brq->cmd.resp[0], brq->stop.resp[0]);
1388 
1389 		if (rq_data_dir(req) == READ) {
1390 			if (ecc_err)
1391 				return MMC_BLK_ECC_ERR;
1392 			return MMC_BLK_DATA_ERR;
1393 		} else {
1394 			return MMC_BLK_CMD_ERR;
1395 		}
1396 	}
1397 
1398 	if (!brq->data.bytes_xfered)
1399 		return MMC_BLK_RETRY;
1400 
1401 	if (mmc_packed_cmd(mq_mrq->cmd_type)) {
1402 		if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered))
1403 			return MMC_BLK_PARTIAL;
1404 		else
1405 			return MMC_BLK_SUCCESS;
1406 	}
1407 
1408 	if (blk_rq_bytes(req) != brq->data.bytes_xfered)
1409 		return MMC_BLK_PARTIAL;
1410 
1411 	return MMC_BLK_SUCCESS;
1412 }
1413 
mmc_blk_packed_err_check(struct mmc_card * card,struct mmc_async_req * areq)1414 static int mmc_blk_packed_err_check(struct mmc_card *card,
1415 				    struct mmc_async_req *areq)
1416 {
1417 	struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
1418 			mmc_active);
1419 	struct request *req = mq_rq->req;
1420 	struct mmc_packed *packed = mq_rq->packed;
1421 	int err, check, status;
1422 	u8 *ext_csd;
1423 
1424 	BUG_ON(!packed);
1425 
1426 	packed->retries--;
1427 	check = mmc_blk_err_check(card, areq);
1428 	err = get_card_status(card, &status, 0);
1429 	if (err) {
1430 		pr_err("%s: error %d sending status command\n",
1431 		       req->rq_disk->disk_name, err);
1432 		return MMC_BLK_ABORT;
1433 	}
1434 
1435 	if (status & R1_EXCEPTION_EVENT) {
1436 		err = mmc_get_ext_csd(card, &ext_csd);
1437 		if (err) {
1438 			pr_err("%s: error %d sending ext_csd\n",
1439 			       req->rq_disk->disk_name, err);
1440 			return MMC_BLK_ABORT;
1441 		}
1442 
1443 		if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] &
1444 		     EXT_CSD_PACKED_FAILURE) &&
1445 		    (ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
1446 		     EXT_CSD_PACKED_GENERIC_ERROR)) {
1447 			if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
1448 			    EXT_CSD_PACKED_INDEXED_ERROR) {
1449 				packed->idx_failure =
1450 				  ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1;
1451 				check = MMC_BLK_PARTIAL;
1452 			}
1453 			pr_err("%s: packed cmd failed, nr %u, sectors %u, "
1454 			       "failure index: %d\n",
1455 			       req->rq_disk->disk_name, packed->nr_entries,
1456 			       packed->blocks, packed->idx_failure);
1457 		}
1458 		kfree(ext_csd);
1459 	}
1460 
1461 	return check;
1462 }
1463 
mmc_blk_rw_rq_prep(struct mmc_queue_req * mqrq,struct mmc_card * card,int disable_multi,struct mmc_queue * mq)1464 static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1465 			       struct mmc_card *card,
1466 			       int disable_multi,
1467 			       struct mmc_queue *mq)
1468 {
1469 	u32 readcmd, writecmd;
1470 	struct mmc_blk_request *brq = &mqrq->brq;
1471 	struct request *req = mqrq->req;
1472 	struct mmc_blk_data *md = mq->data;
1473 	bool do_data_tag;
1474 
1475 	/*
1476 	 * Reliable writes are used to implement Forced Unit Access and
1477 	 * are supported only on MMCs.
1478 	 */
1479 	bool do_rel_wr = (req->cmd_flags & REQ_FUA) &&
1480 		(rq_data_dir(req) == WRITE) &&
1481 		(md->flags & MMC_BLK_REL_WR);
1482 
1483 	memset(brq, 0, sizeof(struct mmc_blk_request));
1484 	brq->mrq.cmd = &brq->cmd;
1485 	brq->mrq.data = &brq->data;
1486 
1487 	brq->cmd.arg = blk_rq_pos(req);
1488 	if (!mmc_card_blockaddr(card))
1489 		brq->cmd.arg <<= 9;
1490 	brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1491 	brq->data.blksz = 512;
1492 	brq->stop.opcode = MMC_STOP_TRANSMISSION;
1493 	brq->stop.arg = 0;
1494 	brq->data.blocks = blk_rq_sectors(req);
1495 
1496 	/*
1497 	 * The block layer doesn't support all sector count
1498 	 * restrictions, so we need to be prepared for too big
1499 	 * requests.
1500 	 */
1501 	if (brq->data.blocks > card->host->max_blk_count)
1502 		brq->data.blocks = card->host->max_blk_count;
1503 
1504 	if (brq->data.blocks > 1) {
1505 		/*
1506 		 * After a read error, we redo the request one sector
1507 		 * at a time in order to accurately determine which
1508 		 * sectors can be read successfully.
1509 		 */
1510 		if (disable_multi)
1511 			brq->data.blocks = 1;
1512 
1513 		/*
1514 		 * Some controllers have HW issues while operating
1515 		 * in multiple I/O mode
1516 		 */
1517 		if (card->host->ops->multi_io_quirk)
1518 			brq->data.blocks = card->host->ops->multi_io_quirk(card,
1519 						(rq_data_dir(req) == READ) ?
1520 						MMC_DATA_READ : MMC_DATA_WRITE,
1521 						brq->data.blocks);
1522 	}
1523 
1524 	if (brq->data.blocks > 1 || do_rel_wr) {
1525 		/* SPI multiblock writes terminate using a special
1526 		 * token, not a STOP_TRANSMISSION request.
1527 		 */
1528 		if (!mmc_host_is_spi(card->host) ||
1529 		    rq_data_dir(req) == READ)
1530 			brq->mrq.stop = &brq->stop;
1531 		readcmd = MMC_READ_MULTIPLE_BLOCK;
1532 		writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1533 	} else {
1534 		brq->mrq.stop = NULL;
1535 		readcmd = MMC_READ_SINGLE_BLOCK;
1536 		writecmd = MMC_WRITE_BLOCK;
1537 	}
1538 	if (rq_data_dir(req) == READ) {
1539 		brq->cmd.opcode = readcmd;
1540 		brq->data.flags |= MMC_DATA_READ;
1541 		if (brq->mrq.stop)
1542 			brq->stop.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 |
1543 					MMC_CMD_AC;
1544 	} else {
1545 		brq->cmd.opcode = writecmd;
1546 		brq->data.flags |= MMC_DATA_WRITE;
1547 		if (brq->mrq.stop)
1548 			brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B |
1549 					MMC_CMD_AC;
1550 	}
1551 
1552 	if (do_rel_wr)
1553 		mmc_apply_rel_rw(brq, card, req);
1554 
1555 	/*
1556 	 * Data tag is used only during writing meta data to speed
1557 	 * up write and any subsequent read of this meta data
1558 	 */
1559 	do_data_tag = (card->ext_csd.data_tag_unit_size) &&
1560 		(req->cmd_flags & REQ_META) &&
1561 		(rq_data_dir(req) == WRITE) &&
1562 		((brq->data.blocks * brq->data.blksz) >=
1563 		 card->ext_csd.data_tag_unit_size);
1564 
1565 	/*
1566 	 * Pre-defined multi-block transfers are preferable to
1567 	 * open ended-ones (and necessary for reliable writes).
1568 	 * However, it is not sufficient to just send CMD23,
1569 	 * and avoid the final CMD12, as on an error condition
1570 	 * CMD12 (stop) needs to be sent anyway. This, coupled
1571 	 * with Auto-CMD23 enhancements provided by some
1572 	 * hosts, means that the complexity of dealing
1573 	 * with this is best left to the host. If CMD23 is
1574 	 * supported by card and host, we'll fill sbc in and let
1575 	 * the host deal with handling it correctly. This means
1576 	 * that for hosts that don't expose MMC_CAP_CMD23, no
1577 	 * change of behavior will be observed.
1578 	 *
1579 	 * N.B: Some MMC cards experience perf degradation.
1580 	 * We'll avoid using CMD23-bounded multiblock writes for
1581 	 * these, while retaining features like reliable writes.
1582 	 */
1583 	if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
1584 	    (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) ||
1585 	     do_data_tag)) {
1586 		brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1587 		brq->sbc.arg = brq->data.blocks |
1588 			(do_rel_wr ? (1 << 31) : 0) |
1589 			(do_data_tag ? (1 << 29) : 0);
1590 		brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1591 		brq->mrq.sbc = &brq->sbc;
1592 	}
1593 
1594 	mmc_set_data_timeout(&brq->data, card);
1595 
1596 	brq->data.sg = mqrq->sg;
1597 	brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1598 
1599 	/*
1600 	 * Adjust the sg list so it is the same size as the
1601 	 * request.
1602 	 */
1603 	if (brq->data.blocks != blk_rq_sectors(req)) {
1604 		int i, data_size = brq->data.blocks << 9;
1605 		struct scatterlist *sg;
1606 
1607 		for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1608 			data_size -= sg->length;
1609 			if (data_size <= 0) {
1610 				sg->length += data_size;
1611 				i++;
1612 				break;
1613 			}
1614 		}
1615 		brq->data.sg_len = i;
1616 	}
1617 
1618 	mqrq->mmc_active.mrq = &brq->mrq;
1619 	mqrq->mmc_active.err_check = mmc_blk_err_check;
1620 
1621 	mmc_queue_bounce_pre(mqrq);
1622 }
1623 
mmc_calc_packed_hdr_segs(struct request_queue * q,struct mmc_card * card)1624 static inline u8 mmc_calc_packed_hdr_segs(struct request_queue *q,
1625 					  struct mmc_card *card)
1626 {
1627 	unsigned int hdr_sz = mmc_large_sector(card) ? 4096 : 512;
1628 	unsigned int max_seg_sz = queue_max_segment_size(q);
1629 	unsigned int len, nr_segs = 0;
1630 
1631 	do {
1632 		len = min(hdr_sz, max_seg_sz);
1633 		hdr_sz -= len;
1634 		nr_segs++;
1635 	} while (hdr_sz);
1636 
1637 	return nr_segs;
1638 }
1639 
mmc_blk_prep_packed_list(struct mmc_queue * mq,struct request * req)1640 static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req)
1641 {
1642 	struct request_queue *q = mq->queue;
1643 	struct mmc_card *card = mq->card;
1644 	struct request *cur = req, *next = NULL;
1645 	struct mmc_blk_data *md = mq->data;
1646 	struct mmc_queue_req *mqrq = mq->mqrq_cur;
1647 	bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN;
1648 	unsigned int req_sectors = 0, phys_segments = 0;
1649 	unsigned int max_blk_count, max_phys_segs;
1650 	bool put_back = true;
1651 	u8 max_packed_rw = 0;
1652 	u8 reqs = 0;
1653 
1654 	if (!(md->flags & MMC_BLK_PACKED_CMD))
1655 		goto no_packed;
1656 
1657 	if ((rq_data_dir(cur) == WRITE) &&
1658 	    mmc_host_packed_wr(card->host))
1659 		max_packed_rw = card->ext_csd.max_packed_writes;
1660 
1661 	if (max_packed_rw == 0)
1662 		goto no_packed;
1663 
1664 	if (mmc_req_rel_wr(cur) &&
1665 	    (md->flags & MMC_BLK_REL_WR) && !en_rel_wr)
1666 		goto no_packed;
1667 
1668 	if (mmc_large_sector(card) &&
1669 	    !IS_ALIGNED(blk_rq_sectors(cur), 8))
1670 		goto no_packed;
1671 
1672 	mmc_blk_clear_packed(mqrq);
1673 
1674 	max_blk_count = min(card->host->max_blk_count,
1675 			    card->host->max_req_size >> 9);
1676 	if (unlikely(max_blk_count > 0xffff))
1677 		max_blk_count = 0xffff;
1678 
1679 	max_phys_segs = queue_max_segments(q);
1680 	req_sectors += blk_rq_sectors(cur);
1681 	phys_segments += cur->nr_phys_segments;
1682 
1683 	if (rq_data_dir(cur) == WRITE) {
1684 		req_sectors += mmc_large_sector(card) ? 8 : 1;
1685 		phys_segments += mmc_calc_packed_hdr_segs(q, card);
1686 	}
1687 
1688 	do {
1689 		if (reqs >= max_packed_rw - 1) {
1690 			put_back = false;
1691 			break;
1692 		}
1693 
1694 		spin_lock_irq(q->queue_lock);
1695 		next = blk_fetch_request(q);
1696 		spin_unlock_irq(q->queue_lock);
1697 		if (!next) {
1698 			put_back = false;
1699 			break;
1700 		}
1701 
1702 		if (mmc_large_sector(card) &&
1703 		    !IS_ALIGNED(blk_rq_sectors(next), 8))
1704 			break;
1705 
1706 		if (next->cmd_flags & REQ_DISCARD ||
1707 		    next->cmd_flags & REQ_FLUSH)
1708 			break;
1709 
1710 		if (rq_data_dir(cur) != rq_data_dir(next))
1711 			break;
1712 
1713 		if (mmc_req_rel_wr(next) &&
1714 		    (md->flags & MMC_BLK_REL_WR) && !en_rel_wr)
1715 			break;
1716 
1717 		req_sectors += blk_rq_sectors(next);
1718 		if (req_sectors > max_blk_count)
1719 			break;
1720 
1721 		phys_segments +=  next->nr_phys_segments;
1722 		if (phys_segments > max_phys_segs)
1723 			break;
1724 
1725 		list_add_tail(&next->queuelist, &mqrq->packed->list);
1726 		cur = next;
1727 		reqs++;
1728 	} while (1);
1729 
1730 	if (put_back) {
1731 		spin_lock_irq(q->queue_lock);
1732 		blk_requeue_request(q, next);
1733 		spin_unlock_irq(q->queue_lock);
1734 	}
1735 
1736 	if (reqs > 0) {
1737 		list_add(&req->queuelist, &mqrq->packed->list);
1738 		mqrq->packed->nr_entries = ++reqs;
1739 		mqrq->packed->retries = reqs;
1740 		return reqs;
1741 	}
1742 
1743 no_packed:
1744 	mqrq->cmd_type = MMC_PACKED_NONE;
1745 	return 0;
1746 }
1747 
mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req * mqrq,struct mmc_card * card,struct mmc_queue * mq)1748 static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq,
1749 					struct mmc_card *card,
1750 					struct mmc_queue *mq)
1751 {
1752 	struct mmc_blk_request *brq = &mqrq->brq;
1753 	struct request *req = mqrq->req;
1754 	struct request *prq;
1755 	struct mmc_blk_data *md = mq->data;
1756 	struct mmc_packed *packed = mqrq->packed;
1757 	bool do_rel_wr, do_data_tag;
1758 	u32 *packed_cmd_hdr;
1759 	u8 hdr_blocks;
1760 	u8 i = 1;
1761 
1762 	BUG_ON(!packed);
1763 
1764 	mqrq->cmd_type = MMC_PACKED_WRITE;
1765 	packed->blocks = 0;
1766 	packed->idx_failure = MMC_PACKED_NR_IDX;
1767 
1768 	packed_cmd_hdr = packed->cmd_hdr;
1769 	memset(packed_cmd_hdr, 0, sizeof(packed->cmd_hdr));
1770 	packed_cmd_hdr[0] = (packed->nr_entries << 16) |
1771 		(PACKED_CMD_WR << 8) | PACKED_CMD_VER;
1772 	hdr_blocks = mmc_large_sector(card) ? 8 : 1;
1773 
1774 	/*
1775 	 * Argument for each entry of packed group
1776 	 */
1777 	list_for_each_entry(prq, &packed->list, queuelist) {
1778 		do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR);
1779 		do_data_tag = (card->ext_csd.data_tag_unit_size) &&
1780 			(prq->cmd_flags & REQ_META) &&
1781 			(rq_data_dir(prq) == WRITE) &&
1782 			((brq->data.blocks * brq->data.blksz) >=
1783 			 card->ext_csd.data_tag_unit_size);
1784 		/* Argument of CMD23 */
1785 		packed_cmd_hdr[(i * 2)] =
1786 			(do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) |
1787 			(do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) |
1788 			blk_rq_sectors(prq);
1789 		/* Argument of CMD18 or CMD25 */
1790 		packed_cmd_hdr[((i * 2)) + 1] =
1791 			mmc_card_blockaddr(card) ?
1792 			blk_rq_pos(prq) : blk_rq_pos(prq) << 9;
1793 		packed->blocks += blk_rq_sectors(prq);
1794 		i++;
1795 	}
1796 
1797 	memset(brq, 0, sizeof(struct mmc_blk_request));
1798 	brq->mrq.cmd = &brq->cmd;
1799 	brq->mrq.data = &brq->data;
1800 	brq->mrq.sbc = &brq->sbc;
1801 	brq->mrq.stop = &brq->stop;
1802 
1803 	brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1804 	brq->sbc.arg = MMC_CMD23_ARG_PACKED | (packed->blocks + hdr_blocks);
1805 	brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1806 
1807 	brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
1808 	brq->cmd.arg = blk_rq_pos(req);
1809 	if (!mmc_card_blockaddr(card))
1810 		brq->cmd.arg <<= 9;
1811 	brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1812 
1813 	brq->data.blksz = 512;
1814 	brq->data.blocks = packed->blocks + hdr_blocks;
1815 	brq->data.flags |= MMC_DATA_WRITE;
1816 
1817 	brq->stop.opcode = MMC_STOP_TRANSMISSION;
1818 	brq->stop.arg = 0;
1819 	brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1820 
1821 	mmc_set_data_timeout(&brq->data, card);
1822 
1823 	brq->data.sg = mqrq->sg;
1824 	brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1825 
1826 	mqrq->mmc_active.mrq = &brq->mrq;
1827 	mqrq->mmc_active.err_check = mmc_blk_packed_err_check;
1828 
1829 	mmc_queue_bounce_pre(mqrq);
1830 }
1831 
mmc_blk_cmd_err(struct mmc_blk_data * md,struct mmc_card * card,struct mmc_blk_request * brq,struct request * req,int ret)1832 static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
1833 			   struct mmc_blk_request *brq, struct request *req,
1834 			   int ret)
1835 {
1836 	struct mmc_queue_req *mq_rq;
1837 	mq_rq = container_of(brq, struct mmc_queue_req, brq);
1838 
1839 	/*
1840 	 * If this is an SD card and we're writing, we can first
1841 	 * mark the known good sectors as ok.
1842 	 *
1843 	 * If the card is not SD, we can still ok written sectors
1844 	 * as reported by the controller (which might be less than
1845 	 * the real number of written sectors, but never more).
1846 	 */
1847 	if (mmc_card_sd(card)) {
1848 		u32 blocks;
1849 
1850 		blocks = mmc_sd_num_wr_blocks(card);
1851 		if (blocks != (u32)-1) {
1852 			ret = blk_end_request(req, 0, blocks << 9);
1853 		}
1854 	} else {
1855 		if (!mmc_packed_cmd(mq_rq->cmd_type))
1856 			ret = blk_end_request(req, 0, brq->data.bytes_xfered);
1857 	}
1858 	return ret;
1859 }
1860 
mmc_blk_end_packed_req(struct mmc_queue_req * mq_rq)1861 static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq)
1862 {
1863 	struct request *prq;
1864 	struct mmc_packed *packed = mq_rq->packed;
1865 	int idx = packed->idx_failure, i = 0;
1866 	int ret = 0;
1867 
1868 	BUG_ON(!packed);
1869 
1870 	while (!list_empty(&packed->list)) {
1871 		prq = list_entry_rq(packed->list.next);
1872 		if (idx == i) {
1873 			/* retry from error index */
1874 			packed->nr_entries -= idx;
1875 			mq_rq->req = prq;
1876 			ret = 1;
1877 
1878 			if (packed->nr_entries == MMC_PACKED_NR_SINGLE) {
1879 				list_del_init(&prq->queuelist);
1880 				mmc_blk_clear_packed(mq_rq);
1881 			}
1882 			return ret;
1883 		}
1884 		list_del_init(&prq->queuelist);
1885 		blk_end_request(prq, 0, blk_rq_bytes(prq));
1886 		i++;
1887 	}
1888 
1889 	mmc_blk_clear_packed(mq_rq);
1890 	return ret;
1891 }
1892 
mmc_blk_abort_packed_req(struct mmc_queue_req * mq_rq)1893 static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq)
1894 {
1895 	struct request *prq;
1896 	struct mmc_packed *packed = mq_rq->packed;
1897 
1898 	BUG_ON(!packed);
1899 
1900 	while (!list_empty(&packed->list)) {
1901 		prq = list_entry_rq(packed->list.next);
1902 		list_del_init(&prq->queuelist);
1903 		blk_end_request(prq, -EIO, blk_rq_bytes(prq));
1904 	}
1905 
1906 	mmc_blk_clear_packed(mq_rq);
1907 }
1908 
mmc_blk_revert_packed_req(struct mmc_queue * mq,struct mmc_queue_req * mq_rq)1909 static void mmc_blk_revert_packed_req(struct mmc_queue *mq,
1910 				      struct mmc_queue_req *mq_rq)
1911 {
1912 	struct request *prq;
1913 	struct request_queue *q = mq->queue;
1914 	struct mmc_packed *packed = mq_rq->packed;
1915 
1916 	BUG_ON(!packed);
1917 
1918 	while (!list_empty(&packed->list)) {
1919 		prq = list_entry_rq(packed->list.prev);
1920 		if (prq->queuelist.prev != &packed->list) {
1921 			list_del_init(&prq->queuelist);
1922 			spin_lock_irq(q->queue_lock);
1923 			blk_requeue_request(mq->queue, prq);
1924 			spin_unlock_irq(q->queue_lock);
1925 		} else {
1926 			list_del_init(&prq->queuelist);
1927 		}
1928 	}
1929 
1930 	mmc_blk_clear_packed(mq_rq);
1931 }
1932 
mmc_blk_issue_rw_rq(struct mmc_queue * mq,struct request * rqc)1933 static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
1934 {
1935 	struct mmc_blk_data *md = mq->data;
1936 	struct mmc_card *card = md->queue.card;
1937 	struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
1938 	int ret = 1, disable_multi = 0, retry = 0, type, retune_retry_done = 0;
1939 	enum mmc_blk_status status;
1940 	struct mmc_queue_req *mq_rq;
1941 	struct request *req = rqc;
1942 	struct mmc_async_req *areq;
1943 	const u8 packed_nr = 2;
1944 	u8 reqs = 0;
1945 
1946 	if (!rqc && !mq->mqrq_prev->req)
1947 		return 0;
1948 
1949 	if (rqc)
1950 		reqs = mmc_blk_prep_packed_list(mq, rqc);
1951 
1952 	do {
1953 		if (rqc) {
1954 			/*
1955 			 * When 4KB native sector is enabled, only 8 blocks
1956 			 * multiple read or write is allowed
1957 			 */
1958 			if ((brq->data.blocks & 0x07) &&
1959 			    (card->ext_csd.data_sector_size == 4096)) {
1960 				pr_err("%s: Transfer size is not 4KB sector size aligned\n",
1961 					req->rq_disk->disk_name);
1962 				mq_rq = mq->mqrq_cur;
1963 				goto cmd_abort;
1964 			}
1965 
1966 			if (reqs >= packed_nr)
1967 				mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur,
1968 							    card, mq);
1969 			else
1970 				mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
1971 			areq = &mq->mqrq_cur->mmc_active;
1972 		} else
1973 			areq = NULL;
1974 		areq = mmc_start_req(card->host, areq, (int *) &status);
1975 		if (!areq) {
1976 			if (status == MMC_BLK_NEW_REQUEST)
1977 				mq->flags |= MMC_QUEUE_NEW_REQUEST;
1978 			return 0;
1979 		}
1980 
1981 		mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
1982 		brq = &mq_rq->brq;
1983 		req = mq_rq->req;
1984 		type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1985 		mmc_queue_bounce_post(mq_rq);
1986 
1987 		switch (status) {
1988 		case MMC_BLK_SUCCESS:
1989 		case MMC_BLK_PARTIAL:
1990 			/*
1991 			 * A block was successfully transferred.
1992 			 */
1993 			mmc_blk_reset_success(md, type);
1994 
1995 			if (mmc_packed_cmd(mq_rq->cmd_type)) {
1996 				ret = mmc_blk_end_packed_req(mq_rq);
1997 				break;
1998 			} else {
1999 				ret = blk_end_request(req, 0,
2000 						brq->data.bytes_xfered);
2001 			}
2002 
2003 			/*
2004 			 * If the blk_end_request function returns non-zero even
2005 			 * though all data has been transferred and no errors
2006 			 * were returned by the host controller, it's a bug.
2007 			 */
2008 			if (status == MMC_BLK_SUCCESS && ret) {
2009 				pr_err("%s BUG rq_tot %d d_xfer %d\n",
2010 				       __func__, blk_rq_bytes(req),
2011 				       brq->data.bytes_xfered);
2012 				rqc = NULL;
2013 				goto cmd_abort;
2014 			}
2015 			break;
2016 		case MMC_BLK_CMD_ERR:
2017 			ret = mmc_blk_cmd_err(md, card, brq, req, ret);
2018 			if (mmc_blk_reset(md, card->host, type))
2019 				goto cmd_abort;
2020 			if (!ret)
2021 				goto start_new_req;
2022 			break;
2023 		case MMC_BLK_RETRY:
2024 			retune_retry_done = brq->retune_retry_done;
2025 			if (retry++ < 5)
2026 				break;
2027 			/* Fall through */
2028 		case MMC_BLK_ABORT:
2029 			if (!mmc_blk_reset(md, card->host, type))
2030 				break;
2031 			goto cmd_abort;
2032 		case MMC_BLK_DATA_ERR: {
2033 			int err;
2034 
2035 			err = mmc_blk_reset(md, card->host, type);
2036 			if (!err)
2037 				break;
2038 			if (err == -ENODEV ||
2039 				mmc_packed_cmd(mq_rq->cmd_type))
2040 				goto cmd_abort;
2041 			/* Fall through */
2042 		}
2043 		case MMC_BLK_ECC_ERR:
2044 			if (brq->data.blocks > 1) {
2045 				/* Redo read one sector at a time */
2046 				pr_warn("%s: retrying using single block read\n",
2047 					req->rq_disk->disk_name);
2048 				disable_multi = 1;
2049 				break;
2050 			}
2051 			/*
2052 			 * After an error, we redo I/O one sector at a
2053 			 * time, so we only reach here after trying to
2054 			 * read a single sector.
2055 			 */
2056 			ret = blk_end_request(req, -EIO,
2057 						brq->data.blksz);
2058 			if (!ret)
2059 				goto start_new_req;
2060 			break;
2061 		case MMC_BLK_NOMEDIUM:
2062 			goto cmd_abort;
2063 		default:
2064 			pr_err("%s: Unhandled return value (%d)",
2065 					req->rq_disk->disk_name, status);
2066 			goto cmd_abort;
2067 		}
2068 
2069 		if (ret) {
2070 			if (mmc_packed_cmd(mq_rq->cmd_type)) {
2071 				if (!mq_rq->packed->retries)
2072 					goto cmd_abort;
2073 				mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq);
2074 				mmc_start_req(card->host,
2075 					      &mq_rq->mmc_active, NULL);
2076 			} else {
2077 
2078 				/*
2079 				 * In case of a incomplete request
2080 				 * prepare it again and resend.
2081 				 */
2082 				mmc_blk_rw_rq_prep(mq_rq, card,
2083 						disable_multi, mq);
2084 				mmc_start_req(card->host,
2085 						&mq_rq->mmc_active, NULL);
2086 			}
2087 			mq_rq->brq.retune_retry_done = retune_retry_done;
2088 		}
2089 	} while (ret);
2090 
2091 	return 1;
2092 
2093  cmd_abort:
2094 	if (mmc_packed_cmd(mq_rq->cmd_type)) {
2095 		mmc_blk_abort_packed_req(mq_rq);
2096 	} else {
2097 		if (mmc_card_removed(card))
2098 			req->cmd_flags |= REQ_QUIET;
2099 		while (ret)
2100 			ret = blk_end_request(req, -EIO,
2101 					blk_rq_cur_bytes(req));
2102 	}
2103 
2104  start_new_req:
2105 	if (rqc) {
2106 		if (mmc_card_removed(card)) {
2107 			rqc->cmd_flags |= REQ_QUIET;
2108 			blk_end_request_all(rqc, -EIO);
2109 		} else {
2110 			/*
2111 			 * If current request is packed, it needs to put back.
2112 			 */
2113 			if (mmc_packed_cmd(mq->mqrq_cur->cmd_type))
2114 				mmc_blk_revert_packed_req(mq, mq->mqrq_cur);
2115 
2116 			mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
2117 			mmc_start_req(card->host,
2118 				      &mq->mqrq_cur->mmc_active, NULL);
2119 		}
2120 	}
2121 
2122 	return 0;
2123 }
2124 
mmc_blk_issue_rq(struct mmc_queue * mq,struct request * req)2125 static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
2126 {
2127 	int ret;
2128 	struct mmc_blk_data *md = mq->data;
2129 	struct mmc_card *card = md->queue.card;
2130 	struct mmc_host *host = card->host;
2131 	unsigned long flags;
2132 	unsigned int cmd_flags = req ? req->cmd_flags : 0;
2133 
2134 	if (req && !mq->mqrq_prev->req)
2135 		/* claim host only for the first request */
2136 		mmc_get_card(card);
2137 
2138 	ret = mmc_blk_part_switch(card, md);
2139 	if (ret) {
2140 		if (req) {
2141 			blk_end_request_all(req, -EIO);
2142 		}
2143 		ret = 0;
2144 		goto out;
2145 	}
2146 
2147 	mq->flags &= ~MMC_QUEUE_NEW_REQUEST;
2148 	if (cmd_flags & REQ_DISCARD) {
2149 		/* complete ongoing async transfer before issuing discard */
2150 		if (card->host->areq)
2151 			mmc_blk_issue_rw_rq(mq, NULL);
2152 		if (req->cmd_flags & REQ_SECURE)
2153 			ret = mmc_blk_issue_secdiscard_rq(mq, req);
2154 		else
2155 			ret = mmc_blk_issue_discard_rq(mq, req);
2156 	} else if (cmd_flags & REQ_FLUSH) {
2157 		/* complete ongoing async transfer before issuing flush */
2158 		if (card->host->areq)
2159 			mmc_blk_issue_rw_rq(mq, NULL);
2160 		ret = mmc_blk_issue_flush(mq, req);
2161 	} else {
2162 		if (!req && host->areq) {
2163 			spin_lock_irqsave(&host->context_info.lock, flags);
2164 			host->context_info.is_waiting_last_req = true;
2165 			spin_unlock_irqrestore(&host->context_info.lock, flags);
2166 		}
2167 		ret = mmc_blk_issue_rw_rq(mq, req);
2168 	}
2169 
2170 out:
2171 	if ((!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) ||
2172 	     (cmd_flags & MMC_REQ_SPECIAL_MASK))
2173 		/*
2174 		 * Release host when there are no more requests
2175 		 * and after special request(discard, flush) is done.
2176 		 * In case sepecial request, there is no reentry to
2177 		 * the 'mmc_blk_issue_rq' with 'mqrq_prev->req'.
2178 		 */
2179 		mmc_put_card(card);
2180 	return ret;
2181 }
2182 
mmc_blk_readonly(struct mmc_card * card)2183 static inline int mmc_blk_readonly(struct mmc_card *card)
2184 {
2185 	return mmc_card_readonly(card) ||
2186 	       !(card->csd.cmdclass & CCC_BLOCK_WRITE);
2187 }
2188 
mmc_blk_alloc_req(struct mmc_card * card,struct device * parent,sector_t size,bool default_ro,const char * subname,int area_type)2189 static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
2190 					      struct device *parent,
2191 					      sector_t size,
2192 					      bool default_ro,
2193 					      const char *subname,
2194 					      int area_type)
2195 {
2196 	struct mmc_blk_data *md;
2197 	int devidx, ret;
2198 
2199 	devidx = find_first_zero_bit(dev_use, max_devices);
2200 	if (devidx >= max_devices)
2201 		return ERR_PTR(-ENOSPC);
2202 	__set_bit(devidx, dev_use);
2203 
2204 	md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
2205 	if (!md) {
2206 		ret = -ENOMEM;
2207 		goto out;
2208 	}
2209 
2210 	/*
2211 	 * !subname implies we are creating main mmc_blk_data that will be
2212 	 * associated with mmc_card with dev_set_drvdata. Due to device
2213 	 * partitions, devidx will not coincide with a per-physical card
2214 	 * index anymore so we keep track of a name index.
2215 	 */
2216 	if (!subname) {
2217 		md->name_idx = find_first_zero_bit(name_use, max_devices);
2218 		__set_bit(md->name_idx, name_use);
2219 	} else
2220 		md->name_idx = ((struct mmc_blk_data *)
2221 				dev_to_disk(parent)->private_data)->name_idx;
2222 
2223 	md->area_type = area_type;
2224 
2225 	/*
2226 	 * Set the read-only status based on the supported commands
2227 	 * and the write protect switch.
2228 	 */
2229 	md->read_only = mmc_blk_readonly(card);
2230 
2231 	md->disk = alloc_disk(perdev_minors);
2232 	if (md->disk == NULL) {
2233 		ret = -ENOMEM;
2234 		goto err_kfree;
2235 	}
2236 
2237 	spin_lock_init(&md->lock);
2238 	INIT_LIST_HEAD(&md->part);
2239 	md->usage = 1;
2240 
2241 	ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
2242 	if (ret)
2243 		goto err_putdisk;
2244 
2245 	md->queue.issue_fn = mmc_blk_issue_rq;
2246 	md->queue.data = md;
2247 
2248 	md->disk->major	= MMC_BLOCK_MAJOR;
2249 	md->disk->first_minor = devidx * perdev_minors;
2250 	md->disk->fops = &mmc_bdops;
2251 	md->disk->private_data = md;
2252 	md->disk->queue = md->queue.queue;
2253 	md->disk->driverfs_dev = parent;
2254 	set_disk_ro(md->disk, md->read_only || default_ro);
2255 	if (area_type & (MMC_BLK_DATA_AREA_RPMB | MMC_BLK_DATA_AREA_BOOT))
2256 		md->disk->flags |= GENHD_FL_NO_PART_SCAN;
2257 
2258 	/*
2259 	 * As discussed on lkml, GENHD_FL_REMOVABLE should:
2260 	 *
2261 	 * - be set for removable media with permanent block devices
2262 	 * - be unset for removable block devices with permanent media
2263 	 *
2264 	 * Since MMC block devices clearly fall under the second
2265 	 * case, we do not set GENHD_FL_REMOVABLE.  Userspace
2266 	 * should use the block device creation/destruction hotplug
2267 	 * messages to tell when the card is present.
2268 	 */
2269 
2270 	snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
2271 		 "mmcblk%u%s", md->name_idx, subname ? subname : "");
2272 
2273 	if (mmc_card_mmc(card))
2274 		blk_queue_logical_block_size(md->queue.queue,
2275 					     card->ext_csd.data_sector_size);
2276 	else
2277 		blk_queue_logical_block_size(md->queue.queue, 512);
2278 
2279 	set_capacity(md->disk, size);
2280 
2281 	if (mmc_host_cmd23(card->host)) {
2282 		if (mmc_card_mmc(card) ||
2283 		    (mmc_card_sd(card) &&
2284 		     card->scr.cmds & SD_SCR_CMD23_SUPPORT))
2285 			md->flags |= MMC_BLK_CMD23;
2286 	}
2287 
2288 	if (mmc_card_mmc(card) &&
2289 	    md->flags & MMC_BLK_CMD23 &&
2290 	    ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
2291 	     card->ext_csd.rel_sectors)) {
2292 		md->flags |= MMC_BLK_REL_WR;
2293 		blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
2294 	}
2295 
2296 	if (mmc_card_mmc(card) &&
2297 	    (area_type == MMC_BLK_DATA_AREA_MAIN) &&
2298 	    (md->flags & MMC_BLK_CMD23) &&
2299 	    card->ext_csd.packed_event_en) {
2300 		if (!mmc_packed_init(&md->queue, card))
2301 			md->flags |= MMC_BLK_PACKED_CMD;
2302 	}
2303 
2304 	return md;
2305 
2306  err_putdisk:
2307 	put_disk(md->disk);
2308  err_kfree:
2309 	kfree(md);
2310  out:
2311 	return ERR_PTR(ret);
2312 }
2313 
mmc_blk_alloc(struct mmc_card * card)2314 static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
2315 {
2316 	sector_t size;
2317 
2318 	if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
2319 		/*
2320 		 * The EXT_CSD sector count is in number or 512 byte
2321 		 * sectors.
2322 		 */
2323 		size = card->ext_csd.sectors;
2324 	} else {
2325 		/*
2326 		 * The CSD capacity field is in units of read_blkbits.
2327 		 * set_capacity takes units of 512 bytes.
2328 		 */
2329 		size = (typeof(sector_t))card->csd.capacity
2330 			<< (card->csd.read_blkbits - 9);
2331 	}
2332 
2333 	return mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
2334 					MMC_BLK_DATA_AREA_MAIN);
2335 }
2336 
mmc_blk_alloc_part(struct mmc_card * card,struct mmc_blk_data * md,unsigned int part_type,sector_t size,bool default_ro,const char * subname,int area_type)2337 static int mmc_blk_alloc_part(struct mmc_card *card,
2338 			      struct mmc_blk_data *md,
2339 			      unsigned int part_type,
2340 			      sector_t size,
2341 			      bool default_ro,
2342 			      const char *subname,
2343 			      int area_type)
2344 {
2345 	char cap_str[10];
2346 	struct mmc_blk_data *part_md;
2347 
2348 	part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
2349 				    subname, area_type);
2350 	if (IS_ERR(part_md))
2351 		return PTR_ERR(part_md);
2352 	part_md->part_type = part_type;
2353 	list_add(&part_md->part, &md->part);
2354 
2355 	string_get_size((u64)get_capacity(part_md->disk), 512, STRING_UNITS_2,
2356 			cap_str, sizeof(cap_str));
2357 	pr_info("%s: %s %s partition %u %s\n",
2358 	       part_md->disk->disk_name, mmc_card_id(card),
2359 	       mmc_card_name(card), part_md->part_type, cap_str);
2360 	return 0;
2361 }
2362 
2363 /* MMC Physical partitions consist of two boot partitions and
2364  * up to four general purpose partitions.
2365  * For each partition enabled in EXT_CSD a block device will be allocatedi
2366  * to provide access to the partition.
2367  */
2368 
mmc_blk_alloc_parts(struct mmc_card * card,struct mmc_blk_data * md)2369 static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
2370 {
2371 	int idx, ret = 0;
2372 
2373 	if (!mmc_card_mmc(card))
2374 		return 0;
2375 
2376 	for (idx = 0; idx < card->nr_parts; idx++) {
2377 		if (card->part[idx].size) {
2378 			ret = mmc_blk_alloc_part(card, md,
2379 				card->part[idx].part_cfg,
2380 				card->part[idx].size >> 9,
2381 				card->part[idx].force_ro,
2382 				card->part[idx].name,
2383 				card->part[idx].area_type);
2384 			if (ret)
2385 				return ret;
2386 		}
2387 	}
2388 
2389 	return ret;
2390 }
2391 
mmc_blk_remove_req(struct mmc_blk_data * md)2392 static void mmc_blk_remove_req(struct mmc_blk_data *md)
2393 {
2394 	struct mmc_card *card;
2395 
2396 	if (md) {
2397 		/*
2398 		 * Flush remaining requests and free queues. It
2399 		 * is freeing the queue that stops new requests
2400 		 * from being accepted.
2401 		 */
2402 		card = md->queue.card;
2403 		mmc_cleanup_queue(&md->queue);
2404 		if (md->flags & MMC_BLK_PACKED_CMD)
2405 			mmc_packed_clean(&md->queue);
2406 		if (md->disk->flags & GENHD_FL_UP) {
2407 			device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2408 			if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2409 					card->ext_csd.boot_ro_lockable)
2410 				device_remove_file(disk_to_dev(md->disk),
2411 					&md->power_ro_lock);
2412 
2413 			del_gendisk(md->disk);
2414 		}
2415 		mmc_blk_put(md);
2416 	}
2417 }
2418 
mmc_blk_remove_parts(struct mmc_card * card,struct mmc_blk_data * md)2419 static void mmc_blk_remove_parts(struct mmc_card *card,
2420 				 struct mmc_blk_data *md)
2421 {
2422 	struct list_head *pos, *q;
2423 	struct mmc_blk_data *part_md;
2424 
2425 	__clear_bit(md->name_idx, name_use);
2426 	list_for_each_safe(pos, q, &md->part) {
2427 		part_md = list_entry(pos, struct mmc_blk_data, part);
2428 		list_del(pos);
2429 		mmc_blk_remove_req(part_md);
2430 	}
2431 }
2432 
mmc_add_disk(struct mmc_blk_data * md)2433 static int mmc_add_disk(struct mmc_blk_data *md)
2434 {
2435 	int ret;
2436 	struct mmc_card *card = md->queue.card;
2437 
2438 	add_disk(md->disk);
2439 	md->force_ro.show = force_ro_show;
2440 	md->force_ro.store = force_ro_store;
2441 	sysfs_attr_init(&md->force_ro.attr);
2442 	md->force_ro.attr.name = "force_ro";
2443 	md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
2444 	ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
2445 	if (ret)
2446 		goto force_ro_fail;
2447 
2448 	if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2449 	     card->ext_csd.boot_ro_lockable) {
2450 		umode_t mode;
2451 
2452 		if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS)
2453 			mode = S_IRUGO;
2454 		else
2455 			mode = S_IRUGO | S_IWUSR;
2456 
2457 		md->power_ro_lock.show = power_ro_lock_show;
2458 		md->power_ro_lock.store = power_ro_lock_store;
2459 		sysfs_attr_init(&md->power_ro_lock.attr);
2460 		md->power_ro_lock.attr.mode = mode;
2461 		md->power_ro_lock.attr.name =
2462 					"ro_lock_until_next_power_on";
2463 		ret = device_create_file(disk_to_dev(md->disk),
2464 				&md->power_ro_lock);
2465 		if (ret)
2466 			goto power_ro_lock_fail;
2467 	}
2468 	return ret;
2469 
2470 power_ro_lock_fail:
2471 	device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2472 force_ro_fail:
2473 	del_gendisk(md->disk);
2474 
2475 	return ret;
2476 }
2477 
2478 #define CID_MANFID_SANDISK	0x2
2479 #define CID_MANFID_TOSHIBA	0x11
2480 #define CID_MANFID_MICRON	0x13
2481 #define CID_MANFID_SAMSUNG	0x15
2482 #define CID_MANFID_KINGSTON	0x70
2483 
2484 static const struct mmc_fixup blk_fixups[] =
2485 {
2486 	MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk,
2487 		  MMC_QUIRK_INAND_CMD38),
2488 	MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk,
2489 		  MMC_QUIRK_INAND_CMD38),
2490 	MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk,
2491 		  MMC_QUIRK_INAND_CMD38),
2492 	MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk,
2493 		  MMC_QUIRK_INAND_CMD38),
2494 	MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk,
2495 		  MMC_QUIRK_INAND_CMD38),
2496 
2497 	/*
2498 	 * Some MMC cards experience performance degradation with CMD23
2499 	 * instead of CMD12-bounded multiblock transfers. For now we'll
2500 	 * black list what's bad...
2501 	 * - Certain Toshiba cards.
2502 	 *
2503 	 * N.B. This doesn't affect SD cards.
2504 	 */
2505 	MMC_FIXUP("SDMB-32", CID_MANFID_SANDISK, CID_OEMID_ANY, add_quirk_mmc,
2506 		  MMC_QUIRK_BLK_NO_CMD23),
2507 	MMC_FIXUP("SDM032", CID_MANFID_SANDISK, CID_OEMID_ANY, add_quirk_mmc,
2508 		  MMC_QUIRK_BLK_NO_CMD23),
2509 	MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2510 		  MMC_QUIRK_BLK_NO_CMD23),
2511 	MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2512 		  MMC_QUIRK_BLK_NO_CMD23),
2513 	MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2514 		  MMC_QUIRK_BLK_NO_CMD23),
2515 
2516 	/*
2517 	 * Some MMC cards need longer data read timeout than indicated in CSD.
2518 	 */
2519 	MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc,
2520 		  MMC_QUIRK_LONG_READ_TIME),
2521 	MMC_FIXUP("008GE0", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
2522 		  MMC_QUIRK_LONG_READ_TIME),
2523 
2524 	/*
2525 	 * On these Samsung MoviNAND parts, performing secure erase or
2526 	 * secure trim can result in unrecoverable corruption due to a
2527 	 * firmware bug.
2528 	 */
2529 	MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2530 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2531 	MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2532 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2533 	MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2534 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2535 	MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2536 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2537 	MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2538 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2539 	MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2540 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2541 	MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2542 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2543 	MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
2544 		  MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
2545 
2546 	/*
2547 	 *  On Some Kingston eMMCs, performing trim can result in
2548 	 *  unrecoverable data conrruption occasionally due to a firmware bug.
2549 	 */
2550 	MMC_FIXUP("V10008", CID_MANFID_KINGSTON, CID_OEMID_ANY, add_quirk_mmc,
2551 		  MMC_QUIRK_TRIM_BROKEN),
2552 	MMC_FIXUP("V10016", CID_MANFID_KINGSTON, CID_OEMID_ANY, add_quirk_mmc,
2553 		  MMC_QUIRK_TRIM_BROKEN),
2554 
2555 	END_FIXUP
2556 };
2557 
mmc_blk_probe(struct mmc_card * card)2558 static int mmc_blk_probe(struct mmc_card *card)
2559 {
2560 	struct mmc_blk_data *md, *part_md;
2561 	char cap_str[10];
2562 
2563 	/*
2564 	 * Check that the card supports the command class(es) we need.
2565 	 */
2566 	if (!(card->csd.cmdclass & CCC_BLOCK_READ))
2567 		return -ENODEV;
2568 
2569 	mmc_fixup_device(card, blk_fixups);
2570 
2571 	md = mmc_blk_alloc(card);
2572 	if (IS_ERR(md))
2573 		return PTR_ERR(md);
2574 
2575 	string_get_size((u64)get_capacity(md->disk), 512, STRING_UNITS_2,
2576 			cap_str, sizeof(cap_str));
2577 	pr_info("%s: %s %s %s %s\n",
2578 		md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
2579 		cap_str, md->read_only ? "(ro)" : "");
2580 
2581 	if (mmc_blk_alloc_parts(card, md))
2582 		goto out;
2583 
2584 	dev_set_drvdata(&card->dev, md);
2585 
2586 	if (mmc_add_disk(md))
2587 		goto out;
2588 
2589 	list_for_each_entry(part_md, &md->part, part) {
2590 		if (mmc_add_disk(part_md))
2591 			goto out;
2592 	}
2593 
2594 	pm_runtime_set_autosuspend_delay(&card->dev, 3000);
2595 	pm_runtime_use_autosuspend(&card->dev);
2596 
2597 	/*
2598 	 * Don't enable runtime PM for SD-combo cards here. Leave that
2599 	 * decision to be taken during the SDIO init sequence instead.
2600 	 */
2601 	if (card->type != MMC_TYPE_SD_COMBO) {
2602 		pm_runtime_set_active(&card->dev);
2603 		pm_runtime_enable(&card->dev);
2604 	}
2605 
2606 	return 0;
2607 
2608  out:
2609 	mmc_blk_remove_parts(card, md);
2610 	mmc_blk_remove_req(md);
2611 	return 0;
2612 }
2613 
mmc_blk_remove(struct mmc_card * card)2614 static void mmc_blk_remove(struct mmc_card *card)
2615 {
2616 	struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2617 
2618 	mmc_blk_remove_parts(card, md);
2619 	pm_runtime_get_sync(&card->dev);
2620 	mmc_claim_host(card->host);
2621 	mmc_blk_part_switch(card, md);
2622 	mmc_release_host(card->host);
2623 	if (card->type != MMC_TYPE_SD_COMBO)
2624 		pm_runtime_disable(&card->dev);
2625 	pm_runtime_put_noidle(&card->dev);
2626 	mmc_blk_remove_req(md);
2627 	dev_set_drvdata(&card->dev, NULL);
2628 }
2629 
_mmc_blk_suspend(struct mmc_card * card)2630 static int _mmc_blk_suspend(struct mmc_card *card)
2631 {
2632 	struct mmc_blk_data *part_md;
2633 	struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2634 
2635 	if (md) {
2636 		mmc_queue_suspend(&md->queue);
2637 		list_for_each_entry(part_md, &md->part, part) {
2638 			mmc_queue_suspend(&part_md->queue);
2639 		}
2640 	}
2641 	return 0;
2642 }
2643 
mmc_blk_shutdown(struct mmc_card * card)2644 static void mmc_blk_shutdown(struct mmc_card *card)
2645 {
2646 	_mmc_blk_suspend(card);
2647 }
2648 
2649 #ifdef CONFIG_PM_SLEEP
mmc_blk_suspend(struct device * dev)2650 static int mmc_blk_suspend(struct device *dev)
2651 {
2652 	struct mmc_card *card = mmc_dev_to_card(dev);
2653 
2654 	return _mmc_blk_suspend(card);
2655 }
2656 
mmc_blk_resume(struct device * dev)2657 static int mmc_blk_resume(struct device *dev)
2658 {
2659 	struct mmc_blk_data *part_md;
2660 	struct mmc_blk_data *md = dev_get_drvdata(dev);
2661 
2662 	if (md) {
2663 		/*
2664 		 * Resume involves the card going into idle state,
2665 		 * so current partition is always the main one.
2666 		 */
2667 		md->part_curr = md->part_type;
2668 		mmc_queue_resume(&md->queue);
2669 		list_for_each_entry(part_md, &md->part, part) {
2670 			mmc_queue_resume(&part_md->queue);
2671 		}
2672 	}
2673 	return 0;
2674 }
2675 #endif
2676 
2677 static SIMPLE_DEV_PM_OPS(mmc_blk_pm_ops, mmc_blk_suspend, mmc_blk_resume);
2678 
2679 static struct mmc_driver mmc_driver = {
2680 	.drv		= {
2681 		.name	= "mmcblk",
2682 		.pm	= &mmc_blk_pm_ops,
2683 	},
2684 	.probe		= mmc_blk_probe,
2685 	.remove		= mmc_blk_remove,
2686 	.shutdown	= mmc_blk_shutdown,
2687 };
2688 
mmc_blk_init(void)2689 static int __init mmc_blk_init(void)
2690 {
2691 	int res;
2692 
2693 	if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
2694 		pr_info("mmcblk: using %d minors per device\n", perdev_minors);
2695 
2696 	max_devices = min(MAX_DEVICES, (1 << MINORBITS) / perdev_minors);
2697 
2698 	res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
2699 	if (res)
2700 		goto out;
2701 
2702 	res = mmc_register_driver(&mmc_driver);
2703 	if (res)
2704 		goto out2;
2705 
2706 	return 0;
2707  out2:
2708 	unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
2709  out:
2710 	return res;
2711 }
2712 
mmc_blk_exit(void)2713 static void __exit mmc_blk_exit(void)
2714 {
2715 	mmc_unregister_driver(&mmc_driver);
2716 	unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
2717 }
2718 
2719 module_init(mmc_blk_init);
2720 module_exit(mmc_blk_exit);
2721 
2722 MODULE_LICENSE("GPL");
2723 MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
2724 
2725