1 // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
17 #include <sys/param.h>
22 #include "rom/cache.h"
23 #include "rom/efuse.h"
24 #include "rom/ets_sys.h"
25 #include "rom/spi_flash.h"
30 #include "rom/secure_boot.h"
35 #include "soc/dport_reg.h"
36 #include "soc/io_mux_reg.h"
37 #include "soc/efuse_reg.h"
38 #include "soc/rtc_cntl_reg.h"
39 #include "soc/timer_group_reg.h"
40 #include "soc/gpio_reg.h"
41 #include "soc/gpio_sig_map.h"
43 #include "sdkconfig.h"
44 #include "esp_image_format.h"
45 #include "esp_secure_boot.h"
46 #include "esp_flash_encrypt.h"
47 #include "esp_flash_partitions.h"
48 #include "bootloader_flash.h"
49 #include "bootloader_random.h"
50 #include "bootloader_config.h"
51 #include "bootloader_common.h"
52 #include "bootloader_utility.h"
54 static const char* TAG = "boot";
56 /* Reduce literal size for some generic string literals */
57 #define MAP_ERR_MSG "Image contains multiple %s segments. Only the last one will be mapped."
59 static void load_image(const esp_image_metadata_t* image_data);
60 static void unpack_load_app(const esp_image_metadata_t *data);
61 static void set_cache_and_start_app(uint32_t drom_addr,
62 uint32_t drom_load_addr,
65 uint32_t irom_load_addr,
69 bool bootloader_utility_load_partition_table(bootloader_state_t* bs)
71 const esp_partition_info_t *partitions;
72 const char *partition_usage;
76 partitions = bootloader_mmap(ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
78 ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
81 ESP_LOGD(TAG, "mapped partition table 0x%x at 0x%x", ESP_PARTITION_TABLE_OFFSET, (intptr_t)partitions);
83 err = esp_partition_table_verify(partitions, true, &num_partitions);
85 ESP_LOGE(TAG, "Failed to verify partition table");
89 ESP_LOGI(TAG, "Partition Table:");
90 ESP_LOGI(TAG, "## Label Usage Type ST Offset Length");
92 for(int i = 0; i < num_partitions; i++) {
93 const esp_partition_info_t *partition = &partitions[i];
94 ESP_LOGD(TAG, "load partition table entry 0x%x", (intptr_t)partition);
95 ESP_LOGD(TAG, "type=%x subtype=%x", partition->type, partition->subtype);
96 partition_usage = "unknown";
98 /* valid partition table */
99 switch(partition->type) {
100 case PART_TYPE_APP: /* app partition */
101 switch(partition->subtype) {
102 case PART_SUBTYPE_FACTORY: /* factory binary */
103 bs->factory = partition->pos;
104 partition_usage = "factory app";
106 case PART_SUBTYPE_TEST: /* test binary */
107 bs->test = partition->pos;
108 partition_usage = "test app";
112 if ((partition->subtype & ~PART_SUBTYPE_OTA_MASK) == PART_SUBTYPE_OTA_FLAG) {
113 bs->ota[partition->subtype & PART_SUBTYPE_OTA_MASK] = partition->pos;
115 partition_usage = "OTA app";
118 partition_usage = "Unknown app";
122 break; /* PART_TYPE_APP */
123 case PART_TYPE_DATA: /* data partition */
124 switch(partition->subtype) {
125 case PART_SUBTYPE_DATA_OTA: /* ota data */
126 bs->ota_info = partition->pos;
127 partition_usage = "OTA data";
129 case PART_SUBTYPE_DATA_RF:
130 partition_usage = "RF data";
132 case PART_SUBTYPE_DATA_WIFI:
133 partition_usage = "WiFi data";
136 partition_usage = "Unknown data";
139 break; /* PARTITION_USAGE_DATA */
140 default: /* other partition type */
144 /* print partition type info */
145 ESP_LOGI(TAG, "%2d %-16s %-16s %02x %02x %08x %08x", i, partition->label, partition_usage,
146 partition->type, partition->subtype,
147 partition->pos.offset, partition->pos.size);
150 bootloader_munmap(partitions);
152 ESP_LOGI(TAG,"End of partition table");
156 /* Given a partition index, return the partition position data from the bootloader_state_t structure */
157 static esp_partition_pos_t index_to_partition(const bootloader_state_t *bs, int index)
159 if (index == FACTORY_INDEX) {
163 if (index == TEST_APP_INDEX) {
167 if (index >= 0 && index < MAX_OTA_SLOTS && index < bs->app_count) {
168 return bs->ota[index];
171 esp_partition_pos_t invalid = { 0 };
175 static void log_invalid_app_partition(int index)
177 const char *not_bootable = " is not bootable"; /* save a few string literal bytes */
180 ESP_LOGE(TAG, "Factory app partition%s", not_bootable);
183 ESP_LOGE(TAG, "Factory test app partition%s", not_bootable);
186 ESP_LOGE(TAG, "OTA app partition slot %d%s", index, not_bootable);
191 int bootloader_utility_get_selected_boot_partition(const bootloader_state_t *bs)
193 esp_ota_select_entry_t sa,sb;
194 const esp_ota_select_entry_t *ota_select_map;
196 if (bs->ota_info.offset != 0) {
197 // partition table has OTA data partition
198 if (bs->ota_info.size < 2 * SPI_SEC_SIZE) {
199 ESP_LOGE(TAG, "ota_info partition size %d is too small (minimum %d bytes)", bs->ota_info.size, sizeof(esp_ota_select_entry_t));
200 return INVALID_INDEX; // can't proceed
203 ESP_LOGD(TAG, "OTA data offset 0x%x", bs->ota_info.offset);
204 ota_select_map = bootloader_mmap(bs->ota_info.offset, bs->ota_info.size);
205 if (!ota_select_map) {
206 ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", bs->ota_info.offset, bs->ota_info.size);
207 return INVALID_INDEX; // can't proceed
209 memcpy(&sa, ota_select_map, sizeof(esp_ota_select_entry_t));
210 memcpy(&sb, (uint8_t *)ota_select_map + SPI_SEC_SIZE, sizeof(esp_ota_select_entry_t));
211 bootloader_munmap(ota_select_map);
213 ESP_LOGD(TAG, "OTA sequence values A 0x%08x B 0x%08x", sa.ota_seq, sb.ota_seq);
214 if ((sa.ota_seq == UINT32_MAX && sb.ota_seq == UINT32_MAX) || (bs->app_count == 0)) {
215 ESP_LOGD(TAG, "OTA sequence numbers both empty (all-0xFF) or partition table does not have bootable ota_apps (app_count=%d)", bs->app_count);
216 if (bs->factory.offset != 0) {
217 ESP_LOGI(TAG, "Defaulting to factory image");
218 return FACTORY_INDEX;
220 ESP_LOGI(TAG, "No factory image, trying OTA 0");
224 bool ota_valid = false;
226 int ota_seq; // Raw OTA sequence number. May be more than # of OTA slots
227 if(bootloader_common_ota_select_valid(&sa) && bootloader_common_ota_select_valid(&sb)) {
229 ota_msg = "Both OTA values";
230 ota_seq = MAX(sa.ota_seq, sb.ota_seq) - 1;
231 } else if(bootloader_common_ota_select_valid(&sa)) {
233 ota_msg = "Only OTA sequence A is";
234 ota_seq = sa.ota_seq - 1;
235 } else if(bootloader_common_ota_select_valid(&sb)) {
237 ota_msg = "Only OTA sequence B is";
238 ota_seq = sb.ota_seq - 1;
242 int ota_slot = ota_seq % bs->app_count; // Actual OTA partition selection
243 ESP_LOGD(TAG, "%s valid. Mapping seq %d -> OTA slot %d", ota_msg, ota_seq, ota_slot);
245 } else if (bs->factory.offset != 0) {
246 ESP_LOGE(TAG, "ota data partition invalid, falling back to factory");
247 return FACTORY_INDEX;
249 ESP_LOGE(TAG, "ota data partition invalid and no factory, will try all partitions");
250 return FACTORY_INDEX;
255 // otherwise, start from factory app partition and let the search logic
256 // proceed from there
257 return FACTORY_INDEX;
260 /* Return true if a partition has a valid app image that was successfully loaded */
261 static bool try_load_partition(const esp_partition_pos_t *partition, esp_image_metadata_t *data)
263 if (partition->size == 0) {
264 ESP_LOGD(TAG, "Can't boot from zero-length partition");
267 #ifdef BOOTLOADER_BUILD
268 if (esp_image_load(ESP_IMAGE_LOAD, partition, data) == ESP_OK) {
269 ESP_LOGI(TAG, "Loaded app from partition at offset 0x%x",
278 #define TRY_LOG_FORMAT "Trying partition index %d offs 0x%x size 0x%x"
280 void bootloader_utility_load_boot_image(const bootloader_state_t *bs, int start_index)
282 int index = start_index;
283 esp_partition_pos_t part;
284 esp_image_metadata_t image_data;
286 if(start_index == TEST_APP_INDEX) {
287 if (try_load_partition(&bs->test, &image_data)) {
288 load_image(&image_data);
290 ESP_LOGE(TAG, "No bootable test partition in the partition table");
295 /* work backwards from start_index, down to the factory app */
296 for(index = start_index; index >= FACTORY_INDEX; index--) {
297 part = index_to_partition(bs, index);
298 if (part.size == 0) {
301 ESP_LOGD(TAG, TRY_LOG_FORMAT, index, part.offset, part.size);
302 if (try_load_partition(&part, &image_data)) {
303 load_image(&image_data);
305 log_invalid_app_partition(index);
308 /* failing that work forwards from start_index, try valid OTA slots */
309 for(index = start_index + 1; index < bs->app_count; index++) {
310 part = index_to_partition(bs, index);
311 if (part.size == 0) {
314 ESP_LOGD(TAG, TRY_LOG_FORMAT, index, part.offset, part.size);
315 if (try_load_partition(&part, &image_data)) {
316 load_image(&image_data);
318 log_invalid_app_partition(index);
321 if (try_load_partition(&bs->test, &image_data)) {
322 ESP_LOGW(TAG, "Falling back to test app as only bootable partition");
323 load_image(&image_data);
326 ESP_LOGE(TAG, "No bootable app partitions in the partition table");
327 bzero(&image_data, sizeof(esp_image_metadata_t));
331 // Copy loaded segments to RAM, set up caches for mapped segments, and start application.
332 static void load_image(const esp_image_metadata_t* image_data)
334 #if defined(CONFIG_SECURE_BOOT_ENABLED) || defined(CONFIG_FLASH_ENCRYPTION_ENABLED)
337 #ifdef CONFIG_SECURE_BOOT_ENABLED
338 /* Generate secure digest from this bootloader to protect future
340 ESP_LOGI(TAG, "Checking secure boot...");
341 err = esp_secure_boot_permanently_enable();
343 ESP_LOGE(TAG, "Bootloader digest generation failed (%d). SECURE BOOT IS NOT ENABLED.", err);
344 /* Allow booting to continue, as the failure is probably
345 due to user-configured EFUSEs for testing...
350 #ifdef CONFIG_FLASH_ENCRYPTION_ENABLED
352 ESP_LOGI(TAG, "Checking flash encryption...");
353 bool flash_encryption_enabled = esp_flash_encryption_enabled();
354 err = esp_flash_encrypt_check_and_update();
356 ESP_LOGE(TAG, "Flash encryption check failed (%d).", err);
360 if (!flash_encryption_enabled && esp_flash_encryption_enabled()) {
361 /* Flash encryption was just enabled for the first time,
362 so issue a system reset to ensure flash encryption
363 cache resets properly */
364 ESP_LOGI(TAG, "Resetting with flash encryption enabled...");
369 ESP_LOGI(TAG, "Disabling RNG early entropy source...");
370 bootloader_random_disable();
372 // copy loaded segments to RAM, set up caches for mapped segments, and start application
373 unpack_load_app(image_data);
376 static void unpack_load_app(const esp_image_metadata_t* data)
378 uint32_t drom_addr = 0;
379 uint32_t drom_load_addr = 0;
380 uint32_t drom_size = 0;
381 uint32_t irom_addr = 0;
382 uint32_t irom_load_addr = 0;
383 uint32_t irom_size = 0;
385 // Find DROM & IROM addresses, to configure cache mappings
386 for (int i = 0; i < data->image.segment_count; i++) {
387 const esp_image_segment_header_t *header = &data->segments[i];
388 if (header->load_addr >= SOC_IROM_LOW && header->load_addr < SOC_IROM_HIGH) {
389 if (drom_addr != 0) {
390 ESP_LOGE(TAG, MAP_ERR_MSG, "DROM");
392 ESP_LOGD(TAG, "Mapping segment %d as %s", i, "DROM");
394 drom_addr = data->segment_data[i];
395 drom_load_addr = header->load_addr;
396 drom_size = header->data_len;
398 if (header->load_addr >= SOC_DROM_LOW && header->load_addr < SOC_DROM_HIGH) {
399 if (irom_addr != 0) {
400 ESP_LOGE(TAG, MAP_ERR_MSG, "IROM");
402 ESP_LOGD(TAG, "Mapping segment %d as %s", i, "IROM");
404 irom_addr = data->segment_data[i];
405 irom_load_addr = header->load_addr;
406 irom_size = header->data_len;
410 ESP_LOGD(TAG, "calling set_cache_and_start_app");
411 set_cache_and_start_app(drom_addr,
417 data->image.entry_addr);
420 static void set_cache_and_start_app(
422 uint32_t drom_load_addr,
425 uint32_t irom_load_addr,
429 ESP_LOGD(TAG, "configure drom and irom and start");
430 Cache_Read_Disable( 0 );
433 /* Clear the MMU entries that are already set up,
434 so the new app only has the mappings it creates.
436 for (int i = 0; i < DPORT_FLASH_MMU_TABLE_SIZE; i++) {
437 DPORT_PRO_FLASH_MMU_TABLE[i] = DPORT_FLASH_MMU_TABLE_INVALID_VAL;
440 uint32_t drom_page_count = (drom_size + 64*1024 - 1) / (64*1024); // round up to 64k
441 ESP_LOGV(TAG, "d mmu set paddr=%08x vaddr=%08x size=%d n=%d", drom_addr & 0xffff0000, drom_load_addr & 0xffff0000, drom_size, drom_page_count );
442 int rc = cache_flash_mmu_set( 0, 0, drom_load_addr & 0xffff0000, drom_addr & 0xffff0000, 64, drom_page_count );
443 ESP_LOGV(TAG, "rc=%d", rc );
444 rc = cache_flash_mmu_set( 1, 0, drom_load_addr & 0xffff0000, drom_addr & 0xffff0000, 64, drom_page_count );
445 ESP_LOGV(TAG, "rc=%d", rc );
446 uint32_t irom_page_count = (irom_size + 64*1024 - 1) / (64*1024); // round up to 64k
447 ESP_LOGV(TAG, "i mmu set paddr=%08x vaddr=%08x size=%d n=%d", irom_addr & 0xffff0000, irom_load_addr & 0xffff0000, irom_size, irom_page_count );
448 rc = cache_flash_mmu_set( 0, 0, irom_load_addr & 0xffff0000, irom_addr & 0xffff0000, 64, irom_page_count );
449 ESP_LOGV(TAG, "rc=%d", rc );
450 rc = cache_flash_mmu_set( 1, 0, irom_load_addr & 0xffff0000, irom_addr & 0xffff0000, 64, irom_page_count );
451 ESP_LOGV(TAG, "rc=%d", rc );
452 DPORT_REG_CLR_BIT( DPORT_PRO_CACHE_CTRL1_REG, (DPORT_PRO_CACHE_MASK_IRAM0) | (DPORT_PRO_CACHE_MASK_IRAM1 & 0) | (DPORT_PRO_CACHE_MASK_IROM0 & 0) | DPORT_PRO_CACHE_MASK_DROM0 | DPORT_PRO_CACHE_MASK_DRAM1 );
453 DPORT_REG_CLR_BIT( DPORT_APP_CACHE_CTRL1_REG, (DPORT_APP_CACHE_MASK_IRAM0) | (DPORT_APP_CACHE_MASK_IRAM1 & 0) | (DPORT_APP_CACHE_MASK_IROM0 & 0) | DPORT_APP_CACHE_MASK_DROM0 | DPORT_APP_CACHE_MASK_DRAM1 );
454 Cache_Read_Enable( 0 );
456 // Application will need to do Cache_Flush(1) and Cache_Read_Enable(1)
458 ESP_LOGD(TAG, "start: 0x%08x", entry_addr);
459 typedef void (*entry_t)(void) __attribute__((noreturn));
460 entry_t entry = ((entry_t) entry_addr);
462 // TODO: we have used quite a bit of stack at this point.
463 // use "movsp" instruction to reset stack back to where ROM stack starts.
468 void bootloader_reset(void)
470 #ifdef BOOTLOADER_BUILD
471 uart_tx_flush(0); /* Ensure any buffered log output is displayed */
473 ets_delay_us(1000); /* Allow last byte to leave FIFO */
474 REG_WRITE(RTC_CNTL_OPTIONS0_REG, RTC_CNTL_SW_SYS_RST);
475 while (1) { } /* This line will never be reached, used to keep gcc happy */
477 abort(); /* This function should really not be called from application code */