1 /**
2   ******************************************************************************
3   * @file    stm32h5xx_hal_cortex.c
4   * @author  MCD Application Team
5   * @brief   CORTEX HAL module driver.
6   *          This file provides firmware functions to manage the following
7   *          functionalities of the CORTEX:
8   *           + Initialization and Configuration functions
9   *           + Peripheral Control functions
10   *
11   ******************************************************************************
12   * @attention
13   *
14   * Copyright (c) 2023 STMicroelectronics.
15   * All rights reserved.
16   *
17   * This software is licensed under terms that can be found in the LICENSE file
18   * in the root directory of this software component.
19   * If no LICENSE file comes with this software, it is provided AS-IS.
20   *
21   ******************************************************************************
22   @verbatim
23   ==============================================================================
24                         ##### How to use this driver #####
25   ==============================================================================
26 
27     [..]
28     *** How to configure Interrupts using CORTEX HAL driver ***
29     ===========================================================
30     [..]
31     This section provides functions allowing to configure the NVIC interrupts (IRQ).
32     The Cortex-M33 exceptions are managed by CMSIS functions.
33 
34     (#) Configure the NVIC Priority Grouping using HAL_NVIC_SetPriorityGrouping() function.
35     (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority().
36     (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ().
37 
38      -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ pre-emption is no more possible.
39          The pending IRQ priority will be managed only by the sub priority.
40 
41      -@- IRQ priority order (sorted by highest to lowest priority):
42         (+@) Lowest pre-emption priority
43         (+@) Lowest sub priority
44         (+@) Lowest hardware priority (IRQ number)
45 
46     [..]
47     *** How to configure SysTick using CORTEX HAL driver ***
48     ========================================================
49     [..]
50     Setup SysTick Timer for time base.
51 
52    (+) The HAL_SYSTICK_Config() function calls the SysTick_Config() function which
53        is a CMSIS function that:
54         (++) Configures the SysTick Reload register with value passed as function parameter.
55         (++) Configures the SysTick IRQ priority to the lowest value (0x0F).
56         (++) Resets the SysTick Counter register.
57         (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK).
58         (++) Enables the SysTick Interrupt.
59         (++) Starts the SysTick Counter.
60 
61    (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro
62        __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the
63        HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined
64        inside the stm32h5xx_hal_cortex.h file.
65 
66    (+) You can change the SysTick IRQ priority by calling the
67        HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function
68        call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function.
69 
70    (+) To adjust the SysTick time base, use the following formula:
71 
72        Reload Value = SysTick Counter Clock (Hz) x  Desired Time base (s)
73        (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function
74        (++) Reload Value should not exceed 0xFFFFFF
75 
76     [..]
77     *** How to configure MPU regions using CORTEX HAL driver ***
78     ============================================================
79     [..]
80     This section provides functions allowing to configure the Memory Protection Unit (MPU).
81 
82     (#) Disable the MPU using HAL_MPU_Disable().
83     (#) Configure the necessary MPU memory attributes using HAL_MPU_ConfigMemoryAttributes().
84     (#) Configure the necessary MPU regions using HAL_MPU_ConfigRegion() ennsuring that the MPU region configuration link to
85         the right MPU attributes number.
86     (#) Enable the MPU using HAL_MPU_Enable() function.
87 
88      -@- The memory management fault exception is enabled in HAL_MPU_Enable() function and the system will enter the memory
89          management fault handler MemManage_Handler() when an illegal memory access is performed.
90      -@- If the MPU has previously been programmed, disable the unused regions to prevent any previous region configuration
91          from affecting the new MPU configuration.
92      -@- MPU APIs ending with '_NS' allow to control the non-secure Memory Protection Unit (MPU_NS) from the secure context
93 
94   @endverbatim
95   ******************************************************************************
96 
97   The table below gives the allowed values of the pre-emption priority and subpriority according
98   to the Priority Grouping configuration performed by HAL_NVIC_SetPriorityGrouping() function.
99 
100 ========================================================================================================================
101   NVIC_PriorityGroup  | NVIC_IRQChannelPreemptionPriority | NVIC_IRQChannelSubPriority |       Description
102 ========================================================================================================================
103  NVIC_PRIORITYGROUP_0 |                0                  |            0-15            | 0 bit for pre-emption priority
104                       |                                   |                            | 4 bits for subpriority
105 ------------------------------------------------------------------------------------------------------------------------
106  NVIC_PRIORITYGROUP_1 |                0-1                |            0-7             | 1 bit for pre-emption priority
107                       |                                   |                            | 3 bits for subpriority
108 ------------------------------------------------------------------------------------------------------------------------
109  NVIC_PRIORITYGROUP_2 |                0-3                |            0-3             | 2 bits for pre-emption priority
110                       |                                   |                            | 2 bits for subpriority
111 ------------------------------------------------------------------------------------------------------------------------
112  NVIC_PRIORITYGROUP_3 |                0-7                |            0-1             | 3 bits for pre-emption priority
113                       |                                   |                            | 1 bit for subpriority
114 ------------------------------------------------------------------------------------------------------------------------
115  NVIC_PRIORITYGROUP_4 |                0-15               |            0               | 4 bits for pre-emption priority
116                       |                                   |                            | 0 bit for subpriority
117 ========================================================================================================================
118   */
119 
120 /* Includes ------------------------------------------------------------------*/
121 #include "stm32h5xx_hal.h"
122 
123 /** @addtogroup STM32H5xx_HAL_Driver
124   * @{
125   */
126 
127 /** @addtogroup CORTEX
128   * @{
129   */
130 
131 #ifdef HAL_CORTEX_MODULE_ENABLED
132 
133 /* Private types -------------------------------------------------------------*/
134 /* Private variables ---------------------------------------------------------*/
135 /* Private constants ---------------------------------------------------------*/
136 /* Private macros ------------------------------------------------------------*/
137 /* Private functions ---------------------------------------------------------*/
138 /** @defgroup CORTEX_Private_Functions CORTEX Private Functions
139   * @{
140   */
141 static void MPU_ConfigRegion(MPU_Type *MPUx, const MPU_Region_InitTypeDef *const pMPU_RegionInit);
142 static void MPU_ConfigMemoryAttributes(MPU_Type *MPUx, const MPU_Attributes_InitTypeDef *const pMPU_AttributesInit);
143 /**
144   * @}
145   */
146 /* Exported functions --------------------------------------------------------*/
147 
148 /** @addtogroup CORTEX_Exported_Functions
149   * @{
150   */
151 
152 
153 /** @addtogroup CORTEX_Exported_Functions_Group1
154   *  @brief    NVIC functions
155   *
156 @verbatim
157   ==============================================================================
158                           ##### NVIC functions #####
159   ==============================================================================
160     [..]
161       This section provides the CORTEX HAL driver functions for NVIC functionalities
162 
163 @endverbatim
164   * @{
165   */
166 
167 
168 /**
169   * @brief  Set the priority grouping field (pre-emption priority and subpriority)
170   *         using the required unlock sequence.
171   * @param  PriorityGroup: The priority grouping bits length.
172   *         This parameter can be one of the following values:
173   *         @arg NVIC_PRIORITYGROUP_0: 0 bit  for pre-emption priority,
174   *                                    4 bits for subpriority
175   *         @arg NVIC_PRIORITYGROUP_1: 1 bit  for pre-emption priority,
176   *                                    3 bits for subpriority
177   *         @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority,
178   *                                    2 bits for subpriority
179   *         @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority,
180   *                                    1 bit  for subpriority
181   *         @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority,
182   *                                    0 bit  for subpriority
183   * @note   When the NVIC_PRIORITYGROUP_0 is selected, IRQ pre-emption is no more possible.
184   *         The pending IRQ priority will be managed only by the subpriority.
185   * @retval None
186   */
HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup)187 void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
188 {
189   /* Check the parameters */
190   assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup));
191 
192   /* Set the PRIGROUP[10:8] bits according to the PriorityGroup parameter value */
193   NVIC_SetPriorityGrouping(PriorityGroup);
194 }
195 
196 /**
197   * @brief  Set the priority of an interrupt.
198   * @param  IRQn: External interrupt number.
199   *         This parameter can be an enumerator of IRQn_Type enumeration
200   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
201   *          CMSIS device file (stm32h5xxxx.h))
202   * @param  PreemptPriority: The pre-emption priority for the IRQn channel.
203   *         This parameter can be a value between 0 and 15
204   *         A lower priority value indicates a higher priority
205   * @param  SubPriority: the subpriority level for the IRQ channel.
206   *         This parameter can be a value between 0 and 15
207   *         A lower priority value indicates a higher priority.
208   * @retval None
209   */
HAL_NVIC_SetPriority(IRQn_Type IRQn,uint32_t PreemptPriority,uint32_t SubPriority)210 void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority)
211 {
212   uint32_t prioritygroup;
213 
214   /* Check the parameters */
215   assert_param(IS_NVIC_SUB_PRIORITY(SubPriority));
216   assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority));
217 
218   prioritygroup = NVIC_GetPriorityGrouping();
219 
220   NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority));
221 }
222 
223 /**
224   * @brief  Enable a device specific interrupt in the NVIC interrupt controller.
225   * @note   To configure interrupts priority correctly, the NVIC_PriorityGroupConfig()
226   *         function should be called before.
227   * @param  IRQn External interrupt number.
228   *         This parameter can be an enumerator of IRQn_Type enumeration
229   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
230   *          CMSIS device file (stm32h5xxxx.h))
231   * @retval None
232   */
HAL_NVIC_EnableIRQ(IRQn_Type IRQn)233 void HAL_NVIC_EnableIRQ(IRQn_Type IRQn)
234 {
235   /* Check the parameters */
236   assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
237 
238   /* Enable interrupt */
239   NVIC_EnableIRQ(IRQn);
240 }
241 
242 /**
243   * @brief  Disable a device specific interrupt in the NVIC interrupt controller.
244   * @param  IRQn External interrupt number.
245   *         This parameter can be an enumerator of IRQn_Type enumeration
246   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
247   *          CMSIS device file (stm32h5xxxx.h))
248   * @retval None
249   */
HAL_NVIC_DisableIRQ(IRQn_Type IRQn)250 void HAL_NVIC_DisableIRQ(IRQn_Type IRQn)
251 {
252   /* Check the parameters */
253   assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
254 
255   /* Disable interrupt */
256   NVIC_DisableIRQ(IRQn);
257 }
258 
259 /**
260   * @brief  Initiate a system reset request to reset the MCU.
261   * @retval None
262   */
HAL_NVIC_SystemReset(void)263 void HAL_NVIC_SystemReset(void)
264 {
265   /* System Reset */
266   NVIC_SystemReset();
267 }
268 
269 /**
270   * @brief  Get the priority grouping field from the NVIC Interrupt Controller.
271   * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field)
272   */
HAL_NVIC_GetPriorityGrouping(void)273 uint32_t HAL_NVIC_GetPriorityGrouping(void)
274 {
275   /* Get the PRIGROUP[10:8] field value */
276   return NVIC_GetPriorityGrouping();
277 }
278 
279 /**
280   * @brief  Get the priority of an interrupt.
281   * @param  IRQn: External interrupt number.
282   *         This parameter can be an enumerator of IRQn_Type enumeration
283   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
284   *          CMSIS device file (stm32h5xxxx.h))
285   * @param   PriorityGroup: the priority grouping bits length.
286   *         This parameter can be one of the following values:
287   *           @arg NVIC_PRIORITYGROUP_0: 0 bit for pre-emption priority,
288   *                                      4 bits for subpriority
289   *           @arg NVIC_PRIORITYGROUP_1: 1 bit for pre-emption priority,
290   *                                      3 bits for subpriority
291   *           @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority,
292   *                                      2 bits for subpriority
293   *           @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority,
294   *                                      1 bit for subpriority
295   *           @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority,
296   *                                      0 bit for subpriority
297   * @param  pPreemptPriority: Pointer on the Preemptive priority value (starting from 0).
298   * @param  pSubPriority: Pointer on the Subpriority value (starting from 0).
299   * @retval None
300   */
HAL_NVIC_GetPriority(IRQn_Type IRQn,uint32_t PriorityGroup,uint32_t * const pPreemptPriority,uint32_t * const pSubPriority)301 void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *const pPreemptPriority,
302                           uint32_t *const pSubPriority)
303 {
304   /* Check the parameters */
305   assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup));
306   /* Get priority for Cortex-M system or device specific interrupts */
307   NVIC_DecodePriority(NVIC_GetPriority(IRQn), PriorityGroup, pPreemptPriority, pSubPriority);
308 }
309 
310 /**
311   * @brief  Set Pending bit of an external interrupt.
312   * @param  IRQn External interrupt number
313   *         This parameter can be an enumerator of IRQn_Type enumeration
314   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
315   *          CMSIS device file (stm32h5xxxx.h))
316   * @retval None
317   */
HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn)318 void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn)
319 {
320   /* Set interrupt pending */
321   NVIC_SetPendingIRQ(IRQn);
322 }
323 
324 /**
325   * @brief  Get Pending Interrupt (read the pending register in the NVIC
326   *         and return the pending bit for the specified interrupt).
327   * @param  IRQn External interrupt number.
328   *         This parameter can be an enumerator of IRQn_Type enumeration
329   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
330   *          CMSIS device file (stm32h5xxxx.h))
331   * @retval status: - 0  Interrupt status is not pending.
332   *                 - 1  Interrupt status is pending.
333   */
HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn)334 uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn)
335 {
336   /* Return 1 if pending else 0 */
337   return NVIC_GetPendingIRQ(IRQn);
338 }
339 
340 /**
341   * @brief  Clear the pending bit of an external interrupt.
342   * @param  IRQn External interrupt number.
343   *         This parameter can be an enumerator of IRQn_Type enumeration
344   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
345   *          CMSIS device file (stm32h5xxxx.h))
346   * @retval None
347   */
HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn)348 void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn)
349 {
350   /* Clear pending interrupt */
351   NVIC_ClearPendingIRQ(IRQn);
352 }
353 
354 /**
355   * @brief Get active interrupt (read the active register in NVIC and return the active bit).
356   * @param IRQn External interrupt number
357   *         This parameter can be an enumerator of IRQn_Type enumeration
358   *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate
359   *          CMSIS device file (stm32h5xxxx.h))
360   * @retval status: - 0  Interrupt status is not pending.
361   *                 - 1  Interrupt status is pending.
362   */
HAL_NVIC_GetActive(IRQn_Type IRQn)363 uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn)
364 {
365   /* Return 1 if active else 0 */
366   return NVIC_GetActive(IRQn);
367 }
368 
369 /**
370   * @}
371   */
372 
373 
374 /** @addtogroup CORTEX_Exported_Functions_Group2
375   *  @brief   SYSTICK functions
376   *
377 @verbatim
378   ==============================================================================
379                           ##### SYSTICK functions #####
380   ==============================================================================
381     [..]
382       This section provides the CORTEX HAL driver functions for SYSTICK functionalities
383 
384 
385 @endverbatim
386   * @{
387   */
388 
389 /**
390   * @brief  Initialize the System Timer with interrupt enabled and start the System Tick Timer (SysTick):
391   *         Counter is in free running mode to generate periodic interrupts.
392   * @param  TicksNumb: Specifies the ticks Number of ticks between two interrupts.
393   * @retval status:  - 0  Function succeeded.
394   *                  - 1  Function failed.
395   */
HAL_SYSTICK_Config(uint32_t TicksNumb)396 uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb)
397 {
398   if ((TicksNumb - 1UL) > SysTick_LOAD_RELOAD_Msk)
399   {
400     /* Reload value impossible */
401     return (1UL);
402   }
403 
404   /* Set reload register */
405   WRITE_REG(SysTick->LOAD, (uint32_t)(TicksNumb - 1UL));
406 
407   /* Load the SysTick Counter Value */
408   WRITE_REG(SysTick->VAL, 0UL);
409 
410   /* Enable SysTick IRQ and SysTick Timer */
411   SET_BIT(SysTick->CTRL, (SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk));
412 
413   /* Function successful */
414   return (0UL);
415 }
416 
417 /**
418   * @brief  Configure the SysTick clock source.
419   * @param  CLKSource: specifies the SysTick clock source.
420   *          This parameter can be one of the following values:
421   *             @arg SYSTICK_CLKSOURCE_LSI: LSI clock selected as SysTick clock source.
422   *             @arg SYSTICK_CLKSOURCE_LSE: LSE clock selected as SysTick clock source.
423   *             @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source.
424   *             @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source.
425   * @retval None
426   */
HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource)427 void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource)
428 {
429   /* Check the parameters */
430   assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource));
431   switch (CLKSource)
432   {
433     /* Select HCLK as Systick clock source */
434     case SYSTICK_CLKSOURCE_HCLK:
435       SET_BIT(SysTick->CTRL, SYSTICK_CLKSOURCE_HCLK);
436       break;
437     /* Select HCLK_DIV8 as Systick clock source */
438     case SYSTICK_CLKSOURCE_HCLK_DIV8:
439       CLEAR_BIT(SysTick->CTRL, SYSTICK_CLKSOURCE_HCLK);
440       MODIFY_REG(RCC->CCIPR4, RCC_CCIPR4_SYSTICKSEL, (0x00000000U));
441       break;
442     /* Select LSI as Systick clock source */
443     case SYSTICK_CLKSOURCE_LSI:
444       CLEAR_BIT(SysTick->CTRL, SYSTICK_CLKSOURCE_HCLK);
445       MODIFY_REG(RCC->CCIPR4, RCC_CCIPR4_SYSTICKSEL, RCC_CCIPR4_SYSTICKSEL_0);
446       break;
447     /* Select LSE as Systick clock source */
448     case SYSTICK_CLKSOURCE_LSE:
449       CLEAR_BIT(SysTick->CTRL, SYSTICK_CLKSOURCE_HCLK);
450       MODIFY_REG(RCC->CCIPR4, RCC_CCIPR4_SYSTICKSEL, RCC_CCIPR4_SYSTICKSEL_1);
451       break;
452     default:
453       /* Nothing to do */
454       break;
455   }
456 }
457 
458 /**
459   * @brief  Get the SysTick clock source configuration.
460   * @retval  SysTick clock source that can be one of the following values:
461   *             @arg SYSTICK_CLKSOURCE_LSI: LSI clock selected as SysTick clock source.
462   *             @arg SYSTICK_CLKSOURCE_LSE: LSE clock selected as SysTick clock source.
463   *             @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source.
464   *             @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source.
465   */
HAL_SYSTICK_GetCLKSourceConfig(void)466 uint32_t HAL_SYSTICK_GetCLKSourceConfig(void)
467 {
468   uint32_t systick_source;
469   uint32_t systick_rcc_source;
470 
471   /* Read SysTick->CTRL register for internal or external clock source */
472   if (READ_BIT(SysTick->CTRL, SysTick_CTRL_CLKSOURCE_Msk) != 0U)
473   {
474     /* Internal clock source */
475     systick_source = SYSTICK_CLKSOURCE_HCLK;
476   }
477   else
478   {
479     /* External clock source, check the selected one in RCC */
480     systick_rcc_source = READ_BIT(RCC->CCIPR4, RCC_CCIPR4_SYSTICKSEL);
481 
482     switch (systick_rcc_source)
483     {
484       case (0x00000000U):
485         systick_source = SYSTICK_CLKSOURCE_HCLK_DIV8;
486         break;
487 
488       case (RCC_CCIPR4_SYSTICKSEL_0):
489         systick_source = SYSTICK_CLKSOURCE_LSI;
490         break;
491 
492       case (RCC_CCIPR4_SYSTICKSEL_1):
493         systick_source = SYSTICK_CLKSOURCE_LSE;
494         break;
495 
496       default:
497         systick_source = SYSTICK_CLKSOURCE_HCLK_DIV8;
498         break;
499     }
500   }
501   return systick_source;
502 }
503 
504 /**
505   * @brief  Handle SYSTICK interrupt request.
506   * @retval None
507   */
HAL_SYSTICK_IRQHandler(void)508 void HAL_SYSTICK_IRQHandler(void)
509 {
510   HAL_SYSTICK_Callback();
511 }
512 
513 /**
514   * @brief  SYSTICK callback.
515   * @retval None
516   */
HAL_SYSTICK_Callback(void)517 __weak void HAL_SYSTICK_Callback(void)
518 {
519   /* NOTE : This function should not be modified, when the callback is needed,
520             the HAL_SYSTICK_Callback could be implemented in the user file
521    */
522 }
523 
524 /**
525   * @}
526   */
527 
528 /** @addtogroup CORTEX_Exported_Functions_Group3
529   *  @brief   MPU functions
530   *
531 @verbatim
532   ==============================================================================
533                          ##### MPU functions #####
534   ==============================================================================
535     [..]
536       This section provides the CORTEX HAL driver functions for MPU functionalities
537 
538 
539 @endverbatim
540   * @{
541   */
542 
543 /**
544   * @brief  Enable the MPU.
545   * @param  MPU_Control: Specifies the control mode of the MPU during hard fault,
546   *          NMI, FAULTMASK and privileged access to the default memory
547   *          This parameter can be one of the following values:
548   *            @arg MPU_HFNMI_PRIVDEF_NONE
549   *            @arg MPU_HARDFAULT_NMI
550   *            @arg MPU_PRIVILEGED_DEFAULT
551   *            @arg MPU_HFNMI_PRIVDEF
552   * @retval None
553   */
HAL_MPU_Enable(uint32_t MPU_Control)554 void HAL_MPU_Enable(uint32_t MPU_Control)
555 {
556   __DMB(); /* Data Memory Barrier operation to force any outstanding writes to memory before enabling the MPU */
557 
558   /* Enable the MPU */
559   MPU->CTRL   = MPU_Control | MPU_CTRL_ENABLE_Msk;
560 
561   /* Enable fault exceptions */
562   SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
563 
564   /* Follow ARM recommendation with */
565   /* Data Synchronization and Instruction Synchronization Barriers to ensure MPU configuration */
566   __DSB(); /* Ensure that the subsequent instruction is executed only after the write to memory */
567   __ISB(); /* Flush and refill pipeline with updated MPU configuration settings */
568 }
569 
570 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
571 /**
572   * @brief  Enable the non-secure MPU.
573   * @param  MPU_Control: Specifies the control mode of the MPU during hard fault,
574   *          NMI, FAULTMASK and privileged access to the default memory
575   *          This parameter can be one of the following values:
576   *            @arg MPU_HFNMI_PRIVDEF_NONE
577   *            @arg MPU_HARDFAULT_NMI
578   *            @arg MPU_PRIVILEGED_DEFAULT
579   *            @arg MPU_HFNMI_PRIVDEF
580   * @retval None
581   */
HAL_MPU_Enable_NS(uint32_t MPU_Control)582 void HAL_MPU_Enable_NS(uint32_t MPU_Control)
583 {
584   __DMB(); /* Data Memory Barrier operation to force any outstanding writes to memory before enabling the MPU */
585 
586   /* Enable the MPU */
587   MPU_NS->CTRL   = MPU_Control | MPU_CTRL_ENABLE_Msk;
588 
589   /* Enable fault exceptions */
590   SCB_NS->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
591 
592   /* Follow ARM recommendation with */
593   /* Data Synchronization and Instruction Synchronization Barriers to ensure MPU configuration */
594   __DSB(); /* Ensure that the subsequent instruction is executed only after the write to memory */
595   __ISB(); /* Flush and refill pipeline with updated MPU configuration settings */
596 }
597 #endif /* __ARM_FEATURE_CMSE */
598 
599 /**
600   * @brief  Disable the MPU.
601   * @retval None
602   */
HAL_MPU_Disable(void)603 void HAL_MPU_Disable(void)
604 {
605   __DMB(); /* Force any outstanding transfers to complete before disabling MPU */
606 
607   /* Disable fault exceptions */
608   SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
609 
610   /* Disable the MPU */
611   MPU->CTRL  &= ~MPU_CTRL_ENABLE_Msk;
612 
613   /* Follow ARM recommendation with */
614   /* Data Synchronization and Instruction Synchronization Barriers to ensure MPU configuration */
615   __DSB(); /* Ensure that the subsequent instruction is executed only after the write to memory */
616   __ISB(); /* Flush and refill pipeline with updated MPU configuration settings */
617 }
618 
619 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
620 /**
621   * @brief  Disable the non-secure MPU.
622   * @retval None
623   */
HAL_MPU_Disable_NS(void)624 void HAL_MPU_Disable_NS(void)
625 {
626   __DMB(); /* Force any outstanding transfers to complete before disabling MPU */
627 
628   /* Disable fault exceptions */
629   SCB_NS->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
630 
631   /* Disable the MPU */
632   MPU_NS->CTRL  &= ~MPU_CTRL_ENABLE_Msk;
633 
634   /* Follow ARM recommendation with */
635   /* Data Synchronization and Instruction Synchronization Barriers to ensure MPU configuration */
636   __DSB(); /* Ensure that the subsequent instruction is executed only after the write to memory */
637   __ISB(); /* Flush and refill pipeline with updated MPU configuration settings */
638 }
639 #endif /* __ARM_FEATURE_CMSE */
640 
641 /**
642   * @brief  Enable the MPU Region.
643   * @param  RegionNumber Specifies the index of the region to enable.
644   *         this parameter can be a value of @ref CORTEX_MPU_Region_Number
645   * @retval None
646   */
HAL_MPU_EnableRegion(uint32_t RegionNumber)647 void HAL_MPU_EnableRegion(uint32_t RegionNumber)
648 {
649   /* Check the parameters */
650   assert_param(IS_MPU_REGION_NUMBER(RegionNumber));
651 
652   /* Set the Region number */
653   MPU->RNR = RegionNumber;
654 
655   /* Enable the Region */
656   SET_BIT(MPU->RLAR, MPU_RLAR_EN_Msk);
657 }
658 
659 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
660 /**
661   * @brief  Enable the MPU_NS Region.
662   * @param  RegionNumber Specifies the index of the region to enable.
663   *         this parameter can be a value of @ref CORTEX_MPU_Region_Number
664   * @retval None
665   */
HAL_MPU_EnableRegion_NS(uint32_t RegionNumber)666 void HAL_MPU_EnableRegion_NS(uint32_t RegionNumber)
667 {
668   /* Check the parameters */
669   assert_param(IS_MPU_REGION_NUMBER_NS(RegionNumber));
670 
671   /* Set the Region number */
672   MPU_NS->RNR = RegionNumber;
673 
674   /* Enable the Region */
675   SET_BIT(MPU_NS->RLAR, MPU_RLAR_EN_Msk);
676 }
677 #endif /* __ARM_FEATURE_CMSE */
678 
679 /**
680   * @brief  Disable the MPU Region.
681   * @param  RegionNumber Specifies the index of the region to disable.
682   *         this parameter can be a value of @ref CORTEX_MPU_Region_Number
683   * @retval None
684   */
HAL_MPU_DisableRegion(uint32_t RegionNumber)685 void HAL_MPU_DisableRegion(uint32_t RegionNumber)
686 {
687   /* Check the parameters */
688   assert_param(IS_MPU_REGION_NUMBER(RegionNumber));
689 
690   /* Set the Region number */
691   MPU->RNR = RegionNumber;
692 
693   /* Disable the Region */
694   CLEAR_BIT(MPU->RLAR, MPU_RLAR_EN_Msk);
695 }
696 
697 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
698 /**
699   * @brief  Disable the MPU_NS Region.
700   * @param  RegionNumber Specifies the index of the region to disable.
701   *         this parameter can be a value of @ref CORTEX_MPU_Region_Number
702   * @retval None
703   */
HAL_MPU_DisableRegion_NS(uint32_t RegionNumber)704 void HAL_MPU_DisableRegion_NS(uint32_t RegionNumber)
705 {
706   /* Check the parameters */
707   assert_param(IS_MPU_REGION_NUMBER_NS(RegionNumber));
708 
709   /* Set the Region number */
710   MPU_NS->RNR = RegionNumber;
711 
712   /* Disable the Region */
713   CLEAR_BIT(MPU_NS->RLAR, MPU_RLAR_EN_Msk);
714 }
715 #endif /* __ARM_FEATURE_CMSE */
716 
717 /**
718   * @brief  Initialize and configure the Region and the memory to be protected.
719   * @param  pMPU_RegionInit: Pointer to a MPU_Region_InitTypeDef structure that contains
720   *                the initialization and configuration information.
721   * @retval None
722   */
HAL_MPU_ConfigRegion(const MPU_Region_InitTypeDef * const pMPU_RegionInit)723 void HAL_MPU_ConfigRegion(const MPU_Region_InitTypeDef *const pMPU_RegionInit)
724 {
725   MPU_ConfigRegion(MPU, pMPU_RegionInit);
726 }
727 
728 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
729 /**
730   * @brief  Initialize and configure the Region and the memory to be protected for non-secure MPU.
731   * @param  pMPU_RegionInit: Pointer to a MPU_Region_InitTypeDef structure that contains
732   *                the initialization and configuration information.
733   * @retval None
734   */
HAL_MPU_ConfigRegion_NS(const MPU_Region_InitTypeDef * const pMPU_RegionInit)735 void HAL_MPU_ConfigRegion_NS(const MPU_Region_InitTypeDef *const pMPU_RegionInit)
736 {
737   MPU_ConfigRegion(MPU_NS, pMPU_RegionInit);
738 }
739 #endif /* __ARM_FEATURE_CMSE */
740 
741 /**
742   * @brief  Initialize and configure the memory attributes.
743   * @param  pMPU_AttributesInit: Pointer to a MPU_Attributes_InitTypeDef structure that contains
744   *                the initialization and configuration information.
745   * @retval None
746   */
HAL_MPU_ConfigMemoryAttributes(const MPU_Attributes_InitTypeDef * const pMPU_AttributesInit)747 void HAL_MPU_ConfigMemoryAttributes(const MPU_Attributes_InitTypeDef *const pMPU_AttributesInit)
748 {
749   MPU_ConfigMemoryAttributes(MPU, pMPU_AttributesInit);
750 }
751 
752 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
753 /**
754   * @brief  Initialize and configure the memory attributes for non-secure MPU.
755   * @param  pMPU_AttributesInit: Pointer to a MPU_Attributes_InitTypeDef structure that contains
756   *                the initialization and configuration information.
757   * @retval None
758   */
HAL_MPU_ConfigMemoryAttributes_NS(const MPU_Attributes_InitTypeDef * const pMPU_AttributesInit)759 void HAL_MPU_ConfigMemoryAttributes_NS(const MPU_Attributes_InitTypeDef *const pMPU_AttributesInit)
760 {
761   MPU_ConfigMemoryAttributes(MPU_NS, pMPU_AttributesInit);
762 }
763 #endif /* __ARM_FEATURE_CMSE */
764 
765 /**
766   * @}
767   */
768 
769 /**
770   * @}
771   */
772 
773 /** @addtogroup CORTEX_Private_Functions
774   * @{
775   */
776 /**
777   * @brief  Initialize and configure the Region and the memory to be protected for MPU.
778   * @param  MPUx: Pointer to MPU_Type structure
779   *          This parameter can be one of the following values:
780   *            @arg MPU
781   *            @arg MPU_NS
782   * @param  pMPU_RegionInit: Pointer to a MPU_Region_InitTypeDef structure that contains
783   *                the initialization and configuration information.
784   * @retval None
785   */
MPU_ConfigRegion(MPU_Type * MPUx,const MPU_Region_InitTypeDef * const pMPU_RegionInit)786 static void MPU_ConfigRegion(MPU_Type *MPUx, const MPU_Region_InitTypeDef *const pMPU_RegionInit)
787 {
788   /* Check the parameters */
789 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
790   assert_param(IS_MPU_INSTANCE(MPUx));
791 #endif /* __ARM_FEATURE_CMSE */
792   assert_param(IS_MPU_REGION_NUMBER(pMPU_RegionInit->Number));
793   assert_param(IS_MPU_REGION_ENABLE(pMPU_RegionInit->Enable));
794   assert_param(IS_MPU_INSTRUCTION_ACCESS(pMPU_RegionInit->DisableExec));
795   assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(pMPU_RegionInit->AccessPermission));
796   assert_param(IS_MPU_ACCESS_SHAREABLE(pMPU_RegionInit->IsShareable));
797 
798   /* Follow ARM recommendation with Data Memory Barrier prior to MPU configuration */
799   __DMB();
800 
801   /* Set the Region number */
802   MPUx->RNR = pMPU_RegionInit->Number;
803 
804   /* Disable the Region */
805   CLEAR_BIT(MPUx->RLAR, MPU_RLAR_EN_Msk);
806 
807   MPUx->RBAR = (((uint32_t)pMPU_RegionInit->BaseAddress               & 0xFFFFFFE0UL)  |
808                 ((uint32_t)pMPU_RegionInit->IsShareable           << MPU_RBAR_SH_Pos)  |
809                 ((uint32_t)pMPU_RegionInit->AccessPermission      << MPU_RBAR_AP_Pos)  |
810                 ((uint32_t)pMPU_RegionInit->DisableExec           << MPU_RBAR_XN_Pos));
811 
812   MPUx->RLAR = (((uint32_t)pMPU_RegionInit->LimitAddress                    & 0xFFFFFFE0UL) |
813                 ((uint32_t)pMPU_RegionInit->AttributesIndex       << MPU_RLAR_AttrIndx_Pos) |
814                 ((uint32_t)pMPU_RegionInit->Enable                << MPU_RLAR_EN_Pos));
815 }
816 
817 /**
818   * @brief  Initialize and configure the memory attributes for MPU.
819   * @param  MPUx: Pointer to MPU_Type structure
820   *          This parameter can be one of the following values:
821   *            @arg MPU
822   *            @arg MPU_NS
823   * @param  pMPU_AttributesInit: Pointer to a MPU_Attributes_InitTypeDef structure that contains
824   *                the initialization and configuration information.
825   * @retval None
826   */
MPU_ConfigMemoryAttributes(MPU_Type * MPUx,const MPU_Attributes_InitTypeDef * const pMPU_AttributesInit)827 static void MPU_ConfigMemoryAttributes(MPU_Type *MPUx, const MPU_Attributes_InitTypeDef *const pMPU_AttributesInit)
828 {
829   __IO uint32_t *p_mair;
830   uint32_t      attr_values;
831   uint32_t      attr_number;
832 
833   /* Check the parameters */
834 #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
835   assert_param(IS_MPU_INSTANCE(MPUx));
836 #endif /* __ARM_FEATURE_CMSE */
837   assert_param(IS_MPU_ATTRIBUTES_NUMBER(pMPU_AttributesInit->Number));
838   /* No need to check Attributes value as all 0x0..0xFF possible */
839 
840   /* Follow ARM recommendation with Data Memory Barrier prior to MPUx configuration */
841   __DMB();
842 
843   if (pMPU_AttributesInit->Number < MPU_ATTRIBUTES_NUMBER4)
844   {
845     /* Program MPU_MAIR0 */
846     p_mair = &(MPUx->MAIR0);
847     attr_number = pMPU_AttributesInit->Number;
848   }
849   else
850   {
851     /* Program MPU_MAIR1 */
852     p_mair = &(MPUx->MAIR1);
853     attr_number = (uint32_t)pMPU_AttributesInit->Number - 4U;
854   }
855 
856   attr_values = *(p_mair);
857   attr_values &=  ~(0xFFUL << (attr_number * 8U));
858   *(p_mair) = attr_values | ((uint32_t)pMPU_AttributesInit->Attributes << (attr_number * 8U));
859 }
860 /**
861   * @}
862   */
863 
864 #endif /* HAL_CORTEX_MODULE_ENABLED */
865 /**
866   * @}
867   */
868 
869 /**
870   * @}
871   */
872