cancel
Showing results for 
Search instead for 
Did you mean: 

Severe error in Azure RTOS FileX, corrupts memory, solution

DmitryR
Associate II

Hi all,

 

Synopsis

I have just found a severe error in FileX that looks like buffer overrun in fx_file_read(), but the problem is much deeper.

This function leads to the function sd_read_data() which when invoked with use_scratch_buffer = 0 reads sectors to a user buffer directly. Unfortunately caller of the sd_read_data() (function fx_stm32_sd_driver()) checks buffer alignment for 4 only despite if project uses data cache or not. What happens next is very simple: sd_read_data() invalidates the cache for the entire buffer. If it is not aligned to cache line size then some bytes around it are also invalidated. If these bytes were dirty in cache they are lost. If the user buffer is allocated in the heap it hopelessly corrupts it. 

 

Workarounds 

  1. In the function fx_stm32_sd_read_blocks(), in /*USER CODE*/ section BEFORE the call to HAL_SD_ReadBlocks_DMA(), add the following code:

    clean_cache_by_addr(buffer, 1);

    clean_cache_by_addr((((char*)buffer) + hsd1.SdCard.BlockSize * total_blocks), 1);

    This will write cache lines surrounding the buffer to memory and make invalidating them later safe (of course if they do not change during the HAL call which is less probable). Please note that there is one another error in the macro: it does not add braces around arguments. So if you write clean_cache_by_addr(((char*)buffer) + hsd1.SdCard.BlockSize * total_blocks, 1);
    it will not work.
  2.  In the function fx_stm32_sd_driver() replace the code

    /* the SD DMA requires a 4-byte aligned buffers */

    unaligned_buffer = (UINT)(media_ptr->fx_media_driver_buffer) & 0x3;

    with the following code:

    #if (FX_STM32_SD_CACHE_MAINTENANCE == 1)

    /* caching requires a cache-line aligned buffers */

    unaligned_buffer = (UINT)(media_ptr->fx_media_driver_buffer) & (__SCB_DCACHE_LINE_SIZE - 1);

    #else

    /* the SD DMA requires a 4-byte aligned buffers */

    unaligned_buffer = (UINT)(media_ptr->fx_media_driver_buffer) & 0x3;

    #endif

     

Conclusion

Despite of this fix my projects still crushes (but much further). I would be very thankful if any developer of the Azure RTOS pays attention to it ASAP and fixes at least this bug, and all other irregular cache handling if any. I have already lost several days with it as I first thought as usual that the error was in my code and not in OS.

 

Regards,

Dmitry

 
2 REPLIES 2
Andrew Neil
Evangelist III

@DmitryR wrote:

developer of the Azure RTOS

 

Azure RTOS is now Eclipse ThreadX:

https://techcommunity.microsoft.com/blog/iotblog/azure-rtos-transition-to-open-source-is-now-complete/4105027

So you'll find the developers at https://threadx.io/ 

Dear @andrew ,

 

I have already found you. Hope it will be enough. 

 

Regards,

Dmitry