port.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. /*
  2. * FreeRTOS Kernel <DEVELOPMENT BRANCH>
  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 CM4F port.
  30. *----------------------------------------------------------*/
  31. /* Scheduler includes. */
  32. #include "FreeRTOS.h"
  33. #include "task.h"
  34. #ifndef __ARM_FP
  35. #error This port can only be used when the project options are configured to enable hardware floating point support.
  36. #endif
  37. /* Prototype of all Interrupt Service Routines (ISRs). */
  38. typedef void ( * portISR_t )( void );
  39. /* Constants required to manipulate the core. Registers first... */
  40. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  41. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  42. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  43. #define portNVIC_SHPR2_REG ( *( ( volatile uint32_t * ) 0xe000ed1c ) )
  44. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  45. /* ...then bits in the registers. */
  46. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  47. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  48. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  49. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  50. #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
  51. #define portNVIC_PEND_SYSTICK_SET_BIT ( 1UL << 26UL )
  52. #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
  53. /* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7
  54. * r0p1 port. */
  55. #define portCPUID ( *( ( volatile uint32_t * ) 0xE000ed00 ) )
  56. #define portCORTEX_M7_r0p1_ID ( 0x410FC271UL )
  57. #define portCORTEX_M7_r0p0_ID ( 0x410FC270UL )
  58. #define portMIN_INTERRUPT_PRIORITY ( 255UL )
  59. #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
  60. #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
  61. /* Constants used to check the installation of the FreeRTOS interrupt handlers. */
  62. #define portSCB_VTOR_REG ( *( ( portISR_t ** ) 0xE000ED08 ) )
  63. #define portVECTOR_INDEX_SVC ( 11 )
  64. #define portVECTOR_INDEX_PENDSV ( 14 )
  65. /* Constants required to check the validity of an interrupt priority. */
  66. #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
  67. #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
  68. #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
  69. #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
  70. #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
  71. #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
  72. #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
  73. #define portPRIGROUP_SHIFT ( 8UL )
  74. /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
  75. #define portVECTACTIVE_MASK ( 0xFFUL )
  76. /* Constants required to manipulate the VFP. */
  77. #define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
  78. #define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL )
  79. /* Constants required to set up the initial stack. */
  80. #define portINITIAL_XPSR ( 0x01000000 )
  81. #define portINITIAL_EXC_RETURN ( 0xfffffffd )
  82. /* The systick is a 24-bit counter. */
  83. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  84. /* For strict compliance with the Cortex-M spec the task start address should
  85. * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
  86. #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
  87. /* A fiddle factor to estimate the number of SysTick counts that would have
  88. * occurred while the SysTick counter is stopped during tickless idle
  89. * calculations. */
  90. #define portMISSED_COUNTS_FACTOR ( 94UL )
  91. /* Let the user override the default SysTick clock rate. If defined by the
  92. * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
  93. * configuration register. */
  94. #ifndef configSYSTICK_CLOCK_HZ
  95. #define configSYSTICK_CLOCK_HZ ( configCPU_CLOCK_HZ )
  96. /* Ensure the SysTick is clocked at the same frequency as the core. */
  97. #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( portNVIC_SYSTICK_CLK_BIT )
  98. #else
  99. /* Select the option to clock SysTick not at the same frequency as the core. */
  100. #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( 0 )
  101. #endif
  102. /* Let the user override the pre-loading of the initial LR with the address of
  103. * prvTaskExitError() in case it messes up unwinding of the stack in the
  104. * debugger. */
  105. #ifdef configTASK_RETURN_ADDRESS
  106. #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
  107. #else
  108. #define portTASK_RETURN_ADDRESS prvTaskExitError
  109. #endif
  110. /*
  111. * Setup the timer to generate the tick interrupts. The implementation in this
  112. * file is weak to allow application writers to change the timer used to
  113. * generate the tick interrupt.
  114. */
  115. void vPortSetupTimerInterrupt( void );
  116. /*
  117. * Exception handlers.
  118. */
  119. void xPortPendSVHandler( void ) __attribute__( ( naked ) );
  120. void xPortSysTickHandler( void );
  121. void vPortSVCHandler( void ) __attribute__( ( naked ) );
  122. /*
  123. * Start first task is a separate function so it can be tested in isolation.
  124. */
  125. static void prvPortStartFirstTask( void ) __attribute__( ( naked ) );
  126. /*
  127. * Function to enable the VFP.
  128. */
  129. static void vPortEnableVFP( void ) __attribute__( ( naked ) );
  130. /*
  131. * Used to catch tasks that attempt to return from their implementing function.
  132. */
  133. static void prvTaskExitError( void );
  134. /*-----------------------------------------------------------*/
  135. /* Each task maintains its own interrupt status in the critical nesting
  136. * variable. */
  137. static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
  138. /*
  139. * The number of SysTick increments that make up one tick period.
  140. */
  141. #if ( configUSE_TICKLESS_IDLE == 1 )
  142. static uint32_t ulTimerCountsForOneTick = 0;
  143. #endif /* configUSE_TICKLESS_IDLE */
  144. /*
  145. * The maximum number of tick periods that can be suppressed is limited by the
  146. * 24 bit resolution of the SysTick timer.
  147. */
  148. #if ( configUSE_TICKLESS_IDLE == 1 )
  149. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  150. #endif /* configUSE_TICKLESS_IDLE */
  151. /*
  152. * Compensate for the CPU cycles that pass while the SysTick is stopped (low
  153. * power functionality only.
  154. */
  155. #if ( configUSE_TICKLESS_IDLE == 1 )
  156. static uint32_t ulStoppedTimerCompensation = 0;
  157. #endif /* configUSE_TICKLESS_IDLE */
  158. /*
  159. * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
  160. * FreeRTOS API functions are not called from interrupts that have been assigned
  161. * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
  162. */
  163. #if ( configASSERT_DEFINED == 1 )
  164. static uint8_t ucMaxSysCallPriority = 0;
  165. static uint32_t ulMaxPRIGROUPValue = 0;
  166. static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
  167. #endif /* configASSERT_DEFINED */
  168. /*-----------------------------------------------------------*/
  169. /*
  170. * See header file for description.
  171. */
  172. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  173. TaskFunction_t pxCode,
  174. void * pvParameters )
  175. {
  176. /* Simulate the stack frame as it would be created by a context switch
  177. * interrupt. */
  178. /* Offset added to account for the way the MCU uses the stack on entry/exit
  179. * of interrupts, and to ensure alignment. */
  180. pxTopOfStack--;
  181. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  182. pxTopOfStack--;
  183. *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
  184. pxTopOfStack--;
  185. *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
  186. /* Save code space by skipping register initialisation. */
  187. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  188. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  189. /* A save method is being used that requires each task to maintain its
  190. * own exec return value. */
  191. pxTopOfStack--;
  192. *pxTopOfStack = portINITIAL_EXC_RETURN;
  193. pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
  194. return pxTopOfStack;
  195. }
  196. /*-----------------------------------------------------------*/
  197. static void prvTaskExitError( void )
  198. {
  199. volatile uint32_t ulDummy = 0;
  200. /* A function that implements a task must not exit or attempt to return to
  201. * its caller as there is nothing to return to. If a task wants to exit it
  202. * should instead call vTaskDelete( NULL ).
  203. *
  204. * Artificially force an assert() to be triggered if configASSERT() is
  205. * defined, then stop here so application writers can catch the error. */
  206. configASSERT( uxCriticalNesting == ~0UL );
  207. portDISABLE_INTERRUPTS();
  208. while( ulDummy == 0 )
  209. {
  210. /* This file calls prvTaskExitError() after the scheduler has been
  211. * started to remove a compiler warning about the function being defined
  212. * but never called. ulDummy is used purely to quieten other warnings
  213. * about code appearing after this function is called - making ulDummy
  214. * volatile makes the compiler think the function could return and
  215. * therefore not output an 'unreachable code' warning for code that appears
  216. * after it. */
  217. }
  218. }
  219. /*-----------------------------------------------------------*/
  220. void vPortSVCHandler( void )
  221. {
  222. __asm volatile (
  223. " ldr r3, =pxCurrentTCB \n" /* Restore the context. */
  224. " ldr r1, [r3] \n" /* Get the pxCurrentTCB address. */
  225. " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
  226. " ldmia r0!, {r4-r11, r14} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
  227. " msr psp, r0 \n" /* Restore the task stack pointer. */
  228. " isb \n"
  229. " mov r0, #0 \n"
  230. " msr basepri, r0 \n"
  231. " bx r14 \n"
  232. " \n"
  233. " .ltorg \n"
  234. );
  235. }
  236. /*-----------------------------------------------------------*/
  237. static void prvPortStartFirstTask( void )
  238. {
  239. /* Start the first task. This also clears the bit that indicates the FPU is
  240. * in use in case the FPU was used before the scheduler was started - which
  241. * would otherwise result in the unnecessary leaving of space in the SVC stack
  242. * for lazy saving of FPU registers. */
  243. __asm volatile (
  244. " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
  245. " ldr r0, [r0] \n"
  246. " ldr r0, [r0] \n"
  247. " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
  248. " mov r0, #0 \n" /* Clear the bit that indicates the FPU is in use, see comment above. */
  249. " msr control, r0 \n"
  250. " cpsie i \n" /* Globally enable interrupts. */
  251. " cpsie f \n"
  252. " dsb \n"
  253. " isb \n"
  254. " svc 0 \n" /* System call to start first task. */
  255. " nop \n"
  256. " .ltorg \n"
  257. );
  258. }
  259. /*-----------------------------------------------------------*/
  260. /*
  261. * See header file for description.
  262. */
  263. BaseType_t xPortStartScheduler( void )
  264. {
  265. /* This port can be used on all revisions of the Cortex-M7 core other than
  266. * the r0p1 parts. r0p1 parts should use the port from the
  267. * /source/portable/GCC/ARM_CM7/r0p1 directory. */
  268. configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
  269. configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
  270. /* An application can install FreeRTOS interrupt handlers in one of the
  271. * following ways:
  272. * 1. Direct Routing - Install the functions vPortSVCHandler and
  273. * xPortPendSVHandler for SVCall and PendSV interrupts respectively.
  274. * 2. Indirect Routing - Install separate handlers for SVCall and PendSV
  275. * interrupts and route program control from those handlers to
  276. * vPortSVCHandler and xPortPendSVHandler functions.
  277. *
  278. * Applications that use Indirect Routing must set
  279. * configCHECK_HANDLER_INSTALLATION to 0 in their FreeRTOSConfig.h. Direct
  280. * routing, which is validated here when configCHECK_HANDLER_INSTALLATION
  281. * is 1, should be preferred when possible. */
  282. #if ( configCHECK_HANDLER_INSTALLATION == 1 )
  283. {
  284. const portISR_t * const pxVectorTable = portSCB_VTOR_REG;
  285. /* Validate that the application has correctly installed the FreeRTOS
  286. * handlers for SVCall and PendSV interrupts. We do not check the
  287. * installation of the SysTick handler because the application may
  288. * choose to drive the RTOS tick using a timer other than the SysTick
  289. * timer by overriding the weak function vPortSetupTimerInterrupt().
  290. *
  291. * Assertion failures here indicate incorrect installation of the
  292. * FreeRTOS handlers. For help installing the FreeRTOS handlers, see
  293. * https://www.freertos.org/Why-FreeRTOS/FAQs.
  294. *
  295. * Systems with a configurable address for the interrupt vector table
  296. * can also encounter assertion failures or even system faults here if
  297. * VTOR is not set correctly to point to the application's vector table. */
  298. configASSERT( pxVectorTable[ portVECTOR_INDEX_SVC ] == vPortSVCHandler );
  299. configASSERT( pxVectorTable[ portVECTOR_INDEX_PENDSV ] == xPortPendSVHandler );
  300. }
  301. #endif /* configCHECK_HANDLER_INSTALLATION */
  302. #if ( configASSERT_DEFINED == 1 )
  303. {
  304. volatile uint8_t ucOriginalPriority;
  305. volatile uint32_t ulImplementedPrioBits = 0;
  306. volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
  307. volatile uint8_t ucMaxPriorityValue;
  308. /* Determine the maximum priority from which ISR safe FreeRTOS API
  309. * functions can be called. ISR safe functions are those that end in
  310. * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
  311. * ensure interrupt entry is as fast and simple as possible.
  312. *
  313. * Save the interrupt priority value that is about to be clobbered. */
  314. ucOriginalPriority = *pucFirstUserPriorityRegister;
  315. /* Determine the number of priority bits available. First write to all
  316. * possible bits. */
  317. *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
  318. /* Read the value back to see how many bits stuck. */
  319. ucMaxPriorityValue = *pucFirstUserPriorityRegister;
  320. /* Use the same mask on the maximum system call priority. */
  321. ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
  322. /* Check that the maximum system call priority is nonzero after
  323. * accounting for the number of priority bits supported by the
  324. * hardware. A priority of 0 is invalid because setting the BASEPRI
  325. * register to 0 unmasks all interrupts, and interrupts with priority 0
  326. * cannot be masked using BASEPRI.
  327. * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  328. configASSERT( ucMaxSysCallPriority );
  329. /* Check that the bits not implemented in hardware are zero in
  330. * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
  331. configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
  332. /* Calculate the maximum acceptable priority group value for the number
  333. * of bits read back. */
  334. while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
  335. {
  336. ulImplementedPrioBits++;
  337. ucMaxPriorityValue <<= ( uint8_t ) 0x01;
  338. }
  339. if( ulImplementedPrioBits == 8 )
  340. {
  341. /* When the hardware implements 8 priority bits, there is no way for
  342. * the software to configure PRIGROUP to not have sub-priorities. As
  343. * a result, the least significant bit is always used for sub-priority
  344. * and there are 128 preemption priorities and 2 sub-priorities.
  345. *
  346. * This may cause some confusion in some cases - for example, if
  347. * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
  348. * priority interrupts will be masked in Critical Sections as those
  349. * are at the same preemption priority. This may appear confusing as
  350. * 4 is higher (numerically lower) priority than
  351. * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
  352. * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
  353. * to 4, this confusion does not happen and the behaviour remains the same.
  354. *
  355. * The following assert ensures that the sub-priority bit in the
  356. * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
  357. * confusion. */
  358. configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
  359. ulMaxPRIGROUPValue = 0;
  360. }
  361. else
  362. {
  363. ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
  364. }
  365. /* Shift the priority group value back to its position within the AIRCR
  366. * register. */
  367. ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
  368. ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
  369. /* Restore the clobbered interrupt priority register to its original
  370. * value. */
  371. *pucFirstUserPriorityRegister = ucOriginalPriority;
  372. }
  373. #endif /* configASSERT_DEFINED */
  374. /* Make PendSV and SysTick the lowest priority interrupts, and make SVCall
  375. * the highest priority. */
  376. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  377. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  378. portNVIC_SHPR2_REG = 0;
  379. /* Start the timer that generates the tick ISR. Interrupts are disabled
  380. * here already. */
  381. vPortSetupTimerInterrupt();
  382. /* Initialise the critical nesting count ready for the first task. */
  383. uxCriticalNesting = 0;
  384. /* Ensure the VFP is enabled - it should be anyway. */
  385. vPortEnableVFP();
  386. /* Lazy save always. */
  387. *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
  388. /* Start the first task. */
  389. prvPortStartFirstTask();
  390. /* Should never get here as the tasks will now be executing! Call the task
  391. * exit error function to prevent compiler warnings about a static function
  392. * not being called in the case that the application writer overrides this
  393. * functionality by defining configTASK_RETURN_ADDRESS. Call
  394. * vTaskSwitchContext() so link time optimisation does not remove the
  395. * symbol. */
  396. vTaskSwitchContext();
  397. prvTaskExitError();
  398. /* Should not get here! */
  399. return 0;
  400. }
  401. /*-----------------------------------------------------------*/
  402. void vPortEndScheduler( void )
  403. {
  404. /* Not implemented in ports where there is nothing to return to.
  405. * Artificially force an assert. */
  406. configASSERT( uxCriticalNesting == 1000UL );
  407. }
  408. /*-----------------------------------------------------------*/
  409. void vPortEnterCritical( void )
  410. {
  411. portDISABLE_INTERRUPTS();
  412. uxCriticalNesting++;
  413. /* This is not the interrupt safe version of the enter critical function so
  414. * assert() if it is being called from an interrupt context. Only API
  415. * functions that end in "FromISR" can be used in an interrupt. Only assert if
  416. * the critical nesting count is 1 to protect against recursive calls if the
  417. * assert function also uses a critical section. */
  418. if( uxCriticalNesting == 1 )
  419. {
  420. configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
  421. }
  422. }
  423. /*-----------------------------------------------------------*/
  424. void vPortExitCritical( void )
  425. {
  426. configASSERT( uxCriticalNesting );
  427. uxCriticalNesting--;
  428. if( uxCriticalNesting == 0 )
  429. {
  430. portENABLE_INTERRUPTS();
  431. }
  432. }
  433. /*-----------------------------------------------------------*/
  434. void xPortPendSVHandler( void )
  435. {
  436. /* This is a naked function. */
  437. __asm volatile
  438. (
  439. " mrs r0, psp \n"
  440. " isb \n"
  441. " \n"
  442. " ldr r3, =pxCurrentTCB \n" /* Get the location of the current TCB. */
  443. " ldr r2, [r3] \n"
  444. " \n"
  445. " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, push high vfp registers. */
  446. " it eq \n"
  447. " vstmdbeq r0!, {s16-s31} \n"
  448. " \n"
  449. " stmdb r0!, {r4-r11, r14} \n" /* Save the core registers. */
  450. " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
  451. " \n"
  452. " stmdb sp!, {r0, r3} \n"
  453. " mov r0, %0 \n"
  454. " msr basepri, r0 \n"
  455. " dsb \n"
  456. " isb \n"
  457. " bl vTaskSwitchContext \n"
  458. " mov r0, #0 \n"
  459. " msr basepri, r0 \n"
  460. " ldmia sp!, {r0, r3} \n"
  461. " \n"
  462. " ldr r1, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
  463. " ldr r0, [r1] \n"
  464. " \n"
  465. " ldmia r0!, {r4-r11, r14} \n" /* Pop the core registers. */
  466. " \n"
  467. " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, pop the high vfp registers too. */
  468. " it eq \n"
  469. " vldmiaeq r0!, {s16-s31} \n"
  470. " \n"
  471. " msr psp, r0 \n"
  472. " isb \n"
  473. " \n"
  474. #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */
  475. #if WORKAROUND_PMU_CM001 == 1
  476. " push { r14 } \n"
  477. " pop { pc } \n"
  478. #endif
  479. #endif
  480. " \n"
  481. " bx r14 \n"
  482. " \n"
  483. " .ltorg \n"
  484. ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
  485. );
  486. }
  487. /*-----------------------------------------------------------*/
  488. void xPortSysTickHandler( void )
  489. {
  490. /* The SysTick runs at the lowest interrupt priority, so when this interrupt
  491. * executes all interrupts must be unmasked. There is therefore no need to
  492. * save and then restore the interrupt mask value as its value is already
  493. * known. */
  494. portDISABLE_INTERRUPTS();
  495. traceISR_ENTER();
  496. {
  497. /* Increment the RTOS tick. */
  498. if( xTaskIncrementTick() != pdFALSE )
  499. {
  500. traceISR_EXIT_TO_SCHEDULER();
  501. /* A context switch is required. Context switching is performed in
  502. * the PendSV interrupt. Pend the PendSV interrupt. */
  503. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  504. }
  505. else
  506. {
  507. traceISR_EXIT();
  508. }
  509. }
  510. portENABLE_INTERRUPTS();
  511. }
  512. /*-----------------------------------------------------------*/
  513. #if ( configUSE_TICKLESS_IDLE == 1 )
  514. __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  515. {
  516. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
  517. TickType_t xModifiableIdleTime;
  518. /* Make sure the SysTick reload value does not overflow the counter. */
  519. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  520. {
  521. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  522. }
  523. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  524. * method as that will mask interrupts that should exit sleep mode. */
  525. __asm volatile ( "cpsid i" ::: "memory" );
  526. __asm volatile ( "dsb" );
  527. __asm volatile ( "isb" );
  528. /* If a context switch is pending or a task is waiting for the scheduler
  529. * to be unsuspended then abandon the low power entry. */
  530. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  531. {
  532. /* Re-enable interrupts - see comments above the cpsid instruction
  533. * above. */
  534. __asm volatile ( "cpsie i" ::: "memory" );
  535. }
  536. else
  537. {
  538. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  539. * is accounted for as best it can be, but using the tickless mode will
  540. * inevitably result in some tiny drift of the time maintained by the
  541. * kernel with respect to calendar time. */
  542. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
  543. /* Use the SysTick current-value register to determine the number of
  544. * SysTick decrements remaining until the next tick interrupt. If the
  545. * current-value register is zero, then there are actually
  546. * ulTimerCountsForOneTick decrements remaining, not zero, because the
  547. * SysTick requests the interrupt when decrementing from 1 to 0. */
  548. ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  549. if( ulSysTickDecrementsLeft == 0 )
  550. {
  551. ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
  552. }
  553. /* Calculate the reload value required to wait xExpectedIdleTime
  554. * tick periods. -1 is used because this code normally executes part
  555. * way through the first tick period. But if the SysTick IRQ is now
  556. * pending, then clear the IRQ, suppressing the first tick, and correct
  557. * the reload value to reflect that the second tick period is already
  558. * underway. The expected idle time is always at least two ticks. */
  559. ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  560. if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
  561. {
  562. portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
  563. ulReloadValue -= ulTimerCountsForOneTick;
  564. }
  565. if( ulReloadValue > ulStoppedTimerCompensation )
  566. {
  567. ulReloadValue -= ulStoppedTimerCompensation;
  568. }
  569. /* Set the new reload value. */
  570. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  571. /* Clear the SysTick count flag and set the count value back to
  572. * zero. */
  573. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  574. /* Restart SysTick. */
  575. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  576. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  577. * set its parameter to 0 to indicate that its implementation contains
  578. * its own wait for interrupt or wait for event instruction, and so wfi
  579. * should not be executed again. However, the original expected idle
  580. * time variable must remain unmodified, so a copy is taken. */
  581. xModifiableIdleTime = xExpectedIdleTime;
  582. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  583. if( xModifiableIdleTime > 0 )
  584. {
  585. __asm volatile ( "dsb" ::: "memory" );
  586. __asm volatile ( "wfi" );
  587. __asm volatile ( "isb" );
  588. }
  589. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  590. /* Re-enable interrupts to allow the interrupt that brought the MCU
  591. * out of sleep mode to execute immediately. See comments above
  592. * the cpsid instruction above. */
  593. __asm volatile ( "cpsie i" ::: "memory" );
  594. __asm volatile ( "dsb" );
  595. __asm volatile ( "isb" );
  596. /* Disable interrupts again because the clock is about to be stopped
  597. * and interrupts that execute while the clock is stopped will increase
  598. * any slippage between the time maintained by the RTOS and calendar
  599. * time. */
  600. __asm volatile ( "cpsid i" ::: "memory" );
  601. __asm volatile ( "dsb" );
  602. __asm volatile ( "isb" );
  603. /* Disable the SysTick clock without reading the
  604. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  605. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  606. * the time the SysTick is stopped for is accounted for as best it can
  607. * be, but using the tickless mode will inevitably result in some tiny
  608. * drift of the time maintained by the kernel with respect to calendar
  609. * time*/
  610. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
  611. /* Determine whether the SysTick has already counted to zero. */
  612. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  613. {
  614. uint32_t ulCalculatedLoadValue;
  615. /* The tick interrupt ended the sleep (or is now pending), and
  616. * a new tick period has started. Reset portNVIC_SYSTICK_LOAD_REG
  617. * with whatever remains of the new tick period. */
  618. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  619. /* Don't allow a tiny value, or values that have somehow
  620. * underflowed because the post sleep hook did something
  621. * that took too long or because the SysTick current-value register
  622. * is zero. */
  623. if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  624. {
  625. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  626. }
  627. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  628. /* As the pending tick will be processed as soon as this
  629. * function exits, the tick value maintained by the tick is stepped
  630. * forward by one less than the time spent waiting. */
  631. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  632. }
  633. else
  634. {
  635. /* Something other than the tick interrupt ended the sleep. */
  636. /* Use the SysTick current-value register to determine the
  637. * number of SysTick decrements remaining until the expected idle
  638. * time would have ended. */
  639. ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  640. #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
  641. {
  642. /* If the SysTick is not using the core clock, the current-
  643. * value register might still be zero here. In that case, the
  644. * SysTick didn't load from the reload register, and there are
  645. * ulReloadValue decrements remaining in the expected idle
  646. * time, not zero. */
  647. if( ulSysTickDecrementsLeft == 0 )
  648. {
  649. ulSysTickDecrementsLeft = ulReloadValue;
  650. }
  651. }
  652. #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
  653. /* Work out how long the sleep lasted rounded to complete tick
  654. * periods (not the ulReload value which accounted for part
  655. * ticks). */
  656. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
  657. /* How many complete tick periods passed while the processor
  658. * was waiting? */
  659. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  660. /* The reload value is set to whatever fraction of a single tick
  661. * period remains. */
  662. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  663. }
  664. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
  665. * then set portNVIC_SYSTICK_LOAD_REG back to its standard value. If
  666. * the SysTick is not using the core clock, temporarily configure it to
  667. * use the core clock. This configuration forces the SysTick to load
  668. * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
  669. * cycle of the other clock. Then portNVIC_SYSTICK_LOAD_REG is ready
  670. * to receive the standard value immediately. */
  671. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  672. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  673. #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
  674. {
  675. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  676. }
  677. #else
  678. {
  679. /* The temporary usage of the core clock has served its purpose,
  680. * as described above. Resume usage of the other clock. */
  681. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
  682. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  683. {
  684. /* The partial tick period already ended. Be sure the SysTick
  685. * counts it only once. */
  686. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
  687. }
  688. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  689. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  690. }
  691. #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
  692. /* Step the tick to account for any tick periods that elapsed. */
  693. vTaskStepTick( ulCompleteTickPeriods );
  694. /* Exit with interrupts enabled. */
  695. __asm volatile ( "cpsie i" ::: "memory" );
  696. }
  697. }
  698. #endif /* #if configUSE_TICKLESS_IDLE */
  699. /*-----------------------------------------------------------*/
  700. /*
  701. * Setup the systick timer to generate the tick interrupts at the required
  702. * frequency.
  703. */
  704. __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
  705. {
  706. /* Calculate the constants required to configure the tick interrupt. */
  707. #if ( configUSE_TICKLESS_IDLE == 1 )
  708. {
  709. ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
  710. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  711. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
  712. }
  713. #endif /* configUSE_TICKLESS_IDLE */
  714. /* Stop and clear the SysTick. */
  715. portNVIC_SYSTICK_CTRL_REG = 0UL;
  716. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  717. /* Configure SysTick to interrupt at the requested rate. */
  718. portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
  719. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
  720. }
  721. /*-----------------------------------------------------------*/
  722. /* This is a naked function. */
  723. static void vPortEnableVFP( void )
  724. {
  725. __asm volatile
  726. (
  727. " ldr.w r0, =0xE000ED88 \n" /* The FPU enable bits are in the CPACR. */
  728. " ldr r1, [r0] \n"
  729. " \n"
  730. " orr r1, r1, #( 0xf << 20 ) \n" /* Enable CP10 and CP11 coprocessors, then save back. */
  731. " str r1, [r0] \n"
  732. " bx r14 \n"
  733. " .ltorg \n"
  734. );
  735. }
  736. /*-----------------------------------------------------------*/
  737. #if ( configASSERT_DEFINED == 1 )
  738. void vPortValidateInterruptPriority( void )
  739. {
  740. uint32_t ulCurrentInterrupt;
  741. uint8_t ucCurrentPriority;
  742. /* Obtain the number of the currently executing interrupt. */
  743. __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
  744. /* Is the interrupt number a user defined interrupt? */
  745. if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
  746. {
  747. /* Look up the interrupt's priority. */
  748. ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
  749. /* The following assertion will fail if a service routine (ISR) for
  750. * an interrupt that has been assigned a priority above
  751. * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
  752. * function. ISR safe FreeRTOS API functions must *only* be called
  753. * from interrupts that have been assigned a priority at or below
  754. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  755. *
  756. * Numerically low interrupt priority numbers represent logically high
  757. * interrupt priorities, therefore the priority of the interrupt must
  758. * be set to a value equal to or numerically *higher* than
  759. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  760. *
  761. * Interrupts that use the FreeRTOS API must not be left at their
  762. * default priority of zero as that is the highest possible priority,
  763. * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
  764. * and therefore also guaranteed to be invalid.
  765. *
  766. * FreeRTOS maintains separate thread and ISR API functions to ensure
  767. * interrupt entry is as fast and simple as possible.
  768. *
  769. * The following links provide detailed information:
  770. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
  771. * https://www.freertos.org/Why-FreeRTOS/FAQs */
  772. configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
  773. }
  774. /* Priority grouping: The interrupt controller (NVIC) allows the bits
  775. * that define each interrupt's priority to be split between bits that
  776. * define the interrupt's pre-emption priority bits and bits that define
  777. * the interrupt's sub-priority. For simplicity all bits must be defined
  778. * to be pre-emption priority bits. The following assertion will fail if
  779. * this is not the case (if some bits represent a sub-priority).
  780. *
  781. * If the application only uses CMSIS libraries for interrupt
  782. * configuration then the correct setting can be achieved on all Cortex-M
  783. * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
  784. * scheduler. Note however that some vendor specific peripheral libraries
  785. * assume a non-zero priority group setting, in which cases using a value
  786. * of zero will result in unpredictable behaviour. */
  787. configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
  788. }
  789. #endif /* configASSERT_DEFINED */