port.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. /* Standard includes. */
  29. #include <stdio.h>
  30. /* Scheduler includes. */
  31. #include "FreeRTOS.h"
  32. #include "task.h"
  33. #ifdef __GNUC__
  34. #include "mmsystem.h"
  35. #else
  36. #pragma comment(lib, "winmm.lib")
  37. #endif
  38. #define portMAX_INTERRUPTS ( ( uint32_t ) sizeof( uint32_t ) * 8UL ) /* The number of bits in an uint32_t. */
  39. #define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 )
  40. /* The priorities at which the various components of the simulation execute. */
  41. #define portDELETE_SELF_THREAD_PRIORITY THREAD_PRIORITY_TIME_CRITICAL /* Must be highest. */
  42. #define portSIMULATED_INTERRUPTS_THREAD_PRIORITY THREAD_PRIORITY_TIME_CRITICAL
  43. #define portSIMULATED_TIMER_THREAD_PRIORITY THREAD_PRIORITY_HIGHEST
  44. #define portTASK_THREAD_PRIORITY THREAD_PRIORITY_ABOVE_NORMAL
  45. /*
  46. * Created as a high priority thread, this function uses a timer to simulate
  47. * a tick interrupt being generated on an embedded target. In this Windows
  48. * environment the timer does not achieve anything approaching real time
  49. * performance though.
  50. */
  51. static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );
  52. /*
  53. * Process all the simulated interrupts - each represented by a bit in
  54. * ulPendingInterrupts variable.
  55. */
  56. static void prvProcessSimulatedInterrupts( void );
  57. /*
  58. * Interrupt handlers used by the kernel itself. These are executed from the
  59. * simulated interrupt handler thread.
  60. */
  61. static uint32_t prvProcessYieldInterrupt( void );
  62. static uint32_t prvProcessTickInterrupt( void );
  63. /*
  64. * Exiting a critical section will cause the calling task to block on yield
  65. * event to wait for an interrupt to process if an interrupt was pended while
  66. * inside the critical section. This variable protects against a recursive
  67. * attempt to obtain pvInterruptEventMutex if a critical section is used inside
  68. * an interrupt handler itself.
  69. */
  70. volatile BaseType_t xInsideInterrupt = pdFALSE;
  71. /*
  72. * Called when the process exits to let Windows know the high timer resolution
  73. * is no longer required.
  74. */
  75. static BOOL WINAPI prvEndProcess( DWORD dwCtrlType );
  76. /*-----------------------------------------------------------*/
  77. /* The WIN32 simulator runs each task in a thread. The context switching is
  78. managed by the threads, so the task stack does not have to be managed directly,
  79. although the task stack is still used to hold an xThreadState structure this is
  80. the only thing it will ever hold. The structure indirectly maps the task handle
  81. to a thread handle. */
  82. typedef struct
  83. {
  84. /* Handle of the thread that executes the task. */
  85. void *pvThread;
  86. /* Event used to make sure the thread does not execute past a yield point
  87. between the call to SuspendThread() to suspend the thread and the
  88. asynchronous SuspendThread() operation actually being performed. */
  89. void *pvYieldEvent;
  90. } ThreadState_t;
  91. /* Simulated interrupts waiting to be processed. This is a bit mask where each
  92. bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
  93. static volatile uint32_t ulPendingInterrupts = 0UL;
  94. /* An event used to inform the simulated interrupt processing thread (a high
  95. priority thread that simulated interrupt processing) that an interrupt is
  96. pending. */
  97. static void *pvInterruptEvent = NULL;
  98. /* Mutex used to protect all the simulated interrupt variables that are accessed
  99. by multiple threads. */
  100. static void *pvInterruptEventMutex = NULL;
  101. /* The critical nesting count for the currently executing task. This is
  102. initialised to a non-zero value so interrupts do not become enabled during
  103. the initialisation phase. As each task has its own critical nesting value
  104. ulCriticalNesting will get set to zero when the first task runs. This
  105. initialisation is probably not critical in this simulated environment as the
  106. simulated interrupt handlers do not get created until the FreeRTOS scheduler is
  107. started anyway. */
  108. static volatile uint32_t ulCriticalNesting = 9999UL;
  109. /* Handlers for all the simulated software interrupts. The first two positions
  110. are used for the Yield and Tick interrupts so are handled slightly differently,
  111. all the other interrupts can be user defined. */
  112. static uint32_t (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
  113. /* Pointer to the TCB of the currently executing task. */
  114. extern void * volatile pxCurrentTCB;
  115. /* Used to ensure nothing is processed during the startup sequence. */
  116. static BaseType_t xPortRunning = pdFALSE;
  117. /*-----------------------------------------------------------*/
  118. static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
  119. {
  120. TickType_t xMinimumWindowsBlockTime;
  121. TIMECAPS xTimeCaps;
  122. /* Set the timer resolution to the maximum possible. */
  123. if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
  124. {
  125. xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin;
  126. timeBeginPeriod( xTimeCaps.wPeriodMin );
  127. /* Register an exit handler so the timeBeginPeriod() function can be
  128. matched with a timeEndPeriod() when the application exits. */
  129. SetConsoleCtrlHandler( prvEndProcess, TRUE );
  130. }
  131. else
  132. {
  133. xMinimumWindowsBlockTime = ( TickType_t ) 20;
  134. }
  135. /* Just to prevent compiler warnings. */
  136. ( void ) lpParameter;
  137. for( ;; )
  138. {
  139. /* Wait until the timer expires and we can access the simulated interrupt
  140. variables. *NOTE* this is not a 'real time' way of generating tick
  141. events as the next wake time should be relative to the previous wake
  142. time, not the time that Sleep() is called. It is done this way to
  143. prevent overruns in this very non real time simulated/emulated
  144. environment. */
  145. if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime )
  146. {
  147. Sleep( xMinimumWindowsBlockTime );
  148. }
  149. else
  150. {
  151. Sleep( portTICK_PERIOD_MS );
  152. }
  153. configASSERT( xPortRunning );
  154. /* Can't proceed if in a critical section as pvInterruptEventMutex won't
  155. be available. */
  156. WaitForSingleObject( pvInterruptEventMutex, INFINITE );
  157. /* The timer has expired, generate the simulated tick event. */
  158. ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
  159. /* The interrupt is now pending - notify the simulated interrupt
  160. handler thread. Must be outside of a critical section to get here so
  161. the handler thread can execute immediately pvInterruptEventMutex is
  162. released. */
  163. configASSERT( ulCriticalNesting == 0UL );
  164. SetEvent( pvInterruptEvent );
  165. /* Give back the mutex so the simulated interrupt handler unblocks
  166. and can access the interrupt handler variables. */
  167. ReleaseMutex( pvInterruptEventMutex );
  168. }
  169. #ifdef __GNUC__
  170. /* Should never reach here - MingW complains if you leave this line out,
  171. MSVC complains if you put it in. */
  172. return 0;
  173. #endif
  174. }
  175. /*-----------------------------------------------------------*/
  176. static BOOL WINAPI prvEndProcess( DWORD dwCtrlType )
  177. {
  178. TIMECAPS xTimeCaps;
  179. ( void ) dwCtrlType;
  180. if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
  181. {
  182. /* Match the call to timeBeginPeriod( xTimeCaps.wPeriodMin ) made when
  183. the process started with a timeEndPeriod() as the process exits. */
  184. timeEndPeriod( xTimeCaps.wPeriodMin );
  185. }
  186. return pdFALSE;
  187. }
  188. /*-----------------------------------------------------------*/
  189. StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
  190. {
  191. ThreadState_t *pxThreadState = NULL;
  192. int8_t *pcTopOfStack = ( int8_t * ) pxTopOfStack;
  193. const SIZE_T xStackSize = 1024; /* Set the size to a small number which will get rounded up to the minimum possible. */
  194. /* In this simulated case a stack is not initialised, but instead a thread
  195. is created that will execute the task being created. The thread handles
  196. the context switching itself. The ThreadState_t object is placed onto
  197. the stack that was created for the task - so the stack buffer is still
  198. used, just not in the conventional way. It will not be used for anything
  199. other than holding this structure. */
  200. pxThreadState = ( ThreadState_t * ) ( pcTopOfStack - sizeof( ThreadState_t ) );
  201. /* Create the event used to prevent the thread from executing past its yield
  202. point if the SuspendThread() call that suspends the thread does not take
  203. effect immediately (it is an asynchronous call). */
  204. pxThreadState->pvYieldEvent = CreateEvent( NULL, /* Default security attributes. */
  205. FALSE, /* Auto reset. */
  206. FALSE, /* Start not signalled. */
  207. NULL );/* No name. */
  208. /* Create the thread itself. */
  209. pxThreadState->pvThread = CreateThread( NULL, xStackSize, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, NULL );
  210. configASSERT( pxThreadState->pvThread ); /* See comment where TerminateThread() is called. */
  211. SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );
  212. SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
  213. SetThreadPriority( pxThreadState->pvThread, portTASK_THREAD_PRIORITY );
  214. return ( StackType_t * ) pxThreadState;
  215. }
  216. /*-----------------------------------------------------------*/
  217. BaseType_t xPortStartScheduler( void )
  218. {
  219. void *pvHandle = NULL;
  220. int32_t lSuccess;
  221. ThreadState_t *pxThreadState = NULL;
  222. SYSTEM_INFO xSystemInfo;
  223. /* This port runs windows threads with extremely high priority. All the
  224. threads execute on the same core - to prevent locking up the host only start
  225. if the host has multiple cores. */
  226. GetSystemInfo( &xSystemInfo );
  227. if( xSystemInfo.dwNumberOfProcessors <= 1 )
  228. {
  229. printf( "This version of the FreeRTOS Windows port can only be used on multi-core hosts.\r\n" );
  230. lSuccess = pdFAIL;
  231. }
  232. else
  233. {
  234. lSuccess = pdPASS;
  235. /* The highest priority class is used to [try to] prevent other Windows
  236. activity interfering with FreeRTOS timing too much. */
  237. if( SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS ) == 0 )
  238. {
  239. printf( "SetPriorityClass() failed\r\n" );
  240. }
  241. /* Install the interrupt handlers used by the scheduler itself. */
  242. vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );
  243. vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );
  244. /* Create the events and mutexes that are used to synchronise all the
  245. threads. */
  246. pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
  247. pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  248. if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )
  249. {
  250. lSuccess = pdFAIL;
  251. }
  252. /* Set the priority of this thread such that it is above the priority of
  253. the threads that run tasks. This higher priority is required to ensure
  254. simulated interrupts take priority over tasks. */
  255. pvHandle = GetCurrentThread();
  256. if( pvHandle == NULL )
  257. {
  258. lSuccess = pdFAIL;
  259. }
  260. }
  261. if( lSuccess == pdPASS )
  262. {
  263. if( SetThreadPriority( pvHandle, portSIMULATED_INTERRUPTS_THREAD_PRIORITY ) == 0 )
  264. {
  265. lSuccess = pdFAIL;
  266. }
  267. SetThreadPriorityBoost( pvHandle, TRUE );
  268. SetThreadAffinityMask( pvHandle, 0x01 );
  269. }
  270. if( lSuccess == pdPASS )
  271. {
  272. /* Start the thread that simulates the timer peripheral to generate
  273. tick interrupts. The priority is set below that of the simulated
  274. interrupt handler so the interrupt event mutex is used for the
  275. handshake / overrun protection. */
  276. pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, CREATE_SUSPENDED, NULL );
  277. if( pvHandle != NULL )
  278. {
  279. SetThreadPriority( pvHandle, portSIMULATED_TIMER_THREAD_PRIORITY );
  280. SetThreadPriorityBoost( pvHandle, TRUE );
  281. SetThreadAffinityMask( pvHandle, 0x01 );
  282. ResumeThread( pvHandle );
  283. }
  284. /* Start the highest priority task by obtaining its associated thread
  285. state structure, in which is stored the thread handle. */
  286. pxThreadState = ( ThreadState_t * ) *( ( size_t * ) pxCurrentTCB );
  287. ulCriticalNesting = portNO_CRITICAL_NESTING;
  288. /* Start the first task. */
  289. ResumeThread( pxThreadState->pvThread );
  290. /* Handle all simulated interrupts - including yield requests and
  291. simulated ticks. */
  292. prvProcessSimulatedInterrupts();
  293. }
  294. /* Would not expect to return from prvProcessSimulatedInterrupts(), so should
  295. not get here. */
  296. return 0;
  297. }
  298. /*-----------------------------------------------------------*/
  299. static uint32_t prvProcessYieldInterrupt( void )
  300. {
  301. /* Always return true as this is a yield. */
  302. return pdTRUE;
  303. }
  304. /*-----------------------------------------------------------*/
  305. static uint32_t prvProcessTickInterrupt( void )
  306. {
  307. uint32_t ulSwitchRequired;
  308. /* Process the tick itself. */
  309. configASSERT( xPortRunning );
  310. ulSwitchRequired = ( uint32_t ) xTaskIncrementTick();
  311. return ulSwitchRequired;
  312. }
  313. /*-----------------------------------------------------------*/
  314. static void prvProcessSimulatedInterrupts( void )
  315. {
  316. uint32_t ulSwitchRequired, i;
  317. ThreadState_t *pxThreadState;
  318. void *pvObjectList[ 2 ];
  319. CONTEXT xContext;
  320. /* Going to block on the mutex that ensured exclusive access to the simulated
  321. interrupt objects, and the event that signals that a simulated interrupt
  322. should be processed. */
  323. pvObjectList[ 0 ] = pvInterruptEventMutex;
  324. pvObjectList[ 1 ] = pvInterruptEvent;
  325. /* Create a pending tick to ensure the first task is started as soon as
  326. this thread pends. */
  327. ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
  328. SetEvent( pvInterruptEvent );
  329. xPortRunning = pdTRUE;
  330. for(;;)
  331. {
  332. xInsideInterrupt = pdFALSE;
  333. WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
  334. /* Cannot be in a critical section to get here. Tasks that exit a
  335. critical section will block on a yield mutex to wait for an interrupt to
  336. process if an interrupt was set pending while the task was inside the
  337. critical section. xInsideInterrupt prevents interrupts that contain
  338. critical sections from doing the same. */
  339. xInsideInterrupt = pdTRUE;
  340. /* Used to indicate whether the simulated interrupt processing has
  341. necessitated a context switch to another task/thread. */
  342. ulSwitchRequired = pdFALSE;
  343. /* For each interrupt we are interested in processing, each of which is
  344. represented by a bit in the 32bit ulPendingInterrupts variable. */
  345. for( i = 0; i < portMAX_INTERRUPTS; i++ )
  346. {
  347. /* Is the simulated interrupt pending? */
  348. if( ( ulPendingInterrupts & ( 1UL << i ) ) != 0 )
  349. {
  350. /* Is a handler installed? */
  351. if( ulIsrHandler[ i ] != NULL )
  352. {
  353. /* Run the actual handler. Handlers return pdTRUE if they
  354. necessitate a context switch. */
  355. if( ulIsrHandler[ i ]() != pdFALSE )
  356. {
  357. /* A bit mask is used purely to help debugging. */
  358. ulSwitchRequired |= ( 1 << i );
  359. }
  360. }
  361. /* Clear the interrupt pending bit. */
  362. ulPendingInterrupts &= ~( 1UL << i );
  363. }
  364. }
  365. if( ulSwitchRequired != pdFALSE )
  366. {
  367. void *pvOldCurrentTCB;
  368. pvOldCurrentTCB = pxCurrentTCB;
  369. /* Select the next task to run. */
  370. vTaskSwitchContext();
  371. /* If the task selected to enter the running state is not the task
  372. that is already in the running state. */
  373. if( pvOldCurrentTCB != pxCurrentTCB )
  374. {
  375. /* Suspend the old thread. In the cases where the (simulated)
  376. interrupt is asynchronous (tick event swapping a task out rather
  377. than a task blocking or yielding) it doesn't matter if the
  378. 'suspend' operation doesn't take effect immediately - if it
  379. doesn't it would just be like the interrupt occurring slightly
  380. later. In cases where the yield was caused by a task blocking
  381. or yielding then the task will block on a yield event after the
  382. yield operation in case the 'suspend' operation doesn't take
  383. effect immediately. */
  384. pxThreadState = ( ThreadState_t *) *( ( size_t * ) pvOldCurrentTCB );
  385. SuspendThread( pxThreadState->pvThread );
  386. /* Ensure the thread is actually suspended by performing a
  387. synchronous operation that can only complete when the thread is
  388. actually suspended. The below code asks for dummy register
  389. data. Experimentation shows that these two lines don't appear
  390. to do anything now, but according to
  391. https://devblogs.microsoft.com/oldnewthing/20150205-00/?p=44743
  392. they do - so as they do not harm (slight run-time hit). */
  393. xContext.ContextFlags = CONTEXT_INTEGER;
  394. ( void ) GetThreadContext( pxThreadState->pvThread, &xContext );
  395. /* Obtain the state of the task now selected to enter the
  396. Running state. */
  397. pxThreadState = ( ThreadState_t * ) ( *( size_t *) pxCurrentTCB );
  398. /* pxThreadState->pvThread can be NULL if the task deleted
  399. itself - but a deleted task should never be resumed here. */
  400. configASSERT( pxThreadState->pvThread != NULL );
  401. ResumeThread( pxThreadState->pvThread );
  402. }
  403. }
  404. /* If the thread that is about to be resumed stopped running
  405. because it yielded then it will wait on an event when it resumed
  406. (to ensure it does not continue running after the call to
  407. SuspendThread() above as SuspendThread() is asynchronous).
  408. Signal the event to ensure the thread can proceed now it is
  409. valid for it to do so. Signaling the event is benign in the case that
  410. the task was switched out asynchronously by an interrupt as the event
  411. is reset before the task blocks on it. */
  412. pxThreadState = ( ThreadState_t * ) ( *( size_t *) pxCurrentTCB );
  413. SetEvent( pxThreadState->pvYieldEvent );
  414. ReleaseMutex( pvInterruptEventMutex );
  415. }
  416. }
  417. /*-----------------------------------------------------------*/
  418. void vPortDeleteThread( void *pvTaskToDelete )
  419. {
  420. ThreadState_t *pxThreadState;
  421. uint32_t ulErrorCode;
  422. /* Remove compiler warnings if configASSERT() is not defined. */
  423. ( void ) ulErrorCode;
  424. /* Find the handle of the thread being deleted. */
  425. pxThreadState = ( ThreadState_t * ) ( *( size_t *) pvTaskToDelete );
  426. /* Check that the thread is still valid, it might have been closed by
  427. vPortCloseRunningThread() - which will be the case if the task associated
  428. with the thread originally deleted itself rather than being deleted by a
  429. different task. */
  430. if( pxThreadState->pvThread != NULL )
  431. {
  432. WaitForSingleObject( pvInterruptEventMutex, INFINITE );
  433. /* !!! This is not a nice way to terminate a thread, and will eventually
  434. result in resources being depleted if tasks frequently delete other
  435. tasks (rather than deleting themselves) as the task stacks will not be
  436. freed. */
  437. ulErrorCode = TerminateThread( pxThreadState->pvThread, 0 );
  438. configASSERT( ulErrorCode );
  439. ulErrorCode = CloseHandle( pxThreadState->pvThread );
  440. configASSERT( ulErrorCode );
  441. ReleaseMutex( pvInterruptEventMutex );
  442. }
  443. }
  444. /*-----------------------------------------------------------*/
  445. void vPortCloseRunningThread( void *pvTaskToDelete, volatile BaseType_t *pxPendYield )
  446. {
  447. ThreadState_t *pxThreadState;
  448. void *pvThread;
  449. uint32_t ulErrorCode;
  450. /* Remove compiler warnings if configASSERT() is not defined. */
  451. ( void ) ulErrorCode;
  452. /* Find the handle of the thread being deleted. */
  453. pxThreadState = ( ThreadState_t * ) ( *( size_t *) pvTaskToDelete );
  454. pvThread = pxThreadState->pvThread;
  455. /* Raise the Windows priority of the thread to ensure the FreeRTOS scheduler
  456. does not run and swap it out before it is closed. If that were to happen
  457. the thread would never run again and effectively be a thread handle and
  458. memory leak. */
  459. SetThreadPriority( pvThread, portDELETE_SELF_THREAD_PRIORITY );
  460. /* This function will not return, therefore a yield is set as pending to
  461. ensure a context switch occurs away from this thread on the next tick. */
  462. *pxPendYield = pdTRUE;
  463. /* Mark the thread associated with this task as invalid so
  464. vPortDeleteThread() does not try to terminate it. */
  465. pxThreadState->pvThread = NULL;
  466. /* Close the thread. */
  467. ulErrorCode = CloseHandle( pvThread );
  468. configASSERT( ulErrorCode );
  469. /* This is called from a critical section, which must be exited before the
  470. thread stops. */
  471. taskEXIT_CRITICAL();
  472. CloseHandle( pxThreadState->pvYieldEvent );
  473. ExitThread( 0 );
  474. }
  475. /*-----------------------------------------------------------*/
  476. void vPortEndScheduler( void )
  477. {
  478. exit( 0 );
  479. }
  480. /*-----------------------------------------------------------*/
  481. void vPortGenerateSimulatedInterrupt( uint32_t ulInterruptNumber )
  482. {
  483. ThreadState_t *pxThreadState = ( ThreadState_t *) *( ( size_t * ) pxCurrentTCB );
  484. configASSERT( xPortRunning );
  485. if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
  486. {
  487. WaitForSingleObject( pvInterruptEventMutex, INFINITE );
  488. ulPendingInterrupts |= ( 1 << ulInterruptNumber );
  489. /* The simulated interrupt is now held pending, but don't actually
  490. process it yet if this call is within a critical section. It is
  491. possible for this to be in a critical section as calls to wait for
  492. mutexes are accumulative. If in a critical section then the event
  493. will get set when the critical section nesting count is wound back
  494. down to zero. */
  495. if( ulCriticalNesting == portNO_CRITICAL_NESTING )
  496. {
  497. SetEvent( pvInterruptEvent );
  498. /* Going to wait for an event - make sure the event is not already
  499. signaled. */
  500. ResetEvent( pxThreadState->pvYieldEvent );
  501. }
  502. ReleaseMutex( pvInterruptEventMutex );
  503. if( ulCriticalNesting == portNO_CRITICAL_NESTING )
  504. {
  505. /* An interrupt was pended so ensure to block to allow it to
  506. execute. In most cases the (simulated) interrupt will have
  507. executed before the next line is reached - so this is just to make
  508. sure. */
  509. WaitForSingleObject( pxThreadState->pvYieldEvent, INFINITE );
  510. }
  511. }
  512. }
  513. /*-----------------------------------------------------------*/
  514. void vPortSetInterruptHandler( uint32_t ulInterruptNumber, uint32_t (*pvHandler)( void ) )
  515. {
  516. if( ulInterruptNumber < portMAX_INTERRUPTS )
  517. {
  518. if( pvInterruptEventMutex != NULL )
  519. {
  520. WaitForSingleObject( pvInterruptEventMutex, INFINITE );
  521. ulIsrHandler[ ulInterruptNumber ] = pvHandler;
  522. ReleaseMutex( pvInterruptEventMutex );
  523. }
  524. else
  525. {
  526. ulIsrHandler[ ulInterruptNumber ] = pvHandler;
  527. }
  528. }
  529. }
  530. /*-----------------------------------------------------------*/
  531. void vPortEnterCritical( void )
  532. {
  533. if( xPortRunning == pdTRUE )
  534. {
  535. /* The interrupt event mutex is held for the entire critical section,
  536. effectively disabling (simulated) interrupts. */
  537. WaitForSingleObject( pvInterruptEventMutex, INFINITE );
  538. }
  539. ulCriticalNesting++;
  540. }
  541. /*-----------------------------------------------------------*/
  542. void vPortExitCritical( void )
  543. {
  544. int32_t lMutexNeedsReleasing;
  545. /* The interrupt event mutex should already be held by this thread as it was
  546. obtained on entry to the critical section. */
  547. lMutexNeedsReleasing = pdTRUE;
  548. if( ulCriticalNesting > portNO_CRITICAL_NESTING )
  549. {
  550. ulCriticalNesting--;
  551. /* Don't need to wait for any pending interrupts to execute if the
  552. critical section was exited from inside an interrupt. */
  553. if( ( ulCriticalNesting == portNO_CRITICAL_NESTING ) && ( xInsideInterrupt == pdFALSE ) )
  554. {
  555. /* Were any interrupts set to pending while interrupts were
  556. (simulated) disabled? */
  557. if( ulPendingInterrupts != 0UL )
  558. {
  559. ThreadState_t *pxThreadState = ( ThreadState_t *) *( ( size_t * ) pxCurrentTCB );
  560. configASSERT( xPortRunning );
  561. /* The interrupt won't actually executed until
  562. pvInterruptEventMutex is released as it waits on both
  563. pvInterruptEventMutex and pvInterruptEvent.
  564. pvInterruptEvent is only set when the simulated
  565. interrupt is pended if the interrupt is pended
  566. from outside a critical section - hence it is set
  567. here. */
  568. SetEvent( pvInterruptEvent );
  569. /* The calling task is going to wait for an event to ensure the
  570. interrupt that is pending executes immediately after the
  571. critical section is exited - so make sure the event is not
  572. already signaled. */
  573. ResetEvent( pxThreadState->pvYieldEvent );
  574. /* Mutex will be released now so the (simulated) interrupt can
  575. execute, so does not require releasing on function exit. */
  576. lMutexNeedsReleasing = pdFALSE;
  577. ReleaseMutex( pvInterruptEventMutex );
  578. WaitForSingleObject( pxThreadState->pvYieldEvent, INFINITE );
  579. }
  580. }
  581. }
  582. if( pvInterruptEventMutex != NULL )
  583. {
  584. if( lMutexNeedsReleasing == pdTRUE )
  585. {
  586. configASSERT( xPortRunning );
  587. ReleaseMutex( pvInterruptEventMutex );
  588. }
  589. }
  590. }
  591. /*-----------------------------------------------------------*/