port.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /*
  2. * FreeRTOS Kernel V10.4.6
  3. * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. * Copyright (c) 2021 Raspberry Pi (Trading) Ltd.
  5. *
  6. * SPDX-License-Identifier: MIT AND BSD-3-Clause
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  9. * this software and associated documentation files (the "Software"), to deal in
  10. * the Software without restriction, including without limitation the rights to
  11. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  12. * the Software, and to permit persons to whom the Software is furnished to do so,
  13. * subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  20. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  21. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  22. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  23. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. *
  25. * https://www.FreeRTOS.org
  26. * https://github.com/FreeRTOS
  27. *
  28. */
  29. /*----------------------------------------------------------------------
  30. * Implementation of functions defined in portable.h for the RP2040 port.
  31. *----------------------------------------------------------------------*/
  32. #include "FreeRTOS.h"
  33. #include "task.h"
  34. #include "rp2040_config.h"
  35. #include "hardware/clocks.h"
  36. #include "hardware/exception.h"
  37. /*
  38. * LIB_PICO_MULTICORE == 1, if we are linked with pico_multicore (note that
  39. * the non SMP FreeRTOS_Kernel is not linked with pico_multicore itself). We
  40. * use this flag to determine if we need multi-core functionality.
  41. */
  42. #if ( LIB_PICO_MULTICORE == 1)
  43. #include "pico/multicore.h"
  44. #endif /* LIB_PICO_MULTICORE */
  45. /* Constants required to manipulate the NVIC. */
  46. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  47. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  48. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  49. #define portNVIC_INT_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000ed04 ) )
  50. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  51. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  52. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  53. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  54. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  55. #define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )
  56. #define portMIN_INTERRUPT_PRIORITY ( 255UL )
  57. #define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL )
  58. #define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL )
  59. /* Constants required to set up the initial stack. */
  60. #define portINITIAL_XPSR ( 0x01000000 )
  61. /* The systick is a 24-bit counter. */
  62. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  63. /* A fiddle factor to estimate the number of SysTick counts that would have
  64. * occurred while the SysTick counter is stopped during tickless idle
  65. * calculations. */
  66. #ifndef portMISSED_COUNTS_FACTOR
  67. #define portMISSED_COUNTS_FACTOR ( 45UL )
  68. #endif
  69. /* Let the user override the pre-loading of the initial LR with the address of
  70. * prvTaskExitError() in case it messes up unwinding of the stack in the
  71. * debugger. */
  72. #ifdef configTASK_RETURN_ADDRESS
  73. #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
  74. #else
  75. #define portTASK_RETURN_ADDRESS prvTaskExitError
  76. #endif
  77. /*
  78. * Setup the timer to generate the tick interrupts. The implementation in this
  79. * file is weak to allow application writers to change the timer used to
  80. * generate the tick interrupt.
  81. */
  82. void vPortSetupTimerInterrupt( void );
  83. /*
  84. * Exception handlers.
  85. */
  86. void xPortPendSVHandler( void ) __attribute__( ( naked ) );
  87. void xPortSysTickHandler( void );
  88. void vPortSVCHandler( void );
  89. /*
  90. * Start first task is a separate function so it can be tested in isolation.
  91. */
  92. static void vPortStartFirstTask( void ) __attribute__( ( naked ) );
  93. /*
  94. * Used to catch tasks that attempt to return from their implementing function.
  95. */
  96. static void prvTaskExitError( void );
  97. /*-----------------------------------------------------------*/
  98. /* Each task maintains its own interrupt status in the critical nesting
  99. * variable. */
  100. static UBaseType_t uxCriticalNesting = {0xaaaaaaaa};
  101. /*-----------------------------------------------------------*/
  102. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1 )
  103. #include "pico/lock_core.h"
  104. #include "hardware/irq.h"
  105. #include "event_groups.h"
  106. #if configSUPPORT_STATIC_ALLOCATION
  107. static StaticEventGroup_t xStaticEventGroup;
  108. #define pEventGroup (&xStaticEventGroup)
  109. #endif /* configSUPPORT_STATIC_ALLOCATION */
  110. static EventGroupHandle_t xEventGroup;
  111. #if ( LIB_PICO_MULTICORE == 1 )
  112. static EventBits_t uxCrossCoreEventBits;
  113. static spin_lock_t * pxCrossCoreSpinLock;
  114. #endif /* LIB_PICO_MULTICORE */
  115. static spin_lock_t * pxYieldSpinLock;
  116. static uint32_t ulYieldSpinLockSaveValue;
  117. #endif /* configSUPPORT_PICO_SYNC_INTEROP */
  118. /*
  119. * The number of SysTick increments that make up one tick period.
  120. */
  121. #if ( configUSE_TICKLESS_IDLE == 1 )
  122. static uint32_t ulTimerCountsForOneTick = 0;
  123. #endif /* configUSE_TICKLESS_IDLE */
  124. /*
  125. * The maximum number of tick periods that can be suppressed is limited by the
  126. * 24 bit resolution of the SysTick timer.
  127. */
  128. #if ( configUSE_TICKLESS_IDLE == 1 )
  129. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  130. #endif /* configUSE_TICKLESS_IDLE */
  131. /*
  132. * Compensate for the CPU cycles that pass while the SysTick is stopped (low
  133. * power functionality only.
  134. */
  135. #if ( configUSE_TICKLESS_IDLE == 1 )
  136. static uint32_t ulStoppedTimerCompensation = 0;
  137. #endif /* configUSE_TICKLESS_IDLE */
  138. /*-----------------------------------------------------------*/
  139. #if ( LIB_PICO_MULTICORE == 1 )
  140. #define INVALID_LAUNCH_CORE_NUM 0xffu
  141. static uint8_t ucLaunchCoreNum = INVALID_LAUNCH_CORE_NUM;
  142. #define portIS_FREE_RTOS_CORE() ( ucLaunchCoreNum == get_core_num() )
  143. #else
  144. #define portIS_FREE_RTOS_CORE() pdTRUE
  145. #endif /* LIB_PICO_MULTICORE */
  146. /*
  147. * See header file for description.
  148. */
  149. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  150. TaskFunction_t pxCode,
  151. void * pvParameters )
  152. {
  153. /* Simulate the stack frame as it would be created by a context switch
  154. * interrupt. */
  155. pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
  156. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  157. pxTopOfStack--;
  158. *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
  159. pxTopOfStack--;
  160. *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
  161. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  162. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  163. pxTopOfStack -= 8; /* R11..R4. */
  164. return pxTopOfStack;
  165. }
  166. /*-----------------------------------------------------------*/
  167. static void prvTaskExitError( void )
  168. {
  169. /* A function that implements a task must not exit or attempt to return to
  170. * its caller as there is nothing to return to. If a task wants to exit it
  171. * should instead call vTaskDelete( NULL ). */
  172. panic_unsupported();
  173. }
  174. /*-----------------------------------------------------------*/
  175. void vPortSVCHandler( void )
  176. {
  177. /* This function is no longer used, but retained for backward
  178. * compatibility. */
  179. }
  180. /*-----------------------------------------------------------*/
  181. void vPortStartFirstTask( void )
  182. {
  183. __asm volatile (
  184. " .syntax unified \n"
  185. " ldr r2, =pxCurrentTCB \n"/* Obtain location of pxCurrentTCB. */
  186. " ldr r3, [r2] \n"
  187. " ldr r0, [r3] \n"/* The first item in pxCurrentTCB is the task top of stack. */
  188. " adds r0, #32 \n"/* Discard everything up to r0. */
  189. " msr psp, r0 \n"/* This is now the new top of stack to use in the task. */
  190. " movs r0, #2 \n"/* Switch to the psp stack. */
  191. " msr CONTROL, r0 \n"
  192. " isb \n"
  193. " pop {r0-r5} \n"/* Pop the registers that are saved automatically. */
  194. " mov lr, r5 \n"/* lr is now in r5. */
  195. " pop {r3} \n"/* Return address is now in r3. */
  196. " pop {r2} \n"/* Pop and discard XPSR. */
  197. " cpsie i \n"/* The first task has its context and interrupts can be enabled. */
  198. " bx r3 \n"/* Finally, jump to the user defined task code. */
  199. );
  200. }
  201. /*-----------------------------------------------------------*/
  202. #if ( LIB_PICO_MULTICORE == 1 ) && ( configSUPPORT_PICO_SYNC_INTEROP == 1)
  203. static void prvFIFOInterruptHandler()
  204. {
  205. /* We must remove the contents (which we don't care about)
  206. * to clear the IRQ */
  207. multicore_fifo_drain();
  208. multicore_fifo_clear_irq();
  209. BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  210. uint32_t ulSave = spin_lock_blocking( pxCrossCoreSpinLock );
  211. EventBits_t ulBits = uxCrossCoreEventBits;
  212. uxCrossCoreEventBits &= ~ulBits;
  213. spin_unlock( pxCrossCoreSpinLock, ulSave );
  214. xEventGroupSetBitsFromISR( xEventGroup, ulBits, &xHigherPriorityTaskWoken );
  215. portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
  216. }
  217. #endif
  218. /*
  219. * See header file for description.
  220. */
  221. BaseType_t xPortStartScheduler( void )
  222. {
  223. /* Make PendSV, CallSV and SysTick the same priority as the kernel. */
  224. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  225. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  226. #if (configUSE_DYNAMIC_EXCEPTION_HANDLERS == 1)
  227. exception_set_exclusive_handler( PENDSV_EXCEPTION, xPortPendSVHandler );
  228. exception_set_exclusive_handler( SYSTICK_EXCEPTION, xPortSysTickHandler );
  229. exception_set_exclusive_handler( SVCALL_EXCEPTION, vPortSVCHandler );
  230. #endif
  231. /* Start the timer that generates the tick ISR. Interrupts are disabled
  232. * here already. */
  233. vPortSetupTimerInterrupt();
  234. /* Initialise the critical nesting count ready for the first task. */
  235. uxCriticalNesting = 0;
  236. #if (LIB_PICO_MULTICORE == 1)
  237. ucLaunchCoreNum = get_core_num();
  238. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1)
  239. multicore_fifo_clear_irq();
  240. multicore_fifo_drain();
  241. uint32_t irq_num = 15 + get_core_num();
  242. irq_set_priority( irq_num, portMIN_INTERRUPT_PRIORITY );
  243. irq_set_exclusive_handler( irq_num, prvFIFOInterruptHandler );
  244. irq_set_enabled( irq_num, 1 );
  245. #endif
  246. #endif
  247. /* Start the first task. */
  248. vPortStartFirstTask();
  249. /* Should never get here as the tasks will now be executing! Call the task
  250. * exit error function to prevent compiler warnings about a static function
  251. * not being called in the case that the application writer overrides this
  252. * functionality by defining configTASK_RETURN_ADDRESS. Call
  253. * vTaskSwitchContext() so link time optimisation does not remove the
  254. * symbol. */
  255. vTaskSwitchContext();
  256. prvTaskExitError();
  257. /* Should not get here! */
  258. return 0;
  259. }
  260. /*-----------------------------------------------------------*/
  261. void vPortEndScheduler( void )
  262. {
  263. /* Not implemented in ports where there is nothing to return to. */
  264. panic_unsupported();
  265. }
  266. /*-----------------------------------------------------------*/
  267. void vPortYield( void )
  268. {
  269. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1 )
  270. /* We are not in an ISR, and pxYieldSpinLock is always dealt with and
  271. * cleared interrupts are re-enabled, so should be NULL */
  272. configASSERT( pxYieldSpinLock == NULL );
  273. #endif /* configSUPPORT_PICO_SYNC_INTEROP */
  274. /* Set a PendSV to request a context switch. */
  275. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  276. /* Barriers are normally not required but do ensure the code is completely
  277. * within the specified behaviour for the architecture. */
  278. __asm volatile ( "dsb" ::: "memory" );
  279. __asm volatile ( "isb" );
  280. }
  281. /*-----------------------------------------------------------*/
  282. void vPortEnterCritical( void )
  283. {
  284. portDISABLE_INTERRUPTS();
  285. uxCriticalNesting++;
  286. __asm volatile ( "dsb" ::: "memory" );
  287. __asm volatile ( "isb" );
  288. }
  289. /*-----------------------------------------------------------*/
  290. void vPortExitCritical( void )
  291. {
  292. configASSERT( uxCriticalNesting );
  293. uxCriticalNesting--;
  294. if( uxCriticalNesting == 0 )
  295. {
  296. portENABLE_INTERRUPTS();
  297. }
  298. }
  299. void vPortEnableInterrupts() {
  300. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1 )
  301. if( pxYieldSpinLock )
  302. {
  303. spin_unlock(pxYieldSpinLock, ulYieldSpinLockSaveValue);
  304. pxYieldSpinLock = NULL;
  305. }
  306. #endif
  307. __asm volatile ( " cpsie i " ::: "memory" );
  308. }
  309. /*-----------------------------------------------------------*/
  310. uint32_t ulSetInterruptMaskFromISR( void )
  311. {
  312. __asm volatile (
  313. " mrs r0, PRIMASK \n"
  314. " cpsid i \n"
  315. " bx lr "
  316. ::: "memory"
  317. );
  318. }
  319. /*-----------------------------------------------------------*/
  320. void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask )
  321. {
  322. __asm volatile (
  323. " msr PRIMASK, r0 \n"
  324. " bx lr "
  325. ::: "memory"
  326. );
  327. }
  328. /*-----------------------------------------------------------*/
  329. void xPortPendSVHandler( void )
  330. {
  331. /* This is a naked function. */
  332. __asm volatile
  333. (
  334. " .syntax unified \n"
  335. " mrs r0, psp \n"
  336. " \n"
  337. " ldr r3, =pxCurrentTCB \n"/* Get the location of the current TCB. */
  338. " ldr r2, [r3] \n"
  339. " \n"
  340. " subs r0, r0, #32 \n"/* Make space for the remaining low registers. */
  341. " str r0, [r2] \n"/* Save the new top of stack. */
  342. " stmia r0!, {r4-r7} \n"/* Store the low registers that are not saved automatically. */
  343. " mov r4, r8 \n"/* Store the high registers. */
  344. " mov r5, r9 \n"
  345. " mov r6, r10 \n"
  346. " mov r7, r11 \n"
  347. " stmia r0!, {r4-r7} \n"
  348. #if portUSE_DIVIDER_SAVE_RESTORE
  349. " movs r2, #0xd \n"/* Store the divider state. */
  350. " lsls r2, #28 \n"
  351. /* We expect that the divider is ready at this point (which is
  352. * necessary to safely save/restore), because:
  353. * a) if we have not been interrupted since we entered this method,
  354. * then >8 cycles have clearly passed, so the divider is done
  355. * b) if we were interrupted in the interim, then any "safe" - i.e.
  356. * does the right thing in an IRQ - use of the divider should
  357. * have waited for any in-process divide to complete, saved and
  358. * then fully restored the result, thus the result is ready in
  359. * that case too. */
  360. " ldr r4, [r2, #0x60] \n"/* SIO_DIV_UDIVIDEND_OFFSET */
  361. " ldr r5, [r2, #0x64] \n"/* SIO_DIV_UDIVISOR_OFFSET */
  362. " ldr r6, [r2, #0x74] \n"/* SIO_DIV_REMAINDER_OFFSET */
  363. " ldr r7, [r2, #0x70] \n"/* SIO_DIV_QUOTIENT_OFFSET */
  364. /* We actually save the divider state in the 4 words below
  365. * our recorded stack pointer, so as not to disrupt the stack
  366. * frame expected by debuggers - this is addressed by
  367. * portEXTRA_STACK_SIZE */
  368. " subs r0, r0, #48 \n"
  369. " stmia r0!, {r4-r7} \n"
  370. #endif /* portUSE_DIVIDER_SAVE_RESTORE */
  371. " push {r3, r14} \n"
  372. " cpsid i \n"
  373. " bl vTaskSwitchContext \n"
  374. " cpsie i \n"
  375. " pop {r2, r3} \n"/* lr goes in r3. r2 now holds tcb pointer. */
  376. " \n"
  377. " ldr r1, [r2] \n"
  378. " ldr r0, [r1] \n"/* The first item in pxCurrentTCB is the task top of stack. */
  379. " adds r0, r0, #16 \n"/* Move to the high registers. */
  380. " ldmia r0!, {r4-r7} \n"/* Pop the high registers. */
  381. " mov r8, r4 \n"
  382. " mov r9, r5 \n"
  383. " mov r10, r6 \n"
  384. " mov r11, r7 \n"
  385. " \n"
  386. " msr psp, r0 \n"/* Remember the new top of stack for the task. */
  387. " \n"
  388. #if portUSE_DIVIDER_SAVE_RESTORE
  389. " movs r2, #0xd \n"/* Pop the divider state. */
  390. " lsls r2, #28 \n"
  391. " subs r0, r0, #48 \n"/* Go back for the divider state */
  392. " ldmia r0!, {r4-r7} \n"/* Pop the divider state. */
  393. /* Note always restore via SIO_DIV_UDIVI*, because we will overwrite the
  394. * results stopping the calculation anyway, however the sign of results
  395. * is adjusted by the h/w at read time based on whether the last started
  396. * division was signed and the inputs' signs differed */
  397. " str r4, [r2, #0x60] \n"/* SIO_DIV_UDIVIDEND_OFFSET */
  398. " str r5, [r2, #0x64] \n"/* SIO_DIV_UDIVISOR_OFFSET */
  399. " str r6, [r2, #0x74] \n"/* SIO_DIV_REMAINDER_OFFSET */
  400. " str r7, [r2, #0x70] \n"/* SIO_DIV_QUOTIENT_OFFSET */
  401. #else
  402. " subs r0, r0, #32 \n"/* Go back for the low registers that are not automatically restored. */
  403. #endif /* portUSE_DIVIDER_SAVE_RESTORE */
  404. " ldmia r0!, {r4-r7} \n"/* Pop low registers. */
  405. " \n"
  406. " bx r3 \n"
  407. );
  408. }
  409. /*-----------------------------------------------------------*/
  410. void xPortSysTickHandler( void )
  411. {
  412. uint32_t ulPreviousMask;
  413. ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
  414. {
  415. /* Increment the RTOS tick. */
  416. if( xTaskIncrementTick() != pdFALSE )
  417. {
  418. /* Pend a context switch. */
  419. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  420. }
  421. }
  422. portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
  423. }
  424. /*-----------------------------------------------------------*/
  425. /*
  426. * Setup the systick timer to generate the tick interrupts at the required
  427. * frequency.
  428. */
  429. __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
  430. {
  431. /* Calculate the constants required to configure the tick interrupt. */
  432. #if ( configUSE_TICKLESS_IDLE == 1 )
  433. {
  434. ulTimerCountsForOneTick = ( clock_get_hz(clk_sys) / configTICK_RATE_HZ );
  435. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  436. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;
  437. }
  438. #endif /* configUSE_TICKLESS_IDLE */
  439. /* Stop and reset the SysTick. */
  440. portNVIC_SYSTICK_CTRL_REG = 0UL;
  441. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  442. /* Configure SysTick to interrupt at the requested rate. */
  443. portNVIC_SYSTICK_LOAD_REG = ( clock_get_hz( clk_sys ) / configTICK_RATE_HZ ) - 1UL;
  444. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  445. }
  446. /*-----------------------------------------------------------*/
  447. #if ( configUSE_TICKLESS_IDLE == 1 )
  448. __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  449. {
  450. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
  451. TickType_t xModifiableIdleTime;
  452. /* Make sure the SysTick reload value does not overflow the counter. */
  453. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  454. {
  455. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  456. }
  457. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  458. * is accounted for as best it can be, but using the tickless mode will
  459. * inevitably result in some tiny drift of the time maintained by the
  460. * kernel with respect to calendar time. */
  461. portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
  462. /* Calculate the reload value required to wait xExpectedIdleTime
  463. * tick periods. -1 is used because this code will execute part way
  464. * through one of the tick periods. */
  465. ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  466. if( ulReloadValue > ulStoppedTimerCompensation )
  467. {
  468. ulReloadValue -= ulStoppedTimerCompensation;
  469. }
  470. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  471. * method as that will mask interrupts that should exit sleep mode. */
  472. __asm volatile ( "cpsid i" ::: "memory" );
  473. __asm volatile ( "dsb" );
  474. __asm volatile ( "isb" );
  475. /* If a context switch is pending or a task is waiting for the scheduler
  476. * to be unsuspended then abandon the low power entry. */
  477. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  478. {
  479. /* Restart from whatever is left in the count register to complete
  480. * this tick period. */
  481. portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  482. /* Restart SysTick. */
  483. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  484. /* Reset the reload register to the value required for normal tick
  485. * periods. */
  486. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  487. /* Re-enable interrupts - see comments above the cpsid instruction()
  488. * above. */
  489. __asm volatile ( "cpsie i" ::: "memory" );
  490. }
  491. else
  492. {
  493. /* Set the new reload value. */
  494. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  495. /* Clear the SysTick count flag and set the count value back to
  496. * zero. */
  497. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  498. /* Restart SysTick. */
  499. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  500. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  501. * set its parameter to 0 to indicate that its implementation contains
  502. * its own wait for interrupt or wait for event instruction, and so wfi
  503. * should not be executed again. However, the original expected idle
  504. * time variable must remain unmodified, so a copy is taken. */
  505. xModifiableIdleTime = xExpectedIdleTime;
  506. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  507. if( xModifiableIdleTime > 0 )
  508. {
  509. __asm volatile ( "dsb" ::: "memory" );
  510. __asm volatile ( "wfi" );
  511. __asm volatile ( "isb" );
  512. }
  513. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  514. /* Re-enable interrupts to allow the interrupt that brought the MCU
  515. * out of sleep mode to execute immediately. see comments above
  516. * __disable_interrupt() call above. */
  517. __asm volatile ( "cpsie i" ::: "memory" );
  518. __asm volatile ( "dsb" );
  519. __asm volatile ( "isb" );
  520. /* Disable interrupts again because the clock is about to be stopped
  521. * and interrupts that execute while the clock is stopped will increase
  522. * any slippage between the time maintained by the RTOS and calendar
  523. * time. */
  524. __asm volatile ( "cpsid i" ::: "memory" );
  525. __asm volatile ( "dsb" );
  526. __asm volatile ( "isb" );
  527. /* Disable the SysTick clock without reading the
  528. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  529. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  530. * the time the SysTick is stopped for is accounted for as best it can
  531. * be, but using the tickless mode will inevitably result in some tiny
  532. * drift of the time maintained by the kernel with respect to calendar
  533. * time*/
  534. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
  535. /* Determine if the SysTick clock has already counted to zero and
  536. * been set back to the current reload value (the reload back being
  537. * correct for the entire expected idle time) or if the SysTick is yet
  538. * to count to zero (in which case an interrupt other than the SysTick
  539. * must have brought the system out of sleep mode). */
  540. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  541. {
  542. uint32_t ulCalculatedLoadValue;
  543. /* The tick interrupt is already pending, and the SysTick count
  544. * reloaded with ulReloadValue. Reset the
  545. * portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
  546. * period. */
  547. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  548. /* Don't allow a tiny value, or values that have somehow
  549. * underflowed because the post sleep hook did something
  550. * that took too long. */
  551. if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  552. {
  553. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  554. }
  555. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  556. /* As the pending tick will be processed as soon as this
  557. * function exits, the tick value maintained by the tick is stepped
  558. * forward by one less than the time spent waiting. */
  559. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  560. }
  561. else
  562. {
  563. /* Something other than the tick interrupt ended the sleep.
  564. * Work out how long the sleep lasted rounded to complete tick
  565. * periods (not the ulReload value which accounted for part
  566. * ticks). */
  567. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
  568. /* How many complete tick periods passed while the processor
  569. * was waiting? */
  570. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  571. /* The reload value is set to whatever fraction of a single tick
  572. * period remains. */
  573. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  574. }
  575. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
  576. * again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
  577. * value. */
  578. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  579. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  580. vTaskStepTick( ulCompleteTickPeriods );
  581. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  582. /* Exit with interrupts enabled. */
  583. __asm volatile ( "cpsie i" ::: "memory" );
  584. }
  585. }
  586. #endif /* configUSE_TICKLESS_IDLE */
  587. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1 ) || ( configSUPPORT_PICO_TIME_INTEROP == 1 )
  588. static TickType_t prvGetTicksToWaitBefore( absolute_time_t t )
  589. {
  590. int64_t xDelay = absolute_time_diff_us(get_absolute_time(), t);
  591. const uint32_t ulTickPeriod = 1000000 / configTICK_RATE_HZ;
  592. xDelay -= ulTickPeriod;
  593. if( xDelay >= ulTickPeriod )
  594. {
  595. return xDelay / ulTickPeriod;
  596. }
  597. return 0;
  598. }
  599. #endif
  600. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1 )
  601. uint32_t ulPortLockGetCurrentOwnerId()
  602. {
  603. if( portIS_FREE_RTOS_CORE())
  604. {
  605. uint32_t exception = __get_current_exception();
  606. if( !exception )
  607. {
  608. return ( uintptr_t ) xTaskGetCurrentTaskHandle();
  609. }
  610. /* Note: since ROM as at 0x00000000, these can't be confused with
  611. * valid task handles (pointers) in RAM */
  612. /* We make all exception handler/core combinations distinct owners */
  613. return get_core_num() + exception * 2;
  614. }
  615. /* Note: since ROM as at 0x00000000, this can't be confused with
  616. * valid task handles (pointers) in RAM */
  617. return get_core_num();
  618. }
  619. static inline EventBits_t prvGetEventGroupBit( spin_lock_t * spinLock )
  620. {
  621. uint32_t ulBit;
  622. #if ( configUSE_16_BIT_TICKS == 1 )
  623. ulBit = 1u << (spin_lock_get_num(spinLock) & 0x7u);
  624. #else
  625. ulBit = 1u << spin_lock_get_num(spinLock);
  626. /* reduce to range 0-24 */
  627. ulBit |= ulBit << 8u;
  628. ulBit >>= 8u;
  629. #endif /* configUSE_16_BIT_TICKS */
  630. return ( EventBits_t ) ulBit;
  631. }
  632. static inline EventBits_t prvGetAllEventGroupBits()
  633. {
  634. #if ( configUSE_16_BIT_TICKS == 1 )
  635. return (EventBits_t) 0xffu;
  636. #else
  637. return ( EventBits_t ) 0xffffffu;
  638. #endif /* configUSE_16_BIT_TICKS */
  639. }
  640. void vPortLockInternalSpinUnlockWithWait( struct lock_core * pxLock, uint32_t ulSave )
  641. {
  642. configASSERT( !portCHECK_IF_IN_ISR() );
  643. // note no need to check LIB_PICO_MULTICORE, as this is always returns true if that is not defined
  644. if( !portIS_FREE_RTOS_CORE() )
  645. {
  646. spin_unlock(pxLock->spin_lock, ulSave );
  647. __wfe();
  648. }
  649. else
  650. {
  651. configASSERT( pxYieldSpinLock == NULL );
  652. // we want to hold the lock until the event bits have been set; since interrupts are currently disabled
  653. // by the spinlock, we can defer until portENABLE_INTERRUPTS is called which is always called when
  654. // the scheduler is unlocked during this call
  655. configASSERT(pxLock->spin_lock);
  656. pxYieldSpinLock = pxLock->spin_lock;
  657. ulYieldSpinLockSaveValue = ulSave;
  658. xEventGroupWaitBits( xEventGroup, prvGetEventGroupBit(pxLock->spin_lock),
  659. pdTRUE, pdFALSE, portMAX_DELAY);
  660. /* sanity check that interrupts were disabled, then re-enabled during the call, which will have
  661. * taken care of the yield */
  662. configASSERT( pxYieldSpinLock == NULL);
  663. }
  664. }
  665. void vPortLockInternalSpinUnlockWithNotify( struct lock_core *pxLock, uint32_t ulSave ) {
  666. EventBits_t uxBits = prvGetEventGroupBit(pxLock->spin_lock );
  667. if (portIS_FREE_RTOS_CORE()) {
  668. #if LIB_PICO_MULTICORE
  669. /* signal an event in case a regular core is waiting */
  670. __sev();
  671. #endif
  672. spin_unlock(pxLock->spin_lock, ulSave );
  673. if( !portCHECK_IF_IN_ISR() )
  674. {
  675. xEventGroupSetBits( xEventGroup, uxBits );
  676. }
  677. else
  678. {
  679. BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  680. xEventGroupSetBitsFromISR( xEventGroup, uxBits, &xHigherPriorityTaskWoken );
  681. portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
  682. }
  683. }
  684. else
  685. {
  686. __sev();
  687. #if ( LIB_PICO_MULTICORE == 1)
  688. /* We could sent the bits across the FIFO which would have required us to block here if the FIFO was full,
  689. * or we could have just set all bits on the other side, however it seems reasonable instead to take
  690. * the hit of another spin lock to protect an accurate bit set. */
  691. if( pxCrossCoreSpinLock != pxLock->spin_lock )
  692. {
  693. spin_lock_unsafe_blocking(pxCrossCoreSpinLock);
  694. uxCrossCoreEventBits |= uxBits;
  695. spin_unlock_unsafe(pxCrossCoreSpinLock);
  696. }
  697. else
  698. {
  699. uxCrossCoreEventBits |= uxBits;
  700. }
  701. /* This causes fifo irq on the other (FreeRTOS) core which will do the set the event bits */
  702. sio_hw->fifo_wr = 0;
  703. #endif /* LIB_PICO_MULTICORE */
  704. spin_unlock(pxLock->spin_lock, ulSave);
  705. }
  706. }
  707. bool xPortLockInternalSpinUnlockWithBestEffortWaitOrTimeout( struct lock_core * pxLock, uint32_t ulSave, absolute_time_t uxUntil )
  708. {
  709. configASSERT( !portCHECK_IF_IN_ISR() );
  710. // note no need to check LIB_PICO_MULTICORE, as this is always returns true if that is not defined
  711. if( !portIS_FREE_RTOS_CORE() )
  712. {
  713. spin_unlock(pxLock->spin_lock, ulSave);
  714. return best_effort_wfe_or_timeout(uxUntil);
  715. }
  716. else
  717. {
  718. configASSERT( portIS_FREE_RTOS_CORE() );
  719. configASSERT( pxYieldSpinLock == NULL );
  720. TickType_t uxTicksToWait = prvGetTicksToWaitBefore( uxUntil );
  721. if( uxTicksToWait )
  722. {
  723. /* We want to hold the lock until the event bits have been set; since interrupts are currently disabled
  724. * by the spinlock, we can defer until portENABLE_INTERRUPTS is called which is always called when
  725. * the scheduler is unlocked during this call */
  726. configASSERT(pxLock->spin_lock);
  727. pxYieldSpinLock = pxLock->spin_lock;
  728. ulYieldSpinLockSaveValue = ulSave;
  729. xEventGroupWaitBits( xEventGroup,
  730. prvGetEventGroupBit(pxLock->spin_lock), pdTRUE,
  731. pdFALSE, uxTicksToWait );
  732. /* sanity check that interrupts were disabled, then re-enabled during the call, which will have
  733. * taken care of the yield */
  734. configASSERT( pxYieldSpinLock == NULL );
  735. }
  736. else
  737. {
  738. spin_unlock( pxLock->spin_lock, ulSave );
  739. }
  740. if ( time_reached( uxUntil ) )
  741. {
  742. return true;
  743. }
  744. else
  745. {
  746. /* We do not want to hog the core */
  747. portYIELD();
  748. /* We aren't sure if we've reached the timeout yet; the caller will check */
  749. return false;
  750. }
  751. }
  752. }
  753. #if ( configSUPPORT_PICO_SYNC_INTEROP == 1)
  754. /* runs before main */
  755. static void __attribute__((constructor)) prvRuntimeInitializer( void )
  756. {
  757. /* This must be done even before the scheduler is started, as the spin lock
  758. * is used by the overrides of the SDK wait/notify primitives */
  759. #if ( LIB_PICO_MULTICORE == 1 )
  760. pxCrossCoreSpinLock = spin_lock_instance( next_striped_spin_lock_num() );
  761. #endif /* portRUNNING_ON_BOTH_CORES */
  762. /* The event group is not used prior to scheduler init, but is initialized
  763. * here to since it logically belongs with the spin lock */
  764. #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
  765. xEventGroup = xEventGroupCreateStatic(&xStaticEventGroup);
  766. #else
  767. xEventGroup = xEventGroupCreate();
  768. #endif /* configSUPPORT_STATIC_ALLOCATION */
  769. }
  770. #endif
  771. #endif /* configSUPPORT_PICO_SYNC_INTEROP */
  772. #if ( configSUPPORT_PICO_TIME_INTEROP == 1 )
  773. void xPortSyncInternalYieldUntilBefore( absolute_time_t t )
  774. {
  775. TickType_t uxTicksToWait = prvGetTicksToWaitBefore(t);
  776. if( uxTicksToWait )
  777. {
  778. vTaskDelay(uxTicksToWait);
  779. }
  780. }
  781. #endif /* configSUPPORT_PICO_TIME_INTEROP */