FPII-2741:platform: msm_shared: change location of integer overflow checks
[fp2-dev/kernel/lk.git] / app / aboot / aboot.c
1 /*
2  * Copyright (c) 2009, Google Inc.
3  * All rights reserved.
4  *
5  * Copyright (c) 2009-2014, The Linux Foundation. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above copyright
12  *       notice, this list of conditions and the following disclaimer in the
13  *       documentation and/or other materials provided with the distribution.
14  *     * Neither the name of The Linux Foundation nor
15  *       the names of its contributors may be used to endorse or promote
16  *       products derived from this software without specific prior written
17  *       permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22  * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
26  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
28  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32
33 #include <app.h>
34 #include <debug.h>
35 #include <arch/arm.h>
36 #include <string.h>
37 #include <stdlib.h>
38 #include <limits.h>
39 #include <kernel/thread.h>
40 #include <arch/ops.h>
41
42 #include <dev/flash.h>
43 #include <lib/ptable.h>
44 #include <dev/keys.h>
45 #include <dev/fbcon.h>
46 #include <baseband.h>
47 #include <target.h>
48 #include <mmc.h>
49 #include <partition_parser.h>
50 #include <platform.h>
51 #include <crypto_hash.h>
52 #include <malloc.h>
53 #include <boot_stats.h>
54 #include <sha.h>
55
56 #if DEVICE_TREE
57 #include <libfdt.h>
58 #include <dev_tree.h>
59 #endif
60
61 #include "image_verify.h"
62 #include "recovery.h"
63 #include "bootimg.h"
64 #include "fastboot.h"
65 #include "sparse_format.h"
66 #include "mmc.h"
67 #include "devinfo.h"
68 #include "board.h"
69 #include "scm.h"
70
71 extern  bool target_use_signed_kernel(void);
72 extern void platform_uninit(void);
73 extern void target_uninit(void);
74
75 void write_device_info_mmc(device_info *dev);
76 void write_device_info_flash(device_info *dev);
77
78 /* fastboot command function pointer */
79 typedef void (*fastboot_cmd_fn) (const char *, void *, unsigned);
80
81 struct fastboot_cmd_desc {
82         char * name;
83         fastboot_cmd_fn cb;
84 };
85
86 #define EXPAND(NAME) #NAME
87 #define TARGET(NAME) EXPAND(NAME)
88
89 #ifdef MEMBASE
90 #define EMMC_BOOT_IMG_HEADER_ADDR (0xFF000+(MEMBASE))
91 #else
92 #define EMMC_BOOT_IMG_HEADER_ADDR 0xFF000
93 #endif
94
95 #ifndef MEMSIZE
96 #define MEMSIZE 1024*1024
97 #endif
98
99 #define MAX_TAGS_SIZE   1024
100
101 #define RECOVERY_MODE   0x77665502
102 #define FASTBOOT_MODE   0x77665500
103
104 /* make 4096 as default size to ensure EFS,EXT4's erasing */
105 #define DEFAULT_ERASE_SIZE  4096
106 #define MAX_PANEL_BUF_SIZE 128
107
108 #define ADD_OF(a, b) (UINT_MAX - b > a) ? (a + b) : UINT_MAX
109
110 static const char *emmc_cmdline = " androidboot.emmc=true";
111 static const char *usb_sn_cmdline = " androidboot.serialno=";
112 static const char *androidboot_mode = " androidboot.mode=";
113 static const char *display_cmdline = " mdss_mdp.panel=";
114 static const char *loglevel         = " quiet";
115 static const char *battchg_pause = " androidboot.mode=charger";
116 static const char *auth_kernel = " androidboot.authorized_kernel=true";
117 static const char *secondary_gpt_enable = " gpt";
118
119 static const char *baseband_apq     = " androidboot.baseband=apq";
120 static const char *baseband_msm     = " androidboot.baseband=msm";
121 static const char *baseband_csfb    = " androidboot.baseband=csfb";
122 static const char *baseband_svlte2a = " androidboot.baseband=svlte2a";
123 static const char *baseband_mdm     = " androidboot.baseband=mdm";
124 static const char *baseband_sglte   = " androidboot.baseband=sglte";
125 static const char *baseband_dsda    = " androidboot.baseband=dsda";
126 static const char *baseband_dsda2   = " androidboot.baseband=dsda2";
127 static const char *baseband_sglte2  = " androidboot.baseband=sglte2";
128
129 static unsigned page_size = 0;
130 static unsigned page_mask = 0;
131 static char ffbm_mode_string[FFBM_MODE_BUF_SIZE];
132 static bool boot_into_ffbm;
133
134 /* Assuming unauthorized kernel image by default */
135 static int auth_kernel_img = 0;
136
137 static device_info device = {DEVICE_MAGIC, 0, 0, 0, 0};
138
139 struct atag_ptbl_entry
140 {
141         char name[16];
142         unsigned offset;
143         unsigned size;
144         unsigned flags;
145 };
146
147 /*
148  * Partition info, required to be published
149  * for fastboot
150  */
151 struct getvar_partition_info {
152         const char part_name[MAX_GPT_NAME_SIZE]; /* Partition name */
153         char getvar_size[MAX_GET_VAR_NAME_SIZE]; /* fastboot get var name for size */
154         char getvar_type[MAX_GET_VAR_NAME_SIZE]; /* fastboot get var name for type */
155         char size_response[MAX_RSP_SIZE];        /* fastboot response for size */
156         char type_response[MAX_RSP_SIZE];        /* fastboot response for type */
157 };
158
159 /*
160  * Right now, we are publishing the info for only
161  * three partitions
162  */
163 struct getvar_partition_info part_info[] =
164 {
165         { "system"  , "partition-size:", "partition-type:", "", "ext4" },
166         { "userdata", "partition-size:", "partition-type:", "", "ext4" },
167         { "cache"   , "partition-size:", "partition-type:", "", "ext4" },
168 };
169
170 char max_download_size[MAX_RSP_SIZE];
171 char charger_screen_enabled[MAX_RSP_SIZE];
172 char sn_buf[13];
173 char display_panel_buf[MAX_PANEL_BUF_SIZE];
174 char panel_display_mode[MAX_RSP_SIZE];
175
176 extern int emmc_recovery_init(void);
177
178 #if NO_KEYPAD_DRIVER
179 extern int fastboot_trigger(void);
180 #endif
181
182 static void update_ker_tags_rdisk_addr(struct boot_img_hdr *hdr)
183 {
184         /* overwrite the destination of specified for the project */
185 #ifdef ABOOT_IGNORE_BOOT_HEADER_ADDRS
186         hdr->kernel_addr = ABOOT_FORCE_KERNEL_ADDR;
187         hdr->ramdisk_addr = ABOOT_FORCE_RAMDISK_ADDR;
188         hdr->tags_addr = ABOOT_FORCE_TAGS_ADDR;
189 #endif
190 }
191
192 static void ptentry_to_tag(unsigned **ptr, struct ptentry *ptn)
193 {
194         struct atag_ptbl_entry atag_ptn;
195
196         memcpy(atag_ptn.name, ptn->name, 16);
197         atag_ptn.name[15] = '\0';
198         atag_ptn.offset = ptn->start;
199         atag_ptn.size = ptn->length;
200         atag_ptn.flags = ptn->flags;
201         memcpy(*ptr, &atag_ptn, sizeof(struct atag_ptbl_entry));
202         *ptr += sizeof(struct atag_ptbl_entry) / sizeof(unsigned);
203 }
204
205 unsigned char *update_cmdline(const char * cmdline)
206 {
207         int cmdline_len = 0;
208         int have_cmdline = 0;
209         unsigned char *cmdline_final = NULL;
210         int pause_at_bootup = 0;
211         bool gpt_exists = partition_gpt_exists();
212
213         if (cmdline && cmdline[0]) {
214                 cmdline_len = strlen(cmdline);
215                 have_cmdline = 1;
216         }
217         if (target_is_emmc_boot()) {
218                 cmdline_len += strlen(emmc_cmdline);
219         }
220
221         cmdline_len += strlen(usb_sn_cmdline);
222         cmdline_len += strlen(sn_buf);
223
224         if (boot_into_recovery && gpt_exists)
225                 cmdline_len += strlen(secondary_gpt_enable);
226
227         if (boot_into_ffbm) {
228                 cmdline_len += strlen(androidboot_mode);
229                 cmdline_len += strlen(ffbm_mode_string);
230                 /* reduce kernel console messages to speed-up boot */
231                 cmdline_len += strlen(loglevel);
232         } else if (device.charger_screen_enabled &&
233                         target_pause_for_battery_charge()) {
234                 pause_at_bootup = 1;
235                 cmdline_len += strlen(battchg_pause);
236         }
237
238         if(target_use_signed_kernel() && auth_kernel_img) {
239                 cmdline_len += strlen(auth_kernel);
240         }
241
242         /* Determine correct androidboot.baseband to use */
243         switch(target_baseband())
244         {
245                 case BASEBAND_APQ:
246                         cmdline_len += strlen(baseband_apq);
247                         break;
248
249                 case BASEBAND_MSM:
250                         cmdline_len += strlen(baseband_msm);
251                         break;
252
253                 case BASEBAND_CSFB:
254                         cmdline_len += strlen(baseband_csfb);
255                         break;
256
257                 case BASEBAND_SVLTE2A:
258                         cmdline_len += strlen(baseband_svlte2a);
259                         break;
260
261                 case BASEBAND_MDM:
262                         cmdline_len += strlen(baseband_mdm);
263                         break;
264
265                 case BASEBAND_SGLTE:
266                         cmdline_len += strlen(baseband_sglte);
267                         break;
268
269                 case BASEBAND_SGLTE2:
270                         cmdline_len += strlen(baseband_sglte2);
271                         break;
272
273                 case BASEBAND_DSDA:
274                         cmdline_len += strlen(baseband_dsda);
275                         break;
276
277                 case BASEBAND_DSDA2:
278                         cmdline_len += strlen(baseband_dsda2);
279                         break;
280         }
281
282         if (target_display_panel_node(display_panel_buf, MAX_PANEL_BUF_SIZE) &&
283             strlen(display_panel_buf))
284         {
285                 cmdline_len += strlen(display_cmdline);
286                 cmdline_len += strlen(display_panel_buf);
287         }
288
289         if (cmdline_len > 0) {
290                 const char *src;
291                 unsigned char *dst = (unsigned char*) malloc((cmdline_len + 4) & (~3));
292                 ASSERT(dst != NULL);
293
294                 /* Save start ptr for debug print */
295                 cmdline_final = dst;
296                 if (have_cmdline) {
297                         src = cmdline;
298                         while ((*dst++ = *src++));
299                 }
300                 if (target_is_emmc_boot()) {
301                         src = emmc_cmdline;
302                         if (have_cmdline) --dst;
303                         have_cmdline = 1;
304                         while ((*dst++ = *src++));
305                 }
306
307                 src = usb_sn_cmdline;
308                 if (have_cmdline) --dst;
309                 have_cmdline = 1;
310                 while ((*dst++ = *src++));
311                 src = sn_buf;
312                 if (have_cmdline) --dst;
313                 have_cmdline = 1;
314                 while ((*dst++ = *src++));
315
316                 if (boot_into_recovery && gpt_exists) {
317                         src = secondary_gpt_enable;
318                         if (have_cmdline) --dst;
319                         while ((*dst++ = *src++));
320                 }
321
322                 if (boot_into_ffbm) {
323                         src = androidboot_mode;
324                         if (have_cmdline) --dst;
325                         while ((*dst++ = *src++));
326                         src = ffbm_mode_string;
327                         if (have_cmdline) --dst;
328                         while ((*dst++ = *src++));
329                         src = loglevel;
330                         if (have_cmdline) --dst;
331                         while ((*dst++ = *src++));
332                 } else if (pause_at_bootup) {
333                         src = battchg_pause;
334                         if (have_cmdline) --dst;
335                         while ((*dst++ = *src++));
336                 }
337
338                 if(target_use_signed_kernel() && auth_kernel_img) {
339                         src = auth_kernel;
340                         if (have_cmdline) --dst;
341                         while ((*dst++ = *src++));
342                 }
343
344                 switch(target_baseband())
345                 {
346                         case BASEBAND_APQ:
347                                 src = baseband_apq;
348                                 if (have_cmdline) --dst;
349                                 while ((*dst++ = *src++));
350                                 break;
351
352                         case BASEBAND_MSM:
353                                 src = baseband_msm;
354                                 if (have_cmdline) --dst;
355                                 while ((*dst++ = *src++));
356                                 break;
357
358                         case BASEBAND_CSFB:
359                                 src = baseband_csfb;
360                                 if (have_cmdline) --dst;
361                                 while ((*dst++ = *src++));
362                                 break;
363
364                         case BASEBAND_SVLTE2A:
365                                 src = baseband_svlte2a;
366                                 if (have_cmdline) --dst;
367                                 while ((*dst++ = *src++));
368                                 break;
369
370                         case BASEBAND_MDM:
371                                 src = baseband_mdm;
372                                 if (have_cmdline) --dst;
373                                 while ((*dst++ = *src++));
374                                 break;
375
376                         case BASEBAND_SGLTE:
377                                 src = baseband_sglte;
378                                 if (have_cmdline) --dst;
379                                 while ((*dst++ = *src++));
380                                 break;
381
382                         case BASEBAND_SGLTE2:
383                                 src = baseband_sglte2;
384                                 if (have_cmdline) --dst;
385                                 while ((*dst++ = *src++));
386                                 break;
387
388                         case BASEBAND_DSDA:
389                                 src = baseband_dsda;
390                                 if (have_cmdline) --dst;
391                                 while ((*dst++ = *src++));
392                                 break;
393
394                         case BASEBAND_DSDA2:
395                                 src = baseband_dsda2;
396                                 if (have_cmdline) --dst;
397                                 while ((*dst++ = *src++));
398                                 break;
399                 }
400
401                 if (strlen(display_panel_buf)) {
402                         src = display_cmdline;
403                         if (have_cmdline) --dst;
404                         while ((*dst++ = *src++));
405                         src = display_panel_buf;
406                         if (have_cmdline) --dst;
407                         while ((*dst++ = *src++));
408                 }
409         }
410
411
412         dprintf(INFO, "cmdline: %s\n", cmdline_final);
413         return cmdline_final;
414 }
415
416 unsigned *atag_core(unsigned *ptr)
417 {
418         /* CORE */
419         *ptr++ = 2;
420         *ptr++ = 0x54410001;
421
422         return ptr;
423
424 }
425
426 unsigned *atag_ramdisk(unsigned *ptr, void *ramdisk,
427                                                            unsigned ramdisk_size)
428 {
429         if (ramdisk_size) {
430                 *ptr++ = 4;
431                 *ptr++ = 0x54420005;
432                 *ptr++ = (unsigned)ramdisk;
433                 *ptr++ = ramdisk_size;
434         }
435
436         return ptr;
437 }
438
439 unsigned *atag_ptable(unsigned **ptr_addr)
440 {
441         int i;
442         struct ptable *ptable;
443
444         if ((ptable = flash_get_ptable()) && (ptable->count != 0)) {
445                 *(*ptr_addr)++ = 2 + (ptable->count * (sizeof(struct atag_ptbl_entry) /
446                                                         sizeof(unsigned)));
447                 *(*ptr_addr)++ = 0x4d534d70;
448                 for (i = 0; i < ptable->count; ++i)
449                         ptentry_to_tag(ptr_addr, ptable_get(ptable, i));
450         }
451
452         return (*ptr_addr);
453 }
454
455 unsigned *atag_cmdline(unsigned *ptr, const char *cmdline)
456 {
457         int cmdline_length = 0;
458         int n;
459         char *dest;
460
461         cmdline_length = strlen((const char*)cmdline);
462         n = (cmdline_length + 4) & (~3);
463
464         *ptr++ = (n / 4) + 2;
465         *ptr++ = 0x54410009;
466         dest = (char *) ptr;
467         while ((*dest++ = *cmdline++));
468         ptr += (n / 4);
469
470         return ptr;
471 }
472
473 unsigned *atag_end(unsigned *ptr)
474 {
475         /* END */
476         *ptr++ = 0;
477         *ptr++ = 0;
478
479         return ptr;
480 }
481
482 void generate_atags(unsigned *ptr, const char *cmdline,
483                     void *ramdisk, unsigned ramdisk_size)
484 {
485
486         ptr = atag_core(ptr);
487         ptr = atag_ramdisk(ptr, ramdisk, ramdisk_size);
488         ptr = target_atag_mem(ptr);
489
490         /* Skip NAND partition ATAGS for eMMC boot */
491         if (!target_is_emmc_boot()){
492                 ptr = atag_ptable(&ptr);
493         }
494
495         ptr = atag_cmdline(ptr, cmdline);
496         ptr = atag_end(ptr);
497 }
498
499 typedef void entry_func_ptr(unsigned, unsigned, unsigned*);
500 void boot_linux(void *kernel, unsigned *tags,
501                 const char *cmdline, unsigned machtype,
502                 void *ramdisk, unsigned ramdisk_size)
503 {
504         unsigned char *final_cmdline;
505 #if DEVICE_TREE
506         int ret = 0;
507 #endif
508
509         void (*entry)(unsigned, unsigned, unsigned*) = (entry_func_ptr*)(PA((addr_t)kernel));
510         uint32_t tags_phys = PA((addr_t)tags);
511
512         ramdisk = PA(ramdisk);
513
514         final_cmdline = update_cmdline((const char*)cmdline);
515
516 #if DEVICE_TREE
517         dprintf(INFO, "Updating device tree: start\n");
518
519         /* Update the Device Tree */
520         ret = update_device_tree((void *)tags, final_cmdline, ramdisk, ramdisk_size);
521         if(ret)
522         {
523                 dprintf(CRITICAL, "ERROR: Updating Device Tree Failed \n");
524                 ASSERT(0);
525         }
526         dprintf(INFO, "Updating device tree: done\n");
527 #else
528         /* Generating the Atags */
529         generate_atags(tags, final_cmdline, ramdisk, ramdisk_size);
530 #endif
531
532         /* Perform target specific cleanup */
533         target_uninit();
534
535         /* Turn off splash screen if enabled */
536 #if DISPLAY_SPLASH_SCREEN
537         target_display_shutdown();
538 #endif
539
540
541         dprintf(INFO, "booting linux @ %p, ramdisk @ %p (%d), tags/device tree @ %p\n",
542                 entry, ramdisk, ramdisk_size, tags_phys);
543
544         enter_critical_section();
545
546         /* do any platform specific cleanup before kernel entry */
547         platform_uninit();
548
549         arch_disable_cache(UCACHE);
550
551 #if ARM_WITH_MMU
552         arch_disable_mmu();
553 #endif
554         bs_set_timestamp(BS_KERNEL_ENTRY);
555         entry(0, machtype, (unsigned*)tags_phys);
556 }
557
558 /* Function to check if the memory address range falls within the aboot
559  * boundaries.
560  * start: Start of the memory region
561  * size: Size of the memory region
562  */
563 int check_aboot_addr_range_overlap(uint32_t start, uint32_t size)
564 {
565         /* Check for boundary conditions. */
566         if ((UINT_MAX - start) < size)
567                 return -1;
568
569         /* Check for memory overlap. */
570         if ((start < MEMBASE) && ((start + size) <= MEMBASE))
571                 return 0;
572         else if (start >= (MEMBASE + MEMSIZE))
573                 return 0;
574         else
575                 return -1;
576 }
577
578 #define ROUND_TO_PAGE(x,y) (((x) + (y)) & (~(y)))
579
580 BUF_DMA_ALIGN(buf, 4096); //Equal to max-supported pagesize
581 #if DEVICE_TREE
582 BUF_DMA_ALIGN(dt_buf, 4096);
583 #endif
584
585 static void verify_signed_bootimg(uint32_t bootimg_addr, uint32_t bootimg_size)
586 {
587         int ret;
588
589         /* Assume device is rooted at this time. */
590         device.is_tampered = 1;
591
592         dprintf(INFO, "Authenticating boot image (%d): start\n", bootimg_size);
593
594         ret = image_verify((unsigned char *)bootimg_addr,
595                                            (unsigned char *)(bootimg_addr + bootimg_size),
596                                            bootimg_size,
597                                            CRYPTO_AUTH_ALG_SHA256);
598
599         dprintf(INFO, "Authenticating boot image: done return value = %d\n", ret);
600
601         if (ret)
602         {
603                 /* Authorized kernel */
604                 device.is_tampered = 0;
605         }
606
607 #if USE_PCOM_SECBOOT
608         set_tamper_flag(device.is_tampered);
609 #endif
610
611         if(device.is_tampered)
612         {
613                 write_device_info_mmc(&device);
614         #ifdef TZ_TAMPER_FUSE
615                 set_tamper_fuse_cmd();
616         #endif
617         #ifdef ASSERT_ON_TAMPER
618                 dprintf(CRITICAL, "Device is tampered. Asserting..\n");
619                 ASSERT(0);
620         #endif
621         }
622 }
623
624 static bool check_format_bit()
625 {
626         bool ret = false;
627         int index;
628         uint64_t offset;
629         struct boot_selection_info *in = NULL;
630         char *buf = NULL;
631
632         index = partition_get_index("bootselect");
633         if (index == INVALID_PTN)
634         {
635                 dprintf(INFO, "Unable to locate /bootselect partition\n");
636                 return ret;
637         }
638         offset = partition_get_offset(index);
639         if(!offset)
640         {
641                 dprintf(INFO, "partition /bootselect doesn't exist\n");
642                 return ret;
643         }
644         buf = (char *) memalign(CACHE_LINE, ROUNDUP(page_size, CACHE_LINE));
645         ASSERT(buf);
646         if (mmc_read(offset, (unsigned int *)buf, page_size))
647         {
648                 dprintf(INFO, "mmc read failure /bootselect %d\n", page_size);
649                 free(buf);
650                 return ret;
651         }
652         in = (struct boot_selection_info *) buf;
653         if ((in->signature == BOOTSELECT_SIGNATURE) &&
654                         (in->version == BOOTSELECT_VERSION)) {
655                 if ((in->state_info & BOOTSELECT_FORMAT) &&
656                                 !(in->state_info & BOOTSELECT_FACTORY))
657                         ret = true;
658         } else {
659                 dprintf(CRITICAL, "Signature: 0x%08x or version: 0x%08x mismatched of /bootselect\n",
660                                 in->signature, in->version);
661                 ASSERT(0);
662         }
663         free(buf);
664         return ret;
665 }
666
667 int boot_linux_from_mmc(void)
668 {
669         struct boot_img_hdr *hdr = (void*) buf;
670         struct boot_img_hdr *uhdr;
671         unsigned offset = 0;
672         int rcode;
673         unsigned long long ptn = 0;
674         int index = INVALID_PTN;
675
676         unsigned char *image_addr = 0;
677         unsigned kernel_actual;
678         unsigned ramdisk_actual;
679         unsigned imagesize_actual;
680         unsigned second_actual = 0;
681
682 #if DEVICE_TREE
683         struct dt_table *table;
684         struct dt_entry dt_entry;
685         unsigned dt_table_offset;
686         uint32_t dt_actual;
687         uint32_t dt_hdr_size;
688 #endif
689         if (check_format_bit())
690                 boot_into_recovery = 1;
691
692         if (!boot_into_recovery) {
693                 memset(ffbm_mode_string, '\0', sizeof(ffbm_mode_string));
694                 rcode = get_ffbm(ffbm_mode_string, sizeof(ffbm_mode_string));
695                 if (rcode <= 0) {
696                         boot_into_ffbm = false;
697                         if (rcode < 0)
698                                 dprintf(CRITICAL,"failed to get ffbm cookie");
699                 } else
700                         boot_into_ffbm = true;
701         } else
702                 boot_into_ffbm = false;
703         uhdr = (struct boot_img_hdr *)EMMC_BOOT_IMG_HEADER_ADDR;
704         if (!memcmp(uhdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
705                 dprintf(INFO, "Unified boot method!\n");
706                 hdr = uhdr;
707                 goto unified_boot;
708         }
709         if (!boot_into_recovery) {
710                 index = partition_get_index("boot");
711                 ptn = partition_get_offset(index);
712                 if(ptn == 0) {
713                         dprintf(CRITICAL, "ERROR: No boot partition found\n");
714                     return -1;
715                 }
716         }
717         else {
718                 index = partition_get_index("recovery");
719                 ptn = partition_get_offset(index);
720                 if(ptn == 0) {
721                         dprintf(CRITICAL, "ERROR: No recovery partition found\n");
722                     return -1;
723                 }
724         }
725
726         if (mmc_read(ptn + offset, (unsigned int *) buf, page_size)) {
727                 dprintf(CRITICAL, "ERROR: Cannot read boot image header\n");
728                 return -1;
729         }
730
731         if (memcmp(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
732                 dprintf(CRITICAL, "ERROR: Invalid boot image header\n");
733                 return -1;
734         }
735
736         if (hdr->page_size && (hdr->page_size != page_size)) {
737                   if (hdr->page_size > BOOT_IMG_MAX_PAGE_SIZE) {
738                           dprintf(CRITICAL, "ERROR: Invalid page size\n");
739                           return -1;
740       }
741                 page_size = hdr->page_size;
742                 page_mask = page_size - 1;
743         }
744
745         /*
746          * Update the kernel/ramdisk/tags address if the boot image header
747          * has default values, these default values come from mkbootimg when
748          * the boot image is flashed using fastboot flash:raw
749          */
750         update_ker_tags_rdisk_addr(hdr);
751
752         /* Get virtual addresses since the hdr saves physical addresses. */
753         hdr->kernel_addr = VA((addr_t)(hdr->kernel_addr));
754         hdr->ramdisk_addr = VA((addr_t)(hdr->ramdisk_addr));
755         hdr->tags_addr = VA((addr_t)(hdr->tags_addr));
756
757         kernel_actual  = ROUND_TO_PAGE(hdr->kernel_size,  page_mask);
758         ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
759
760         /* Check if the addresses in the header are valid. */
761         if (check_aboot_addr_range_overlap(hdr->kernel_addr, kernel_actual) ||
762                 check_aboot_addr_range_overlap(hdr->ramdisk_addr, ramdisk_actual))
763         {
764                 dprintf(CRITICAL, "kernel/ramdisk addresses overlap with aboot addresses.\n");
765                 return -1;
766         }
767
768 #ifndef DEVICE_TREE
769         if (check_aboot_addr_range_overlap(hdr->tags_addr, MAX_TAGS_SIZE))
770         {
771                 dprintf(CRITICAL, "Tags addresses overlap with aboot addresses.\n");
772                 return -1;
773         }
774 #endif
775
776         /* Authenticate Kernel */
777         dprintf(INFO, "use_signed_kernel=%d, is_unlocked=%d, is_tampered=%d.\n",
778                 (int) target_use_signed_kernel(),
779                 device.is_unlocked,
780                 device.is_tampered);
781
782         if(target_use_signed_kernel() && (!device.is_unlocked))
783         {
784                 offset = 0;
785
786                 image_addr = (unsigned char *)target_get_scratch_address();
787
788 #if DEVICE_TREE
789                 dt_actual = ROUND_TO_PAGE(hdr->dt_size, page_mask);
790         if (UINT_MAX < ((uint64_t)kernel_actual + (uint64_t)ramdisk_actual+ (uint64_t)dt_actual + page_size)) {
791                         dprintf(CRITICAL, "Integer overflow detected in bootimage header fields\n");
792                         return -1;
793                 }
794
795                 imagesize_actual = (page_size + kernel_actual + ramdisk_actual + dt_actual);
796
797                 if (check_aboot_addr_range_overlap(hdr->tags_addr, dt_actual))
798                 {
799                         dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
800                         return -1;
801                 }
802 #else
803         if (UINT_MAX < ((uint64_t)kernel_actual + (uint64_t)ramdisk_actual+ page_size)) {
804                         dprintf(CRITICAL, "Integer overflow detected in bootimage header fields\n");
805                         return -1;
806                 }
807                 imagesize_actual = (page_size + kernel_actual + ramdisk_actual);
808
809 #endif
810
811                 dprintf(INFO, "Loading boot image (%d): start\n", imagesize_actual);
812                 bs_set_timestamp(BS_KERNEL_LOAD_START);
813
814                 if (check_aboot_addr_range_overlap(image_addr, imagesize_actual))
815                 {
816                         dprintf(CRITICAL, "Boot image buffer address overlaps with aboot addresses.\n");
817                         return -1;
818                 }
819
820                 /* Read image without signature */
821                 if (mmc_read(ptn + offset, (void *)image_addr, imagesize_actual))
822                 {
823                         dprintf(CRITICAL, "ERROR: Cannot read boot image\n");
824                                 return -1;
825                 }
826
827                 dprintf(INFO, "Loading boot image (%d): done\n", imagesize_actual);
828                 bs_set_timestamp(BS_KERNEL_LOAD_DONE);
829
830                 offset = imagesize_actual;
831
832                 if (check_aboot_addr_range_overlap(image_addr + offset, page_size))
833                 {
834                         dprintf(CRITICAL, "Signature read buffer address overlaps with aboot addresses.\n");
835                         return -1;
836                 }
837
838                 /* Read signature */
839                 if(mmc_read(ptn + offset, (void *)(image_addr + offset), page_size))
840                 {
841                         dprintf(CRITICAL, "ERROR: Cannot read boot image signature\n");
842                         return -1;
843                 }
844
845         //      verify_signed_bootimg(image_addr, imagesize_actual);
846
847                 /* Move kernel, ramdisk and device tree to correct address */
848                 memmove((void*) hdr->kernel_addr, (char *)(image_addr + page_size), hdr->kernel_size);
849                 memmove((void*) hdr->ramdisk_addr, (char *)(image_addr + page_size + kernel_actual), hdr->ramdisk_size);
850
851                 #if DEVICE_TREE
852                 if(hdr->dt_size) {
853                         dt_table_offset = ((uint32_t)image_addr + page_size + kernel_actual + ramdisk_actual + second_actual);
854                         table = (struct dt_table*) dt_table_offset;
855
856                         if (dev_tree_validate(table, hdr->page_size, &dt_hdr_size) != 0) {
857                                 dprintf(CRITICAL, "ERROR: Cannot validate Device Tree Table \n");
858                                 return -1;
859                         }
860
861                         /* Find index of device tree within device tree table */
862                         if(dev_tree_get_entry_info(table, &dt_entry) != 0){
863                                 dprintf(CRITICAL, "ERROR: Device Tree Blob cannot be found\n");
864                                 return -1;
865                         }
866
867                         /* Validate and Read device device tree in the "tags_add */
868                         if (check_aboot_addr_range_overlap(hdr->tags_addr, dt_entry.size))
869                         {
870                                 dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
871                                 return -1;
872                         }
873
874                         memmove((void *)hdr->tags_addr, (char *)dt_table_offset + dt_entry.offset, dt_entry.size);
875                 } else {
876                         /*
877                          * If appended dev tree is found, update the atags with
878                          * memory address to the DTB appended location on RAM.
879                          * Else update with the atags address in the kernel header
880                          */
881                         void *dtb;
882                         dtb = dev_tree_appended((void*) hdr->kernel_addr,
883                                                 hdr->kernel_size,
884                                                 (void *)hdr->tags_addr);
885                         if (!dtb) {
886                                 dprintf(CRITICAL, "ERROR: Appended Device Tree Blob not found\n");
887                                 return -1;
888                         }
889                 }
890                 #endif
891         }
892         else
893         {
894                 second_actual  = ROUND_TO_PAGE(hdr->second_size,  page_mask);
895
896                 dprintf(INFO, "Loading boot image (%d): start\n",
897                                 kernel_actual + ramdisk_actual);
898                 bs_set_timestamp(BS_KERNEL_LOAD_START);
899
900                 offset = page_size;
901
902                 /* Load kernel */
903                 if (mmc_read(ptn + offset, (void *)hdr->kernel_addr, kernel_actual)) {
904                         dprintf(CRITICAL, "ERROR: Cannot read kernel image\n");
905                                         return -1;
906                 }
907                 offset += kernel_actual;
908
909                 /* Load ramdisk */
910                 if(ramdisk_actual != 0)
911                 {
912                         if (mmc_read(ptn + offset, (void *)hdr->ramdisk_addr, ramdisk_actual)) {
913                                 dprintf(CRITICAL, "ERROR: Cannot read ramdisk image\n");
914                                 return -1;
915                         }
916                 }
917                 offset += ramdisk_actual;
918
919                 dprintf(INFO, "Loading boot image (%d): done\n",
920                                 kernel_actual + ramdisk_actual);
921                 bs_set_timestamp(BS_KERNEL_LOAD_DONE);
922
923                 if(hdr->second_size != 0) {
924                         offset += second_actual;
925                         /* Second image loading not implemented. */
926                         ASSERT(0);
927                 }
928
929                 #if DEVICE_TREE
930                 if(hdr->dt_size != 0) {
931                         /* Read the first page of device tree table into buffer */
932                         if(mmc_read(ptn + offset,(unsigned int *) dt_buf, page_size)) {
933                                 dprintf(CRITICAL, "ERROR: Cannot read the Device Tree Table\n");
934                                 return -1;
935                         }
936                         table = (struct dt_table*) dt_buf;
937
938                         if (dev_tree_validate(table, hdr->page_size, &dt_hdr_size) != 0) {
939                                 dprintf(CRITICAL, "ERROR: Cannot validate Device Tree Table \n");
940                                 return -1;
941                         }
942
943                         table = (struct dt_table*) memalign(CACHE_LINE, dt_hdr_size);
944                         if (!table)
945                                 return -1;
946
947                         /* Read the entire device tree table into buffer */
948                         if(mmc_read(ptn + offset,(unsigned int *) table, dt_hdr_size)) {
949                                 dprintf(CRITICAL, "ERROR: Cannot read the Device Tree Table\n");
950                                 return -1;
951                         }
952
953                         /* Find index of device tree within device tree table */
954                         if(dev_tree_get_entry_info(table, &dt_entry) != 0){
955                                 dprintf(CRITICAL, "ERROR: Getting device tree address failed\n");
956                                 return -1;
957                         }
958
959                         /* Validate and Read device device tree in the "tags_add */
960                         if (check_aboot_addr_range_overlap(hdr->tags_addr, dt_entry.size))
961                         {
962                                 dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
963                                 return -1;
964                         }
965
966                         if(mmc_read(ptn + offset + dt_entry.offset,
967                                                  (void *)hdr->tags_addr, dt_entry.size)) {
968                                 dprintf(CRITICAL, "ERROR: Cannot read device tree\n");
969                                 return -1;
970                         }
971                         #ifdef TZ_SAVE_KERNEL_HASH
972                         aboot_save_boot_hash_mmc(hdr->kernel_addr, kernel_actual,
973                                        hdr->ramdisk_addr, ramdisk_actual,
974                                        ptn, offset, hdr->dt_size);
975                         #endif /* TZ_SAVE_KERNEL_HASH */
976
977                 } else {
978
979                         /* Validate the tags_addr */
980                         if (check_aboot_addr_range_overlap(hdr->tags_addr, kernel_actual))
981                         {
982                                 dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
983                                 return -1;
984                         }
985                         /*
986                          * If appended dev tree is found, update the atags with
987                          * memory address to the DTB appended location on RAM.
988                          * Else update with the atags address in the kernel header
989                          */
990                         void *dtb;
991                         dtb = dev_tree_appended((void*) hdr->kernel_addr,
992                                                 kernel_actual,
993                                                 (void *)hdr->tags_addr);
994                         if (!dtb) {
995                                 dprintf(CRITICAL, "ERROR: Appended Device Tree Blob not found\n");
996                                 return -1;
997                         }
998                 }
999                 #endif
1000         }
1001
1002         if (boot_into_recovery && !device.is_unlocked && !device.is_tampered)
1003                 target_load_ssd_keystore();
1004
1005 unified_boot:
1006
1007         boot_linux((void *)hdr->kernel_addr, (void *)hdr->tags_addr,
1008                    (const char *)hdr->cmdline, board_machtype(),
1009                    (void *)hdr->ramdisk_addr, hdr->ramdisk_size);
1010
1011         return 0;
1012 }
1013
1014 int boot_linux_from_flash(void)
1015 {
1016         struct boot_img_hdr *hdr = (void*) buf;
1017         struct ptentry *ptn;
1018         struct ptable *ptable;
1019         unsigned offset = 0;
1020
1021         unsigned char *image_addr = 0;
1022         unsigned kernel_actual;
1023         unsigned ramdisk_actual;
1024         unsigned imagesize_actual;
1025         unsigned second_actual;
1026
1027 #if DEVICE_TREE
1028         struct dt_table *table;
1029         struct dt_entry dt_entry;
1030         uint32_t dt_actual;
1031         uint32_t dt_hdr_size;
1032 #endif
1033
1034         if (target_is_emmc_boot()) {
1035                 hdr = (struct boot_img_hdr *)EMMC_BOOT_IMG_HEADER_ADDR;
1036                 if (memcmp(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
1037                         dprintf(CRITICAL, "ERROR: Invalid boot image header\n");
1038                         return -1;
1039                 }
1040                 goto continue_boot;
1041         }
1042
1043         ptable = flash_get_ptable();
1044         if (ptable == NULL) {
1045                 dprintf(CRITICAL, "ERROR: Partition table not found\n");
1046                 return -1;
1047         }
1048
1049         if(!boot_into_recovery)
1050         {
1051                 ptn = ptable_find(ptable, "boot");
1052
1053                 if (ptn == NULL) {
1054                         dprintf(CRITICAL, "ERROR: No boot partition found\n");
1055                         return -1;
1056                 }
1057         }
1058         else
1059         {
1060                 ptn = ptable_find(ptable, "recovery");
1061                 if (ptn == NULL) {
1062                         dprintf(CRITICAL, "ERROR: No recovery partition found\n");
1063                         return -1;
1064                 }
1065         }
1066
1067         if (flash_read(ptn, offset, buf, page_size)) {
1068                 dprintf(CRITICAL, "ERROR: Cannot read boot image header\n");
1069                 return -1;
1070         }
1071
1072         if (memcmp(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
1073                 dprintf(CRITICAL, "ERROR: Invalid boot image header\n");
1074                 return -1;
1075         }
1076
1077         if (hdr->page_size != page_size) {
1078                 dprintf(CRITICAL, "ERROR: Invalid boot image pagesize. Device pagesize: %d, Image pagesize: %d\n",page_size,hdr->page_size);
1079                 return -1;
1080         }
1081
1082         /*
1083          * Update the kernel/ramdisk/tags address if the boot image header
1084          * has default values, these default values come from mkbootimg when
1085          * the boot image is flashed using fastboot flash:raw
1086          */
1087         update_ker_tags_rdisk_addr(hdr);
1088
1089         /* Get virtual addresses since the hdr saves physical addresses. */
1090         hdr->kernel_addr = VA((addr_t)(hdr->kernel_addr));
1091         hdr->ramdisk_addr = VA((addr_t)(hdr->ramdisk_addr));
1092         hdr->tags_addr = VA((addr_t)(hdr->tags_addr));
1093
1094         kernel_actual  = ROUND_TO_PAGE(hdr->kernel_size,  page_mask);
1095         ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
1096
1097         /* Check if the addresses in the header are valid. */
1098         if (check_aboot_addr_range_overlap(hdr->kernel_addr, kernel_actual) ||
1099                 check_aboot_addr_range_overlap(hdr->ramdisk_addr, ramdisk_actual))
1100         {
1101                 dprintf(CRITICAL, "kernel/ramdisk addresses overlap with aboot addresses.\n");
1102                 return -1;
1103         }
1104
1105 #ifndef DEVICE_TREE
1106                 if (check_aboot_addr_range_overlap(hdr->tags_addr, MAX_TAGS_SIZE))
1107                 {
1108                         dprintf(CRITICAL, "Tags addresses overlap with aboot addresses.\n");
1109                         return -1;
1110                 }
1111 #endif
1112
1113         /* Authenticate Kernel */
1114         if(target_use_signed_kernel() && (!device.is_unlocked))
1115         {
1116                 image_addr = (unsigned char *)target_get_scratch_address();
1117                 offset = 0;
1118
1119 #if DEVICE_TREE
1120                 dt_actual = ROUND_TO_PAGE(hdr->dt_size, page_mask);
1121
1122                 if (UINT_MAX < ((uint64_t)kernel_actual + (uint64_t)ramdisk_actual+ (uint64_t)dt_actual + page_size)) {
1123                         dprintf(CRITICAL, "Integer overflow detected in bootimage header fields\n");
1124                         return -1;
1125                 }
1126
1127                 imagesize_actual = (page_size + kernel_actual + ramdisk_actual + dt_actual);
1128
1129                 if (check_aboot_addr_range_overlap(hdr->tags_addr, hdr->dt_size))
1130                 {
1131                         dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
1132                         return -1;
1133                 }
1134 #else
1135                 if (UINT_MAX < ((uint64_t)kernel_actual + (uint64_t)ramdisk_actual+ page_size)) {
1136                         dprintf(CRITICAL, "Integer overflow detected in bootimage header fields\n");
1137                         return -1;
1138                 }
1139                 imagesize_actual = (page_size + kernel_actual + ramdisk_actual);
1140 #endif
1141
1142                 dprintf(INFO, "Loading boot image (%d): start\n", imagesize_actual);
1143                 bs_set_timestamp(BS_KERNEL_LOAD_START);
1144
1145                 /* Read image without signature */
1146                 if (flash_read(ptn, offset, (void *)image_addr, imagesize_actual))
1147                 {
1148                         dprintf(CRITICAL, "ERROR: Cannot read boot image\n");
1149                                 return -1;
1150                 }
1151
1152                 dprintf(INFO, "Loading boot image (%d): done\n", imagesize_actual);
1153                 bs_set_timestamp(BS_KERNEL_LOAD_DONE);
1154
1155                 offset = imagesize_actual;
1156                 /* Read signature */
1157                 if (flash_read(ptn, offset, (void *)(image_addr + offset), page_size))
1158                 {
1159                         dprintf(CRITICAL, "ERROR: Cannot read boot image signature\n");
1160                         return -1;
1161                 }
1162
1163                 //verify_signed_bootimg(image_addr, imagesize_actual);
1164
1165                 /* Move kernel and ramdisk to correct address */
1166                 memmove((void*) hdr->kernel_addr, (char *)(image_addr + page_size), hdr->kernel_size);
1167                 memmove((void*) hdr->ramdisk_addr, (char *)(image_addr + page_size + kernel_actual), hdr->ramdisk_size);
1168 #if DEVICE_TREE
1169                 /* Validate and Read device device tree in the "tags_add */
1170                 if (check_aboot_addr_range_overlap(hdr->tags_addr, dt_entry.size))
1171                 {
1172                         dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
1173                         return -1;
1174                 }
1175
1176                 memmove((void*) hdr->tags_addr, (char *)(image_addr + page_size + kernel_actual + ramdisk_actual), hdr->dt_size);
1177 #endif
1178
1179                 /* Make sure everything from scratch address is read before next step!*/
1180                 if(device.is_tampered)
1181                 {
1182                         write_device_info_flash(&device);
1183                 }
1184 #if USE_PCOM_SECBOOT
1185                 set_tamper_flag(device.is_tampered);
1186 #endif
1187         }
1188         else
1189         {
1190                 offset = page_size;
1191
1192                 kernel_actual = ROUND_TO_PAGE(hdr->kernel_size, page_mask);
1193                 ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
1194                 second_actual = ROUND_TO_PAGE(hdr->second_size, page_mask);
1195
1196                 dprintf(INFO, "Loading boot image (%d): start\n",
1197                                 kernel_actual + ramdisk_actual);
1198                 bs_set_timestamp(BS_KERNEL_LOAD_START);
1199
1200                 if (flash_read(ptn, offset, (void *)hdr->kernel_addr, kernel_actual)) {
1201                         dprintf(CRITICAL, "ERROR: Cannot read kernel image\n");
1202                         return -1;
1203                 }
1204                 offset += kernel_actual;
1205
1206                 if (flash_read(ptn, offset, (void *)hdr->ramdisk_addr, ramdisk_actual)) {
1207                         dprintf(CRITICAL, "ERROR: Cannot read ramdisk image\n");
1208                         return -1;
1209                 }
1210                 offset += ramdisk_actual;
1211
1212                 dprintf(INFO, "Loading boot image (%d): done\n",
1213                                 kernel_actual + ramdisk_actual);
1214                 bs_set_timestamp(BS_KERNEL_LOAD_DONE);
1215
1216                 if(hdr->second_size != 0) {
1217                         offset += second_actual;
1218                         /* Second image loading not implemented. */
1219                         ASSERT(0);
1220                 }
1221
1222 #if DEVICE_TREE
1223                 if(hdr->dt_size != 0) {
1224
1225                         /* Read the device tree table into buffer */
1226                         if(flash_read(ptn, offset, (void *) dt_buf, page_size)) {
1227                                 dprintf(CRITICAL, "ERROR: Cannot read the Device Tree Table\n");
1228                                 return -1;
1229                         }
1230
1231                         table = (struct dt_table*) dt_buf;
1232
1233                         if (dev_tree_validate(table, hdr->page_size, &dt_hdr_size) != 0) {
1234                                 dprintf(CRITICAL, "ERROR: Cannot validate Device Tree Table \n");
1235                                 return -1;
1236                         }
1237
1238                         table = (struct dt_table*) memalign(CACHE_LINE, dt_hdr_size);
1239                         if (!table)
1240                                 return -1;
1241
1242                         /* Read the entire device tree table into buffer */
1243                         if(flash_read(ptn, offset, (void *)table, dt_hdr_size)) {
1244                                 dprintf(CRITICAL, "ERROR: Cannot read the Device Tree Table\n");
1245                                 return -1;
1246                         }
1247
1248
1249                         /* Find index of device tree within device tree table */
1250                         if(dev_tree_get_entry_info(table, &dt_entry) != 0){
1251                                 dprintf(CRITICAL, "ERROR: Getting device tree address failed\n");
1252                                 return -1;
1253                         }
1254
1255                         /* Validate and Read device device tree in the "tags_add */
1256                         if (check_aboot_addr_range_overlap(hdr->tags_addr, dt_entry.size))
1257                         {
1258                                 dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
1259                                 return -1;
1260                         }
1261
1262                         /* Read device device tree in the "tags_add */
1263                         if(flash_read(ptn, offset + dt_entry.offset,
1264                                                  (void *)hdr->tags_addr, dt_entry.size)) {
1265                                 dprintf(CRITICAL, "ERROR: Cannot read device tree\n");
1266                                 return -1;
1267                         }
1268                 }
1269 #endif
1270
1271         }
1272 continue_boot:
1273
1274         /* TODO: create/pass atags to kernel */
1275
1276         boot_linux((void *)hdr->kernel_addr, (void *)hdr->tags_addr,
1277                    (const char *)hdr->cmdline, board_machtype(),
1278                    (void *)hdr->ramdisk_addr, hdr->ramdisk_size);
1279
1280         return 0;
1281 }
1282
1283 BUF_DMA_ALIGN(info_buf, 4096);
1284 void write_device_info_mmc(device_info *dev)
1285 {
1286         struct device_info *info = (void*) info_buf;
1287         unsigned long long ptn = 0;
1288         unsigned long long size;
1289         int index = INVALID_PTN;
1290
1291         index = partition_get_index("aboot");
1292         ptn = partition_get_offset(index);
1293         if(ptn == 0)
1294         {
1295                 return;
1296         }
1297
1298         size = partition_get_size(index);
1299
1300         memcpy(info, dev, sizeof(device_info));
1301
1302         if(mmc_write((ptn + size - 512), 512, (void *)info_buf))
1303         {
1304                 dprintf(CRITICAL, "ERROR: Cannot write device info\n");
1305                 return;
1306         }
1307 }
1308
1309 void read_device_info_mmc(device_info *dev)
1310 {
1311         struct device_info *info = (void*) info_buf;
1312         unsigned long long ptn = 0;
1313         unsigned long long size;
1314         int index = INVALID_PTN;
1315
1316         index = partition_get_index("aboot");
1317         ptn = partition_get_offset(index);
1318         if(ptn == 0)
1319         {
1320                 return;
1321         }
1322
1323         size = partition_get_size(index);
1324
1325         if(mmc_read((ptn + size - 512), (void *)info_buf, 512))
1326         {
1327                 dprintf(CRITICAL, "ERROR: Cannot read device info\n");
1328                 return;
1329         }
1330
1331         if (memcmp(info->magic, DEVICE_MAGIC, DEVICE_MAGIC_SIZE))
1332         {
1333                 memcpy(info->magic, DEVICE_MAGIC, DEVICE_MAGIC_SIZE);
1334                 info->is_unlocked = 0;
1335                 info->is_tampered = 0;
1336                 info->charger_screen_enabled = 1;
1337
1338                 write_device_info_mmc(info);
1339         }
1340         memcpy(dev, info, sizeof(device_info));
1341 }
1342
1343 void write_device_info_flash(device_info *dev)
1344 {
1345         struct device_info *info = (void *) info_buf;
1346         struct ptentry *ptn;
1347         struct ptable *ptable;
1348
1349         ptable = flash_get_ptable();
1350         if (ptable == NULL)
1351         {
1352                 dprintf(CRITICAL, "ERROR: Partition table not found\n");
1353                 return;
1354         }
1355
1356         ptn = ptable_find(ptable, "devinfo");
1357         if (ptn == NULL)
1358         {
1359                 dprintf(CRITICAL, "ERROR: No boot partition found\n");
1360                         return;
1361         }
1362
1363         memcpy(info, dev, sizeof(device_info));
1364
1365         if (flash_write(ptn, 0, (void *)info_buf, page_size))
1366         {
1367                 dprintf(CRITICAL, "ERROR: Cannot write device info\n");
1368                         return;
1369         }
1370 }
1371
1372 void read_device_info_flash(device_info *dev)
1373 {
1374         struct device_info *info = (void*) info_buf;
1375         struct ptentry *ptn;
1376         struct ptable *ptable;
1377
1378         ptable = flash_get_ptable();
1379         if (ptable == NULL)
1380         {
1381                 dprintf(CRITICAL, "ERROR: Partition table not found\n");
1382                 return;
1383         }
1384
1385         ptn = ptable_find(ptable, "devinfo");
1386         if (ptn == NULL)
1387         {
1388                 dprintf(CRITICAL, "ERROR: No boot partition found\n");
1389                         return;
1390         }
1391
1392         if (flash_read(ptn, 0, (void *)info_buf, page_size))
1393         {
1394                 dprintf(CRITICAL, "ERROR: Cannot write device info\n");
1395                         return;
1396         }
1397
1398         if (memcmp(info->magic, DEVICE_MAGIC, DEVICE_MAGIC_SIZE))
1399         {
1400                 memcpy(info->magic, DEVICE_MAGIC, DEVICE_MAGIC_SIZE);
1401                 info->is_unlocked = 0;
1402                 info->is_tampered = 0;
1403                 write_device_info_flash(info);
1404         }
1405         memcpy(dev, info, sizeof(device_info));
1406 }
1407
1408 void write_device_info(device_info *dev)
1409 {
1410         if(target_is_emmc_boot())
1411         {
1412                 write_device_info_mmc(dev);
1413         }
1414         else
1415         {
1416                 write_device_info_flash(dev);
1417         }
1418 }
1419
1420 void read_device_info(device_info *dev)
1421 {
1422         if(target_is_emmc_boot())
1423         {
1424                 read_device_info_mmc(dev);
1425         }
1426         else
1427         {
1428                 read_device_info_flash(dev);
1429         }
1430 }
1431
1432 void reset_device_info()
1433 {
1434         dprintf(ALWAYS, "reset_device_info called.");
1435         device.is_tampered = 0;
1436         write_device_info(&device);
1437 }
1438
1439 void set_device_root()
1440 {
1441         dprintf(ALWAYS, "set_device_root called.");
1442         device.is_tampered = 1;
1443         write_device_info(&device);
1444 }
1445
1446 #if DEVICE_TREE
1447 int copy_dtb(uint8_t *boot_image_start)
1448 {
1449         uint32 dt_image_offset = 0;
1450         uint32_t n;
1451         struct dt_table *table;
1452         struct dt_entry dt_entry;
1453         uint32_t dt_hdr_size;
1454
1455         struct boot_img_hdr *hdr = (struct boot_img_hdr *) (boot_image_start);
1456
1457         if(hdr->dt_size != 0) {
1458
1459                 /* add kernel offset */
1460                 dt_image_offset += page_size;
1461                 n = ROUND_TO_PAGE(hdr->kernel_size, page_mask);
1462                 dt_image_offset += n;
1463
1464                 /* add ramdisk offset */
1465                 n = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
1466                 dt_image_offset += n;
1467
1468                 /* add second offset */
1469                 if(hdr->second_size != 0) {
1470                         n = ROUND_TO_PAGE(hdr->second_size, page_mask);
1471                         dt_image_offset += n;
1472                 }
1473
1474                 /* offset now point to start of dt.img */
1475                 table = (struct dt_table*)(boot_image_start + dt_image_offset);
1476
1477                 if (dev_tree_validate(table, hdr->page_size, &dt_hdr_size) != 0) {
1478                         dprintf(CRITICAL, "ERROR: Cannot validate Device Tree Table \n");
1479                         return -1;
1480                 }
1481                 /* Find index of device tree within device tree table */
1482                 if(dev_tree_get_entry_info(table, &dt_entry) != 0){
1483                         dprintf(CRITICAL, "ERROR: Getting device tree address failed\n");
1484                         return -1;
1485                 }
1486
1487                 /* Validate and Read device device tree in the "tags_add */
1488                 if (check_aboot_addr_range_overlap(hdr->tags_addr, dt_entry.size))
1489                 {
1490                         dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\n");
1491                         return -1;
1492                 }
1493
1494                 /* Read device device tree in the "tags_add */
1495                 memmove((void*) hdr->tags_addr,
1496                                 boot_image_start + dt_image_offset +  dt_entry.offset,
1497                                 dt_entry.size);
1498         } else
1499                 return -1;
1500
1501         /* Everything looks fine. Return success. */
1502         return 0;
1503 }
1504 #endif
1505
1506 void cmd_boot(const char *arg, void *data, unsigned sz)
1507 {
1508         unsigned kernel_actual;
1509         unsigned ramdisk_actual;
1510         uint32_t image_actual;
1511         uint32_t dt_actual = 0;
1512         uint32_t sig_actual = SIGNATURE_SIZE;
1513         struct boot_img_hdr *hdr;
1514         char *ptr = ((char*) data);
1515         int ret = 0;
1516         uint8_t dtb_copied = 0;
1517
1518         if (sz < sizeof(hdr)) {
1519                 fastboot_fail("invalid bootimage header");
1520                 return;
1521         }
1522
1523         hdr = (struct boot_img_hdr *)data;
1524
1525         /* ensure commandline is terminated */
1526         hdr->cmdline[BOOT_ARGS_SIZE-1] = 0;
1527
1528         if(target_is_emmc_boot() && hdr->page_size) {
1529                 page_size = hdr->page_size;
1530                 page_mask = page_size - 1;
1531         }
1532
1533         kernel_actual = ROUND_TO_PAGE(hdr->kernel_size, page_mask);
1534         ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
1535 #if DEVICE_TREE
1536         dt_actual = ROUND_TO_PAGE(hdr->dt_size, page_mask);
1537 #endif
1538
1539         image_actual = ADD_OF(page_size, kernel_actual);
1540         image_actual = ADD_OF(image_actual, ramdisk_actual);
1541         image_actual = ADD_OF(image_actual, dt_actual);
1542
1543         if (target_use_signed_kernel() && (!device.is_unlocked))
1544                 image_actual = ADD_OF(image_actual, sig_actual);
1545
1546         /* sz should have atleast raw boot image */
1547         if (image_actual > sz) {
1548                 fastboot_fail("bootimage: incomplete or not signed");
1549                 return;
1550         }
1551
1552         /* Verify the boot image
1553          * device & page_size are initialized in aboot_init
1554          */
1555         if (target_use_signed_kernel() && (!device.is_unlocked))
1556                 /* Pass size excluding signature size, otherwise we would try to
1557                  * access signature beyond its length
1558                  */
1559                 //verify_signed_bootimg((uint32_t)data, (image_actual - sig_actual));
1560
1561         /*
1562          * Update the kernel/ramdisk/tags address if the boot image header
1563          * has default values, these default values come from mkbootimg when
1564          * the boot image is flashed using fastboot flash:raw
1565          */
1566         update_ker_tags_rdisk_addr(hdr);
1567
1568         /* Get virtual addresses since the hdr saves physical addresses. */
1569         hdr->kernel_addr = VA(hdr->kernel_addr);
1570         hdr->ramdisk_addr = VA(hdr->ramdisk_addr);
1571         hdr->tags_addr = VA(hdr->tags_addr);
1572
1573         /* Check if the addresses in the header are valid. */
1574         if (check_aboot_addr_range_overlap(hdr->kernel_addr, kernel_actual) ||
1575                 check_aboot_addr_range_overlap(hdr->ramdisk_addr, ramdisk_actual))
1576         {
1577                 dprintf(CRITICAL, "kernel/ramdisk addresses overlap with aboot addresses.\n");
1578                 return;
1579         }
1580
1581 #if DEVICE_TREE
1582         /* find correct dtb and copy it to right location */
1583         ret = copy_dtb(data);
1584
1585         dtb_copied = !ret ? 1 : 0;
1586 #else
1587         if (check_aboot_addr_range_overlap(hdr->tags_addr, MAX_TAGS_SIZE))
1588         {
1589                 dprintf(CRITICAL, "Tags addresses overlap with aboot addresses.\n");
1590                 return;
1591         }
1592 #endif
1593
1594         /* Load ramdisk & kernel */
1595         memmove((void*) hdr->ramdisk_addr, ptr + page_size + kernel_actual, hdr->ramdisk_size);
1596         memmove((void*) hdr->kernel_addr, ptr + page_size, hdr->kernel_size);
1597
1598 #if DEVICE_TREE
1599         /*
1600          * If dtb is not found look for appended DTB in the kernel.
1601          * If appended dev tree is found, update the atags with
1602          * memory address to the DTB appended location on RAM.
1603          * Else update with the atags address in the kernel header
1604          */
1605         if (!dtb_copied) {
1606                 void *dtb;
1607                 dtb = dev_tree_appended((void *)hdr->kernel_addr, hdr->kernel_size,
1608                                         (void *)hdr->tags_addr);
1609                 if (!dtb) {
1610                         fastboot_fail("dtb not found");
1611                         return;
1612                 }
1613         }
1614 #endif
1615
1616 #ifndef DEVICE_TREE
1617         if (check_aboot_addr_range_overlap(hdr->tags_addr, MAX_TAGS_SIZE))
1618         {
1619                 dprintf(CRITICAL, "Tags addresses overlap with aboot addresses.\n");
1620                 return;
1621         }
1622 #endif
1623
1624         fastboot_okay("");
1625         udc_stop();
1626
1627         boot_linux((void*) hdr->kernel_addr, (void*) hdr->tags_addr,
1628                    (const char*) hdr->cmdline, board_machtype(),
1629                    (void*) hdr->ramdisk_addr, hdr->ramdisk_size);
1630 }
1631
1632 void cmd_erase_nand(const char *arg, void *data, unsigned sz)
1633 {
1634         struct ptentry *ptn;
1635         struct ptable *ptable;
1636
1637         ptable = flash_get_ptable();
1638         if (ptable == NULL) {
1639                 fastboot_fail("partition table doesn't exist");
1640                 return;
1641         }
1642
1643         ptn = ptable_find(ptable, arg);
1644         if (ptn == NULL) {
1645                 fastboot_fail("unknown partition name");
1646                 return;
1647         }
1648
1649         if (flash_erase(ptn)) {
1650                 fastboot_fail("failed to erase partition");
1651                 return;
1652         }
1653         fastboot_okay("");
1654 }
1655
1656
1657 void cmd_erase_mmc(const char *arg, void *data, unsigned sz)
1658 {
1659         BUF_DMA_ALIGN(out, DEFAULT_ERASE_SIZE);
1660         unsigned long long ptn = 0;
1661         unsigned long long size = 0;
1662         int index = INVALID_PTN;
1663
1664         index = partition_get_index(arg);
1665         ptn = partition_get_offset(index);
1666         size = partition_get_size(index);
1667
1668         if(ptn == 0) {
1669                 fastboot_fail("Partition table doesn't exist\n");
1670                 return;
1671         }
1672
1673 #if MMC_SDHCI_SUPPORT
1674         if (mmc_erase_card(ptn, size)) {
1675                 fastboot_fail("failed to erase partition\n");
1676                 return;
1677         }
1678 #else
1679         size = partition_get_size(index);
1680         if (size > DEFAULT_ERASE_SIZE)
1681                 size = DEFAULT_ERASE_SIZE;
1682
1683         /* Simple inefficient version of erase. Just writing
1684        0 in first several blocks */
1685         if (mmc_write(ptn , size, (unsigned int *)out)) {
1686                 fastboot_fail("failed to erase partition");
1687                 return;
1688         }
1689 #endif
1690         fastboot_okay("");
1691 }
1692
1693 void cmd_erase(const char *arg, void *data, unsigned sz)
1694 {
1695         if(target_is_emmc_boot())
1696                 cmd_erase_mmc(arg, data, sz);
1697         else
1698                 cmd_erase_nand(arg, data, sz);
1699 }
1700
1701 void cmd_flash_mmc_img(const char *arg, void *data, unsigned sz)
1702 {
1703         unsigned long long ptn = 0;
1704         unsigned long long size = 0;
1705         int index = INVALID_PTN;
1706
1707         if (!strcmp(arg, "partition"))
1708         {
1709                 dprintf(INFO, "Attempt to write partition image.\n");
1710                 if (write_partition(sz, (unsigned char *) data)) {
1711                         fastboot_fail("failed to write partition");
1712                         return;
1713                 }
1714         }
1715         else
1716         {
1717                 index = partition_get_index(arg);
1718                 ptn = partition_get_offset(index);
1719                 if(ptn == 0) {
1720                         fastboot_fail("partition table doesn't exist");
1721                         return;
1722                 }
1723
1724                 if (!strcmp(arg, "boot") || !strcmp(arg, "recovery")) {
1725                         if (memcmp((void *)data, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
1726                                 fastboot_fail("image is not a boot image");
1727                                 return;
1728                         }
1729                 }
1730
1731                 size = partition_get_size(index);
1732                 if (ROUND_TO_PAGE(sz,511) > size) {
1733                         fastboot_fail("size too large");
1734                         return;
1735                 }
1736                 else if (mmc_write(ptn , sz, (unsigned int *)data)) {
1737                         fastboot_fail("flash write failure");
1738                         return;
1739                 }
1740         }
1741         fastboot_okay("");
1742         return;
1743 }
1744
1745 void cmd_flash_mmc_sparse_img(const char *arg, void *data, unsigned sz)
1746 {
1747         unsigned int chunk;
1748         unsigned int chunk_data_sz;
1749         sparse_header_t *sparse_header;
1750         chunk_header_t *chunk_header;
1751         uint32_t total_blocks = 0;
1752         unsigned long long ptn = 0;
1753         unsigned long long size = 0;
1754         int index = INVALID_PTN;
1755         /*End of the sparse image address*/
1756         uint32_t data_end = (uint32_t)data + sz;
1757
1758         index = partition_get_index(arg);
1759         ptn = partition_get_offset(index);
1760         if(ptn == 0) {
1761                 fastboot_fail("partition table doesn't exist");
1762                 return;
1763         }
1764
1765         size = partition_get_size(index);
1766         if (sz < sizeof(sparse_header_t)) {
1767                 fastboot_fail("size too low");
1768                 return;
1769         }
1770
1771         /* Read and skip over sparse image header */
1772         sparse_header = (sparse_header_t *) data;
1773         if (((uint64_t)sparse_header->total_blks * (uint64_t)sparse_header->blk_sz) > size) {
1774                 fastboot_fail("size too large");
1775                 return;
1776         }
1777
1778         data += sparse_header->file_hdr_sz;
1779         if (data_end < (uint32_t)data) {
1780                 fastboot_fail("buffer overreads occured due to invalid sparse header");
1781                 return;
1782         }
1783  
1784         if(sparse_header->file_hdr_sz > sizeof(sparse_header_t))
1785         {
1786                 /* Skip the remaining bytes in a header that is longer than
1787                  * we expected.
1788                  */
1789                 data += (sparse_header->file_hdr_sz - sizeof(sparse_header_t));
1790         }
1791         if (data_end < (uint32_t)data) {
1792                 fastboot_fail("buffer overreads occured due to invalid sparse header");
1793                 return;
1794         }
1795
1796         dprintf (SPEW, "=== Sparse Image Header ===\n");
1797         dprintf (SPEW, "magic: 0x%x\n", sparse_header->magic);
1798         dprintf (SPEW, "major_version: 0x%x\n", sparse_header->major_version);
1799         dprintf (SPEW, "minor_version: 0x%x\n", sparse_header->minor_version);
1800         dprintf (SPEW, "file_hdr_sz: %d\n", sparse_header->file_hdr_sz);
1801         dprintf (SPEW, "chunk_hdr_sz: %d\n", sparse_header->chunk_hdr_sz);
1802         dprintf (SPEW, "blk_sz: %d\n", sparse_header->blk_sz);
1803         dprintf (SPEW, "total_blks: %d\n", sparse_header->total_blks);
1804         dprintf (SPEW, "total_chunks: %d\n", sparse_header->total_chunks);
1805
1806         /* Start processing chunks */
1807         for (chunk=0; chunk<sparse_header->total_chunks; chunk++)
1808         {
1809                 /* Make sure the total image size does not exceed the partition size */
1810                 if(((uint64_t)total_blocks * (uint64_t)sparse_header->blk_sz) >= size) {
1811                         fastboot_fail("size too large");
1812                         return;
1813                 }
1814                 /* Read and skip over chunk header */
1815                 chunk_header = (chunk_header_t *) data;
1816                 data += sizeof(chunk_header_t);
1817
1818                 dprintf (SPEW, "=== Chunk Header ===\n");
1819                 dprintf (SPEW, "chunk_type: 0x%x\n", chunk_header->chunk_type);
1820                 dprintf (SPEW, "chunk_data_sz: 0x%x\n", chunk_header->chunk_sz);
1821                 dprintf (SPEW, "total_size: 0x%x\n", chunk_header->total_sz);
1822
1823                 if(sparse_header->chunk_hdr_sz > sizeof(chunk_header_t))
1824                 {
1825                         /* Skip the remaining bytes in a header that is longer than
1826                          * we expected.
1827                          */
1828                         data += (sparse_header->chunk_hdr_sz - sizeof(chunk_header_t));
1829                 }
1830
1831                 chunk_data_sz = sparse_header->blk_sz * chunk_header->chunk_sz;
1832
1833                 /* Make sure multiplication does not overflow uint32 size */
1834                 if (sparse_header->blk_sz && (chunk_header->chunk_sz != chunk_data_sz / sparse_header->blk_sz))
1835                 {
1836                         fastboot_fail("Bogus size sparse and chunk header");
1837                         return;
1838                 }
1839
1840                 /* Make sure that the chunk size calculated from sparse image does not
1841                  * exceed partition size
1842                  */
1843                 if ((uint64_t)total_blocks * (uint64_t)sparse_header->blk_sz + chunk_data_sz > size)
1844                 {
1845                         fastboot_fail("Chunk data size exceeds partition size");
1846                         return;
1847                 }
1848
1849                 switch (chunk_header->chunk_type)
1850                 {
1851                         case CHUNK_TYPE_RAW:
1852                         if(chunk_header->total_sz != (sparse_header->chunk_hdr_sz +
1853                                                                                         chunk_data_sz))
1854                         {
1855                                 fastboot_fail("Bogus chunk size for chunk type Raw");
1856                                 return;
1857                         }
1858
1859                         if(mmc_write(ptn + ((uint64_t)total_blocks*sparse_header->blk_sz),
1860                                                 chunk_data_sz,
1861                                                 (unsigned int*)data))
1862                         {
1863                                 fastboot_fail("flash write failure");
1864                                 return;
1865                         }
1866                         if(total_blocks > (UINT_MAX - chunk_header->chunk_sz)) {
1867                                 fastboot_fail("Bogus size for RAW chunk type");
1868                                 return;
1869                         }
1870                         total_blocks += chunk_header->chunk_sz;
1871                         data += chunk_data_sz;
1872                         break;
1873
1874                         case CHUNK_TYPE_DONT_CARE:
1875                         if(total_blocks > (UINT_MAX - chunk_header->chunk_sz)) {
1876                                 fastboot_fail("bogus size for chunk DONT CARE type");
1877                                 return;
1878                         }
1879                         total_blocks += chunk_header->chunk_sz;
1880                         break;
1881
1882                         case CHUNK_TYPE_CRC:
1883                         if(chunk_header->total_sz != sparse_header->chunk_hdr_sz)
1884                         {
1885                                 fastboot_fail("Bogus chunk size for chunk type Dont Care");
1886                                 return;
1887                         }
1888                         if(total_blocks > (UINT_MAX - chunk_header->chunk_sz)) {
1889                                 fastboot_fail("bogus size for chunk CRC type");
1890                                 return;
1891                         }
1892                         total_blocks += chunk_header->chunk_sz;
1893                         data += chunk_data_sz;
1894                         break;
1895
1896                         default:
1897                         fastboot_fail("Unknown chunk type");
1898                         return;
1899                 }
1900         }
1901
1902         dprintf(INFO, "Wrote %d blocks, expected to write %d blocks\n",
1903                                         total_blocks, sparse_header->total_blks);
1904
1905         if(total_blocks != sparse_header->total_blks)
1906         {
1907                 fastboot_fail("sparse image write failure");
1908         }
1909
1910         fastboot_okay("");
1911         return;
1912 }
1913
1914 void cmd_flash_mmc(const char *arg, void *data, unsigned sz)
1915 {
1916         sparse_header_t *sparse_header;
1917         /* 8 Byte Magic + 2048 Byte xml + Encrypted Data */
1918         unsigned int *magic_number = (unsigned int *) data;
1919
1920 #ifdef SSD_ENABLE
1921         int              ret=0;
1922         uint32           major_version=0;
1923         uint32           minor_version=0;
1924
1925         ret = scm_svc_version(&major_version,&minor_version);
1926         if(!ret)
1927         {
1928                 if(major_version >= 2)
1929                 {
1930                         if( !strcmp(arg, "ssd") || !strcmp(arg, "tqs") )
1931                         {
1932                                 ret = encrypt_scm((uint32 **) &data, &sz);
1933                                 if (ret != 0) {
1934                                         dprintf(CRITICAL, "ERROR: Encryption Failure\n");
1935                                         return;
1936                                 }
1937
1938                                 /* Protect only for SSD */
1939                                 if (!strcmp(arg, "ssd")) {
1940                                         ret = scm_protect_keystore((uint32 *) data, sz);
1941                                         if (ret != 0) {
1942                                                 dprintf(CRITICAL, "ERROR: scm_protect_keystore Failed\n");
1943                                                 return;
1944                                         }
1945                                 }
1946                         }
1947                         else
1948                         {
1949                                 ret = decrypt_scm_v2((uint32 **) &data, &sz);
1950                                 if(ret != 0)
1951                                 {
1952                                         dprintf(CRITICAL,"ERROR: Decryption Failure\n");
1953                                         return;
1954                                 }
1955                         }
1956                 }
1957                 else
1958                 {
1959                         if (magic_number[0] == DECRYPT_MAGIC_0 &&
1960                         magic_number[1] == DECRYPT_MAGIC_1)
1961                         {
1962                                 ret = decrypt_scm((uint32 **) &data, &sz);
1963                                 if (ret != 0) {
1964                                         dprintf(CRITICAL, "ERROR: Invalid secure image\n");
1965                                         return;
1966                                 }
1967                         }
1968                         else if (magic_number[0] == ENCRYPT_MAGIC_0 &&
1969                                 magic_number[1] == ENCRYPT_MAGIC_1)
1970                         {
1971                                 ret = encrypt_scm((uint32 **) &data, &sz);
1972                                 if (ret != 0) {
1973                                         dprintf(CRITICAL, "ERROR: Encryption Failure\n");
1974                                         return;
1975                                 }
1976                         }
1977                 }
1978         }
1979         else
1980         {
1981                 dprintf(CRITICAL,"INVALID SVC Version\n");
1982                 return;
1983         }
1984 #endif /* SSD_ENABLE */
1985
1986         sparse_header = (sparse_header_t *) data;
1987         if (sparse_header->magic != SPARSE_HEADER_MAGIC)
1988                 cmd_flash_mmc_img(arg, data, sz);
1989         else
1990                 cmd_flash_mmc_sparse_img(arg, data, sz);
1991         return;
1992 }
1993
1994 void cmd_flash_nand(const char *arg, void *data, unsigned sz)
1995 {
1996         struct ptentry *ptn;
1997         struct ptable *ptable;
1998         unsigned extra = 0;
1999
2000         ptable = flash_get_ptable();
2001         if (ptable == NULL) {
2002                 fastboot_fail("partition table doesn't exist");
2003                 return;
2004         }
2005
2006         ptn = ptable_find(ptable, arg);
2007         if (ptn == NULL) {
2008                 fastboot_fail("unknown partition name");
2009                 return;
2010         }
2011
2012         if (!strcmp(ptn->name, "boot") || !strcmp(ptn->name, "recovery")) {
2013                 if (memcmp((void *)data, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
2014                         fastboot_fail("image is not a boot image");
2015                         return;
2016                 }
2017         }
2018
2019         if (!strcmp(ptn->name, "system")
2020                 || !strcmp(ptn->name, "userdata")
2021                 || !strcmp(ptn->name, "persist")
2022                 || !strcmp(ptn->name, "recoveryfs")) {
2023                 if (flash_ecc_bch_enabled())
2024                         /* Spare data bytes for 8 bit ECC increased by 4 */
2025                         extra = ((page_size >> 9) * 20);
2026                 else
2027                         extra = ((page_size >> 9) * 16);
2028         } else
2029                 sz = ROUND_TO_PAGE(sz, page_mask);
2030
2031         dprintf(INFO, "writing %d bytes to '%s'\n", sz, ptn->name);
2032         if (flash_write(ptn, extra, data, sz)) {
2033                 fastboot_fail("flash write failure");
2034                 return;
2035         }
2036         dprintf(INFO, "partition '%s' updated\n", ptn->name);
2037         fastboot_okay("");
2038 }
2039
2040 void cmd_flash(const char *arg, void *data, unsigned sz)
2041 {
2042         if(target_is_emmc_boot())
2043                 cmd_flash_mmc(arg, data, sz);
2044         else
2045                 cmd_flash_nand(arg, data, sz);
2046 }
2047
2048 void cmd_continue(const char *arg, void *data, unsigned sz)
2049 {
2050         fastboot_okay("");
2051         udc_stop();
2052         if (target_is_emmc_boot())
2053         {
2054                 boot_linux_from_mmc();
2055         }
2056         else
2057         {
2058                 boot_linux_from_flash();
2059         }
2060 }
2061
2062 void cmd_reboot(const char *arg, void *data, unsigned sz)
2063 {
2064         dprintf(INFO, "rebooting the device\n");
2065         fastboot_okay("");
2066         reboot_device(0);
2067 }
2068
2069 void cmd_reboot_bootloader(const char *arg, void *data, unsigned sz)
2070 {
2071         dprintf(INFO, "rebooting the device\n");
2072         fastboot_okay("");
2073         reboot_device(FASTBOOT_MODE);
2074 }
2075
2076 void cmd_oem_enable_charger_screen(const char *arg, void *data, unsigned size)
2077 {
2078         dprintf(INFO, "Enabling charger screen check\n");
2079         device.charger_screen_enabled = 1;
2080         write_device_info(&device);
2081         fastboot_okay("");
2082 }
2083
2084 void cmd_oem_disable_charger_screen(const char *arg, void *data, unsigned size)
2085 {
2086         dprintf(INFO, "Disabling charger screen check\n");
2087         device.charger_screen_enabled = 0;
2088         write_device_info(&device);
2089         fastboot_okay("");
2090 }
2091
2092 void cmd_oem_select_display_panel(const char *arg, void *data, unsigned size)
2093 {
2094         dprintf(INFO, "Selecting display panel %s\n", arg);
2095         if (arg)
2096                 strlcpy(device.display_panel, arg,
2097                         sizeof(device.display_panel));
2098         write_device_info(&device);
2099         fastboot_okay("");
2100 }
2101
2102 void cmd_oem_unlock(const char *arg, void *data, unsigned sz)
2103 {
2104         if(!device.is_unlocked)
2105         {
2106                 device.is_unlocked = 1;
2107                 write_device_info(&device);
2108         }
2109         fastboot_okay("");
2110 }
2111
2112 void cmd_oem_devinfo(const char *arg, void *data, unsigned sz)
2113 {
2114         char response[128];
2115         snprintf(response, sizeof(response), "\tDevice tampered: %s", (device.is_tampered ? "true" : "false"));
2116         fastboot_info(response);
2117         snprintf(response, sizeof(response), "\tDevice unlocked: %s", (device.is_unlocked ? "true" : "false"));
2118         fastboot_info(response);
2119         snprintf(response, sizeof(response), "\tCharger screen enabled: %s", (device.charger_screen_enabled ? "true" : "false"));
2120         fastboot_info(response);
2121         snprintf(response, sizeof(response), "\tDisplay panel: %s", (device.display_panel));
2122         fastboot_info(response);
2123         fastboot_okay("");
2124 }
2125
2126 void cmd_preflash(const char *arg, void *data, unsigned sz)
2127 {
2128         fastboot_okay("");
2129 }
2130
2131 static struct fbimage logo_header = {0};
2132 struct fbimage* splash_screen_flash();
2133
2134 int splash_screen_check_header(struct fbimage *logo)
2135 {
2136         if (memcmp(logo->header.magic, LOGO_IMG_MAGIC, 8))
2137                 return -1;
2138         if (logo->header.width == 0 || logo->header.height == 0)
2139                 return -1;
2140         return 0;
2141 }
2142
2143 struct fbimage* splash_screen_flash()
2144 {
2145         struct ptentry *ptn;
2146         struct ptable *ptable;
2147         struct fbcon_config *fb_display = NULL;
2148         struct fbimage *logo = &logo_header;
2149
2150
2151         ptable = flash_get_ptable();
2152         if (ptable == NULL) {
2153         dprintf(CRITICAL, "ERROR: Partition table not found\n");
2154         return NULL;
2155         }
2156         ptn = ptable_find(ptable, "splash");
2157         if (ptn == NULL) {
2158                 dprintf(CRITICAL, "ERROR: splash Partition not found\n");
2159                 return NULL;
2160         }
2161
2162         if (flash_read(ptn, 0,(unsigned int *) logo, sizeof(logo->header))) {
2163                 dprintf(CRITICAL, "ERROR: Cannot read boot image header\n");
2164                 return NULL;
2165         }
2166
2167         if (splash_screen_check_header(logo)) {
2168                 dprintf(CRITICAL, "ERROR: Boot image header invalid\n");
2169                 return NULL;
2170         }
2171
2172         fb_display = fbcon_display();
2173         if (fb_display) {
2174                 if ((logo->header.width != fb_display->width) || (logo->header.height != fb_display->height)) {
2175                         dprintf(CRITICAL, "Logo config doesn't match with fb config. Fall back to default logo\n");
2176                         return NULL;
2177                 }
2178                 uint8_t *base = (uint8_t *) fb_display->base;
2179                 if (flash_read(ptn + sizeof(logo->header), 0,
2180                         base,
2181                         ((((logo->header.width * logo->header.height * fb_display->bpp/8) + 511) >> 9) << 9))) {
2182                         fbcon_clear();
2183                         dprintf(CRITICAL, "ERROR: Cannot read splash image from partition\n");
2184                         return NULL;
2185                 }
2186                 logo->image = base;
2187         }
2188
2189         return logo;
2190 }
2191
2192 struct fbimage* splash_screen_mmc()
2193 {
2194         int index = INVALID_PTN;
2195         unsigned long long ptn = 0;
2196         struct fbcon_config *fb_display = NULL;
2197         struct fbimage *logo = &logo_header;
2198
2199         index = partition_get_index("splash");
2200         if (index == 0) {
2201                 dprintf(CRITICAL, "ERROR: splash Partition table not found\n");
2202                 return NULL;
2203         }
2204
2205         ptn = partition_get_offset(index);
2206         if (ptn == 0) {
2207                 dprintf(CRITICAL, "ERROR: splash Partition invalid\n");
2208                 return NULL;
2209         }
2210
2211         if (mmc_read(ptn, (unsigned int *) logo, sizeof(logo->header))) {
2212                 dprintf(CRITICAL, "ERROR: Cannot read splash image header\n");
2213                 return NULL;
2214         }
2215
2216         if (splash_screen_check_header(logo)) {
2217                 dprintf(CRITICAL, "ERROR: Splash image header invalid\n");
2218                 return NULL;
2219         }
2220
2221         fb_display = fbcon_display();
2222         if (fb_display) {
2223                 if ((logo->header.width != fb_display->width) || (logo->header.height != fb_display->height)) {
2224                         dprintf(CRITICAL, "Logo config doesn't match with fb config. Fall back default logo\n");
2225                         return NULL;
2226                 }
2227                 uint8_t *base = (uint8_t *) fb_display->base;
2228                 if (mmc_read(ptn + sizeof(logo->header),
2229                         base,
2230                         ((((logo->header.width * logo->header.height * fb_display->bpp/8) + 511) >> 9) << 9))) {
2231                         fbcon_clear();
2232                         dprintf(CRITICAL, "ERROR: Cannot read splash image from partition\n");
2233                         return NULL;
2234                 }
2235
2236                 logo->image = base;
2237         }
2238
2239         return logo;
2240 }
2241
2242
2243 struct fbimage* fetch_image_from_partition()
2244 {
2245         if (target_is_emmc_boot()) {
2246                 return splash_screen_mmc();
2247         } else {
2248                 return splash_screen_flash();
2249         }
2250 }
2251
2252 /* Get the size from partiton name */
2253 static void get_partition_size(const char *arg, char *response)
2254 {
2255         uint64_t ptn = 0;
2256         uint64_t size;
2257         int index = INVALID_PTN;
2258
2259         index = partition_get_index(arg);
2260
2261         if (index == INVALID_PTN)
2262         {
2263                 dprintf(CRITICAL, "Invalid partition index\n");
2264                 return;
2265         }
2266
2267         ptn = partition_get_offset(index);
2268
2269         if(!ptn)
2270         {
2271                 dprintf(CRITICAL, "Invalid partition name %s\n", arg);
2272                 return;
2273         }
2274
2275         size = partition_get_size(index);
2276
2277         snprintf(response, MAX_RSP_SIZE, "\t 0x%llx", size);
2278         return;
2279 }
2280
2281 /*
2282  * Publish the partition type & size info
2283  * fastboot getvar will publish the required information.
2284  * fastboot getvar partition_size:<partition_name>: partition size in hex
2285  * fastboot getvar partition_type:<partition_name>: partition type (ext/fat)
2286  */
2287 static void publish_getvar_partition_info(struct getvar_partition_info *info, uint8_t num_parts)
2288 {
2289         uint8_t i;
2290
2291         for (i = 0; i < num_parts; i++) {
2292                 get_partition_size(info[i].part_name, info[i].size_response);
2293
2294                 if (strlcat(info[i].getvar_size, info[i].part_name, MAX_GET_VAR_NAME_SIZE) >= MAX_GET_VAR_NAME_SIZE)
2295                 {
2296                         dprintf(CRITICAL, "partition size name truncated\n");
2297                         return;
2298                 }
2299                 if (strlcat(info[i].getvar_type, info[i].part_name, MAX_GET_VAR_NAME_SIZE) >= MAX_GET_VAR_NAME_SIZE)
2300                 {
2301                         dprintf(CRITICAL, "partition type name truncated\n");
2302                         return;
2303                 }
2304
2305                 /* publish partition size & type info */
2306                 fastboot_publish((const char *) info[i].getvar_size, (const char *) info[i].size_response);
2307                 fastboot_publish((const char *) info[i].getvar_type, (const char *) info[i].type_response);
2308         }
2309 }
2310
2311 /* register commands and variables for fastboot */
2312 void aboot_fastboot_register_commands(void)
2313 {
2314         int i;
2315
2316         struct fastboot_cmd_desc cmd_list[] = {
2317                                                                                         /* By default the enabled list is empty. */
2318                                                                                         {"", NULL},
2319                                                                                         /* move commands enclosed within the below ifndef to here
2320                                                                                          * if they need to be enabled in user build.
2321                                                                                          */
2322 #ifndef DISABLE_FASTBOOT_CMDS
2323                                                                                         /* Register the following commands only for non-user builds */
2324                                                                                         {"flash:", cmd_flash},
2325                                                                                         {"erase:", cmd_erase},
2326                                                                                         {"boot", cmd_boot},
2327                                                                                         {"continue", cmd_continue},
2328                                                                                         {"reboot", cmd_reboot},
2329                                                                                         {"reboot-bootloader", cmd_reboot_bootloader},
2330                                                                                         {"oem unlock", cmd_oem_unlock},
2331                                                                                         {"oem device-info", cmd_oem_devinfo},
2332                                                                                         {"preflash", cmd_preflash},
2333                                                                                         {"oem enable-charger-screen", cmd_oem_enable_charger_screen},
2334                                                                                         {"oem disable-charger-screen", cmd_oem_disable_charger_screen},
2335                                                                                         {"oem select-display-panel", cmd_oem_select_display_panel},
2336 #endif
2337                                                                                   };
2338
2339         int fastboot_cmds_count = sizeof(cmd_list)/sizeof(cmd_list[0]);
2340         for (i = 1; i < fastboot_cmds_count; i++)
2341                 fastboot_register(cmd_list[i].name,cmd_list[i].cb);
2342
2343         /* publish variables and their values */
2344         fastboot_publish("product",  TARGET(BOARD));
2345         fastboot_publish("kernel",   "lk");
2346         fastboot_publish("serialno", sn_buf);
2347
2348         /*
2349          * partition info is supported only for emmc partitions
2350          * Calling this for NAND prints some error messages which
2351          * is harmless but misleading. Avoid calling this for NAND
2352          * devices.
2353          */
2354         if (target_is_emmc_boot())
2355                 publish_getvar_partition_info(part_info, ARRAY_SIZE(part_info));
2356
2357         /* Max download size supported */
2358         snprintf(max_download_size, MAX_RSP_SIZE, "\t0x%x",
2359                         target_get_max_flash_size());
2360         fastboot_publish("max-download-size", (const char *) max_download_size);
2361         /* Is the charger screen check enabled */
2362         snprintf(charger_screen_enabled, MAX_RSP_SIZE, "%d",
2363                         device.charger_screen_enabled);
2364         fastboot_publish("charger-screen-enabled",
2365                         (const char *) charger_screen_enabled);
2366         snprintf(panel_display_mode, MAX_RSP_SIZE, "%s",
2367                         device.display_panel);
2368         fastboot_publish("display-panel",
2369                         (const char *) panel_display_mode);
2370 }
2371
2372 void aboot_init(const struct app_descriptor *app)
2373 {
2374         unsigned reboot_mode = 0;
2375         bool boot_into_fastboot = false;
2376
2377         /* Setup page size information for nand/emmc reads */
2378         if (target_is_emmc_boot())
2379         {
2380                 page_size = 2048;
2381                 page_mask = page_size - 1;
2382         }
2383         else
2384         {
2385                 page_size = flash_page_size();
2386                 page_mask = page_size - 1;
2387         }
2388
2389         ASSERT((MEMBASE + MEMSIZE) > MEMBASE);
2390
2391         read_device_info(&device);
2392
2393         /* Display splash screen if enabled */
2394 #if DISPLAY_SPLASH_SCREEN
2395         dprintf(SPEW, "Display Init: Start\n");
2396         target_display_init(device.display_panel);
2397         dprintf(SPEW, "Display Init: Done\n");
2398 #endif
2399
2400
2401         target_serialno((unsigned char *) sn_buf);
2402         dprintf(SPEW,"serial number: %s\n",sn_buf);
2403
2404         memset(display_panel_buf, '\0', MAX_PANEL_BUF_SIZE);
2405
2406         /* Check if we should do something other than booting up */
2407         if (keys_get_state(KEY_VOLUMEUP) && keys_get_state(KEY_VOLUMEDOWN))
2408         {
2409                 dprintf(ALWAYS,"dload mode key sequence detected\n");
2410                 if (set_download_mode(EMERGENCY_DLOAD))
2411                 {
2412                         dprintf(CRITICAL,"dload mode not supported by target\n");
2413                 }
2414                 else
2415                 {
2416                         reboot_device(0);
2417                         dprintf(CRITICAL,"Failed to reboot into dload mode\n");
2418                 }
2419                 boot_into_fastboot = true;
2420         }
2421         if (!boot_into_fastboot)
2422         {
2423                 if (keys_get_state(KEY_HOME) || keys_get_state(KEY_VOLUMEUP))
2424                         boot_into_recovery = 1;
2425                 if (!boot_into_recovery &&
2426                         (keys_get_state(KEY_BACK) || keys_get_state(KEY_VOLUMEDOWN)))
2427                         boot_into_fastboot = true;
2428         }
2429         #if NO_KEYPAD_DRIVER
2430         if (fastboot_trigger())
2431                 boot_into_fastboot = true;
2432         #endif
2433
2434         reboot_mode = check_reboot_mode();
2435         if (reboot_mode == RECOVERY_MODE) {
2436                 boot_into_recovery = 1;
2437         } else if(reboot_mode == FASTBOOT_MODE) {
2438                 boot_into_fastboot = true;
2439         }
2440
2441         if (!boot_into_fastboot)
2442         {
2443                 if (target_is_emmc_boot())
2444                 {
2445                         if(emmc_recovery_init())
2446                                 dprintf(ALWAYS,"error in emmc_recovery_init\n");
2447                         if(target_use_signed_kernel())
2448                         {
2449                                 if((device.is_unlocked) || (device.is_tampered))
2450                                 {
2451                                 #ifdef TZ_TAMPER_FUSE
2452                                         set_tamper_fuse_cmd();
2453                                 #endif
2454                                 #if USE_PCOM_SECBOOT
2455                                         set_tamper_flag(device.is_tampered);
2456                                 #endif
2457                                 }
2458                         }
2459                         boot_linux_from_mmc();
2460                 }
2461                 else
2462                 {
2463                         recovery_init();
2464         #if USE_PCOM_SECBOOT
2465                 if((device.is_unlocked) || (device.is_tampered))
2466                         set_tamper_flag(device.is_tampered);
2467         #endif
2468                         boot_linux_from_flash();
2469                 }
2470                 dprintf(CRITICAL, "ERROR: Could not do normal boot. Reverting "
2471                         "to fastboot mode.\n");
2472         }
2473
2474         /* We are here means regular boot did not happen. Start fastboot. */
2475
2476         /* register aboot specific fastboot commands */
2477         aboot_fastboot_register_commands();
2478
2479         /* dump partition table for debug info */
2480         partition_dump();
2481
2482         /* initialize and start fastboot */
2483         fastboot_init(target_get_scratch_address(), target_get_max_flash_size());
2484 }
2485
2486 uint32_t get_page_size()
2487 {
2488         return page_size;
2489 }
2490
2491 /*
2492  * Calculated and save hash (SHA256) for non-signed boot image.
2493  *
2494  * Hash the same data that is checked on the signed boot image.
2495  * Kernel and Ramdisk are already read to memory buffers.
2496  * Need to read the entire device-tree from mmc
2497  * since non-signed image only read the DT tags of the relevant platform.
2498  *
2499  * @param kernel_addr - kernel bufer
2500  * @param kernel_actual - kernel size in bytes
2501  * @param ramdisk_addr - ramdisk buffer
2502  * @param ramdisk_actual - ramdisk size
2503  * @param ptn - partition
2504  * @param dt_offset - device tree offset on mmc partition
2505  * @param dt_size
2506  *
2507  * @return int - 0 on success, negative value on failure.
2508  */
2509 int aboot_save_boot_hash_mmc(void *kernel_addr, unsigned kernel_actual,
2510                    void *ramdisk_addr, unsigned ramdisk_actual,
2511                    unsigned long long ptn,
2512                    unsigned dt_offset, unsigned dt_size)
2513 {
2514         SHA256_CTX sha256_ctx;
2515         char digest[32]={0};
2516         char *buf = (char *)target_get_scratch_address();
2517         unsigned dt_actual = ROUND_TO_PAGE(dt_size, page_mask);
2518         unsigned imagesize_actual = page_size + kernel_actual + ramdisk_actual + dt_actual;
2519
2520         SHA256_Init(&sha256_ctx);
2521
2522         /* Read Boot Header */
2523         if (mmc_read(ptn, buf, page_size))
2524         {
2525                 dprintf(CRITICAL, "ERROR: mmc_read() fail.\n");
2526                 return -1;
2527         }
2528         /* Read entire Device Tree */
2529         if (mmc_read(ptn + dt_offset, buf+page_size, dt_actual))
2530         {
2531                 dprintf(CRITICAL, "ERROR: mmc_read() fail.\n");
2532                 return -1;
2533         }
2534         SHA256_Update(&sha256_ctx, buf, page_size); // Boot Header
2535         SHA256_Update(&sha256_ctx, kernel_addr, kernel_actual);
2536         SHA256_Update(&sha256_ctx, ramdisk_addr, ramdisk_actual);
2537         SHA256_Update(&sha256_ctx, buf+page_size, dt_actual); // Device Tree
2538
2539         SHA256_Final(digest, &sha256_ctx);
2540
2541         save_kernel_hash_cmd(digest);
2542         dprintf(INFO, "aboot_save_boot_hash_mmc: imagesize_actual size %d bytes.\n", (int) imagesize_actual);
2543
2544         return 0;
2545 }
2546
2547 APP_START(aboot)
2548         .init = aboot_init,
2549 APP_END