STM32L4 + SD + STM32CubeMX v5.0.0: SD clock speed during call to SDMMC_CmdSendSCR (as part of switch to 4-bit bus) is too fast for many SD cards
The function BSP_SD_Init() is called once the basic SD card initialisation is complete, and after the SD clock speed has switched from 400 kHz(*) to full speed.
If the bus has been configured in Cube to use 4-bit mode, the following call chain occurs, which ultimately reads the SD card's SCR register, to check if it supports 4-bit mode:
BSP_SD_Init() -> HAL_SD_ConfigWideBusOperation() -> SD_WideBus_Enable() -> SD_FindSCR() -> SDMMC_CmdSendSCR()
We found that different cards respond differently to this command at full clock speed. Some work most of the time, but sometimes fail. Some respond to the command without error - but report that the register contents (stored in scr) are zero. And some never respond to the command, causing the code to enter the timeout loop - which is unfortunate because SDMMC_DATATIMEOUT is set to (essentially) forever, so the code gets stuck here.
Although the SD spec (if we've understood it correctly) seems to suggest that it should be fine to read the SCR register at any speed, this doesn't seem to be true in practice. So, we modified BSP_SD_Init() to reduce the clock speed to 400 kHz before the call to HAL_SD_ConfigWideBusOperation() - and this solved the problem completely.
It wasn't necessary to change the clock speed back again ourselves, as this happens in HAL_SD_ConfigWideBusOperation() if the SCR read is successful.
So we recommend that ST change the library code, whether in the default BSP_SD_Init() or elsewhere, so that the SCR read occurs at 400 kHz.
(*) Actually, the initialisation SD clock speed is only set to 400 kHz if the SD peripheral clock is 48 MHz, as the library doesn't check what its true value is. Hence SDMMC_INIT_CLK_DIV is fixed at 0x76, giving a divider value of 120. All this means is that if you're using a slower peripheral clock, then the initialisation clock speed will be below 400 kHz. This is harmless, but means that SD setup may take slightly longer.