From d4d4d7324ad82509223d5bcd8cb13e71f4dafabb Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Sat, 25 Apr 2020 14:59:39 +1000 Subject: [PATCH] efuse: Don't need to burn WR_CRYPT_CNT if CRYPT_CNT is already max Reduces write cycles, and useful on ESP32 ECO3 as UART_DIS_DL is protected by the same efuse. Also fixes accidental macro definition introduced in 7635dce502b4de8fa8a32ae9a140e82fc3a72eb5 --- components/bootloader_support/src/flash_encrypt.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/components/bootloader_support/src/flash_encrypt.c b/components/bootloader_support/src/flash_encrypt.c index 2b6159eea..cf817e9a1 100644 --- a/components/bootloader_support/src/flash_encrypt.c +++ b/components/bootloader_support/src/flash_encrypt.c @@ -21,10 +21,10 @@ #include "esp_secure_boot.h" #if CONFIG_IDF_TARGET_ESP32 -#define CRYPT_CNT ESP_EFUSE_WR_DIS_FLASH_CRYPT_CNT +#define CRYPT_CNT ESP_EFUSE_FLASH_CRYPT_CNT #define WR_DIS_CRYPT_CNT ESP_EFUSE_WR_DIS_FLASH_CRYPT_CNT #elif CONFIG_IDF_TARGET_ESP32S2 -#define CRYPT_CNT ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT +#define CRYPT_CNT ESP_EFUSE_SPI_BOOT_CRYPT_CNT #define WR_DIS_CRYPT_CNT ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT #endif @@ -42,8 +42,15 @@ void esp_flash_encryption_init_checks() #ifdef CONFIG_SECURE_BOOT if (esp_secure_boot_enabled() && esp_flash_encryption_enabled()) { uint8_t flash_crypt_cnt_wr_dis = 0; - esp_efuse_read_field_blob(CRYPT_CNT, &flash_crypt_cnt_wr_dis, 1); + esp_efuse_read_field_blob(WR_DIS_CRYPT_CNT, &flash_crypt_cnt_wr_dis, 1); if (!flash_crypt_cnt_wr_dis) { + uint8_t flash_crypt_cnt = 0; + esp_efuse_read_field_blob(CRYPT_CNT, &flash_crypt_cnt, CRYPT_CNT[0]->bit_count); + if (flash_crypt_cnt == (1<<(CRYPT_CNT[0]->bit_count))-1) { + // If encryption counter is already max, no need to write protect it + // (this distinction is important on ESP32 ECO3 where write-procted FLASH_CRYPT_CNT also write-protects UART_DL_DIS) + return; + } ESP_EARLY_LOGE(TAG, "Flash encryption & Secure Boot together requires FLASH_CRYPT_CNT efuse to be write protected. Fixing now..."); esp_flash_write_protect_crypt_cnt(); } @@ -71,7 +78,7 @@ void esp_flash_write_protect_crypt_cnt(void) { uint8_t flash_crypt_cnt_wr_dis = 0; - esp_efuse_read_field_blob(CRYPT_CNT, &flash_crypt_cnt_wr_dis, 1); + esp_efuse_read_field_blob(WR_DIS_CRYPT_CNT, &flash_crypt_cnt_wr_dis, 1); if (!flash_crypt_cnt_wr_dis) { esp_efuse_write_field_cnt(WR_DIS_CRYPT_CNT, 1);