bootloader_utility.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. /*
  2. * SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <stdint.h>
  8. #include <limits.h>
  9. #include <sys/param.h>
  10. #include "esp_attr.h"
  11. #include "esp_log.h"
  12. #include "esp_rom_sys.h"
  13. #include "esp_rom_uart.h"
  14. #if CONFIG_IDF_TARGET_ESP32
  15. #include "soc/dport_reg.h"
  16. #include "esp32/rom/cache.h"
  17. #include "esp32/rom/spi_flash.h"
  18. #include "esp32/rom/rtc.h"
  19. #include "esp32/rom/secure_boot.h"
  20. #elif CONFIG_IDF_TARGET_ESP32S2
  21. #include "esp32s2/rom/cache.h"
  22. #include "esp32s2/rom/spi_flash.h"
  23. #include "esp32s2/rom/rtc.h"
  24. #include "esp32s2/rom/secure_boot.h"
  25. #include "soc/extmem_reg.h"
  26. #include "soc/cache_memory.h"
  27. #elif CONFIG_IDF_TARGET_ESP32S3
  28. #include "esp32s3/rom/cache.h"
  29. #include "esp32s3/rom/spi_flash.h"
  30. #include "esp32s3/rom/rtc.h"
  31. #include "esp32s3/rom/secure_boot.h"
  32. #include "soc/extmem_reg.h"
  33. #include "soc/cache_memory.h"
  34. #elif CONFIG_IDF_TARGET_ESP32C3
  35. #include "esp32c3/rom/cache.h"
  36. #include "esp32c3/rom/efuse.h"
  37. #include "esp32c3/rom/ets_sys.h"
  38. #include "esp32c3/rom/spi_flash.h"
  39. #include "esp32c3/rom/crc.h"
  40. #include "esp32c3/rom/rtc.h"
  41. #include "esp32c3/rom/uart.h"
  42. #include "esp32c3/rom/gpio.h"
  43. #include "esp32c3/rom/secure_boot.h"
  44. #include "soc/extmem_reg.h"
  45. #include "soc/cache_memory.h"
  46. #else // CONFIG_IDF_TARGET_*
  47. #error "Unsupported IDF_TARGET"
  48. #endif
  49. #include "soc/soc.h"
  50. #include "soc/cpu.h"
  51. #include "soc/rtc.h"
  52. #include "soc/gpio_periph.h"
  53. #include "soc/efuse_periph.h"
  54. #include "soc/rtc_periph.h"
  55. #include "soc/timer_periph.h"
  56. #include "sdkconfig.h"
  57. #include "esp_image_format.h"
  58. #include "esp_secure_boot.h"
  59. #include "esp_flash_encrypt.h"
  60. #include "esp_flash_partitions.h"
  61. #include "bootloader_flash_priv.h"
  62. #include "bootloader_random.h"
  63. #include "bootloader_config.h"
  64. #include "bootloader_common.h"
  65. #include "bootloader_utility.h"
  66. #include "bootloader_sha.h"
  67. #include "bootloader_console.h"
  68. #include "esp_efuse.h"
  69. static const char *TAG = "boot";
  70. /* Reduce literal size for some generic string literals */
  71. #define MAP_ERR_MSG "Image contains multiple %s segments. Only the last one will be mapped."
  72. static bool ota_has_initial_contents;
  73. static void load_image(const esp_image_metadata_t *image_data);
  74. static void unpack_load_app(const esp_image_metadata_t *data);
  75. static void set_cache_and_start_app(uint32_t drom_addr,
  76. uint32_t drom_load_addr,
  77. uint32_t drom_size,
  78. uint32_t irom_addr,
  79. uint32_t irom_load_addr,
  80. uint32_t irom_size,
  81. uint32_t entry_addr);
  82. // Read ota_info partition and fill array from two otadata structures.
  83. static esp_err_t read_otadata(const esp_partition_pos_t *ota_info, esp_ota_select_entry_t *two_otadata)
  84. {
  85. const esp_ota_select_entry_t *ota_select_map;
  86. if (ota_info->offset == 0) {
  87. return ESP_ERR_NOT_FOUND;
  88. }
  89. // partition table has OTA data partition
  90. if (ota_info->size < 2 * SPI_SEC_SIZE) {
  91. ESP_LOGE(TAG, "ota_info partition size %d is too small (minimum %d bytes)", ota_info->size, (2 * SPI_SEC_SIZE));
  92. return ESP_FAIL; // can't proceed
  93. }
  94. ESP_LOGD(TAG, "OTA data offset 0x%x", ota_info->offset);
  95. ota_select_map = bootloader_mmap(ota_info->offset, ota_info->size);
  96. if (!ota_select_map) {
  97. ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ota_info->offset, ota_info->size);
  98. return ESP_FAIL; // can't proceed
  99. }
  100. memcpy(&two_otadata[0], ota_select_map, sizeof(esp_ota_select_entry_t));
  101. memcpy(&two_otadata[1], (uint8_t *)ota_select_map + SPI_SEC_SIZE, sizeof(esp_ota_select_entry_t));
  102. bootloader_munmap(ota_select_map);
  103. return ESP_OK;
  104. }
  105. bool bootloader_utility_load_partition_table(bootloader_state_t *bs)
  106. {
  107. const esp_partition_info_t *partitions;
  108. const char *partition_usage;
  109. esp_err_t err;
  110. int num_partitions;
  111. partitions = bootloader_mmap(ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
  112. if (!partitions) {
  113. ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
  114. return false;
  115. }
  116. ESP_LOGD(TAG, "mapped partition table 0x%x at 0x%x", ESP_PARTITION_TABLE_OFFSET, (intptr_t)partitions);
  117. err = esp_partition_table_verify(partitions, true, &num_partitions);
  118. if (err != ESP_OK) {
  119. ESP_LOGE(TAG, "Failed to verify partition table");
  120. return false;
  121. }
  122. ESP_LOGI(TAG, "Partition Table:");
  123. ESP_LOGI(TAG, "## Label Usage Type ST Offset Length");
  124. for (int i = 0; i < num_partitions; i++) {
  125. const esp_partition_info_t *partition = &partitions[i];
  126. ESP_LOGD(TAG, "load partition table entry 0x%x", (intptr_t)partition);
  127. ESP_LOGD(TAG, "type=%x subtype=%x", partition->type, partition->subtype);
  128. partition_usage = "unknown";
  129. /* valid partition table */
  130. switch (partition->type) {
  131. case PART_TYPE_APP: /* app partition */
  132. switch (partition->subtype) {
  133. case PART_SUBTYPE_FACTORY: /* factory binary */
  134. bs->factory = partition->pos;
  135. partition_usage = "factory app";
  136. break;
  137. case PART_SUBTYPE_TEST: /* test binary */
  138. bs->test = partition->pos;
  139. partition_usage = "test app";
  140. break;
  141. default:
  142. /* OTA binary */
  143. if ((partition->subtype & ~PART_SUBTYPE_OTA_MASK) == PART_SUBTYPE_OTA_FLAG) {
  144. bs->ota[partition->subtype & PART_SUBTYPE_OTA_MASK] = partition->pos;
  145. ++bs->app_count;
  146. partition_usage = "OTA app";
  147. } else {
  148. partition_usage = "Unknown app";
  149. }
  150. break;
  151. }
  152. break; /* PART_TYPE_APP */
  153. case PART_TYPE_DATA: /* data partition */
  154. switch (partition->subtype) {
  155. case PART_SUBTYPE_DATA_OTA: /* ota data */
  156. bs->ota_info = partition->pos;
  157. partition_usage = "OTA data";
  158. break;
  159. case PART_SUBTYPE_DATA_RF:
  160. partition_usage = "RF data";
  161. break;
  162. case PART_SUBTYPE_DATA_WIFI:
  163. partition_usage = "WiFi data";
  164. break;
  165. case PART_SUBTYPE_DATA_NVS_KEYS:
  166. partition_usage = "NVS keys";
  167. break;
  168. case PART_SUBTYPE_DATA_EFUSE_EM:
  169. partition_usage = "efuse";
  170. #ifdef CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH
  171. esp_efuse_init_virtual_mode_in_flash(partition->pos.offset, partition->pos.size);
  172. #endif
  173. break;
  174. default:
  175. partition_usage = "Unknown data";
  176. break;
  177. }
  178. break; /* PARTITION_USAGE_DATA */
  179. default: /* other partition type */
  180. break;
  181. }
  182. /* print partition type info */
  183. ESP_LOGI(TAG, "%2d %-16s %-16s %02x %02x %08x %08x", i, partition->label, partition_usage,
  184. partition->type, partition->subtype,
  185. partition->pos.offset, partition->pos.size);
  186. }
  187. bootloader_munmap(partitions);
  188. ESP_LOGI(TAG, "End of partition table");
  189. return true;
  190. }
  191. /* Given a partition index, return the partition position data from the bootloader_state_t structure */
  192. static esp_partition_pos_t index_to_partition(const bootloader_state_t *bs, int index)
  193. {
  194. if (index == FACTORY_INDEX) {
  195. return bs->factory;
  196. }
  197. if (index == TEST_APP_INDEX) {
  198. return bs->test;
  199. }
  200. if (index >= 0 && index < MAX_OTA_SLOTS && index < (int)bs->app_count) {
  201. return bs->ota[index];
  202. }
  203. esp_partition_pos_t invalid = { 0 };
  204. return invalid;
  205. }
  206. static void log_invalid_app_partition(int index)
  207. {
  208. const char *not_bootable = " is not bootable"; /* save a few string literal bytes */
  209. switch (index) {
  210. case FACTORY_INDEX:
  211. ESP_LOGE(TAG, "Factory app partition%s", not_bootable);
  212. break;
  213. case TEST_APP_INDEX:
  214. ESP_LOGE(TAG, "Factory test app partition%s", not_bootable);
  215. break;
  216. default:
  217. ESP_LOGE(TAG, "OTA app partition slot %d%s", index, not_bootable);
  218. break;
  219. }
  220. }
  221. static esp_err_t write_otadata(esp_ota_select_entry_t *otadata, uint32_t offset, bool write_encrypted)
  222. {
  223. esp_err_t err = bootloader_flash_erase_sector(offset / FLASH_SECTOR_SIZE);
  224. if (err == ESP_OK) {
  225. err = bootloader_flash_write(offset, otadata, sizeof(esp_ota_select_entry_t), write_encrypted);
  226. }
  227. if (err != ESP_OK) {
  228. ESP_LOGE(TAG, "Error in write_otadata operation. err = 0x%x", err);
  229. }
  230. return err;
  231. }
  232. static bool check_anti_rollback(const esp_partition_pos_t *partition)
  233. {
  234. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  235. esp_app_desc_t app_desc;
  236. esp_err_t err = bootloader_common_get_partition_description(partition, &app_desc);
  237. return err == ESP_OK && esp_efuse_check_secure_version(app_desc.secure_version) == true;
  238. #else
  239. return true;
  240. #endif
  241. }
  242. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  243. static void update_anti_rollback(const esp_partition_pos_t *partition)
  244. {
  245. esp_app_desc_t app_desc;
  246. esp_err_t err = bootloader_common_get_partition_description(partition, &app_desc);
  247. if (err == ESP_OK) {
  248. esp_efuse_update_secure_version(app_desc.secure_version);
  249. }
  250. }
  251. static int get_active_otadata_with_check_anti_rollback(const bootloader_state_t *bs, esp_ota_select_entry_t *two_otadata)
  252. {
  253. uint32_t ota_seq;
  254. uint32_t ota_slot;
  255. bool valid_otadata[2];
  256. valid_otadata[0] = bootloader_common_ota_select_valid(&two_otadata[0]);
  257. valid_otadata[1] = bootloader_common_ota_select_valid(&two_otadata[1]);
  258. bool sec_ver_valid_otadata[2] = { 0 };
  259. for (int i = 0; i < 2; ++i) {
  260. if (valid_otadata[i] == true) {
  261. ota_seq = two_otadata[i].ota_seq - 1; // Raw OTA sequence number. May be more than # of OTA slots
  262. ota_slot = ota_seq % bs->app_count; // Actual OTA partition selection
  263. if (check_anti_rollback(&bs->ota[ota_slot]) == false) {
  264. // invalid. This otadata[i] will not be selected as active.
  265. ESP_LOGD(TAG, "OTA slot %d has an app with secure_version, this version is smaller than in the device. This OTA slot will not be selected.", ota_slot);
  266. } else {
  267. sec_ver_valid_otadata[i] = true;
  268. }
  269. }
  270. }
  271. return bootloader_common_select_otadata(two_otadata, sec_ver_valid_otadata, true);
  272. }
  273. #endif
  274. int bootloader_utility_get_selected_boot_partition(const bootloader_state_t *bs)
  275. {
  276. esp_ota_select_entry_t otadata[2];
  277. int boot_index = FACTORY_INDEX;
  278. if (bs->ota_info.offset == 0) {
  279. return FACTORY_INDEX;
  280. }
  281. if (read_otadata(&bs->ota_info, otadata) != ESP_OK) {
  282. return INVALID_INDEX;
  283. }
  284. ota_has_initial_contents = false;
  285. ESP_LOGD(TAG, "otadata[0]: sequence values 0x%08x", otadata[0].ota_seq);
  286. ESP_LOGD(TAG, "otadata[1]: sequence values 0x%08x", otadata[1].ota_seq);
  287. #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
  288. bool write_encrypted = esp_flash_encryption_enabled();
  289. for (int i = 0; i < 2; ++i) {
  290. if (otadata[i].ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  291. ESP_LOGD(TAG, "otadata[%d] is marking as ABORTED", i);
  292. otadata[i].ota_state = ESP_OTA_IMG_ABORTED;
  293. write_otadata(&otadata[i], bs->ota_info.offset + FLASH_SECTOR_SIZE * i, write_encrypted);
  294. }
  295. }
  296. #endif
  297. #ifndef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  298. if ((bootloader_common_ota_select_invalid(&otadata[0]) &&
  299. bootloader_common_ota_select_invalid(&otadata[1])) ||
  300. bs->app_count == 0) {
  301. 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);
  302. if (bs->factory.offset != 0) {
  303. ESP_LOGI(TAG, "Defaulting to factory image");
  304. boot_index = FACTORY_INDEX;
  305. } else {
  306. ESP_LOGI(TAG, "No factory image, trying OTA 0");
  307. boot_index = 0;
  308. // Try to boot from ota_0.
  309. if ((otadata[0].ota_seq == UINT32_MAX || otadata[0].crc != bootloader_common_ota_select_crc(&otadata[0])) &&
  310. (otadata[1].ota_seq == UINT32_MAX || otadata[1].crc != bootloader_common_ota_select_crc(&otadata[1]))) {
  311. // Factory is not found and both otadata are initial(0xFFFFFFFF) or incorrect crc.
  312. // will set correct ota_seq.
  313. ota_has_initial_contents = true;
  314. }
  315. }
  316. } else {
  317. int active_otadata = bootloader_common_get_active_otadata(otadata);
  318. #else
  319. ESP_LOGI(TAG, "Enabled a check secure version of app for anti rollback");
  320. ESP_LOGI(TAG, "Secure version (from eFuse) = %d", esp_efuse_read_secure_version());
  321. // When CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK is enabled factory partition should not be in partition table, only two ota_app are there.
  322. if ((otadata[0].ota_seq == UINT32_MAX || otadata[0].crc != bootloader_common_ota_select_crc(&otadata[0])) &&
  323. (otadata[1].ota_seq == UINT32_MAX || otadata[1].crc != bootloader_common_ota_select_crc(&otadata[1]))) {
  324. ESP_LOGI(TAG, "otadata[0..1] in initial state");
  325. // both otadata are initial(0xFFFFFFFF) or incorrect crc.
  326. // will set correct ota_seq.
  327. ota_has_initial_contents = true;
  328. } else {
  329. int active_otadata = get_active_otadata_with_check_anti_rollback(bs, otadata);
  330. #endif
  331. if (active_otadata != -1) {
  332. ESP_LOGD(TAG, "Active otadata[%d]", active_otadata);
  333. uint32_t ota_seq = otadata[active_otadata].ota_seq - 1; // Raw OTA sequence number. May be more than # of OTA slots
  334. boot_index = ota_seq % bs->app_count; // Actual OTA partition selection
  335. ESP_LOGD(TAG, "Mapping seq %d -> OTA slot %d", ota_seq, boot_index);
  336. #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
  337. if (otadata[active_otadata].ota_state == ESP_OTA_IMG_NEW) {
  338. ESP_LOGD(TAG, "otadata[%d] is selected as new and marked PENDING_VERIFY state", active_otadata);
  339. otadata[active_otadata].ota_state = ESP_OTA_IMG_PENDING_VERIFY;
  340. write_otadata(&otadata[active_otadata], bs->ota_info.offset + FLASH_SECTOR_SIZE * active_otadata, write_encrypted);
  341. }
  342. #endif // CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
  343. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  344. if (otadata[active_otadata].ota_state == ESP_OTA_IMG_VALID) {
  345. update_anti_rollback(&bs->ota[boot_index]);
  346. }
  347. #endif // CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  348. } else if (bs->factory.offset != 0) {
  349. ESP_LOGE(TAG, "ota data partition invalid, falling back to factory");
  350. boot_index = FACTORY_INDEX;
  351. } else {
  352. ESP_LOGE(TAG, "ota data partition invalid and no factory, will try all partitions");
  353. boot_index = FACTORY_INDEX;
  354. }
  355. }
  356. return boot_index;
  357. }
  358. /* Return true if a partition has a valid app image that was successfully loaded */
  359. static bool try_load_partition(const esp_partition_pos_t *partition, esp_image_metadata_t *data)
  360. {
  361. if (partition->size == 0) {
  362. ESP_LOGD(TAG, "Can't boot from zero-length partition");
  363. return false;
  364. }
  365. #ifdef BOOTLOADER_BUILD
  366. if (bootloader_load_image(partition, data) == ESP_OK) {
  367. ESP_LOGI(TAG, "Loaded app from partition at offset 0x%x",
  368. partition->offset);
  369. return true;
  370. }
  371. #endif
  372. return false;
  373. }
  374. // ota_has_initial_contents flag is set if factory does not present in partition table and
  375. // otadata has initial content(0xFFFFFFFF), then set actual ota_seq.
  376. static void set_actual_ota_seq(const bootloader_state_t *bs, int index)
  377. {
  378. if (index > FACTORY_INDEX && ota_has_initial_contents == true) {
  379. esp_ota_select_entry_t otadata;
  380. memset(&otadata, 0xFF, sizeof(otadata));
  381. otadata.ota_seq = index + 1;
  382. otadata.ota_state = ESP_OTA_IMG_VALID;
  383. otadata.crc = bootloader_common_ota_select_crc(&otadata);
  384. bool write_encrypted = esp_flash_encryption_enabled();
  385. write_otadata(&otadata, bs->ota_info.offset + FLASH_SECTOR_SIZE * 0, write_encrypted);
  386. ESP_LOGI(TAG, "Set actual ota_seq=%d in otadata[0]", otadata.ota_seq);
  387. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  388. update_anti_rollback(&bs->ota[index]);
  389. #endif
  390. }
  391. #if defined( CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP ) || defined( CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC )
  392. esp_partition_pos_t partition = index_to_partition(bs, index);
  393. bootloader_common_update_rtc_retain_mem(&partition, true);
  394. #endif
  395. }
  396. #ifdef CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP
  397. void bootloader_utility_load_boot_image_from_deep_sleep(void)
  398. {
  399. if (rtc_get_reset_reason(0) == DEEPSLEEP_RESET) {
  400. esp_partition_pos_t *partition = bootloader_common_get_rtc_retain_mem_partition();
  401. if (partition != NULL) {
  402. esp_image_metadata_t image_data;
  403. if (bootloader_load_image_no_verify(partition, &image_data) == ESP_OK) {
  404. ESP_LOGI(TAG, "Fast booting app from partition at offset 0x%x", partition->offset);
  405. bootloader_common_update_rtc_retain_mem(NULL, true);
  406. load_image(&image_data);
  407. }
  408. }
  409. ESP_LOGE(TAG, "Fast booting is not successful");
  410. ESP_LOGI(TAG, "Try to load an app as usual with all validations");
  411. }
  412. }
  413. #endif
  414. #define TRY_LOG_FORMAT "Trying partition index %d offs 0x%x size 0x%x"
  415. void bootloader_utility_load_boot_image(const bootloader_state_t *bs, int start_index)
  416. {
  417. int index = start_index;
  418. esp_partition_pos_t part;
  419. esp_image_metadata_t image_data;
  420. if (start_index == TEST_APP_INDEX) {
  421. if (check_anti_rollback(&bs->test) && try_load_partition(&bs->test, &image_data)) {
  422. load_image(&image_data);
  423. } else {
  424. ESP_LOGE(TAG, "No bootable test partition in the partition table");
  425. bootloader_reset();
  426. }
  427. }
  428. /* work backwards from start_index, down to the factory app */
  429. for (index = start_index; index >= FACTORY_INDEX; index--) {
  430. part = index_to_partition(bs, index);
  431. if (part.size == 0) {
  432. continue;
  433. }
  434. ESP_LOGD(TAG, TRY_LOG_FORMAT, index, part.offset, part.size);
  435. if (check_anti_rollback(&part) && try_load_partition(&part, &image_data)) {
  436. set_actual_ota_seq(bs, index);
  437. load_image(&image_data);
  438. }
  439. log_invalid_app_partition(index);
  440. }
  441. /* failing that work forwards from start_index, try valid OTA slots */
  442. for (index = start_index + 1; index < (int)bs->app_count; index++) {
  443. part = index_to_partition(bs, index);
  444. if (part.size == 0) {
  445. continue;
  446. }
  447. ESP_LOGD(TAG, TRY_LOG_FORMAT, index, part.offset, part.size);
  448. if (check_anti_rollback(&part) && try_load_partition(&part, &image_data)) {
  449. set_actual_ota_seq(bs, index);
  450. load_image(&image_data);
  451. }
  452. log_invalid_app_partition(index);
  453. }
  454. if (check_anti_rollback(&bs->test) && try_load_partition(&bs->test, &image_data)) {
  455. ESP_LOGW(TAG, "Falling back to test app as only bootable partition");
  456. load_image(&image_data);
  457. }
  458. ESP_LOGE(TAG, "No bootable app partitions in the partition table");
  459. bzero(&image_data, sizeof(esp_image_metadata_t));
  460. bootloader_reset();
  461. }
  462. // Copy loaded segments to RAM, set up caches for mapped segments, and start application.
  463. static void load_image(const esp_image_metadata_t *image_data)
  464. {
  465. /**
  466. * Rough steps for a first boot, when encryption and secure boot are both disabled:
  467. * 1) Generate secure boot key and write to EFUSE.
  468. * 2) Write plaintext digest based on plaintext bootloader
  469. * 3) Generate flash encryption key and write to EFUSE.
  470. * 4) Encrypt flash in-place including bootloader, then digest,
  471. * then app partitions and other encrypted partitions
  472. * 5) Burn EFUSE to enable flash encryption (FLASH_CRYPT_CNT)
  473. * 6) Burn EFUSE to enable secure boot (ABS_DONE_0)
  474. *
  475. * If power failure happens during Step 1, probably the next boot will continue from Step 2.
  476. * There is some small chance that EFUSEs will be part-way through being written so will be
  477. * somehow corrupted here. Thankfully this window of time is very small, but if that's the
  478. * case, one has to use the espefuse tool to manually set the remaining bits and enable R/W
  479. * protection. Once the relevant EFUSE bits are set and R/W protected, Step 1 will be skipped
  480. * successfully on further reboots.
  481. *
  482. * If power failure happens during Step 2, Step 1 will be skipped and Step 2 repeated:
  483. * the digest will get re-written on the next boot.
  484. *
  485. * If power failure happens during Step 3, it's possible that EFUSE was partially written
  486. * with the generated flash encryption key, though the time window for that would again
  487. * be very small. On reboot, Step 1 will be skipped and Step 2 repeated, though, Step 3
  488. * may fail due to the above mentioned reason, in which case, one has to use the espefuse
  489. * tool to manually set the remaining bits and enable R/W protection. Once the relevant EFUSE
  490. * bits are set and R/W protected, Step 3 will be skipped successfully on further reboots.
  491. *
  492. * If power failure happens after start of 4 and before end of 5, the next boot will fail
  493. * (bootloader header is encrypted and flash encryption isn't enabled yet, so it looks like
  494. * noise to the ROM bootloader). The check in the ROM is pretty basic so if the first byte of
  495. * ciphertext happens to be the magic byte E9 then it may try to boot, but it will definitely
  496. * crash (no chance that the remaining ciphertext will look like a valid bootloader image).
  497. * Only solution is to reflash with all plaintext and the whole process starts again: skips
  498. * Step 1, repeats Step 2, skips Step 3, etc.
  499. *
  500. * If power failure happens after 5 but before 6, the device will reboot with flash
  501. * encryption on and will regenerate an encrypted digest in Step 2. This should still
  502. * be valid as the input data for the digest is read via flash cache (so will be decrypted)
  503. * and the code in secure_boot_generate() tells bootloader_flash_write() to encrypt the data
  504. * on write if flash encryption is enabled. Steps 3 - 5 are skipped (encryption already on),
  505. * then Step 6 enables secure boot.
  506. */
  507. #if defined(CONFIG_SECURE_BOOT) || defined(CONFIG_SECURE_FLASH_ENC_ENABLED)
  508. esp_err_t err;
  509. #endif
  510. #ifdef CONFIG_SECURE_BOOT_V2_ENABLED
  511. err = esp_secure_boot_v2_permanently_enable(image_data);
  512. if (err != ESP_OK) {
  513. ESP_LOGE(TAG, "Secure Boot v2 failed (%d)", err);
  514. return;
  515. }
  516. #endif
  517. #ifdef CONFIG_SECURE_BOOT_V1_ENABLED
  518. /* Steps 1 & 2 (see above for full description):
  519. * 1) Generate secure boot EFUSE key
  520. * 2) Compute digest of plaintext bootloader
  521. */
  522. err = esp_secure_boot_generate_digest();
  523. if (err != ESP_OK) {
  524. ESP_LOGE(TAG, "Bootloader digest generation for secure boot failed (%d).", err);
  525. return;
  526. }
  527. #endif
  528. #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
  529. /* Steps 3, 4 & 5 (see above for full description):
  530. * 3) Generate flash encryption EFUSE key
  531. * 4) Encrypt flash contents
  532. * 5) Burn EFUSE to enable flash encryption
  533. */
  534. ESP_LOGI(TAG, "Checking flash encryption...");
  535. bool flash_encryption_enabled = esp_flash_encryption_enabled();
  536. err = esp_flash_encrypt_check_and_update();
  537. if (err != ESP_OK) {
  538. ESP_LOGE(TAG, "Flash encryption check failed (%d).", err);
  539. return;
  540. }
  541. #endif
  542. #ifdef CONFIG_SECURE_BOOT_V1_ENABLED
  543. /* Step 6 (see above for full description):
  544. * 6) Burn EFUSE to enable secure boot
  545. */
  546. ESP_LOGI(TAG, "Checking secure boot...");
  547. err = esp_secure_boot_permanently_enable();
  548. if (err != ESP_OK) {
  549. ESP_LOGE(TAG, "FAILED TO ENABLE SECURE BOOT (%d).", err);
  550. /* Panic here as secure boot is not properly enabled
  551. due to one of the reasons in above function
  552. */
  553. abort();
  554. }
  555. #endif
  556. #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
  557. if (!flash_encryption_enabled && esp_flash_encryption_enabled()) {
  558. /* Flash encryption was just enabled for the first time,
  559. so issue a system reset to ensure flash encryption
  560. cache resets properly */
  561. ESP_LOGI(TAG, "Resetting with flash encryption enabled...");
  562. esp_rom_uart_tx_wait_idle(0);
  563. bootloader_reset();
  564. }
  565. #endif
  566. ESP_LOGI(TAG, "Disabling RNG early entropy source...");
  567. bootloader_random_disable();
  568. // copy loaded segments to RAM, set up caches for mapped segments, and start application
  569. unpack_load_app(image_data);
  570. }
  571. static void unpack_load_app(const esp_image_metadata_t *data)
  572. {
  573. uint32_t drom_addr = 0;
  574. uint32_t drom_load_addr = 0;
  575. uint32_t drom_size = 0;
  576. uint32_t irom_addr = 0;
  577. uint32_t irom_load_addr = 0;
  578. uint32_t irom_size = 0;
  579. // Find DROM & IROM addresses, to configure cache mappings
  580. for (int i = 0; i < data->image.segment_count; i++) {
  581. const esp_image_segment_header_t *header = &data->segments[i];
  582. if (header->load_addr >= SOC_DROM_LOW && header->load_addr < SOC_DROM_HIGH) {
  583. if (drom_addr != 0) {
  584. ESP_LOGE(TAG, MAP_ERR_MSG, "DROM");
  585. } else {
  586. ESP_LOGD(TAG, "Mapping segment %d as %s", i, "DROM");
  587. }
  588. drom_addr = data->segment_data[i];
  589. drom_load_addr = header->load_addr;
  590. drom_size = header->data_len;
  591. }
  592. if (header->load_addr >= SOC_IROM_LOW && header->load_addr < SOC_IROM_HIGH) {
  593. if (irom_addr != 0) {
  594. ESP_LOGE(TAG, MAP_ERR_MSG, "IROM");
  595. } else {
  596. ESP_LOGD(TAG, "Mapping segment %d as %s", i, "IROM");
  597. }
  598. irom_addr = data->segment_data[i];
  599. irom_load_addr = header->load_addr;
  600. irom_size = header->data_len;
  601. }
  602. }
  603. ESP_LOGD(TAG, "calling set_cache_and_start_app");
  604. set_cache_and_start_app(drom_addr,
  605. drom_load_addr,
  606. drom_size,
  607. irom_addr,
  608. irom_load_addr,
  609. irom_size,
  610. data->image.entry_addr);
  611. }
  612. static void set_cache_and_start_app(
  613. uint32_t drom_addr,
  614. uint32_t drom_load_addr,
  615. uint32_t drom_size,
  616. uint32_t irom_addr,
  617. uint32_t irom_load_addr,
  618. uint32_t irom_size,
  619. uint32_t entry_addr)
  620. {
  621. int rc;
  622. ESP_LOGD(TAG, "configure drom and irom and start");
  623. #if CONFIG_IDF_TARGET_ESP32
  624. Cache_Read_Disable(0);
  625. Cache_Flush(0);
  626. #elif CONFIG_IDF_TARGET_ESP32S2
  627. uint32_t autoload = Cache_Suspend_ICache();
  628. Cache_Invalidate_ICache_All();
  629. #elif CONFIG_IDF_TARGET_ESP32S3
  630. uint32_t autoload = Cache_Suspend_DCache();
  631. Cache_Invalidate_DCache_All();
  632. #elif CONFIG_IDF_TARGET_ESP32C3
  633. uint32_t autoload = Cache_Suspend_ICache();
  634. Cache_Invalidate_ICache_All();
  635. #endif
  636. /* Clear the MMU entries that are already set up,
  637. so the new app only has the mappings it creates.
  638. */
  639. #if CONFIG_IDF_TARGET_ESP32
  640. for (int i = 0; i < DPORT_FLASH_MMU_TABLE_SIZE; i++) {
  641. DPORT_PRO_FLASH_MMU_TABLE[i] = DPORT_FLASH_MMU_TABLE_INVALID_VAL;
  642. }
  643. #else
  644. for (size_t i = 0; i < FLASH_MMU_TABLE_SIZE; i++) {
  645. FLASH_MMU_TABLE[i] = MMU_TABLE_INVALID_VAL;
  646. }
  647. #endif
  648. uint32_t drom_load_addr_aligned = drom_load_addr & MMU_FLASH_MASK;
  649. uint32_t drom_page_count = bootloader_cache_pages_to_map(drom_size, drom_load_addr);
  650. ESP_LOGV(TAG, "d mmu set paddr=%08x vaddr=%08x size=%d n=%d",
  651. drom_addr & MMU_FLASH_MASK, drom_load_addr_aligned, drom_size, drom_page_count);
  652. #if CONFIG_IDF_TARGET_ESP32
  653. rc = cache_flash_mmu_set(0, 0, drom_load_addr_aligned, drom_addr & MMU_FLASH_MASK, 64, drom_page_count);
  654. #elif CONFIG_IDF_TARGET_ESP32S2
  655. rc = Cache_Ibus_MMU_Set(MMU_ACCESS_FLASH, drom_load_addr & 0xffff0000, drom_addr & 0xffff0000, 64, drom_page_count, 0);
  656. #elif CONFIG_IDF_TARGET_ESP32S3
  657. rc = Cache_Dbus_MMU_Set(MMU_ACCESS_FLASH, drom_load_addr & 0xffff0000, drom_addr & 0xffff0000, 64, drom_page_count, 0);
  658. #elif CONFIG_IDF_TARGET_ESP32C3
  659. rc = Cache_Dbus_MMU_Set(MMU_ACCESS_FLASH, drom_load_addr & 0xffff0000, drom_addr & 0xffff0000, 64, drom_page_count, 0);
  660. #endif
  661. ESP_LOGV(TAG, "rc=%d", rc);
  662. #if CONFIG_IDF_TARGET_ESP32
  663. rc = cache_flash_mmu_set(1, 0, drom_load_addr_aligned, drom_addr & MMU_FLASH_MASK, 64, drom_page_count);
  664. ESP_LOGV(TAG, "rc=%d", rc);
  665. #endif
  666. uint32_t irom_load_addr_aligned = irom_load_addr & MMU_FLASH_MASK;
  667. uint32_t irom_page_count = bootloader_cache_pages_to_map(irom_size, irom_load_addr);
  668. ESP_LOGV(TAG, "i mmu set paddr=%08x vaddr=%08x size=%d n=%d",
  669. irom_addr & MMU_FLASH_MASK, irom_load_addr_aligned, irom_size, irom_page_count);
  670. #if CONFIG_IDF_TARGET_ESP32
  671. rc = cache_flash_mmu_set(0, 0, irom_load_addr_aligned, irom_addr & MMU_FLASH_MASK, 64, irom_page_count);
  672. #elif CONFIG_IDF_TARGET_ESP32S2
  673. uint32_t iram1_used = 0;
  674. if (irom_load_addr + irom_size > IRAM1_ADDRESS_LOW) {
  675. iram1_used = 1;
  676. }
  677. if (iram1_used) {
  678. rc = Cache_Ibus_MMU_Set(MMU_ACCESS_FLASH, IRAM0_ADDRESS_LOW, 0, 64, 64, 1);
  679. rc = Cache_Ibus_MMU_Set(MMU_ACCESS_FLASH, IRAM1_ADDRESS_LOW, 0, 64, 64, 1);
  680. REG_CLR_BIT(EXTMEM_PRO_ICACHE_CTRL1_REG, EXTMEM_PRO_ICACHE_MASK_IRAM1);
  681. }
  682. rc = Cache_Ibus_MMU_Set(MMU_ACCESS_FLASH, irom_load_addr & 0xffff0000, irom_addr & 0xffff0000, 64, irom_page_count, 0);
  683. #elif CONFIG_IDF_TARGET_ESP32S3
  684. rc = Cache_Ibus_MMU_Set(MMU_ACCESS_FLASH, irom_load_addr & 0xffff0000, irom_addr & 0xffff0000, 64, irom_page_count, 0);
  685. #elif CONFIG_IDF_TARGET_ESP32C3
  686. rc = Cache_Ibus_MMU_Set(MMU_ACCESS_FLASH, irom_load_addr & 0xffff0000, irom_addr & 0xffff0000, 64, irom_page_count, 0);
  687. #endif
  688. ESP_LOGV(TAG, "rc=%d", rc);
  689. #if CONFIG_IDF_TARGET_ESP32
  690. rc = cache_flash_mmu_set(1, 0, irom_load_addr_aligned, irom_addr & MMU_FLASH_MASK, 64, irom_page_count);
  691. ESP_LOGV(TAG, "rc=%d", rc);
  692. DPORT_REG_CLR_BIT( DPORT_PRO_CACHE_CTRL1_REG,
  693. (DPORT_PRO_CACHE_MASK_IRAM0) | (DPORT_PRO_CACHE_MASK_IRAM1 & 0) |
  694. (DPORT_PRO_CACHE_MASK_IROM0 & 0) | DPORT_PRO_CACHE_MASK_DROM0 |
  695. DPORT_PRO_CACHE_MASK_DRAM1 );
  696. DPORT_REG_CLR_BIT( DPORT_APP_CACHE_CTRL1_REG,
  697. (DPORT_APP_CACHE_MASK_IRAM0) | (DPORT_APP_CACHE_MASK_IRAM1 & 0) |
  698. (DPORT_APP_CACHE_MASK_IROM0 & 0) | DPORT_APP_CACHE_MASK_DROM0 |
  699. DPORT_APP_CACHE_MASK_DRAM1 );
  700. #elif CONFIG_IDF_TARGET_ESP32S2
  701. REG_CLR_BIT( EXTMEM_PRO_ICACHE_CTRL1_REG, (EXTMEM_PRO_ICACHE_MASK_IRAM0) | (EXTMEM_PRO_ICACHE_MASK_IRAM1 & 0) | EXTMEM_PRO_ICACHE_MASK_DROM0 );
  702. #elif CONFIG_IDF_TARGET_ESP32S3
  703. REG_CLR_BIT(EXTMEM_DCACHE_CTRL1_REG, EXTMEM_DCACHE_SHUT_CORE0_BUS);
  704. #if !CONFIG_FREERTOS_UNICORE
  705. REG_CLR_BIT(EXTMEM_DCACHE_CTRL1_REG, EXTMEM_DCACHE_SHUT_CORE1_BUS);
  706. #endif
  707. #elif CONFIG_IDF_TARGET_ESP32C3
  708. REG_CLR_BIT(EXTMEM_ICACHE_CTRL1_REG, EXTMEM_ICACHE_SHUT_IBUS);
  709. REG_CLR_BIT(EXTMEM_ICACHE_CTRL1_REG, EXTMEM_ICACHE_SHUT_DBUS);
  710. #endif
  711. #if CONFIG_IDF_TARGET_ESP32
  712. Cache_Read_Enable(0);
  713. #elif CONFIG_IDF_TARGET_ESP32S2
  714. Cache_Resume_ICache(autoload);
  715. #elif CONFIG_IDF_TARGET_ESP32S3
  716. Cache_Resume_DCache(autoload);
  717. #elif CONFIG_IDF_TARGET_ESP32C3
  718. Cache_Resume_ICache(autoload);
  719. #endif
  720. // Application will need to do Cache_Flush(1) and Cache_Read_Enable(1)
  721. ESP_LOGD(TAG, "start: 0x%08x", entry_addr);
  722. bootloader_atexit();
  723. typedef void (*entry_t)(void) __attribute__((noreturn));
  724. entry_t entry = ((entry_t) entry_addr);
  725. // TODO: we have used quite a bit of stack at this point.
  726. // use "movsp" instruction to reset stack back to where ROM stack starts.
  727. (*entry)();
  728. }
  729. void bootloader_reset(void)
  730. {
  731. #ifdef BOOTLOADER_BUILD
  732. bootloader_atexit();
  733. esp_rom_delay_us(1000); /* Allow last byte to leave FIFO */
  734. REG_WRITE(RTC_CNTL_OPTIONS0_REG, RTC_CNTL_SW_SYS_RST);
  735. while (1) { } /* This line will never be reached, used to keep gcc happy */
  736. #else
  737. abort(); /* This function should really not be called from application code */
  738. #endif
  739. }
  740. void bootloader_atexit(void)
  741. {
  742. bootloader_console_deinit();
  743. }
  744. esp_err_t bootloader_sha256_hex_to_str(char *out_str, const uint8_t *in_array_hex, size_t len)
  745. {
  746. if (out_str == NULL || in_array_hex == NULL || len == 0) {
  747. return ESP_ERR_INVALID_ARG;
  748. }
  749. for (size_t i = 0; i < len; i++) {
  750. for (int shift = 0; shift < 2; shift++) {
  751. uint8_t nibble = (in_array_hex[i] >> (shift ? 0 : 4)) & 0x0F;
  752. if (nibble < 10) {
  753. out_str[i * 2 + shift] = '0' + nibble;
  754. } else {
  755. out_str[i * 2 + shift] = 'a' + nibble - 10;
  756. }
  757. }
  758. }
  759. return ESP_OK;
  760. }
  761. void bootloader_debug_buffer(const void *buffer, size_t length, const char *label)
  762. {
  763. #if BOOT_LOG_LEVEL >= LOG_LEVEL_DEBUG
  764. assert(length <= 128); // Avoid unbounded VLA size
  765. const uint8_t *bytes = (const uint8_t *)buffer;
  766. char hexbuf[length * 2 + 1];
  767. hexbuf[length * 2] = 0;
  768. for (size_t i = 0; i < length; i++) {
  769. for (int shift = 0; shift < 2; shift++) {
  770. uint8_t nibble = (bytes[i] >> (shift ? 0 : 4)) & 0x0F;
  771. if (nibble < 10) {
  772. hexbuf[i * 2 + shift] = '0' + nibble;
  773. } else {
  774. hexbuf[i * 2 + shift] = 'a' + nibble - 10;
  775. }
  776. }
  777. }
  778. ESP_LOGD(TAG, "%s: %s", label, hexbuf);
  779. #endif
  780. }
  781. esp_err_t bootloader_sha256_flash_contents(uint32_t flash_offset, uint32_t len, uint8_t *digest)
  782. {
  783. if (digest == NULL) {
  784. return ESP_ERR_INVALID_ARG;
  785. }
  786. /* Handling firmware images larger than MMU capacity */
  787. uint32_t mmu_free_pages_count = bootloader_mmap_get_free_pages();
  788. bootloader_sha256_handle_t sha_handle = NULL;
  789. sha_handle = bootloader_sha256_start();
  790. if (sha_handle == NULL) {
  791. return ESP_ERR_NO_MEM;
  792. }
  793. while (len > 0) {
  794. uint32_t mmu_page_offset = ((flash_offset & MMAP_ALIGNED_MASK) != 0) ? 1 : 0; /* Skip 1st MMU Page if it is already populated */
  795. uint32_t partial_image_len = MIN(len, ((mmu_free_pages_count - mmu_page_offset) * SPI_FLASH_MMU_PAGE_SIZE)); /* Read the image that fits in the free MMU pages */
  796. const void * image = bootloader_mmap(flash_offset, partial_image_len);
  797. if (image == NULL) {
  798. bootloader_sha256_finish(sha_handle, NULL);
  799. return ESP_FAIL;
  800. }
  801. bootloader_sha256_data(sha_handle, image, partial_image_len);
  802. bootloader_munmap(image);
  803. flash_offset += partial_image_len;
  804. len -= partial_image_len;
  805. }
  806. bootloader_sha256_finish(sha_handle, digest);
  807. return ESP_OK;
  808. }