Blame view

drivers/usb/gadget/f_fastboot.c 118 KB
3aab70afc   Sebastian Siewior   usb/gadget: add t...
1
2
3
4
5
6
7
8
9
10
  /*
   * (C) Copyright 2008 - 2009
   * Windriver, <www.windriver.com>
   * Tom Rix <Tom.Rix@windriver.com>
   *
   * Copyright 2011 Sebastian Andrzej Siewior <bigeasy@linutronix.de>
   *
   * Copyright 2014 Linaro, Ltd.
   * Rob Herring <robh@kernel.org>
   *
2c840c82b   Ye Li   MLK-18591-3 andro...
11
12
13
   * Copyright (C) 2015-2016 Freescale Semiconductor, Inc.
   * Copyright 2017 NXP
   *
3aab70afc   Sebastian Siewior   usb/gadget: add t...
14
15
   * SPDX-License-Identifier:	GPL-2.0+
   */
593cbd93f   Steve Rae   usb/gadget: fastb...
16
  #include <config.h>
3aab70afc   Sebastian Siewior   usb/gadget: add t...
17
18
  #include <common.h>
  #include <errno.h>
2c840c82b   Ye Li   MLK-18591-3 andro...
19
  #include <stdlib.h>
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
20
  #include <fastboot.h>
3aab70afc   Sebastian Siewior   usb/gadget: add t...
21
22
23
24
25
26
27
  #include <malloc.h>
  #include <linux/usb/ch9.h>
  #include <linux/usb/gadget.h>
  #include <linux/usb/composite.h>
  #include <linux/compiler.h>
  #include <version.h>
  #include <g_dnl.h>
2c840c82b   Ye Li   MLK-18591-3 andro...
28
  #include "../lib/avb/fsl/utils.h"
d1b5ed075   Steve Rae   usb/gadget: fastb...
29
30
31
  #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
  #include <fb_mmc.h>
  #endif
1ae9ecc73   Ye Li   MLK-18591-6 andro...
32
33
  
  #ifdef CONFIG_IMX_TRUSTY_OS
979995530   Yu Shan   [iot] Support ata...
34
35
  #define ATAP_UUID_SIZE 32
  #define ATAP_UUID_STR_SIZE ((ATAP_UUID_SIZE*2) + 1)
1ae9ecc73   Ye Li   MLK-18591-6 andro...
36
37
38
39
  extern int armv7_init_nonsec(void);
  extern void trusty_os_init(void);
  #include <trusty/libtipc.h>
  #endif
bf8940d35   Maxime Ripard   fastboot: Impleme...
40
41
42
  #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
  #include <fb_nand.h>
  #endif
3aab70afc   Sebastian Siewior   usb/gadget: add t...
43

2c840c82b   Ye Li   MLK-18591-3 andro...
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  #ifdef CONFIG_FSL_FASTBOOT
  #include <asm/mach-imx/sys_proto.h>
  #include <fsl_fastboot.h>
  #include <mmc.h>
  #include <android_image.h>
  #include <asm/bootm.h>
  #include <nand.h>
  #include <part.h>
  #include <sparse_format.h>
  #include <image-sparse.h>
  #include <image.h>
  #include <asm/mach-imx/boot_mode.h>
  #include <asm/arch/sys_proto.h>
  #include <asm/setup.h>
  #include <environment.h>
  #ifdef CONFIG_ANDROID_RECOVERY
  #include <recovery.h>
  #endif
23c5c1858   Luo Ji   [iot] Add fastboo...
62
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
63
64
65
66
67
68
  
  #ifdef CONFIG_BCB_SUPPORT
  #include "bcb.h"
  #endif
  
  #ifdef CONFIG_AVB_SUPPORT
153021557   Braden Kell   [iot] Load fdt fr...
69
  #include <dt_table.h>
2c840c82b   Ye Li   MLK-18591-3 andro...
70
71
  #include <fsl_avb.h>
  #endif
23c5c1858   Luo Ji   [iot] Add fastboo...
72
73
74
  #ifdef CONFIG_ANDROID_THINGS_SUPPORT
  #include <asm-generic/gpio.h>
  #include <asm/mach-imx/gpio.h>
b57739cac   Ji Luo   [iot] Support fas...
75
76
  #include "../lib/avb/fsl/fsl_avbkey.h"
  #include "../arch/arm/include/asm/mach-imx/hab.h"
23c5c1858   Luo Ji   [iot] Add fastboo...
77
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
78
79
80
  #ifdef CONFIG_FASTBOOT_LOCK
  #include "fastboot_lock_unlock.h"
  #endif
23c5c1858   Luo Ji   [iot] Add fastboo...
81

26131b634   Ji Luo   [iot] Calculate V...
82
83
84
85
86
  #if defined(CONFIG_IMX_TRUSTY_OS) && defined(CONFIG_DUAL_BOOTLOADER)
  #include "u-boot/sha256.h"
  #endif
  
  #define FASTBOOT_VERSION		"0.4"
23c5c1858   Luo Ji   [iot] Add fastboo...
87
88
89
90
  #if defined(CONFIG_ANDROID_THINGS_SUPPORT) && defined(CONFIG_ARCH_IMX8M)
  #define FASTBOOT_COMMON_VAR_NUM 14
  #else
  #define FASTBOOT_COMMON_VAR_NUM 13
2c840c82b   Ye Li   MLK-18591-3 andro...
91
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
92
93
  #define FASTBOOT_VAR_YES    "yes"
  #define FASTBOOT_VAR_NO     "no"
3aab70afc   Sebastian Siewior   usb/gadget: add t...
94
95
96
97
98
99
100
  #define FASTBOOT_INTERFACE_CLASS	0xff
  #define FASTBOOT_INTERFACE_SUB_CLASS	0x42
  #define FASTBOOT_INTERFACE_PROTOCOL	0x03
  
  #define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_2_0  (0x0200)
  #define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_1_1  (0x0040)
  #define TX_ENDPOINT_MAXIMUM_PACKET_SIZE      (0x0040)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
101
  #define EP_BUFFER_SIZE			4096
2c840c82b   Ye Li   MLK-18591-3 andro...
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
  
  #ifdef CONFIG_FSL_FASTBOOT
  
  #define ANDROID_GPT_OFFSET         0
  #define ANDROID_GPT_SIZE           0x100000
  #define ANDROID_GPT_END	           0x4400
  
  #ifdef CONFIG_FLASH_MCUFIRMWARE_SUPPORT
  struct fastboot_device_info fastboot_firmwareinfo;
  #endif
  
  #if defined (CONFIG_ARCH_IMX8) || defined (CONFIG_ARCH_IMX8M)
  #define DST_DECOMPRESS_LEN 1024*1024*32
  #endif
  
  #endif
156a16fd8   Luo Ji   [iot] Add AVB ver...
118

156a16fd8   Luo Ji   [iot] Add AVB ver...
119
120
121
122
123
  #ifdef CONFIG_ANDROID_THINGS_SUPPORT
  #define FDT_PART_NAME "oem_bootloader"
  #else
  #define FDT_PART_NAME "dtbo"
  #endif
156a16fd8   Luo Ji   [iot] Add AVB ver...
124

9a3670492   faqiang.zhu   MA-12283-3 chage ...
125
  #define MEK_8QM_EMMC 0
ac484c5a6   Roger Quadros   fastboot: Clean u...
126
127
128
129
130
  /*
   * EP_BUFFER_SIZE must always be an integral multiple of maxpacket size
   * (64 or 512 or 1024), else we break on certain controllers like DWC3
   * that expect bulk OUT requests to be divisible by maxpacket size.
   */
3aab70afc   Sebastian Siewior   usb/gadget: add t...
131

5eb21386c   Braden Kell   [iot] Copy fdt fr...
132
133
134
  /* Offset (in u32's) of start and end fields in the zImage header. */
  #define ZIMAGE_START_ADDR	10
  #define ZIMAGE_END_ADDR	11
2c840c82b   Ye Li   MLK-18591-3 andro...
135
136
137
138
139
140
141
142
143
144
145
146
147
148
  /* common variables of fastboot getvar command */
  char *fastboot_common_var[FASTBOOT_COMMON_VAR_NUM] = {
  	"version",
  	"version-bootloader",
  	"version-baseband",
  	"product",
  	"secure",
  	"max-download-size",
  	"erase-block-size",
  	"logical-block-size",
  	"unlocked",
  	"off-mode-charge",
  	"battery-voltage",
  	"variant",
23c5c1858   Luo Ji   [iot] Add fastboo...
149
150
151
152
  	"battery-soc-ok",
  #if defined(CONFIG_ANDROID_THINGS_SUPPORT) && defined(CONFIG_ARCH_IMX8M)
  	"baseboard_id"
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
153
  };
b57739cac   Ji Luo   [iot] Support fas...
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
  /* at-vboot-state variable list */
  #ifdef CONFIG_AVB_ATX
  #define AT_VBOOT_STATE_VAR_NUM 6
  extern struct imx_sec_config_fuse_t const imx_sec_config_fuse;
  extern int fuse_read(u32 bank, u32 word, u32 *val);
  
  char *fastboot_at_vboot_state_var[AT_VBOOT_STATE_VAR_NUM] = {
  	"bootloader-locked",
  	"bootloader-min-versions",
  	"avb-perm-attr-set",
  	"avb-locked",
  	"avb-unlock-disabled",
  	"avb-min-versions"
  };
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
  /* Boot metric variables */
  boot_metric metrics = {
  	.bll_1 = 0,
  	.ble_1 = 0,
  	.kl    = 0,
  	.kd    = 0,
  	.avb   = 0,
  	.odt   = 0,
  	.sw    = 0
  };
  
  typedef struct usb_req usb_req;
  struct usb_req {
  	struct usb_request *in_req;
  	usb_req *next;
  };
3aab70afc   Sebastian Siewior   usb/gadget: add t...
185
186
  struct f_fastboot {
  	struct usb_function usb_function;
593cbd93f   Steve Rae   usb/gadget: fastb...
187
  	/* IN/OUT EP's and corresponding requests */
3aab70afc   Sebastian Siewior   usb/gadget: add t...
188
189
  	struct usb_ep *in_ep, *out_ep;
  	struct usb_request *in_req, *out_req;
2c840c82b   Ye Li   MLK-18591-3 andro...
190
  	usb_req *front, *rear;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
191
  };
a505d1ed5   Li Jun   MLK-18376-5 usb: ...
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
  static char fb_ext_prop_name[] = "DeviceInterfaceGUID";
  static char fb_ext_prop_data[] = "{4866319A-F4D6-4374-93B9-DC2DEB361BA9}";
  
  static struct usb_os_desc_ext_prop fb_ext_prop = {
  	.type = 1,		/* NUL-terminated Unicode String (REG_SZ) */
  	.name = fb_ext_prop_name,
  	.data = fb_ext_prop_data,
  };
  
  /* 16 bytes of "Compatible ID" and "Subcompatible ID" */
  static char fb_cid[16] = {'W', 'I', 'N', 'U', 'S', 'B'};
  static struct usb_os_desc fb_os_desc = {
  	.ext_compat_id = fb_cid,
  };
  
  static struct usb_os_desc_table fb_os_desc_table = {
  	.os_desc = &fb_os_desc,
  };
3aab70afc   Sebastian Siewior   usb/gadget: add t...
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  static inline struct f_fastboot *func_to_fastboot(struct usb_function *f)
  {
  	return container_of(f, struct f_fastboot, usb_function);
  }
  
  static struct f_fastboot *fastboot_func;
  static unsigned int download_size;
  static unsigned int download_bytes;
  
  static struct usb_endpoint_descriptor fs_ep_in = {
  	.bLength            = USB_DT_ENDPOINT_SIZE,
  	.bDescriptorType    = USB_DT_ENDPOINT,
  	.bEndpointAddress   = USB_DIR_IN,
  	.bmAttributes       = USB_ENDPOINT_XFER_BULK,
718156ad0   Roger Quadros   fastboot: Fix wMa...
224
  	.wMaxPacketSize     = cpu_to_le16(64),
3aab70afc   Sebastian Siewior   usb/gadget: add t...
225
226
227
228
229
230
231
  };
  
  static struct usb_endpoint_descriptor fs_ep_out = {
  	.bLength		= USB_DT_ENDPOINT_SIZE,
  	.bDescriptorType	= USB_DT_ENDPOINT,
  	.bEndpointAddress	= USB_DIR_OUT,
  	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
718156ad0   Roger Quadros   fastboot: Fix wMa...
232
233
234
235
236
237
238
239
240
  	.wMaxPacketSize		= cpu_to_le16(64),
  };
  
  static struct usb_endpoint_descriptor hs_ep_in = {
  	.bLength		= USB_DT_ENDPOINT_SIZE,
  	.bDescriptorType	= USB_DT_ENDPOINT,
  	.bEndpointAddress	= USB_DIR_IN,
  	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
  	.wMaxPacketSize		= cpu_to_le16(512),
3aab70afc   Sebastian Siewior   usb/gadget: add t...
241
242
243
244
245
246
247
  };
  
  static struct usb_endpoint_descriptor hs_ep_out = {
  	.bLength		= USB_DT_ENDPOINT_SIZE,
  	.bDescriptorType	= USB_DT_ENDPOINT,
  	.bEndpointAddress	= USB_DIR_OUT,
  	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
718156ad0   Roger Quadros   fastboot: Fix wMa...
248
  	.wMaxPacketSize		= cpu_to_le16(512),
3aab70afc   Sebastian Siewior   usb/gadget: add t...
249
250
251
252
253
254
255
256
257
258
259
260
  };
  
  static struct usb_interface_descriptor interface_desc = {
  	.bLength		= USB_DT_INTERFACE_SIZE,
  	.bDescriptorType	= USB_DT_INTERFACE,
  	.bInterfaceNumber	= 0x00,
  	.bAlternateSetting	= 0x00,
  	.bNumEndpoints		= 0x02,
  	.bInterfaceClass	= FASTBOOT_INTERFACE_CLASS,
  	.bInterfaceSubClass	= FASTBOOT_INTERFACE_SUB_CLASS,
  	.bInterfaceProtocol	= FASTBOOT_INTERFACE_PROTOCOL,
  };
718156ad0   Roger Quadros   fastboot: Fix wMa...
261
  static struct usb_descriptor_header *fb_fs_function[] = {
3aab70afc   Sebastian Siewior   usb/gadget: add t...
262
263
  	(struct usb_descriptor_header *)&interface_desc,
  	(struct usb_descriptor_header *)&fs_ep_in,
718156ad0   Roger Quadros   fastboot: Fix wMa...
264
265
266
267
268
269
  	(struct usb_descriptor_header *)&fs_ep_out,
  };
  
  static struct usb_descriptor_header *fb_hs_function[] = {
  	(struct usb_descriptor_header *)&interface_desc,
  	(struct usb_descriptor_header *)&hs_ep_in,
3aab70afc   Sebastian Siewior   usb/gadget: add t...
270
271
272
  	(struct usb_descriptor_header *)&hs_ep_out,
  	NULL,
  };
8b704a0e3   Roger Quadros   fastboot: Enable ...
273
274
275
276
277
278
279
280
  static struct usb_endpoint_descriptor *
  fb_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
  	    struct usb_endpoint_descriptor *hs)
  {
  	if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
  		return hs;
  	return fs;
  }
3aab70afc   Sebastian Siewior   usb/gadget: add t...
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
  /*
   * static strings, in UTF-8
   */
  static const char fastboot_name[] = "Android Fastboot";
  
  static struct usb_string fastboot_string_defs[] = {
  	[0].s = fastboot_name,
  	{  }			/* end of list */
  };
  
  static struct usb_gadget_strings stringtab_fastboot = {
  	.language	= 0x0409,	/* en-us */
  	.strings	= fastboot_string_defs,
  };
  
  static struct usb_gadget_strings *fastboot_strings[] = {
  	&stringtab_fastboot,
  	NULL,
  };
2c840c82b   Ye Li   MLK-18591-3 andro...
300
301
302
303
304
305
306
  static void rx_handler_command(struct usb_ep *ep, struct usb_request *req);
  static int strcmp_l1(const char *s1, const char *s2);
  
  
  static char *fb_response_str;
  
  #ifdef CONFIG_FSL_FASTBOOT
1ae9ecc73   Ye Li   MLK-18591-6 andro...
307
308
309
310
311
312
  #ifndef TRUSTY_OS_MMC_BLKS
  #define TRUSTY_OS_MMC_BLKS 0x7FF
  #endif
  #ifndef TEE_HWPARTITION_ID
  #define TEE_HWPARTITION_ID 2
  #endif
5423ef478   Frank Li   MLK-18406 fastboo...
313
  #define FASTBOOT_PARTITION_ALL "all"
2c840c82b   Ye Li   MLK-18591-3 andro...
314
315
  #define ANDROID_MBR_OFFSET	    0
  #define ANDROID_MBR_SIZE	    0x200
502522c08   Haoran.Wang   [iot] Support ARM...
316
  #define ANDROID_BOOTLOADER_SIZE	    0x400000
2c840c82b   Ye Li   MLK-18591-3 andro...
317
318
319
320
321
322
323
  
  #define MMC_SATA_BLOCK_SIZE 512
  #define FASTBOOT_FBPARTS_ENV_MAX_LEN 1024
  /* To support the Android-style naming of flash */
  #define MAX_PTN		    32
  struct fastboot_ptentry g_ptable[MAX_PTN];
  unsigned int g_pcount;
a251b17f4   Ye Li   MLK-19356 fastboo...
324
  struct fastboot_device_info fastboot_devinfo = {0xff, 0xff};
2c840c82b   Ye Li   MLK-18591-3 andro...
325
326
327
328
  
  
  enum {
  	PTN_GPT_INDEX = 0,
1ae9ecc73   Ye Li   MLK-18591-6 andro...
329
  	PTN_TEE_INDEX,
2c840c82b   Ye Li   MLK-18591-3 andro...
330
331
332
  #ifdef CONFIG_FLASH_MCUFIRMWARE_SUPPORT
  	PTN_M4_OS_INDEX,
  #endif
5423ef478   Frank Li   MLK-18406 fastboo...
333
  	PTN_ALL_INDEX,
2c840c82b   Ye Li   MLK-18591-3 andro...
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
  	PTN_BOOTLOADER_INDEX,
  };
  static unsigned int download_bytes_unpadded;
  
  static struct cmd_fastboot_interface interface = {
  	.rx_handler            = NULL,
  	.reset_handler         = NULL,
  	.product_name          = NULL,
  	.serial_no             = NULL,
  	.nand_block_size       = 0,
  	.transfer_buffer       = (unsigned char *)0xffffffff,
  	.transfer_buffer_size  = 0,
  };
  
  int read_from_partition_multi(const char* partition,
  		int64_t offset, size_t num_bytes, void* buffer, size_t* out_num_read)
  {
  	struct fastboot_ptentry *pte;
  	unsigned char *bdata;
  	unsigned char *out_buf = (unsigned char *)buffer;
  	unsigned char *dst, *dst64 = NULL;
  	unsigned long blksz;
  	unsigned long s, cnt;
  	size_t num_read = 0;
  	lbaint_t part_start, part_end, bs, be, bm, blk_num;
  	margin_pos_t margin;
  	struct blk_desc *fs_dev_desc = NULL;
  	int dev_no;
  	int ret;
  
  	assert(buffer != NULL && out_num_read != NULL);
  
  	dev_no = mmc_get_env_dev();
  	if ((fs_dev_desc = blk_get_dev("mmc", dev_no)) == NULL) {
  		printf("mmc device not found
  ");
  		return -1;
  	}
  
  	pte = fastboot_flash_find_ptn(partition);
  	if (!pte) {
  		printf("no %s partition
  ", partition);
c2763113a   Ji Luo   MA-12358 Only dum...
377
  		fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
  		return -1;
  	}
  
  	blksz = fs_dev_desc->blksz;
  	part_start = pte->start;
  	part_end = pte->start + pte->length - 1;
  
  	if (get_margin_pos((uint64_t)part_start, (uint64_t)part_end, blksz,
  				&margin, offset, num_bytes, true))
  		return -1;
  
  	bs = (lbaint_t)margin.blk_start;
  	be = (lbaint_t)margin.blk_end;
  	s = margin.start;
  	bm = margin.multi;
  
  	/* alloc a blksz mem */
  	bdata = (unsigned char *)memalign(ALIGN_BYTES, blksz);
  	if (bdata == NULL) {
  		printf("Failed to allocate memory!
  ");
  		return -1;
  	}
  
  	/* support multi blk read */
  	while (bs <= be) {
  		if (!s && bm > 1) {
  			dst = out_buf;
  			dst64 = PTR_ALIGN(out_buf, 64); /* for mmc blk read alignment */
  			if (dst64 != dst) {
  				dst = dst64;
  				bm--;
  			}
  			blk_num = bm;
  			cnt = bm * blksz;
  			bm = 0; /* no more multi blk */
  		} else {
  			blk_num = 1;
  			cnt = blksz - s;
  			if (num_read + cnt > num_bytes)
  				cnt = num_bytes - num_read;
  			dst = bdata;
  		}
  		if (blk_dread(fs_dev_desc, bs, blk_num, dst) != blk_num) {
  			ret = -1;
  			goto fail;
  		}
  
  		if (dst == bdata)
  			memcpy(out_buf, bdata + s, cnt);
  		else if (dst == dst64)
  			memcpy(out_buf, dst, cnt); /* internal copy */
  
  		s = 0;
  		bs += blk_num;
  		num_read += cnt;
  		out_buf += cnt;
  	}
  	*out_num_read = num_read;
  	ret = 0;
  
  fail:
  	free(bdata);
  	return ret;
  }
  
  static void save_env(struct fastboot_ptentry *ptn,
  		     char *var, char *val)
  {
  	env_set(var, val);
  	env_save();
  }
  
  /* When save = 0, just parse.  The input is unchanged
     When save = 1, parse and do the save.  The input is changed */
  static int parse_env(void *ptn, char *err_string, int save, int debug)
  {
  	int ret = 1;
  	unsigned int sets = 0;
  	unsigned int comment_start = 0;
  	char *var = NULL;
  	char *var_end = NULL;
  	char *val = NULL;
  	char *val_end = NULL;
  	unsigned int i;
  
  	char *buff = (char *)interface.transfer_buffer;
  	unsigned int size = download_bytes_unpadded;
  
  	/* The input does not have to be null terminated.
  	   This will cause a problem in the corner case
  	   where the last line does not have a new line.
  	   Put a null after the end of the input.
  
  	   WARNING : Input buffer is assumed to be bigger
  	   than the size of the input */
  	if (save)
  		buff[size] = 0;
  
  	for (i = 0; i < size; i++) {
  
  		if (NULL == var) {
  
  			/*
  			 * Check for comments, comment ok only on
  			 * mostly empty lines
  			 */
  			if (buff[i] == '#')
  				comment_start = 1;
  
  			if (comment_start) {
  				if  ((buff[i] == '\r') ||
  				     (buff[i] == '
  ')) {
  					comment_start = 0;
  				}
  			} else {
  				if (!((buff[i] == ' ') ||
  				      (buff[i] == '\t') ||
  				      (buff[i] == '\r') ||
  				      (buff[i] == '
  '))) {
  					/*
  					 * Normal whitespace before the
  					 * variable
  					 */
  					var = &buff[i];
  				}
  			}
  
  		} else if (((NULL == var_end) || (NULL == val)) &&
  			   ((buff[i] == '\r') || (buff[i] == '
  '))) {
  
  			/* This is the case when a variable
  			   is unset. */
  
  			if (save) {
  				/* Set the var end to null so the
  				   normal string routines will work
  
  				   WARNING : This changes the input */
  				buff[i] = '\0';
  
  				save_env(ptn, var, val);
  
  				if (debug)
  					printf("Unsetting %s
  ", var);
  			}
  
  			/* Clear the variable so state is parse is back
  			   to initial. */
  			var = NULL;
  			var_end = NULL;
  			sets++;
  		} else if (NULL == var_end) {
  			if ((buff[i] == ' ') ||
  			    (buff[i] == '\t'))
  				var_end = &buff[i];
  		} else if (NULL == val) {
  			if (!((buff[i] == ' ') ||
  			      (buff[i] == '\t')))
  				val = &buff[i];
  		} else if (NULL == val_end) {
  			if ((buff[i] == '\r') ||
  			    (buff[i] == '
  ')) {
  				/* look for escaped cr or ln */
  				if ('\\' == buff[i - 1]) {
  					/* check for dos */
  					if ((buff[i] == '\r') &&
  					    (buff[i+1] == '
  '))
  						buff[i + 1] = ' ';
  					buff[i - 1] = buff[i] = ' ';
  				} else {
  					val_end = &buff[i];
  				}
  			}
  		} else {
  			sprintf(err_string, "Internal Error");
  
  			if (debug)
  				printf("Internal error at %s %d
  ",
  				       __FILE__, __LINE__);
  			return 1;
  		}
  		/* Check if a var / val pair is ready */
  		if (NULL != val_end) {
  			if (save) {
  				/* Set the end's with nulls so
  				   normal string routines will
  				   work.
  
  				   WARNING : This changes the input */
  				*var_end = '\0';
  				*val_end = '\0';
  
  				save_env(ptn, var, val);
  
  				if (debug)
  					printf("Setting %s %s
  ", var, val);
  			}
  
  			/* Clear the variable so state is parse is back
  			   to initial. */
  			var = NULL;
  			var_end = NULL;
  			val = NULL;
  			val_end = NULL;
  
  			sets++;
  		}
  	}
  
  	/* Corner case
  	   Check for the case that no newline at end of the input */
  	if ((NULL != var) &&
  	    (NULL == val_end)) {
  		if (save) {
  			/* case of val / val pair */
  			if (var_end)
  				*var_end = '\0';
  			/* else case handled by setting 0 past
  			   the end of buffer.
  			   Similar for val_end being null */
  			save_env(ptn, var, val);
  
  			if (debug) {
  				if (var_end)
  					printf("Trailing Setting %s %s
  ", var, val);
  				else
  					printf("Trailing Unsetting %s
  ", var);
  			}
  		}
  		sets++;
  	}
  	/* Did we set anything ? */
  	if (0 == sets)
  		sprintf(err_string, "No variables set");
  	else
  		ret = 0;
  
  	return ret;
  }
  
  static int saveenv_to_ptn(struct fastboot_ptentry *ptn, char *err_string)
  {
  	int ret = 1;
  	int save = 0;
  	int debug = 0;
  
  	/* err_string is only 32 bytes
  	   Initialize with a generic error message. */
  	sprintf(err_string, "%s", "Unknown Error");
  
  	/* Parse the input twice.
  	   Only save to the enviroment if the entire input if correct */
  	save = 0;
  	if (0 == parse_env(ptn, err_string, save, debug)) {
  		save = 1;
  		ret = parse_env(ptn, err_string, save, debug);
  	}
  	return ret;
  }
  
  static int get_block_size(void);
  #ifdef CONFIG_FLASH_MCUFIRMWARE_SUPPORT
  static void process_flash_sf(const char *cmdbuf)
  {
  	int blksz = 0;
  	blksz = get_block_size();
  
  	if (download_bytes) {
  		struct fastboot_ptentry *ptn;
  		ptn = fastboot_flash_find_ptn(cmdbuf);
  		if (ptn == 0) {
  			fastboot_fail("partition does not exist");
c2763113a   Ji Luo   MA-12358 Only dum...
661
  			fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
  		} else if ((download_bytes > ptn->length * blksz)) {
  			fastboot_fail("image too large for partition");
  		/* TODO : Improve check for yaffs write */
  		} else {
  			int ret;
  			char sf_command[128];
  			/* Normal case */
  			/* Probe device */
  			sprintf(sf_command, "sf probe");
  			ret = run_command(sf_command, 0);
  			if (ret){
  				fastboot_fail("Probe sf failed");
  				return;
  			}
  			/* Erase */
  			sprintf(sf_command, "sf erase 0x%x 0x%x", ptn->start * blksz, /*start*/
  			ptn->length * blksz /*size*/);
  			ret = run_command(sf_command, 0);
  			if (ret) {
  				fastboot_fail("Erasing sf failed");
  				return;
  			}
  			/* Write image */
  			sprintf(sf_command, "sf write 0x%x 0x%x 0x%x",
  					(unsigned int)(ulong)interface.transfer_buffer, /* source */
  					ptn->start * blksz, /* start */
  					download_bytes /*size*/);
  			printf("sf write '%s'
  ", ptn->name);
  			ret = run_command(sf_command, 0);
  			if (ret){
  				fastboot_fail("Writing sf failed");
  				return;
  			}
  			printf("sf write finished '%s'
  ", ptn->name);
  			fastboot_okay("");
  		}
  	} else {
  		fastboot_fail("no image downloaded");
  	}
  }
  
  #ifdef CONFIG_ARCH_IMX8M
  /* Check if the mcu image is built for running from TCM */
  static bool is_tcm_image(unsigned char *image_addr)
  {
  	u32 stack;
  
  	stack = *(u32 *)image_addr;
  
  	if ((stack != (u32)ANDROID_MCU_FIRMWARE_HEADER_STACK)) {
  		printf("Please flash mcu firmware images for running from TCM
  ");
  		return false;
  	} else
  		return true;
  }
  
  static int do_bootmcu(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
  {
  	int ret;
  	size_t out_num_read;
  	void *m4_base_addr = (void *)M4_BOOTROM_BASE_ADDR;
  	char command[32];
  
  	ret = read_from_partition_multi(FASTBOOT_MCU_FIRMWARE_PARTITION,
  			0, ANDROID_MCU_FIRMWARE_SIZE, (void *)m4_base_addr, &out_num_read);
  	if ((ret != 0) || (out_num_read != ANDROID_MCU_FIRMWARE_SIZE)) {
  		printf("Read M4 images failed!
  ");
  		return 1;
  	} else {
  		printf("run command: 'bootaux 0x%x'
  ",(unsigned int)(ulong)m4_base_addr);
  
  		sprintf(command, "bootaux 0x%x", (unsigned int)(ulong)m4_base_addr);
  		ret = run_command(command, 0);
  		if (ret) {
  			printf("run 'bootaux' command failed!
  ");
  			return 1;
  		}
  	}
  	return 0;
  }
  
  U_BOOT_CMD(
  	bootmcu, 1, 0, do_bootmcu,
  	"boot mcu images
  ",
  	"boot mcu images from 'm4_os' partition, only support images run from TCM"
  );
  #endif
  #endif /* CONFIG_FLASH_MCUFIRMWARE_SUPPORT */
065c4a2bd   Ye Li   MLK-18934 usb: fa...
757
758
759
760
  static ulong bootloader_mmc_offset(void)
  {
  	if (is_imx8m() || (is_imx8() && is_soc_rev(CHIP_REV_A)))
  		return 0x8400;
9a3670492   faqiang.zhu   MA-12283-3 chage ...
761
  	else if (is_imx8qm()) {
68261e4ca   faqiang.zhu   MA-13303 fix the ...
762
  		if (MEK_8QM_EMMC == fastboot_devinfo.dev_id)
9a3670492   faqiang.zhu   MA-12283-3 chage ...
763
764
765
766
767
768
  		/* target device is eMMC boot0 partition, bootloader offset is 0x0 */
  			return 0x0;
  		else
  		/* target device is SD card, bootloader offset is 0x8000 */
  			return 0x8000;
  	}
065c4a2bd   Ye Li   MLK-18934 usb: fa...
769
770
771
772
773
  	else if (is_imx8())
  		return 0x8000;
  	else
  		return 0x400;
  }
a612cab38   Richard Zhu   MLK-19479-2 fastb...
774
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC) || defined(CONFIG_FASTBOOT_STORAGE_SATA)
2c840c82b   Ye Li   MLK-18591-3 andro...
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
  static int is_raw_partition(struct fastboot_ptentry *ptn)
  {
  #ifdef CONFIG_ANDROID_AB_SUPPORT
  	if (ptn && (!strncmp(ptn->name, FASTBOOT_PARTITION_BOOTLOADER,
  			strlen(FASTBOOT_PARTITION_BOOTLOADER)) ||
  			!strncmp(ptn->name, FASTBOOT_PARTITION_GPT,
  			strlen(FASTBOOT_PARTITION_GPT)) ||
  			!strncmp(ptn->name, FASTBOOT_PARTITION_BOOT_A,
  			strlen(FASTBOOT_PARTITION_BOOT_A)) ||
  			!strncmp(ptn->name, FASTBOOT_PARTITION_BOOT_B,
  			strlen(FASTBOOT_PARTITION_BOOT_B)) ||
  #ifdef CONFIG_FASTBOOT_LOCK
  			!strncmp(ptn->name, FASTBOOT_PARTITION_FBMISC,
  			strlen(FASTBOOT_PARTITION_FBMISC)) ||
  #endif
  			!strncmp(ptn->name, FASTBOOT_PARTITION_MISC,
  			strlen(FASTBOOT_PARTITION_MISC)))) {
  #else
  	 if (ptn && (!strncmp(ptn->name, FASTBOOT_PARTITION_BOOTLOADER,
  		strlen(FASTBOOT_PARTITION_BOOTLOADER)) ||
  		!strncmp(ptn->name, FASTBOOT_PARTITION_BOOT,
  		strlen(FASTBOOT_PARTITION_BOOT)) ||
  #ifdef CONFIG_FASTBOOT_LOCK
  		!strncmp(ptn->name, FASTBOOT_PARTITION_FBMISC,
  		strlen(FASTBOOT_PARTITION_FBMISC)) ||
  #endif
  		!strncmp(ptn->name, FASTBOOT_PARTITION_MISC,
  		strlen(FASTBOOT_PARTITION_MISC)))) {
  #endif
  		printf("support sparse flash partition for %s
  ", ptn->name);
  		return 1;
  	 } else
  		return 0;
  }
  
  static lbaint_t mmc_sparse_write(struct sparse_storage *info,
  		lbaint_t blk, lbaint_t blkcnt, const void *buffer)
  {
  #define SPARSE_FILL_BUF_SIZE (2 * 1024 * 1024)
5423ef478   Frank Li   MLK-18406 fastboo...
815

2c840c82b   Ye Li   MLK-18591-3 andro...
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
  	struct blk_desc *dev_desc = (struct blk_desc *)info->priv;
  	ulong ret = 0;
  	void *data;
  	int fill_buf_num_blks, cnt;
  
  	if ((unsigned long)buffer & (CONFIG_SYS_CACHELINE_SIZE - 1)) {
  
  		fill_buf_num_blks = SPARSE_FILL_BUF_SIZE / info->blksz;
  
  		data = memalign(CONFIG_SYS_CACHELINE_SIZE, fill_buf_num_blks * info->blksz);
  
  		while (blkcnt) {
  
  			if (blkcnt > fill_buf_num_blks)
  				cnt = fill_buf_num_blks;
  			else
  				cnt = blkcnt;
  
  			memcpy(data, buffer, cnt * info->blksz);
  
  			ret += blk_dwrite(dev_desc, blk, cnt, data);
  
  			blk += cnt;
  			blkcnt -= cnt;
  			buffer = (void *)((unsigned long)buffer + cnt * info->blksz);
  
  		}
  
  		free(data);
  	} else {
  		ret = blk_dwrite(dev_desc, blk, blkcnt, buffer);
  	}
  
  	return ret;
  }
  
  static lbaint_t mmc_sparse_reserve(struct sparse_storage *info,
  		lbaint_t blk, lbaint_t blkcnt)
  {
  	return blkcnt;
  }
  
  /*judge wether the gpt image and bootloader image are overlay*/
  bool bootloader_gpt_overlay(void)
  {
  	return (g_ptable[PTN_GPT_INDEX].partition_id  == g_ptable[PTN_BOOTLOADER_INDEX].partition_id  &&
065c4a2bd   Ye Li   MLK-18934 usb: fa...
862
  		bootloader_mmc_offset() < ANDROID_GPT_END);
2c840c82b   Ye Li   MLK-18591-3 andro...
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
  }
  
  int write_backup_gpt(void)
  {
  	int mmc_no = 0;
  	struct mmc *mmc;
  	struct blk_desc *dev_desc;
  
  	mmc_no = fastboot_devinfo.dev_id;
  	mmc = find_mmc_device(mmc_no);
  	if (mmc == NULL) {
  		printf("invalid mmc device
  ");
  		return -1;
  	}
  	dev_desc = blk_get_dev("mmc", mmc_no);
661bc6ec6   Ye Li   MLK-20240-7 fastb...
879
880
881
882
883
884
  	if (dev_desc == NULL) {
  		printf("Can't get Block device MMC %d
  ",
  			mmc_no);
  		return -ENODEV;
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
885
886
887
888
889
890
891
892
893
894
895
896
  
  	/* write backup get partition */
  	if (write_backup_gpt_partitions(dev_desc, interface.transfer_buffer)) {
  		printf("writing GPT image fail
  ");
  		return -1;
  	}
  
  	printf("flash backup gpt image successfully
  ");
  	return 0;
  }
244e083d5   Luo Ji   MA-11948 [Android...
897
898
899
900
901
902
903
904
905
906
907
908
909
  static int get_fastboot_target_dev(char *mmc_dev, struct fastboot_ptentry *ptn)
  {
  	int dev = 0;
  	struct mmc *target_mmc;
  
  	/* Support flash bootloader to mmc 'target_ubootdev' devices, if the
  	* 'target_ubootdev' env is not set just flash bootloader to current
  	* mmc device.
  	*/
  	if ((!strncmp(ptn->name, FASTBOOT_PARTITION_BOOTLOADER,
  					sizeof(FASTBOOT_PARTITION_BOOTLOADER))) &&
  					(env_get("target_ubootdev"))) {
  		dev = simple_strtoul(env_get("target_ubootdev"), NULL, 10);
68261e4ca   faqiang.zhu   MA-13303 fix the ...
910
911
912
913
  
  		/* if target_ubootdev is set, it must be that users want to change
  		 * fastboot device, then fastboot environment need to be updated */
  		fastboot_setup();
244e083d5   Luo Ji   MA-11948 [Android...
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
  		target_mmc = find_mmc_device(dev);
  		if ((target_mmc == NULL) || mmc_init(target_mmc)) {
  			printf("MMC card init failed!
  ");
  			return -1;
  		} else {
  			printf("Flash target is mmc%d
  ", dev);
  			if (target_mmc->part_config != MMCPART_NOAVAILABLE)
  				sprintf(mmc_dev, "mmc dev %x %x", dev, /*slot no*/
  						FASTBOOT_MMC_BOOT_PARTITION_ID/*part no*/);
  			else
  				sprintf(mmc_dev, "mmc dev %x", dev);
  			}
  	} else if (ptn->partition_id != FASTBOOT_MMC_NONE_PARTITION_ID)
  		sprintf(mmc_dev, "mmc dev %x %x",
  				fastboot_devinfo.dev_id, /*slot no*/
  				ptn->partition_id /*part no*/);
  	else
  		sprintf(mmc_dev, "mmc dev %x",
  				fastboot_devinfo.dev_id /*slot no*/);
  	return 0;
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
937
938
939
940
  static void process_flash_mmc(const char *cmdbuf)
  {
  	if (download_bytes) {
  		struct fastboot_ptentry *ptn;
2c840c82b   Ye Li   MLK-18591-3 andro...
941
942
943
944
945
  
  		/* Next is the partition name */
  		ptn = fastboot_flash_find_ptn(cmdbuf);
  		if (ptn == NULL) {
  			fastboot_fail("partition does not exist");
c2763113a   Ji Luo   MA-12358 Only dum...
946
  			fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
  		} else if ((download_bytes >
  			   ptn->length * MMC_SATA_BLOCK_SIZE) &&
  				!(ptn->flags & FASTBOOT_PTENTRY_FLAGS_WRITE_ENV)) {
  			printf("Image too large for the partition
  ");
  			fastboot_fail("image too large for partition");
  		} else if (ptn->flags & FASTBOOT_PTENTRY_FLAGS_WRITE_ENV) {
  			/* Since the response can only be 64 bytes,
  			   there is no point in having a large error message. */
  			char err_string[32];
  			if (saveenv_to_ptn(ptn, &err_string[0])) {
  				printf("savenv '%s' failed : %s
  ", ptn->name, err_string);
  				fastboot_fail(err_string);
  			} else {
  				printf("partition '%s' saveenv-ed
  ", ptn->name);
  				fastboot_okay("");
  			}
  		} else {
  			unsigned int temp;
a612cab38   Richard Zhu   MLK-19479-2 fastb...
968
969
970
  			char blk_dev[128];
  			char blk_write[128];
  			int blkret;
2c840c82b   Ye Li   MLK-18591-3 andro...
971
972
973
  
  			printf("writing to partition '%s'
  ", ptn->name);
244e083d5   Luo Ji   MA-11948 [Android...
974
  			/* Get target flash device. */
a612cab38   Richard Zhu   MLK-19479-2 fastb...
975
  			if (get_fastboot_target_dev(blk_dev, ptn) != 0)
244e083d5   Luo Ji   MA-11948 [Android...
976
  				return;
2c840c82b   Ye Li   MLK-18591-3 andro...
977
978
979
  
  			if (!is_raw_partition(ptn) &&
  				is_sparse_image(interface.transfer_buffer)) {
a612cab38   Richard Zhu   MLK-19479-2 fastb...
980
  				int dev_no = 0;
2c840c82b   Ye Li   MLK-18591-3 andro...
981
982
983
984
  				struct mmc *mmc;
  				struct blk_desc *dev_desc;
  				disk_partition_t info;
  				struct sparse_storage sparse;
a612cab38   Richard Zhu   MLK-19479-2 fastb...
985
  				dev_no = fastboot_devinfo.dev_id;
2c840c82b   Ye Li   MLK-18591-3 andro...
986

a612cab38   Richard Zhu   MLK-19479-2 fastb...
987
988
989
990
991
992
993
994
995
996
  				printf("sparse flash target is %s:%d
  ",
  				       fastboot_devinfo.type == DEV_SATA ? "sata" : "mmc",
  				       dev_no);
  				if (fastboot_devinfo.type == DEV_MMC) {
  					mmc = find_mmc_device(dev_no);
  					if (mmc && mmc_init(mmc))
  						printf("MMC card init failed!
  ");
  				}
2c840c82b   Ye Li   MLK-18591-3 andro...
997

a612cab38   Richard Zhu   MLK-19479-2 fastb...
998
  				dev_desc = blk_get_dev(fastboot_devinfo.type == DEV_SATA ? "sata" : "mmc", dev_no);
2c840c82b   Ye Li   MLK-18591-3 andro...
999
  				if (!dev_desc || dev_desc->type == DEV_TYPE_UNKNOWN) {
a612cab38   Richard Zhu   MLK-19479-2 fastb...
1000
1001
1002
1003
  					printf("** Block device %s %d not supported
  ",
  					       fastboot_devinfo.type == DEV_SATA ? "sata" : "mmc",
  					       dev_no);
2c840c82b   Ye Li   MLK-18591-3 andro...
1004
1005
  					return;
  				}
5423ef478   Frank Li   MLK-18406 fastboo...
1006
1007
1008
1009
1010
1011
  				if( strncmp(ptn->name, FASTBOOT_PARTITION_ALL,
  					    strlen(FASTBOOT_PARTITION_ALL)) == 0) {
  					info.blksz = dev_desc->blksz;
  					info.size = dev_desc->lba;
  					info.start = 0;
  				} else {
2c840c82b   Ye Li   MLK-18591-3 andro...
1012

5423ef478   Frank Li   MLK-18406 fastboo...
1013
1014
1015
1016
1017
1018
1019
1020
  					if (part_get_info(dev_desc,
  							  ptn->partition_index, &info)) {
  						printf("Bad partition index:%d for partition:%s
  ",
  						ptn->partition_index, ptn->name);
  						return;
  					}
  				}
2c840c82b   Ye Li   MLK-18591-3 andro...
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
  				printf("writing to partition '%s' for sparse, buffer size %d
  ",
  						ptn->name, download_bytes);
  
  				sparse.blksz = info.blksz;
  				sparse.start = info.start;
  				sparse.size = info.size;
  				sparse.write = mmc_sparse_write;
  				sparse.reserve = mmc_sparse_reserve;
  				printf("Flashing sparse image at offset " LBAFU "
  ",
  				       sparse.start);
  
  				sparse.priv = dev_desc;
  				write_sparse_image(&sparse, ptn->name, interface.transfer_buffer,
  						   download_bytes);
  
  			} else {
  				/* Will flash images in below case:
  				 * 1. Is not gpt partition.
  				 * 2. Is gpt partition but no overlay detected.
  				 * */
  				if (strncmp(ptn->name, "gpt", 3) || !bootloader_gpt_overlay()) {
  					/* block count */
  					if (strncmp(ptn->name, "gpt", 3) == 0) {
  						temp = (ANDROID_GPT_END +
  								MMC_SATA_BLOCK_SIZE - 1) /
  								MMC_SATA_BLOCK_SIZE;
  					} else {
  						temp = (download_bytes +
  								MMC_SATA_BLOCK_SIZE - 1) /
  								MMC_SATA_BLOCK_SIZE;
  					}
a612cab38   Richard Zhu   MLK-19479-2 fastb...
1054
1055
1056
1057
1058
  					sprintf(blk_write, "%s write 0x%x 0x%x 0x%x",
  						fastboot_devinfo.type == DEV_SATA ? "sata" : "mmc",
  						(unsigned int)(uintptr_t)interface.transfer_buffer, /*source*/
  						ptn->start, /*dest*/
  						temp /*length*/);
2c840c82b   Ye Li   MLK-18591-3 andro...
1059
1060
1061
  
  					printf("Initializing '%s'
  ", ptn->name);
a612cab38   Richard Zhu   MLK-19479-2 fastb...
1062
1063
1064
  					blkret = run_command(blk_dev, 0);
  					if (blkret)
  						fastboot_fail("Init of BLK device failed");
2c840c82b   Ye Li   MLK-18591-3 andro...
1065
1066
1067
1068
1069
  					else
  						fastboot_okay("");
  
  					printf("Writing '%s'
  ", ptn->name);
a612cab38   Richard Zhu   MLK-19479-2 fastb...
1070
  					if (run_command(blk_write, 0)) {
2c840c82b   Ye Li   MLK-18591-3 andro...
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
  						printf("Writing '%s' FAILED!
  ", ptn->name);
  						fastboot_fail("Write partition failed");
  					} else {
  						printf("Writing '%s' DONE!
  ", ptn->name);
  						fastboot_okay("");
  					}
  				}
  				/* Write backup gpt image */
  				if (strncmp(ptn->name, "gpt", 3) == 0) {
  					if (write_backup_gpt())
  						fastboot_fail("write backup GPT image fail");
  					else
  						fastboot_okay("");
  
  					/* will force scan the device,
  					 * so dev_desc can be re-inited
  					 * with the latest data */
a612cab38   Richard Zhu   MLK-19479-2 fastb...
1090
  					run_command(blk_dev, 0);
2c840c82b   Ye Li   MLK-18591-3 andro...
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
  				}
  			}
  		}
  	} else {
  		fastboot_fail("no image downloaded");
  	}
  }
  
  #endif
  
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  static void process_erase_mmc(const char *cmdbuf, char *response)
  {
  	int mmc_no = 0;
  	lbaint_t blks, blks_start, blks_size, grp_size;
  	struct mmc *mmc;
  	struct blk_desc *dev_desc;
  	struct fastboot_ptentry *ptn;
  	disk_partition_t info;
  
  	ptn = fastboot_flash_find_ptn(cmdbuf);
  	if ((ptn == NULL) || (ptn->flags & FASTBOOT_PTENTRY_FLAGS_UNERASEABLE)) {
  		sprintf(response, "FAILpartition does not exist or uneraseable");
c2763113a   Ji Luo   MA-12358 Only dum...
1114
  		fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
  		return;
  	}
  
  	mmc_no = fastboot_devinfo.dev_id;
  	printf("erase target is MMC:%d
  ", mmc_no);
  
  	mmc = find_mmc_device(mmc_no);
  	if ((mmc == NULL) || mmc_init(mmc)) {
  		printf("MMC card init failed!
  ");
  		return;
  	}
  
  	dev_desc = blk_get_dev("mmc", mmc_no);
  	if (NULL == dev_desc) {
  		printf("Block device MMC %d not supported
  ",
  			mmc_no);
  		sprintf(response, "FAILnot valid MMC card");
  		return;
  	}
  
  	if (part_get_info(dev_desc,
  				ptn->partition_index, &info)) {
  		printf("Bad partition index:%d for partition:%s
  ",
  		ptn->partition_index, ptn->name);
  		sprintf(response, "FAILerasing of MMC card");
  		return;
  	}
  
  	/* Align blocks to erase group size to avoid erasing other partitions */
  	grp_size = mmc->erase_grp_size;
  	blks_start = (info.start + grp_size - 1) & ~(grp_size - 1);
  	if (info.size >= grp_size)
  		blks_size = (info.size - (blks_start - info.start)) &
  				(~(grp_size - 1));
  	else
  		blks_size = 0;
  
  	printf("Erasing blocks " LBAFU " to " LBAFU " due to alignment
  ",
  	       blks_start, blks_start + blks_size);
  
  	blks = blk_derase(dev_desc, blks_start, blks_size);
  	if (blks != blks_size) {
  		printf("failed erasing from device %d", dev_desc->devnum);
  		sprintf(response, "FAILerasing of MMC card");
  		return;
  	}
  
  	printf("........ erased " LBAFU " bytes from '%s'
  ",
  	       blks_size * info.blksz, cmdbuf);
  	sprintf(response, "OKAY");
  
      return;
  }
  #endif
  
  #if defined(CONFIG_FASTBOOT_STORAGE_SATA)
  static void process_erase_sata(const char *cmdbuf, char *response)
  {
      return;
  }
  #endif
  
  static void rx_process_erase(const char *cmdbuf, char *response)
  {
  	switch (fastboot_devinfo.type) {
  #if defined(CONFIG_FASTBOOT_STORAGE_SATA)
  	case DEV_SATA:
  		process_erase_sata(cmdbuf, response);
  		break;
  #endif
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	case DEV_MMC:
  		process_erase_mmc(cmdbuf, response);
  		break;
  #endif
  	default:
  		printf("Not support flash command for current device %d
  ",
  			fastboot_devinfo.type);
  		sprintf(response,
  			   "FAILfailed to flash device");
  		break;
  	}
  }
  
  static void rx_process_flash(const char *cmdbuf)
  {
  /* Check if we need to flash mcu firmware */
  #ifdef CONFIG_FLASH_MCUFIRMWARE_SUPPORT
  	if (!strncmp(cmdbuf, FASTBOOT_MCU_FIRMWARE_PARTITION,
  				sizeof(FASTBOOT_MCU_FIRMWARE_PARTITION))) {
  		switch (fastboot_firmwareinfo.type) {
  		case DEV_SF:
  			process_flash_sf(cmdbuf);
  			break;
  #ifdef CONFIG_ARCH_IMX8M
  		case DEV_MMC:
  			if (is_tcm_image(interface.transfer_buffer))
  				process_flash_mmc(cmdbuf);
  			break;
  #endif
  		default:
  			printf("Don't support flash firmware
  ");
  		}
  		return;
  	}
  #endif
  	/* Normal case */
  	switch (fastboot_devinfo.type) {
  #if defined(CONFIG_FASTBOOT_STORAGE_SATA)
  	case DEV_SATA:
a612cab38   Richard Zhu   MLK-19479-2 fastb...
1233
  		process_flash_mmc(cmdbuf);
2c840c82b   Ye Li   MLK-18591-3 andro...
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
  		break;
  #endif
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	case DEV_MMC:
  		process_flash_mmc(cmdbuf);
  		break;
  #endif
  	default:
  		printf("Not support flash command for current device %d
  ",
  			fastboot_devinfo.type);
  		fastboot_fail("failed to flash device");
  		break;
  	}
  }
  
  
  static void parameters_setup(void)
  {
  	interface.nand_block_size = 0;
  	interface.transfer_buffer =
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
1255
  				(unsigned char *)env_get_ulong("fastboot_buffer", 16, CONFIG_FASTBOOT_BUF_ADDR);
2c840c82b   Ye Li   MLK-18591-3 andro...
1256
1257
1258
  	interface.transfer_buffer_size =
  				CONFIG_FASTBOOT_BUF_SIZE;
  }
a251b17f4   Ye Li   MLK-19356 fastboo...
1259
  static int _fastboot_setup_dev(int *switched)
2c840c82b   Ye Li   MLK-18591-3 andro...
1260
1261
  {
  	char *fastboot_env;
a251b17f4   Ye Li   MLK-19356 fastboo...
1262
  	struct fastboot_device_info devinfo;;
2c840c82b   Ye Li   MLK-18591-3 andro...
1263
1264
1265
1266
  	fastboot_env = env_get("fastboot_dev");
  
  	if (fastboot_env) {
  		if (!strcmp(fastboot_env, "sata")) {
a251b17f4   Ye Li   MLK-19356 fastboo...
1267
1268
  			devinfo.type = DEV_SATA;
  			devinfo.dev_id = 0;
2c840c82b   Ye Li   MLK-18591-3 andro...
1269
1270
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  		} else if (!strncmp(fastboot_env, "mmc", 3)) {
a251b17f4   Ye Li   MLK-19356 fastboo...
1271
  			devinfo.type = DEV_MMC;
68261e4ca   faqiang.zhu   MA-13303 fix the ...
1272
1273
1274
1275
  			if(env_get("target_ubootdev"))
  				devinfo.dev_id = simple_strtoul(env_get("target_ubootdev"), NULL, 10);
  			else
  				devinfo.dev_id = mmc_get_env_dev();
2c840c82b   Ye Li   MLK-18591-3 andro...
1276
  #endif
a251b17f4   Ye Li   MLK-19356 fastboo...
1277
1278
  		} else {
  			return 1;
2c840c82b   Ye Li   MLK-18591-3 andro...
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
  		}
  	} else {
  		return 1;
  	}
  #ifdef CONFIG_FLASH_MCUFIRMWARE_SUPPORT
  	/* For imx7ulp, flash m4 images directly to spi nor-flash, M4 will
  	 * run automatically after powered on. For imx8mq, flash m4 images to
  	 * physical partition 'm4_os', m4 will be kicked off by A core. */
  	fastboot_firmwareinfo.type = ANDROID_MCU_FRIMWARE_DEV_TYPE;
  #endif
a251b17f4   Ye Li   MLK-19356 fastboo...
1289
1290
1291
1292
1293
1294
1295
1296
1297
  	if (switched) {
  		if (devinfo.type != fastboot_devinfo.type || devinfo.dev_id != fastboot_devinfo.dev_id)
  			*switched = 1;
  		else
  			*switched = 0;
  	}
  
  	fastboot_devinfo.type	 = devinfo.type;
  	fastboot_devinfo.dev_id = devinfo.dev_id;
2c840c82b   Ye Li   MLK-18591-3 andro...
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
  	return 0;
  }
  
  #if defined(CONFIG_FASTBOOT_STORAGE_SATA) \
  	|| defined(CONFIG_FASTBOOT_STORAGE_MMC)
  /**
     @mmc_dos_partition_index: the partition index in mbr.
     @mmc_partition_index: the boot partition or user partition index,
     not related to the partition table.
   */
  static int _fastboot_parts_add_ptable_entry(int ptable_index,
  				      int mmc_dos_partition_index,
  				      int mmc_partition_index,
  				      const char *name,
  				      const char *fstype,
  				      struct blk_desc *dev_desc,
  				      struct fastboot_ptentry *ptable)
  {
  	disk_partition_t info;
  
  	if (part_get_info(dev_desc,
  			       mmc_dos_partition_index, &info)) {
  		debug("Bad partition index:%d for partition:%s
  ",
  		       mmc_dos_partition_index, name);
  		return -1;
  	}
  	ptable[ptable_index].start = info.start;
  	ptable[ptable_index].length = info.size;
  	ptable[ptable_index].partition_id = mmc_partition_index;
  	ptable[ptable_index].partition_index = mmc_dos_partition_index;
  	strncpy(ptable[ptable_index].name, (const char *)info.name,
  			sizeof(ptable[ptable_index].name) - 1);
  
  #ifdef CONFIG_PARTITION_UUIDS
  	strcpy(ptable[ptable_index].uuid, (const char *)info.uuid);
  #endif
  #ifdef CONFIG_ANDROID_AB_SUPPORT
  	if (!strcmp((const char *)info.name, FASTBOOT_PARTITION_SYSTEM_A) ||
b45ecdb05   Haoran.Wang   [iot] Correct oem...
1337
1338
1339
1340
1341
1342
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_SYSTEM_B) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_OEM_A) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_VENDOR_A) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_OEM_B) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_VENDOR_B) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_DATA))
2c840c82b   Ye Li   MLK-18591-3 andro...
1343
1344
  #else
  	if (!strcmp((const char *)info.name, FASTBOOT_PARTITION_SYSTEM) ||
b45ecdb05   Haoran.Wang   [iot] Correct oem...
1345
1346
1347
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_DATA) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_DEVICE) ||
  	    !strcmp((const char *)info.name, FASTBOOT_PARTITION_CACHE))
2c840c82b   Ye Li   MLK-18591-3 andro...
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
  #endif
  		strcpy(ptable[ptable_index].fstype, "ext4");
  	else
  		strcpy(ptable[ptable_index].fstype, "raw");
  	return 0;
  }
  
  static int _fastboot_parts_load_from_ptable(void)
  {
  	int i;
  #ifdef CONFIG_CMD_SATA
  	int sata_device_no;
  #endif
  
  	/* mmc boot partition: -1 means no partition, 0 user part., 1 boot part.
  	 * default is no partition, for emmc default user part, except emmc*/
  	int boot_partition = FASTBOOT_MMC_NONE_PARTITION_ID;
      int user_partition = FASTBOOT_MMC_NONE_PARTITION_ID;
  
  	struct mmc *mmc;
  	struct blk_desc *dev_desc;
  	struct fastboot_ptentry ptable[MAX_PTN];
  
  	/* sata case in env */
  	if (fastboot_devinfo.type == DEV_SATA) {
  #ifdef CONFIG_CMD_SATA
  		puts("flash target is SATA
  ");
  		if (sata_initialize())
  			return -1;
  		sata_device_no = CONFIG_FASTBOOT_SATA_NO;
  		if (sata_device_no >= CONFIG_SYS_SATA_MAX_DEVICE) {
  			printf("Unknown SATA(%d) device for fastboot
  ",
  				sata_device_no);
  			return -1;
  		}
  		dev_desc = sata_get_dev(sata_device_no);
  #else /*! CONFIG_CMD_SATA*/
  		puts("SATA isn't buildin
  ");
  		return -1;
  #endif /*! CONFIG_CMD_SATA*/
  	} else if (fastboot_devinfo.type == DEV_MMC) {
  		int mmc_no = 0;
  		mmc_no = fastboot_devinfo.dev_id;
  
  		printf("flash target is MMC:%d
  ", mmc_no);
  		mmc = find_mmc_device(mmc_no);
a251b17f4   Ye Li   MLK-19356 fastboo...
1398

f85da6b1f   Ye Li   MLK-20240-8 fastb...
1399
1400
1401
1402
1403
  		if (mmc == NULL) {
  			printf("invalid mmc device %d
  ", mmc_no);
  			return -1;
  		}
a251b17f4   Ye Li   MLK-19356 fastboo...
1404
1405
  		/* Force to init mmc */
  		mmc->has_init = 0;
f85da6b1f   Ye Li   MLK-20240-8 fastb...
1406
  		if (mmc_init(mmc))
2c840c82b   Ye Li   MLK-18591-3 andro...
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
  			printf("MMC card init failed!
  ");
  
  		dev_desc = blk_get_dev("mmc", mmc_no);
  		if (!dev_desc || dev_desc->type == DEV_TYPE_UNKNOWN) {
  			printf("** Block device MMC %d not supported
  ",
  				mmc_no);
  			return -1;
  		}
  
  		/* multiple boot paritions for eMMC 4.3 later */
  		if (mmc->part_config != MMCPART_NOAVAILABLE) {
  			boot_partition = FASTBOOT_MMC_BOOT_PARTITION_ID;
  			user_partition = FASTBOOT_MMC_USER_PARTITION_ID;
  		}
  	} else {
  		printf("Can't setup partition table on this device %d
  ",
  			fastboot_devinfo.type);
  		return -1;
  	}
  
  	memset((char *)ptable, 0,
  		    sizeof(struct fastboot_ptentry) * (MAX_PTN));
  	/* GPT */
  	strcpy(ptable[PTN_GPT_INDEX].name, FASTBOOT_PARTITION_GPT);
  	ptable[PTN_GPT_INDEX].start = ANDROID_GPT_OFFSET / dev_desc->blksz;
  	ptable[PTN_GPT_INDEX].length = ANDROID_GPT_SIZE  / dev_desc->blksz;
  	ptable[PTN_GPT_INDEX].partition_id = user_partition;
  	ptable[PTN_GPT_INDEX].flags = FASTBOOT_PTENTRY_FLAGS_UNERASEABLE;
  	strcpy(ptable[PTN_GPT_INDEX].fstype, "raw");
502522c08   Haoran.Wang   [iot] Support ARM...
1439
  #ifndef CONFIG_ARM64
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1440
1441
1442
1443
1444
1445
  	/* Trusty OS */
  	strcpy(ptable[PTN_TEE_INDEX].name, FASTBOOT_PARTITION_TEE);
  	ptable[PTN_TEE_INDEX].start = 0;
  	ptable[PTN_TEE_INDEX].length = TRUSTY_OS_MMC_BLKS;
  	ptable[PTN_TEE_INDEX].partition_id = TEE_HWPARTITION_ID;
  	strcpy(ptable[PTN_TEE_INDEX].fstype, "raw");
502522c08   Haoran.Wang   [iot] Support ARM...
1446
  #endif
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1447

2c840c82b   Ye Li   MLK-18591-3 andro...
1448
1449
1450
1451
1452
1453
1454
1455
1456
  	/* Add m4_os partition if we support mcu firmware image flash */
  #ifdef CONFIG_FLASH_MCUFIRMWARE_SUPPORT
  	strcpy(ptable[PTN_M4_OS_INDEX].name, FASTBOOT_MCU_FIRMWARE_PARTITION);
  	ptable[PTN_M4_OS_INDEX].start = ANDROID_MCU_FIRMWARE_START / dev_desc->blksz;
  	ptable[PTN_M4_OS_INDEX].length = ANDROID_MCU_FIRMWARE_SIZE / dev_desc->blksz;
  	ptable[PTN_M4_OS_INDEX].flags = FASTBOOT_PTENTRY_FLAGS_UNERASEABLE;
  	ptable[PTN_M4_OS_INDEX].partition_id = user_partition;
  	strcpy(ptable[PTN_M4_OS_INDEX].fstype, "raw");
  #endif
5423ef478   Frank Li   MLK-18406 fastboo...
1457
1458
1459
1460
1461
  	strcpy(ptable[PTN_ALL_INDEX].name, FASTBOOT_PARTITION_ALL);
  	ptable[PTN_ALL_INDEX].start = 0;
  	ptable[PTN_ALL_INDEX].length = dev_desc->lba;
  	ptable[PTN_ALL_INDEX].partition_id = user_partition;
  	strcpy(ptable[PTN_ALL_INDEX].fstype, "device");
2c840c82b   Ye Li   MLK-18591-3 andro...
1462
1463
1464
  	/* Bootloader */
  	strcpy(ptable[PTN_BOOTLOADER_INDEX].name, FASTBOOT_PARTITION_BOOTLOADER);
  	ptable[PTN_BOOTLOADER_INDEX].start =
065c4a2bd   Ye Li   MLK-18934 usb: fa...
1465
  				bootloader_mmc_offset() / dev_desc->blksz;
2c840c82b   Ye Li   MLK-18591-3 andro...
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
  	ptable[PTN_BOOTLOADER_INDEX].length =
  				 ANDROID_BOOTLOADER_SIZE / dev_desc->blksz;
  	ptable[PTN_BOOTLOADER_INDEX].partition_id = boot_partition;
  	ptable[PTN_BOOTLOADER_INDEX].flags = FASTBOOT_PTENTRY_FLAGS_UNERASEABLE;
  	strcpy(ptable[PTN_BOOTLOADER_INDEX].fstype, "raw");
  
  	int tbl_idx;
  	int part_idx = 1;
  	int ret;
  	for (tbl_idx = PTN_BOOTLOADER_INDEX + 1; tbl_idx < MAX_PTN; tbl_idx++) {
  		ret = _fastboot_parts_add_ptable_entry(tbl_idx,
  				part_idx++,
  				user_partition,
  				NULL,
  				NULL,
  				dev_desc, ptable);
  		if (ret)
  			break;
  	}
  	for (i = 0; i < tbl_idx; i++)
  		fastboot_flash_add_ptn(&ptable[i]);
  
  	return 0;
  }
  #endif /*CONFIG_FASTBOOT_STORAGE_SATA || CONFIG_FASTBOOT_STORAGE_MMC*/
  
  static void _fastboot_load_partitions(void)
  {
  	g_pcount = 0;
  #if defined(CONFIG_FASTBOOT_STORAGE_SATA) \
  	|| defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	_fastboot_parts_load_from_ptable();
  #endif
  }
  
  /*
   * Android style flash utilties */
  void fastboot_flash_add_ptn(struct fastboot_ptentry *ptn)
  {
  	if (g_pcount < MAX_PTN) {
  		memcpy(g_ptable + g_pcount, ptn, sizeof(struct fastboot_ptentry));
  		g_pcount++;
  	}
  }
  
  void fastboot_flash_dump_ptn(void)
  {
  	unsigned int n;
  	for (n = 0; n < g_pcount; n++) {
  		struct fastboot_ptentry *ptn = g_ptable + n;
  		printf("idx %d, ptn %d name='%s' start=%d len=%d
  ",
  			n, ptn->partition_index, ptn->name, ptn->start, ptn->length);
  	}
  }
  
  
  struct fastboot_ptentry *fastboot_flash_find_ptn(const char *name)
  {
  	unsigned int n;
  
  	for (n = 0; n < g_pcount; n++) {
  		/* Make sure a substring is not accepted */
  		if (strlen(name) == strlen(g_ptable[n].name)) {
  			if (0 == strcmp(g_ptable[n].name, name))
  				return g_ptable + n;
  		}
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
1534
1535
1536
1537
1538
1539
1540
1541
1542
  	return 0;
  }
  
  int fastboot_flash_find_index(const char *name)
  {
  	struct fastboot_ptentry *ptentry = fastboot_flash_find_ptn(name);
  	if (ptentry == NULL) {
  		printf("cannot get the partion info for %s
  ",name);
c2763113a   Ji Luo   MA-12358 Only dum...
1543
  		fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
  		return -1;
  	}
  	return ptentry->partition_index;
  }
  
  struct fastboot_ptentry *fastboot_flash_get_ptn(unsigned int n)
  {
  	if (n < g_pcount)
  		return g_ptable + n;
  	else
  		return 0;
  }
  
  unsigned int fastboot_flash_get_ptn_count(void)
  {
  	return g_pcount;
  }
  
  #ifdef CONFIG_FSL_FASTBOOT
  void board_fastboot_setup(void)
  {
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	static char boot_dev_part[32];
  	u32 dev_no;
  #endif
  	switch (get_boot_device()) {
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	case SD1_BOOT:
  	case SD2_BOOT:
  	case SD3_BOOT:
  	case SD4_BOOT:
  	case MMC1_BOOT:
  	case MMC2_BOOT:
  	case MMC3_BOOT:
  	case MMC4_BOOT:
  		dev_no = mmc_get_env_dev();
  		sprintf(boot_dev_part,"mmc%d",dev_no);
  		if (!env_get("fastboot_dev"))
  			env_set("fastboot_dev", boot_dev_part);
  		sprintf(boot_dev_part, "boota mmc%d", dev_no);
  		if (!env_get("bootcmd"))
  			env_set("bootcmd", boot_dev_part);
  		break;
107204622   Haoran.Wang   MA-12283 Enter fa...
1587
1588
1589
1590
1591
  	case USB_BOOT:
  		printf("Detect USB boot. Will enter fastboot mode!
  ");
  		if (!env_get("bootcmd"))
  			env_set("bootcmd", "fastboot 0");
e4a824f6c   faqiang.zhu   MA-12283: elimina...
1592
  		break;
2c840c82b   Ye Li   MLK-18591-3 andro...
1593
1594
  #endif /*CONFIG_FASTBOOT_STORAGE_MMC*/
  	default:
d86096acc   Ye Li   MLK-19852 imx: fa...
1595
1596
1597
  		if (!env_get("bootcmd"))
  			printf("unsupported boot devices
  ");
2c840c82b   Ye Li   MLK-18591-3 andro...
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
  		break;
  	}
  
  	/* add soc type into bootargs */
  	if (is_mx6dqp()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx6qp");
  	} else if (is_mx6dq()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx6q");
  	} else if (is_mx6sdl()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx6dl");
  	} else if (is_mx6sx()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx6sx");
  	} else if (is_mx6sl()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx6sl");
  	} else if (is_mx6ul()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx6ul");
  	} else if (is_mx7()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx7d");
  	} else if (is_mx7ulp()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx7ulp");
  	} else if (is_imx8qm()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx8qm");
  	} else if (is_imx8qxp()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx8qxp");
  	} else if (is_imx8mq()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx8mq");
  	} else if (is_imx8mm()) {
  		if (!env_get("soc_type"))
  			env_set("soc_type", "imx8mm");
  	}
  }
  
  #ifdef CONFIG_ANDROID_RECOVERY
  void board_recovery_setup(void)
  {
  /* boot from current mmc with avb verify */
  #ifdef CONFIG_AVB_SUPPORT
  	if (!env_get("bootcmd_android_recovery"))
  		env_set("bootcmd_android_recovery", "boota recovery");
  #else
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	static char boot_dev_part[32];
  	u32 dev_no;
  #endif
  	int bootdev = get_boot_device();
  	switch (bootdev) {
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  	case SD1_BOOT:
  	case SD2_BOOT:
  	case SD3_BOOT:
  	case SD4_BOOT:
  	case MMC1_BOOT:
  	case MMC2_BOOT:
  	case MMC3_BOOT:
  	case MMC4_BOOT:
  		dev_no = mmc_get_env_dev();
  		sprintf(boot_dev_part,"boota mmc%d recovery",dev_no);
  		if (!env_get("bootcmd_android_recovery"))
  			env_set("bootcmd_android_recovery", boot_dev_part);
  		break;
  #endif /*CONFIG_FASTBOOT_STORAGE_MMC*/
  	default:
  		printf("Unsupported bootup device for recovery: dev: %d
  ",
  			bootdev);
  		return;
  	}
  #endif /* CONFIG_AVB_SUPPORT */
  	printf("setup env for recovery..
  ");
1731bacd1   zhang sanshan   MA-12196 [Android...
1679
  	env_set("bootcmd", env_get("bootcmd_android_recovery"));
2c840c82b   Ye Li   MLK-18591-3 andro...
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
  }
  #endif /*CONFIG_ANDROID_RECOVERY*/
  #endif /*CONFIG_FSL_FASTBOOT*/
  
  #if defined(CONFIG_AVB_SUPPORT) && defined(CONFIG_MMC)
  static AvbABOps fsl_avb_ab_ops = {
  	.read_ab_metadata = fsl_read_ab_metadata,
  	.write_ab_metadata = fsl_write_ab_metadata,
  	.ops = NULL
  };
  #ifdef CONFIG_AVB_ATX
  static AvbAtxOps fsl_avb_atx_ops = {
  	.ops = NULL,
  	.read_permanent_attributes = fsl_read_permanent_attributes,
449f9048e   Luo Ji   [iot] Update liba...
1694
  	.read_permanent_attributes_hash = fsl_read_permanent_attributes_hash,
4ecf3a4c2   Yu Shan   [iot] Support ATX...
1695
  #ifdef CONFIG_IMX_TRUSTY_OS
d4a0dbd9a   Ji Luo   [iot] Support aut...
1696
  	.set_key_version = fsl_write_rollback_index_rpmb,
4ecf3a4c2   Yu Shan   [iot] Support ATX...
1697
  #else
d4a0dbd9a   Ji Luo   [iot] Support aut...
1698
  	.set_key_version = fsl_set_key_version,
4ecf3a4c2   Yu Shan   [iot] Support ATX...
1699
  #endif
d4a0dbd9a   Ji Luo   [iot] Support aut...
1700
  	.get_random = fsl_get_random
2c840c82b   Ye Li   MLK-18591-3 andro...
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
  };
  #endif
  static AvbOps fsl_avb_ops = {
  	.ab_ops = &fsl_avb_ab_ops,
  #ifdef CONFIG_AVB_ATX
  	.atx_ops = &fsl_avb_atx_ops,
  #endif
  	.read_from_partition = fsl_read_from_partition_multi,
  	.write_to_partition = fsl_write_to_partition,
  #ifdef CONFIG_AVB_ATX
  	.validate_vbmeta_public_key = avb_atx_validate_vbmeta_public_key,
  #else
  	.validate_vbmeta_public_key = fsl_validate_vbmeta_public_key_rpmb,
  #endif
  	.read_rollback_index = fsl_read_rollback_index_rpmb,
  	.write_rollback_index = fsl_write_rollback_index_rpmb,
  	.read_is_device_unlocked = fsl_read_is_device_unlocked,
  	.get_unique_guid_for_partition = fsl_get_unique_guid_for_partition,
  	.get_size_of_partition = fsl_get_size_of_partition
  };
  #endif
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1722
  #ifdef CONFIG_IMX_TRUSTY_OS
502522c08   Haoran.Wang   [iot] Support ARM...
1723
1724
1725
1726
1727
1728
1729
1730
  #ifdef CONFIG_ARM64
  void tee_setup(void)
  {
  	trusty_ipc_init();
  }
  
  #else
  extern bool tos_flashed;
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
  void tee_setup(void)
  {
  	/* load tee from boot1 of eMMC. */
  	int mmcc = mmc_get_env_dev();
  	struct blk_desc *dev_desc = NULL;
  
  	struct mmc *mmc;
  	mmc = find_mmc_device(mmcc);
  	if (!mmc) {
  	            printf("boota: cannot find '%d' mmc device
  ", mmcc);
  		            goto fail;
  	}
  
  	dev_desc = blk_get_dev("mmc", mmcc);
  	if (NULL == dev_desc) {
  	            printf("** Block device MMC %d not supported
  ", mmcc);
  		            goto fail;
  	}
  
  	/* below was i.MX mmc operation code */
  	if (mmc_init(mmc)) {
  	            printf("mmc%d init failed
  ", mmcc);
  		            goto fail;
  	}
  
  	struct fastboot_ptentry *tee_pte;
  	char *tee_ptn = FASTBOOT_PARTITION_TEE;
  	tee_pte = fastboot_flash_find_ptn(tee_ptn);
  	mmc_switch_part(mmc, TEE_HWPARTITION_ID);
  	if (!tee_pte) {
  		printf("boota: cannot find tee partition!
  ");
c2763113a   Ji Luo   MA-12358 Only dum...
1766
  		fastboot_flash_dump_ptn();
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1767
1768
1769
1770
1771
1772
1773
  	}
  
  	if (blk_dread(dev_desc, tee_pte->start,
  		    tee_pte->length, (void *)TRUSTY_OS_ENTRY) < 0) {
  		printf("Failed to load tee.");
  	}
  	mmc_switch_part(mmc, FASTBOOT_MMC_USER_PARTITION_ID);
cce0bd746   Yu Shan   [iot] Check Trust...
1774
1775
1776
1777
1778
1779
1780
1781
  	tos_flashed = false;
  	if(!valid_tos()) {
  		printf("TOS not flashed! Will enter TOS recovery mode. Everything will be wiped!
  ");
  		fastboot_wipe_all();
  		run_command("fastboot 0", 0);
  		goto fail;
  	}
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
  #ifdef NON_SECURE_FASTBOOT
  	armv7_init_nonsec();
  	trusty_os_init();
  	trusty_ipc_init();
  #endif
  
  fail:
  	return;
  
  }
502522c08   Haoran.Wang   [iot] Support ARM...
1792
1793
  #endif /* CONFIG_ARM64 */
  #endif /* CONFIG_IMX_TRUSTY_OS */
1ae9ecc73   Ye Li   MLK-18591-6 andro...
1794

2c840c82b   Ye Li   MLK-18591-3 andro...
1795
1796
  void fastboot_setup(void)
  {
a251b17f4   Ye Li   MLK-19356 fastboo...
1797
  	int sw, ret;
2c840c82b   Ye Li   MLK-18591-3 andro...
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
  #ifdef CONFIG_USB_GADGET
  	struct tag_serialnr serialnr;
  	char serial[17];
  
  	get_board_serial(&serialnr);
  	sprintf(serial, "%08x%08x", serialnr.high, serialnr.low);
  	g_dnl_set_serialnumber(serial);
  #endif
  	/*execute board relevant initilizations for preparing fastboot */
  	board_fastboot_setup();
  
  	/*get the fastboot dev*/
a251b17f4   Ye Li   MLK-19356 fastboo...
1810
  	ret = _fastboot_setup_dev(&sw);
2c840c82b   Ye Li   MLK-18591-3 andro...
1811
1812
  
  	/*load partitions information for the fastboot dev*/
a251b17f4   Ye Li   MLK-19356 fastboo...
1813
1814
  	if (!ret && sw)
  		_fastboot_load_partitions();
2c840c82b   Ye Li   MLK-18591-3 andro...
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
  
  	parameters_setup();
  #ifdef CONFIG_AVB_SUPPORT
  	fsl_avb_ab_ops.ops = &fsl_avb_ops;
  #ifdef CONFIG_AVB_ATX
  	fsl_avb_atx_ops.ops = &fsl_avb_ops;
  #endif
  #endif
  }
  
  /* Write the bcb with fastboot bootloader commands */
  static void enable_fastboot_command(void)
  {
0fe527d32   Ye Li   MLK-19132-1 fastb...
1828
  #ifdef CONFIG_BCB_SUPPORT
2c840c82b   Ye Li   MLK-18591-3 andro...
1829
1830
1831
  	char fastboot_command[32] = {0};
  	strncpy(fastboot_command, FASTBOOT_BCB_CMD, 31);
  	bcb_write_command(fastboot_command);
0fe527d32   Ye Li   MLK-19132-1 fastb...
1832
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
1833
1834
1835
1836
1837
  }
  
  /* Get the Boot mode from BCB cmd or Key pressed */
  static FbBootMode fastboot_get_bootmode(void)
  {
2c840c82b   Ye Li   MLK-18591-3 andro...
1838
  	int boot_mode = BOOTMODE_NORMAL;
2c840c82b   Ye Li   MLK-18591-3 andro...
1839
1840
1841
1842
1843
1844
  #ifdef CONFIG_ANDROID_RECOVERY
  	if(is_recovery_key_pressing()) {
  		boot_mode = BOOTMODE_RECOVERY_KEY_PRESSED;
  		return boot_mode;
  	}
  #endif
0fe527d32   Ye Li   MLK-19132-1 fastb...
1845
1846
1847
  #ifdef CONFIG_BCB_SUPPORT
  	int ret = 0;
  	char command[32];
2c840c82b   Ye Li   MLK-18591-3 andro...
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
  	ret = bcb_read_command(command);
  	if (ret < 0) {
  		printf("read command failed
  ");
  		return boot_mode;
  	}
  	if (!strcmp(command, FASTBOOT_BCB_CMD)) {
  		boot_mode = BOOTMODE_FASTBOOT_BCB_CMD;
  	}
  #ifdef CONFIG_ANDROID_RECOVERY
  	else if (!strcmp(command, RECOVERY_BCB_CMD)) {
  		boot_mode = BOOTMODE_RECOVERY_BCB_CMD;
  	}
  #endif
  
  	/* Clean the mode once its read out,
  	   no matter what in the mode string */
  	memset(command, 0, 32);
  	bcb_write_command(command);
0fe527d32   Ye Li   MLK-19132-1 fastb...
1867
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
  	return boot_mode;
  }
  
  #ifdef CONFIG_SYSTEM_RAMDISK_SUPPORT
  /* Setup booargs for taking the system parition as ramdisk */
  static void fastboot_setup_system_boot_args(const char *slot, bool append_root)
  {
  	const char *system_part_name = NULL;
  	if(slot == NULL)
  		return;
  	if(!strncmp(slot, "_a", strlen("_a")) || !strncmp(slot, "boot_a", strlen("boot_a"))) {
  		system_part_name = FASTBOOT_PARTITION_SYSTEM_A;
  	}
  	else if(!strncmp(slot, "_b", strlen("_b")) || !strncmp(slot, "boot_b", strlen("boot_b"))) {
  		system_part_name = FASTBOOT_PARTITION_SYSTEM_B;
  	} else {
  		printf("slot invalid!
  ");
  		return;
  	}
  	struct fastboot_ptentry *ptentry = fastboot_flash_find_ptn(system_part_name);
  	if(ptentry != NULL) {
  		char bootargs_3rd[ANDR_BOOT_ARGS_SIZE];
  #if defined(CONFIG_FASTBOOT_STORAGE_MMC)
  		if (append_root) {
  			u32 dev_no = mmc_map_to_kernel_blk(mmc_get_env_dev());
  			sprintf(bootargs_3rd, "skip_initramfs root=/dev/mmcblk%dp%d",
  					dev_no,
  					ptentry->partition_index);
  		} else {
  			sprintf(bootargs_3rd, "skip_initramfs");
  		}
  		strcat(bootargs_3rd, " rootwait");
  		env_set("bootargs_3rd", bootargs_3rd);
  #endif
c2763113a   Ji Luo   MA-12358 Only dum...
1903
1904
1905
1906
  	} else {
  		printf("Can't find partition: %s
  ", system_part_name);
  		fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
  	}
  }
  #endif
  /* export to lib_arm/board.c */
  void fastboot_run_bootmode(void)
  {
  	FbBootMode boot_mode = fastboot_get_bootmode();
  	switch(boot_mode){
  	case BOOTMODE_FASTBOOT_BCB_CMD:
  		/* Make the boot into fastboot mode*/
  		puts("Fastboot: Got bootloader commands!
  ");
  		run_command("fastboot 0", 0);
  		break;
  #ifdef CONFIG_ANDROID_RECOVERY
  	case BOOTMODE_RECOVERY_BCB_CMD:
  	case BOOTMODE_RECOVERY_KEY_PRESSED:
  		/* Make the boot into recovery mode */
  		puts("Fastboot: Got Recovery key pressing or recovery commands!
  ");
  		board_recovery_setup();
  		break;
  #endif
  	default:
  		/* skip special mode boot*/
  		puts("Fastboot: Normal
  ");
  		break;
  	}
  }
  
  #ifdef CONFIG_CMD_BOOTA
    /* Section for Android bootimage format support
     * Refer:
     * http://android.git.kernel.org/?p=platform/system/core.git;a=blob;
     * f=mkbootimg/bootimg.h
     */
  
  void
  bootimg_print_image_hdr(struct andr_img_hdr *hdr)
  {
  #ifdef DEBUG
  	int i;
  	printf("   Image magic:   %s
  ", hdr->magic);
  
  	printf("   kernel_size:   0x%x
  ", hdr->kernel_size);
  	printf("   kernel_addr:   0x%x
  ", hdr->kernel_addr);
  
  	printf("   rdisk_size:   0x%x
  ", hdr->ramdisk_size);
  	printf("   rdisk_addr:   0x%x
  ", hdr->ramdisk_addr);
  
  	printf("   second_size:   0x%x
  ", hdr->second_size);
  	printf("   second_addr:   0x%x
  ", hdr->second_addr);
  
  	printf("   tags_addr:   0x%x
  ", hdr->tags_addr);
  	printf("   page_size:   0x%x
  ", hdr->page_size);
  
  	printf("   name:      %s
  ", hdr->name);
  	printf("   cmdline:   %s
  ", hdr->cmdline);
  
  	for (i = 0; i < 8; i++)
  		printf("   id[%d]:   0x%x
  ", i, hdr->id[i]);
  #endif
  }
6c1d174ae   Luo Ji   [iot] Enter fastb...
1983
  #if !defined(CONFIG_AVB_SUPPORT) || !defined(CONFIG_MMC)
2c840c82b   Ye Li   MLK-18591-3 andro...
1984
  static struct andr_img_hdr boothdr __aligned(ARCH_DMA_MINALIGN);
6c1d174ae   Luo Ji   [iot] Enter fastb...
1985
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
1986

5bc03ddaf   Haoran.Wang   [iot] Configure k...
1987
  #ifdef CONFIG_IMX_TRUSTY_OS
26131b634   Ji Luo   [iot] Calculate V...
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
  #ifdef CONFIG_DUAL_BOOTLOADER
  static int sha256_concatenation(uint8_t *hash_buf, uint8_t *vbh, uint8_t *image_hash)
  {
  	if ((hash_buf == NULL) || (vbh == NULL) || (image_hash == NULL)) {
  		printf("sha256_concatenation: null buffer found!
  ");
  		return -1;
  	}
  
  	memcpy(hash_buf, vbh, AVB_SHA256_DIGEST_SIZE);
  	memcpy(hash_buf + AVB_SHA256_DIGEST_SIZE,
  	       image_hash, AVB_SHA256_DIGEST_SIZE);
  	sha256_csum_wd((unsigned char *)hash_buf, 2 * AVB_SHA256_DIGEST_SIZE,
  		       (unsigned char *)vbh, CHUNKSZ_SHA256);
  
  	return 0;
  }
  
  /* Since we use fit format to organize the atf, tee, u-boot and u-boot dtb,
   * so calculate the hash of fit is enough.
   */
  static int vbh_bootloader(uint8_t *image_hash)
  {
  	char* slot_suffixes[2] = {"_a", "_b"};
  	char partition_name[20];
  	AvbABData ab_data;
  	uint8_t *image_buf = NULL;
  	uint32_t image_size;
  	size_t image_num_read;
  	int target_slot;
  	int ret = 0;
  
  	/* Load A/B metadata and decide which slot we are going to load */
  	if (fsl_avb_ab_ops.read_ab_metadata(&fsl_avb_ab_ops, &ab_data) !=
  					    AVB_IO_RESULT_OK) {
  		ret = -1;
  		goto fail ;
  	}
  	target_slot = get_curr_slot(&ab_data);
  	sprintf(partition_name, "bootloader%s", slot_suffixes[target_slot]);
  
  	/* Read image header to find the image size */
  	image_buf = (uint8_t *)malloc(MMC_SATA_BLOCK_SIZE);
  	if (fsl_avb_ops.read_from_partition(&fsl_avb_ops, partition_name,
  					    0, MMC_SATA_BLOCK_SIZE,
  					    image_buf, &image_num_read)) {
  		printf("bootloader image load error!
  ");
  		ret = -1;
  		goto fail;
  	}
  	image_size = fdt_totalsize((struct image_header *)image_buf);
  	image_size = (image_size + 3) & ~3;
  	free(image_buf);
  
  	/* Load full fit image */
  	image_buf = (uint8_t *)malloc(image_size);
  	if (fsl_avb_ops.read_from_partition(&fsl_avb_ops, partition_name,
  					    0, image_size,
  					    image_buf, &image_num_read)) {
  		printf("bootloader image load error!
  ");
  		ret = -1;
  		goto fail;
  	}
  	/* Calculate hash */
  	sha256_csum_wd((unsigned char *)image_buf, image_size,
  		       (unsigned char *)image_hash, CHUNKSZ_SHA256);
  
  fail:
  	if (image_buf != NULL)
  		free(image_buf);
  	return ret;
  }
  
  int vbh_calculate(uint8_t *vbh, AvbSlotVerifyData *avb_out_data)
  {
  	uint8_t image_hash[AVB_SHA256_DIGEST_SIZE];
  	uint8_t hash_buf[2 * AVB_SHA256_DIGEST_SIZE];
  	uint8_t* image_buf = NULL;
  	uint32_t image_size;
  	size_t image_num_read;
  	int ret = 0;
  
  	if (vbh == NULL)
  		return -1;
  
  	/* Initial VBH (VBH0) should be 32 bytes 0 */
  	memset(vbh, 0, AVB_SHA256_DIGEST_SIZE);
  	/* Load and calculate the sha256 hash of spl.bin */
  	image_size = (ANDROID_SPL_SIZE + MMC_SATA_BLOCK_SIZE -1) /
  		      MMC_SATA_BLOCK_SIZE;
  	image_buf = (uint8_t *)malloc(image_size);
  	if (fsl_avb_ops.read_from_partition(&fsl_avb_ops,
  					    FASTBOOT_PARTITION_BOOTLOADER,
  					    0, image_size,
  					    image_buf, &image_num_read)) {
  		printf("spl image load error!
  ");
  		ret = -1;
  		goto fail;
  	}
  	sha256_csum_wd((unsigned char *)image_buf, image_size,
  		       (unsigned char *)image_hash, CHUNKSZ_SHA256);
  	/* Calculate VBH1 */
  	if (sha256_concatenation(hash_buf, vbh, image_hash)) {
  		ret = -1;
  		goto fail;
  	}
  	free(image_buf);
  
  	/* Load and calculate hash of bootloader.img */
  	if (vbh_bootloader(image_hash)) {
  		ret = -1;
  		goto fail;
  	}
  	/* Calculate VBH2 */
  	if (sha256_concatenation(hash_buf, vbh, image_hash)) {
  		ret = -1;
  		goto fail;
  	}
  
  	/* Calculate the hash of vbmeta.img */
  	avb_slot_verify_data_calculate_vbmeta_digest(avb_out_data,
  						     AVB_DIGEST_TYPE_SHA256,
  						     image_hash);
  	/* Calculate VBH3 */
  	if (sha256_concatenation(hash_buf, vbh, image_hash)) {
  		ret = -1;
  		goto fail;
  	}
  
  fail:
  	if (image_buf != NULL)
  		free(image_buf);
  	return ret;
  }
  
  #endif
  int trusty_setbootparameter(struct andr_img_hdr *hdr, AvbABFlowResult avb_result,
  			    AvbSlotVerifyData *avb_out_data) {
  #ifdef CONFIG_DUAL_BOOTLOADER
  	uint8_t vbh[AVB_SHA256_DIGEST_SIZE];
  #endif
  	int ret = 0;
5bc03ddaf   Haoran.Wang   [iot] Configure k...
2133
2134
2135
2136
2137
2138
2139
2140
2141
  	u32 os_ver = hdr->os_version >> 11;
  	u32 os_ver_km = (((os_ver >> 14) & 0x7F) * 100 + ((os_ver >> 7) & 0x7F)) * 100
  	    + (os_ver & 0x7F);
  	u32 os_lvl = hdr->os_version & ((1U << 11) - 1);
  	u32 os_lvl_km = ((os_lvl >> 4) + 2000) * 100 + (os_lvl & 0x0F);
  	keymaster_verified_boot_t vbstatus;
  	FbLockState lock_status = fastboot_get_lock_stat();
  
  	uint8_t permanent_attributes_hash[AVB_SHA256_DIGEST_SIZE];
502522c08   Haoran.Wang   [iot] Support ARM...
2142
  #ifdef CONFIG_AVB_ATX
5bc03ddaf   Haoran.Wang   [iot] Configure k...
2143
2144
2145
2146
2147
  	if (fsl_read_permanent_attributes_hash(&fsl_avb_atx_ops, permanent_attributes_hash)) {
  		printf("ERROR - failed to read permanent attributes hash for keymaster
  ");
  		memset(permanent_attributes_hash, 0, AVB_SHA256_DIGEST_SIZE);
  	}
502522c08   Haoran.Wang   [iot] Support ARM...
2148
  #endif
5bc03ddaf   Haoran.Wang   [iot] Configure k...
2149
2150
2151
2152
2153
2154
  
  	bool lock = (lock_status == FASTBOOT_LOCK)? true: false;
  	if (avb_result == AVB_AB_FLOW_RESULT_OK)
  		vbstatus = KM_VERIFIED_BOOT_VERIFIED;
  	else
  		vbstatus = KM_VERIFIED_BOOT_FAILED;
26131b634   Ji Luo   [iot] Calculate V...
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
  	/* Calculate VBH */
  #ifdef CONFIG_DUAL_BOOTLOADER
  	if (vbh_calculate(vbh, avb_out_data)) {
  		ret = -1;
  		goto fail;
  	}
  
  	trusty_set_boot_params(os_ver_km, os_lvl_km, vbstatus, lock,
  			       permanent_attributes_hash, AVB_SHA256_DIGEST_SIZE,
  			       vbh, AVB_SHA256_DIGEST_SIZE);
  #else
5bc03ddaf   Haoran.Wang   [iot] Configure k...
2166
  	trusty_set_boot_params(os_ver_km, os_lvl_km, vbstatus, lock,
26131b634   Ji Luo   [iot] Calculate V...
2167
2168
2169
2170
2171
2172
  			       permanent_attributes_hash, AVB_SHA256_DIGEST_SIZE,
  			       NULL, 0);
  #endif
  
  fail:
  	return ret;
5bc03ddaf   Haoran.Wang   [iot] Configure k...
2173
2174
  }
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
2175
  #if defined(CONFIG_AVB_SUPPORT) && defined(CONFIG_MMC)
156a16fd8   Luo Ji   [iot] Add AVB ver...
2176
2177
2178
  /* we can use avb to verify Trusty if we want */
  const char *requested_partitions_boot[] = {"boot", FDT_PART_NAME, NULL};
  const char *requested_partitions_recovery[] = {"recovery", FDT_PART_NAME, NULL};
d8e1440bc   Ji Luo   MA-12345 Decide f...
2179
2180
  static bool is_load_fdt_from_part(void)
  {
b918c85c4   Ji Luo   MA-12423 Fix lega...
2181
  #if defined(CONFIG_ANDROID_THINGS_SUPPORT)
d8e1440bc   Ji Luo   MA-12345 Decide f...
2182
2183
  	if (fastboot_flash_find_ptn("oem_bootloader_a") &&
  		fastboot_flash_find_ptn("oem_bootloader_b")) {
b918c85c4   Ji Luo   MA-12423 Fix lega...
2184
  #elif defined(CONFIG_ANDROID_AB_SUPPORT)
d8e1440bc   Ji Luo   MA-12345 Decide f...
2185
2186
  	if (fastboot_flash_find_ptn("dtbo_a") &&
  		fastboot_flash_find_ptn("dtbo_b")) {
b918c85c4   Ji Luo   MA-12423 Fix lega...
2187
2188
2189
  #else
  	/* for legacy platfrom (imx6/7), we don't support A/B slot. */
  	if (fastboot_flash_find_ptn("dtbo")) {
d8e1440bc   Ji Luo   MA-12345 Decide f...
2190
2191
2192
2193
2194
2195
  #endif
  		return true;
  	} else {
  		return false;
  	}
  }
156a16fd8   Luo Ji   [iot] Add AVB ver...
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
  static int find_partition_data_by_name(char* part_name,
  		AvbSlotVerifyData* avb_out_data, AvbPartitionData** avb_loadpart)
  {
  	int num = 0;
  	AvbPartitionData* loadpart = NULL;
  
  	for (num = 0; num < avb_out_data->num_loaded_partitions; num++) {
  		loadpart = &(avb_out_data->loaded_partitions[num]);
  		if (!(strncmp(loadpart->partition_name,
  			part_name, strlen(part_name)))) {
  			*avb_loadpart = loadpart;
  			break;
  		}
  	}
  	if (num == avb_out_data->num_loaded_partitions) {
  		printf("Error! Can't find %s partition from avb partition data!
  ",
  				part_name);
  		return -1;
  	}
  	else
  		return 0;
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
  
  int do_boota(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) {
  
  	ulong addr = 0;
  	struct andr_img_hdr *hdr = NULL;
  	void *boot_buf = NULL;
  	ulong image_size;
  	u32 avb_metric;
  	bool check_image_arm64 =  false;
  	bool is_recovery_mode = false;
2c840c82b   Ye Li   MLK-18591-3 andro...
2229
  	AvbABFlowResult avb_result;
156a16fd8   Luo Ji   [iot] Add AVB ver...
2230
2231
  	AvbSlotVerifyData *avb_out_data = NULL;
  	AvbPartitionData *avb_loadpart = NULL;
2c840c82b   Ye Li   MLK-18591-3 andro...
2232
2233
2234
2235
2236
  
  	/* get bootmode, default to boot "boot" */
  	if (argc > 1) {
  		is_recovery_mode =
  			(strncmp(argv[1], "recovery", sizeof("recovery")) != 0) ? false: true;
dff624023   Ji Luo   MA-12459 Add mess...
2237
2238
2239
  		if (is_recovery_mode)
  			printf("Will boot from recovery!
  ");
2c840c82b   Ye Li   MLK-18591-3 andro...
2240
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
2241
2242
2243
  	/* check lock state */
  	FbLockState lock_status = fastboot_get_lock_stat();
  	if (lock_status == FASTBOOT_LOCK_ERROR) {
c14e9d4e2   Ji Luo   [iot] Support loc...
2244
2245
2246
2247
2248
  #ifdef CONFIG_AVB_ATX
  		printf("In boota get fastboot lock status error, enter fastboot mode.
  ");
  		goto fail;
  #else
2c840c82b   Ye Li   MLK-18591-3 andro...
2249
2250
2251
2252
  		printf("In boota get fastboot lock status error. Set lock status
  ");
  		fastboot_set_lock_stat(FASTBOOT_LOCK);
  		lock_status = FASTBOOT_LOCK;
c14e9d4e2   Ji Luo   [iot] Support loc...
2253
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
2254
2255
2256
  	}
  	bool allow_fail = (lock_status == FASTBOOT_UNLOCK ? true : false);
  	avb_metric = get_timer(0);
d8e1440bc   Ji Luo   MA-12345 Decide f...
2257
2258
2259
2260
2261
  	/* we don't need to verify fdt partition if we don't have it. */
  	if (!is_load_fdt_from_part()) {
  		requested_partitions_boot[1] = NULL;
  		requested_partitions_recovery[1] = NULL;
  	}
77542218a   Ji Luo   MA-12337-1 Includ...
2262
2263
2264
2265
2266
  #ifndef CONFIG_ANDROID_AB_SUPPORT
  	else if (is_recovery_mode){
  		requested_partitions_recovery[1] = NULL;
  	}
  #endif
0bfb34cbc   Luo Ji   [iot] Verify sing...
2267
2268
  	/* if in lock state, do avb verify */
  #ifndef CONFIG_DUAL_BOOTLOADER
2c840c82b   Ye Li   MLK-18591-3 andro...
2269
2270
2271
2272
2273
  	/* For imx6 on Android, we don't have a/b slot and we want to verify
  	 * boot/recovery with AVB. For imx8 and Android Things we don't have
  	 * recovery and support a/b slot for boot */
  #ifdef CONFIG_ANDROID_AB_SUPPORT
  	/* we can use avb to verify Trusty if we want */
156a16fd8   Luo Ji   [iot] Add AVB ver...
2274
  	avb_result = avb_ab_flow_fast(&fsl_avb_ab_ops, requested_partitions_boot, allow_fail,
2c840c82b   Ye Li   MLK-18591-3 andro...
2275
  			AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE, &avb_out_data);
0bfb34cbc   Luo Ji   [iot] Verify sing...
2276
  #else
2c840c82b   Ye Li   MLK-18591-3 andro...
2277
  	if (!is_recovery_mode) {
156a16fd8   Luo Ji   [iot] Add AVB ver...
2278
  		avb_result = avb_single_flow(&fsl_avb_ab_ops, requested_partitions_boot, allow_fail,
2c840c82b   Ye Li   MLK-18591-3 andro...
2279
2280
  				AVB_HASHTREE_ERROR_MODE_RESTART, &avb_out_data);
  	} else {
156a16fd8   Luo Ji   [iot] Add AVB ver...
2281
  		avb_result = avb_single_flow(&fsl_avb_ab_ops, requested_partitions_recovery, allow_fail,
2c840c82b   Ye Li   MLK-18591-3 andro...
2282
2283
  				AVB_HASHTREE_ERROR_MODE_RESTART, &avb_out_data);
  	}
0bfb34cbc   Luo Ji   [iot] Verify sing...
2284
2285
2286
  #endif
  #else /* !CONFIG_DUAL_BOOTLOADER */
  	/* We will only verify single one slot which has been selected in SPL */
156a16fd8   Luo Ji   [iot] Add AVB ver...
2287
  	avb_result = avb_flow_dual_uboot(&fsl_avb_ab_ops, requested_partitions_boot, allow_fail,
0bfb34cbc   Luo Ji   [iot] Verify sing...
2288
2289
2290
2291
2292
2293
2294
2295
2296
  			AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE, &avb_out_data);
  
  	/* Goto fail early if current slot is not bootable. */
  	if (avb_result == AVB_AB_FLOW_RESULT_ERROR_NO_BOOTABLE_SLOTS) {
  		printf("boota: slot verify fail!
  ");
  		goto fail;
  	}
  #endif /* !CONFIG_DUAL_BOOTLOADER */
2c840c82b   Ye Li   MLK-18591-3 andro...
2297
2298
2299
2300
2301
2302
  	/* get the duration of avb */
  	metrics.avb = get_timer(avb_metric);
  
  	if ((avb_result == AVB_AB_FLOW_RESULT_OK) ||
  			(avb_result == AVB_AB_FLOW_RESULT_OK_WITH_VERIFICATION_ERROR)) {
  		assert(avb_out_data != NULL);
156a16fd8   Luo Ji   [iot] Add AVB ver...
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
  		/* We may have more than one partition loaded by AVB, find the boot
  		 * partition first.
  		 */
  #ifdef CONFIG_ANDROID_AB_SUPPORT
  		if (find_partition_data_by_name("boot", avb_out_data, &avb_loadpart))
  			goto fail;
  #else
  		if (!is_recovery_mode) {
  			if (find_partition_data_by_name("boot", avb_out_data, &avb_loadpart))
  				goto fail;
  		} else {
  			if (find_partition_data_by_name("recovery", avb_out_data, &avb_loadpart))
  				goto fail;
  		}
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
  		assert(avb_loadpart != NULL);
  		/* we should use avb_part_data->data as boot image */
  		/* boot image is already read by avb */
  		hdr = (struct andr_img_hdr *)avb_loadpart->data;
  		if (android_image_check_header(hdr)) {
  			printf("boota: bad boot image magic
  ");
  			goto fail;
  		}
  		if (avb_result == AVB_AB_FLOW_RESULT_OK)
  			printf(" verify OK, boot '%s%s'
  ",
  					avb_loadpart->partition_name, avb_out_data->ab_suffix);
  		else {
  			printf(" verify FAIL, state: UNLOCK
  ");
  			printf(" boot '%s%s' still
  ",
  					avb_loadpart->partition_name, avb_out_data->ab_suffix);
  		}
2081a2556   Braden Kell   Fix buffer overfl...
2338
  		char bootargs_sec[ANDR_BOOT_EXTRA_ARGS_SIZE];
2c840c82b   Ye Li   MLK-18591-3 andro...
2339
  		if (lock_status == FASTBOOT_LOCK) {
2081a2556   Braden Kell   Fix buffer overfl...
2340
  			snprintf(bootargs_sec, sizeof(bootargs_sec),
2c840c82b   Ye Li   MLK-18591-3 andro...
2341
2342
2343
  					"androidboot.verifiedbootstate=green androidboot.slot_suffix=%s %s",
  					avb_out_data->ab_suffix, avb_out_data->cmdline);
  		} else {
2081a2556   Braden Kell   Fix buffer overfl...
2344
  			snprintf(bootargs_sec, sizeof(bootargs_sec),
2c840c82b   Ye Li   MLK-18591-3 andro...
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
  					"androidboot.verifiedbootstate=orange androidboot.slot_suffix=%s %s",
  					avb_out_data->ab_suffix, avb_out_data->cmdline);
  		}
  		env_set("bootargs_sec", bootargs_sec);
  #ifdef CONFIG_SYSTEM_RAMDISK_SUPPORT
  		if(!is_recovery_mode) {
  			if(avb_out_data->cmdline != NULL && strstr(avb_out_data->cmdline, "root="))
  				fastboot_setup_system_boot_args(avb_out_data->ab_suffix, false);
  			else
  				fastboot_setup_system_boot_args(avb_out_data->ab_suffix, true);
  		}
  #endif /* CONFIG_SYSTEM_RAMDISK_SUPPORT */
  		image_size = avb_loadpart->data_size;
  #if defined (CONFIG_ARCH_IMX8) || defined (CONFIG_ARCH_IMX8M)
  		/* If we are using uncompressed kernel image, copy it directly to
  		 * hdr->kernel_addr, if we are using compressed lz4 kernel image,
  		 * we need to decompress the kernel image first. */
  		if (image_arm64((void *)((ulong)hdr + hdr->page_size))) {
  			memcpy((void *)(long)hdr->kernel_addr,
  					(void *)((ulong)hdr + hdr->page_size), hdr->kernel_size);
  		} else {
  #ifdef CONFIG_LZ4
4d6938979   Luo Ji   MA-12124 [Android...
2367
  			size_t lz4_len = DST_DECOMPRESS_LEN;
2c840c82b   Ye Li   MLK-18591-3 andro...
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
  			if (ulz4fn((void *)((ulong)hdr + hdr->page_size),
  						hdr->kernel_size, (void *)(ulong)hdr->kernel_addr, &lz4_len) != 0) {
  				printf("Decompress kernel fail!
  ");
  				goto fail;
  			}
  #else /* CONFIG_LZ4 */
  			printf("please enable CONFIG_LZ4 if we're using compressed lz4 kernel image!
  ");
  			goto fail;
  #endif /* CONFIG_LZ4 */
  		}
  #else /* CONFIG_ARCH_IMX8 || CONFIG_ARCH_IMX8M */
  		/* copy kernel image and boot header to hdr->kernel_addr - hdr->page_size */
  		memcpy((void *)(ulong)(hdr->kernel_addr - hdr->page_size), (void *)hdr,
  				hdr->page_size + ALIGN(hdr->kernel_size, hdr->page_size));
  #endif /* CONFIG_ARCH_IMX8 || CONFIG_ARCH_IMX8M */
6c1d174ae   Luo Ji   [iot] Enter fastb...
2385
2386
2387
2388
2389
2390
2391
  	} else {
  		/* Fall into fastboot mode if get unacceptable error from avb
  		 * or verify fail in lock state.
  		 */
  		if (lock_status == FASTBOOT_LOCK)
  			printf(" verify FAIL, state: LOCK
  ");
2c840c82b   Ye Li   MLK-18591-3 andro...
2392
  		goto fail;
2c840c82b   Ye Li   MLK-18591-3 andro...
2393
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
  
  	flush_cache((ulong)load_addr, image_size);
  	check_image_arm64  = image_arm64((void *)(ulong)hdr->kernel_addr);
  #ifdef CONFIG_SYSTEM_RAMDISK_SUPPORT
  	if (is_recovery_mode)
  		memcpy((void *)(ulong)hdr->ramdisk_addr, (void *)(ulong)hdr + hdr->page_size
  				+ ALIGN(hdr->kernel_size, hdr->page_size), hdr->ramdisk_size);
  #else
  	memcpy((void *)(ulong)hdr->ramdisk_addr, (void *)(ulong)hdr + hdr->page_size
  			+ ALIGN(hdr->kernel_size, hdr->page_size), hdr->ramdisk_size);
  #endif
  #ifdef CONFIG_OF_LIBFDT
cfcbadd83   Luo Ji   MA-12121 [Android...
2406
  	/* load the dtb file */
77542218a   Ji Luo   MA-12337-1 Includ...
2407
2408
  	u32 fdt_size = 0;
  	struct dt_table_header *dt_img = NULL;
d8e1440bc   Ji Luo   MA-12345 Decide f...
2409
  	if (is_load_fdt_from_part()) {
156a16fd8   Luo Ji   [iot] Add AVB ver...
2410
  #ifdef CONFIG_ANDROID_THINGS_SUPPORT
d8e1440bc   Ji Luo   MA-12345 Decide f...
2411
2412
2413
  		if (find_partition_data_by_name("oem_bootloader",
  					avb_out_data, &avb_loadpart)) {
  			goto fail;
77542218a   Ji Luo   MA-12337-1 Includ...
2414
2415
2416
  		} else
  			dt_img = (struct dt_table_header *)avb_loadpart->data;
  #elif defined(CONFIG_ANDROID_AB_SUPPORT)
d8e1440bc   Ji Luo   MA-12345 Decide f...
2417
2418
2419
  		if (find_partition_data_by_name("dtbo",
  					avb_out_data, &avb_loadpart)) {
  			goto fail;
77542218a   Ji Luo   MA-12337-1 Includ...
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
  		} else
  			dt_img = (struct dt_table_header *)avb_loadpart->data;
  #else
  		if (is_recovery_mode) {
  			if (hdr->header_version != 1) {
  				printf("boota: boot image header version error!
  ");
  				goto fail;
  			}
  
  			dt_img = (struct dt_table_header *)((void *)(ulong)hdr +
  						hdr->page_size +
  						ALIGN(hdr->kernel_size, hdr->page_size) +
  						ALIGN(hdr->ramdisk_size, hdr->page_size) +
  						ALIGN(hdr->second_size, hdr->page_size));
  		} else if (find_partition_data_by_name("dtbo",
  						avb_out_data, &avb_loadpart)) {
  			goto fail;
  		} else
  			dt_img = (struct dt_table_header *)avb_loadpart->data;
156a16fd8   Luo Ji   [iot] Add AVB ver...
2440
  #endif
77542218a   Ji Luo   MA-12337-1 Includ...
2441

d8e1440bc   Ji Luo   MA-12345 Decide f...
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
  		if (be32_to_cpu(dt_img->magic) != DT_TABLE_MAGIC) {
  			printf("boota: bad dt table magic %08x
  ",
  					be32_to_cpu(dt_img->magic));
  			goto fail;
  		} else if (!be32_to_cpu(dt_img->dt_entry_count)) {
  			printf("boota: no dt entries
  ");
  			goto fail;
  		}
153021557   Braden Kell   [iot] Load fdt fr...
2452

d8e1440bc   Ji Luo   MA-12345 Decide f...
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
  		struct dt_table_entry *dt_entry;
  		dt_entry = (struct dt_table_entry *)((ulong)dt_img +
  				be32_to_cpu(dt_img->dt_entries_offset));
  		fdt_size = be32_to_cpu(dt_entry->dt_size);
  		memcpy((void *)(ulong)hdr->second_addr, (void *)((ulong)dt_img +
  				be32_to_cpu(dt_entry->dt_offset)), fdt_size);
  	} else {
  		if (hdr->second_size && hdr->second_addr) {
  			memcpy((void *)(ulong)hdr->second_addr,
  				(void *)(ulong)hdr + hdr->page_size
  				+ ALIGN(hdr->kernel_size, hdr->page_size)
  				+ ALIGN(hdr->ramdisk_size, hdr->page_size),
  				hdr->second_size);
  		}
cfcbadd83   Luo Ji   MA-12121 [Android...
2467
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
2468
  #endif /*CONFIG_OF_LIBFDT*/
156a16fd8   Luo Ji   [iot] Add AVB ver...
2469

2c840c82b   Ye Li   MLK-18591-3 andro...
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
  	if (check_image_arm64) {
  		android_image_get_kernel(hdr, 0, NULL, NULL);
  		addr = hdr->kernel_addr;
  	} else {
  		addr = (ulong)(hdr->kernel_addr - hdr->page_size);
  	}
  	printf("kernel   @ %08x (%d)
  ", hdr->kernel_addr, hdr->kernel_size);
  	printf("ramdisk  @ %08x (%d)
  ", hdr->ramdisk_addr, hdr->ramdisk_size);
  #ifdef CONFIG_OF_LIBFDT
d8e1440bc   Ji Luo   MA-12345 Decide f...
2481
2482
2483
2484
2485
2486
2487
2488
2489
  	if (is_load_fdt_from_part()) {
  		if (fdt_size)
  			printf("fdt      @ %08x (%d)
  ", hdr->second_addr, fdt_size);
  	} else {
  		if (hdr->second_size)
  			printf("fdt      @ %08x (%d)
  ", hdr->second_addr, hdr->second_size);
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
  #endif /*CONFIG_OF_LIBFDT*/
  
  	char boot_addr_start[12];
  	char ramdisk_addr[25];
  	char fdt_addr[12];
  
  	char *boot_args[] = { NULL, boot_addr_start, ramdisk_addr, fdt_addr};
  	if (check_image_arm64)
  		boot_args[0] = "booti";
  	else
  		boot_args[0] = "bootm";
  
  	sprintf(boot_addr_start, "0x%lx", addr);
  	sprintf(ramdisk_addr, "0x%x:0x%x", hdr->ramdisk_addr, hdr->ramdisk_size);
  	sprintf(fdt_addr, "0x%x", hdr->second_addr);
  
  /* no need to pass ramdisk addr for normal boot mode when enable CONFIG_SYSTEM_RAMDISK_SUPPORT*/
  #ifdef CONFIG_SYSTEM_RAMDISK_SUPPORT
  	if (!is_recovery_mode)
  		boot_args[2] = NULL;
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
2511

1ae9ecc73   Ye Li   MLK-18591-6 andro...
2512
  #ifdef CONFIG_IMX_TRUSTY_OS
5bc03ddaf   Haoran.Wang   [iot] Configure k...
2513
  	/* Trusty keymaster needs some parameters before it work */
26131b634   Ji Luo   [iot] Calculate V...
2514
2515
  	if (trusty_setbootparameter(hdr, avb_result, avb_out_data))
  		goto fail;
b92b0e1d4   Yu Shan   [iot] Use Trusty ...
2516
2517
  	/* lock the boot status and rollback_idx preventing Linux modify it */
  	trusty_lock_boot_state();
1ae9ecc73   Ye Li   MLK-18591-6 andro...
2518
2519
2520
  	/* put ql-tipc to release resource for Linux */
  	trusty_ipc_shutdown();
  #endif
26131b634   Ji Luo   [iot] Calculate V...
2521
2522
2523
2524
2525
  
  	if (avb_out_data != NULL)
  		avb_slot_verify_data_free(avb_out_data);
  	if (boot_buf != NULL)
  		free(boot_buf);
2c840c82b   Ye Li   MLK-18591-3 andro...
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
  	if (check_image_arm64) {
  #ifdef CONFIG_CMD_BOOTI
  		do_booti(NULL, 0, 4, boot_args);
  #else
  		debug("please enable CONFIG_CMD_BOOTI when kernel are Image");
  #endif
  	} else {
  		do_bootm(NULL, 0, 4, boot_args);
  	}
  
  	/* This only happens if image is somehow faulty so we start over */
  	do_reset(NULL, 0, 0, NULL);
  
  	return 1;
  
  fail:
  	/* avb has no recovery */
  	if (avb_out_data != NULL)
  		avb_slot_verify_data_free(avb_out_data);
2c840c82b   Ye Li   MLK-18591-3 andro...
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
  
  	return run_command("fastboot 0", 0);
  }
  
  U_BOOT_CMD(
  	boota,	2,	1,	do_boota,
  	"boota   - boot android bootimg 
  ",
  	"boot from current mmc with avb verify
  "
  );
  #else /* CONFIG_AVB_SUPPORT */
  /* boota <addr> [ mmc0 | mmc1 [ <partition> ] ] */
  int do_boota(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
  {
  	ulong addr = 0;
  	char *ptn = "boot";
  	int mmcc = -1;
  	struct andr_img_hdr *hdr = &boothdr;
  	ulong image_size;
  	bool check_image_arm64 =  false;
  	int i = 0;
  
  	for (i = 0; i < argc; i++)
  		printf("%s ", argv[i]);
  	printf("
  ");
  
  	if (argc < 2)
  		return -1;
  
  	mmcc = simple_strtoul(argv[1]+3, NULL, 10);
  
  	if (argc > 2)
  		ptn = argv[2];
  
  	if (mmcc != -1) {
  #ifdef CONFIG_MMC
  		struct fastboot_ptentry *pte;
  		struct mmc *mmc;
  		disk_partition_t info;
  		struct blk_desc *dev_desc = NULL;
  		unsigned bootimg_sectors;
  
  		memset((void *)&info, 0 , sizeof(disk_partition_t));
  		/* i.MX use MBR as partition table, so this will have
  		   to find the start block and length for the
  		   partition name and register the fastboot pte we
  		   define the partition number of each partition in
  		   config file
  		 */
  		mmc = find_mmc_device(mmcc);
  		if (!mmc) {
  			printf("boota: cannot find '%d' mmc device
  ", mmcc);
  			goto fail;
  		}
  		dev_desc = blk_get_dev("mmc", mmcc);
  		if (!dev_desc || dev_desc->type == DEV_TYPE_UNKNOWN) {
  			printf("** Block device MMC %d not supported
  ", mmcc);
  			goto fail;
  		}
  
  		/* below was i.MX mmc operation code */
  		if (mmc_init(mmc)) {
  			printf("mmc%d init failed
  ", mmcc);
  			goto fail;
  		}
  
  		pte = fastboot_flash_find_ptn(ptn);
  		if (!pte) {
  			printf("boota: cannot find '%s' partition
  ", ptn);
c2763113a   Ji Luo   MA-12358 Only dum...
2620
  			fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
  			goto fail;
  		}
  
  		if (blk_dread(dev_desc, pte->start,
  					      1, (void *)hdr) < 0) {
  			printf("boota: mmc failed to read bootimg header
  ");
  			goto fail;
  		}
  
  		if (android_image_check_header(hdr)) {
  			printf("boota: bad boot image magic
  ");
  			goto fail;
  		}
  
  		image_size = android_image_get_end(hdr) - (ulong)hdr;
  		bootimg_sectors = image_size/512;
  
  		if (blk_dread(dev_desc,	pte->start,
  					bootimg_sectors,
  					(void *)(hdr->kernel_addr - hdr->page_size)) < 0) {
  			printf("boota: mmc failed to read bootimage
  ");
  			goto fail;
  		}
  		check_image_arm64  = image_arm64((void *)hdr->kernel_addr);
  #ifdef CONFIG_FASTBOOT_LOCK
  		int verifyresult = -1;
  #endif
  
  #ifdef CONFIG_FASTBOOT_LOCK
  		int lock_status = fastboot_get_lock_stat();
  		if (lock_status == FASTBOOT_LOCK_ERROR) {
  			printf("In boota get fastboot lock status error. Set lock status
  ");
  			fastboot_set_lock_stat(FASTBOOT_LOCK);
  		}
  		display_lock(fastboot_get_lock_stat(), verifyresult);
  #endif
  		/* load the ramdisk file */
  		memcpy((void *)hdr->ramdisk_addr, (void *)hdr->kernel_addr
  			+ ALIGN(hdr->kernel_size, hdr->page_size), hdr->ramdisk_size);
  
  #ifdef CONFIG_OF_LIBFDT
5eb21386c   Braden Kell   [iot] Copy fdt fr...
2666
  		u32 fdt_size = 0;
2c840c82b   Ye Li   MLK-18591-3 andro...
2667
  		/* load the dtb file */
5eb21386c   Braden Kell   [iot] Copy fdt fr...
2668
2669
2670
2671
2672
2673
  		if (hdr->second_addr) {
  			u32 zimage_size = ((u32 *)hdrload->kernel_addr)[ZIMAGE_END_ADDR]
  					- ((u32 *)hdrload->kernel_addr)[ZIMAGE_START_ADDR];
  			fdt_size = hdrload->kernel_size - zimage_size;
  			memcpy((void *)(ulong)hdrload->second_addr,
  					(void*)(ulong)hdrload->kernel_addr + zimage_size, fdt_size);
2c840c82b   Ye Li   MLK-18591-3 andro...
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
  		}
  #endif /*CONFIG_OF_LIBFDT*/
  
  #else /*! CONFIG_MMC*/
  		return -1;
  #endif /*! CONFIG_MMC*/
  	} else {
  		printf("boota: parameters is invalid. only support mmcX device
  ");
  		return -1;
  	}
  
  	printf("kernel   @ %08x (%d)
  ", hdr->kernel_addr, hdr->kernel_size);
  	printf("ramdisk  @ %08x (%d)
  ", hdr->ramdisk_addr, hdr->ramdisk_size);
  #ifdef CONFIG_OF_LIBFDT
5eb21386c   Braden Kell   [iot] Copy fdt fr...
2691
2692
2693
  	if (fdt_size)
  		printf("fdt      @ %08x (%d)
  ", hdr->second_addr, fdt_size);
2c840c82b   Ye Li   MLK-18591-3 andro...
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
  #endif /*CONFIG_OF_LIBFDT*/
  
  
  	char boot_addr_start[12];
  	char ramdisk_addr[25];
  	char fdt_addr[12];
  	char *boot_args[] = { NULL, boot_addr_start, ramdisk_addr, fdt_addr};
  	if (check_image_arm64 ) {
  		addr = hdr->kernel_addr;
  		boot_args[0] = "booti";
  	} else {
  		addr = hdr->kernel_addr - hdr->page_size;
  		boot_args[0] = "bootm";
  	}
  
  	sprintf(boot_addr_start, "0x%lx", addr);
  	sprintf(ramdisk_addr, "0x%x:0x%x", hdr->ramdisk_addr, hdr->ramdisk_size);
  	sprintf(fdt_addr, "0x%x", hdr->second_addr);
  	if (check_image_arm64) {
  		android_image_get_kernel(hdr, 0, NULL, NULL);
  #ifdef CONFIG_CMD_BOOTI
  		do_booti(NULL, 0, 4, boot_args);
  #else
  		debug("please enable CONFIG_CMD_BOOTI when kernel are Image");
  #endif
  	} else {
  		do_bootm(NULL, 0, 4, boot_args);
  	}
  	/* This only happens if image is somehow faulty so we start over */
  	do_reset(NULL, 0, 0, NULL);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2724

2c840c82b   Ye Li   MLK-18591-3 andro...
2725
  	return 1;
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
2726

2c840c82b   Ye Li   MLK-18591-3 andro...
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
  fail:
  #if defined(CONFIG_FSL_FASTBOOT)
  	return run_command("fastboot 0", 0);
  #else /*! CONFIG_FSL_FASTBOOT*/
  	return -1;
  #endif /*! CONFIG_FSL_FASTBOOT*/
  }
  
  U_BOOT_CMD(
  	boota,	3,	1,	do_boota,
  	"boota   - boot android bootimg from memory
  ",
  	"[<addr> | mmc0 | mmc1 | mmc2 | mmcX] [<partition>]
      "
  	"- boot application image stored in memory or mmc
  "
  	"\t'addr' should be the address of boot image "
  	"which is zImage+ramdisk.img
  "
  	"\t'mmcX' is the mmc device you store your boot.img, "
  	"which will read the boot.img from 1M offset('/boot' partition)
  "
  	"\t 'partition' (optional) is the partition id of your device, "
  	"if no partition give, will going to 'boot' partition
  "
  );
  #endif /* CONFIG_AVB_SUPPORT */
  #endif	/* CONFIG_CMD_BOOTA */
  #endif
9bc34799c   Steve Rae   fastboot: sparse:...
2756
2757
  
  void fastboot_fail(const char *reason)
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
2758
  {
9bc34799c   Steve Rae   fastboot: sparse:...
2759
2760
  	strncpy(fb_response_str, "FAIL\0", 5);
  	strncat(fb_response_str, reason, FASTBOOT_RESPONSE_LEN - 4 - 1);
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
2761
  }
9bc34799c   Steve Rae   fastboot: sparse:...
2762
  void fastboot_okay(const char *reason)
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
2763
  {
9bc34799c   Steve Rae   fastboot: sparse:...
2764
2765
  	strncpy(fb_response_str, "OKAY\0", 5);
  	strncat(fb_response_str, reason, FASTBOOT_RESPONSE_LEN - 4 - 1);
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
2766
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
  static void fastboot_fifo_complete(struct usb_ep *ep, struct usb_request *req)
  {
  	int status = req->status;
  	usb_req *request;
  
  	if (!status) {
  		if (fastboot_func->front != NULL) {
  			request = fastboot_func->front;
  			fastboot_func->front = fastboot_func->front->next;
  			usb_ep_free_request(ep, request->in_req);
  			free(request);
  		} else {
  			printf("fail free request
  ");
  		}
  		return;
  	}
  }
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
  static void fastboot_complete(struct usb_ep *ep, struct usb_request *req)
  {
  	int status = req->status;
  	if (!status)
  		return;
  	printf("status: %d ep '%s' trans: %d
  ", status, ep->name, req->actual);
  }
  
  static int fastboot_bind(struct usb_configuration *c, struct usb_function *f)
  {
  	int id;
  	struct usb_gadget *gadget = c->cdev->gadget;
  	struct f_fastboot *f_fb = func_to_fastboot(f);
537cd072d   Dileep Katta   usb: gadget: fast...
2799
  	const char *s;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2800
2801
2802
2803
2804
2805
  
  	/* DYNAMIC interface numbers assignments */
  	id = usb_interface_id(c, f);
  	if (id < 0)
  		return id;
  	interface_desc.bInterfaceNumber = id;
a505d1ed5   Li Jun   MLK-18376-5 usb: ...
2806
2807
2808
2809
2810
2811
2812
  	/* Enable OS and Extended Properties Feature Descriptor */
  	c->cdev->use_os_string = 1;
  	f->os_desc_table = &fb_os_desc_table;
  	f->os_desc_n = 1;
  	f->os_desc_table->if_id = id;
  	INIT_LIST_HEAD(&fb_os_desc.ext_prop);
  	fb_ext_prop.name_len = strlen(fb_ext_prop.name) * 2 + 2;
e66d1fb4f   Li Jun   MLK-20305 usb: ga...
2813
  	fb_os_desc.ext_prop_len = 10 + fb_ext_prop.name_len;
a505d1ed5   Li Jun   MLK-18376-5 usb: ...
2814
  	fb_os_desc.ext_prop_count = 1;
e66d1fb4f   Li Jun   MLK-20305 usb: ga...
2815
2816
  	fb_ext_prop.data_len = strlen(fb_ext_prop.data) * 2 + 2;
  	fb_os_desc.ext_prop_len += fb_ext_prop.data_len + 4;
a505d1ed5   Li Jun   MLK-18376-5 usb: ...
2817
  	list_add_tail(&fb_ext_prop.entry, &fb_os_desc.ext_prop);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
  	id = usb_string_id(c->cdev);
  	if (id < 0)
  		return id;
  	fastboot_string_defs[0].id = id;
  	interface_desc.iInterface = id;
  
  	f_fb->in_ep = usb_ep_autoconfig(gadget, &fs_ep_in);
  	if (!f_fb->in_ep)
  		return -ENODEV;
  	f_fb->in_ep->driver_data = c->cdev;
  
  	f_fb->out_ep = usb_ep_autoconfig(gadget, &fs_ep_out);
  	if (!f_fb->out_ep)
  		return -ENODEV;
  	f_fb->out_ep->driver_data = c->cdev;
718156ad0   Roger Quadros   fastboot: Fix wMa...
2833
2834
2835
2836
2837
2838
2839
2840
2841
  	f->descriptors = fb_fs_function;
  
  	if (gadget_is_dualspeed(gadget)) {
  		/* Assume endpoint addresses are the same for both speeds */
  		hs_ep_in.bEndpointAddress = fs_ep_in.bEndpointAddress;
  		hs_ep_out.bEndpointAddress = fs_ep_out.bEndpointAddress;
  		/* copy HS descriptors */
  		f->hs_descriptors = fb_hs_function;
  	}
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2842

00caae6d4   Simon Glass   env: Rename geten...
2843
  	s = env_get("serial#");
537cd072d   Dileep Katta   usb: gadget: fast...
2844
2845
  	if (s)
  		g_dnl_set_serialnumber((char *)s);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2846
2847
2848
2849
2850
  	return 0;
  }
  
  static void fastboot_unbind(struct usb_configuration *c, struct usb_function *f)
  {
a505d1ed5   Li Jun   MLK-18376-5 usb: ...
2851
2852
  	f->os_desc_table = NULL;
  	list_del(&fb_os_desc.ext_prop);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2853
2854
2855
2856
2857
  	memset(fastboot_func, 0, sizeof(*fastboot_func));
  }
  
  static void fastboot_disable(struct usb_function *f)
  {
2c840c82b   Ye Li   MLK-18591-3 andro...
2858
  	usb_req *req;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
  	struct f_fastboot *f_fb = func_to_fastboot(f);
  
  	usb_ep_disable(f_fb->out_ep);
  	usb_ep_disable(f_fb->in_ep);
  
  	if (f_fb->out_req) {
  		free(f_fb->out_req->buf);
  		usb_ep_free_request(f_fb->out_ep, f_fb->out_req);
  		f_fb->out_req = NULL;
  	}
  	if (f_fb->in_req) {
  		free(f_fb->in_req->buf);
  		usb_ep_free_request(f_fb->in_ep, f_fb->in_req);
2c840c82b   Ye Li   MLK-18591-3 andro...
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
  
  		/* disable usb request FIFO */
  		while(f_fb->front != NULL) {
  			req = f_fb->front;
  			f_fb->front = f_fb->front->next;
  			free(req->in_req->buf);
  			usb_ep_free_request(f_fb->in_ep, req->in_req);
  			free(req);
  		}
  
  		f_fb->rear = NULL;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
  		f_fb->in_req = NULL;
  	}
  }
  
  static struct usb_request *fastboot_start_ep(struct usb_ep *ep)
  {
  	struct usb_request *req;
  
  	req = usb_ep_alloc_request(ep, 0);
  	if (!req)
  		return NULL;
  
  	req->length = EP_BUFFER_SIZE;
  	req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, EP_BUFFER_SIZE);
  	if (!req->buf) {
  		usb_ep_free_request(ep, req);
  		return NULL;
  	}
  
  	memset(req->buf, 0, req->length);
  	return req;
  }
  
  static int fastboot_set_alt(struct usb_function *f,
  			    unsigned interface, unsigned alt)
  {
  	int ret;
  	struct usb_composite_dev *cdev = f->config->cdev;
  	struct usb_gadget *gadget = cdev->gadget;
  	struct f_fastboot *f_fb = func_to_fastboot(f);
8b704a0e3   Roger Quadros   fastboot: Enable ...
2913
  	const struct usb_endpoint_descriptor *d;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2914
2915
2916
2917
  
  	debug("%s: func: %s intf: %d alt: %d
  ",
  	      __func__, f->name, interface, alt);
8b704a0e3   Roger Quadros   fastboot: Enable ...
2918
2919
  	d = fb_ep_desc(gadget, &fs_ep_out, &hs_ep_out);
  	ret = usb_ep_enable(f_fb->out_ep, d);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
  	if (ret) {
  		puts("failed to enable out ep
  ");
  		return ret;
  	}
  
  	f_fb->out_req = fastboot_start_ep(f_fb->out_ep);
  	if (!f_fb->out_req) {
  		puts("failed to alloc out req
  ");
  		ret = -EINVAL;
  		goto err;
  	}
  	f_fb->out_req->complete = rx_handler_command;
8b704a0e3   Roger Quadros   fastboot: Enable ...
2934
2935
  	d = fb_ep_desc(gadget, &fs_ep_in, &hs_ep_in);
  	ret = usb_ep_enable(f_fb->in_ep, d);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
  	if (ret) {
  		puts("failed to enable in ep
  ");
  		goto err;
  	}
  
  	f_fb->in_req = fastboot_start_ep(f_fb->in_ep);
  	if (!f_fb->in_req) {
  		puts("failed alloc req in
  ");
  		ret = -EINVAL;
  		goto err;
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
2949
2950
2951
2952
2953
2954
2955
2956
2957
  #ifdef CONFIG_ANDROID_THINGS_SUPPORT
  	/*
  	 * fastboot host end implement to get data in one bulk package so need
  	 * large buffer for the "fastboot upload" and "fastboot get_staged".
  	 */
  	if (f_fb->in_req->buf)
  		free(f_fb->in_req->buf);
  	f_fb->in_req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, EP_BUFFER_SIZE * 32);
  #endif
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2958
  	f_fb->in_req->complete = fastboot_complete;
2c840c82b   Ye Li   MLK-18591-3 andro...
2959
  	f_fb->front = f_fb->rear = NULL;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
  	ret = usb_ep_queue(f_fb->out_ep, f_fb->out_req, 0);
  	if (ret)
  		goto err;
  
  	return 0;
  err:
  	fastboot_disable(f);
  	return ret;
  }
  
  static int fastboot_add(struct usb_configuration *c)
  {
  	struct f_fastboot *f_fb = fastboot_func;
  	int status;
  
  	debug("%s: cdev: 0x%p
  ", __func__, c->cdev);
  
  	if (!f_fb) {
  		f_fb = memalign(CONFIG_SYS_CACHELINE_SIZE, sizeof(*f_fb));
  		if (!f_fb)
  			return -ENOMEM;
  
  		fastboot_func = f_fb;
  		memset(f_fb, 0, sizeof(*f_fb));
  	}
  
  	f_fb->usb_function.name = "f_fastboot";
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2988
2989
2990
2991
2992
2993
2994
2995
2996
  	f_fb->usb_function.bind = fastboot_bind;
  	f_fb->usb_function.unbind = fastboot_unbind;
  	f_fb->usb_function.set_alt = fastboot_set_alt;
  	f_fb->usb_function.disable = fastboot_disable;
  	f_fb->usb_function.strings = fastboot_strings;
  
  	status = usb_add_function(c, &f_fb->usb_function);
  	if (status) {
  		free(f_fb);
2c840c82b   Ye Li   MLK-18591-3 andro...
2997
  		fastboot_func = NULL;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
2998
2999
3000
3001
3002
  	}
  
  	return status;
  }
  DECLARE_GADGET_BIND_CALLBACK(usb_dnl_fastboot, fastboot_add);
2c840c82b   Ye Li   MLK-18591-3 andro...
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
  static int fastboot_tx_write_more(const char *buffer)
  {
  	int ret = 0;
  
  	/* alloc usb request FIFO node */
  	usb_req *req = (usb_req *)malloc(sizeof(usb_req));
  	if (!req) {
  		printf("failed alloc usb req!
  ");
  		return -ENOMEM;
  	}
  
  	/* usb request node FIFO enquene */
  	if ((fastboot_func->front == NULL) && (fastboot_func->rear == NULL)) {
  		fastboot_func->front = fastboot_func->rear = req;
  		req->next = NULL;
  	} else {
  		fastboot_func->rear->next = req;
  		fastboot_func->rear = req;
  		req->next = NULL;
  	}
  
  	/* alloc in request for current node */
  	req->in_req = fastboot_start_ep(fastboot_func->in_ep);
  	if (!req->in_req) {
  		printf("failed alloc req in
  ");
  		fastboot_disable(&(fastboot_func->usb_function));
  		return  -EINVAL;
  	}
  	req->in_req->complete = fastboot_fifo_complete;
  
  	memcpy(req->in_req->buf, buffer, strlen(buffer));
  	req->in_req->length = strlen(buffer);
  
  	ret = usb_ep_queue(fastboot_func->in_ep, req->in_req, 0);
  	if (ret) {
  		printf("Error %d on queue
  ", ret);
  		return -EINVAL;
  	}
  
  	ret = 0;
  	return ret;
  }
593cbd93f   Steve Rae   usb/gadget: fastb...
3048
  static int fastboot_tx_write(const char *buffer, unsigned int buffer_size)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
3049
3050
3051
3052
3053
3054
  {
  	struct usb_request *in_req = fastboot_func->in_req;
  	int ret;
  
  	memcpy(in_req->buf, buffer, buffer_size);
  	in_req->length = buffer_size;
bc9071c9f   Paul Kocialkowski   usb: gadget: fast...
3055

2c840c82b   Ye Li   MLK-18591-3 andro...
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
  	usb_ep_dequeue(fastboot_func->in_ep, in_req);
  
  	ret = usb_ep_queue(fastboot_func->in_ep, in_req, 0);
  	if (ret)
  		printf("Error %d on queue
  ", ret);
  	return 0;
  }
  
  static int fastboot_tx_write_str(const char *buffer)
  {
  	return fastboot_tx_write(buffer, strlen(buffer));
  }
  
  static void compl_do_reset(struct usb_ep *ep, struct usb_request *req)
  {
  	do_reset(NULL, 0, 0, NULL);
  }
  
  int __weak fb_set_reboot_flag(void)
  {
  	return -ENOSYS;
  }
  
  static void cb_reboot(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  	if (!strcmp_l1("reboot-bootloader", cmd)) {
  		if (fb_set_reboot_flag()) {
  			fastboot_tx_write_str("FAILCannot set reboot flag");
  			return;
  		}
  	}
  	fastboot_func->in_req->complete = compl_do_reset;
  	fastboot_tx_write_str("OKAY");
  }
  
  static int strcmp_l1(const char *s1, const char *s2)
  {
  	if (!s1 || !s2)
  		return -1;
  	return strncmp(s1, s2, strlen(s1));
  }
  
  #ifdef CONFIG_FSL_FASTBOOT
  static bool is_slotvar(char *cmd)
  {
  	assert(cmd != NULL);
  	if (!strcmp_l1("has-slot:", cmd) ||
  		!strcmp_l1("slot-successful:", cmd) ||
  		!strcmp_l1("slot-count", cmd) ||
  		!strcmp_l1("slot-suffixes", cmd) ||
  		!strcmp_l1("current-slot", cmd) ||
  		!strcmp_l1("slot-unbootable:", cmd) ||
  		!strcmp_l1("slot-retry-count:", cmd))
  			return true;
  	return false;
  }
  
  static char *get_serial(void)
  {
  #ifdef CONFIG_SERIAL_TAG
  	struct tag_serialnr serialnr;
  	static char serial[32];
  	get_board_serial(&serialnr);
  	sprintf(serial, "%08x%08x", serialnr.high,      serialnr.low);
  	return serial;
  #else
  	return NULL;
  #endif
  }
  
  #if !defined(PRODUCT_NAME)
  #define PRODUCT_NAME "NXP i.MX"
  #endif
  
  #if !defined(VARIANT_NAME)
  #define VARIANT_NAME "NXP i.MX"
  #endif
  
  static int get_block_size(void) {
a612cab38   Richard Zhu   MLK-19479-2 fastb...
3137
  	int dev_no = 0;
2c840c82b   Ye Li   MLK-18591-3 andro...
3138
  	struct blk_desc *dev_desc;
a612cab38   Richard Zhu   MLK-19479-2 fastb...
3139
3140
3141
  
  	dev_no = fastboot_devinfo.dev_id;
  	dev_desc = blk_get_dev(fastboot_devinfo.type == DEV_SATA ? "sata" : "mmc", dev_no);
2c840c82b   Ye Li   MLK-18591-3 andro...
3142
  	if (NULL == dev_desc) {
a612cab38   Richard Zhu   MLK-19479-2 fastb...
3143
3144
3145
3146
  		printf("** Block device %s %d not supported
  ",
  		       fastboot_devinfo.type == DEV_SATA ? "sata" : "mmc",
  		       dev_no);
2c840c82b   Ye Li   MLK-18591-3 andro...
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
  		return 0;
  	}
  	return dev_desc->blksz;
  }
  
  static bool is_exist(char (*partition_base_name)[16], char *buffer, int count)
  {
  	int n;
  
  	for (n = 0; n < count; n++) {
  		if (!strcmp(partition_base_name[n],buffer))
  			return true;
  	}
  	return false;
  }
  /*get partition base name from gpt without "_a/_b"*/
  static int get_partition_base_name(char (*partition_base_name)[16])
  {
  	int n = 0;
  	int count = 0;
  	char *ptr1, *ptr2;
7bc5136e5   Ye Li   MLK-20240-6 fastb...
3168
  	char buffer[20];
2c840c82b   Ye Li   MLK-18591-3 andro...
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
  
  	for (n = 0; n < g_pcount; n++) {
  		strcpy(buffer,g_ptable[n].name);
  		ptr1 = strstr(buffer, "_a");
  		ptr2 = strstr(buffer, "_b");
  		if (ptr1 != NULL) {
  			*ptr1 = '\0';
  			if (!is_exist(partition_base_name,buffer,count)) {
  				strcpy(partition_base_name[count++],buffer);
  			}
  		} else if (ptr2 != NULL) {
  			*ptr2 = '\0';
  			if (!is_exist(partition_base_name,buffer,count)) {
  				strcpy(partition_base_name[count++],buffer);
  			}
  		} else {
  			strcpy(partition_base_name[count++],buffer);
  		}
  	}
  	return count;
  }
  
  static bool is_slot(void)
  {
  	char slot_suffix[2][5] = {"_a","_b"};
  	int n;
  
  	for (n = 0; n < g_pcount; n++) {
  		if (strstr(g_ptable[n].name, slot_suffix[0]) ||
  		strstr(g_ptable[n].name, slot_suffix[1]))
  			return true;
  	}
  	return false;
  }
979995530   Yu Shan   [iot] Support ata...
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
  #ifdef CONFIG_IMX_TRUSTY_OS
  static void uuid_hex2string(uint8_t *uuid, char* buf, uint32_t uuid_len, uint32_t uuid_strlen) {
  	uint32_t i;
  	if (!uuid || !buf)
  		return;
  	char *cp = buf;
  	char *buf_end = buf + uuid_strlen;
  	for (i = 0; i < uuid_len; i++) {
  		cp += snprintf(cp, buf_end - cp, "%02x", uuid[i]);
  	}
  }
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3215

23c5c1858   Luo Ji   [iot] Add fastboo...
3216
  #if defined(CONFIG_ANDROID_THINGS_SUPPORT) && defined(CONFIG_ARCH_IMX8M)
bfd330bce   Luo Ji   [iot] Support 1G ...
3217
  int get_imx8m_baseboard_id(void);
23c5c1858   Luo Ji   [iot] Add fastboo...
3218
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3219
3220
3221
  static int get_single_var(char *cmd, char *response)
  {
  	char *str = cmd;
b57739cac   Ji Luo   [iot] Support fas...
3222
  	int chars_left;
2c840c82b   Ye Li   MLK-18591-3 andro...
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
  	const char *s;
  	struct mmc *mmc;
  	int mmc_dev_no;
  	int blksz;
  
  	chars_left = FASTBOOT_RESPONSE_LEN - strlen(response) - 1;
  
  	if ((str = strstr(cmd, "partition-size:"))) {
  		str +=strlen("partition-size:");
  		struct fastboot_ptentry* fb_part;
  		fb_part = fastboot_flash_find_ptn(str);
  		if (!fb_part) {
  			strncat(response, "Wrong partition name.", chars_left);
c2763113a   Ji Luo   MA-12358 Only dum...
3236
  			fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
3237
3238
  			return -1;
  		} else {
4cfd7437a   Luo Ji   MA-11958 Fix user...
3239
  			snprintf(response + strlen(response), chars_left,
21a49ca83   Ji Luo   MA-13295 Fix user...
3240
3241
  				 "0x%llx",
  				 (uint64_t)fb_part->length * get_block_size());
2c840c82b   Ye Li   MLK-18591-3 andro...
3242
3243
3244
3245
3246
3247
3248
  		}
  	} else if ((str = strstr(cmd, "partition-type:"))) {
  		str +=strlen("partition-type:");
  		struct fastboot_ptentry* fb_part;
  		fb_part = fastboot_flash_find_ptn(str);
  		if (!fb_part) {
  			strncat(response, "Wrong partition name.", chars_left);
c2763113a   Ji Luo   MA-12358 Only dum...
3249
  			fastboot_flash_dump_ptn();
2c840c82b   Ye Li   MLK-18591-3 andro...
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
  			return -1;
  		} else {
  			strncat(response, fb_part->fstype, chars_left);
  		}
  	} else if (!strcmp_l1("version-baseband", cmd)) {
  		strncat(response, "N/A", chars_left);
  	} else if (!strcmp_l1("version-bootloader", cmd) ||
  		!strcmp_l1("bootloader-version", cmd)) {
  		strncat(response, U_BOOT_VERSION, chars_left);
  	} else if (!strcmp_l1("version", cmd)) {
  		strncat(response, FASTBOOT_VERSION, chars_left);
  	} else if (!strcmp_l1("battery-voltage", cmd)) {
  		strncat(response, "0mV", chars_left);
  	} else if (!strcmp_l1("battery-soc-ok", cmd)) {
  		strncat(response, "yes", chars_left);
  	} else if (!strcmp_l1("variant", cmd)) {
  		strncat(response, VARIANT_NAME, chars_left);
  	} else if (!strcmp_l1("off-mode-charge", cmd)) {
  		strncat(response, "1", chars_left);
  	} else if (!strcmp_l1("downloadsize", cmd) ||
  		!strcmp_l1("max-download-size", cmd)) {
  
  		snprintf(response + strlen(response), chars_left, "0x%x", CONFIG_FASTBOOT_BUF_SIZE);
  	} else if (!strcmp_l1("erase-block-size", cmd)) {
  		mmc_dev_no = mmc_get_env_dev();
  		mmc = find_mmc_device(mmc_dev_no);
  		blksz = get_block_size();
  		snprintf(response + strlen(response), chars_left, "0x%x",
  				(blksz * mmc->erase_grp_size));
  	} else if (!strcmp_l1("logical-block-size", cmd)) {
  		blksz = get_block_size();
  		snprintf(response + strlen(response), chars_left, "0x%x", blksz);
  	} else if (!strcmp_l1("serialno", cmd)) {
  		s = get_serial();
  		if (s)
  			strncat(response, s, chars_left);
  		else {
  			strncat(response, "FAILValue not set", chars_left);
  			return -1;
  		}
  	} else if (!strcmp_l1("product", cmd)) {
  		strncat(response, PRODUCT_NAME, chars_left);
  	}
979995530   Yu Shan   [iot] Support ata...
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
  #ifdef CONFIG_IMX_TRUSTY_OS
          else if(!strcmp_l1("at-attest-uuid", cmd)) {
  		char *uuid;
  		char uuid_str[ATAP_UUID_STR_SIZE];
  		if (trusty_atap_read_uuid_str(&uuid)) {
  			printf("ERROR read uuid failed!
  ");
  			strncat(response, "FAILCannot get uuid!", chars_left);
  			return -1;
  		} else {
  			uuid_hex2string((uint8_t*)uuid, uuid_str,ATAP_UUID_SIZE, ATAP_UUID_STR_SIZE);
  			strncat(response, uuid_str, chars_left);
  			trusty_free(uuid);
  		}
  	}
41ee143a2   Haoran.Wang   [iot] Support at-...
3308
3309
3310
  	else if(!strcmp_l1("at-attest-dh", cmd)) {
  		strncat(response, "1:P256,2:curve25519", chars_left);
  	}
979995530   Yu Shan   [iot] Support ata...
3311
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
  #ifdef CONFIG_FASTBOOT_LOCK
  	else if (!strcmp_l1("secure", cmd)) {
  		strncat(response, FASTBOOT_VAR_YES, chars_left);
  	} else if (!strcmp_l1("unlocked",cmd)){
  		int status = fastboot_get_lock_stat();
  		if (status == FASTBOOT_UNLOCK) {
  			strncat(response, FASTBOOT_VAR_YES, chars_left);
  		} else {
  			strncat(response, FASTBOOT_VAR_NO, chars_left);
  		}
  	}
  #else
  	else if (!strcmp_l1("secure", cmd)) {
  		strncat(response, FASTBOOT_VAR_NO, chars_left);
  	} else if (!strcmp_l1("unlocked",cmd)) {
  		strncat(response, FASTBOOT_VAR_NO, chars_left);
  	}
  #endif
  	else if (is_slotvar(cmd)) {
  #ifdef CONFIG_AVB_SUPPORT
  		if (get_slotvar_avb(&fsl_avb_ab_ops, cmd,
  				response + strlen(response), chars_left + 1) < 0)
  			return -1;
  #else
  		strncat(response, FASTBOOT_VAR_NO, chars_left);
  #endif
  	}
23c5c1858   Luo Ji   [iot] Add fastboo...
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
  #if defined(CONFIG_ANDROID_THINGS_SUPPORT) && defined(CONFIG_ARCH_IMX8M)
  	else if (!strcmp_l1("baseboard_id", cmd)) {
  		int baseboard_id;
  
  		baseboard_id = get_imx8m_baseboard_id();
  		if (baseboard_id < 0) {
  			printf("Get baseboard id failed!
  ");
  			strncat(response, "Get baseboard id failed!", chars_left);
  			return -1;
  		} else
  			snprintf(response + strlen(response), chars_left, "0x%x", baseboard_id);
  	}
  #endif
b57739cac   Ji Luo   [iot] Support fas...
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
  #ifdef CONFIG_AVB_ATX
  	else if (!strcmp_l1("bootloader-locked", cmd)) {
  
  		/* Below is basically copied from is_hab_enabled() */
  		struct imx_sec_config_fuse_t *fuse =
  			(struct imx_sec_config_fuse_t *)&imx_sec_config_fuse;
  		uint32_t reg;
  		int ret;
  
  		/* Read the secure boot status from fuse. */
  		ret = fuse_read(fuse->bank, fuse->word, &reg);
  		if (ret) {
  			printf("
  Secure boot fuse read error!
  ");
  			strncat(response, "Secure boot fuse read error!", chars_left);
  			return -1;
  		}
  		/* Check if the secure boot bit is enabled */
  		if ((reg & 0x2000000) == 0x2000000)
  			strncat(response, "1", chars_left);
  		else
  			strncat(response, "0", chars_left);
  	} else if (!strcmp_l1("bootloader-min-versions", cmd)) {
  #ifndef CONFIG_ARM64
  		/* We don't support bootloader rbindex protection for
  		 * ARM32(like imx7d) and the format is: "bootloader,tee". */
  		strncat(response, "-1,-1", chars_left);
  
  #elif defined(CONFIG_DUAL_BOOTLOADER)
  		/* Rbindex protection for bootloader is supported only when the
  		 * 'dual bootloader' feature is enabled. U-boot will get the rbindx
  		 * from RAM which is passed by spl because we can only get the rbindex
  		 * at spl stage. The format in this case is: "spl,atf,tee,u-boot".
  		 */
  		struct bl_rbindex_package *bl_rbindex;
  		uint32_t rbindex;
  
  		bl_rbindex = (struct bl_rbindex_package *)BL_RBINDEX_LOAD_ADDR;
  		if (!strncmp(bl_rbindex->magic, BL_RBINDEX_MAGIC,
  				BL_RBINDEX_MAGIC_LEN)) {
  			rbindex = bl_rbindex->rbindex;
  			snprintf(response + strlen(response), chars_left,
  					"-1,%d,%d,%d",rbindex, rbindex, rbindex);
  		} else {
  			printf("Error bootloader rbindex magic!
  ");
  			strncat(response, "Get bootloader rbindex fail!", chars_left);
  			return -1;
  		}
  #else
  		/* Return -1 for all partition if 'dual bootloader' feature
  		 * is not enabled */
  		strncat(response, "-1,-1,-1,-1", chars_left);
  #endif
  	} else if (!strcmp_l1("avb-perm-attr-set", cmd)) {
  		if (perm_attr_are_fused())
  			strncat(response, "1", chars_left);
  		else
  			strncat(response, "0", chars_left);
  	} else if (!strcmp_l1("avb-locked", cmd)) {
  		FbLockState status;
  
  		status = fastboot_get_lock_stat();
  		if (status == FASTBOOT_LOCK)
  			strncat(response, "1", chars_left);
  		else if (status == FASTBOOT_UNLOCK)
  			strncat(response, "0", chars_left);
  		else {
  			printf("Get lock state error!
  ");
  			strncat(response, "Get lock state failed!", chars_left);
  			return -1;
  		}
  	} else if (!strcmp_l1("avb-unlock-disabled", cmd)) {
  		if (at_unlock_vboot_is_disabled())
  			strncat(response, "1", chars_left);
  		else
  			strncat(response, "0", chars_left);
  	} else if (!strcmp_l1("avb-min-versions", cmd)) {
  		int i = 0;
  		/* rbindex location/value can be very large
  		 * number so we reserve enough space here.
  		 */
  		char buffer[35];
  		uint32_t rbindex_location[AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS + 2];
  		uint32_t location;
  		uint64_t rbindex;
  
  		memset(buffer, '\0', sizeof(buffer));
  
  		/* Set rbindex locations. */
  		for (i = 0; i < AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS; i++)
  			rbindex_location[i] = i;
  
  		/* Set Android Things key version rbindex locations */
  		rbindex_location[AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS]
  						= AVB_ATX_PIK_VERSION_LOCATION;
  		rbindex_location[AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS + 1]
  						= AVB_ATX_PSK_VERSION_LOCATION;
  
  		/* Read rollback index and set the reponse*/
  		for (i = 0; i < AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS + 2; i++) {
  			location = rbindex_location[i];
  			if (fsl_avb_ops.read_rollback_index(&fsl_avb_ops,
  								location, &rbindex)
  								!= AVB_IO_RESULT_OK) {
  				printf("Read rollback index error!
  ");
  				snprintf(response, sizeof(response),
  					"INFOread rollback index error when get avb-min-versions");
  				return -1;
  			}
  			/* Generate the "location:value" pair */
  			snprintf(buffer, sizeof(buffer), "%d:%lld", location, rbindex);
  			if (i != AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS + 1)
  				strncat(buffer, ",", strlen(","));
  
  			if ((chars_left - (int)strlen(buffer)) >= 0) {
  				strncat(response, buffer, strlen(buffer));
  				chars_left -= strlen(buffer);
  			} else {
  				strncat(response, buffer, chars_left);
  				/* reponse buffer is full, send it first */
  				fastboot_tx_write_more(response);
  				/* reset the reponse buffer for next round */
  				memset(response, '\0', sizeof(response));
  				strncpy(response, "INFO", 5);
  				/* Copy left strings from 'buffer' to 'response' */
  				strncat(response, buffer + chars_left, strlen(buffer));
  				chars_left = FASTBOOT_RESPONSE_LEN -
  						strlen(response) - 1;
  			}
  		}
  
  	}
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3490
3491
3492
3493
3494
3495
3496
3497
  	else {
  		char envstr[32];
  
  		snprintf(envstr, sizeof(envstr) - 1, "fastboot.%s", cmd);
  		s = env_get(envstr);
  		if (s) {
  			strncat(response, s, chars_left);
  		} else {
fd9eec336   Yu Shan   [iot] Support fas...
3498
  			snprintf(response, chars_left, "FAILunknown variable:%s",cmd);
2c840c82b   Ye Li   MLK-18591-3 andro...
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
  			printf("WARNING: unknown variable: %s
  ", cmd);
  			return -1;
  		}
  	}
  	return 0;
  }
  
  static void cb_getvar(struct usb_ep *ep, struct usb_request *req)
  {
  	int n = 0;
  	int status = 0;
  	int count = 0;
  	char *cmd = req->buf;
b57739cac   Ji Luo   [iot] Support fas...
3513
  	char var_name[FASTBOOT_RESPONSE_LEN];
2c840c82b   Ye Li   MLK-18591-3 andro...
3514
3515
  	char partition_base_name[MAX_PTN][16];
  	char slot_suffix[2][5] = {"a","b"};
b57739cac   Ji Luo   [iot] Support fas...
3516
  	char response[FASTBOOT_RESPONSE_LEN];
2c840c82b   Ye Li   MLK-18591-3 andro...
3517
3518
3519
3520
3521
3522
3523
3524
3525
  
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing variable");
  		fastboot_tx_write_str("FAILmissing var");
  		return;
  	}
  
  	if (!strcmp_l1("all", cmd)) {
b57739cac   Ji Luo   [iot] Support fas...
3526
  		memset(response, '\0', FASTBOOT_RESPONSE_LEN);
2c840c82b   Ye Li   MLK-18591-3 andro...
3527
3528
3529
3530
3531
3532
3533
3534
  
  
  		/* get common variables */
  		for (n = 0; n < FASTBOOT_COMMON_VAR_NUM; n++) {
  			snprintf(response, sizeof(response), "INFO%s:", fastboot_common_var[n]);
  			get_single_var(fastboot_common_var[n], response);
  			fastboot_tx_write_more(response);
  		}
b57739cac   Ji Luo   [iot] Support fas...
3535
3536
3537
3538
3539
3540
3541
3542
  		/* get at-vboot-state variables */
  #ifdef CONFIG_AVB_ATX
  		for (n = 0; n < AT_VBOOT_STATE_VAR_NUM; n++) {
  			snprintf(response, sizeof(response), "INFO%s:", fastboot_at_vboot_state_var[n]);
  			get_single_var(fastboot_at_vboot_state_var[n], response);
  			fastboot_tx_write_more(response);
  		}
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
  		/* get partition type */
  		for (n = 0; n < g_pcount; n++) {
  			snprintf(response, sizeof(response), "INFOpartition-type:%s:", g_ptable[n].name);
  			snprintf(var_name, sizeof(var_name), "partition-type:%s", g_ptable[n].name);
  			get_single_var(var_name, response);
  			fastboot_tx_write_more(response);
  		}
  		/* get partition size */
  		for (n = 0; n < g_pcount; n++) {
  			snprintf(response, sizeof(response), "INFOpartition-size:%s:", g_ptable[n].name);
  			snprintf(var_name, sizeof(var_name), "partition-size:%s", g_ptable[n].name);
  			get_single_var(var_name,response);
  			fastboot_tx_write_more(response);
  		}
  		/* slot related variables */
  		if (is_slot()) {
  			/* get has-slot variables */
  			count = get_partition_base_name(partition_base_name);
  			for (n = 0; n < count; n++) {
  				snprintf(response, sizeof(response), "INFOhas-slot:%s:", partition_base_name[n]);
  				snprintf(var_name, sizeof(var_name), "has-slot:%s", partition_base_name[n]);
  				get_single_var(var_name,response);
  				fastboot_tx_write_more(response);
  			}
  			/* get current slot */
  			strncpy(response, "INFOcurrent-slot:", sizeof(response));
  			get_single_var("current-slot", response);
  			fastboot_tx_write_more(response);
  			/* get slot count */
  			strncpy(response, "INFOslot-count:", sizeof(response));
  			get_single_var("slot-count", response);
  			fastboot_tx_write_more(response);
  			/* get slot-successful variable */
  			for (n = 0; n < 2; n++) {
  				snprintf(response, sizeof(response), "INFOslot-successful:%s:", slot_suffix[n]);
  				snprintf(var_name, sizeof(var_name), "slot-successful:%s", slot_suffix[n]);
  				get_single_var(var_name, response);
  				fastboot_tx_write_more(response);
  			}
  			/*get slot-unbootable variable*/
  			for (n = 0; n < 2; n++) {
  				snprintf(response, sizeof(response), "INFOslot-unbootable:%s:", slot_suffix[n]);
  				snprintf(var_name, sizeof(var_name), "slot-unbootable:%s", slot_suffix[n]);
  				get_single_var(var_name, response);
  				fastboot_tx_write_more(response);
  			}
  			/*get slot-retry-count variable*/
  			for (n = 0; n < 2; n++) {
  				snprintf(response, sizeof(response), "INFOslot-retry-count:%s:", slot_suffix[n]);
  				snprintf(var_name, sizeof(var_name), "slot-retry-count:%s", slot_suffix[n]);
  				get_single_var(var_name, response);
  				fastboot_tx_write_more(response);
  			}
  		}
  
  		strncpy(response, "OKAYDone!", 10);
  		fastboot_tx_write_more(response);
  
  		return;
b57739cac   Ji Luo   [iot] Support fas...
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
  	}
  #ifdef CONFIG_AVB_ATX
  	else if (!strcmp_l1("at-vboot-state", cmd)) {
  			/* get at-vboot-state variables */
  		for (n = 0; n < AT_VBOOT_STATE_VAR_NUM; n++) {
  			snprintf(response, sizeof(response), "INFO%s:", fastboot_at_vboot_state_var[n]);
  			get_single_var(fastboot_at_vboot_state_var[n], response);
  			fastboot_tx_write_more(response);
  		}
  
  		strncpy(response, "OKAY", 5);
  		fastboot_tx_write_more(response);
  
  		return;
  	} else if ((!strcmp_l1("bootloader-locked", cmd)) ||
  			(!strcmp_l1("bootloader-min-versions", cmd)) ||
  			(!strcmp_l1("avb-perm-attr-set", cmd)) ||
  			(!strcmp_l1("avb-locked", cmd)) ||
  			(!strcmp_l1("avb-unlock-disabled", cmd)) ||
  			(!strcmp_l1("avb-min-versions", cmd))) {
  
  		printf("Can't get this variable alone, get 'at-vboot-state' instead!
  ");
  		snprintf(response, sizeof(response),
  			"FAILCan't get this variable alone, get 'at-vboot-state' instead.");
  		fastboot_tx_write_str(response);
  		return;
  	}
  #endif
  	else {
2c840c82b   Ye Li   MLK-18591-3 andro...
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
  
  		strncpy(response, "OKAY", 5);
  		status = get_single_var(cmd, response);
  		if (status != 0) {
  			strncpy(response, "FAIL", 5);
  		}
  		fastboot_tx_write_str(response);
  		return;
  	}
  }
  
  #ifdef CONFIG_FASTBOOT_LOCK
  
  int do_lock_status(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) {
  	FbLockState status = fastboot_get_lock_stat();
  	if (status != FASTBOOT_LOCK_ERROR) {
  		if (status == FASTBOOT_LOCK)
  			printf("fastboot lock status: locked.
  ");
  		else
  			printf("fastboot lock status: unlocked.
  ");
  	} else
  		printf("fastboot lock status error!
  ");
  
  	display_lock(status, -1);
  
  	return 0;
  
  }
  
  U_BOOT_CMD(
  	lock_status, 2, 1, do_lock_status,
  	"lock_status",
  	"lock_status");
8654c6f81   Ji Luo   MA-12214: Wipe al...
3668
3669
3670
3671
3672
3673
3674
3675
3676
  static void wipe_all_userdata(void)
  {
  	char response[FASTBOOT_RESPONSE_LEN];
  
  	/* Erase all user data */
  	printf("Start userdata wipe process....
  ");
  	/* Erase /data partition */
  	fastboot_wipe_data_partition();
1d1999625   faqiang.zhu   MA-13696 Android-...
3677
  #if defined (CONFIG_ANDROID_SUPPORT) || defined (CONFIG_ANDROID_AUTO_SUPPORT)
8654c6f81   Ji Luo   MA-12214: Wipe al...
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
  	/* Erase the misc partition. */
  	process_erase_mmc(FASTBOOT_PARTITION_MISC, response);
  #endif
  
  #ifndef CONFIG_ANDROID_AB_SUPPORT
  	/* Erase the cache partition for legacy imx6/7 */
  	process_erase_mmc(FASTBOOT_PARTITION_CACHE, response);
  #endif
  	/* The unlock permissive flag is set by user and should be wiped here. */
  	set_fastboot_lock_disable();
cf2a6c19c   Haoran.Wang   MA-12699 Refine l...
3688
  #if defined(AVB_RPMB) && !defined(CONFIG_IMX_TRUSTY_OS)
8654c6f81   Ji Luo   MA-12214: Wipe al...
3689
3690
3691
3692
3693
3694
3695
3696
3697
  	printf("Start stored_rollback_index wipe process....
  ");
  	rbkidx_erase();
  	printf("Wipe stored_rollback_index completed.
  ");
  #endif
  	printf("Wipe userdata completed.
  ");
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
3698
3699
3700
  static FbLockState do_fastboot_unlock(bool force)
  {
  	int status;
8654c6f81   Ji Luo   MA-12214: Wipe al...
3701

f322e8a2c   faqiang.zhu   MA-13603 change u...
3702
3703
3704
3705
3706
  	if (fastboot_get_lock_stat() == FASTBOOT_UNLOCK) {
  		printf("The device is already unlocked
  ");
  		return FASTBOOT_UNLOCK;
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
3707
3708
3709
  	if ((fastboot_lock_enable() == FASTBOOT_UL_ENABLE) || force) {
  		printf("It is able to unlock device. %d
  ",fastboot_lock_enable());
2c840c82b   Ye Li   MLK-18591-3 andro...
3710
3711
3712
  		status = fastboot_set_lock_stat(FASTBOOT_UNLOCK);
  		if (status < 0)
  			return FASTBOOT_LOCK_ERROR;
8654c6f81   Ji Luo   MA-12214: Wipe al...
3713
  		wipe_all_userdata();
2c840c82b   Ye Li   MLK-18591-3 andro...
3714

2c840c82b   Ye Li   MLK-18591-3 andro...
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
  	} else {
  		printf("It is not able to unlock device.");
  		return FASTBOOT_LOCK_ERROR;
  	}
  
  	return FASTBOOT_UNLOCK;
  }
  
  static FbLockState do_fastboot_lock(void)
  {
  	int status;
8654c6f81   Ji Luo   MA-12214: Wipe al...
3726

2c840c82b   Ye Li   MLK-18591-3 andro...
3727
3728
3729
3730
3731
3732
3733
3734
  	if (fastboot_get_lock_stat() == FASTBOOT_LOCK) {
  		printf("The device is already locked
  ");
  		return FASTBOOT_LOCK;
  	}
  	status = fastboot_set_lock_stat(FASTBOOT_LOCK);
  	if (status < 0)
  		return FASTBOOT_LOCK_ERROR;
8654c6f81   Ji Luo   MA-12214: Wipe al...
3735
  	wipe_all_userdata();
2c840c82b   Ye Li   MLK-18591-3 andro...
3736
3737
3738
  
  	return FASTBOOT_LOCK;
  }
fd9eec336   Yu Shan   [iot] Support fas...
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
  static bool endswith(char* s, char* subs) {
  	if (!s || !subs)
  		return false;
  	uint32_t len = strlen(s);
  	uint32_t sublen = strlen(subs);
  	if (len < sublen) {
  		return false;
  	}
  	if (strncmp(s + len - sublen, subs, sublen)) {
  		return false;
  	}
  	return true;
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
3752
3753
3754
3755
  static void cb_flashing(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  	char response[FASTBOOT_RESPONSE_LEN];
2c840c82b   Ye Li   MLK-18591-3 andro...
3756
3757
  	FbLockState status;
  	FbLockEnableResult result;
fd9eec336   Yu Shan   [iot] Support fas...
3758
  	if (endswith(cmd, "lock_critical")) {
2c840c82b   Ye Li   MLK-18591-3 andro...
3759
  		strcpy(response, "OKAY");
fd9eec336   Yu Shan   [iot] Support fas...
3760
3761
3762
3763
3764
3765
3766
  	}
  #ifdef CONFIG_AVB_ATX
  	else if (endswith(cmd, FASTBOOT_AVB_AT_PERM_ATTR)) {
  		if (avb_atx_fuse_perm_attr(interface.transfer_buffer, download_bytes))
  			strcpy(response, "FAILInternal error!");
  		else
  			strcpy(response, "OKAY");
d4a0dbd9a   Ji Luo   [iot] Support aut...
3767
3768
3769
3770
3771
3772
3773
  	} else if (endswith(cmd, FASTBOOT_AT_GET_UNLOCK_CHALLENGE)) {
  		if (avb_atx_get_unlock_challenge(fsl_avb_ops.atx_ops,
  						interface.transfer_buffer, &download_bytes))
  			strcpy(response, "FAILInternal error!");
  		else
  			strcpy(response, "OKAY");
  	} else if (endswith(cmd, FASTBOOT_AT_UNLOCK_VBOOT)) {
aebefa804   Ji Luo   [iot] Support com...
3774
3775
3776
3777
3778
  		if (at_unlock_vboot_is_disabled()) {
  			printf("unlock vboot already disabled, can't unlock the device!
  ");
  			strcpy(response, "FAILunlock vboot already disabled!.");
  		} else {
d4a0dbd9a   Ji Luo   [iot] Support aut...
3779
  #ifdef CONFIG_AT_AUTHENTICATE_UNLOCK
aebefa804   Ji Luo   [iot] Support com...
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
  			if (avb_atx_verify_unlock_credential(fsl_avb_ops.atx_ops,
  								interface.transfer_buffer))
  				strcpy(response, "FAILIncorrect unlock credential!");
  			else {
  #endif
  				status = do_fastboot_unlock(true);
  				if (status != FASTBOOT_LOCK_ERROR)
  					strcpy(response, "OKAY");
  				else
  					strcpy(response, "FAILunlock device failed.");
d4a0dbd9a   Ji Luo   [iot] Support aut...
3790
  #ifdef CONFIG_AT_AUTHENTICATE_UNLOCK
aebefa804   Ji Luo   [iot] Support com...
3791
  			}
d4a0dbd9a   Ji Luo   [iot] Support aut...
3792
  #endif
aebefa804   Ji Luo   [iot] Support com...
3793
  		}
c14e9d4e2   Ji Luo   [iot] Support loc...
3794
3795
3796
3797
3798
3799
3800
3801
3802
  	} else if (endswith(cmd, FASTBOOT_AT_LOCK_VBOOT)) {
  		if (perm_attr_are_fused()) {
  			status = do_fastboot_lock();
  			if (status != FASTBOOT_LOCK_ERROR)
  				strcpy(response, "OKAY");
  			else
  				strcpy(response, "FAILlock device failed.");
  		} else
  			strcpy(response, "FAILpermanent attributes not fused!");
aebefa804   Ji Luo   [iot] Support com...
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
  	} else if (endswith(cmd, FASTBOOT_AT_DISABLE_UNLOCK_VBOOT)) {
  		/* This command can only be called after 'oem at-lock-vboot' */
  		status = fastboot_get_lock_stat();
  		if (status == FASTBOOT_LOCK) {
  			if (at_unlock_vboot_is_disabled()) {
  				printf("unlock vboot already disabled!
  ");
  				strcpy(response, "OKAY");
  			}
  			else {
  				if (!at_disable_vboot_unlock())
  					strcpy(response, "OKAY");
  				else
  					strcpy(response, "FAILdisable unlock vboot fail!");
  			}
  		} else
  			strcpy(response, "FAILplease lock the device first!");
fd9eec336   Yu Shan   [iot] Support fas...
3820
3821
3822
  	}
  #endif /* CONFIG_AVB_ATX */
  #ifdef CONFIG_ANDROID_THINGS_SUPPORT
a1f5c4f9f   Yu Shan   [iot] Minor forma...
3823
  	else if (endswith(cmd, FASTBOOT_BOOTLOADER_VBOOT_KEY)) {
2c840c82b   Ye Li   MLK-18591-3 andro...
3824
  		strcpy(response, "OKAY");
fd9eec336   Yu Shan   [iot] Support fas...
3825
3826
  	}
  #endif /* CONFIG_ANDROID_THINGS_SUPPORT */
979995530   Yu Shan   [iot] Support ata...
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
  #ifdef CONFIG_IMX_TRUSTY_OS
  	else if (endswith(cmd, FASTBOOT_GET_CA_REQ)) {
  		uint8_t *ca_output;
  		uint32_t ca_length, cp_length;
  		if (trusty_atap_get_ca_request(interface.transfer_buffer, download_bytes,
  						&(ca_output), &ca_length)) {
  			printf("ERROR get_ca_request failed!
  ");
  			strcpy(response, "FAILInternal error!");
  		} else {
  			cp_length = min((uint32_t)CONFIG_FASTBOOT_BUF_SIZE, ca_length);
  			memcpy(interface.transfer_buffer, ca_output, cp_length);
  			download_bytes = ca_length;
  			strcpy(response, "OKAY");
  		}
  
  	}
  	else if (endswith(cmd, FASTBOOT_SET_CA_RESP)) {
  		if (trusty_atap_set_ca_response(interface.transfer_buffer,download_bytes)) {
  			printf("ERROR set_ca_response failed!
  ");
  			strcpy(response, "FAILInternal error!");
  		} else
  			strcpy(response, "OKAY");
  	}
bcb82557f   Ji Luo   MA-13759-1 imx8mm...
3852
  #ifndef CONFIG_AVB_ATX
557981f3a   Ji Luo   MA-13048 [AUTO] S...
3853
3854
3855
3856
3857
3858
3859
  	else if (endswith(cmd, FASTBOOT_SET_RPMB_KEY)) {
  		if (fastboot_set_rpmb_key(interface.transfer_buffer, download_bytes)) {
  			printf("ERROR set rpmb key failed!
  ");
  			strcpy(response, "FAILset rpmb key failed!");
  		} else
  			strcpy(response, "OKAY");
7ade5b407   Ji Luo   MA-13832 [Trusty]...
3860
3861
3862
3863
3864
3865
3866
  	} else if (endswith(cmd, FASTBOOT_SET_RPMB_RANDOM_KEY)) {
  		if (fastboot_set_rpmb_random_key()) {
  			printf("ERROR set rpmb random key failed!
  ");
  			strcpy(response, "FAILset rpmb random key failed!");
  		} else
  			strcpy(response, "OKAY");
0e8b4af40   Ji Luo   MA-13629 [Trusty]...
3867
3868
3869
3870
3871
3872
  	} else if (endswith(cmd, FASTBOOT_SET_VBMETA_PUBLIC_KEY)) {
  		if (avb_set_public_key(interface.transfer_buffer,
  					download_bytes))
  			strcpy(response, "FAILcan't set public key!");
  		else
  			strcpy(response, "OKAY");
557981f3a   Ji Luo   MA-13048 [AUTO] S...
3873
  	}
bcb82557f   Ji Luo   MA-13759-1 imx8mm...
3874
  #endif /* !CONFIG_AVB_ATX */
979995530   Yu Shan   [iot] Support ata...
3875
  #endif /* CONFIG_IMX_TRUSTY_OS */
fd9eec336   Yu Shan   [iot] Support fas...
3876
  	else if (endswith(cmd, "unlock_critical")) {
2c840c82b   Ye Li   MLK-18591-3 andro...
3877
  		strcpy(response, "OKAY");
fd9eec336   Yu Shan   [iot] Support fas...
3878
  	} else if (endswith(cmd, "unlock")) {
2c840c82b   Ye Li   MLK-18591-3 andro...
3879
3880
  		printf("flashing unlock.
  ");
d4a0dbd9a   Ji Luo   [iot] Support aut...
3881
3882
3883
3884
3885
3886
  #ifdef CONFIG_AVB_ATX
  		/* We should do nothing here For Android Things which
  		 * enables the authenticated unlock feature.
  		 */
  		strcpy(response, "OKAY");
  #else
2c840c82b   Ye Li   MLK-18591-3 andro...
3887
3888
3889
3890
  		status = do_fastboot_unlock(false);
  		if (status != FASTBOOT_LOCK_ERROR)
  			strcpy(response, "OKAY");
  		else
fd9eec336   Yu Shan   [iot] Support fas...
3891
  			strcpy(response, "FAILunlock device failed.");
d4a0dbd9a   Ji Luo   [iot] Support aut...
3892
  #endif
fd9eec336   Yu Shan   [iot] Support fas...
3893
  	} else if (endswith(cmd, "lock")) {
c14e9d4e2   Ji Luo   [iot] Support loc...
3894
3895
3896
3897
3898
3899
  #ifdef CONFIG_AVB_ATX
  		/* We should do nothing here For Android Things which
  		 * enables the at-lock-vboot feature.
  		 */
  		strcpy(response, "OKAY");
  #else
2c840c82b   Ye Li   MLK-18591-3 andro...
3900
3901
3902
3903
3904
3905
  		printf("flashing lock.
  ");
  		status = do_fastboot_lock();
  		if (status != FASTBOOT_LOCK_ERROR)
  			strcpy(response, "OKAY");
  		else
fd9eec336   Yu Shan   [iot] Support fas...
3906
  			strcpy(response, "FAILlock device failed.");
c14e9d4e2   Ji Luo   [iot] Support loc...
3907
  #endif
fd9eec336   Yu Shan   [iot] Support fas...
3908
  	} else if (endswith(cmd, "get_unlock_ability")) {
2c840c82b   Ye Li   MLK-18591-3 andro...
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
  		result = fastboot_lock_enable();
  		if (result == FASTBOOT_UL_ENABLE) {
  			fastboot_tx_write_more("INFO1");
  			strcpy(response, "OKAY");
  		} else if (result == FASTBOOT_UL_DISABLE) {
  			fastboot_tx_write_more("INFO0");
  			strcpy(response, "OKAY");
  		} else {
  			printf("flashing get_unlock_ability fail!
  ");
fd9eec336   Yu Shan   [iot] Support fas...
3919
  			strcpy(response, "FAILget unlock ability failed.");
2c840c82b   Ye Li   MLK-18591-3 andro...
3920
3921
3922
3923
  		}
  	} else {
  		printf("Unknown flashing command:%s
  ", cmd);
fd9eec336   Yu Shan   [iot] Support fas...
3924
  		strcpy(response, "FAILcommand not defined");
2c840c82b   Ye Li   MLK-18591-3 andro...
3925
3926
3927
  	}
  	fastboot_tx_write_more(response);
  }
fd9eec336   Yu Shan   [iot] Support fas...
3928
3929
3930
3931
  #endif /* CONFIG_FASTBOOT_LOCK */
  
  #ifdef CONFIG_FSL_FASTBOOT
  #ifdef CONFIG_FASTBOOT_LOCK
2c840c82b   Ye Li   MLK-18591-3 andro...
3932
3933
3934
3935
  static int partition_table_valid(void)
  {
  	int status, mmc_no;
  	struct blk_desc *dev_desc;
502522c08   Haoran.Wang   [iot] Support ARM...
3936
  #if defined(CONFIG_IMX_TRUSTY_OS) && !defined(CONFIG_ARM64)
cce0bd746   Yu Shan   [iot] Check Trust...
3937
3938
3939
3940
  	//Prevent other partition accessing when no TOS flashed.
  	if (!tos_flashed)
  		return 0;
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3941
3942
3943
3944
3945
3946
3947
3948
3949
  	disk_partition_t info;
  	mmc_no = fastboot_devinfo.dev_id;
  	dev_desc = blk_get_dev("mmc", mmc_no);
  	if (dev_desc)
  		status = part_get_info(dev_desc, 1, &info);
  	else
  		status = -1;
  	return (status == 0);
  }
fd9eec336   Yu Shan   [iot] Support fas...
3950
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
  #endif /* CONFIG_FASTBOOT_LOCK */
  
  #ifdef CONFIG_FASTBOOT_FLASH
  static void cb_flash(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  	char response[FASTBOOT_RESPONSE_LEN];
  
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing partition name");
  		fastboot_tx_write_str("FAILmissing partition name");
  		return;
  	}
  
  	/* initialize the response buffer */
  	fb_response_str = response;
d4a0dbd9a   Ji Luo   [iot] Support aut...
3968
3969
  	/* Always enable image flash for Android Things. */
  #if defined(CONFIG_FASTBOOT_LOCK) && !defined(CONFIG_AVB_ATX)
4495a7a73   faqiang.zhu   MA-13715 Alway re...
3970
3971
  	int status;
  	status = fastboot_get_lock_stat();
bea54d4fb   faqiang.zhu   MA-12283-4 remove...
3972

4495a7a73   faqiang.zhu   MA-13715 Alway re...
3973
3974
3975
3976
3977
3978
  	if (status == FASTBOOT_LOCK) {
  		pr_err("device is LOCKed!
  ");
  		strcpy(response, "FAIL device is locked.");
  		fastboot_tx_write_str(response);
  		return;
2c840c82b   Ye Li   MLK-18591-3 andro...
3979

4495a7a73   faqiang.zhu   MA-13715 Alway re...
3980
3981
3982
3983
3984
3985
3986
  	} else if (status == FASTBOOT_LOCK_ERROR) {
  		pr_err("write lock status into device!
  ");
  		fastboot_set_lock_stat(FASTBOOT_LOCK);
  		strcpy(response, "FAILdevice is locked.");
  		fastboot_tx_write_str(response);
  		return;
2c840c82b   Ye Li   MLK-18591-3 andro...
3987
3988
3989
  	}
  #endif
  	fastboot_fail("no flash device defined");
2c840c82b   Ye Li   MLK-18591-3 andro...
3990
  	rx_process_flash(cmd);
d4a0dbd9a   Ji Luo   [iot] Support aut...
3991

2c840c82b   Ye Li   MLK-18591-3 andro...
3992
3993
  #ifdef CONFIG_FASTBOOT_LOCK
  	if (strncmp(cmd, "gpt", 3) == 0) {
fd9c8a502   Luo Ji   MA-12197 [Android...
3994
3995
  		int gpt_valid = 0;
  		gpt_valid = partition_table_valid();
2c840c82b   Ye Li   MLK-18591-3 andro...
3996
3997
3998
  		/* If gpt is valid, load partitons table into memory.
  		   So if the next command is "fastboot reboot bootloader",
  		   it can find the "misc" partition to r/w. */
fd9c8a502   Luo Ji   MA-12197 [Android...
3999
  		if(gpt_valid) {
2c840c82b   Ye Li   MLK-18591-3 andro...
4000
  			_fastboot_load_partitions();
fd9c8a502   Luo Ji   MA-12197 [Android...
4001
  			/* Unlock device if the gpt is valid */
2c840c82b   Ye Li   MLK-18591-3 andro...
4002
  			do_fastboot_unlock(true);
fd9c8a502   Luo Ji   MA-12197 [Android...
4003
  		}
2c840c82b   Ye Li   MLK-18591-3 andro...
4004
  	}
bc9071c9f   Paul Kocialkowski   usb: gadget: fast...
4005

2c840c82b   Ye Li   MLK-18591-3 andro...
4006
4007
  #endif
  	fastboot_tx_write_str(response);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4008
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
4009
  #endif
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4010

2c840c82b   Ye Li   MLK-18591-3 andro...
4011
4012
  #ifdef CONFIG_FASTBOOT_FLASH
  static void cb_erase(struct usb_ep *ep, struct usb_request *req)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4013
  {
2c840c82b   Ye Li   MLK-18591-3 andro...
4014
4015
  	char *cmd = req->buf;
  	char response[FASTBOOT_RESPONSE_LEN];
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4016

2c840c82b   Ye Li   MLK-18591-3 andro...
4017
4018
4019
4020
4021
4022
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing partition name");
  		fastboot_tx_write_str("FAILmissing partition name");
  		return;
  	}
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4023

2c840c82b   Ye Li   MLK-18591-3 andro...
4024
4025
  	/* initialize the response buffer */
  	fb_response_str = response;
d4a0dbd9a   Ji Luo   [iot] Support aut...
4026
  #if defined(CONFIG_FASTBOOT_LOCK) && !defined(CONFIG_AVB_ATX)
2c840c82b   Ye Li   MLK-18591-3 andro...
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
  	FbLockState status;
  	status = fastboot_get_lock_stat();
  	if (status == FASTBOOT_LOCK) {
  		pr_err("device is LOCKed!
  ");
  		strcpy(response, "FAIL device is locked.");
  		fastboot_tx_write_str(response);
  		return;
  	} else if (status == FASTBOOT_LOCK_ERROR) {
  		pr_err("write lock status into device!
  ");
  		fastboot_set_lock_stat(FASTBOOT_LOCK);
fd9eec336   Yu Shan   [iot] Support fas...
4039
  		strcpy(response, "FAILdevice is locked.");
2c840c82b   Ye Li   MLK-18591-3 andro...
4040
4041
4042
4043
4044
4045
  		fastboot_tx_write_str(response);
  		return;
  	}
  #endif
  	rx_process_erase(cmd, response);
  	fastboot_tx_write_str(response);
e2ec3e461   Alexey Firago   fastboot: add sup...
4046
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
4047
  #endif
e2ec3e461   Alexey Firago   fastboot: add sup...
4048

b053775c0   faqiang.zhu   MA-13785 remove t...
4049
  #ifndef CONFIG_NOT_UUU_BUILD
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
  static void cb_run_uboot_cmd(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing slot suffix
  ");
  		fastboot_tx_write_str("FAILmissing command");
  		return;
  	}
5423ef478   Frank Li   MLK-18406 fastboo...
4060
  	if(run_command(cmd, 0)) {
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4061
  		fastboot_tx_write_str("FAIL");
5423ef478   Frank Li   MLK-18406 fastboo...
4062
  	} else {
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4063
  		fastboot_tx_write_str("OKAY");
5423ef478   Frank Li   MLK-18406 fastboo...
4064
4065
4066
  		/* cmd may impact fastboot related environment*/
  		fastboot_setup();
  	}
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
  	return ;
  }
  
  static char g_a_cmd_buff[64];
  static void do_acmd_complete(struct usb_ep *ep, struct usb_request *req)
  {
  	/* When usb dequeue complete will be called
  	 * Meed status value before call run_command.
  	 * otherwise, host can't get last message.
  	 */
  	if(req->status == 0)
  		run_command(g_a_cmd_buff, 0);
  }
  
  static void cb_run_uboot_acmd(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
          strsep(&cmd, ":");
          if (!cmd) {
                  pr_err("missing slot suffix
  ");
                  fastboot_tx_write_str("FAILmissing command");
                  return;
          }
  	strcpy(g_a_cmd_buff, cmd);
  	fastboot_func->in_req->complete = do_acmd_complete;
  	fastboot_tx_write_str("OKAY");
  }
b053775c0   faqiang.zhu   MA-13785 remove t...
4095
  #endif
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4096

2c840c82b   Ye Li   MLK-18591-3 andro...
4097
4098
  #ifdef CONFIG_AVB_SUPPORT
  static void cb_set_active_avb(struct usb_ep *ep, struct usb_request *req)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4099
  {
2c840c82b   Ye Li   MLK-18591-3 andro...
4100
4101
  	AvbIOResult ret;
  	int slot = 0;
e2ec3e461   Alexey Firago   fastboot: add sup...
4102
  	char *cmd = req->buf;
2c840c82b   Ye Li   MLK-18591-3 andro...
4103
4104
4105
4106
4107
4108
4109
  
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing slot suffix
  ");
  		fastboot_tx_write_str("FAILmissing slot suffix");
  		return;
e2ec3e461   Alexey Firago   fastboot: add sup...
4110
  	}
2c840c82b   Ye Li   MLK-18591-3 andro...
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
  
  	slot = slotidx_from_suffix(cmd);
  
  	if (slot < 0) {
  		fastboot_tx_write_str("FAILerr slot suffix");
  		return;
  	}
  
  	ret = avb_ab_mark_slot_active(&fsl_avb_ab_ops, slot);
  	if (ret != AVB_IO_RESULT_OK)
  		fastboot_tx_write_str("avb IO error");
  	else
  		fastboot_tx_write_str("OKAY");
  
  	return;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4126
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
4127
  #endif /*CONFIG_AVB_SUPPORT*/
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4128

2c840c82b   Ye Li   MLK-18591-3 andro...
4129
  static void cb_reboot_bootloader(struct usb_ep *ep, struct usb_request *req)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4130
  {
2c840c82b   Ye Li   MLK-18591-3 andro...
4131
  	enable_fastboot_command();
4f39afdd5   Marty Faltesek   [iot] "fastboot r...
4132
4133
          fastboot_func->in_req->complete = compl_do_reset;
          fastboot_tx_write_str("OKAY");
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4134
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
4135
  #else /* CONFIG_FSL_FASTBOOT */
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4136
4137
4138
  static void cb_getvar(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
4139
  	char response[FASTBOOT_RESPONSE_LEN];
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4140
  	const char *s;
29425be49   Jeroen Hofstee   usb: fastboot: fi...
4141
  	size_t chars_left;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4142
4143
  
  	strcpy(response, "OKAY");
29425be49   Jeroen Hofstee   usb: fastboot: fi...
4144
  	chars_left = sizeof(response) - strlen(response) - 1;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4145
4146
  	strsep(&cmd, ":");
  	if (!cmd) {
9b643e312   Masahiro Yamada   treewide: replace...
4147
  		pr_err("missing variable");
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4148
4149
4150
4151
4152
  		fastboot_tx_write_str("FAILmissing var");
  		return;
  	}
  
  	if (!strcmp_l1("version", cmd)) {
29425be49   Jeroen Hofstee   usb: fastboot: fi...
4153
  		strncat(response, FASTBOOT_VERSION, chars_left);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4154
  	} else if (!strcmp_l1("bootloader-version", cmd)) {
29425be49   Jeroen Hofstee   usb: fastboot: fi...
4155
  		strncat(response, U_BOOT_VERSION, chars_left);
c674a6660   Eric Nelson   usb: gadget: fast...
4156
4157
  	} else if (!strcmp_l1("downloadsize", cmd) ||
  		!strcmp_l1("max-download-size", cmd)) {
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4158
  		char str_num[12];
a588d99ac   Paul Kocialkowski   usb: CONFIG_USB_F...
4159
  		sprintf(str_num, "0x%08x", CONFIG_FASTBOOT_BUF_SIZE);
29425be49   Jeroen Hofstee   usb: fastboot: fi...
4160
  		strncat(response, str_num, chars_left);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4161
  	} else if (!strcmp_l1("serialno", cmd)) {
00caae6d4   Simon Glass   env: Rename geten...
4162
  		s = env_get("serial#");
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4163
  		if (s)
29425be49   Jeroen Hofstee   usb: fastboot: fi...
4164
  			strncat(response, s, chars_left);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4165
4166
4167
  		else
  			strcpy(response, "FAILValue not set");
  	} else {
b1f2a17c7   nicolas.le.bayon@st.com   usb: gadget: avoi...
4168
  		char *envstr;
74322201d   Rob Herring   fastboot: allow r...
4169

b1f2a17c7   nicolas.le.bayon@st.com   usb: gadget: avoi...
4170
4171
4172
4173
4174
4175
4176
  		envstr = malloc(strlen("fastboot.") + strlen(cmd) + 1);
  		if (!envstr) {
  			fastboot_tx_write_str("FAILmalloc error");
  			return;
  		}
  
  		sprintf(envstr, "fastboot.%s", cmd);
00caae6d4   Simon Glass   env: Rename geten...
4177
  		s = env_get(envstr);
74322201d   Rob Herring   fastboot: allow r...
4178
4179
4180
4181
4182
4183
4184
  		if (s) {
  			strncat(response, s, chars_left);
  		} else {
  			printf("WARNING: unknown variable: %s
  ", cmd);
  			strcpy(response, "FAILVariable not implemented");
  		}
b1f2a17c7   nicolas.le.bayon@st.com   usb: gadget: avoi...
4185
4186
  
  		free(envstr);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4187
4188
4189
  	}
  	fastboot_tx_write_str(response);
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
  #ifdef CONFIG_FASTBOOT_FLASH
  static void cb_flash(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  	char response[FASTBOOT_RESPONSE_LEN];
  
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing partition name");
  		fastboot_tx_write_str("FAILmissing partition name");
  		return;
  	}
  
  	/* initialize the response buffer */
  	fb_response_str = response;
  
  	fastboot_fail("no flash device defined");
  #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
  	fb_mmc_flash_write(cmd, (void *)CONFIG_FASTBOOT_BUF_ADDR,
  			   download_bytes);
  #endif
  #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
  	fb_nand_flash_write(cmd,
  			    (void *)CONFIG_FASTBOOT_BUF_ADDR,
  			    download_bytes);
  #endif
  	fastboot_tx_write_str(response);
  }
  #endif
  
  static void cb_oem(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
  	if (strncmp("format", cmd + 4, 6) == 0) {
  		char cmdbuf[32];
                  sprintf(cmdbuf, "gpt write mmc %x $partitions",
  			CONFIG_FASTBOOT_FLASH_MMC_DEV);
                  if (run_command(cmdbuf, 0))
  			fastboot_tx_write_str("FAIL");
                  else
  			fastboot_tx_write_str("OKAY");
  	} else
  #endif
  	if (strncmp("unlock", cmd + 4, 8) == 0) {
  		fastboot_tx_write_str("FAILnot implemented");
  	}
  	else {
  		fastboot_tx_write_str("FAILunknown oem command");
  	}
  }
  
  #ifdef CONFIG_FASTBOOT_FLASH
  static void cb_erase(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
  	char response[FASTBOOT_RESPONSE_LEN];
  
  	strsep(&cmd, ":");
  	if (!cmd) {
  		pr_err("missing partition name");
  		fastboot_tx_write_str("FAILmissing partition name");
  		return;
  	}
  
  	/* initialize the response buffer */
  	fb_response_str = response;
  
  	fastboot_fail("no flash device defined");
  #ifdef CONFIG_FASTBOOT_FLASH_MMC_DEV
  	fb_mmc_erase(cmd);
  #endif
  #ifdef CONFIG_FASTBOOT_FLASH_NAND_DEV
  	fb_nand_erase(cmd);
  #endif
  	fastboot_tx_write_str(response);
  }
  #endif
  
  #endif /* CONFIG_FSL_FASTBOOT*/
ac484c5a6   Roger Quadros   fastboot: Clean u...
4270
  static unsigned int rx_bytes_expected(struct usb_ep *ep)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4271
4272
  {
  	int rx_remain = download_size - download_bytes;
ac484c5a6   Roger Quadros   fastboot: Clean u...
4273
4274
4275
4276
  	unsigned int rem;
  	unsigned int maxpacket = ep->maxpacket;
  
  	if (rx_remain <= 0)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4277
  		return 0;
ac484c5a6   Roger Quadros   fastboot: Clean u...
4278
  	else if (rx_remain > EP_BUFFER_SIZE)
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4279
  		return EP_BUFFER_SIZE;
ac484c5a6   Roger Quadros   fastboot: Clean u...
4280
4281
4282
4283
4284
4285
4286
4287
4288
  
  	/*
  	 * Some controllers e.g. DWC3 don't like OUT transfers to be
  	 * not ending in maxpacket boundary. So just make them happy by
  	 * always requesting for integral multiple of maxpackets.
  	 * This shouldn't bother controllers that don't care about it.
  	 */
  	rem = rx_remain % maxpacket;
  	if (rem > 0)
9e4b510d4   Dileep Katta   fastboot: OUT tra...
4289
  		rx_remain = rx_remain + (maxpacket - rem);
ac484c5a6   Roger Quadros   fastboot: Clean u...
4290

3aab70afc   Sebastian Siewior   usb/gadget: add t...
4291
4292
4293
4294
4295
4296
  	return rx_remain;
  }
  
  #define BYTES_PER_DOT	0x20000
  static void rx_handler_dl_image(struct usb_ep *ep, struct usb_request *req)
  {
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
4297
  	char response[FASTBOOT_RESPONSE_LEN];
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4298
4299
4300
  	unsigned int transfer_size = download_size - download_bytes;
  	const unsigned char *buffer = req->buf;
  	unsigned int buffer_size = req->actual;
23d1d10c4   Bo Shen   usb: gadget: fast...
4301
  	unsigned int pre_dot_num, now_dot_num;
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4302
  	void * base_addr = (void*)env_get_ulong("fastboot_buffer", 16, CONFIG_FASTBOOT_BUF_ADDR);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4303
4304
4305
4306
4307
4308
4309
4310
4311
  
  	if (req->status != 0) {
  		printf("Bad status: %d
  ", req->status);
  		return;
  	}
  
  	if (buffer_size < transfer_size)
  		transfer_size = buffer_size;
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4312
  	memcpy(base_addr + download_bytes,
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4313
  	       buffer, transfer_size);
23d1d10c4   Bo Shen   usb: gadget: fast...
4314
  	pre_dot_num = download_bytes / BYTES_PER_DOT;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4315
  	download_bytes += transfer_size;
23d1d10c4   Bo Shen   usb: gadget: fast...
4316
4317
4318
4319
4320
4321
4322
4323
  	now_dot_num = download_bytes / BYTES_PER_DOT;
  
  	if (pre_dot_num != now_dot_num) {
  		putc('.');
  		if (!(now_dot_num % 74))
  			putc('
  ');
  	}
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
  
  	/* Check if transfer is done */
  	if (download_bytes >= download_size) {
  		/*
  		 * Reset global transfer variable, keep download_bytes because
  		 * it will be used in the next possible flashing command
  		 */
  		download_size = 0;
  		req->complete = rx_handler_command;
  		req->length = EP_BUFFER_SIZE;
192bc6948   Ben Whitten   Fix GCC format-se...
4334
  		strcpy(response, "OKAY");
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4335
  		fastboot_tx_write_str(response);
4752217d6   Han Xu   MLK-19212: set th...
4336
  		env_set_hex("fastboot_bytes", download_bytes);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4337
4338
4339
4340
4341
  
  		printf("
  downloading of %d bytes finished
  ", download_bytes);
  	} else {
ac484c5a6   Roger Quadros   fastboot: Clean u...
4342
  		req->length = rx_bytes_expected(ep);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4343
  	}
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4344
4345
4346
  	req->actual = 0;
  	usb_ep_queue(ep, req, 0);
  }
2c840c82b   Ye Li   MLK-18591-3 andro...
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
  static void cb_upload(struct usb_ep *ep, struct usb_request *req)
  {
  	char response[FASTBOOT_RESPONSE_LEN];
  
  	if (!download_bytes || download_bytes > (EP_BUFFER_SIZE * 32)) {
  		sprintf(response, "FAIL");
  		fastboot_tx_write_str(response);
  		return;
  	}
  
  	printf("Will upload %d bytes.
  ", download_bytes);
  	snprintf(response, FASTBOOT_RESPONSE_LEN, "DATA%08x", download_bytes);
  	fastboot_tx_write_more(response);
  
  	fastboot_tx_write((const char *)(interface.transfer_buffer), download_bytes);
  
  	snprintf(response,FASTBOOT_RESPONSE_LEN, "OKAY");
  	fastboot_tx_write_more(response);
  }
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4367
4368
4369
  static void cb_download(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmd = req->buf;
3c8f98f5f   Maxime Ripard   fastboot: Move fa...
4370
  	char response[FASTBOOT_RESPONSE_LEN];
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4371
4372
4373
4374
4375
4376
4377
4378
4379
  
  	strsep(&cmd, ":");
  	download_size = simple_strtoul(cmd, NULL, 16);
  	download_bytes = 0;
  
  	printf("Starting download of %d bytes
  ", download_size);
  
  	if (0 == download_size) {
192bc6948   Ben Whitten   Fix GCC format-se...
4380
  		strcpy(response, "FAILdata invalid size");
a588d99ac   Paul Kocialkowski   usb: CONFIG_USB_F...
4381
  	} else if (download_size > CONFIG_FASTBOOT_BUF_SIZE) {
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4382
  		download_size = 0;
192bc6948   Ben Whitten   Fix GCC format-se...
4383
  		strcpy(response, "FAILdata too large");
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4384
4385
4386
  	} else {
  		sprintf(response, "DATA%08x", download_size);
  		req->complete = rx_handler_dl_image;
ac484c5a6   Roger Quadros   fastboot: Clean u...
4387
  		req->length = rx_bytes_expected(ep);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4388
4389
4390
4391
4392
4393
4394
  	}
  	fastboot_tx_write_str(response);
  }
  
  static void do_bootm_on_complete(struct usb_ep *ep, struct usb_request *req)
  {
  	char boot_addr_start[12];
2c840c82b   Ye Li   MLK-18591-3 andro...
4395
4396
4397
4398
  #ifdef CONFIG_FSL_FASTBOOT
  	char *bootm_args[] = { "boota", boot_addr_start, NULL };
  	sprintf(boot_addr_start, "0x%lx", load_addr);
  #else
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4399
  	char *bootm_args[] = { "bootm", boot_addr_start, NULL };
2c840c82b   Ye Li   MLK-18591-3 andro...
4400
4401
  	sprintf(boot_addr_start, "0x%lx", (long)CONFIG_FASTBOOT_BUF_ADDR);
  #endif
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4402
4403
4404
  
  	puts("Booting kernel..
  ");
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
  	do_bootm(NULL, 0, 2, bootm_args);
  
  	/* This only happens if image is somehow faulty so we start over */
  	do_reset(NULL, 0, 0, NULL);
  }
  
  static void cb_boot(struct usb_ep *ep, struct usb_request *req)
  {
  	fastboot_func->in_req->complete = do_bootm_on_complete;
  	fastboot_tx_write_str("OKAY");
  }
267abc626   Rob Herring   fastboot: add sup...
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
  static void do_exit_on_complete(struct usb_ep *ep, struct usb_request *req)
  {
  	g_dnl_trigger_detach();
  }
  
  static void cb_continue(struct usb_ep *ep, struct usb_request *req)
  {
  	fastboot_func->in_req->complete = do_exit_on_complete;
  	fastboot_tx_write_str("OKAY");
  }
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4426
4427
4428
4429
4430
4431
  struct cmd_dispatch_info {
  	char *cmd;
  	void (*cb)(struct usb_ep *ep, struct usb_request *req);
  };
  
  static const struct cmd_dispatch_info cmd_dispatch_info[] = {
2c840c82b   Ye Li   MLK-18591-3 andro...
4432
4433
4434
4435
4436
4437
4438
4439
4440
  #ifdef CONFIG_FSL_FASTBOOT
  	{
  		.cmd = "reboot-bootloader",
  		.cb = cb_reboot_bootloader,
  	},
  	{
  		.cmd = "upload",
  		.cb = cb_upload,
  	},
979995530   Yu Shan   [iot] Support ata...
4441
4442
4443
4444
  	{
  		.cmd = "get_staged",
  		.cb = cb_upload,
  	},
2c840c82b   Ye Li   MLK-18591-3 andro...
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
  #ifdef CONFIG_FASTBOOT_LOCK
  	{
  		.cmd = "flashing",
  		.cb = cb_flashing,
  	},
  	{
  		.cmd = "oem",
  		.cb = cb_flashing,
  	},
  #endif
  #ifdef CONFIG_AVB_SUPPORT
  	{
  		.cmd = "set_active",
  		.cb = cb_set_active_avb,
  	},
  #endif
b053775c0   faqiang.zhu   MA-13785 remove t...
4461
  #ifndef CONFIG_NOT_UUU_BUILD
ccffd6e0b   Frank Li   MLK-18257-5 enhen...
4462
4463
4464
4465
4466
4467
4468
  	{
  		.cmd = "UCmd:",
  		.cb = cb_run_uboot_cmd,
  	},
  	{	.cmd ="ACmd:",
  		.cb = cb_run_uboot_acmd,
  	},
2c840c82b   Ye Li   MLK-18591-3 andro...
4469
  #endif
b053775c0   faqiang.zhu   MA-13785 remove t...
4470
  #endif
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
  	{
  		.cmd = "reboot",
  		.cb = cb_reboot,
  	}, {
  		.cmd = "getvar:",
  		.cb = cb_getvar,
  	}, {
  		.cmd = "download:",
  		.cb = cb_download,
  	}, {
  		.cmd = "boot",
  		.cb = cb_boot,
267abc626   Rob Herring   fastboot: add sup...
4483
4484
4485
  	}, {
  		.cmd = "continue",
  		.cb = cb_continue,
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4486
  	},
d1b5ed075   Steve Rae   usb/gadget: fastb...
4487
4488
4489
4490
  #ifdef CONFIG_FASTBOOT_FLASH
  	{
  		.cmd = "flash",
  		.cb = cb_flash,
897923819   Dileep Katta   usb: gadget: fast...
4491
4492
4493
  	}, {
  		.cmd = "erase",
  		.cb = cb_erase,
d1b5ed075   Steve Rae   usb/gadget: fastb...
4494
4495
  	},
  #endif
2c840c82b   Ye Li   MLK-18591-3 andro...
4496
  #ifndef CONFIG_FSL_FASTBOOT
de1956202   Michael Scott   fastboot: add "fa...
4497
4498
4499
4500
  	{
  		.cmd = "oem",
  		.cb = cb_oem,
  	},
2c840c82b   Ye Li   MLK-18591-3 andro...
4501
  #endif
fd9eec336   Yu Shan   [iot] Support fas...
4502
4503
4504
4505
4506
4507
  #ifdef CONFIG_AVB_ATX
  	{
  		.cmd = "stage",
  		.cb = cb_download,
  	},
  #endif
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4508
4509
4510
4511
4512
4513
4514
  };
  
  static void rx_handler_command(struct usb_ep *ep, struct usb_request *req)
  {
  	char *cmdbuf = req->buf;
  	void (*func_cb)(struct usb_ep *ep, struct usb_request *req) = NULL;
  	int i;
2c840c82b   Ye Li   MLK-18591-3 andro...
4515
4516
4517
  	/* init in request FIFO pointer */
  	fastboot_func->front = NULL;
  	fastboot_func->rear  = NULL;
94b385fa2   Paul Kocialkowski   usb: gadget: fast...
4518
4519
  	if (req->status != 0 || req->length == 0)
  		return;
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4520
4521
4522
4523
4524
4525
  	for (i = 0; i < ARRAY_SIZE(cmd_dispatch_info); i++) {
  		if (!strcmp_l1(cmd_dispatch_info[i].cmd, cmdbuf)) {
  			func_cb = cmd_dispatch_info[i].cb;
  			break;
  		}
  	}
593cbd93f   Steve Rae   usb/gadget: fastb...
4526
  	if (!func_cb) {
9b643e312   Masahiro Yamada   treewide: replace...
4527
  		pr_err("unknown command: %.*s", req->actual, cmdbuf);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4528
  		fastboot_tx_write_str("FAILunknown command");
593cbd93f   Steve Rae   usb/gadget: fastb...
4529
  	} else {
e2140588d   Eric Nelson   usb: gadget: fast...
4530
4531
4532
4533
4534
  		if (req->actual < req->length) {
  			u8 *buf = (u8 *)req->buf;
  			buf[req->actual] = 0;
  			func_cb(ep, req);
  		} else {
9b643e312   Masahiro Yamada   treewide: replace...
4535
  			pr_err("buffer overflow");
e2140588d   Eric Nelson   usb: gadget: fast...
4536
4537
  			fastboot_tx_write_str("FAILbuffer overflow");
  		}
593cbd93f   Steve Rae   usb/gadget: fastb...
4538
  	}
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4539

94b385fa2   Paul Kocialkowski   usb: gadget: fast...
4540
4541
4542
  	*cmdbuf = '\0';
  	req->actual = 0;
  	usb_ep_queue(ep, req, 0);
3aab70afc   Sebastian Siewior   usb/gadget: add t...
4543
  }