From 960eef70e8a0073440d6d7edc2c05f6e2237e0af Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Tue, 14 Nov 2023 16:46:55 +1100 Subject: [PATCH] esp32/network_wlan: Reduce RAM usage if SPIRAM fails to initialise. In ESP-IDF, enabling SPIRAM in menuconfig sets some Kconfig options: - "Wi-Fi Cache TX Buffers" enabled. By default this tries to allocate 32 of these when Wi-Fi is initialised, which requires 54,400 bytes of free heap. - Switches "Type of WiFi TX buffers" from Dynamic to Static. This pre-allocates all of the Wi-Fi transmit buffers. Not a problem if PSRAM is initialised, but it's quite a lot of RAM if PSRAM failed to initialise! As we use the same config for PSRAM & no-PSRAM builds now, this either causes Wi-Fi to fail to initialise (seen on S2) or will eat quite a lot of RAM. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton --- ports/esp32/network_wlan.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/ports/esp32/network_wlan.c b/ports/esp32/network_wlan.c index e1d16b4191..e9918efa5e 100644 --- a/ports/esp32/network_wlan.c +++ b/ports/esp32/network_wlan.c @@ -41,6 +41,7 @@ #include "esp_wifi.h" #include "esp_log.h" +#include "esp_psram.h" #ifndef NO_QSTR #include "mdns.h" @@ -206,6 +207,23 @@ void esp_initialise_wifi(void) { wlan_ap_obj.active = false; wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + #if CONFIG_SPIRAM_IGNORE_NOTFOUND + if (!esp_psram_is_initialized()) { + // If PSRAM failed to initialize, disable "Wi-Fi Cache TX Buffers" + // (default SPIRAM config ESP32_WIFI_CACHE_TX_BUFFER_NUM==32, this is 54,400 bytes of heap) + cfg.cache_tx_buf_num = 0; + cfg.feature_caps &= ~CONFIG_FEATURE_CACHE_TX_BUF_BIT; + + // Set some other options back to the non-SPIRAM default values + // to save more RAM. + // + // These can be determined from ESP-IDF components/esp_wifi/Kconfig and the + // WIFI_INIT_CONFIG_DEFAULT macro + cfg.tx_buf_type = 1; // Dynamic, this "magic number" is defined in IDF KConfig + cfg.static_tx_buf_num = 0; // Probably don't need, due to tx_buf_type + cfg.dynamic_tx_buf_num = 32; // ESP-IDF default value (maximum) + } + #endif ESP_LOGD("modnetwork", "Initializing WiFi"); esp_exceptions(esp_wifi_init(&cfg)); esp_exceptions(esp_wifi_set_storage(WIFI_STORAGE_RAM));