xref: /rk3399_rockchip-uboot/drivers/usb/gadget/f_fastboot.c (revision 6222c401243b38707fd88ccf5e4c35678c183f8d)
1 /*
2  * (C) Copyright 2008 - 2009
3  * Windriver, <www.windriver.com>
4  * Tom Rix <Tom.Rix@windriver.com>
5  *
6  * Copyright 2011 Sebastian Andrzej Siewior <bigeasy@linutronix.de>
7  *
8  * Copyright 2014 Linaro, Ltd.
9  * Rob Herring <robh@kernel.org>
10  *
11  * SPDX-License-Identifier:	GPL-2.0+
12  */
13 #include <config.h>
14 #include <common.h>
15 #include <errno.h>
16 #include <fastboot.h>
17 #include <malloc.h>
18 #include <linux/usb/ch9.h>
19 #include <linux/usb/gadget.h>
20 #include <linux/usb/composite.h>
21 #include <linux/compiler.h>
22 #include <version.h>
23 #include <g_dnl.h>
24 #include <android_avb/avb_ops_user.h>
25 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
26 #include <fb_mmc.h>
27 #endif
28 #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
29 #include <fb_nand.h>
30 #endif
31 #ifdef CONFIG_OPTEE_CLIENT
32 #include <optee_include/OpteeClientInterface.h>
33 #endif
34 
35 #define FASTBOOT_VERSION		"0.4"
36 
37 #define FASTBOOT_INTERFACE_CLASS	0xff
38 #define FASTBOOT_INTERFACE_SUB_CLASS	0x42
39 #define FASTBOOT_INTERFACE_PROTOCOL	0x03
40 
41 #define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_2_0  (0x0200)
42 #define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_1_1  (0x0040)
43 #define TX_ENDPOINT_MAXIMUM_PACKET_SIZE      (0x0040)
44 
45 #define EP_BUFFER_SIZE			4096
46 /*
47  * EP_BUFFER_SIZE must always be an integral multiple of maxpacket size
48  * (64 or 512 or 1024), else we break on certain controllers like DWC3
49  * that expect bulk OUT requests to be divisible by maxpacket size.
50  */
51 
52 struct f_fastboot {
53 	struct usb_function usb_function;
54 
55 	/* IN/OUT EP's and corresponding requests */
56 	struct usb_ep *in_ep, *out_ep;
57 	struct usb_request *in_req, *out_req;
58 };
59 
60 static inline struct f_fastboot *func_to_fastboot(struct usb_function *f)
61 {
62 	return container_of(f, struct f_fastboot, usb_function);
63 }
64 
65 static struct f_fastboot *fastboot_func;
66 static unsigned int download_size;
67 static unsigned int download_bytes;
68 static unsigned int upload_size;
69 static unsigned int upload_bytes;
70 static bool start_upload;
71 
72 static struct usb_endpoint_descriptor fs_ep_in = {
73 	.bLength            = USB_DT_ENDPOINT_SIZE,
74 	.bDescriptorType    = USB_DT_ENDPOINT,
75 	.bEndpointAddress   = USB_DIR_IN,
76 	.bmAttributes       = USB_ENDPOINT_XFER_BULK,
77 	.wMaxPacketSize     = cpu_to_le16(64),
78 };
79 
80 static struct usb_endpoint_descriptor fs_ep_out = {
81 	.bLength		= USB_DT_ENDPOINT_SIZE,
82 	.bDescriptorType	= USB_DT_ENDPOINT,
83 	.bEndpointAddress	= USB_DIR_OUT,
84 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
85 	.wMaxPacketSize		= cpu_to_le16(64),
86 };
87 
88 static struct usb_endpoint_descriptor hs_ep_in = {
89 	.bLength		= USB_DT_ENDPOINT_SIZE,
90 	.bDescriptorType	= USB_DT_ENDPOINT,
91 	.bEndpointAddress	= USB_DIR_IN,
92 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
93 	.wMaxPacketSize		= cpu_to_le16(512),
94 };
95 
96 static struct usb_endpoint_descriptor hs_ep_out = {
97 	.bLength		= USB_DT_ENDPOINT_SIZE,
98 	.bDescriptorType	= USB_DT_ENDPOINT,
99 	.bEndpointAddress	= USB_DIR_OUT,
100 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
101 	.wMaxPacketSize		= cpu_to_le16(512),
102 };
103 
104 static struct usb_interface_descriptor interface_desc = {
105 	.bLength		= USB_DT_INTERFACE_SIZE,
106 	.bDescriptorType	= USB_DT_INTERFACE,
107 	.bInterfaceNumber	= 0x00,
108 	.bAlternateSetting	= 0x00,
109 	.bNumEndpoints		= 0x02,
110 	.bInterfaceClass	= FASTBOOT_INTERFACE_CLASS,
111 	.bInterfaceSubClass	= FASTBOOT_INTERFACE_SUB_CLASS,
112 	.bInterfaceProtocol	= FASTBOOT_INTERFACE_PROTOCOL,
113 };
114 
115 static struct usb_descriptor_header *fb_fs_function[] = {
116 	(struct usb_descriptor_header *)&interface_desc,
117 	(struct usb_descriptor_header *)&fs_ep_in,
118 	(struct usb_descriptor_header *)&fs_ep_out,
119 };
120 
121 static struct usb_descriptor_header *fb_hs_function[] = {
122 	(struct usb_descriptor_header *)&interface_desc,
123 	(struct usb_descriptor_header *)&hs_ep_in,
124 	(struct usb_descriptor_header *)&hs_ep_out,
125 	NULL,
126 };
127 
128 static struct usb_endpoint_descriptor *
129 fb_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
130 	    struct usb_endpoint_descriptor *hs)
131 {
132 	if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
133 		return hs;
134 	return fs;
135 }
136 
137 /*
138  * static strings, in UTF-8
139  */
140 static const char fastboot_name[] = "Android Fastboot";
141 
142 static struct usb_string fastboot_string_defs[] = {
143 	[0].s = fastboot_name,
144 	{  }			/* end of list */
145 };
146 
147 static struct usb_gadget_strings stringtab_fastboot = {
148 	.language	= 0x0409,	/* en-us */
149 	.strings	= fastboot_string_defs,
150 };
151 
152 static struct usb_gadget_strings *fastboot_strings[] = {
153 	&stringtab_fastboot,
154 	NULL,
155 };
156 
157 static void rx_handler_command(struct usb_ep *ep, struct usb_request *req);
158 static int strcmp_l1(const char *s1, const char *s2);
159 
160 static void fastboot_complete(struct usb_ep *ep, struct usb_request *req)
161 {
162 	int status = req->status;
163 	if (!status)
164 		return;
165 	printf("status: %d ep '%s' trans: %d\n", status, ep->name, req->actual);
166 }
167 
168 static int fastboot_bind(struct usb_configuration *c, struct usb_function *f)
169 {
170 	int id;
171 	struct usb_gadget *gadget = c->cdev->gadget;
172 	struct f_fastboot *f_fb = func_to_fastboot(f);
173 	const char *s;
174 
175 	/* DYNAMIC interface numbers assignments */
176 	id = usb_interface_id(c, f);
177 	if (id < 0)
178 		return id;
179 	interface_desc.bInterfaceNumber = id;
180 
181 	id = usb_string_id(c->cdev);
182 	if (id < 0)
183 		return id;
184 	fastboot_string_defs[0].id = id;
185 	interface_desc.iInterface = id;
186 
187 	f_fb->in_ep = usb_ep_autoconfig(gadget, &fs_ep_in);
188 	if (!f_fb->in_ep)
189 		return -ENODEV;
190 	f_fb->in_ep->driver_data = c->cdev;
191 
192 	f_fb->out_ep = usb_ep_autoconfig(gadget, &fs_ep_out);
193 	if (!f_fb->out_ep)
194 		return -ENODEV;
195 	f_fb->out_ep->driver_data = c->cdev;
196 
197 	f->descriptors = fb_fs_function;
198 
199 	if (gadget_is_dualspeed(gadget)) {
200 		/* Assume endpoint addresses are the same for both speeds */
201 		hs_ep_in.bEndpointAddress = fs_ep_in.bEndpointAddress;
202 		hs_ep_out.bEndpointAddress = fs_ep_out.bEndpointAddress;
203 		/* copy HS descriptors */
204 		f->hs_descriptors = fb_hs_function;
205 	}
206 
207 	s = env_get("serial#");
208 	if (s)
209 		g_dnl_set_serialnumber((char *)s);
210 
211 	return 0;
212 }
213 
214 static void fastboot_unbind(struct usb_configuration *c, struct usb_function *f)
215 {
216 	memset(fastboot_func, 0, sizeof(*fastboot_func));
217 }
218 
219 static void fastboot_disable(struct usb_function *f)
220 {
221 	struct f_fastboot *f_fb = func_to_fastboot(f);
222 
223 	usb_ep_disable(f_fb->out_ep);
224 	usb_ep_disable(f_fb->in_ep);
225 
226 	if (f_fb->out_req) {
227 		free(f_fb->out_req->buf);
228 		usb_ep_free_request(f_fb->out_ep, f_fb->out_req);
229 		f_fb->out_req = NULL;
230 	}
231 	if (f_fb->in_req) {
232 		free(f_fb->in_req->buf);
233 		usb_ep_free_request(f_fb->in_ep, f_fb->in_req);
234 		f_fb->in_req = NULL;
235 	}
236 }
237 
238 static struct usb_request *fastboot_start_ep(struct usb_ep *ep)
239 {
240 	struct usb_request *req;
241 
242 	req = usb_ep_alloc_request(ep, 0);
243 	if (!req)
244 		return NULL;
245 
246 	req->length = EP_BUFFER_SIZE;
247 	req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, EP_BUFFER_SIZE);
248 	if (!req->buf) {
249 		usb_ep_free_request(ep, req);
250 		return NULL;
251 	}
252 
253 	memset(req->buf, 0, req->length);
254 	return req;
255 }
256 
257 static int fastboot_set_alt(struct usb_function *f,
258 			    unsigned interface, unsigned alt)
259 {
260 	int ret;
261 	struct usb_composite_dev *cdev = f->config->cdev;
262 	struct usb_gadget *gadget = cdev->gadget;
263 	struct f_fastboot *f_fb = func_to_fastboot(f);
264 	const struct usb_endpoint_descriptor *d;
265 
266 	debug("%s: func: %s intf: %d alt: %d\n",
267 	      __func__, f->name, interface, alt);
268 
269 	d = fb_ep_desc(gadget, &fs_ep_out, &hs_ep_out);
270 	ret = usb_ep_enable(f_fb->out_ep, d);
271 	if (ret) {
272 		puts("failed to enable out ep\n");
273 		return ret;
274 	}
275 
276 	f_fb->out_req = fastboot_start_ep(f_fb->out_ep);
277 	if (!f_fb->out_req) {
278 		puts("failed to alloc out req\n");
279 		ret = -EINVAL;
280 		goto err;
281 	}
282 	f_fb->out_req->complete = rx_handler_command;
283 
284 	d = fb_ep_desc(gadget, &fs_ep_in, &hs_ep_in);
285 	ret = usb_ep_enable(f_fb->in_ep, d);
286 	if (ret) {
287 		puts("failed to enable in ep\n");
288 		goto err;
289 	}
290 
291 	f_fb->in_req = fastboot_start_ep(f_fb->in_ep);
292 	if (!f_fb->in_req) {
293 		puts("failed alloc req in\n");
294 		ret = -EINVAL;
295 		goto err;
296 	}
297 	f_fb->in_req->complete = fastboot_complete;
298 
299 	ret = usb_ep_queue(f_fb->out_ep, f_fb->out_req, 0);
300 	if (ret)
301 		goto err;
302 
303 	return 0;
304 err:
305 	fastboot_disable(f);
306 	return ret;
307 }
308 
309 static int fastboot_add(struct usb_configuration *c)
310 {
311 	struct f_fastboot *f_fb = fastboot_func;
312 	int status;
313 
314 	debug("%s: cdev: 0x%p\n", __func__, c->cdev);
315 
316 	if (!f_fb) {
317 		f_fb = memalign(CONFIG_SYS_CACHELINE_SIZE, sizeof(*f_fb));
318 		if (!f_fb)
319 			return -ENOMEM;
320 
321 		fastboot_func = f_fb;
322 		memset(f_fb, 0, sizeof(*f_fb));
323 	}
324 
325 	f_fb->usb_function.name = "f_fastboot";
326 	f_fb->usb_function.bind = fastboot_bind;
327 	f_fb->usb_function.unbind = fastboot_unbind;
328 	f_fb->usb_function.set_alt = fastboot_set_alt;
329 	f_fb->usb_function.disable = fastboot_disable;
330 	f_fb->usb_function.strings = fastboot_strings;
331 
332 	status = usb_add_function(c, &f_fb->usb_function);
333 	if (status) {
334 		free(f_fb);
335 		fastboot_func = f_fb;
336 	}
337 
338 	return status;
339 }
340 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_fastboot, fastboot_add);
341 
342 static int fastboot_tx_write(const char *buffer, unsigned int buffer_size)
343 {
344 	struct usb_request *in_req = fastboot_func->in_req;
345 	int ret;
346 
347 	memcpy(in_req->buf, buffer, buffer_size);
348 	in_req->length = buffer_size;
349 
350 	usb_ep_dequeue(fastboot_func->in_ep, in_req);
351 
352 	ret = usb_ep_queue(fastboot_func->in_ep, in_req, 0);
353 	if (ret)
354 		printf("Error %d on queue\n", ret);
355 	return 0;
356 }
357 
358 static int fastboot_tx_write_str(const char *buffer)
359 {
360 	return fastboot_tx_write(buffer, strlen(buffer));
361 }
362 
363 static void compl_do_reset(struct usb_ep *ep, struct usb_request *req)
364 {
365 	do_reset(NULL, 0, 0, NULL);
366 }
367 
368 int __weak fb_set_reboot_flag(void)
369 {
370 	return -ENOSYS;
371 }
372 
373 static void cb_reboot(struct usb_ep *ep, struct usb_request *req)
374 {
375 	char *cmd = req->buf;
376 	if (!strcmp_l1("reboot-bootloader", cmd)) {
377 		if (fb_set_reboot_flag()) {
378 			fastboot_tx_write_str("FAILCannot set reboot flag");
379 			return;
380 		}
381 	}
382 	fastboot_func->in_req->complete = compl_do_reset;
383 	fastboot_tx_write_str("OKAY");
384 }
385 
386 static int strcmp_l1(const char *s1, const char *s2)
387 {
388 	if (!s1 || !s2)
389 		return -1;
390 	return strncmp(s1, s2, strlen(s1));
391 }
392 
393 static void cb_getvar(struct usb_ep *ep, struct usb_request *req)
394 {
395 	char *cmd = req->buf;
396 	char response[FASTBOOT_RESPONSE_LEN];
397 	const char *s;
398 	size_t chars_left;
399 
400 	strcpy(response, "OKAY");
401 	chars_left = sizeof(response) - strlen(response) - 1;
402 
403 	strsep(&cmd, ":");
404 	if (!cmd) {
405 		pr_err("missing variable");
406 		fastboot_tx_write_str("FAILmissing var");
407 		return;
408 	}
409 
410 	if (!strcmp_l1("version", cmd)) {
411 		strncat(response, FASTBOOT_VERSION, chars_left);
412 	} else if (!strcmp_l1("bootloader-version", cmd)) {
413 		strncat(response, U_BOOT_VERSION, chars_left);
414 	} else if (!strcmp_l1("product", cmd)) {
415 		strncat(response, CONFIG_SYS_BOARD, chars_left);
416 	} else if (!strcmp_l1("variant", cmd)) {
417 		strncat(response, "userdebug", chars_left);
418 	} else if (!strcmp_l1("secure", cmd)) {
419 		strncat(response, "no", chars_left);
420 	} else if (!strcmp_l1("unlocked", cmd)) {
421 		strncat(response, "yes", chars_left);
422 	} else if (!strcmp_l1("off-mode-charge", cmd)) {
423 		strncat(response, "0", chars_left);
424 	} else if (!strcmp_l1("battery-voltage", cmd)) {
425 		strncat(response, "7.4", chars_left);
426 	} else if (!strcmp_l1("battery-soc-ok", cmd)) {
427 		strncat(response, "yes", chars_left);
428 	} else if (!strcmp_l1("downloadsize", cmd) ||
429 		!strcmp_l1("max-download-size", cmd)) {
430 		char str_num[12];
431 
432 		sprintf(str_num, "0x%08x", CONFIG_FASTBOOT_BUF_SIZE);
433 		strncat(response, str_num, chars_left);
434 	} else if (!strcmp_l1("serialno", cmd)) {
435 		s = env_get("serial#");
436 		if (s)
437 			strncat(response, s, chars_left);
438 		else
439 			strcpy(response, "FAILValue not set");
440 	} else if (strncmp("at-attest-dh", cmd, 12) == 0) {
441 #ifdef CONFIG_OPTEE_CLIENT
442 		char dhbuf[8];
443 		uint32_t dh_len = 8;
444 		uint32_t res = trusty_attest_dh((uint8_t *)dhbuf, &dh_len);
445 		if (res)
446 			strcpy(response, "FAILdh not set");
447 		else
448 			strncat(response, dhbuf, chars_left);
449 #else
450 		fastboot_tx_write_str("FAILnot implemented");
451 		return;
452 #endif
453 	} else if (strncmp("at-attest-uuid", cmd, 14) == 0) {
454 #ifdef CONFIG_OPTEE_CLIENT
455 		char uuid[32] = {0};
456 		uint32_t uuid_len = 32;
457 		uint32_t res = trusty_attest_uuid((uint8_t *)uuid, &uuid_len);
458 		if (res)
459 			strcpy(response, "FAILuuid not set");
460 		else
461 			strncat(response, uuid, chars_left);
462 #else
463 		fastboot_tx_write_str("FAILnot implemented");
464 		return;
465 #endif
466 	} else if (strncmp("at-vboot-state", cmd, 14) == 0) {
467 		char uuid[32] = {0};
468 
469 		strncat(response, uuid, chars_left);
470 	} else if (!strcmp_l1("slot-count", cmd)) {
471 #ifdef CONFIG_AVB_LIBAVB_USER
472 		char slot_count[2];
473 		char temp;
474 
475 		slot_count[1] = '\0';
476 		avb_read_slot_count(&temp);
477 		slot_count[0] = temp + 0x30;
478 		strncat(response, slot_count, chars_left);
479 #else
480 		fastboot_tx_write_str("FAILnot implemented");
481 		return;
482 #endif
483 	} else if (!strcmp_l1("current-slot", cmd)) {
484 #ifdef CONFIG_AVB_LIBAVB_USER
485 		char slot_surrent[8] = {0};
486 
487 		if (!avb_get_current_slot(slot_surrent))
488 			strncat(response, slot_surrent+1, chars_left);
489 		else
490 			strcpy(response, "FAILgeterror");
491 #else
492 		fastboot_tx_write_str("FAILnot implemented");
493 		return;
494 #endif
495 	} else if (!strcmp_l1("slot-suffixes", cmd)) {
496 #ifdef CONFIG_AVB_LIBAVB_USER
497 		char slot_suffixes_temp[4];
498 		char slot_suffixes[9];
499 		int slot_cnt = 0;
500 
501 		memset(slot_suffixes_temp, 0, 4);
502 		memset(slot_suffixes, 0, 9);
503 		avb_read_slot_suffixes(slot_suffixes_temp);
504 		while (slot_suffixes_temp[slot_cnt] != '\0') {
505 			slot_suffixes[slot_cnt * 2]
506 				= slot_suffixes_temp[slot_cnt];
507 			slot_suffixes[slot_cnt * 2 + 1] = ',';
508 			slot_cnt++;
509 		}
510 		strncat(response, slot_suffixes, chars_left);
511 #else
512 		fastboot_tx_write_str("FAILnot implemented");
513 		return;
514 #endif
515 	} else if (!strncmp("has-slot", cmd, 8)) {
516 #ifdef CONFIG_AVB_LIBAVB_USER
517 		char *part_name = cmd;
518 
519 		cmd = strsep(&part_name, ":");
520 		if (!strcmp(part_name, "boot") ||
521 		    !strcmp(part_name, "system") ||
522 		    !strcmp(part_name, "vendor") ||
523 		    !strcmp(part_name, "vbmeta") ||
524 		    !strcmp(part_name, "oem")) {
525 			strncat(response, "yes", chars_left);
526 		} else {
527 			strcpy(response, "FAILno");
528 		}
529 #else
530 		fastboot_tx_write_str("FAILnot implemented");
531 		return;
532 #endif
533 	} else if (!strncmp("slot-unbootable", cmd, 15)) {
534 #ifdef CONFIG_AVB_LIBAVB_USER
535 		char *slot_name = cmd;
536 
537 		cmd = strsep(&slot_name, ":");
538 		if (!strcmp(slot_name, "a") ||
539 		    !strcmp(slot_name, "b")) {
540 			strncat(response, "no", chars_left);
541 		} else {
542 			strcpy(response, "FAILno");
543 		}
544 #else
545 		fastboot_tx_write_str("FAILnot implemented");
546 		return;
547 #endif
548 	} else if (!strncmp("slot-successful", cmd, 15)) {
549 #ifdef CONFIG_AVB_LIBAVB_USER
550 		char *slot_name = cmd;
551 
552 		cmd = strsep(&slot_name, ":");
553 		if (!strcmp(slot_name, "a") ||
554 		    !strcmp(slot_name, "b")) {
555 			strncat(response, "no", chars_left);
556 		} else {
557 			strcpy(response, "FAILno");
558 		}
559 #else
560 		fastboot_tx_write_str("FAILnot implemented");
561 		return;
562 #endif
563 	} else if (!strncmp("slot-retry-count", cmd, 16)) {
564 #ifdef CONFIG_AVB_LIBAVB_USER
565 		char *slot_name = cmd;
566 		char count[10] = {0};
567 		static int cnt[2] = {0};
568 
569 		cmd = strsep(&slot_name, ":");
570 		if (!strcmp(slot_name, "a")) {
571 			sprintf(count, "%c", 0x30+cnt[0]);
572 			strncat(response, count, chars_left);
573 			if (cnt[0] > 0)
574 				cnt[0]--;
575 		} else if (!strcmp(slot_name, "b")) {
576 			sprintf(count, "%c", 0x30+cnt[1]);
577 			strncat(response, count, chars_left);
578 			if (cnt[1] > 0)
579 				cnt[1]--;
580 		} else {
581 			strcpy(response, "FAILno");
582 		}
583 #else
584 		fastboot_tx_write_str("FAILnot implemented");
585 		return;
586 #endif
587 	} else if (!strncmp("partition-type", cmd, 14) ||
588 		   !strncmp("partition-size", cmd, 14)) {
589 		disk_partition_t part_info;
590 		struct blk_desc *dev_desc;
591 		char *part_name = cmd;
592 		char part_size_str[20];
593 
594 		cmd = strsep(&part_name, ":");
595 		dev_desc = blk_get_dev("mmc", 0);
596 		if (!dev_desc) {
597 			strcpy(response, "FAILblock device not found");
598 		} else if (part_get_info_by_name(dev_desc, part_name, &part_info) < 0) {
599 			strcpy(response, "FAILpartition not found");
600 		} else if (!strncmp("partition-type", cmd, 14)) {
601 			strncat(response, (char *)part_info.type, chars_left);
602 		} else if (!strncmp("partition-size", cmd, 14)) {
603 			sprintf(part_size_str, "0x%016x", (int)part_info.size);
604 			strncat(response, part_size_str, chars_left);
605 		}
606 	} else {
607 		char *envstr;
608 
609 		envstr = malloc(strlen("fastboot.") + strlen(cmd) + 1);
610 		if (!envstr) {
611 			fastboot_tx_write_str("FAILmalloc error");
612 			return;
613 		}
614 
615 		sprintf(envstr, "fastboot.%s", cmd);
616 		s = env_get(envstr);
617 		if (s) {
618 			strncat(response, s, chars_left);
619 		} else {
620 			printf("WARNING: unknown variable: %s\n", cmd);
621 			strcpy(response, "FAILVariable not implemented");
622 		}
623 
624 		free(envstr);
625 	}
626 	fastboot_tx_write_str(response);
627 }
628 
629 static unsigned int rx_bytes_expected(struct usb_ep *ep)
630 {
631 	int rx_remain = download_size - download_bytes;
632 	unsigned int rem;
633 	unsigned int maxpacket = ep->maxpacket;
634 
635 	if (rx_remain <= 0)
636 		return 0;
637 	else if (rx_remain > EP_BUFFER_SIZE)
638 		return EP_BUFFER_SIZE;
639 
640 	/*
641 	 * Some controllers e.g. DWC3 don't like OUT transfers to be
642 	 * not ending in maxpacket boundary. So just make them happy by
643 	 * always requesting for integral multiple of maxpackets.
644 	 * This shouldn't bother controllers that don't care about it.
645 	 */
646 	rem = rx_remain % maxpacket;
647 	if (rem > 0)
648 		rx_remain = rx_remain + (maxpacket - rem);
649 
650 	return rx_remain;
651 }
652 
653 #define BYTES_PER_DOT	0x20000
654 static void rx_handler_dl_image(struct usb_ep *ep, struct usb_request *req)
655 {
656 	char response[FASTBOOT_RESPONSE_LEN];
657 	unsigned int transfer_size = download_size - download_bytes;
658 	const unsigned char *buffer = req->buf;
659 	unsigned int buffer_size = req->actual;
660 	unsigned int pre_dot_num, now_dot_num;
661 
662 	if (req->status != 0) {
663 		printf("Bad status: %d\n", req->status);
664 		return;
665 	}
666 
667 	if (buffer_size < transfer_size)
668 		transfer_size = buffer_size;
669 
670 	memcpy((void *)CONFIG_FASTBOOT_BUF_ADDR + download_bytes,
671 	       buffer, transfer_size);
672 
673 	pre_dot_num = download_bytes / BYTES_PER_DOT;
674 	download_bytes += transfer_size;
675 	now_dot_num = download_bytes / BYTES_PER_DOT;
676 
677 	if (pre_dot_num != now_dot_num) {
678 		putc('.');
679 		if (!(now_dot_num % 74))
680 			putc('\n');
681 	}
682 
683 	/* Check if transfer is done */
684 	if (download_bytes >= download_size) {
685 		/*
686 		 * Reset global transfer variable, keep download_bytes because
687 		 * it will be used in the next possible flashing command
688 		 */
689 		download_size = 0;
690 		req->complete = rx_handler_command;
691 		req->length = EP_BUFFER_SIZE;
692 
693 		strcpy(response, "OKAY");
694 		fastboot_tx_write_str(response);
695 
696 		printf("\ndownloading of %d bytes finished\n", download_bytes);
697 	} else {
698 		req->length = rx_bytes_expected(ep);
699 	}
700 
701 	req->actual = 0;
702 	usb_ep_queue(ep, req, 0);
703 }
704 
705 static void cb_download(struct usb_ep *ep, struct usb_request *req)
706 {
707 	char *cmd = req->buf;
708 	char response[FASTBOOT_RESPONSE_LEN];
709 
710 	strsep(&cmd, ":");
711 	download_size = simple_strtoul(cmd, NULL, 16);
712 	download_bytes = 0;
713 
714 	printf("Starting download of %d bytes\n", download_size);
715 
716 	if (0 == download_size) {
717 		strcpy(response, "FAILdata invalid size");
718 	} else if (download_size > CONFIG_FASTBOOT_BUF_SIZE) {
719 		download_size = 0;
720 		strcpy(response, "FAILdata too large");
721 	} else {
722 		sprintf(response, "DATA%08x", download_size);
723 		req->complete = rx_handler_dl_image;
724 		req->length = rx_bytes_expected(ep);
725 	}
726 
727 	fastboot_tx_write_str(response);
728 }
729 
730 static void tx_handler_ul(struct usb_ep *ep, struct usb_request *req)
731 {
732 	unsigned int xfer_size = 0;
733 	unsigned int pre_dot_num, now_dot_num;
734 	unsigned int remain_size = 0;
735 	unsigned int transferred_size = req->actual;
736 
737 	if (req->status != 0) {
738 		printf("Bad status: %d\n", req->status);
739 		return;
740 	}
741 
742 	if (start_upload) {
743 		pre_dot_num = upload_bytes / BYTES_PER_DOT;
744 		upload_bytes += transferred_size;
745 		now_dot_num = upload_bytes / BYTES_PER_DOT;
746 
747 		if (pre_dot_num != now_dot_num) {
748 			putc('.');
749 			if (!(now_dot_num % 74))
750 				putc('\n');
751 		}
752 	}
753 
754 	remain_size = upload_size - upload_bytes;
755 	xfer_size = (remain_size > EP_BUFFER_SIZE) ?
756 		    EP_BUFFER_SIZE : remain_size;
757 
758 	debug("%s: remain_size=%d, transferred_size=%d",
759 	      __func__, remain_size, transferred_size);
760 	debug("xfer_size=%d, upload_bytes=%d, upload_size=%d!\n",
761 	      xfer_size, upload_bytes, upload_size);
762 
763 	if (remain_size <= 0) {
764 		fastboot_func->in_req->complete = fastboot_complete;
765 		fastboot_tx_write_str("OKAY");
766 		printf("\nuploading of %d bytes finished\n", upload_bytes);
767 		upload_bytes = 0;
768 		upload_size = 0;
769 		start_upload = false;
770 		return;
771 	}
772 
773 	/* Remove the transfer callback which response the upload */
774 	/* request from host */
775 	if (!upload_bytes)
776 		start_upload = true;
777 
778 	fastboot_tx_write((char *)(CONFIG_FASTBOOT_BUF_ADDR + upload_bytes),
779 			  xfer_size);
780 }
781 
782 static void cb_upload(struct usb_ep *ep, struct usb_request *req)
783 {
784 	char response[FASTBOOT_RESPONSE_LEN];
785 
786 
787 
788 	printf("Starting upload of %d bytes\n", upload_size);
789 
790 	if (0 == upload_size) {
791 		strcpy(response, "FAILdata invalid size");
792 	} else {
793 		start_upload = false;
794 		sprintf(response, "DATA%08x", upload_size);
795 		fastboot_func->in_req->complete = tx_handler_ul;
796 	}
797 
798 	fastboot_tx_write_str(response);
799 }
800 
801 static void do_bootm_on_complete(struct usb_ep *ep, struct usb_request *req)
802 {
803 	char boot_addr_start[12];
804 	char *bootm_args[] = { "bootm", boot_addr_start, NULL };
805 
806 	puts("Booting kernel..\n");
807 
808 	sprintf(boot_addr_start, "0x%lx", (long)CONFIG_FASTBOOT_BUF_ADDR);
809 	do_bootm(NULL, 0, 2, bootm_args);
810 
811 	/* This only happens if image is somehow faulty so we start over */
812 	do_reset(NULL, 0, 0, NULL);
813 }
814 
815 static void cb_boot(struct usb_ep *ep, struct usb_request *req)
816 {
817 	fastboot_func->in_req->complete = do_bootm_on_complete;
818 	fastboot_tx_write_str("OKAY");
819 }
820 
821 static void do_exit_on_complete(struct usb_ep *ep, struct usb_request *req)
822 {
823 	g_dnl_trigger_detach();
824 }
825 
826 static void cb_continue(struct usb_ep *ep, struct usb_request *req)
827 {
828 	fastboot_func->in_req->complete = do_exit_on_complete;
829 	fastboot_tx_write_str("OKAY");
830 }
831 
832 static void cb_set_active(struct usb_ep *ep, struct usb_request *req)
833 {
834 	char *cmd = req->buf;
835 
836 	debug("%s: %s\n", __func__, cmd);
837 
838 	strsep(&cmd, ":");
839 	if (!cmd) {
840 		pr_err("missing slot name");
841 		fastboot_tx_write_str("FAIL: missing slot name");
842 		return;
843 	}
844 #ifdef CONFIG_AVB_LIBAVB_USER
845 	unsigned int slot_number;
846 	if (strncmp("a", cmd, 1) == 0) {
847 		slot_number = 0;
848 		avb_set_slot_active(&slot_number);
849 	} else if (strncmp("b", cmd, 1) == 0) {
850 		slot_number = 1;
851 		avb_set_slot_active(&slot_number);
852 	} else {
853 		fastboot_tx_write_str("FAIL: unkown slot name");
854 		return;
855 	}
856 
857 	fastboot_tx_write_str("OKAY");
858 	return;
859 #else
860 	fastboot_tx_write_str("FAILnot implemented");
861 	return;
862 #endif
863 }
864 
865 #ifdef CONFIG_FASTBOOT_FLASH
866 static void cb_flash(struct usb_ep *ep, struct usb_request *req)
867 {
868 	char *cmd = req->buf;
869 	char response[FASTBOOT_RESPONSE_LEN] = {0};
870 #ifdef CONFIG_AVB_LIBAVB_USER
871 	uint8_t flash_lock_state;
872 
873 	if (avb_read_flash_lock_state(&flash_lock_state)) {
874 		fastboot_tx_write_str("FAIL");
875 		return;
876 	}
877 
878 	if (flash_lock_state == 0) {
879 		fastboot_tx_write_str("FAILThe device is locked, can not flash!");
880 		printf("The device is locked, can not flash!\n");
881 		return;
882 	}
883 #endif
884 	strsep(&cmd, ":");
885 	if (!cmd) {
886 		pr_err("missing partition name");
887 		fastboot_tx_write_str("FAILmissing partition name");
888 		return;
889 	}
890 
891 	fastboot_fail("no flash device defined", response);
892 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
893 	fb_mmc_flash_write(cmd, (void *)CONFIG_FASTBOOT_BUF_ADDR,
894 				download_bytes, response);
895 #endif
896 #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
897 	fb_nand_flash_write(cmd, (void *)CONFIG_FASTBOOT_BUF_ADDR,
898 				download_bytes, response);
899 #endif
900 	fastboot_tx_write_str(response);
901 }
902 
903 static void cb_flashing(struct usb_ep *ep, struct usb_request *req)
904 {
905 	char *cmd = req->buf;
906 
907 	if (strncmp("lock", cmd + 9, 4) == 0) {
908 #ifdef CONFIG_AVB_LIBAVB_USER
909 		uint8_t flash_lock_state;
910 		flash_lock_state = 0;
911 		if (avb_write_flash_lock_state(flash_lock_state))
912 			fastboot_tx_write_str("FAIL");
913 		else
914 			fastboot_tx_write_str("OKAY");
915 #else
916 		fastboot_tx_write_str("FAILnot implemented");
917 #endif
918 	} else if (strncmp("unlock", cmd + 9, 6) == 0) {
919 #ifdef CONFIG_AVB_LIBAVB_USER
920 		uint8_t flash_lock_state;
921 		flash_lock_state = 1;
922 		if (avb_write_flash_lock_state(flash_lock_state))
923 			fastboot_tx_write_str("FAIL");
924 		else
925 			fastboot_tx_write_str("OKAY");
926 #else
927 		fastboot_tx_write_str("FAILnot implemented");
928 #endif
929 	} else if (strncmp("lock_critical", cmd + 9, 12) == 0) {
930 		fastboot_tx_write_str("FAILnot implemented");
931 	} else if (strncmp("unlock_critical", cmd + 9, 14) == 0) {
932 		fastboot_tx_write_str("FAILnot implemented");
933 	} else if (strncmp("get_unlock_ability", cmd + 9, 17) == 0) {
934 		fastboot_tx_write_str("FAILnot implemented");
935 	} else if (strncmp("get_unlock_bootloader_nonce", cmd + 4, 27) == 0) {
936 		fastboot_tx_write_str("FAILnot implemented");
937 	} else if (strncmp("unlock_bootloader", cmd + 9, 17) == 0) {
938 		fastboot_tx_write_str("FAILnot implemented");
939 	} else if (strncmp("lock_bootloader", cmd + 9, 15) == 0) {
940 		fastboot_tx_write_str("FAILnot implemented");
941 	} else {
942 		fastboot_tx_write_str("FAILunknown flashing command");
943 	}
944 }
945 #endif
946 
947 static void cb_oem(struct usb_ep *ep, struct usb_request *req)
948 {
949 	char *cmd = req->buf;
950 
951 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
952 	if (strncmp("format", cmd + 4, 6) == 0) {
953 		char cmdbuf[32];
954                 sprintf(cmdbuf, "gpt write mmc %x $partitions",
955 			CONFIG_FASTBOOT_FLASH_MMC_DEV);
956                 if (run_command(cmdbuf, 0))
957 			fastboot_tx_write_str("FAIL");
958                 else
959 			fastboot_tx_write_str("OKAY");
960 	} else
961 #endif
962 	if (strncmp("unlock", cmd + 4, 8) == 0) {
963 		fastboot_tx_write_str("FAILnot implemented");
964 	} else if (strncmp("at-get-ca-request", cmd + 4, 17) == 0) {
965 #ifdef CONFIG_OPTEE_CLIENT
966 		uint8_t operation_start[128];
967 		uint8_t out[256];
968 		uint32_t operation_size = download_bytes;
969 		uint32_t out_len = 256;
970 		uint32_t res = 0;
971 		memcpy(operation_start, (void *)CONFIG_FASTBOOT_BUF_ADDR, download_bytes);
972 		res = trusty_attest_get_ca(operation_start, &operation_size, out, &out_len);
973 		if (res) {
974 			fastboot_tx_write_str("FAILtrusty_attest_get_ca failed");
975 			return;
976 		}
977 		upload_size = out_len;
978 		memcpy((void *)CONFIG_FASTBOOT_BUF_ADDR, out, out_len);
979 		fastboot_tx_write_str("OKAY");
980 #else
981 		fastboot_tx_write_str("FAILnot implemented");
982 		return;
983 #endif
984 	} else if (strncmp("at-set-ca-response", cmd + 4, 18) == 0) {
985 #ifdef CONFIG_OPTEE_CLIENT
986 		uint8_t ca_response[8*1024];
987 		uint32_t ca_response_size = download_bytes;
988 		uint32_t res = 0;
989 		memcpy(ca_response, (void *)CONFIG_FASTBOOT_BUF_ADDR, download_bytes);
990 		res = trusty_attest_set_ca(ca_response, &ca_response_size);
991 		if (res) {
992 			fastboot_tx_write_str("FAILtrusty_attest_set_ca failed");
993 		} else {
994 			fastboot_tx_write_str("OKAY");
995 		}
996 #else
997 		fastboot_tx_write_str("FAILnot implemented");
998 		return;
999 #endif
1000 	} else if (strncmp("at-lock-vboot", cmd + 4, 13) == 0) {
1001 #ifdef CONFIG_AVB_LIBAVB_USER
1002 		uint8_t lock_state;
1003 		lock_state = 0;
1004 		if (avb_write_lock_state(lock_state))
1005 			fastboot_tx_write_str("FAIL");
1006 		else
1007 			fastboot_tx_write_str("OKAY");
1008 #else
1009 		fastboot_tx_write_str("FAILnot implemented");
1010 #endif
1011 	} else if (strncmp("at-unlock-vboot", cmd + 4, 15) == 0) {
1012 #ifdef CONFIG_AVB_LIBAVB_USER
1013 		uint8_t lock_state;
1014 		if (avb_read_lock_state(&lock_state))
1015 			fastboot_tx_write_str("FAIL");
1016 		if (lock_state >> 1 == 1) {
1017 			fastboot_tx_write_str("FAILThe vboot is disable!");
1018 		} else {
1019 			lock_state = 1;
1020 			if (avb_write_lock_state(lock_state))
1021 				fastboot_tx_write_str("FAIL");
1022 			else
1023 				fastboot_tx_write_str("OKAY");
1024 		}
1025 #else
1026 		fastboot_tx_write_str("FAILnot implemented");
1027 #endif
1028 	} else if (strncmp("at-disable-unlock-vboot", cmd + 4, 23) == 0) {
1029 #ifdef CONFIG_AVB_LIBAVB_USER
1030 		uint8_t lock_state;
1031 		lock_state = 2;
1032 		if (avb_write_lock_state(lock_state))
1033 			fastboot_tx_write_str("FAIL");
1034 		else
1035 			fastboot_tx_write_str("OKAY");
1036 #else
1037 		fastboot_tx_write_str("FAILnot implemented");
1038 #endif
1039 	} else if (strncmp("fuse at-perm-attr", cmd + 4, 16) == 0) {
1040 #ifdef CONFIG_AVB_LIBAVB_USER
1041 		if (PERM_ATTR_TOTAL_SIZE != download_bytes) {
1042 			printf("Permanent attribute size is not equal!\n");
1043 			fastboot_tx_write_str("FAIL");
1044 			return;
1045 		}
1046 
1047 		if (avb_write_permanent_attributes((uint8_t *)
1048 					       CONFIG_FASTBOOT_BUF_ADDR,
1049 					       download_bytes
1050 					       - PERM_ATTR_DIGEST_SIZE)) {
1051 			fastboot_tx_write_str("FAIL");
1052 			return;
1053 		}
1054 
1055 		if (avb_write_attribute_hash((uint8_t *)
1056 					     (CONFIG_FASTBOOT_BUF_ADDR
1057 					     + download_bytes
1058 					     - PERM_ATTR_DIGEST_SIZE),
1059 					     PERM_ATTR_DIGEST_SIZE)) {
1060 			fastboot_tx_write_str("FAIL");
1061 			return;
1062 		}
1063 
1064 		if (avb_write_perm_attr_flag(1)) {
1065 			fastboot_tx_write_str("FAIL");
1066 			return;
1067 		}
1068 
1069 		fastboot_tx_write_str("OKAY");
1070 #else
1071 		fastboot_tx_write_str("FAILnot implemented");
1072 #endif
1073 	} else if (strncmp("fuse at-bootloader-vboot-key", cmd + 4, 27) == 0) {
1074 #ifdef CONFIG_AVB_LIBAVB_USER
1075 		if (download_bytes != VBOOT_KEY_HASH_SIZE) {
1076 			fastboot_tx_write_str("FAIL");
1077 			printf("The vboot key size error!\n");
1078 		}
1079 
1080 		if (avb_write_vbootkey_hash((uint8_t *)
1081 					    CONFIG_FASTBOOT_BUF_ADDR,
1082 					    VBOOT_KEY_HASH_SIZE)) {
1083 			fastboot_tx_write_str("FAIL");
1084 			return;
1085 		}
1086 		fastboot_tx_write_str("OKAY");
1087 #else
1088 		fastboot_tx_write_str("FAILnot implemented");
1089 #endif
1090 	} else {
1091 		fastboot_tx_write_str("FAILunknown oem command");
1092 	}
1093 }
1094 
1095 #ifdef CONFIG_FASTBOOT_FLASH
1096 static void cb_erase(struct usb_ep *ep, struct usb_request *req)
1097 {
1098 	char *cmd = req->buf;
1099 	char response[FASTBOOT_RESPONSE_LEN];
1100 
1101 	strsep(&cmd, ":");
1102 	if (!cmd) {
1103 		pr_err("missing partition name");
1104 		fastboot_tx_write_str("FAILmissing partition name");
1105 		return;
1106 	}
1107 
1108 	fastboot_fail("no flash device defined", response);
1109 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
1110 	fb_mmc_erase(cmd, response);
1111 #endif
1112 #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
1113 	fb_nand_erase(cmd, response);
1114 #endif
1115 	fastboot_tx_write_str(response);
1116 }
1117 #endif
1118 
1119 struct cmd_dispatch_info {
1120 	char *cmd;
1121 	void (*cb)(struct usb_ep *ep, struct usb_request *req);
1122 };
1123 
1124 static const struct cmd_dispatch_info cmd_dispatch_info[] = {
1125 	{
1126 		.cmd = "reboot",
1127 		.cb = cb_reboot,
1128 	}, {
1129 		.cmd = "getvar:",
1130 		.cb = cb_getvar,
1131 	}, {
1132 		.cmd = "download:",
1133 		.cb = cb_download,
1134 	}, {
1135 		.cmd = "upload",
1136 		.cb = cb_upload,
1137 	}, {
1138 		.cmd = "boot",
1139 		.cb = cb_boot,
1140 	}, {
1141 		.cmd = "continue",
1142 		.cb = cb_continue,
1143 	}, {
1144 		.cmd = "set_active",
1145 		.cb = cb_set_active,
1146 	},
1147 #ifdef CONFIG_FASTBOOT_FLASH
1148 	{
1149 		.cmd = "flashing",
1150 		.cb = cb_flashing,
1151 	},
1152 	{
1153 		.cmd = "flash",
1154 		.cb = cb_flash,
1155 	}, {
1156 		.cmd = "erase",
1157 		.cb = cb_erase,
1158 	},
1159 #endif
1160 	{
1161 		.cmd = "oem",
1162 		.cb = cb_oem,
1163 	},
1164 };
1165 
1166 static void rx_handler_command(struct usb_ep *ep, struct usb_request *req)
1167 {
1168 	char *cmdbuf = req->buf;
1169 	void (*func_cb)(struct usb_ep *ep, struct usb_request *req) = NULL;
1170 	int i;
1171 
1172 	if (req->status != 0 || req->length == 0)
1173 		return;
1174 
1175 	for (i = 0; i < ARRAY_SIZE(cmd_dispatch_info); i++) {
1176 		if (!strcmp_l1(cmd_dispatch_info[i].cmd, cmdbuf)) {
1177 			func_cb = cmd_dispatch_info[i].cb;
1178 			break;
1179 		}
1180 	}
1181 
1182 	if (!func_cb) {
1183 		pr_err("unknown command: %.*s", req->actual, cmdbuf);
1184 		fastboot_tx_write_str("FAILunknown command");
1185 	} else {
1186 		if (req->actual < req->length) {
1187 			u8 *buf = (u8 *)req->buf;
1188 			buf[req->actual] = 0;
1189 			func_cb(ep, req);
1190 		} else {
1191 			pr_err("buffer overflow");
1192 			fastboot_tx_write_str("FAILbuffer overflow");
1193 		}
1194 	}
1195 
1196 	*cmdbuf = '\0';
1197 	req->actual = 0;
1198 	usb_ep_queue(ep, req, 0);
1199 }
1200