port.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /*
  2. * FreeRTOS Kernel V10.4.6
  3. * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * SPDX-License-Identifier: MIT
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. * this software and associated documentation files (the "Software"), to deal in
  9. * the Software without restriction, including without limitation the rights to
  10. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. * the Software, and to permit persons to whom the Software is furnished to do so,
  12. * subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. *
  24. * https://www.FreeRTOS.org
  25. * https://github.com/FreeRTOS
  26. *
  27. */
  28. /*-----------------------------------------------------------
  29. * Implementation of functions defined in portable.h for the ARM CM3 port.
  30. *----------------------------------------------------------*/
  31. /* Scheduler includes. */
  32. #include "FreeRTOS.h"
  33. #include "task.h"
  34. #ifndef configKERNEL_INTERRUPT_PRIORITY
  35. #define configKERNEL_INTERRUPT_PRIORITY 255
  36. #endif
  37. #if configMAX_SYSCALL_INTERRUPT_PRIORITY == 0
  38. #error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. See http: /*www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  39. #endif
  40. #ifndef configSYSTICK_CLOCK_HZ
  41. #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
  42. /* Ensure the SysTick is clocked at the same frequency as the core. */
  43. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  44. #else
  45. /* The way the SysTick is clocked is not modified in case it is not the same
  46. * as the core. */
  47. #define portNVIC_SYSTICK_CLK_BIT ( 0 )
  48. #endif
  49. /* Legacy macro for backward compatibility only. This macro used to be used to
  50. * replace the function that configures the clock used to generate the tick
  51. * interrupt (prvSetupTimerInterrupt()), but now the function is declared weak so
  52. * the application writer can override it by simply defining a function of the
  53. * same name (vApplicationSetupTickInterrupt()). */
  54. #ifndef configOVERRIDE_DEFAULT_TICK_CONFIGURATION
  55. #define configOVERRIDE_DEFAULT_TICK_CONFIGURATION 0
  56. #endif
  57. /* Constants required to manipulate the core. Registers first... */
  58. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  59. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  60. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  61. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  62. /* ...then bits in the registers. */
  63. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  64. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  65. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  66. #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
  67. #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
  68. #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
  69. #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
  70. /* Constants required to check the validity of an interrupt priority. */
  71. #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
  72. #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
  73. #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
  74. #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
  75. #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
  76. #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
  77. #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
  78. #define portPRIGROUP_SHIFT ( 8UL )
  79. /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
  80. #define portVECTACTIVE_MASK ( 0xFFUL )
  81. /* Constants required to set up the initial stack. */
  82. #define portINITIAL_XPSR ( 0x01000000 )
  83. /* The systick is a 24-bit counter. */
  84. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  85. /* A fiddle factor to estimate the number of SysTick counts that would have
  86. * occurred while the SysTick counter is stopped during tickless idle
  87. * calculations. */
  88. #define portMISSED_COUNTS_FACTOR ( 45UL )
  89. /* For strict compliance with the Cortex-M spec the task start address should
  90. * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
  91. #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
  92. /*
  93. * Setup the timer to generate the tick interrupts. The implementation in this
  94. * file is weak to allow application writers to change the timer used to
  95. * generate the tick interrupt.
  96. */
  97. void vPortSetupTimerInterrupt( void );
  98. /*
  99. * Exception handlers.
  100. */
  101. void xPortPendSVHandler( void );
  102. void xPortSysTickHandler( void );
  103. void vPortSVCHandler( void );
  104. /*
  105. * Start first task is a separate function so it can be tested in isolation.
  106. */
  107. static void prvStartFirstTask( void );
  108. /*
  109. * Used to catch tasks that attempt to return from their implementing function.
  110. */
  111. static void prvTaskExitError( void );
  112. /*-----------------------------------------------------------*/
  113. /* Each task maintains its own interrupt status in the critical nesting
  114. * variable. */
  115. static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
  116. /*
  117. * The number of SysTick increments that make up one tick period.
  118. */
  119. #if ( configUSE_TICKLESS_IDLE == 1 )
  120. static uint32_t ulTimerCountsForOneTick = 0;
  121. #endif /* configUSE_TICKLESS_IDLE */
  122. /*
  123. * The maximum number of tick periods that can be suppressed is limited by the
  124. * 24 bit resolution of the SysTick timer.
  125. */
  126. #if ( configUSE_TICKLESS_IDLE == 1 )
  127. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  128. #endif /* configUSE_TICKLESS_IDLE */
  129. /*
  130. * Compensate for the CPU cycles that pass while the SysTick is stopped (low
  131. * power functionality only.
  132. */
  133. #if ( configUSE_TICKLESS_IDLE == 1 )
  134. static uint32_t ulStoppedTimerCompensation = 0;
  135. #endif /* configUSE_TICKLESS_IDLE */
  136. /*
  137. * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
  138. * FreeRTOS API functions are not called from interrupts that have been assigned
  139. * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
  140. */
  141. #if ( configASSERT_DEFINED == 1 )
  142. static uint8_t ucMaxSysCallPriority = 0;
  143. static uint32_t ulMaxPRIGROUPValue = 0;
  144. static const volatile uint8_t * const pcInterruptPriorityRegisters = ( uint8_t * ) portNVIC_IP_REGISTERS_OFFSET_16;
  145. #endif /* configASSERT_DEFINED */
  146. /*-----------------------------------------------------------*/
  147. /*
  148. * See header file for description.
  149. */
  150. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  151. TaskFunction_t pxCode,
  152. void * pvParameters )
  153. {
  154. /* Simulate the stack frame as it would be created by a context switch
  155. * interrupt. */
  156. pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
  157. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  158. pxTopOfStack--;
  159. *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
  160. pxTopOfStack--;
  161. *pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
  162. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  163. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  164. pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
  165. return pxTopOfStack;
  166. }
  167. /*-----------------------------------------------------------*/
  168. static void prvTaskExitError( void )
  169. {
  170. /* A function that implements a task must not exit or attempt to return to
  171. * its caller as there is nothing to return to. If a task wants to exit it
  172. * should instead call vTaskDelete( NULL ).
  173. *
  174. * Artificially force an assert() to be triggered if configASSERT() is
  175. * defined, then stop here so application writers can catch the error. */
  176. configASSERT( uxCriticalNesting == ~0UL );
  177. portDISABLE_INTERRUPTS();
  178. for( ; ; )
  179. {
  180. }
  181. }
  182. /*-----------------------------------------------------------*/
  183. __asm void vPortSVCHandler( void )
  184. {
  185. /* *INDENT-OFF* */
  186. PRESERVE8
  187. ldr r3, = pxCurrentTCB /* Restore the context. */
  188. ldr r1, [ r3 ] /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
  189. ldr r0, [ r1 ] /* The first item in pxCurrentTCB is the task top of stack. */
  190. ldmia r0 !, { r4 - r11 } /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
  191. msr psp, r0 /* Restore the task stack pointer. */
  192. isb
  193. mov r0, # 0
  194. msr basepri, r0
  195. orr r14, # 0xd
  196. bx r14
  197. /* *INDENT-ON* */
  198. }
  199. /*-----------------------------------------------------------*/
  200. __asm void prvStartFirstTask( void )
  201. {
  202. /* *INDENT-OFF* */
  203. PRESERVE8
  204. /* Use the NVIC offset register to locate the stack. */
  205. ldr r0, =0xE000ED08
  206. ldr r0, [ r0 ]
  207. ldr r0, [ r0 ]
  208. /* Set the msp back to the start of the stack. */
  209. msr msp, r0
  210. /* Globally enable interrupts. */
  211. cpsie i
  212. cpsie f
  213. dsb
  214. isb
  215. /* Call SVC to start the first task. */
  216. svc 0
  217. nop
  218. nop
  219. /* *INDENT-ON* */
  220. }
  221. /*-----------------------------------------------------------*/
  222. /*
  223. * See header file for description.
  224. */
  225. BaseType_t xPortStartScheduler( void )
  226. {
  227. #if ( configASSERT_DEFINED == 1 )
  228. {
  229. volatile uint32_t ulOriginalPriority;
  230. volatile uint8_t * const pucFirstUserPriorityRegister = ( uint8_t * ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
  231. volatile uint8_t ucMaxPriorityValue;
  232. /* Determine the maximum priority from which ISR safe FreeRTOS API
  233. * functions can be called. ISR safe functions are those that end in
  234. * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
  235. * ensure interrupt entry is as fast and simple as possible.
  236. *
  237. * Save the interrupt priority value that is about to be clobbered. */
  238. ulOriginalPriority = *pucFirstUserPriorityRegister;
  239. /* Determine the number of priority bits available. First write to all
  240. * possible bits. */
  241. *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
  242. /* Read the value back to see how many bits stuck. */
  243. ucMaxPriorityValue = *pucFirstUserPriorityRegister;
  244. /* The kernel interrupt priority should be set to the lowest
  245. * priority. */
  246. configASSERT( ucMaxPriorityValue == ( configKERNEL_INTERRUPT_PRIORITY & ucMaxPriorityValue ) );
  247. /* Use the same mask on the maximum system call priority. */
  248. ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
  249. /* Calculate the maximum acceptable priority group value for the number
  250. * of bits read back. */
  251. ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
  252. while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
  253. {
  254. ulMaxPRIGROUPValue--;
  255. ucMaxPriorityValue <<= ( uint8_t ) 0x01;
  256. }
  257. #ifdef __NVIC_PRIO_BITS
  258. {
  259. /* Check the CMSIS configuration that defines the number of
  260. * priority bits matches the number of priority bits actually queried
  261. * from the hardware. */
  262. configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );
  263. }
  264. #endif
  265. #ifdef configPRIO_BITS
  266. {
  267. /* Check the FreeRTOS configuration that defines the number of
  268. * priority bits matches the number of priority bits actually queried
  269. * from the hardware. */
  270. configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );
  271. }
  272. #endif
  273. /* Shift the priority group value back to its position within the AIRCR
  274. * register. */
  275. ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
  276. ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
  277. /* Restore the clobbered interrupt priority register to its original
  278. * value. */
  279. *pucFirstUserPriorityRegister = ulOriginalPriority;
  280. }
  281. #endif /* configASSERT_DEFINED */
  282. /* Make PendSV and SysTick the lowest priority interrupts. */
  283. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  284. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  285. /* Start the timer that generates the tick ISR. Interrupts are disabled
  286. * here already. */
  287. vPortSetupTimerInterrupt();
  288. /* Initialise the critical nesting count ready for the first task. */
  289. uxCriticalNesting = 0;
  290. /* Start the first task. */
  291. prvStartFirstTask();
  292. /* Should not get here! */
  293. return 0;
  294. }
  295. /*-----------------------------------------------------------*/
  296. void vPortEndScheduler( void )
  297. {
  298. /* Not implemented in ports where there is nothing to return to.
  299. * Artificially force an assert. */
  300. configASSERT( uxCriticalNesting == 1000UL );
  301. }
  302. /*-----------------------------------------------------------*/
  303. void vPortEnterCritical( void )
  304. {
  305. portDISABLE_INTERRUPTS();
  306. uxCriticalNesting++;
  307. /* This is not the interrupt safe version of the enter critical function so
  308. * assert() if it is being called from an interrupt context. Only API
  309. * functions that end in "FromISR" can be used in an interrupt. Only assert if
  310. * the critical nesting count is 1 to protect against recursive calls if the
  311. * assert function also uses a critical section. */
  312. if( uxCriticalNesting == 1 )
  313. {
  314. configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
  315. }
  316. }
  317. /*-----------------------------------------------------------*/
  318. void vPortExitCritical( void )
  319. {
  320. configASSERT( uxCriticalNesting );
  321. uxCriticalNesting--;
  322. if( uxCriticalNesting == 0 )
  323. {
  324. portENABLE_INTERRUPTS();
  325. }
  326. }
  327. /*-----------------------------------------------------------*/
  328. __asm void xPortPendSVHandler( void )
  329. {
  330. extern uxCriticalNesting;
  331. extern pxCurrentTCB;
  332. extern vTaskSwitchContext;
  333. /* *INDENT-OFF* */
  334. PRESERVE8
  335. mrs r0, psp
  336. isb
  337. ldr r3, =pxCurrentTCB /* Get the location of the current TCB. */
  338. ldr r2, [ r3 ]
  339. stmdb r0 !, { r4 - r11 } /* Save the remaining registers. */
  340. str r0, [ r2 ] /* Save the new top of stack into the first member of the TCB. */
  341. stmdb sp !, { r3, r14 }
  342. mov r0, #configMAX_SYSCALL_INTERRUPT_PRIORITY
  343. msr basepri, r0
  344. dsb
  345. isb
  346. bl vTaskSwitchContext
  347. mov r0, #0
  348. msr basepri, r0
  349. ldmia sp !, { r3, r14 }
  350. ldr r1, [ r3 ]
  351. ldr r0, [ r1 ] /* The first item in pxCurrentTCB is the task top of stack. */
  352. ldmia r0 !, { r4 - r11 } /* Pop the registers and the critical nesting count. */
  353. msr psp, r0
  354. isb
  355. bx r14
  356. nop
  357. /* *INDENT-ON* */
  358. }
  359. /*-----------------------------------------------------------*/
  360. void xPortSysTickHandler( void )
  361. {
  362. /* The SysTick runs at the lowest interrupt priority, so when this interrupt
  363. * executes all interrupts must be unmasked. There is therefore no need to
  364. * save and then restore the interrupt mask value as its value is already
  365. * known - therefore the slightly faster vPortRaiseBASEPRI() function is used
  366. * in place of portSET_INTERRUPT_MASK_FROM_ISR(). */
  367. vPortRaiseBASEPRI();
  368. {
  369. /* Increment the RTOS tick. */
  370. if( xTaskIncrementTick() != pdFALSE )
  371. {
  372. /* A context switch is required. Context switching is performed in
  373. * the PendSV interrupt. Pend the PendSV interrupt. */
  374. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  375. }
  376. }
  377. vPortClearBASEPRIFromISR();
  378. }
  379. /*-----------------------------------------------------------*/
  380. #if ( configUSE_TICKLESS_IDLE == 1 )
  381. __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  382. {
  383. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
  384. TickType_t xModifiableIdleTime;
  385. /* Make sure the SysTick reload value does not overflow the counter. */
  386. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  387. {
  388. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  389. }
  390. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  391. * is accounted for as best it can be, but using the tickless mode will
  392. * inevitably result in some tiny drift of the time maintained by the
  393. * kernel with respect to calendar time. */
  394. portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
  395. /* Calculate the reload value required to wait xExpectedIdleTime
  396. * tick periods. -1 is used because this code will execute part way
  397. * through one of the tick periods. */
  398. ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  399. if( ulReloadValue > ulStoppedTimerCompensation )
  400. {
  401. ulReloadValue -= ulStoppedTimerCompensation;
  402. }
  403. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  404. * method as that will mask interrupts that should exit sleep mode. */
  405. __disable_irq();
  406. __dsb( portSY_FULL_READ_WRITE );
  407. __isb( portSY_FULL_READ_WRITE );
  408. /* If a context switch is pending or a task is waiting for the scheduler
  409. * to be unsuspended then abandon the low power entry. */
  410. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  411. {
  412. /* Restart from whatever is left in the count register to complete
  413. * this tick period. */
  414. portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  415. /* Restart SysTick. */
  416. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  417. /* Reset the reload register to the value required for normal tick
  418. * periods. */
  419. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  420. /* Re-enable interrupts - see comments above __disable_irq() call
  421. * above. */
  422. __enable_irq();
  423. }
  424. else
  425. {
  426. /* Set the new reload value. */
  427. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  428. /* Clear the SysTick count flag and set the count value back to
  429. * zero. */
  430. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  431. /* Restart SysTick. */
  432. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  433. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  434. * set its parameter to 0 to indicate that its implementation contains
  435. * its own wait for interrupt or wait for event instruction, and so wfi
  436. * should not be executed again. However, the original expected idle
  437. * time variable must remain unmodified, so a copy is taken. */
  438. xModifiableIdleTime = xExpectedIdleTime;
  439. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  440. if( xModifiableIdleTime > 0 )
  441. {
  442. __dsb( portSY_FULL_READ_WRITE );
  443. __wfi();
  444. __isb( portSY_FULL_READ_WRITE );
  445. }
  446. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  447. /* Re-enable interrupts to allow the interrupt that brought the MCU
  448. * out of sleep mode to execute immediately. see comments above
  449. * __disable_interrupt() call above. */
  450. __enable_irq();
  451. __dsb( portSY_FULL_READ_WRITE );
  452. __isb( portSY_FULL_READ_WRITE );
  453. /* Disable interrupts again because the clock is about to be stopped
  454. * and interrupts that execute while the clock is stopped will increase
  455. * any slippage between the time maintained by the RTOS and calendar
  456. * time. */
  457. __disable_irq();
  458. __dsb( portSY_FULL_READ_WRITE );
  459. __isb( portSY_FULL_READ_WRITE );
  460. /* Disable the SysTick clock without reading the
  461. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  462. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  463. * the time the SysTick is stopped for is accounted for as best it can
  464. * be, but using the tickless mode will inevitably result in some tiny
  465. * drift of the time maintained by the kernel with respect to calendar
  466. * time*/
  467. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
  468. /* Determine if the SysTick clock has already counted to zero and
  469. * been set back to the current reload value (the reload back being
  470. * correct for the entire expected idle time) or if the SysTick is yet
  471. * to count to zero (in which case an interrupt other than the SysTick
  472. * must have brought the system out of sleep mode). */
  473. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  474. {
  475. uint32_t ulCalculatedLoadValue;
  476. /* The tick interrupt is already pending, and the SysTick count
  477. * reloaded with ulReloadValue. Reset the
  478. * portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
  479. * period. */
  480. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  481. /* Don't allow a tiny value, or values that have somehow
  482. * underflowed because the post sleep hook did something
  483. * that took too long. */
  484. if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  485. {
  486. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  487. }
  488. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  489. /* As the pending tick will be processed as soon as this
  490. * function exits, the tick value maintained by the tick is stepped
  491. * forward by one less than the time spent waiting. */
  492. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  493. }
  494. else
  495. {
  496. /* Something other than the tick interrupt ended the sleep.
  497. * Work out how long the sleep lasted rounded to complete tick
  498. * periods (not the ulReload value which accounted for part
  499. * ticks). */
  500. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
  501. /* How many complete tick periods passed while the processor
  502. * was waiting? */
  503. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  504. /* The reload value is set to whatever fraction of a single tick
  505. * period remains. */
  506. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  507. }
  508. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
  509. * again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
  510. * value. */
  511. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  512. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  513. vTaskStepTick( ulCompleteTickPeriods );
  514. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  515. /* Exit with interrupts enabled. */
  516. __enable_irq();
  517. }
  518. }
  519. #endif /* #if configUSE_TICKLESS_IDLE */
  520. /*-----------------------------------------------------------*/
  521. /*
  522. * Setup the SysTick timer to generate the tick interrupts at the required
  523. * frequency.
  524. */
  525. #if ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 )
  526. __weak void vPortSetupTimerInterrupt( void )
  527. {
  528. /* Calculate the constants required to configure the tick interrupt. */
  529. #if ( configUSE_TICKLESS_IDLE == 1 )
  530. {
  531. ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
  532. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  533. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
  534. }
  535. #endif /* configUSE_TICKLESS_IDLE */
  536. /* Stop and clear the SysTick. */
  537. portNVIC_SYSTICK_CTRL_REG = 0UL;
  538. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  539. /* Configure SysTick to interrupt at the requested rate. */
  540. portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
  541. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
  542. }
  543. #endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
  544. /*-----------------------------------------------------------*/
  545. __asm uint32_t vPortGetIPSR( void )
  546. {
  547. /* *INDENT-OFF* */
  548. PRESERVE8
  549. mrs r0, ipsr
  550. bx r14
  551. /* *INDENT-ON* */
  552. }
  553. /*-----------------------------------------------------------*/
  554. #if ( configASSERT_DEFINED == 1 )
  555. void vPortValidateInterruptPriority( void )
  556. {
  557. uint32_t ulCurrentInterrupt;
  558. uint8_t ucCurrentPriority;
  559. /* Obtain the number of the currently executing interrupt. */
  560. ulCurrentInterrupt = vPortGetIPSR();
  561. /* Is the interrupt number a user defined interrupt? */
  562. if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
  563. {
  564. /* Look up the interrupt's priority. */
  565. ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
  566. /* The following assertion will fail if a service routine (ISR) for
  567. * an interrupt that has been assigned a priority above
  568. * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
  569. * function. ISR safe FreeRTOS API functions must *only* be called
  570. * from interrupts that have been assigned a priority at or below
  571. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  572. *
  573. * Numerically low interrupt priority numbers represent logically high
  574. * interrupt priorities, therefore the priority of the interrupt must
  575. * be set to a value equal to or numerically *higher* than
  576. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  577. *
  578. * Interrupts that use the FreeRTOS API must not be left at their
  579. * default priority of zero as that is the highest possible priority,
  580. * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
  581. * and therefore also guaranteed to be invalid.
  582. *
  583. * FreeRTOS maintains separate thread and ISR API functions to ensure
  584. * interrupt entry is as fast and simple as possible.
  585. *
  586. * The following links provide detailed information:
  587. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
  588. * https://www.FreeRTOS.org/FAQHelp.html */
  589. configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
  590. }
  591. /* Priority grouping: The interrupt controller (NVIC) allows the bits
  592. * that define each interrupt's priority to be split between bits that
  593. * define the interrupt's pre-emption priority bits and bits that define
  594. * the interrupt's sub-priority. For simplicity all bits must be defined
  595. * to be pre-emption priority bits. The following assertion will fail if
  596. * this is not the case (if some bits represent a sub-priority).
  597. *
  598. * If the application only uses CMSIS libraries for interrupt
  599. * configuration then the correct setting can be achieved on all Cortex-M
  600. * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
  601. * scheduler. Note however that some vendor specific peripheral libraries
  602. * assume a non-zero priority group setting, in which cases using a value
  603. * of zero will result in unpredictable behaviour. */
  604. configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
  605. }
  606. #endif /* configASSERT_DEFINED */