port.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 CM0 port.
  30. *----------------------------------------------------------*/
  31. /* IAR includes. */
  32. #include "intrinsics.h"
  33. /* Scheduler includes. */
  34. #include "FreeRTOS.h"
  35. #include "task.h"
  36. /* Constants required to manipulate the NVIC. */
  37. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  38. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  39. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  40. #define portNVIC_INT_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000ed04 ) )
  41. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  42. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  43. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  44. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  45. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  46. #define portMIN_INTERRUPT_PRIORITY ( 255UL )
  47. #define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL )
  48. #define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL )
  49. /* Constants required to set up the initial stack. */
  50. #define portINITIAL_XPSR ( 0x01000000 )
  51. /* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY is
  52. * defined. The value 255 should also ensure backward compatibility.
  53. * FreeRTOS.org versions prior to V4.3.0 did not include this definition. */
  54. #ifndef configKERNEL_INTERRUPT_PRIORITY
  55. #define configKERNEL_INTERRUPT_PRIORITY 0
  56. #endif
  57. /* Each task maintains its own interrupt status in the critical nesting
  58. * variable. */
  59. static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
  60. /* The systick is a 24-bit counter. */
  61. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  62. /* A fiddle factor to estimate the number of SysTick counts that would have
  63. * occurred while the SysTick counter is stopped during tickless idle
  64. * calculations. */
  65. #ifndef portMISSED_COUNTS_FACTOR
  66. #define portMISSED_COUNTS_FACTOR ( 45UL )
  67. #endif
  68. /* The number of SysTick increments that make up one tick period. */
  69. #if ( configUSE_TICKLESS_IDLE == 1 )
  70. static uint32_t ulTimerCountsForOneTick = 0;
  71. #endif /* configUSE_TICKLESS_IDLE */
  72. /* The maximum number of tick periods that can be suppressed is limited by the
  73. * 24 bit resolution of the SysTick timer. */
  74. #if ( configUSE_TICKLESS_IDLE == 1 )
  75. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  76. #endif /* configUSE_TICKLESS_IDLE */
  77. /* Compensate for the CPU cycles that pass while the SysTick is stopped (low
  78. * power functionality only. */
  79. #if ( configUSE_TICKLESS_IDLE == 1 )
  80. static uint32_t ulStoppedTimerCompensation = 0;
  81. #endif /* configUSE_TICKLESS_IDLE */
  82. /*
  83. * Setup the timer to generate the tick interrupts. The implementation in this
  84. * file is weak to allow application writers to change the timer used to
  85. * generate the tick interrupt.
  86. */
  87. void vPortSetupTimerInterrupt( void );
  88. /*
  89. * Exception handlers.
  90. */
  91. void xPortSysTickHandler( void );
  92. /*
  93. * Start first task is a separate function so it can be tested in isolation.
  94. */
  95. extern void vPortStartFirstTask( void );
  96. /*
  97. * Used to catch tasks that attempt to return from their implementing function.
  98. */
  99. static void prvTaskExitError( void );
  100. /*-----------------------------------------------------------*/
  101. /*
  102. * See header file for description.
  103. */
  104. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  105. TaskFunction_t pxCode,
  106. void * pvParameters )
  107. {
  108. /* Simulate the stack frame as it would be created by a context switch
  109. * interrupt. */
  110. pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
  111. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  112. pxTopOfStack--;
  113. *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
  114. pxTopOfStack--;
  115. *pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
  116. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  117. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  118. pxTopOfStack -= 8; /* R11..R4. */
  119. return pxTopOfStack;
  120. }
  121. /*-----------------------------------------------------------*/
  122. static void prvTaskExitError( void )
  123. {
  124. /* A function that implements a task must not exit or attempt to return to
  125. * its caller as there is nothing to return to. If a task wants to exit it
  126. * should instead call vTaskDelete( NULL ).
  127. *
  128. * Artificially force an assert() to be triggered if configASSERT() is
  129. * defined, then stop here so application writers can catch the error. */
  130. configASSERT( uxCriticalNesting == ~0UL );
  131. portDISABLE_INTERRUPTS();
  132. for( ; ; )
  133. {
  134. }
  135. }
  136. /*-----------------------------------------------------------*/
  137. /*
  138. * See header file for description.
  139. */
  140. BaseType_t xPortStartScheduler( void )
  141. {
  142. /* Make PendSV and SysTick the lowest priority interrupts. */
  143. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  144. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  145. /* Start the timer that generates the tick ISR. Interrupts are disabled
  146. * here already. */
  147. vPortSetupTimerInterrupt();
  148. /* Initialise the critical nesting count ready for the first task. */
  149. uxCriticalNesting = 0;
  150. /* Start the first task. */
  151. vPortStartFirstTask();
  152. /* Should not get here! */
  153. return 0;
  154. }
  155. /*-----------------------------------------------------------*/
  156. void vPortEndScheduler( void )
  157. {
  158. /* Not implemented in ports where there is nothing to return to.
  159. * Artificially force an assert. */
  160. configASSERT( uxCriticalNesting == 1000UL );
  161. }
  162. /*-----------------------------------------------------------*/
  163. void vPortYield( void )
  164. {
  165. /* Set a PendSV to request a context switch. */
  166. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET;
  167. /* Barriers are normally not required but do ensure the code is completely
  168. * within the specified behaviour for the architecture. */
  169. __DSB();
  170. __ISB();
  171. }
  172. /*-----------------------------------------------------------*/
  173. void vPortEnterCritical( void )
  174. {
  175. portDISABLE_INTERRUPTS();
  176. uxCriticalNesting++;
  177. __DSB();
  178. __ISB();
  179. }
  180. /*-----------------------------------------------------------*/
  181. void vPortExitCritical( void )
  182. {
  183. configASSERT( uxCriticalNesting );
  184. uxCriticalNesting--;
  185. if( uxCriticalNesting == 0 )
  186. {
  187. portENABLE_INTERRUPTS();
  188. }
  189. }
  190. /*-----------------------------------------------------------*/
  191. void xPortSysTickHandler( void )
  192. {
  193. uint32_t ulPreviousMask;
  194. ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
  195. {
  196. /* Increment the RTOS tick. */
  197. if( xTaskIncrementTick() != pdFALSE )
  198. {
  199. /* Pend a context switch. */
  200. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET;
  201. }
  202. }
  203. portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
  204. }
  205. /*-----------------------------------------------------------*/
  206. /*
  207. * Setup the systick timer to generate the tick interrupts at the required
  208. * frequency.
  209. */
  210. __weak void vPortSetupTimerInterrupt( void )
  211. {
  212. /* Calculate the constants required to configure the tick interrupt. */
  213. #if ( configUSE_TICKLESS_IDLE == 1 )
  214. {
  215. ulTimerCountsForOneTick = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ );
  216. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  217. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;
  218. }
  219. #endif /* configUSE_TICKLESS_IDLE */
  220. /* Stop and reset the SysTick. */
  221. portNVIC_SYSTICK_CTRL_REG = 0UL;
  222. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  223. /* Configure SysTick to interrupt at the requested rate. */
  224. portNVIC_SYSTICK_LOAD_REG = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
  225. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  226. }
  227. /*-----------------------------------------------------------*/
  228. #if ( configUSE_TICKLESS_IDLE == 1 )
  229. __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  230. {
  231. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
  232. TickType_t xModifiableIdleTime;
  233. /* Make sure the SysTick reload value does not overflow the counter. */
  234. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  235. {
  236. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  237. }
  238. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  239. * is accounted for as best it can be, but using the tickless mode will
  240. * inevitably result in some tiny drift of the time maintained by the
  241. * kernel with respect to calendar time. */
  242. portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
  243. /* Calculate the reload value required to wait xExpectedIdleTime
  244. * tick periods. -1 is used because this code will execute part way
  245. * through one of the tick periods. */
  246. ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  247. if( ulReloadValue > ulStoppedTimerCompensation )
  248. {
  249. ulReloadValue -= ulStoppedTimerCompensation;
  250. }
  251. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  252. * method as that will mask interrupts that should exit sleep mode. */
  253. __disable_interrupt();
  254. __DSB();
  255. __ISB();
  256. /* If a context switch is pending or a task is waiting for the scheduler
  257. * to be unsuspended then abandon the low power entry. */
  258. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  259. {
  260. /* Restart from whatever is left in the count register to complete
  261. * this tick period. */
  262. portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  263. /* Restart SysTick. */
  264. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  265. /* Reset the reload register to the value required for normal tick
  266. * periods. */
  267. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  268. /* Re-enable interrupts - see comments above __disable_interrupt()
  269. * call above. */
  270. __enable_interrupt();
  271. }
  272. else
  273. {
  274. /* Set the new reload value. */
  275. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  276. /* Clear the SysTick count flag and set the count value back to
  277. * zero. */
  278. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  279. /* Restart SysTick. */
  280. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  281. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  282. * set its parameter to 0 to indicate that its implementation contains
  283. * its own wait for interrupt or wait for event instruction, and so wfi
  284. * should not be executed again. However, the original expected idle
  285. * time variable must remain unmodified, so a copy is taken. */
  286. xModifiableIdleTime = xExpectedIdleTime;
  287. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  288. if( xModifiableIdleTime > 0 )
  289. {
  290. __DSB();
  291. __WFI();
  292. __ISB();
  293. }
  294. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  295. /* Re-enable interrupts to allow the interrupt that brought the MCU
  296. * out of sleep mode to execute immediately. see comments above
  297. * __disable_interrupt() call above. */
  298. __enable_interrupt();
  299. __DSB();
  300. __ISB();
  301. /* Disable interrupts again because the clock is about to be stopped
  302. * and interrupts that execute while the clock is stopped will increase
  303. * any slippage between the time maintained by the RTOS and calendar
  304. * time. */
  305. __disable_interrupt();
  306. __DSB();
  307. __ISB();
  308. /* Disable the SysTick clock without reading the
  309. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  310. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  311. * the time the SysTick is stopped for is accounted for as best it can
  312. * be, but using the tickless mode will inevitably result in some tiny
  313. * drift of the time maintained by the kernel with respect to calendar
  314. * time*/
  315. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
  316. /* Determine if the SysTick clock has already counted to zero and
  317. * been set back to the current reload value (the reload back being
  318. * correct for the entire expected idle time) or if the SysTick is yet
  319. * to count to zero (in which case an interrupt other than the SysTick
  320. * must have brought the system out of sleep mode). */
  321. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  322. {
  323. uint32_t ulCalculatedLoadValue;
  324. /* The tick interrupt is already pending, and the SysTick count
  325. * reloaded with ulReloadValue. Reset the
  326. * portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
  327. * period. */
  328. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  329. /* Don't allow a tiny value, or values that have somehow
  330. * underflowed because the post sleep hook did something
  331. * that took too long. */
  332. if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  333. {
  334. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  335. }
  336. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  337. /* As the pending tick will be processed as soon as this
  338. * function exits, the tick value maintained by the tick is stepped
  339. * forward by one less than the time spent waiting. */
  340. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  341. }
  342. else
  343. {
  344. /* Something other than the tick interrupt ended the sleep.
  345. * Work out how long the sleep lasted rounded to complete tick
  346. * periods (not the ulReload value which accounted for part
  347. * ticks). */
  348. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
  349. /* How many complete tick periods passed while the processor
  350. * was waiting? */
  351. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  352. /* The reload value is set to whatever fraction of a single tick
  353. * period remains. */
  354. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  355. }
  356. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
  357. * again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
  358. * value. */
  359. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  360. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  361. vTaskStepTick( ulCompleteTickPeriods );
  362. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  363. /* Exit with interrpts enabled. */
  364. __enable_interrupt();
  365. }
  366. }
  367. #endif /* configUSE_TICKLESS_IDLE */