/*
  ******************************************************************************
  * @file    mpu_config.c
  * @author  Chris_Kyle
  * @version V1.0.0
  * @date    2020
  * @brief   mpu_config source code.
  ******************************************************************************
*/
#include "mpu_config.h"


//mpu region config paramters, max 8 regions
//region can not overlap
const MPU_RegionConfigTypeDef MPU_regionConfigs[]=
{  
   //EFlash lower region, cacheable,write-through;  
   {
       0x00000000,
       0x00400000-1, 
       MPU_ACCESS_ALL_READ_WRITE, 
       MPU_EXECUTE_ENABLE, 
       MPU_ATTR_WRITE_THROUGH
   },
   
   //EFlash upper region, non-cacheable  
   {
       0x00400000,
       0x00800000-1,    
       MPU_ACCESS_ALL_READ_WRITE,
       MPU_EXECUTE_ENABLE,  
       MPU_ATTR_NO_CACHE,
   },
   
   //SRAM lower region, cacheable, write-back   
   {
       0x20000000,
       0x20020000-1, 
       MPU_ACCESS_ALL_READ_WRITE,
       MPU_EXECUTE_ENABLE,  
       MPU_ATTR_WRITE_BACK,
   }, 
   
   //SRAM upper region, non-cacheable  
   {
       0x20020000,
       0x20030000-1,
       MPU_ACCESS_ALL_READ_WRITE,
       MPU_EXECUTE_ENABLE,  
       MPU_ATTR_NO_CACHE,
   },
   
   
   //Device memory type          
   {
       0x40000000,
       0x60000000-1, 
       MPU_ACCESS_ALL_READ_WRITE,
       MPU_EXECUTE_DISABLE,  
       MPU_ATTR_DEVICE,
   },
   
   //Device memory type          
   {
       0xA0000000,
       0xFFFFFFFF, 
       MPU_ACCESS_ALL_READ_WRITE,
       MPU_EXECUTE_DISABLE,  
       MPU_ATTR_DEVICE,
   },

};


void MPU_PrintReg(void)
{
    uint32_t i,index,attr,mair;
    printfS("CTRL:%08x\r\n",MPU->CTRL);
    for(i=0;i<8;i++)
    {
        MPU->RNR = i;
        printfS("%d,RBAR:%08x,RLAR:%08x,",i,MPU->RBAR,MPU->RLAR);
        index = (MPU->RLAR & MPU_RLAR_AttrIndx_Msk)>>MPU_RLAR_AttrIndx_Pos;
        printfS("ATTR%d:",index);
        if(index<4)
            mair = MPU->MAIR0;
        else
        {
            mair = MPU->MAIR1; 
            index -= 4;
        }
        attr = (mair>>(index*8)) & 0xff;
        
        printfS("%02x\r\n",attr);  
    }
    
    printfS("MAIR0:%08x,MAIR1:%08x\r\n",MPU->MAIR0,MPU->MAIR1); 
}

void MPU_Config(void)
{
    MPU_ConfigInitTypeDef mpuConfigInit;
    
    mpuConfigInit.HfNmi = MPU_HFNMI_ENABLE;
    mpuConfigInit.PrivDef = MPU_PRIVDEF_DISABLE; 
    mpuConfigInit.RegionCount = sizeof(MPU_regionConfigs) / sizeof(MPU_regionConfigs[0]);
    mpuConfigInit.RegionConfigs = (MPU_RegionConfigTypeDef *)MPU_regionConfigs;
    
    STD_MPU_Config(&mpuConfigInit); 
}

void System_MspInit(void)
{
//if DCACHE is enabled,suggest to config mpu
//if DCACHE is disabled,suggest to use default config
#if (__ACCELERATE_EH_PRESENT == 1)
    MPU_Config();    
#endif 
}

