diff --git a/components/fatfs/src/vfs_fat_sdmmc.c b/components/fatfs/src/vfs_fat_sdmmc.c index e5956dd7b2..77620f5d87 100644 --- a/components/fatfs/src/vfs_fat_sdmmc.c +++ b/components/fatfs/src/vfs_fat_sdmmc.c @@ -39,14 +39,19 @@ esp_err_t esp_vfs_fat_sdmmc_mount(const char* base_path, sdmmc_host_init(); // enable card slot - sdmmc_host_init_slot(host_config->slot, slot_config); + esp_err_t err = sdmmc_host_init_slot(host_config->slot, slot_config); + if (err != ESP_OK) { + return err; + } + s_card = malloc(sizeof(sdmmc_card_t)); if (s_card == NULL) { - return ESP_ERR_NO_MEM; + err = ESP_ERR_NO_MEM; + goto fail; } // probe and initialize card - esp_err_t err = sdmmc_card_init(host_config, s_card); + err = sdmmc_card_init(host_config, s_card); if (err != ESP_OK) { ESP_LOGD(TAG, "sdmmc_card_init failed 0x(%x)", err); goto fail; @@ -104,6 +109,7 @@ esp_err_t esp_vfs_fat_sdmmc_mount(const char* base_path, return ESP_OK; fail: + sdmmc_host_deinit(); free(workbuf); esp_vfs_unregister(base_path); free(s_card); diff --git a/components/fatfs/test/test_fatfs.c b/components/fatfs/test/test_fatfs.c index 4f6482740c..d518652bc4 100644 --- a/components/fatfs/test/test_fatfs.c +++ b/components/fatfs/test/test_fatfs.c @@ -52,6 +52,25 @@ static void create_file_with_text(const char* name, const char* text) TEST_ASSERT_EQUAL(0, fclose(f)); } +TEST_CASE("Mount fails cleanly without card inserted", "[fatfs][ignore]") +{ + HEAP_SIZE_CAPTURE(); + sdmmc_host_t host = SDMMC_HOST_DEFAULT(); + sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); + esp_vfs_fat_sdmmc_mount_config_t mount_config = { + .format_if_mount_failed = false, + .max_files = 5 + }; + + for (int i = 0; i < 3; ++i) { + printf("Initializing card, attempt %d ", i); + esp_err_t err = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL); + printf(" err=%d\n", err); + TEST_ESP_ERR(ESP_FAIL, err); + } + HEAP_SIZE_CHECK(0); +} + TEST_CASE("can create and write file on sd card", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE();