static void initialize_nvs_partition()

in components/pkcs11_pal/source/core_pkcs11_pal.c [61:113]


static void initialize_nvs_partition()
{
    static bool nvs_inited;

    xSemaphoreTake( s_nvs_inited_mutex, portMAX_DELAY );
    if (nvs_inited == true) {
        xSemaphoreGive( s_nvs_inited_mutex );
        return;
    }

    ESP_EARLY_LOGI(TAG, "Initializing NVS partition: \"%s\"", NVS_PART_NAME);



#if CONFIG_NVS_ENCRYPTION
    if (esp_flash_encryption_enabled()) {
        const esp_partition_t *key_part = esp_partition_find_first(
                ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS, NULL);
        assert(key_part && "NVS key partition not found");

        nvs_sec_cfg_t cfg;
        esp_err_t err = nvs_flash_read_security_cfg(key_part, &cfg);
        if (err == ESP_ERR_NVS_KEYS_NOT_INITIALIZED) {
            ESP_EARLY_LOGI(TAG, "NVS key partition empty, generating keys");
            nvs_flash_generate_keys(key_part, &cfg);
        } else {
            ESP_ERROR_CHECK(err);
        }

        esp_err_t ret = nvs_flash_secure_init_partition(NVS_PART_NAME, &cfg);
        if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
            ESP_EARLY_LOGW(TAG, "Error initialising the NVS partition [%d]. Erasing the partition.", ret);
            ESP_ERROR_CHECK(nvs_flash_erase_partition(NVS_PART_NAME));
            ret = nvs_flash_secure_init_partition(NVS_PART_NAME, &cfg);
        }
        ESP_ERROR_CHECK(ret);
    } else {
#endif // CONFIG_NVS_ENCRYPTION
        esp_err_t ret = nvs_flash_init_partition(NVS_PART_NAME);
        if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
            ESP_EARLY_LOGW(TAG, "Error initialising the NVS partition [%d]. Erasing the partition.", ret);
            ESP_ERROR_CHECK(nvs_flash_erase_partition(NVS_PART_NAME));
            ret = nvs_flash_init_partition(NVS_PART_NAME);
        }
        ESP_ERROR_CHECK(ret);
#if CONFIG_NVS_ENCRYPTION
    }
#endif // CONFIG_NVS_ENCRYPTION
    nvs_inited = true;
    xSemaphoreGive( s_nvs_inited_mutex );

    return;
}