xref: /OK3568_Linux_fs/u-boot/drivers/usb/gadget/f_fastboot.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
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 <console.h>
16 #include <android_bootloader.h>
17 #include <errno.h>
18 #include <fastboot.h>
19 #include <malloc.h>
20 #include <linux/usb/ch9.h>
21 #include <linux/usb/gadget.h>
22 #include <linux/usb/composite.h>
23 #include <linux/compiler.h>
24 #include <u-boot/sha256.h>
25 #include <version.h>
26 #include <g_dnl.h>
27 #include <fs.h>
28 #include <android_avb/avb_ops_user.h>
29 #include <android_avb/rk_avb_ops_user.h>
30 #include <dm/uclass.h>
31 #include <power/fuel_gauge.h>
32 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
33 #include <fb_mmc.h>
34 #endif
35 #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
36 #include <fb_nand.h>
37 #endif
38 #ifdef CONFIG_OPTEE_CLIENT
39 #include <optee_include/OpteeClientInterface.h>
40 #endif
41 #include <boot_rkimg.h>
42 #include <optee_include/tee_client_api.h>
43 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
44 #include <keymaster.h>
45 #endif
46 #ifdef CONFIG_ANDROID_AB
47 #include <android_ab.h>
48 #endif
49 
50 #define FASTBOOT_VERSION		"0.4"
51 
52 #define FASTBOOT_INTERFACE_CLASS	0xff
53 #define FASTBOOT_INTERFACE_SUB_CLASS	0x42
54 #define FASTBOOT_INTERFACE_PROTOCOL	0x03
55 
56 #define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_2_0  (0x0200)
57 #define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_1_1  (0x0040)
58 #define TX_ENDPOINT_MAXIMUM_PACKET_SIZE      (0x0040)
59 
60 #define EP_BUFFER_SIZE			4096
61 #define SLEEP_COUNT 20000
62 #define MAX_PART_NUM_STR_SIZE 4
63 #define PARTITION_TYPE_STRINGS "partition-type"
64 
65 /*
66  * EP_BUFFER_SIZE must always be an integral multiple of maxpacket size
67  * (64 or 512 or 1024), else we break on certain controllers like DWC3
68  * that expect bulk OUT requests to be divisible by maxpacket size.
69  */
70 
71 struct f_fastboot {
72 	struct usb_function usb_function;
73 
74 	/* IN/OUT EP's and corresponding requests */
75 	struct usb_ep *in_ep, *out_ep;
76 	struct usb_request *in_req, *out_req;
77 };
78 
func_to_fastboot(struct usb_function * f)79 static inline struct f_fastboot *func_to_fastboot(struct usb_function *f)
80 {
81 	return container_of(f, struct f_fastboot, usb_function);
82 }
83 
84 static struct f_fastboot *fastboot_func;
85 static unsigned int download_size;
86 static unsigned int download_bytes;
87 static unsigned int upload_size;
88 static unsigned int upload_bytes;
89 static bool start_upload;
90 static unsigned intthread_wakeup_needed;
91 
92 static struct usb_endpoint_descriptor fs_ep_in = {
93 	.bLength            = USB_DT_ENDPOINT_SIZE,
94 	.bDescriptorType    = USB_DT_ENDPOINT,
95 	.bEndpointAddress   = USB_DIR_IN,
96 	.bmAttributes       = USB_ENDPOINT_XFER_BULK,
97 	.wMaxPacketSize     = cpu_to_le16(64),
98 };
99 
100 static struct usb_endpoint_descriptor fs_ep_out = {
101 	.bLength		= USB_DT_ENDPOINT_SIZE,
102 	.bDescriptorType	= USB_DT_ENDPOINT,
103 	.bEndpointAddress	= USB_DIR_OUT,
104 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
105 	.wMaxPacketSize		= cpu_to_le16(64),
106 };
107 
108 static struct usb_endpoint_descriptor hs_ep_in = {
109 	.bLength		= USB_DT_ENDPOINT_SIZE,
110 	.bDescriptorType	= USB_DT_ENDPOINT,
111 	.bEndpointAddress	= USB_DIR_IN,
112 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
113 	.wMaxPacketSize		= cpu_to_le16(512),
114 };
115 
116 static struct usb_endpoint_descriptor hs_ep_out = {
117 	.bLength		= USB_DT_ENDPOINT_SIZE,
118 	.bDescriptorType	= USB_DT_ENDPOINT,
119 	.bEndpointAddress	= USB_DIR_OUT,
120 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
121 	.wMaxPacketSize		= cpu_to_le16(512),
122 };
123 
124 static struct usb_endpoint_descriptor ss_ep_in = {
125 	.bLength		= USB_DT_ENDPOINT_SIZE,
126 	.bDescriptorType	= USB_DT_ENDPOINT,
127 	.bEndpointAddress	= USB_DIR_IN,
128 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
129 	.wMaxPacketSize		= cpu_to_le16(1024),
130 };
131 
132 static struct usb_ss_ep_comp_descriptor ss_ep_in_comp_desc = {
133 	.bLength		= sizeof(ss_ep_in_comp_desc),
134 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
135 	/* .bMaxBurst		= DYNAMIC, */
136 };
137 
138 static struct usb_endpoint_descriptor ss_ep_out = {
139 	.bLength		= USB_DT_ENDPOINT_SIZE,
140 	.bDescriptorType	= USB_DT_ENDPOINT,
141 	.bEndpointAddress	= USB_DIR_OUT,
142 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
143 	.wMaxPacketSize		= cpu_to_le16(1024),
144 };
145 
146 static struct usb_ss_ep_comp_descriptor ss_ep_out_comp_desc = {
147 	.bLength		= sizeof(ss_ep_out_comp_desc),
148 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
149 	/* .bMaxBurst		= DYNAMIC, */
150 };
151 
152 static struct usb_interface_descriptor interface_desc = {
153 	.bLength		= USB_DT_INTERFACE_SIZE,
154 	.bDescriptorType	= USB_DT_INTERFACE,
155 	.bInterfaceNumber	= 0x00,
156 	.bAlternateSetting	= 0x00,
157 	.bNumEndpoints		= 0x02,
158 	.bInterfaceClass	= FASTBOOT_INTERFACE_CLASS,
159 	.bInterfaceSubClass	= FASTBOOT_INTERFACE_SUB_CLASS,
160 	.bInterfaceProtocol	= FASTBOOT_INTERFACE_PROTOCOL,
161 };
162 
163 static struct usb_descriptor_header *fb_fs_function[] = {
164 	(struct usb_descriptor_header *)&interface_desc,
165 	(struct usb_descriptor_header *)&fs_ep_in,
166 	(struct usb_descriptor_header *)&fs_ep_out,
167 };
168 
169 static struct usb_descriptor_header *fb_hs_function[] = {
170 	(struct usb_descriptor_header *)&interface_desc,
171 	(struct usb_descriptor_header *)&hs_ep_in,
172 	(struct usb_descriptor_header *)&hs_ep_out,
173 	NULL,
174 };
175 
176 static struct usb_descriptor_header *fb_ss_function[] = {
177 	(struct usb_descriptor_header *)&interface_desc,
178 	(struct usb_descriptor_header *)&ss_ep_in,
179 	(struct usb_descriptor_header *)&ss_ep_in_comp_desc,
180 	(struct usb_descriptor_header *)&ss_ep_out,
181 	(struct usb_descriptor_header *)&ss_ep_out_comp_desc,
182 	NULL,
183 };
184 
185 static struct usb_endpoint_descriptor *
fb_ep_desc(struct usb_gadget * g,struct usb_endpoint_descriptor * fs,struct usb_endpoint_descriptor * hs,struct usb_endpoint_descriptor * ss,struct usb_ss_ep_comp_descriptor * comp_desc,struct usb_ep * ep)186 fb_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
187 	   struct usb_endpoint_descriptor *hs,
188 	   struct usb_endpoint_descriptor *ss,
189 	   struct usb_ss_ep_comp_descriptor *comp_desc,
190 	   struct usb_ep *ep)
191 {
192 	struct usb_endpoint_descriptor *speed_desc = NULL;
193 
194 	/* select desired speed */
195 	switch (g->speed) {
196 	case USB_SPEED_SUPER:
197 		if (gadget_is_superspeed(g)) {
198 			speed_desc = ss;
199 			ep->comp_desc = comp_desc;
200 			break;
201 		}
202 		/* else: Fall trough */
203 	case USB_SPEED_HIGH:
204 		if (gadget_is_dualspeed(g)) {
205 			speed_desc = hs;
206 			break;
207 		}
208 		/* else: fall through */
209 	default:
210 		speed_desc = fs;
211 	}
212 
213 	return speed_desc;
214 }
215 
216 /*
217  * static strings, in UTF-8
218  */
219 static const char fastboot_name[] = "Android Fastboot";
220 
221 static struct usb_string fastboot_string_defs[] = {
222 	[0].s = fastboot_name,
223 	{  }			/* end of list */
224 };
225 
226 static struct usb_gadget_strings stringtab_fastboot = {
227 	.language	= 0x0409,	/* en-us */
228 	.strings	= fastboot_string_defs,
229 };
230 
231 static struct usb_gadget_strings *fastboot_strings[] = {
232 	&stringtab_fastboot,
233 	NULL,
234 };
235 
236 static void rx_handler_command(struct usb_ep *ep, struct usb_request *req);
237 static int strcmp_l1(const char *s1, const char *s2);
wakeup_thread(void)238 static void wakeup_thread(void)
239 {
240 	intthread_wakeup_needed = false;
241 }
242 
busy_indicator(void)243 static void busy_indicator(void)
244 {
245 	static int state;
246 
247 	switch (state) {
248 	case 0:
249 		puts("\r|"); break;
250 	case 1:
251 		puts("\r/"); break;
252 	case 2:
253 		puts("\r-"); break;
254 	case 3:
255 		puts("\r\\"); break;
256 	case 4:
257 		puts("\r|"); break;
258 	case 5:
259 		puts("\r/"); break;
260 	case 6:
261 		puts("\r-"); break;
262 	case 7:
263 		puts("\r\\"); break;
264 	default:
265 		state = 0;
266 	}
267 	if (state++ == 8)
268 		state = 0;
269 }
270 
fb_get_fstype(const char * ifname,const int part_num,const char ** fs_type)271 static int fb_get_fstype(const char *ifname, const int part_num,
272 			 const char **fs_type)
273 {
274 	char part_num_str[MAX_PART_NUM_STR_SIZE] = {0};
275 
276 	snprintf(part_num_str, ARRAY_SIZE(part_num_str), ":%x", part_num);
277 
278 	if (fs_set_blk_dev(ifname, part_num_str, FS_TYPE_ANY))
279 		return -1;
280 
281 	if (fs_get_fstype(fs_type))
282 		return -1;
283 
284 	return 0;
285 }
286 
sleep_thread(void)287 static int sleep_thread(void)
288 {
289 	int rc = 0;
290 	int i = 0, k = 0;
291 
292 	/* Wait until a signal arrives or we are woken up */
293 	for (;;) {
294 		if (!intthread_wakeup_needed)
295 			break;
296 
297 		if (++i == SLEEP_COUNT) {
298 			busy_indicator();
299 			i = 0;
300 			k++;
301 		}
302 
303 		if (k == 10) {
304 			/* Handle CTRL+C */
305 			if (ctrlc())
306 				return -EPIPE;
307 
308 			/* Check cable connection */
309 			if (!g_dnl_board_usb_cable_connected())
310 				return -EIO;
311 
312 			k = 0;
313 		}
314 
315 		usb_gadget_handle_interrupts(0);
316 	}
317 	intthread_wakeup_needed = true;
318 	return rc;
319 }
320 
fastboot_complete(struct usb_ep * ep,struct usb_request * req)321 static void fastboot_complete(struct usb_ep *ep, struct usb_request *req)
322 {
323 	int status = req->status;
324 
325 	wakeup_thread();
326 	if (!status)
327 		return;
328 	printf("status: %d ep '%s' trans: %d\n", status, ep->name, req->actual);
329 }
330 
fastboot_bind(struct usb_configuration * c,struct usb_function * f)331 static int fastboot_bind(struct usb_configuration *c, struct usb_function *f)
332 {
333 	int id;
334 	struct usb_gadget *gadget = c->cdev->gadget;
335 	struct f_fastboot *f_fb = func_to_fastboot(f);
336 	const char *s;
337 
338 	/* DYNAMIC interface numbers assignments */
339 	id = usb_interface_id(c, f);
340 	if (id < 0)
341 		return id;
342 	interface_desc.bInterfaceNumber = id;
343 
344 	id = usb_string_id(c->cdev);
345 	if (id < 0)
346 		return id;
347 	fastboot_string_defs[0].id = id;
348 	interface_desc.iInterface = id;
349 
350 	f_fb->in_ep = usb_ep_autoconfig(gadget, &fs_ep_in);
351 	if (!f_fb->in_ep)
352 		return -ENODEV;
353 	f_fb->in_ep->driver_data = c->cdev;
354 
355 	f_fb->out_ep = usb_ep_autoconfig(gadget, &fs_ep_out);
356 	if (!f_fb->out_ep)
357 		return -ENODEV;
358 	f_fb->out_ep->driver_data = c->cdev;
359 
360 	f->descriptors = fb_fs_function;
361 
362 	if (gadget_is_dualspeed(gadget)) {
363 		/* Assume endpoint addresses are the same for both speeds */
364 		hs_ep_in.bEndpointAddress = fs_ep_in.bEndpointAddress;
365 		hs_ep_out.bEndpointAddress = fs_ep_out.bEndpointAddress;
366 		/* copy HS descriptors */
367 		f->hs_descriptors = fb_hs_function;
368 	}
369 
370 	if (gadget_is_superspeed(gadget)) {
371 		/* Assume endpoint addresses are the same as full speed */
372 		ss_ep_in.bEndpointAddress = fs_ep_in.bEndpointAddress;
373 		ss_ep_out.bEndpointAddress = fs_ep_out.bEndpointAddress;
374 		/* copy SS descriptors */
375 		f->ss_descriptors = fb_ss_function;
376 	}
377 
378 	s = env_get("serial#");
379 	if (s)
380 		g_dnl_set_serialnumber((char *)s);
381 
382 	return 0;
383 }
384 
fastboot_unbind(struct usb_configuration * c,struct usb_function * f)385 static void fastboot_unbind(struct usb_configuration *c, struct usb_function *f)
386 {
387 	memset(fastboot_func, 0, sizeof(*fastboot_func));
388 }
389 
fastboot_disable(struct usb_function * f)390 static void fastboot_disable(struct usb_function *f)
391 {
392 	struct f_fastboot *f_fb = func_to_fastboot(f);
393 
394 	usb_ep_disable(f_fb->out_ep);
395 	usb_ep_disable(f_fb->in_ep);
396 
397 	if (f_fb->out_req) {
398 		free(f_fb->out_req->buf);
399 		usb_ep_free_request(f_fb->out_ep, f_fb->out_req);
400 		f_fb->out_req = NULL;
401 	}
402 	if (f_fb->in_req) {
403 		free(f_fb->in_req->buf);
404 		usb_ep_free_request(f_fb->in_ep, f_fb->in_req);
405 		f_fb->in_req = NULL;
406 	}
407 }
408 
fastboot_start_ep(struct usb_ep * ep)409 static struct usb_request *fastboot_start_ep(struct usb_ep *ep)
410 {
411 	struct usb_request *req;
412 
413 	req = usb_ep_alloc_request(ep, 0);
414 	if (!req)
415 		return NULL;
416 
417 	req->length = EP_BUFFER_SIZE;
418 	req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, EP_BUFFER_SIZE);
419 	if (!req->buf) {
420 		usb_ep_free_request(ep, req);
421 		return NULL;
422 	}
423 
424 	memset(req->buf, 0, req->length);
425 	return req;
426 }
427 
fastboot_set_alt(struct usb_function * f,unsigned interface,unsigned alt)428 static int fastboot_set_alt(struct usb_function *f,
429 			    unsigned interface, unsigned alt)
430 {
431 	int ret;
432 	struct usb_composite_dev *cdev = f->config->cdev;
433 	struct usb_gadget *gadget = cdev->gadget;
434 	struct f_fastboot *f_fb = func_to_fastboot(f);
435 	const struct usb_endpoint_descriptor *d;
436 
437 	debug("%s: func: %s intf: %d alt: %d\n",
438 	      __func__, f->name, interface, alt);
439 
440 	d = fb_ep_desc(gadget, &fs_ep_out, &hs_ep_out, &ss_ep_out,
441 		       &ss_ep_out_comp_desc, f_fb->out_ep);
442 	ret = usb_ep_enable(f_fb->out_ep, d);
443 	if (ret) {
444 		puts("failed to enable out ep\n");
445 		return ret;
446 	}
447 
448 	f_fb->out_req = fastboot_start_ep(f_fb->out_ep);
449 	if (!f_fb->out_req) {
450 		puts("failed to alloc out req\n");
451 		ret = -EINVAL;
452 		goto err;
453 	}
454 	f_fb->out_req->complete = rx_handler_command;
455 
456 	d = fb_ep_desc(gadget, &fs_ep_in, &hs_ep_in, &ss_ep_in,
457 		       &ss_ep_in_comp_desc, f_fb->in_ep);
458 	ret = usb_ep_enable(f_fb->in_ep, d);
459 	if (ret) {
460 		puts("failed to enable in ep\n");
461 		goto err;
462 	}
463 
464 	f_fb->in_req = fastboot_start_ep(f_fb->in_ep);
465 	if (!f_fb->in_req) {
466 		puts("failed alloc req in\n");
467 		ret = -EINVAL;
468 		goto err;
469 	}
470 	f_fb->in_req->complete = fastboot_complete;
471 
472 	ret = usb_ep_queue(f_fb->out_ep, f_fb->out_req, 0);
473 	if (ret)
474 		goto err;
475 
476 	return 0;
477 err:
478 	fastboot_disable(f);
479 	return ret;
480 }
481 
fastboot_add(struct usb_configuration * c)482 static int fastboot_add(struct usb_configuration *c)
483 {
484 	struct f_fastboot *f_fb = fastboot_func;
485 	int status;
486 
487 	debug("%s: cdev: 0x%p\n", __func__, c->cdev);
488 
489 	if (!f_fb) {
490 		f_fb = memalign(CONFIG_SYS_CACHELINE_SIZE, sizeof(*f_fb));
491 		if (!f_fb)
492 			return -ENOMEM;
493 
494 		fastboot_func = f_fb;
495 		memset(f_fb, 0, sizeof(*f_fb));
496 	}
497 
498 	f_fb->usb_function.name = "f_fastboot";
499 	f_fb->usb_function.bind = fastboot_bind;
500 	f_fb->usb_function.unbind = fastboot_unbind;
501 	f_fb->usb_function.set_alt = fastboot_set_alt;
502 	f_fb->usb_function.disable = fastboot_disable;
503 	f_fb->usb_function.strings = fastboot_strings;
504 
505 	status = usb_add_function(c, &f_fb->usb_function);
506 	if (status) {
507 		free(f_fb);
508 		fastboot_func = f_fb;
509 	}
510 
511 	return status;
512 }
513 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_fastboot, fastboot_add);
514 
fastboot_tx_write(const char * buffer,unsigned int buffer_size)515 static int fastboot_tx_write(const char *buffer, unsigned int buffer_size)
516 {
517 	struct usb_request *in_req = fastboot_func->in_req;
518 	int ret;
519 
520 	memcpy(in_req->buf, buffer, buffer_size);
521 	in_req->length = buffer_size;
522 
523 	usb_ep_dequeue(fastboot_func->in_ep, in_req);
524 
525 	ret = usb_ep_queue(fastboot_func->in_ep, in_req, 0);
526 	if (ret)
527 		printf("Error %d on queue\n", ret);
528 	return 0;
529 }
530 
fastboot_tx_write_str(const char * buffer)531 static int fastboot_tx_write_str(const char *buffer)
532 {
533 	int ret;
534 
535 	ret = sleep_thread();
536 	if (ret < 0)
537 		printf("warning: 0x%x, usb transmission is abnormal!\n", ret);
538 
539 	return fastboot_tx_write(buffer, strlen(buffer));
540 }
541 
compl_do_reset(struct usb_ep * ep,struct usb_request * req)542 static void compl_do_reset(struct usb_ep *ep, struct usb_request *req)
543 {
544 	do_reset(NULL, 0, 0, NULL);
545 }
546 
fb_set_reboot_flag(void)547 int __weak fb_set_reboot_flag(void)
548 {
549 	return -ENOSYS;
550 }
551 
cb_reboot(struct usb_ep * ep,struct usb_request * req)552 static void cb_reboot(struct usb_ep *ep, struct usb_request *req)
553 {
554 	char *cmd = req->buf;
555 
556 	if (!strcmp_l1("reboot-bootloader", cmd)) {
557 		if (fb_set_reboot_flag()) {
558 			fastboot_tx_write_str("FAILCannot set reboot flag");
559 			return;
560 		}
561 	}
562 #ifdef CONFIG_ANDROID_BOOTLOADER
563 	if (!strcmp_l1("reboot-fastboot", cmd)) {
564 		if (android_bcb_write("boot-fastboot")) {
565 			fastboot_tx_write_str("FAILCannot set boot-fastboot");
566 			return;
567 		}
568 	}
569 
570 	if (!strcmp_l1("reboot-recovery", cmd)) {
571 		if (android_bcb_write("boot-recovery")) {
572 			fastboot_tx_write_str("FAILCannot set boot-recovery");
573 			return;
574 		}
575 	}
576 #endif
577 	fastboot_func->in_req->complete = compl_do_reset;
578 	fastboot_tx_write_str("OKAY");
579 }
580 
strcmp_l1(const char * s1,const char * s2)581 static int strcmp_l1(const char *s1, const char *s2)
582 {
583 	if (!s1 || !s2)
584 		return -1;
585 	return strncmp(s1, s2, strlen(s1));
586 }
587 
588 struct name_string {
589 	const char *str;
590 	int expects_args;
591 	char delim;
592 };
593 
594 #define NAME_NO_ARGS(s)	{.str = s, .expects_args = 0}
595 #define NAME_ARGS(s, d)	{.str = s, .expects_args = 1, .delim = d}
596 
name_check_match(const char * str,size_t len,const struct name_string * name)597 static size_t name_check_match(const char *str, size_t len,
598 			       const struct name_string *name)
599 {
600 	size_t str_len = strlen(name->str);
601 
602 	/* If name len is greater than input, return 0. */
603 	if (str_len > len)
604 		return 0;
605 
606 	/* If name str does not match input string, return 0. */
607 	if (memcmp(name->str, str, str_len))
608 		return 0;
609 
610 	if (name->expects_args) {
611 		/* string should have space for delim */
612 		if (len == str_len)
613 			return 0;
614 
615 		/* Check delim match */
616 		if (name->delim != str[str_len])
617 			return 0;
618 	} else {
619 		/* Name str len should match input len */
620 		if (str_len != len)
621 			return 0;
622 	}
623 
624 	return str_len + name->expects_args;
625 }
626 
fb_add_string(char * dst,size_t chars_left,const char * str,const char * args)627 static void fb_add_string(char *dst, size_t chars_left,
628 			  const char *str, const char *args)
629 {
630 	if (!str)
631 		return;
632 
633 	int ret = snprintf(dst, chars_left, str, args);
634 
635 	if (ret < 0)
636 		pr_err("snprintf is error!");
637 }
638 
fb_add_number(char * dst,size_t chars_left,const char * format,size_t num)639 static void fb_add_number(char *dst, size_t chars_left,
640 			  const char *format, size_t num)
641 {
642 	if (!format)
643 		return;
644 
645 	int ret = snprintf(dst, chars_left, format, num);
646 
647 	if (ret > chars_left)
648 		pr_err("snprintf is error!");
649 }
650 
fb_read_var(char * cmd,char * response,fb_getvar_t var,size_t chars_left)651 static int fb_read_var(char *cmd, char *response,
652 		       fb_getvar_t var, size_t chars_left)
653 {
654 	const char *s;
655 	int ret = 0;
656 
657 	switch (var) {
658 	case FB_VERSION:
659 		fb_add_string(response, chars_left, FASTBOOT_VERSION, NULL);
660 		break;
661 	case FB_BOOTLOADER_VERSION:
662 		fb_add_string(response, chars_left, U_BOOT_VERSION, NULL);
663 		break;
664 	case FB_BASEBAND_VERSION:
665 		fb_add_string(response, chars_left, "N/A", NULL);
666 		break;
667 	case FB_PRODUCT:
668 		fb_add_string(response, chars_left, CONFIG_SYS_BOARD, NULL);
669 		break;
670 	case FB_SERIAL_NO:
671 		s = env_get("serial#");
672 		if (s)
673 			fb_add_string(response, chars_left, s, NULL);
674 		else
675 			ret = -1;
676 		break;
677 	case FB_SECURE:
678 		fb_add_string(response, chars_left, "yes", NULL);
679 		break;
680 	case FB_VARIANT:
681 		fb_add_string(response, chars_left, "userdebug", NULL);
682 		break;
683 	case FB_DWNLD_SIZE:
684 		fb_add_number(response, chars_left, "0x%08x",
685 			      CONFIG_FASTBOOT_BUF_SIZE);
686 		break;
687 	case FB_PART_SIZE:
688 	case FB_PART_TYPE: {
689 		char *part_name = cmd;
690 
691 		cmd = strsep(&part_name, ":");
692 		if (!cmd || !part_name) {
693 			fb_add_string(response, chars_left,
694 				      "argument Invalid!", NULL);
695 			ret = -1;
696 			break;
697 		}
698 
699 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
700 		disk_partition_t part_info;
701 		struct blk_desc *dev_desc;
702 		int part_num = -1;
703 		const char *fs_type = NULL;
704 
705 #ifdef CONFIG_RKIMG_BOOTLOADER
706 		dev_desc = rockchip_get_bootdev();
707 #else
708 		dev_desc = NULL;
709 #endif
710 		if (!dev_desc) {
711 			fb_add_string(response, chars_left,
712 				      "block device not found", NULL);
713 			ret = -1;
714 			break;
715 		}
716 
717 		part_num = part_get_info_by_name(dev_desc, part_name,
718 						 &part_info);
719 		if (part_num < 0) {
720 			fb_add_string(response, chars_left,
721 				      "partition not found", NULL);
722 			ret = -1;
723 		} else if (!strncmp(PARTITION_TYPE_STRINGS, cmd,
724 					strlen(PARTITION_TYPE_STRINGS))) {
725 			if (fb_get_fstype("mmc", part_num, &fs_type)) {
726 				fb_add_string(response, chars_left,
727 					      (char *)part_info.type, NULL);
728 			} else {
729 				fb_add_string(response, chars_left,
730 					      fs_type, NULL);
731 			}
732 		} else if (!strncmp("partition-size", cmd, 14)) {
733 			u64 part_size;
734 
735 			part_size = (uint64_t)part_info.size;
736 			snprintf(response, chars_left, "0x%llx",
737 				 part_size * dev_desc->blksz);
738 		}
739 #else
740 		fb_add_string(response, chars_left, "not implemented", NULL);
741 		ret = -1;
742 #endif
743 		break;
744 	}
745 	case FB_BLK_SIZE: {
746 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
747 		struct blk_desc *dev_desc;
748 
749 #ifdef CONFIG_RKIMG_BOOTLOADER
750 		dev_desc = rockchip_get_bootdev();
751 #else
752 		dev_desc = NULL;
753 #endif
754 		if (!dev_desc) {
755 			fb_add_string(response, chars_left,
756 				      "block device not found", NULL);
757 			ret = -1;
758 		} else {
759 			fb_add_number(response, chars_left,
760 				      "0x%lx", dev_desc->blksz);
761 		}
762 #else
763 		fb_add_string(response, chars_left, "not implemented", NULL);
764 		ret = -1;
765 #endif
766 		break;
767 	}
768 	case FB_ERASE_SIZE: {
769 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
770 		lbaint_t erase_grp_size;
771 
772 		erase_grp_size = fb_mmc_get_erase_grp_size();
773 		if (erase_grp_size < 0) {
774 			fb_add_string(response, chars_left,
775 				      "block device not found", NULL);
776 			ret = -1;
777 		} else {
778 			fb_add_number(response, chars_left, "0x"LBAF"",
779 				      erase_grp_size);
780 		}
781 #else
782 		fb_add_string(response, chars_left, "not implemented", NULL);
783 		ret = -1;
784 #endif
785 		break;
786 	}
787 	case FB_UNLOCKED: {
788 #ifdef CONFIG_RK_AVB_LIBAVB_USER
789 		uint8_t flash_lock_state = 0;
790 
791 		if (rk_avb_read_flash_lock_state(&flash_lock_state))
792 			fb_add_string(response, chars_left, "yes", NULL);
793 		else
794 			fb_add_string(response, chars_left, "no", NULL);
795 #else
796 		fb_add_string(response, chars_left, "not implemented", NULL);
797 		ret = -1;
798 #endif
799 		break;
800 	}
801 	case  FB_OFF_MODE_CHARGE: {
802 		fb_add_string(response, chars_left, "not implemented", NULL);
803 		break;
804 	}
805 	case FB_BATT_VOLTAGE: {
806 		fb_add_string(response, chars_left, "not implemented", NULL);
807 		break;
808 	}
809 	case FB_BATT_SOC_OK: {
810 		fb_add_string(response, chars_left, "no", NULL);
811 		break;
812 	}
813 	case FB_IS_USERSPACE: {
814 		fb_add_string(response, chars_left, "no", NULL);
815 		break;
816 	}
817 #ifdef CONFIG_RK_AVB_LIBAVB_USER
818 	case FB_HAS_COUNT: {
819 		char slot_count[2];
820 		char temp;
821 
822 		slot_count[1] = '\0';
823 		if (rk_avb_read_slot_count(&temp) < 0) {
824 			fb_add_number(response, chars_left, "%d", 0);
825 			ret = -1;
826 			break;
827 		}
828 		slot_count[0] = temp + 0x30;
829 		fb_add_string(response, chars_left, slot_count, NULL);
830 		break;
831 	}
832 	case FB_HAS_SLOT: {
833 		char *part_name = cmd;
834 		int has_slot = -1;
835 
836 		cmd = strsep(&part_name, ":");
837 		if (!cmd || !part_name) {
838 			fb_add_string(response, chars_left,
839 				      "argument Invalid!", NULL);
840 			ret = -1;
841 			break;
842 		}
843 
844 		has_slot = rk_avb_get_part_has_slot_info(part_name);
845 		if (has_slot < 0)
846 			fb_add_string(response, chars_left, "no", NULL);
847 		else
848 			fb_add_string(response, chars_left, "yes", NULL);
849 		break;
850 	}
851 	case FB_CURR_SLOT: {
852 		char slot_surrent[8] = {0};
853 
854 		if (!rk_avb_get_current_slot(slot_surrent)) {
855 			fb_add_string(response, chars_left,
856 				      slot_surrent + 1, NULL);
857 		} else {
858 			fb_add_string(response, chars_left, "get error", NULL);
859 			ret = -1;
860 		}
861 		break;
862 	}
863 	case FB_SLOT_SUFFIXES: {
864 		char slot_suffixes_temp[4] = {0};
865 		char slot_suffixes[9] = {0};
866 		int slot_cnt = 0;
867 
868 		rk_avb_read_slot_suffixes(slot_suffixes_temp);
869 		while (slot_suffixes_temp[slot_cnt] != '\0') {
870 			slot_suffixes[slot_cnt * 2]
871 				= slot_suffixes_temp[slot_cnt];
872 			slot_suffixes[slot_cnt * 2 + 1] = ',';
873 			slot_cnt++;
874 		}
875 
876 		slot_suffixes[(slot_cnt - 1) * 2 + 1] = '\0';
877 		fb_add_string(response, chars_left, slot_suffixes, NULL);
878 		break;
879 	}
880 	case FB_SLOT_SUCCESSFUL:{
881 		char *slot_name = cmd;
882 		AvbABData ab_info;
883 
884 		cmd = strsep(&slot_name, ":");
885 		if (!cmd || !slot_name) {
886 			fb_add_string(response, chars_left,
887 				      "argument Invalid!", NULL);
888 			ret = -1;
889 			break;
890 		}
891 
892 		if (rk_avb_get_ab_info(&ab_info) < 0) {
893 			fb_add_string(response, chars_left,
894 				      "get ab info failed!", NULL);
895 			ret = -1;
896 			break;
897 		}
898 
899 		if (!strcmp(slot_name, "a")) {
900 			if (ab_info.slots[0].successful_boot)
901 				fb_add_string(response, chars_left,
902 					      "yes", NULL);
903 			else
904 				fb_add_string(response, chars_left,
905 					      "no", NULL);
906 		} else if (!strcmp(slot_name, "b")) {
907 			if (ab_info.slots[1].successful_boot)
908 				fb_add_string(response, chars_left,
909 					      "yes", NULL);
910 			else
911 				fb_add_string(response, chars_left,
912 					      "no", NULL);
913 		} else {
914 			fb_add_string(response, chars_left, "no", NULL);
915 		}
916 		break;
917 	}
918 	case FB_SLOT_UNBOOTABLE: {
919 		char *slot_name = cmd;
920 		AvbABData ab_info;
921 
922 		cmd = strsep(&slot_name, ":");
923 
924 		if (!cmd || !slot_name) {
925 			fb_add_string(response, chars_left,
926 				      "argument Invalid!", NULL);
927 			ret = -1;
928 			break;
929 		}
930 
931 		if (rk_avb_get_ab_info(&ab_info) < 0) {
932 			fb_add_string(response, chars_left,
933 				      "get ab info failed!", NULL);
934 			ret = -1;
935 			break;
936 		}
937 
938 		if (!strcmp(slot_name, "a")) {
939 			if (!ab_info.slots[0].successful_boot &&
940 			    !ab_info.slots[0].tries_remaining &&
941 			    !ab_info.slots[0].priority)
942 				fb_add_string(response, chars_left,
943 					      "yes", NULL);
944 			else
945 				fb_add_string(response, chars_left, "no", NULL);
946 		} else if (!strcmp(slot_name, "b")) {
947 			if (!ab_info.slots[1].successful_boot &&
948 			    !ab_info.slots[1].tries_remaining &&
949 			    !ab_info.slots[1].priority)
950 				fb_add_string(response, chars_left,
951 					      "yes", NULL);
952 			else
953 				fb_add_string(response, chars_left, "no", NULL);
954 		} else {
955 			fb_add_string(response, chars_left, "no", NULL);
956 		}
957 		break;
958 	}
959 	case FB_SLOT_RETRY_COUNT: {
960 		char *slot_name = cmd;
961 		AvbABData ab_info;
962 
963 		cmd = strsep(&slot_name, ":");
964 		if (!cmd || !slot_name) {
965 			fb_add_string(response, chars_left,
966 				      "argument Invalid!", NULL);
967 			ret = -1;
968 			break;
969 		}
970 
971 		if (rk_avb_get_ab_info(&ab_info) < 0) {
972 			fb_add_string(response, chars_left,
973 				      "get ab info failed!", NULL);
974 			ret = -1;
975 			break;
976 		}
977 
978 		if (!strcmp(slot_name, "a")) {
979 			fb_add_number(response, chars_left,
980 				      "%d", ab_info.slots[0].tries_remaining);
981 		} else if (!strcmp(slot_name, "b")) {
982 			fb_add_number(response, chars_left, "%d",
983 				      ab_info.slots[1].tries_remaining);
984 
985 		} else {
986 			strcpy(response, "FAILno");
987 		}
988 		break;
989 	}
990 	case FB_AT_VBST: {
991 		char vbst[VBOOT_STATE_SIZE] = {0};
992 		char *p_vbst;
993 
994 		strcpy(response, "INFO");
995 		rk_avb_get_at_vboot_state(vbst);
996 		p_vbst = vbst;
997 		do {
998 			cmd = strsep(&p_vbst, "\n");
999 			if (strlen(cmd) > 0) {
1000 				memcpy(&response[4], cmd, chars_left);
1001 				fastboot_tx_write_str(response);
1002 			}
1003 		} while (strlen(cmd));
1004 		break;
1005 	}
1006 	case FB_SNAPSHOT_STATUS: {
1007 #ifdef CONFIG_ANDROID_AB
1008 		struct misc_virtual_ab_message state;
1009 
1010 		memset(&state, 0x0, sizeof(state));
1011 		if (read_misc_virtual_ab_message(&state) != 0) {
1012 			printf("FB_SNAPSHOT_STATUS read_misc_virtual_ab_message failed!\n");
1013 			fb_add_string(response, chars_left, "get error", NULL);
1014 			ret = -1;
1015 		}
1016 
1017 		if (state.magic != MISC_VIRTUAL_AB_MAGIC_HEADER) {
1018 			printf("FB_SNAPSHOT_STATUS not virtual A/B metadata!\n");
1019 			fb_add_string(response, chars_left, "get error", NULL);
1020 			ret = -1;
1021 		}
1022 
1023 		if (state.merge_status == ENUM_MERGE_STATUS_MERGING) {
1024 			fb_add_string(response, chars_left, "merging", NULL);
1025 		} else if (state.merge_status == ENUM_MERGE_STATUS_SNAPSHOTTED) {
1026 			fb_add_string(response, chars_left, "snapshotted", NULL);
1027 		} else {
1028 			fb_add_string(response, chars_left, "none", NULL);
1029 		}
1030 #else
1031 		fb_add_string(response, chars_left, "get error", NULL);
1032 		ret = -1;
1033 #endif
1034 		break;
1035 	}
1036 
1037 #endif
1038 #ifdef CONFIG_OPTEE_CLIENT
1039 	case FB_AT_DH: {
1040 		char dhbuf[ATTEST_DH_SIZE];
1041 		uint32_t dh_len = ATTEST_DH_SIZE;
1042 		uint32_t res = trusty_attest_dh((uint8_t *)dhbuf, &dh_len);
1043 
1044 		if (res) {
1045 			fb_add_string(response, chars_left, "dh not set", NULL);
1046 			ret = -1;
1047 		} else {
1048 			fb_add_string(response, chars_left, dhbuf, NULL);
1049 		}
1050 		break;
1051 	}
1052 	case FB_AT_UUID: {
1053 		char uuid[ATTEST_UUID_SIZE] = {0};
1054 		uint32_t uuid_len = ATTEST_UUID_SIZE;
1055 		uint32_t res = trusty_attest_uuid((uint8_t *)uuid, &uuid_len);
1056 
1057 		uuid[ATTEST_UUID_SIZE - 1] = 0;
1058 		if (res) {
1059 			fb_add_string(response, chars_left, "dh not set", NULL);
1060 			ret = -1;
1061 		} else {
1062 			fb_add_string(response, chars_left, uuid, NULL);
1063 		}
1064 		break;
1065 	}
1066 #endif
1067 	default: {
1068 			char *envstr;
1069 
1070 			envstr = malloc(strlen("fastboot.") + strlen(cmd) + 1);
1071 			if (!envstr) {
1072 				fb_add_string(response, chars_left,
1073 					      "malloc error", NULL);
1074 				ret = -1;
1075 				break;
1076 			}
1077 
1078 			sprintf(envstr, "fastboot.%s", cmd);
1079 			s = env_get(envstr);
1080 			if (s) {
1081 				strncat(response, s, chars_left);
1082 			} else {
1083 				printf("WARNING: unknown variable: %s\n", cmd);
1084 				fb_add_string(response, chars_left,
1085 					      "not implemented", NULL);
1086 			}
1087 
1088 			free(envstr);
1089 			break;
1090 		}
1091 	}
1092 
1093 	return ret;
1094 }
1095 
1096 static const struct {
1097 	/*
1098 	 *any changes to this array require an update to the corresponding
1099 	 *enum in fastboot.h
1100 	 */
1101 	struct name_string name;
1102 	fb_getvar_t var;
1103 } getvar_table[] = {
1104 	{ NAME_NO_ARGS("version"), FB_VERSION},
1105 	{ NAME_NO_ARGS("version-bootloader"), FB_BOOTLOADER_VERSION},
1106 	{ NAME_NO_ARGS("version-baseband"), FB_BASEBAND_VERSION},
1107 	{ NAME_NO_ARGS("product"), FB_PRODUCT},
1108 	{ NAME_NO_ARGS("serialno"), FB_SERIAL_NO},
1109 	{ NAME_NO_ARGS("secure"), FB_SECURE},
1110 	{ NAME_NO_ARGS("max-download-size"), FB_DWNLD_SIZE},
1111 	{ NAME_NO_ARGS("logical-block-size"), FB_BLK_SIZE},
1112 	{ NAME_NO_ARGS("erase-block-size"), FB_ERASE_SIZE},
1113 	{ NAME_ARGS("partition-type", ':'), FB_PART_TYPE},
1114 	{ NAME_ARGS("partition-size", ':'), FB_PART_SIZE},
1115 	{ NAME_NO_ARGS("unlocked"), FB_UNLOCKED},
1116 	{ NAME_NO_ARGS("off-mode-charge"), FB_OFF_MODE_CHARGE},
1117 	{ NAME_NO_ARGS("battery-voltage"), FB_BATT_VOLTAGE},
1118 	{ NAME_NO_ARGS("variant"), FB_VARIANT},
1119 	{ NAME_NO_ARGS("battery-soc-ok"), FB_BATT_SOC_OK},
1120 	{ NAME_NO_ARGS("is-userspace"), FB_IS_USERSPACE},
1121 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1122 	/* Slots related */
1123 	{ NAME_NO_ARGS("slot-count"), FB_HAS_COUNT},
1124 	{ NAME_ARGS("has-slot", ':'), FB_HAS_SLOT},
1125 	{ NAME_NO_ARGS("current-slot"), FB_CURR_SLOT},
1126 	{ NAME_NO_ARGS("slot-suffixes"), FB_SLOT_SUFFIXES},
1127 	{ NAME_ARGS("slot-successful", ':'), FB_SLOT_SUCCESSFUL},
1128 	{ NAME_ARGS("slot-unbootable", ':'), FB_SLOT_UNBOOTABLE},
1129 	{ NAME_ARGS("slot-retry-count", ':'), FB_SLOT_RETRY_COUNT},
1130 	{ NAME_NO_ARGS("at-vboot-state"), FB_AT_VBST},
1131 	{ NAME_NO_ARGS("snapshot-update-status"), FB_SNAPSHOT_STATUS},
1132 #endif
1133 	/*
1134 	 * OEM specific :
1135 	 * Spec says names starting with lowercase letter are reserved.
1136 	 */
1137 #ifdef CONFIG_OPTEE_CLIENT
1138 	{ NAME_NO_ARGS("at-attest-dh"), FB_AT_DH},
1139 	{ NAME_NO_ARGS("at-attest-uuid"), FB_AT_UUID},
1140 #endif
1141 };
1142 
fb_getvar_single(char * cmd,char * response,size_t chars_left)1143 static int fb_getvar_single(char *cmd, char *response, size_t chars_left)
1144 {
1145 	int i;
1146 	size_t match_len = 0;
1147 	size_t len = strlen(cmd);
1148 
1149 	for (i = 0; i < ARRAY_SIZE(getvar_table); i++) {
1150 		match_len = name_check_match(cmd, len, &getvar_table[i].name);
1151 		if (match_len)
1152 			break;
1153 	}
1154 
1155 	if (match_len == 0) {
1156 		fb_add_string(response, chars_left, "unknown variable", NULL);
1157 		return -1;
1158 	}
1159 
1160 	if (fb_read_var(cmd, response, getvar_table[i].var, chars_left) < 0)
1161 		return -1;
1162 
1163 	return 0;
1164 }
1165 
fb_getvar_all(void)1166 static void fb_getvar_all(void)
1167 {
1168 	char response[FASTBOOT_RESPONSE_LEN] = {0};
1169 	char resp_tmp[FASTBOOT_RESPONSE_LEN] = {0};
1170 	char *actual_resp;
1171 	size_t chars_left;
1172 	int i, p;
1173 	disk_partition_t part_info;
1174 	struct blk_desc *dev_desc;
1175 
1176 	strcpy(response, "INFO");
1177 	chars_left = sizeof(response) - strlen(response) - 1;
1178 	actual_resp = response + strlen(response);
1179 
1180 	for (i = 0; i < ARRAY_SIZE(getvar_table); i++) {
1181 		fb_getvar_t var = getvar_table[i].var;
1182 
1183 		switch (var) {
1184 		case FB_PART_TYPE:
1185 		case FB_PART_SIZE: {
1186 			const char *fs_type = NULL;
1187 #ifdef CONFIG_RKIMG_BOOTLOADER
1188 			dev_desc = rockchip_get_bootdev();
1189 #else
1190 			dev_desc = NULL;
1191 #endif
1192 			if (!dev_desc) {
1193 				fb_add_string(actual_resp, chars_left,
1194 					      "%s:block device not found",
1195 					      getvar_table[i].name.str);
1196 				fastboot_tx_write_str(response);
1197 				break;
1198 			}
1199 
1200 			for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
1201 				if (part_get_info(dev_desc, p,
1202 						  &part_info) < 0) {
1203 					break;
1204 				}
1205 
1206 				if (var == FB_PART_TYPE) {
1207 					fs_type = NULL;
1208 					if (fb_get_fstype("mmc", p,
1209 							  &fs_type)) {
1210 						fb_add_string(
1211 							resp_tmp,
1212 							FASTBOOT_RESPONSE_LEN,
1213 							(char *)part_info.type,
1214 							NULL);
1215 					} else {
1216 						fb_add_string(
1217 							resp_tmp,
1218 							FASTBOOT_RESPONSE_LEN,
1219 							fs_type,
1220 							NULL);
1221 					}
1222 
1223 					snprintf(actual_resp,
1224 						 chars_left,
1225 						 "%s:%s:%s",
1226 						 getvar_table[i].name.str,
1227 						 part_info.name,
1228 						 resp_tmp);
1229 				} else {
1230 					uint64_t part_size;
1231 
1232 					part_size = (uint64_t)part_info.size;
1233 					snprintf(actual_resp,
1234 						 chars_left,
1235 						 "%s:%s:0x%llx",
1236 						 getvar_table[i].name.str,
1237 						 part_info.name,
1238 						 part_size * dev_desc->blksz);
1239 				}
1240 				fastboot_tx_write_str(response);
1241 			}
1242 			break;
1243 		}
1244 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1245 		case FB_HAS_SLOT: {
1246 			uchar *ptr_name_tmp;
1247 			char c = '_';
1248 			int has_slot = -1;
1249 
1250 #ifdef CONFIG_RKIMG_BOOTLOADER
1251 			dev_desc = rockchip_get_bootdev();
1252 #else
1253 			dev_desc = NULL;
1254 #endif
1255 			if (!dev_desc) {
1256 				fb_add_string(actual_resp, chars_left,
1257 					      "%s:block device not found",
1258 					      getvar_table[i].name.str);
1259 				fastboot_tx_write_str(response);
1260 				break;
1261 			}
1262 
1263 			for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
1264 				if (part_get_info(dev_desc, p,
1265 						  &part_info) < 0) {
1266 					break;
1267 				} else {
1268 					ptr_name_tmp = (uchar *)strrchr(
1269 						(char *)part_info.name, c);
1270 					if (ptr_name_tmp &&
1271 					    part_info.name[ptr_name_tmp -
1272 						part_info.name + 2] == '\0')
1273 						fb_add_string(
1274 							resp_tmp,
1275 							ptr_name_tmp -
1276 							part_info.name + 1,
1277 							(char *)part_info.name,
1278 							NULL);
1279 					else
1280 						strcpy(resp_tmp,
1281 						       (char *)part_info.name);
1282 
1283 					has_slot = rk_avb_get_part_has_slot_info(
1284 						resp_tmp);
1285 					if (has_slot < 0) {
1286 						snprintf(actual_resp,
1287 							 chars_left,
1288 							 "%s:%s:no",
1289 							 getvar_table[i].name.str,
1290 							 resp_tmp);
1291 					} else {
1292 						snprintf(actual_resp,
1293 							 chars_left,
1294 							 "%s:%s:yes",
1295 							 getvar_table[i].name.str,
1296 							 resp_tmp);
1297 						p++;
1298 					}
1299 
1300 					fastboot_tx_write_str(response);
1301 				}
1302 			}
1303 			break;
1304 		}
1305 
1306 		case FB_SLOT_SUCCESSFUL: {
1307 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1308 			AvbABData ab_info;
1309 
1310 			if (rk_avb_get_ab_info(&ab_info) < 0) {
1311 				fb_add_string(actual_resp,
1312 					      chars_left,
1313 					      "%s:get ab info failed!",
1314 					      getvar_table[i].name.str);
1315 				fastboot_tx_write_str(response);
1316 				break;
1317 			}
1318 
1319 			if (ab_info.slots[0].successful_boot)
1320 				fb_add_string(actual_resp, chars_left,
1321 					      "%s:a:yes",
1322 					      getvar_table[i].name.str);
1323 			else
1324 				fb_add_string(actual_resp, chars_left,
1325 					      "%s:a:no",
1326 					      getvar_table[i].name.str);
1327 			fastboot_tx_write_str(response);
1328 
1329 			if (ab_info.slots[1].successful_boot)
1330 				fb_add_string(actual_resp, chars_left,
1331 					      "%s:b:yes",
1332 					      getvar_table[i].name.str);
1333 			else
1334 				fb_add_string(actual_resp, chars_left,
1335 					      "%s:b:no",
1336 					      getvar_table[i].name.str);
1337 			fastboot_tx_write_str(response);
1338 #else
1339 			fb_add_string(actual_resp, chars_left,
1340 				      "%s:not find ab info!",
1341 				      getvar_table[i].name.str);
1342 			fastboot_tx_write_str(response);
1343 #endif
1344 			break;
1345 		}
1346 
1347 		case FB_SLOT_UNBOOTABLE: {
1348 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1349 			AvbABData ab_info;
1350 
1351 			if (rk_avb_get_ab_info(&ab_info) < 0) {
1352 				fb_add_string(actual_resp, chars_left,
1353 					      "%s:not find ab info!",
1354 					      getvar_table[i].name.str);
1355 				fastboot_tx_write_str(response);
1356 				break;
1357 			}
1358 
1359 			if (!ab_info.slots[0].successful_boot &&
1360 			    !ab_info.slots[0].tries_remaining &&
1361 			    !ab_info.slots[0].priority)
1362 				fb_add_string(actual_resp, chars_left,
1363 					      "%s:a:yes",
1364 					      getvar_table[i].name.str);
1365 			else
1366 				fb_add_string(actual_resp, chars_left,
1367 					      "%s:a:no",
1368 					      getvar_table[i].name.str);
1369 			fastboot_tx_write_str(response);
1370 
1371 			if (!ab_info.slots[1].successful_boot &&
1372 			    !ab_info.slots[1].tries_remaining &&
1373 			    !ab_info.slots[1].priority)
1374 				fb_add_string(actual_resp, chars_left,
1375 					      "%s:b:yes",
1376 					      getvar_table[i].name.str);
1377 			else
1378 				fb_add_string(actual_resp, chars_left,
1379 					      "%s:b:no",
1380 					      getvar_table[i].name.str);
1381 
1382 			fastboot_tx_write_str(response);
1383 #else
1384 			fb_add_string(actual_resp, chars_left,
1385 				      "%s:not find ab info!",
1386 				      getvar_table[i].name.str);
1387 			fastboot_tx_write_str(response);
1388 #endif
1389 			break;
1390 		}
1391 
1392 		case FB_SLOT_RETRY_COUNT: {
1393 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1394 			AvbABData ab_info;
1395 
1396 			if (rk_avb_get_ab_info(&ab_info) < 0) {
1397 				fb_add_string(actual_resp, chars_left,
1398 					      "%s:not find ab info!",
1399 					      getvar_table[i].name.str);
1400 				fastboot_tx_write_str(response);
1401 				break;
1402 			}
1403 
1404 			snprintf(actual_resp, chars_left, "%s:a:%d",
1405 				 getvar_table[i].name.str,
1406 				 ab_info.slots[1].tries_remaining);
1407 			fastboot_tx_write_str(response);
1408 			snprintf(actual_resp, chars_left, "%s:b:%d",
1409 				 getvar_table[i].name.str,
1410 				 ab_info.slots[1].tries_remaining);
1411 			fastboot_tx_write_str(response);
1412 #else
1413 			fb_add_string(actual_resp, chars_left,
1414 				      "%s:not find ab info!",
1415 				      getvar_table[i].name.str);
1416 			fastboot_tx_write_str(response);
1417 #endif
1418 			break;
1419 		}
1420 #endif
1421 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1422 		case FB_AT_VBST:
1423 			break;
1424 #endif
1425 		default:
1426 			fb_getvar_single((char *)getvar_table[i].name.str,
1427 					 resp_tmp, FASTBOOT_RESPONSE_LEN);
1428 			snprintf(actual_resp, chars_left, "%s:%s",
1429 				 getvar_table[i].name.str, resp_tmp);
1430 			fastboot_tx_write_str(response);
1431 		}
1432 	}
1433 }
1434 
1435 #ifdef CONFIG_ANDROID_AB
get_current_slot(void)1436 static int get_current_slot(void)
1437 {
1438 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1439 	char cmd[8] = {0};
1440 	unsigned int slot_number = -1;
1441 
1442 	memset(cmd, 0x0, sizeof(cmd));
1443 	rk_avb_get_current_slot(cmd);
1444 	if (strncmp("_a", cmd, 2) == 0) {
1445 		slot_number = 0;
1446 	} else if (strncmp("_b", cmd, 2) == 0) {
1447 		slot_number = 1;
1448 	} else {
1449 		pr_err("%s: FAILunkown slot name\n", __func__);
1450 		return -1;
1451 	}
1452 
1453 	return slot_number;
1454 #else
1455 	pr_err("%s: FAILnot implemented\n", __func__);
1456 	return -1;
1457 #endif
1458 }
1459 
1460 #ifdef CONFIG_FASTBOOT_FLASH
should_prevent_userdata_wipe(void)1461 static int should_prevent_userdata_wipe(void)
1462 {
1463 	struct misc_virtual_ab_message state;
1464 
1465 	memset(&state, 0x0, sizeof(state));
1466 	if (read_misc_virtual_ab_message(&state) != 0) {
1467 		pr_err("%s: read_misc_virtual_ab_message failed!\n", __func__);
1468 		return 0;
1469 	}
1470 
1471 	if (state.magic != MISC_VIRTUAL_AB_MAGIC_HEADER) {
1472 		pr_err("%s: NOT virtual A/B metadata!\n", __func__);
1473 		return 0;
1474 	}
1475 
1476 	if (state.merge_status == (uint8_t)ENUM_MERGE_STATUS_MERGING ||
1477 		(state.merge_status == (uint8_t)ENUM_MERGE_STATUS_SNAPSHOTTED &&
1478 		state.source_slot != get_current_slot())) {
1479 		return 1;
1480 	}
1481 
1482 	return 0;
1483 }
1484 #endif
1485 
get_virtual_ab_merge_status(void)1486 static int get_virtual_ab_merge_status(void)
1487 {
1488 	struct misc_virtual_ab_message state;
1489 
1490 	memset(&state, 0x0, sizeof(state));
1491 	if (read_misc_virtual_ab_message(&state) != 0) {
1492 		pr_err("%s: read_misc_virtual_ab_message failed!\n", __func__);
1493 		return -1;
1494 	}
1495 
1496 	if (state.magic != MISC_VIRTUAL_AB_MAGIC_HEADER) {
1497 		pr_err("%s: NOT virtual A/B metadata!\n", __func__);
1498 		return -1;
1499 	}
1500 
1501 	return state.merge_status;
1502 }
1503 #endif
1504 
cb_getvar(struct usb_ep * ep,struct usb_request * req)1505 static void cb_getvar(struct usb_ep *ep, struct usb_request *req)
1506 {
1507 	char *cmd = req->buf;
1508 	char response[FASTBOOT_RESPONSE_LEN] = {0};
1509 	const char *str_read_all = "all";
1510 	size_t len = 0;
1511 	size_t chars_left;
1512 
1513 	strsep(&cmd, ":");
1514 	if (!cmd) {
1515 		pr_err("missing variable");
1516 		fastboot_tx_write_str("FAILmissing var");
1517 		return;
1518 	}
1519 
1520 	len = strlen(cmd);
1521 	if (len == strlen(str_read_all) &&
1522 	    (strncmp(cmd, str_read_all, len) == 0)) {
1523 		fb_getvar_all();
1524 		fastboot_tx_write_str("OKAYDone!");
1525 	} else {
1526 		strcpy(response, "OKAY");
1527 		chars_left = sizeof(response) - strlen(response) - 1;
1528 
1529 		if (fb_getvar_single(cmd, &response[strlen(response)],
1530 				     chars_left) < 0) {
1531 			strcpy(cmd, "FAILunknown variable");
1532 			strncat(cmd, &response[strlen(response)], chars_left);
1533 			fastboot_tx_write_str(cmd);
1534 			return;
1535 		}
1536 		fastboot_tx_write_str(response);
1537 	}
1538 
1539 	return;
1540 }
1541 
rx_bytes_expected(struct usb_ep * ep)1542 static unsigned int rx_bytes_expected(struct usb_ep *ep)
1543 {
1544 	int rx_remain = download_size - download_bytes;
1545 	unsigned int rem;
1546 	unsigned int maxpacket = ep->maxpacket;
1547 
1548 	if (rx_remain <= 0)
1549 		return 0;
1550 	else if (rx_remain > EP_BUFFER_SIZE)
1551 		return EP_BUFFER_SIZE;
1552 
1553 	/*
1554 	 * Some controllers e.g. DWC3 don't like OUT transfers to be
1555 	 * not ending in maxpacket boundary. So just make them happy by
1556 	 * always requesting for integral multiple of maxpackets.
1557 	 * This shouldn't bother controllers that don't care about it.
1558 	 */
1559 	rem = rx_remain % maxpacket;
1560 	if (rem > 0)
1561 		rx_remain = rx_remain + (maxpacket - rem);
1562 
1563 	return rx_remain;
1564 }
1565 
1566 #define BYTES_PER_DOT	0x20000
rx_handler_dl_image(struct usb_ep * ep,struct usb_request * req)1567 static void rx_handler_dl_image(struct usb_ep *ep, struct usb_request *req)
1568 {
1569 	char response[FASTBOOT_RESPONSE_LEN];
1570 	unsigned int transfer_size = download_size - download_bytes;
1571 	const unsigned char *buffer = req->buf;
1572 	unsigned int buffer_size = req->actual;
1573 	unsigned int pre_dot_num, now_dot_num;
1574 
1575 	if (req->status != 0) {
1576 		printf("Bad status: %d\n", req->status);
1577 		return;
1578 	}
1579 
1580 	if (buffer_size < transfer_size)
1581 		transfer_size = buffer_size;
1582 
1583 	memcpy((void *)CONFIG_FASTBOOT_BUF_ADDR + download_bytes,
1584 	       buffer, transfer_size);
1585 
1586 	pre_dot_num = download_bytes / BYTES_PER_DOT;
1587 	download_bytes += transfer_size;
1588 	now_dot_num = download_bytes / BYTES_PER_DOT;
1589 
1590 	if (pre_dot_num != now_dot_num) {
1591 		putc('.');
1592 		if (!(now_dot_num % 74))
1593 			putc('\n');
1594 	}
1595 
1596 	/* Check if transfer is done */
1597 	if (download_bytes >= download_size) {
1598 		/*
1599 		 * Reset global transfer variable, keep download_bytes because
1600 		 * it will be used in the next possible flashing command
1601 		 */
1602 		download_size = 0;
1603 		req->complete = rx_handler_command;
1604 		req->length = EP_BUFFER_SIZE;
1605 
1606 		strcpy(response, "OKAY");
1607 		fastboot_tx_write_str(response);
1608 
1609 		printf("\ndownloading of %d bytes finished\n", download_bytes);
1610 	} else {
1611 		req->length = rx_bytes_expected(ep);
1612 	}
1613 
1614 	req->actual = 0;
1615 	usb_ep_queue(ep, req, 0);
1616 }
1617 
cb_download(struct usb_ep * ep,struct usb_request * req)1618 static void cb_download(struct usb_ep *ep, struct usb_request *req)
1619 {
1620 	char *cmd = req->buf;
1621 	char response[FASTBOOT_RESPONSE_LEN];
1622 
1623 	strsep(&cmd, ":");
1624 	download_size = simple_strtoul(cmd, NULL, 16);
1625 	download_bytes = 0;
1626 
1627 	printf("Starting download of %d bytes\n", download_size);
1628 
1629 	if (0 == download_size) {
1630 		strcpy(response, "FAILdata invalid size");
1631 	} else if (download_size > CONFIG_FASTBOOT_BUF_SIZE) {
1632 		download_size = 0;
1633 		strcpy(response, "FAILdata too large");
1634 	} else {
1635 		sprintf(response, "DATA%08x", download_size);
1636 		req->complete = rx_handler_dl_image;
1637 		req->length = rx_bytes_expected(ep);
1638 	}
1639 
1640 	fastboot_tx_write_str(response);
1641 }
1642 
tx_handler_ul(struct usb_ep * ep,struct usb_request * req)1643 static void tx_handler_ul(struct usb_ep *ep, struct usb_request *req)
1644 {
1645 	unsigned int xfer_size = 0;
1646 	unsigned int pre_dot_num, now_dot_num;
1647 	unsigned int remain_size = 0;
1648 	unsigned int transferred_size = req->actual;
1649 
1650 	if (req->status != 0) {
1651 		printf("Bad status: %d\n", req->status);
1652 		return;
1653 	}
1654 
1655 	if (start_upload) {
1656 		pre_dot_num = upload_bytes / BYTES_PER_DOT;
1657 		upload_bytes += transferred_size;
1658 		now_dot_num = upload_bytes / BYTES_PER_DOT;
1659 
1660 		if (pre_dot_num != now_dot_num) {
1661 			putc('.');
1662 			if (!(now_dot_num % 74))
1663 				putc('\n');
1664 		}
1665 	}
1666 
1667 	remain_size = upload_size - upload_bytes;
1668 	xfer_size = (remain_size > EP_BUFFER_SIZE) ?
1669 		    EP_BUFFER_SIZE : remain_size;
1670 
1671 	debug("%s: remain_size=%d, transferred_size=%d",
1672 	      __func__, remain_size, transferred_size);
1673 	debug("xfer_size=%d, upload_bytes=%d, upload_size=%d!\n",
1674 	      xfer_size, upload_bytes, upload_size);
1675 
1676 	if (remain_size <= 0) {
1677 		fastboot_func->in_req->complete = fastboot_complete;
1678 		wakeup_thread();
1679 		fastboot_tx_write_str("OKAY");
1680 		printf("\nuploading of %d bytes finished\n", upload_bytes);
1681 		upload_bytes = 0;
1682 		upload_size = 0;
1683 		start_upload = false;
1684 		return;
1685 	}
1686 
1687 	/* Remove the transfer callback which response the upload */
1688 	/* request from host */
1689 	if (!upload_bytes)
1690 		start_upload = true;
1691 
1692 	fastboot_tx_write((char *)((phys_addr_t)CONFIG_FASTBOOT_BUF_ADDR + \
1693 			  upload_bytes),
1694 			  xfer_size);
1695 }
1696 
cb_upload(struct usb_ep * ep,struct usb_request * req)1697 static void cb_upload(struct usb_ep *ep, struct usb_request *req)
1698 {
1699 	char response[FASTBOOT_RESPONSE_LEN];
1700 
1701 	printf("Starting upload of %d bytes\n", upload_size);
1702 
1703 	if (0 == upload_size) {
1704 		strcpy(response, "FAILdata invalid size");
1705 	} else {
1706 		start_upload = false;
1707 		sprintf(response, "DATA%08x", upload_size);
1708 		fastboot_func->in_req->complete = tx_handler_ul;
1709 	}
1710 
1711 	fastboot_tx_write_str(response);
1712 }
1713 
do_bootm_on_complete(struct usb_ep * ep,struct usb_request * req)1714 static void do_bootm_on_complete(struct usb_ep *ep, struct usb_request *req)
1715 {
1716 	char boot_addr_start[12];
1717 	char *bootm_args[] = { "bootm", boot_addr_start, NULL };
1718 
1719 	puts("Booting kernel..\n");
1720 
1721 	sprintf(boot_addr_start, "0x%lx", (long)CONFIG_FASTBOOT_BUF_ADDR);
1722 	do_bootm(NULL, 0, 2, bootm_args);
1723 
1724 	/* This only happens if image is somehow faulty so we start over */
1725 	do_reset(NULL, 0, 0, NULL);
1726 }
1727 
cb_boot(struct usb_ep * ep,struct usb_request * req)1728 static void cb_boot(struct usb_ep *ep, struct usb_request *req)
1729 {
1730 	fastboot_func->in_req->complete = do_bootm_on_complete;
1731 	fastboot_tx_write_str("OKAY");
1732 }
1733 
do_exit_on_complete(struct usb_ep * ep,struct usb_request * req)1734 static void do_exit_on_complete(struct usb_ep *ep, struct usb_request *req)
1735 {
1736 	g_dnl_trigger_detach();
1737 }
1738 
cb_continue(struct usb_ep * ep,struct usb_request * req)1739 static void cb_continue(struct usb_ep *ep, struct usb_request *req)
1740 {
1741 	fastboot_func->in_req->complete = do_exit_on_complete;
1742 	fastboot_tx_write_str("OKAY");
1743 }
1744 
cb_set_active(struct usb_ep * ep,struct usb_request * req)1745 static void cb_set_active(struct usb_ep *ep, struct usb_request *req)
1746 {
1747 	char *cmd = req->buf;
1748 
1749 	debug("%s: %s\n", __func__, cmd);
1750 
1751 	strsep(&cmd, ":");
1752 	if (!cmd) {
1753 		pr_err("missing slot name");
1754 		fastboot_tx_write_str("FAILmissing slot name");
1755 		return;
1756 	}
1757 #ifdef CONFIG_ANDROID_AB
1758 	if (get_virtual_ab_merge_status() == ENUM_MERGE_STATUS_MERGING) {
1759 		pr_err("virtual A/B is merging, abort the operation");
1760 		fastboot_tx_write_str("FAILvirtual A/B is merging, abort");
1761 		return;
1762 	}
1763 #endif
1764 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1765 	unsigned int slot_number;
1766 	if (strncmp("a", cmd, 1) == 0) {
1767 		slot_number = 0;
1768 		rk_avb_set_slot_active(&slot_number);
1769 	} else if (strncmp("b", cmd, 1) == 0) {
1770 		slot_number = 1;
1771 		rk_avb_set_slot_active(&slot_number);
1772 	} else {
1773 		fastboot_tx_write_str("FAILunkown slot name");
1774 		return;
1775 	}
1776 
1777 	fastboot_tx_write_str("OKAY");
1778 	return;
1779 #else
1780 	fastboot_tx_write_str("FAILnot implemented");
1781 	return;
1782 #endif
1783 }
1784 
1785 #ifdef CONFIG_FASTBOOT_FLASH
cb_flash(struct usb_ep * ep,struct usb_request * req)1786 static void cb_flash(struct usb_ep *ep, struct usb_request *req)
1787 {
1788 	char *cmd = req->buf;
1789 	char response[FASTBOOT_RESPONSE_LEN] = {0};
1790 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1791 	uint8_t flash_lock_state;
1792 
1793 	if (rk_avb_read_flash_lock_state(&flash_lock_state)) {
1794 		/* write the device flashing unlock when first read */
1795 		if (rk_avb_write_flash_lock_state(1)) {
1796 			fastboot_tx_write_str("FAILflash lock state write failure");
1797 			return;
1798 		}
1799 		if (rk_avb_read_flash_lock_state(&flash_lock_state)) {
1800 			fastboot_tx_write_str("FAILflash lock state read failure");
1801 			return;
1802 		}
1803 	}
1804 
1805 	if (flash_lock_state == 0) {
1806 		fastboot_tx_write_str("FAILThe device is locked, can not flash!");
1807 		printf("The device is locked, can not flash!\n");
1808 		return;
1809 	}
1810 #endif
1811 	strsep(&cmd, ":");
1812 	if (!cmd) {
1813 		pr_err("missing partition name");
1814 		fastboot_tx_write_str("FAILmissing partition name");
1815 		return;
1816 	}
1817 #ifdef CONFIG_ANDROID_AB
1818 	if ((strcmp(cmd, PART_USERDATA) == 0) || (strcmp(cmd, PART_METADATA) == 0)) {
1819 		if (should_prevent_userdata_wipe()) {
1820 			pr_err("FAILThe virtual A/B merging, can not flash userdata or metadata!\n");
1821 			fastboot_tx_write_str("FAILvirtual A/B merging,abort flash!");
1822 			return;
1823 		}
1824 	}
1825 #endif
1826 	fastboot_fail("no flash device defined", response);
1827 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
1828 	fb_mmc_flash_write(cmd, (void *)CONFIG_FASTBOOT_BUF_ADDR,
1829 				download_bytes, response);
1830 #endif
1831 #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
1832 	fb_nand_flash_write(cmd, (void *)CONFIG_FASTBOOT_BUF_ADDR,
1833 				download_bytes, response);
1834 #endif
1835 	fastboot_tx_write_str(response);
1836 }
1837 
cb_flashing(struct usb_ep * ep,struct usb_request * req)1838 static void cb_flashing(struct usb_ep *ep, struct usb_request *req)
1839 {
1840 	char *cmd = req->buf;
1841 
1842 	if (strncmp("lock", cmd + 9, 4) == 0) {
1843 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1844 		uint8_t flash_lock_state;
1845 		flash_lock_state = 0;
1846 		if (rk_avb_write_flash_lock_state(flash_lock_state))
1847 			fastboot_tx_write_str("FAILflash lock state"
1848 					      " write failure");
1849 		else
1850 			fastboot_tx_write_str("OKAY");
1851 #else
1852 		fastboot_tx_write_str("FAILnot implemented");
1853 #endif
1854 	} else if (strncmp("unlock", cmd + 9, 6) == 0) {
1855 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1856 		uint8_t flash_lock_state;
1857 		flash_lock_state = 1;
1858 		if (rk_avb_write_flash_lock_state(flash_lock_state))
1859 			fastboot_tx_write_str("FAILflash lock state"
1860 					      " write failure");
1861 		else
1862 			fastboot_tx_write_str("OKAY");
1863 #else
1864 		fastboot_tx_write_str("FAILnot implemented");
1865 #endif
1866 	} else if (strncmp("lock_critical", cmd + 9, 12) == 0) {
1867 		fastboot_tx_write_str("FAILnot implemented");
1868 	} else if (strncmp("unlock_critical", cmd + 9, 14) == 0) {
1869 		fastboot_tx_write_str("FAILnot implemented");
1870 	} else if (strncmp("get_unlock_ability", cmd + 9, 17) == 0) {
1871 		fastboot_tx_write_str("FAILnot implemented");
1872 	} else if (strncmp("get_unlock_bootloader_nonce", cmd + 4, 27) == 0) {
1873 		fastboot_tx_write_str("FAILnot implemented");
1874 	} else if (strncmp("unlock_bootloader", cmd + 9, 17) == 0) {
1875 		fastboot_tx_write_str("FAILnot implemented");
1876 	} else if (strncmp("lock_bootloader", cmd + 9, 15) == 0) {
1877 		fastboot_tx_write_str("FAILnot implemented");
1878 	} else {
1879 		fastboot_tx_write_str("FAILunknown flashing command");
1880 	}
1881 }
1882 #endif
1883 
cb_oem_perm_attr(void)1884 static void cb_oem_perm_attr(void)
1885 {
1886 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1887 #ifndef CONFIG_ROCKCHIP_PRELOADER_PUB_KEY
1888 	sha256_context ctx;
1889 	uint8_t digest[SHA256_SUM_LEN] = {0};
1890 	uint8_t digest_temp[SHA256_SUM_LEN] = {0};
1891 	uint8_t perm_attr_temp[PERM_ATTR_TOTAL_SIZE] = {0};
1892 	uint8_t flag = 0;
1893 #endif
1894 	if (PERM_ATTR_TOTAL_SIZE != download_bytes) {
1895 		printf("Permanent attribute size is not equal!\n");
1896 		fastboot_tx_write_str("FAILincorrect perm attribute size");
1897 		return;
1898 	}
1899 #ifndef CONFIG_ROCKCHIP_PRELOADER_PUB_KEY
1900 	if (rk_avb_read_perm_attr_flag(&flag)) {
1901 		printf("rk_avb_read_perm_attr_flag error!\n");
1902 		fastboot_tx_write_str("FAILperm attr read failed");
1903 		return;
1904 	}
1905 
1906 	if (flag == PERM_ATTR_SUCCESS_FLAG) {
1907 		if (rk_avb_read_attribute_hash(digest_temp,
1908 					       SHA256_SUM_LEN)) {
1909 			printf("The efuse IO can not be used!\n");
1910 			fastboot_tx_write_str("FAILefuse IO can not be used");
1911 			return;
1912 		}
1913 
1914 		if (memcmp(digest, digest_temp, SHA256_SUM_LEN) != 0) {
1915 			if (rk_avb_read_permanent_attributes(perm_attr_temp,
1916 							     PERM_ATTR_TOTAL_SIZE)) {
1917 				printf("rk_avb_write_permanent_attributes error!\n");
1918 				fastboot_tx_write_str("FAILread perm attr error");
1919 				return;
1920 			}
1921 
1922 			sha256_starts(&ctx);
1923 			sha256_update(&ctx,
1924 				      (const uint8_t *)perm_attr_temp,
1925 				      PERM_ATTR_TOTAL_SIZE);
1926 			sha256_finish(&ctx, digest);
1927 			if (memcmp(digest, digest_temp, SHA256_SUM_LEN) == 0) {
1928 				printf("The hash has been written!\n");
1929 				fastboot_tx_write_str("OKAY");
1930 				return;
1931 			}
1932 		}
1933 
1934 		if (rk_avb_write_perm_attr_flag(0)) {
1935 			fastboot_tx_write_str("FAILperm attr flag write failure");
1936 			return;
1937 		}
1938 	}
1939 #endif
1940 	if (rk_avb_write_permanent_attributes((uint8_t *)
1941 					      CONFIG_FASTBOOT_BUF_ADDR,
1942 					      download_bytes)) {
1943 		if (rk_avb_write_perm_attr_flag(0)) {
1944 			fastboot_tx_write_str("FAILperm attr flag write failure");
1945 			return;
1946 		}
1947 		fastboot_tx_write_str("FAILperm attr write failed");
1948 		return;
1949 	}
1950 #ifndef CONFIG_ROCKCHIP_PRELOADER_PUB_KEY
1951 	memset(digest, 0, SHA256_SUM_LEN);
1952 	sha256_starts(&ctx);
1953 	sha256_update(&ctx, (const uint8_t *)CONFIG_FASTBOOT_BUF_ADDR,
1954 		      PERM_ATTR_TOTAL_SIZE);
1955 	sha256_finish(&ctx, digest);
1956 
1957 	if (rk_avb_write_attribute_hash((uint8_t *)digest,
1958 					SHA256_SUM_LEN)) {
1959 		if (rk_avb_read_attribute_hash(digest_temp,
1960 						SHA256_SUM_LEN)) {
1961 			printf("The efuse IO can not be used!\n");
1962 			fastboot_tx_write_str("FAILefuse IO can not be used");
1963 			return;
1964 		}
1965 		if (memcmp(digest, digest_temp, SHA256_SUM_LEN) != 0) {
1966 			if (rk_avb_write_perm_attr_flag(0)) {
1967 				fastboot_tx_write_str("FAILperm attr flag write failure");
1968 				return;
1969 			}
1970 			printf("The hash has been written, but is different!\n");
1971 			fastboot_tx_write_str("FAILhash comparison failure");
1972 			return;
1973 		}
1974 	}
1975 #endif
1976 	if (rk_avb_write_perm_attr_flag(PERM_ATTR_SUCCESS_FLAG)) {
1977 		fastboot_tx_write_str("FAILperm attr flag write failure");
1978 		return;
1979 	}
1980 
1981 	fastboot_tx_write_str("OKAY");
1982 #else
1983 	fastboot_tx_write_str("FAILnot implemented");
1984 #endif
1985 }
1986 
cb_oem_perm_attr_rsa_cer(void)1987 static void cb_oem_perm_attr_rsa_cer(void)
1988 {
1989 #ifdef CONFIG_RK_AVB_LIBAVB_USER
1990 	if (download_bytes != 256) {
1991 		printf("Permanent attribute rsahash size is not equal!\n");
1992 		fastboot_tx_write_str("FAILperm attribute rsahash size error");
1993 		return;
1994 	}
1995 
1996 	if (rk_avb_set_perm_attr_cer((uint8_t *)CONFIG_FASTBOOT_BUF_ADDR,
1997 				     download_bytes)) {
1998 		fastboot_tx_write_str("FAILSet perm attr cer fail!");
1999 		return;
2000 	}
2001 
2002 	fastboot_tx_write_str("OKAY");
2003 #else
2004 	fastboot_tx_write_str("FAILnot implemented");
2005 #endif
2006 }
2007 
cb_oem(struct usb_ep * ep,struct usb_request * req)2008 static void cb_oem(struct usb_ep *ep, struct usb_request *req)
2009 {
2010 	char *cmd = req->buf;
2011 
2012 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
2013 	if (strncmp("format", cmd + 4, 6) == 0) {
2014 		char cmdbuf[32];
2015 		sprintf(cmdbuf, "gpt write mmc %x $partitions",
2016 			CONFIG_FASTBOOT_FLASH_MMC_DEV);
2017 #ifdef CONFIG_ANDROID_AB
2018 		if (should_prevent_userdata_wipe()) {
2019 			printf("FAILThe virtual A/B merging, can not format!\n");
2020 			fastboot_tx_write_str("FAILvirtual A/B merging,abort format!");
2021 		} else {
2022 			if (run_command(cmdbuf, 0))
2023 				fastboot_tx_write_str("FAILmmc write failure");
2024 			else
2025 				fastboot_tx_write_str("OKAY");
2026 		}
2027 #else
2028 	if (run_command(cmdbuf, 0))
2029 		fastboot_tx_write_str("FAILmmc write failure");
2030 	else
2031 		fastboot_tx_write_str("OKAY");
2032 #endif
2033 	} else
2034 #endif
2035 	if (strncmp("unlock", cmd + 4, 8) == 0) {
2036 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
2037 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2038 		fastboot_tx_write_str("FAILnot implemented");
2039 		return;
2040 #else
2041 		uint8_t unlock = 0;
2042 		TEEC_Result result;
2043 		debug("oem unlock\n");
2044 		result = trusty_read_oem_unlock(&unlock);
2045 		if (result) {
2046 			printf("read oem unlock status with error : 0x%x\n", result);
2047 			fastboot_tx_write_str("FAILRead oem unlock status failed");
2048 			return;
2049 		}
2050 		if (unlock) {
2051 			printf("oem unlock ignored, device already unlocked\n");
2052 			fastboot_tx_write_str("FAILalready unlocked");
2053 			return;
2054 		}
2055 		printf("oem unlock requested:\n");
2056 		printf("\tUnlocking forces a factory reset and could\n");
2057 		printf("\topen your device up to a world of hurt.  If you\n");
2058 		printf("\tare sure you know what you're doing, then accept\n");
2059 		printf("\tvia 'fastboot oem unlock_accept'.\n");
2060 		env_set("unlock", "unlock");
2061 		fastboot_tx_write_str("OKAY");
2062 #endif
2063 #else
2064 		fastboot_tx_write_str("FAILnot implemented");
2065 		return;
2066 #endif
2067 	} else if (strncmp("unlock_accept", cmd + 4, 13) == 0) {
2068 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
2069 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2070 		fastboot_tx_write_str("FAILnot implemented");
2071 		return;
2072 #else
2073 		char *unlock = env_get("unlock");
2074 		TEEC_Result result;
2075 		debug("oem unlock_accept\n");
2076 		if (unlock == NULL || strncmp("unlock", unlock, 6) != 0) {
2077 			printf("oem unlock_accept ignored, not pending\n");
2078 			fastboot_tx_write_str("FAILoem unlock not requested");
2079 			return;
2080 		}
2081 		env_set("unlock", "");
2082 		printf("Erasing userdata partition\n");
2083 		struct blk_desc *dev_desc;
2084 		disk_partition_t part_info;
2085 		dev_desc = rockchip_get_bootdev();
2086 		if (!dev_desc) {
2087 			printf("%s: dev_desc is NULL!\n", __func__);
2088 			return;
2089 		}
2090 		int ret = part_get_info_by_name(dev_desc, "userdata",
2091 				&part_info);
2092 		if (ret < 0) {
2093 			printf("not found userdata partition");
2094 			printf("Erase failed with error %d\n", ret);
2095 			fastboot_tx_write_str("FAILErasing userdata failed");
2096 			return;
2097 		}
2098 		ret = blk_derase(dev_desc, part_info.start, part_info.size);
2099 		if (ret != part_info.size) {
2100 			printf("Erase failed with error %d\n", ret);
2101 			fastboot_tx_write_str("FAILErasing userdata failed");
2102 			return;
2103 		}
2104 		printf("Erasing succeeded\n");
2105 
2106 		result = trusty_write_oem_unlock(1);
2107 		if (result) {
2108 			printf("write oem unlock status with error : 0x%x\n", result);
2109 			fastboot_tx_write_str("FAILWrite oem unlock status failed");
2110 			return;
2111 		}
2112 		fastboot_tx_write_str("OKAY");
2113 
2114 		/*
2115 		 * now reboot into recovery to do a format of the
2116 		 * userdata partition so it's ready to use on next boot
2117 		 */
2118 		board_run_recovery_wipe_data();
2119 #endif
2120 #else
2121 		fastboot_tx_write_str("FAILnot implemented");
2122 		return;
2123 #endif
2124 	} else if (strncmp("lock", cmd + 4, 8) == 0) {
2125 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
2126 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2127 		fastboot_tx_write_str("FAILnot implemented");
2128 		return;
2129 #else
2130 		TEEC_Result result;
2131 		uint8_t unlock = 0;
2132 		trusty_read_oem_unlock(&unlock);
2133 		if (!unlock) {
2134 			printf("oem lock ignored, already locked\n");
2135 			fastboot_tx_write_str("FAILalready locked");
2136 			return;
2137 		}
2138 
2139 		result = trusty_write_oem_unlock(0);
2140 		if (result) {
2141 			printf("write oem unlock status with error : 0x%x\n", result);
2142 			fastboot_tx_write_str("FAILWrite oem unlock status failed");
2143 			return;
2144 		}
2145 		fastboot_tx_write_str("OKAY");
2146 #endif
2147 #else
2148 		fastboot_tx_write_str("FAILnot implemented");
2149 		return;
2150 #endif
2151 	} else if (strncmp("at-get-ca-request", cmd + 4, 17) == 0) {
2152 #ifdef CONFIG_OPTEE_CLIENT
2153 		uint8_t out[ATTEST_CA_OUT_SIZE];
2154 		uint32_t operation_size = download_bytes;
2155 		uint32_t out_len = ATTEST_CA_OUT_SIZE;
2156 		uint32_t res = 0;
2157 
2158 		res = trusty_attest_get_ca((uint8_t *)CONFIG_FASTBOOT_BUF_ADDR,
2159 					   &operation_size, out, &out_len);
2160 		if (res) {
2161 			fastboot_tx_write_str("FAILtrusty_attest_get_ca failed");
2162 			return;
2163 		}
2164 		upload_size = out_len;
2165 		memcpy((void *)CONFIG_FASTBOOT_BUF_ADDR, out, out_len);
2166 		fastboot_tx_write_str("OKAY");
2167 #else
2168 		fastboot_tx_write_str("FAILnot implemented");
2169 		return;
2170 #endif
2171 	} else if (strncmp("at-set-ca-response", cmd + 4, 18) == 0) {
2172 #ifdef CONFIG_OPTEE_CLIENT
2173 		uint32_t ca_response_size = download_bytes;
2174 		uint32_t res = 0;
2175 
2176 		res = trusty_attest_set_ca((uint8_t *)CONFIG_FASTBOOT_BUF_ADDR,
2177 					   &ca_response_size);
2178 		if (res)
2179 			fastboot_tx_write_str("FAILtrusty_attest_set_ca failed");
2180 		else
2181 			fastboot_tx_write_str("OKAY");
2182 #else
2183 		fastboot_tx_write_str("FAILnot implemented");
2184 		return;
2185 #endif
2186 	} else if (strncmp("at-get-vboot-unlock-challenge", cmd + 4, 29) == 0) {
2187 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2188 		uint32_t challenge_len = 0;
2189 		int ret = 0;
2190 
2191 		ret = rk_generate_unlock_challenge((void *)CONFIG_FASTBOOT_BUF_ADDR, &challenge_len);
2192 		if (ret == 0) {
2193 			upload_size = challenge_len;
2194 			fastboot_tx_write_str("OKAY");
2195 		} else {
2196 			fastboot_tx_write_str("FAILgenerate unlock challenge fail!");
2197 		}
2198 #else
2199 		fastboot_tx_write_str("FAILnot implemented");
2200 		return;
2201 #endif
2202 	} else if (strncmp("at-lock-vboot", cmd + 4, 13) == 0) {
2203 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2204 		uint8_t lock_state;
2205 		lock_state = 0;
2206 		if (rk_avb_write_lock_state(lock_state))
2207 			fastboot_tx_write_str("FAILwrite lock state failed");
2208 		else
2209 			fastboot_tx_write_str("OKAY");
2210 #else
2211 		fastboot_tx_write_str("FAILnot implemented");
2212 #endif
2213 	} else if (strncmp("at-unlock-vboot", cmd + 4, 15) == 0) {
2214 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2215 		uint8_t lock_state;
2216 		char out_is_trusted = true;
2217 
2218 		if (rk_avb_read_lock_state(&lock_state))
2219 			fastboot_tx_write_str("FAILlock sate read failure");
2220 		if (lock_state >> 1 == 1) {
2221 			fastboot_tx_write_str("FAILThe vboot is disable!");
2222 		} else {
2223 			lock_state = 1;
2224 #ifdef CONFIG_RK_AVB_LIBAVB_ENABLE_ATH_UNLOCK
2225 			if (rk_auth_unlock((void *)CONFIG_FASTBOOT_BUF_ADDR,
2226 					   &out_is_trusted)) {
2227 				printf("rk_auth_unlock ops error!\n");
2228 				fastboot_tx_write_str("FAILrk_auth_unlock ops error!");
2229 				return;
2230 			}
2231 #endif
2232 			if (out_is_trusted == true) {
2233 				if (rk_avb_write_lock_state(lock_state))
2234 					fastboot_tx_write_str("FAILwrite lock state failed");
2235 				else
2236 					fastboot_tx_write_str("OKAY");
2237 			} else {
2238 				fastboot_tx_write_str("FAILauthenticated unlock fail");
2239 			}
2240 		}
2241 #else
2242 		fastboot_tx_write_str("FAILnot implemented");
2243 #endif
2244 	} else if (strncmp("fuse at-perm-attr", cmd + 4, 16) == 0) {
2245 		cb_oem_perm_attr();
2246 	} else if (strncmp("fuse at-rsa-perm-attr", cmd + 4, 25) == 0) {
2247 		cb_oem_perm_attr_rsa_cer();
2248 	} else if (strncmp("fuse at-bootloader-vboot-key", cmd + 4, 27) == 0) {
2249 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2250 		sha256_context ctx;
2251 		uint8_t digest[SHA256_SUM_LEN];
2252 
2253 		if (download_bytes != VBOOT_KEY_HASH_SIZE) {
2254 			fastboot_tx_write_str("FAILinvalid vboot key length");
2255 			printf("The vboot key size error!\n");
2256 			return;
2257 		}
2258 
2259 		sha256_starts(&ctx);
2260 		sha256_update(&ctx, (const uint8_t *)CONFIG_FASTBOOT_BUF_ADDR,
2261 			      VBOOT_KEY_SIZE);
2262 		sha256_finish(&ctx, digest);
2263 
2264 		if (rk_avb_write_vbootkey_hash((uint8_t *)digest,
2265 					       SHA256_SUM_LEN)) {
2266 			fastboot_tx_write_str("FAILvbootkey hash write failure");
2267 			return;
2268 		}
2269 		fastboot_tx_write_str("OKAY");
2270 #else
2271 		fastboot_tx_write_str("FAILnot implemented");
2272 #endif
2273 	} else if (strncmp("init-ab-metadata", cmd + 4, 16) == 0) {
2274 #ifdef CONFIG_RK_AVB_LIBAVB_USER
2275 		if (rk_avb_init_ab_metadata()) {
2276 			fastboot_tx_write_str("FAILinit ab data fail!");
2277 			return;
2278 		}
2279 		fastboot_tx_write_str("OKAY");
2280 #else
2281 		fastboot_tx_write_str("FAILnot implemented");
2282 #endif
2283 	} else {
2284 		fastboot_tx_write_str("FAILunknown oem command");
2285 	}
2286 }
2287 
2288 #ifdef CONFIG_FASTBOOT_FLASH
cb_erase(struct usb_ep * ep,struct usb_request * req)2289 static void cb_erase(struct usb_ep *ep, struct usb_request *req)
2290 {
2291 	char *cmd = req->buf;
2292 	char response[FASTBOOT_RESPONSE_LEN] = {0};
2293 
2294 	strsep(&cmd, ":");
2295 	if (!cmd) {
2296 		pr_err("missing partition name");
2297 		fastboot_tx_write_str("FAILmissing partition name");
2298 		return;
2299 	}
2300 #ifdef CONFIG_ANDROID_AB
2301 	if ((strcmp(cmd, PART_USERDATA) == 0) || (strcmp(cmd, PART_METADATA) == 0)) {
2302 		if (should_prevent_userdata_wipe()) {
2303 			pr_err("virtual A/B merging, can not erase userdata or metadata!\n");
2304 			fastboot_tx_write_str("FAILvirtual A/B merging,abort erase!");
2305 			return;
2306 		}
2307 	}
2308 #endif
2309 	fastboot_fail("no flash device defined", response);
2310 #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
2311 	fb_mmc_erase(cmd, response);
2312 #endif
2313 #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
2314 	fb_nand_erase(cmd, response);
2315 #endif
2316 	fastboot_tx_write_str(response);
2317 }
2318 #endif
2319 
2320 struct cmd_dispatch_info {
2321 	char *cmd;
2322 	void (*cb)(struct usb_ep *ep, struct usb_request *req);
2323 };
2324 
2325 static const struct cmd_dispatch_info cmd_dispatch_info[] = {
2326 	{
2327 		.cmd = "reboot",
2328 		.cb = cb_reboot,
2329 	}, {
2330 		.cmd = "getvar:",
2331 		.cb = cb_getvar,
2332 	}, {
2333 		.cmd = "download:",
2334 		.cb = cb_download,
2335 	}, {
2336 		.cmd = "upload",
2337 		.cb = cb_upload,
2338 	}, {
2339 		.cmd = "boot",
2340 		.cb = cb_boot,
2341 	}, {
2342 		.cmd = "continue",
2343 		.cb = cb_continue,
2344 	}, {
2345 		.cmd = "set_active",
2346 		.cb = cb_set_active,
2347 	},
2348 #ifdef CONFIG_FASTBOOT_FLASH
2349 	{
2350 		.cmd = "flashing",
2351 		.cb = cb_flashing,
2352 	},
2353 	{
2354 		.cmd = "flash",
2355 		.cb = cb_flash,
2356 	}, {
2357 		.cmd = "erase",
2358 		.cb = cb_erase,
2359 	},
2360 #endif
2361 	{
2362 		.cmd = "oem",
2363 		.cb = cb_oem,
2364 	},
2365 };
2366 
rx_handler_command(struct usb_ep * ep,struct usb_request * req)2367 static void rx_handler_command(struct usb_ep *ep, struct usb_request *req)
2368 {
2369 	char *cmdbuf = req->buf;
2370 	void (*func_cb)(struct usb_ep *ep, struct usb_request *req) = NULL;
2371 	int i;
2372 
2373 	if (req->status != 0 || req->length == 0)
2374 		return;
2375 
2376 	for (i = 0; i < ARRAY_SIZE(cmd_dispatch_info); i++) {
2377 		if (!strcmp_l1(cmd_dispatch_info[i].cmd, cmdbuf)) {
2378 			func_cb = cmd_dispatch_info[i].cb;
2379 			break;
2380 		}
2381 	}
2382 
2383 	if (!func_cb) {
2384 		pr_err("unknown command: %.*s", req->actual, cmdbuf);
2385 		fastboot_tx_write_str("FAILunknown command");
2386 	} else {
2387 		if (req->actual < req->length) {
2388 			u8 *buf = (u8 *)req->buf;
2389 			buf[req->actual] = 0;
2390 			func_cb(ep, req);
2391 		} else {
2392 			pr_err("buffer overflow");
2393 			fastboot_tx_write_str("FAILbuffer overflow");
2394 		}
2395 	}
2396 
2397 	*cmdbuf = '\0';
2398 	req->actual = 0;
2399 	usb_ep_queue(ep, req, 0);
2400 }
2401