xref: /rk3399_rockchip-uboot/drivers/usb/gadget/f_rockusb.c (revision 005bd0590c3883bb3cf7a674b032d3614ea6ea2a)
1 /*
2  * Copyright 2017 Rockchip Electronics Co., Ltd
3  * Frank Wang <frank.wang@rock-chips.com>
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 #include <asm/io.h>
9 #include <android_avb/avb_ops_user.h>
10 #include <android_avb/rk_avb_ops_user.h>
11 #include <asm/arch/boot_mode.h>
12 #include <asm/arch/chip_info.h>
13 #include <asm/arch/rk_atags.h>
14 #include <write_keybox.h>
15 #include <linux/mtd/mtd.h>
16 #include <optee_include/OpteeClientInterface.h>
17 #include <mmc.h>
18 #include <stdlib.h>
19 #include <usbplug.h>
20 
21 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
22 #include <asm/arch/vendor.h>
23 #endif
24 #include <rockusb.h>
25 
26 #define ROCKUSB_INTERFACE_CLASS	0xff
27 #define ROCKUSB_INTERFACE_SUB_CLASS	0x06
28 #define ROCKUSB_INTERFACE_PROTOCOL	0x05
29 
30 #define ROCKCHIP_FLASH_BLOCK_SIZE	1024
31 #define ROCKCHIP_FLASH_PAGE_SIZE	4
32 
33 static struct usb_interface_descriptor rkusb_intf_desc = {
34 	.bLength		= USB_DT_INTERFACE_SIZE,
35 	.bDescriptorType	= USB_DT_INTERFACE,
36 	.bInterfaceNumber	= 0x00,
37 	.bAlternateSetting	= 0x00,
38 	.bNumEndpoints		= 0x02,
39 	.bInterfaceClass	= ROCKUSB_INTERFACE_CLASS,
40 	.bInterfaceSubClass	= ROCKUSB_INTERFACE_SUB_CLASS,
41 	.bInterfaceProtocol	= ROCKUSB_INTERFACE_PROTOCOL,
42 };
43 
44 static struct usb_descriptor_header *rkusb_fs_function[] = {
45 	(struct usb_descriptor_header *)&rkusb_intf_desc,
46 	(struct usb_descriptor_header *)&fsg_fs_bulk_in_desc,
47 	(struct usb_descriptor_header *)&fsg_fs_bulk_out_desc,
48 	NULL,
49 };
50 
51 static struct usb_descriptor_header *rkusb_hs_function[] = {
52 	(struct usb_descriptor_header *)&rkusb_intf_desc,
53 	(struct usb_descriptor_header *)&fsg_hs_bulk_in_desc,
54 	(struct usb_descriptor_header *)&fsg_hs_bulk_out_desc,
55 	NULL,
56 };
57 
58 static struct usb_descriptor_header *rkusb_ss_function[] = {
59 	(struct usb_descriptor_header *)&rkusb_intf_desc,
60 	(struct usb_descriptor_header *)&fsg_ss_bulk_in_desc,
61 	(struct usb_descriptor_header *)&fsg_ss_bulk_in_comp_desc,
62 	(struct usb_descriptor_header *)&fsg_ss_bulk_out_desc,
63 	(struct usb_descriptor_header *)&fsg_ss_bulk_out_comp_desc,
64 	NULL,
65 };
66 
67 struct rk_flash_info {
68 	u32	flash_size;
69 	u16	block_size;
70 	u8	page_size;
71 	u8	ecc_bits;
72 	u8	access_time;
73 	u8	manufacturer;
74 	u8	flash_mask;
75 } __packed;
76 
77 static int rkusb_rst_code; /* The subcode in reset command (0xFF) */
78 
79 int g_dnl_bind_fixup(struct usb_device_descriptor *dev, const char *name)
80 {
81 	if (IS_RKUSB_UMS_DNL(name)) {
82 		/* Fix to Rockchip's VID and PID */
83 		dev->idVendor  = __constant_cpu_to_le16(0x2207);
84 		dev->idProduct = __constant_cpu_to_le16(CONFIG_ROCKUSB_G_DNL_PID);
85 
86 		/* Enumerate as a loader device */
87 #if defined(CONFIG_SUPPORT_USBPLUG)
88 		dev->bcdUSB = cpu_to_le16(0x0200);
89 #else
90 		dev->bcdUSB = cpu_to_le16(0x0201);
91 #endif
92 	} else if (!strncmp(name, "usb_dnl_fastboot", 16)) {
93 		/* Fix to Google's VID and PID */
94 		dev->idVendor  = __constant_cpu_to_le16(0x18d1);
95 		dev->idProduct = __constant_cpu_to_le16(0xd00d);
96 	} else if (!strncmp(name, "usb_dnl_dfu", 11)) {
97 		/* Fix to Rockchip's VID and PID for DFU */
98 		dev->idVendor  = cpu_to_le16(0x2207);
99 		dev->idProduct = cpu_to_le16(0x0107);
100 	} else if (!strncmp(name, "usb_dnl_ums", 11)) {
101 		dev->idVendor  = cpu_to_le16(0x2207);
102 		dev->idProduct = cpu_to_le16(0x0010);
103 	}
104 
105 	return 0;
106 }
107 
108 __maybe_unused
109 static inline void dump_cbw(struct fsg_bulk_cb_wrap *cbw)
110 {
111 	assert(!cbw);
112 
113 	debug("%s:\n", __func__);
114 	debug("Signature %x\n", cbw->Signature);
115 	debug("Tag %x\n", cbw->Tag);
116 	debug("DataTransferLength %x\n", cbw->DataTransferLength);
117 	debug("Flags %x\n", cbw->Flags);
118 	debug("LUN %x\n", cbw->Lun);
119 	debug("Length %x\n", cbw->Length);
120 	debug("OptionCode %x\n", cbw->CDB[0]);
121 	debug("SubCode %x\n", cbw->CDB[1]);
122 	debug("SectorAddr %x\n", get_unaligned_be32(&cbw->CDB[2]));
123 	debug("BlkSectors %x\n\n", get_unaligned_be16(&cbw->CDB[7]));
124 }
125 
126 static int rkusb_check_lun(struct fsg_common *common)
127 {
128 	struct fsg_lun *curlun;
129 
130 	/* Check the LUN */
131 	if (common->lun >= 0 && common->lun < common->nluns) {
132 		curlun = &common->luns[common->lun];
133 		if (common->cmnd[0] != SC_REQUEST_SENSE) {
134 			curlun->sense_data = SS_NO_SENSE;
135 			curlun->info_valid = 0;
136 		}
137 	} else {
138 		curlun = NULL;
139 		common->bad_lun_okay = 0;
140 
141 		/*
142 		 * INQUIRY and REQUEST SENSE commands are explicitly allowed
143 		 * to use unsupported LUNs; all others may not.
144 		 */
145 		if (common->cmnd[0] != SC_INQUIRY &&
146 		    common->cmnd[0] != SC_REQUEST_SENSE) {
147 			debug("unsupported LUN %d\n", common->lun);
148 			return -EINVAL;
149 		}
150 	}
151 
152 	return 0;
153 }
154 
155 static void __do_reset(struct usb_ep *ep, struct usb_request *req)
156 {
157 	u32 boot_flag = BOOT_NORMAL;
158 
159 	if (rkusb_rst_code == 0x03)
160 		boot_flag = BOOT_BROM_DOWNLOAD;
161 
162 	rkusb_rst_code = 0; /* restore to default */
163 	writel(boot_flag, (void *)CONFIG_ROCKCHIP_BOOT_MODE_REG);
164 
165 	do_reset(NULL, 0, 0, NULL);
166 }
167 
168 static int rkusb_do_reset(struct fsg_common *common,
169 			  struct fsg_buffhd *bh)
170 {
171 	common->data_size_from_cmnd = common->cmnd[4];
172 	common->residue = 0;
173 	bh->inreq->complete = __do_reset;
174 	bh->state = BUF_STATE_EMPTY;
175 
176 	rkusb_rst_code = !common->cmnd[1] ? 0xff : common->cmnd[1];
177 	return 0;
178 }
179 
180 __weak bool rkusb_usb3_capable(void)
181 {
182 	return false;
183 }
184 
185 static int rkusb_do_switch_to_usb3(struct fsg_common *common,
186 				   struct fsg_buffhd *bh)
187 {
188 	g_dnl_set_serialnumber((char *)&common->cmnd[1]);
189 	rkusb_switch_to_usb3_enable(true);
190 	bh->state = BUF_STATE_EMPTY;
191 
192 	return 0;
193 }
194 
195 static int rkusb_do_test_unit_ready(struct fsg_common *common,
196 				    struct fsg_buffhd *bh)
197 {
198 	struct blk_desc *desc = &ums[common->lun].block_dev;
199 	u32 usb_trb_size;
200 	u16 residue;
201 
202 	if ((desc->if_type == IF_TYPE_MTD && desc->devnum == BLK_MTD_SPI_NOR) ||
203 	    desc->if_type == IF_TYPE_SPINOR)
204 		residue = 0x03; /* 128KB Max block xfer for SPI Nor */
205 	else if (common->cmnd[1] == 0xf7 && FSG_BUFLEN >= 0x400000)
206 		residue = 0x0a; /* Max block xfer for USB DWC3 */
207 	else
208 		residue = 0x06; /* Max block xfer support from host */
209 
210 	usb_trb_size = (1 << residue) * 4096;
211 	common->usb_trb_size = min(usb_trb_size, FSG_BUFLEN);
212 	common->residue = residue << 24;
213 	common->data_dir = DATA_DIR_NONE;
214 	bh->state = BUF_STATE_EMPTY;
215 
216 	return 0;
217 }
218 
219 static int rkusb_do_read_flash_id(struct fsg_common *common,
220 				  struct fsg_buffhd *bh)
221 {
222 	u8 *buf = (u8 *)bh->buf;
223 	u32 len = 5;
224 	enum if_type type = ums[common->lun].block_dev.if_type;
225 	u32 devnum = ums[common->lun].block_dev.devnum;
226 	const char *str;
227 
228 	switch (type) {
229 	case IF_TYPE_MMC:
230 		str = "EMMC ";
231 		break;
232 	case IF_TYPE_RKNAND:
233 		str = "NAND ";
234 		break;
235 	case IF_TYPE_MTD:
236 		if (devnum == BLK_MTD_SPI_NAND)
237 			str ="SNAND";
238 		else if (devnum == BLK_MTD_NAND)
239 			str = "NAND ";
240 		else
241 			str = "NOR  ";
242 		break;
243 	default:
244 		str = "UNKN "; /* unknown */
245 		break;
246 	}
247 
248 	memcpy((void *)&buf[0], str, len);
249 
250 	/* Set data xfer size */
251 	common->residue = common->data_size_from_cmnd = len;
252 	common->data_size = len;
253 
254 	return len;
255 }
256 
257 static int rkusb_do_test_bad_block(struct fsg_common *common,
258 				   struct fsg_buffhd *bh)
259 {
260 	u8 *buf = (u8 *)bh->buf;
261 	u32 len = 64;
262 
263 	memset((void *)&buf[0], 0, len);
264 
265 	/* Set data xfer size */
266 	common->residue = common->data_size_from_cmnd = len;
267 	common->data_size = len;
268 
269 	return len;
270 }
271 
272 static int rkusb_do_read_flash_info(struct fsg_common *common,
273 				    struct fsg_buffhd *bh)
274 {
275 	struct blk_desc *desc = &ums[common->lun].block_dev;
276 	u8 *buf = (u8 *)bh->buf;
277 	u32 len = sizeof(struct rk_flash_info);
278 	struct rk_flash_info finfo = {
279 		.block_size = ROCKCHIP_FLASH_BLOCK_SIZE,
280 		.ecc_bits = 0,
281 		.page_size = ROCKCHIP_FLASH_PAGE_SIZE,
282 		.access_time = 40,
283 		.manufacturer = 0,
284 		.flash_mask = 0
285 	};
286 
287 	finfo.flash_size = (u32)desc->lba;
288 
289 	if (desc->if_type == IF_TYPE_MTD &&
290 	    (desc->devnum == BLK_MTD_NAND ||
291 	    desc->devnum == BLK_MTD_SPI_NAND)) {
292 		struct mtd_info *mtd = (struct mtd_info *)desc->bdev->priv;
293 
294 		if (mtd) {
295 			finfo.block_size = mtd->erasesize >> 9;
296 			finfo.page_size = mtd->writesize >> 9;
297 		}
298 	}
299 
300 	if (desc->if_type == IF_TYPE_MTD && desc->devnum == BLK_MTD_SPI_NOR) {
301 		/* RV1126/RK3308 mtd spinor keep the former upgrade mode */
302 #if !defined(CONFIG_ROCKCHIP_RV1126) && !defined(CONFIG_ROCKCHIP_RK3308)
303 		finfo.block_size = 0x80; /* Aligned to 64KB */
304 #else
305 		finfo.block_size = ROCKCHIP_FLASH_BLOCK_SIZE;
306 #endif
307 	}
308 
309 	debug("Flash info: block_size= %x page_size= %x\n", finfo.block_size,
310 	      finfo.page_size);
311 
312 	if (finfo.flash_size)
313 		finfo.flash_mask = 1;
314 
315 	memset((void *)&buf[0], 0, len);
316 	memcpy((void *)&buf[0], (void *)&finfo, len);
317 
318 	/* Set data xfer size */
319 	common->residue = common->data_size_from_cmnd = len;
320         /* legacy upgrade_tool does not set correct transfer size */
321 	common->data_size = len;
322 
323 	return len;
324 }
325 
326 static int rkusb_do_get_chip_info(struct fsg_common *common,
327 				  struct fsg_buffhd *bh)
328 {
329 	u8 *buf = (u8 *)bh->buf;
330 	u32 len = common->data_size;
331 	u32 chip_info[4];
332 
333 	memset((void *)chip_info, 0, sizeof(chip_info));
334 	rockchip_rockusb_get_chip_info(chip_info);
335 
336 	memset((void *)&buf[0], 0, len);
337 	memcpy((void *)&buf[0], (void *)chip_info, len);
338 
339 	/* Set data xfer size */
340 	common->residue = common->data_size_from_cmnd = len;
341 
342 	return len;
343 }
344 
345 static int rkusb_do_lba_erase(struct fsg_common *common,
346 			      struct fsg_buffhd *bh)
347 {
348 	struct fsg_lun *curlun = &common->luns[common->lun];
349 	u32 lba, amount;
350 	loff_t file_offset;
351 	int rc;
352 
353 	lba = get_unaligned_be32(&common->cmnd[2]);
354 	if (lba >= curlun->num_sectors) {
355 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
356 		rc = -EINVAL;
357 		goto out;
358 	}
359 
360 	file_offset = ((loff_t) lba) << 9;
361 	amount = get_unaligned_be16(&common->cmnd[7]) << 9;
362 	if (unlikely(amount == 0)) {
363 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
364 		rc = -EIO;
365 		goto out;
366 	}
367 
368 	/* Perform the erase */
369 	rc = ums[common->lun].erase_sector(&ums[common->lun],
370 			       file_offset / SECTOR_SIZE,
371 			       amount / SECTOR_SIZE);
372 	if (!rc) {
373 		curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
374 		rc = -EIO;
375 	}
376 
377 out:
378 	common->data_dir = DATA_DIR_NONE;
379 	bh->state = BUF_STATE_EMPTY;
380 
381 	return rc;
382 }
383 
384 static int rkusb_do_erase_force(struct fsg_common *common,
385 				struct fsg_buffhd *bh)
386 {
387 	struct blk_desc *desc = &ums[common->lun].block_dev;
388 	struct fsg_lun *curlun = &common->luns[common->lun];
389 	u16 block_size = ROCKCHIP_FLASH_BLOCK_SIZE;
390 	u32 lba, amount;
391 	loff_t file_offset;
392 	int rc;
393 
394 	lba = get_unaligned_be32(&common->cmnd[2]);
395 	if (lba >= curlun->num_sectors) {
396 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
397 		rc = -EINVAL;
398 		goto out;
399 	}
400 
401 	if (desc->if_type == IF_TYPE_MTD &&
402 	    (desc->devnum == BLK_MTD_NAND ||
403 	    desc->devnum == BLK_MTD_SPI_NAND)) {
404 		struct mtd_info *mtd = (struct mtd_info *)desc->bdev->priv;
405 
406 		if (mtd)
407 			block_size = mtd->erasesize >> 9;
408 	}
409 
410 	file_offset = ((loff_t)lba) * block_size;
411 	amount = get_unaligned_be16(&common->cmnd[7]) * block_size;
412 
413 	debug("%s lba= %x, nsec= %x\n", __func__, lba,
414 	      (u32)get_unaligned_be16(&common->cmnd[7]));
415 
416 	if (unlikely(amount == 0)) {
417 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
418 		rc = -EIO;
419 		goto out;
420 	}
421 
422 	/* Perform the erase */
423 	rc = ums[common->lun].erase_sector(&ums[common->lun],
424 					   file_offset,
425 					   amount);
426 	if (!rc) {
427 		curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
428 		rc = -EIO;
429 	}
430 
431 out:
432 	common->data_dir = DATA_DIR_NONE;
433 	bh->state = BUF_STATE_EMPTY;
434 
435 	return rc;
436 }
437 
438 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
439 static int rkusb_do_vs_write(struct fsg_common *common)
440 {
441 	struct fsg_lun		*curlun = &common->luns[common->lun];
442 	u16			type = get_unaligned_be16(&common->cmnd[4]);
443 	struct vendor_item	*vhead;
444 	struct fsg_buffhd	*bh;
445 	void			*data;
446 	int			rc;
447 
448 	if (common->data_size >= (u32)65536) {
449 		/* _MUST_ small than 64K */
450 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
451 		return -EINVAL;
452 	}
453 
454 	common->residue         = common->data_size;
455 	common->usb_amount_left = common->data_size;
456 
457 	/* Carry out the file writes */
458 	if (unlikely(common->data_size == 0))
459 		return -EIO; /* No data to write */
460 
461 	for (;;) {
462 		if (common->usb_amount_left > 0) {
463 			/* Wait for the next buffer to become available */
464 			bh = common->next_buffhd_to_fill;
465 			if (bh->state != BUF_STATE_EMPTY)
466 				goto wait;
467 
468 			/* Request the next buffer */
469 			common->usb_amount_left      -= common->data_size;
470 			bh->outreq->length	     = common->data_size;
471 			bh->bulk_out_intended_length = common->data_size;
472 			bh->outreq->short_not_ok     = 1;
473 
474 			START_TRANSFER_OR(common, bulk_out, bh->outreq,
475 					  &bh->outreq_busy, &bh->state)
476 				/*
477 				 * Don't know what to do if
478 				 * common->fsg is NULL
479 				 */
480 				return -EIO;
481 			common->next_buffhd_to_fill = bh->next;
482 		} else {
483 			/* Then, wait for the data to become available */
484 			bh = common->next_buffhd_to_drain;
485 			if (bh->state != BUF_STATE_FULL)
486 				goto wait;
487 
488 			common->next_buffhd_to_drain = bh->next;
489 			bh->state = BUF_STATE_EMPTY;
490 
491 			/* Did something go wrong with the transfer? */
492 			if (bh->outreq->status != 0) {
493 				curlun->sense_data = SS_COMMUNICATION_FAILURE;
494 				curlun->info_valid = 1;
495 				break;
496 			}
497 
498 			/* Perform the write */
499 			vhead = (struct vendor_item *)bh->buf;
500 			data  = bh->buf + sizeof(struct vendor_item);
501 
502 			if (!type) {
503 				#ifndef CONFIG_SUPPORT_USBPLUG
504 				if (vhead->id == HDCP_14_HDMI_ID ||
505 				    vhead->id == HDCP_14_HDMIRX_ID ||
506 				    vhead->id == HDCP_14_DP_ID) {
507 					rc = vendor_handle_hdcp(vhead);
508 					if (rc < 0) {
509 						curlun->sense_data = SS_WRITE_ERROR;
510 						return -EIO;
511 					}
512 				}
513 				#endif
514 
515 				/* Vendor storage */
516 				rc = vendor_storage_write(vhead->id,
517 							  (char __user *)data,
518 							  vhead->size);
519 				if (rc < 0) {
520 					curlun->sense_data = SS_WRITE_ERROR;
521 					return -EIO;
522 				}
523 			} else if (type == 1) {
524 				/* RPMB */
525 				rc =
526 				write_keybox_to_secure_storage((u8 *)data,
527 							       vhead->size);
528 				if (rc < 0) {
529 					curlun->sense_data = SS_WRITE_ERROR;
530 					return -EIO;
531 				}
532 			} else if (type == 2) {
533 				/* security storage */
534 #ifdef CONFIG_RK_AVB_LIBAVB_USER
535 				debug("%s call rk_avb_write_perm_attr %d, %d\n",
536 				      __func__, vhead->id, vhead->size);
537 				rc = rk_avb_write_perm_attr(vhead->id,
538 							    (char __user *)data,
539 							    vhead->size);
540 				if (rc < 0) {
541 					curlun->sense_data = SS_WRITE_ERROR;
542 					return -EIO;
543 				}
544 #else
545 				printf("Please enable CONFIG_RK_AVB_LIBAVB_USER\n");
546 #endif
547 			} else if (type == 3) {
548 				/* efuse or otp*/
549 #ifdef CONFIG_OPTEE_CLIENT
550 				if (memcmp(data, "TAEK", 4) == 0) {
551 					if (vhead->size - 8 != 32) {
552 						printf("check ta encryption key size fail!\n");
553 						curlun->sense_data = SS_WRITE_ERROR;
554 						return -EIO;
555 					}
556 					if (trusty_write_ta_encryption_key((uint32_t *)(data + 8), 8) != 0) {
557 						printf("trusty_write_ta_encryption_key error!");
558 						curlun->sense_data = SS_WRITE_ERROR;
559 						return -EIO;
560 					}
561 				} else if (memcmp(data, "EHUK", 4) == 0) {
562 					if (vhead->size - 8 != 32) {
563 						printf("check oem huk size fail!\n");
564 						curlun->sense_data = SS_WRITE_ERROR;
565 						return -EIO;
566 					}
567 					if (trusty_write_oem_huk((uint32_t *)(data + 8), 8) != 0) {
568 						printf("trusty_write_oem_huk error!");
569 						curlun->sense_data = SS_WRITE_ERROR;
570 						return -EIO;
571 					}
572 				} else if (memcmp(data, "ENDA", 4) == 0) {
573 					if (vhead->size - 8 != 16) {
574 						printf("check oem encrypt data size fail!\n");
575 						curlun->sense_data = SS_WRITE_ERROR;
576 						return -EIO;
577 					}
578 					if (trusty_write_oem_encrypt_data((uint32_t *)(data + 8), 4) != 0) {
579 						printf("trusty_write_oem_encrypt_data error!");
580 						curlun->sense_data = SS_WRITE_ERROR;
581 						return -EIO;
582 					}
583 				} else {
584 					printf("Unknown tag\n");
585 					curlun->sense_data = SS_WRITE_ERROR;
586 					return -EIO;
587 				}
588 #else
589 				printf("Please enable CONFIG_OPTEE_CLIENT\n");
590 #endif
591 			} else {
592 				return -EINVAL;
593 			}
594 
595 			common->residue -= common->data_size;
596 
597 			/* Did the host decide to stop early? */
598 			if (bh->outreq->actual != bh->outreq->length)
599 				common->short_packet_received = 1;
600 			break; /* Command done */
601 		}
602 wait:
603 		/* Wait for something to happen */
604 		rc = sleep_thread(common);
605 		if (rc)
606 			return rc;
607 	}
608 
609 	return -EIO; /* No default reply */
610 }
611 
612 static int rkusb_do_vs_read(struct fsg_common *common)
613 {
614 	struct fsg_lun		*curlun = &common->luns[common->lun];
615 	u16			type = get_unaligned_be16(&common->cmnd[4]);
616 	struct vendor_item	*vhead;
617 	struct fsg_buffhd	*bh;
618 	void			*data;
619 	int			rc;
620 
621 	if (common->data_size >= (u32)65536) {
622 		/* _MUST_ small than 64K */
623 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
624 		return -EINVAL;
625 	}
626 
627 	common->residue         = common->data_size;
628 	common->usb_amount_left = common->data_size;
629 
630 	/* Carry out the file reads */
631 	if (unlikely(common->data_size == 0))
632 		return -EIO; /* No default reply */
633 
634 	for (;;) {
635 		/* Wait for the next buffer to become available */
636 		bh = common->next_buffhd_to_fill;
637 		while (bh->state != BUF_STATE_EMPTY) {
638 			rc = sleep_thread(common);
639 			if (rc)
640 				return rc;
641 		}
642 
643 		memset(bh->buf, 0, FSG_BUFLEN);
644 		vhead = (struct vendor_item *)bh->buf;
645 		data  = bh->buf + sizeof(struct vendor_item);
646 		vhead->id = get_unaligned_be16(&common->cmnd[2]);
647 
648 		if (!type) {
649 			/* Vendor storage */
650 			rc = vendor_storage_read(vhead->id,
651 						 (char __user *)data,
652 						 common->data_size);
653 			if (!rc) {
654 				curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
655 				return -EIO;
656 			}
657 			vhead->size = rc;
658 		} else if (type == 1) {
659 			/* RPMB */
660 			rc =
661 			read_raw_data_from_secure_storage((u8 *)data,
662 							  common->data_size);
663 			if (!rc) {
664 				curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
665 				return -EIO;
666 			}
667 			vhead->size = rc;
668 		} else if (type == 2) {
669 			/* security storage */
670 #ifdef CONFIG_RK_AVB_LIBAVB_USER
671 			rc = rk_avb_read_perm_attr(vhead->id,
672 						   (char __user *)data,
673 						   vhead->size);
674 			if (rc < 0)
675 				return -EIO;
676 			vhead->size = rc;
677 #else
678 			printf("Please enable CONFIG_RK_AVB_LIBAVB_USER!\n");
679 #endif
680 		} else if (type == 3) {
681 			/* efuse or otp*/
682 #ifdef CONFIG_OPTEE_CLIENT
683 			if (vhead->id == 120) {
684 				u8 value;
685 				char *written_str = "key is written!";
686 				char *not_written_str = "key is not written!";
687 				if (trusty_ta_encryption_key_is_written(&value) != 0) {
688 					printf("trusty_ta_encryption_key_is_written error!");
689 					return -EIO;
690 				}
691 				if (value) {
692 					memcpy(data, written_str, strlen(written_str));
693 					vhead->size = strlen(written_str);
694 				} else {
695 					memcpy(data, not_written_str, strlen(not_written_str));
696 					vhead->size = strlen(not_written_str);
697 				}
698 			} else {
699 				printf("Unknown tag\n");
700 				return -EIO;
701 			}
702 #else
703 			printf("Please enable CONFIG_OPTEE_CLIENT\n");
704 #endif
705 		} else {
706 			return -EINVAL;
707 		}
708 
709 		common->residue   -= common->data_size;
710 		bh->inreq->length = common->data_size;
711 		bh->state         = BUF_STATE_FULL;
712 
713 		break; /* No more left to read */
714 	}
715 
716 	return -EIO; /* No default reply */
717 }
718 #endif
719 
720 static int rkusb_do_switch_storage(struct fsg_common *common)
721 {
722 	enum if_type type, cur_type = ums[common->lun].block_dev.if_type;
723 	int devnum, cur_devnum = ums[common->lun].block_dev.devnum;
724 	struct blk_desc *block_dev;
725 	u32 media = BOOT_TYPE_UNKNOWN;
726 
727 	media = 1 << common->cmnd[1];
728 
729 	switch (media) {
730 #ifdef CONFIG_MMC
731 	case BOOT_TYPE_EMMC:
732 		type = IF_TYPE_MMC;
733 		devnum = 0;
734 		mmc_initialize(gd->bd);
735 		break;
736 #endif
737 	case BOOT_TYPE_MTD_BLK_NAND:
738 		type = IF_TYPE_MTD;
739 		devnum = 0;
740 		break;
741 	case BOOT_TYPE_MTD_BLK_SPI_NAND:
742 		type = IF_TYPE_MTD;
743 		devnum = 1;
744 		break;
745 	case BOOT_TYPE_MTD_BLK_SPI_NOR:
746 		type = IF_TYPE_MTD;
747 		devnum = 2;
748 		break;
749 	default:
750 		printf("Bootdev 0x%x is not support\n", media);
751 		return -ENODEV;
752 	}
753 
754 	if (cur_type == type && cur_devnum == devnum)
755 		return 0;
756 
757 #if CONFIG_IS_ENABLED(SUPPORT_USBPLUG)
758 	block_dev = usbplug_blk_get_devnum_by_type(type, devnum);
759 #else
760 	block_dev = blk_get_devnum_by_type(type, devnum);
761 #endif
762 	if (!block_dev) {
763 		printf("Bootdev if_type=%d num=%d toggle fail\n", type, devnum);
764 		return -ENODEV;
765 	}
766 
767 	ums[common->lun].num_sectors = block_dev->lba;
768 	ums[common->lun].block_dev = *block_dev;
769 
770 	printf("RKUSB: LUN %d, dev %d, hwpart %d, sector %#x, count %#x\n",
771 	       0,
772 	       ums[common->lun].block_dev.devnum,
773 	       ums[common->lun].block_dev.hwpart,
774 	       ums[common->lun].start_sector,
775 	       ums[common->lun].num_sectors);
776 
777 	return 0;
778 }
779 
780 static int rkusb_do_get_storage_info(struct fsg_common *common,
781 				     struct fsg_buffhd *bh)
782 {
783 	enum if_type type = ums[common->lun].block_dev.if_type;
784 	int devnum = ums[common->lun].block_dev.devnum;
785 	u32 media = BOOT_TYPE_UNKNOWN;
786 	u32 len = common->data_size;
787 	u8 *buf = (u8 *)bh->buf;
788 
789 	if (len > 4)
790 		len = 4;
791 
792 	switch (type) {
793 	case IF_TYPE_MMC:
794 		media = BOOT_TYPE_EMMC;
795 		break;
796 
797 	case IF_TYPE_SD:
798 		media = BOOT_TYPE_SD0;
799 		break;
800 
801 	case IF_TYPE_MTD:
802 		if (devnum == BLK_MTD_SPI_NAND)
803 			media = BOOT_TYPE_MTD_BLK_SPI_NAND;
804 		else if (devnum == BLK_MTD_NAND)
805 			media = BOOT_TYPE_NAND;
806 		else
807 			media = BOOT_TYPE_MTD_BLK_SPI_NOR;
808 		break;
809 
810 	case IF_TYPE_SCSI:
811 		media = BOOT_TYPE_SATA;
812 		break;
813 
814 	case IF_TYPE_RKNAND:
815 		media = BOOT_TYPE_NAND;
816 		break;
817 
818 	case IF_TYPE_NVME:
819 		media = BOOT_TYPE_PCIE;
820 		break;
821 
822 	default:
823 		break;
824 	}
825 
826 	memcpy((void *)&buf[0], (void *)&media, len);
827 	common->residue = len;
828 	common->data_size_from_cmnd = len;
829 
830 	return len;
831 }
832 
833 static int rkusb_do_read_capacity(struct fsg_common *common,
834 				  struct fsg_buffhd *bh)
835 {
836 	u8 *buf = (u8 *)bh->buf;
837 	u32 len = common->data_size;
838 	enum if_type type = ums[common->lun].block_dev.if_type;
839 	int devnum = ums[common->lun].block_dev.devnum;
840 
841 	/*
842 	 * bit[0]: Direct LBA, 0: Disabled;
843 	 * bit[1]: Vendor Storage API, 0: Disabed (default);
844 	 * bit[2]: First 4M Access, 0: Disabled;
845 	 * bit[3]: Read LBA On, 0: Disabed (default);
846 	 * bit[4]: New Vendor Storage API, 0: Disabed;
847 	 * bit[5]: Read uart data from ram
848 	 * bit[6]: Read IDB config
849 	 * bit[7]: Read SecureMode
850 	 * bit[8]: New IDB feature
851 	 * bit[9]: Get storage media info
852 	 * bit[10:63}: Reserved.
853 	 */
854 	memset((void *)&buf[0], 0, len);
855 	if (type == IF_TYPE_MMC || type == IF_TYPE_SD || type == IF_TYPE_NVME)
856 		buf[0] = BIT(0) | BIT(2) | BIT(4);
857 	else
858 		buf[0] = BIT(0) | BIT(4);
859 
860 	if (type == IF_TYPE_MTD &&
861 	    (devnum == BLK_MTD_NAND ||
862 	    devnum == BLK_MTD_SPI_NAND))
863 		buf[0] |= (1 << 6);
864 
865 #if !defined(CONFIG_ROCKCHIP_RV1126) && !defined(CONFIG_ROCKCHIP_RK3308)
866 	if (type == IF_TYPE_MTD && devnum == BLK_MTD_SPI_NOR)
867 		buf[0] |= (1 << 6);
868 #endif
869 
870 #if defined(CONFIG_ROCKCHIP_NEW_IDB)
871 	buf[1] = BIT(0);
872 #endif
873 	buf[1] |= BIT(1); /* Switch Storage */
874 	buf[1] |= BIT(2); /* LBAwrite Parity */
875 
876 	if (rkusb_usb3_capable() && !rkusb_force_usb2_enabled())
877 		buf[1] |= BIT(4);
878 	else
879 		buf[1] &= ~BIT(4);
880 
881 	/* Set data xfer size */
882 	common->residue = len;
883 	common->data_size_from_cmnd = len;
884 
885 	return len;
886 }
887 
888 static void rkusb_fixup_cbwcb(struct fsg_common *common,
889 			      struct fsg_buffhd *bh)
890 {
891 	struct usb_request      *req = bh->outreq;
892 	struct fsg_bulk_cb_wrap *cbw = req->buf;
893 
894 	/* FIXME cbw.DataTransferLength was not set by Upgrade Tool */
895 	common->data_size = le32_to_cpu(cbw->DataTransferLength);
896 	if (common->data_size == 0) {
897 		common->data_size =
898 		get_unaligned_be16(&common->cmnd[7]) << 9;
899 		printf("Trasfer Length NOT set, please use new version tool\n");
900 		debug("%s %d, cmnd1 %x\n", __func__,
901 		      get_unaligned_be16(&common->cmnd[7]),
902 		      get_unaligned_be16(&common->cmnd[1]));
903 	}
904 	if (cbw->Flags & USB_BULK_IN_FLAG)
905 		common->data_dir = DATA_DIR_TO_HOST;
906 	else
907 		common->data_dir = DATA_DIR_FROM_HOST;
908 
909 	/* Not support */
910 	common->cmnd[1] = 0;
911 }
912 
913 static int rkusb_cmd_process(struct fsg_common *common,
914 			     struct fsg_buffhd *bh, int *reply)
915 {
916 	struct usb_request	*req = bh->outreq;
917 	struct fsg_bulk_cb_wrap	*cbw = req->buf;
918 	int rc;
919 
920 	dump_cbw(cbw);
921 
922 	if (rkusb_check_lun(common)) {
923 		*reply = -EINVAL;
924 		return RKUSB_RC_ERROR;
925 	}
926 
927 	switch (common->cmnd[0]) {
928 	case RKUSB_TEST_UNIT_READY:
929 		*reply = rkusb_do_test_unit_ready(common, bh);
930 		rc = RKUSB_RC_FINISHED;
931 		break;
932 
933 	case RKUSB_READ_FLASH_ID:
934 		*reply = rkusb_do_read_flash_id(common, bh);
935 		rc = RKUSB_RC_FINISHED;
936 		break;
937 
938 	case RKUSB_TEST_BAD_BLOCK:
939 		*reply = rkusb_do_test_bad_block(common, bh);
940 		rc = RKUSB_RC_FINISHED;
941 		break;
942 
943 	case RKUSB_ERASE_10_FORCE:
944 		*reply = rkusb_do_erase_force(common, bh);
945 		rc = RKUSB_RC_FINISHED;
946 		break;
947 
948 	case RKUSB_LBA_READ_10:
949 		rkusb_fixup_cbwcb(common, bh);
950 		common->cmnd[0] = SC_READ_10;
951 		common->cmnd[1] = 0; /* Not support */
952 		rc = RKUSB_RC_CONTINUE;
953 		break;
954 
955 	case RKUSB_LBA_WRITE_10:
956 		rkusb_fixup_cbwcb(common, bh);
957 		common->cmnd[0] = SC_WRITE_10;
958 		common->cmnd[1] = 0; /* Not support */
959 		rc = RKUSB_RC_CONTINUE;
960 		break;
961 
962 	case RKUSB_READ_FLASH_INFO:
963 		*reply = rkusb_do_read_flash_info(common, bh);
964 		rc = RKUSB_RC_FINISHED;
965 		break;
966 
967 	case RKUSB_GET_CHIP_VER:
968 		*reply = rkusb_do_get_chip_info(common, bh);
969 		rc = RKUSB_RC_FINISHED;
970 		break;
971 
972 	case RKUSB_LBA_ERASE:
973 		*reply = rkusb_do_lba_erase(common, bh);
974 		rc = RKUSB_RC_FINISHED;
975 		break;
976 
977 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
978 	case RKUSB_VS_WRITE:
979 		*reply = rkusb_do_vs_write(common);
980 		rc = RKUSB_RC_FINISHED;
981 		break;
982 
983 	case RKUSB_VS_READ:
984 		*reply = rkusb_do_vs_read(common);
985 		rc = RKUSB_RC_FINISHED;
986 		break;
987 #endif
988 	case RKUSB_SWITCH_STORAGE:
989 		*reply = rkusb_do_switch_storage(common);
990 		rc = RKUSB_RC_FINISHED;
991 		break;
992 	case RKUSB_GET_STORAGE_MEDIA:
993 		*reply = rkusb_do_get_storage_info(common, bh);
994 		rc = RKUSB_RC_FINISHED;
995 		break;
996 
997 	case RKUSB_READ_CAPACITY:
998 		*reply = rkusb_do_read_capacity(common, bh);
999 		rc = RKUSB_RC_FINISHED;
1000 		break;
1001 
1002 	case RKUSB_SWITCH_USB3:
1003 		*reply = rkusb_do_switch_to_usb3(common, bh);
1004 		rc = RKUSB_RC_FINISHED;
1005 		break;
1006 
1007 	case RKUSB_RESET:
1008 		*reply = rkusb_do_reset(common, bh);
1009 		rc = RKUSB_RC_FINISHED;
1010 		break;
1011 
1012 	case RKUSB_READ_10:
1013 	case RKUSB_WRITE_10:
1014 		printf("CMD Not support, pls use new version Tool\n");
1015 	case RKUSB_SET_DEVICE_ID:
1016 	case RKUSB_ERASE_10:
1017 	case RKUSB_WRITE_SPARE:
1018 	case RKUSB_READ_SPARE:
1019 	case RKUSB_GET_VERSION:
1020 	case RKUSB_ERASE_SYS_DISK:
1021 	case RKUSB_SDRAM_READ_10:
1022 	case RKUSB_SDRAM_WRITE_10:
1023 	case RKUSB_SDRAM_EXECUTE:
1024 	case RKUSB_LOW_FORMAT:
1025 	case RKUSB_SET_RESET_FLAG:
1026 	case RKUSB_SPI_READ_10:
1027 	case RKUSB_SPI_WRITE_10:
1028 	case RKUSB_SESSION:
1029 		/* Fall through */
1030 	default:
1031 		rc = RKUSB_RC_UNKNOWN_CMND;
1032 		break;
1033 	}
1034 
1035 	return rc;
1036 }
1037 
1038 int rkusb_do_check_parity(struct fsg_common *common)
1039 {
1040 	int ret = 0, rc;
1041 	u32 parity, i, usb_parity, lba, len;
1042 	static u32 usb_check_buffer[1024 * 256];
1043 
1044 	usb_parity = common->cmnd[9] | (common->cmnd[10] << 8) |
1045 			(common->cmnd[11] << 16) | (common->cmnd[12] << 24);
1046 
1047 	if (common->cmnd[0] == SC_WRITE_10 && (usb_parity)) {
1048 		lba = get_unaligned_be32(&common->cmnd[2]);
1049 		len = common->data_size_from_cmnd >> 9;
1050 		rc = blk_dread(&ums[common->lun].block_dev, lba, len, usb_check_buffer);
1051 		parity = 0x000055aa;
1052 		for (i = 0; i < len * 128; i++)
1053 			parity += usb_check_buffer[i];
1054 		if (!rc || parity != usb_parity)
1055 			common->phase_error = 1;
1056 	}
1057 
1058 	return ret;
1059 }
1060 
1061 DECLARE_GADGET_BIND_CALLBACK(rkusb_ums_dnl, fsg_add);
1062