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