]> granicus.if.org Git - esp-idf/blob - components/bootloader_support/src/bootloader_utility.c
bootloader: Fix issue - bs->app_count is zero but ota_data have valid entry
[esp-idf] / components / bootloader_support / src / bootloader_utility.c
1 // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14 #include <string.h>
15 #include <stdint.h>
16 #include <limits.h>
17 #include <sys/param.h>
18
19 #include "esp_attr.h"
20 #include "esp_log.h"
21
22 #include "rom/cache.h"
23 #include "rom/efuse.h"
24 #include "rom/ets_sys.h"
25 #include "rom/spi_flash.h"
26 #include "rom/crc.h"
27 #include "rom/rtc.h"
28 #include "rom/uart.h"
29 #include "rom/gpio.h"
30 #include "rom/secure_boot.h"
31
32 #include "soc/soc.h"
33 #include "soc/cpu.h"
34 #include "soc/rtc.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"
42
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"
53
54 static const char* TAG = "boot";
55
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."
58
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,
63     uint32_t drom_size,
64     uint32_t irom_addr,
65     uint32_t irom_load_addr,
66     uint32_t irom_size,
67     uint32_t entry_addr);
68
69 bool bootloader_utility_load_partition_table(bootloader_state_t* bs)
70 {
71     const esp_partition_info_t *partitions;
72     const char *partition_usage;
73     esp_err_t err;
74     int num_partitions;
75
76     partitions = bootloader_mmap(ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
77     if (!partitions) {
78         ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
79         return false;
80     }
81     ESP_LOGD(TAG, "mapped partition table 0x%x at 0x%x", ESP_PARTITION_TABLE_OFFSET, (intptr_t)partitions);
82
83     err = esp_partition_table_verify(partitions, true, &num_partitions);
84     if (err != ESP_OK) {
85         ESP_LOGE(TAG, "Failed to verify partition table");
86         return false;
87     }
88
89     ESP_LOGI(TAG, "Partition Table:");
90     ESP_LOGI(TAG, "## Label            Usage          Type ST Offset   Length");
91
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";
97
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";
105                 break;
106             case PART_SUBTYPE_TEST: /* test binary */
107                 bs->test = partition->pos;
108                 partition_usage = "test app";
109                 break;
110             default:
111                 /* OTA binary */
112                 if ((partition->subtype & ~PART_SUBTYPE_OTA_MASK) == PART_SUBTYPE_OTA_FLAG) {
113                     bs->ota[partition->subtype & PART_SUBTYPE_OTA_MASK] = partition->pos;
114                     ++bs->app_count;
115                     partition_usage = "OTA app";
116                 }
117                 else {
118                     partition_usage = "Unknown app";
119                 }
120                 break;
121             }
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";
128                 break;
129             case PART_SUBTYPE_DATA_RF:
130                 partition_usage = "RF data";
131                 break;
132             case PART_SUBTYPE_DATA_WIFI:
133                 partition_usage = "WiFi data";
134                 break;
135             default:
136                 partition_usage = "Unknown data";
137                 break;
138             }
139             break; /* PARTITION_USAGE_DATA */
140         default: /* other partition type */
141             break;
142         }
143
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);
148     }
149
150     bootloader_munmap(partitions);
151
152     ESP_LOGI(TAG,"End of partition table");
153     return true;
154 }
155
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)
158 {
159     if (index == FACTORY_INDEX) {
160         return bs->factory;
161     }
162
163     if (index == TEST_APP_INDEX) {
164         return bs->test;
165     }
166
167     if (index >= 0 && index < MAX_OTA_SLOTS && index < bs->app_count) {
168         return bs->ota[index];
169     }
170
171     esp_partition_pos_t invalid = { 0 };
172     return invalid;
173 }
174
175 static void log_invalid_app_partition(int index)
176 {
177     const char *not_bootable = " is not bootable"; /* save a few string literal bytes */
178     switch(index) {
179     case FACTORY_INDEX:
180         ESP_LOGE(TAG, "Factory app partition%s", not_bootable);
181         break;
182     case TEST_APP_INDEX:
183         ESP_LOGE(TAG, "Factory test app partition%s", not_bootable);
184         break;
185     default:
186         ESP_LOGE(TAG, "OTA app partition slot %d%s", index, not_bootable);
187         break;
188     }
189 }
190
191 int bootloader_utility_get_selected_boot_partition(const bootloader_state_t *bs)
192 {
193     esp_ota_select_entry_t sa,sb;
194     const esp_ota_select_entry_t *ota_select_map;
195
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
201         }
202
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
208         }
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);
212
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;
219             } else {
220                 ESP_LOGI(TAG, "No factory image, trying OTA 0");
221                 return 0;
222             }
223         } else  {
224             bool ota_valid = false;
225             const char *ota_msg;
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)) {
228                 ota_valid = true;
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)) {
232                 ota_valid = true;
233                 ota_msg = "Only OTA sequence A is";
234                 ota_seq = sa.ota_seq - 1;
235             } else if(bootloader_common_ota_select_valid(&sb)) {
236                 ota_valid = true;
237                 ota_msg = "Only OTA sequence B is";
238                 ota_seq = sb.ota_seq - 1;
239             }
240
241             if (ota_valid) {
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);
244                 return 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;
248             } else {
249                 ESP_LOGE(TAG, "ota data partition invalid and no factory, will try all partitions");
250                 return FACTORY_INDEX;
251             }
252         }
253     }
254
255     // otherwise, start from factory app partition and let the search logic
256     // proceed from there
257     return FACTORY_INDEX;
258 }
259
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)
262 {
263     if (partition->size == 0) {
264         ESP_LOGD(TAG, "Can't boot from zero-length partition");
265         return false;
266     }
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",
270                  partition->offset);
271         return true;
272     }
273 #endif
274
275     return false;
276 }
277
278 #define TRY_LOG_FORMAT "Trying partition index %d offs 0x%x size 0x%x"
279
280 void bootloader_utility_load_boot_image(const bootloader_state_t *bs, int start_index)
281 {
282     int index = start_index;
283     esp_partition_pos_t part;
284     esp_image_metadata_t image_data;
285
286     if(start_index == TEST_APP_INDEX) {
287         if (try_load_partition(&bs->test, &image_data)) {
288             load_image(&image_data);
289         } else {
290             ESP_LOGE(TAG, "No bootable test partition in the partition table");
291             bootloader_reset();
292         }
293     }
294
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) {
299             continue;
300         }
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);
304         }
305         log_invalid_app_partition(index);
306     }
307
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) {
312             continue;
313         }
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);
317         }
318         log_invalid_app_partition(index);
319     }
320
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);
324     }
325
326     ESP_LOGE(TAG, "No bootable app partitions in the partition table");
327     bzero(&image_data, sizeof(esp_image_metadata_t));
328     bootloader_reset();
329 }
330
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)
333 {
334 #if defined(CONFIG_SECURE_BOOT_ENABLED) || defined(CONFIG_FLASH_ENCRYPTION_ENABLED)
335     esp_err_t err;
336 #endif
337 #ifdef CONFIG_SECURE_BOOT_ENABLED
338     /* Generate secure digest from this bootloader to protect future
339        modifications */
340     ESP_LOGI(TAG, "Checking secure boot...");
341     err = esp_secure_boot_permanently_enable();
342     if (err != ESP_OK) {
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...
346         */
347     }
348 #endif
349
350 #ifdef CONFIG_FLASH_ENCRYPTION_ENABLED
351     /* encrypt flash */
352     ESP_LOGI(TAG, "Checking flash encryption...");
353     bool flash_encryption_enabled = esp_flash_encryption_enabled();
354     err = esp_flash_encrypt_check_and_update();
355     if (err != ESP_OK) {
356         ESP_LOGE(TAG, "Flash encryption check failed (%d).", err);
357         return;
358     }
359
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...");
365         bootloader_reset();
366     }
367 #endif
368
369     ESP_LOGI(TAG, "Disabling RNG early entropy source...");
370     bootloader_random_disable();
371
372     // copy loaded segments to RAM, set up caches for mapped segments, and start application
373     unpack_load_app(image_data);
374 }
375
376 static void unpack_load_app(const esp_image_metadata_t* data)
377 {
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;
384
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");
391             } else {
392                 ESP_LOGD(TAG, "Mapping segment %d as %s", i, "DROM");
393             }
394             drom_addr = data->segment_data[i];
395             drom_load_addr = header->load_addr;
396             drom_size = header->data_len;
397         }
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");
401             } else {
402                 ESP_LOGD(TAG, "Mapping segment %d as %s", i, "IROM");
403             }
404             irom_addr = data->segment_data[i];
405             irom_load_addr = header->load_addr;
406             irom_size = header->data_len;
407         }
408     }
409
410     ESP_LOGD(TAG, "calling set_cache_and_start_app");
411     set_cache_and_start_app(drom_addr,
412         drom_load_addr,
413         drom_size,
414         irom_addr,
415         irom_load_addr,
416         irom_size,
417         data->image.entry_addr);
418 }
419
420 static void set_cache_and_start_app(
421     uint32_t drom_addr,
422     uint32_t drom_load_addr,
423     uint32_t drom_size,
424     uint32_t irom_addr,
425     uint32_t irom_load_addr,
426     uint32_t irom_size,
427     uint32_t entry_addr)
428 {
429     ESP_LOGD(TAG, "configure drom and irom and start");
430     Cache_Read_Disable( 0 );
431     Cache_Flush( 0 );
432
433     /* Clear the MMU entries that are already set up,
434        so the new app only has the mappings it creates.
435     */
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;
438     }
439
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 );
455
456     // Application will need to do Cache_Flush(1) and Cache_Read_Enable(1)
457
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);
461
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.
464     (*entry)();
465 }
466
467
468 void bootloader_reset(void)
469 {
470 #ifdef BOOTLOADER_BUILD
471     uart_tx_flush(0);    /* Ensure any buffered log output is displayed */
472     uart_tx_flush(1);
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 */
476 #else
477     abort();            /* This function should really not be called from application code */
478 #endif
479 }