2 * FreeRTOS Kernel V10.0.1
\r
3 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
\r
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
\r
6 * this software and associated documentation files (the "Software"), to deal in
\r
7 * the Software without restriction, including without limitation the rights to
\r
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
\r
9 * the Software, and to permit persons to whom the Software is furnished to do so,
\r
10 * subject to the following conditions:
\r
12 * The above copyright notice and this permission notice shall be included in all
\r
13 * copies or substantial portions of the Software.
\r
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
\r
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
\r
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
\r
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
\r
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
\r
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
22 * http://www.FreeRTOS.org
\r
23 * http://aws.amazon.com/freertos
\r
25 * 1 tab == 4 spaces!
\r
28 /* Standard includes. */
\r
31 /* Scheduler includes. */
\r
32 #include "FreeRTOS.h"
\r
36 #include "mmsystem.h"
\r
38 #pragma comment(lib, "winmm.lib")
\r
41 #define portMAX_INTERRUPTS ( ( uint32_t ) sizeof( uint32_t ) * 8UL ) /* The number of bits in an uint32_t. */
\r
42 #define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 )
\r
44 /* The priorities at which the various components of the simulation execute. */
\r
45 #define portDELETE_SELF_THREAD_PRIORITY THREAD_PRIORITY_TIME_CRITICAL /* Must be highest. */
\r
46 #define portSIMULATED_INTERRUPTS_THREAD_PRIORITY THREAD_PRIORITY_TIME_CRITICAL
\r
47 #define portSIMULATED_TIMER_THREAD_PRIORITY THREAD_PRIORITY_HIGHEST
\r
48 #define portTASK_THREAD_PRIORITY THREAD_PRIORITY_ABOVE_NORMAL
\r
51 * Created as a high priority thread, this function uses a timer to simulate
\r
52 * a tick interrupt being generated on an embedded target. In this Windows
\r
53 * environment the timer does not achieve anything approaching real time
\r
54 * performance though.
\r
56 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );
\r
59 * Process all the simulated interrupts - each represented by a bit in
\r
60 * ulPendingInterrupts variable.
\r
62 static void prvProcessSimulatedInterrupts( void );
\r
65 * Interrupt handlers used by the kernel itself. These are executed from the
\r
66 * simulated interrupt handler thread.
\r
68 static uint32_t prvProcessYieldInterrupt( void );
\r
69 static uint32_t prvProcessTickInterrupt( void );
\r
72 * Called when the process exits to let Windows know the high timer resolution
\r
73 * is no longer required.
\r
75 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType );
\r
77 /*-----------------------------------------------------------*/
\r
79 /* The WIN32 simulator runs each task in a thread. The context switching is
\r
80 managed by the threads, so the task stack does not have to be managed directly,
\r
81 although the task stack is still used to hold an xThreadState structure this is
\r
82 the only thing it will ever hold. The structure indirectly maps the task handle
\r
83 to a thread handle. */
\r
86 /* Handle of the thread that executes the task. */
\r
91 /* Simulated interrupts waiting to be processed. This is a bit mask where each
\r
92 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
\r
93 static volatile uint32_t ulPendingInterrupts = 0UL;
\r
95 /* An event used to inform the simulated interrupt processing thread (a high
\r
96 priority thread that simulated interrupt processing) that an interrupt is
\r
98 static void *pvInterruptEvent = NULL;
\r
100 /* Mutex used to protect all the simulated interrupt variables that are accessed
\r
101 by multiple threads. */
\r
102 static void *pvInterruptEventMutex = NULL;
\r
104 /* The critical nesting count for the currently executing task. This is
\r
105 initialised to a non-zero value so interrupts do not become enabled during
\r
106 the initialisation phase. As each task has its own critical nesting value
\r
107 ulCriticalNesting will get set to zero when the first task runs. This
\r
108 initialisation is probably not critical in this simulated environment as the
\r
109 simulated interrupt handlers do not get created until the FreeRTOS scheduler is
\r
111 static uint32_t ulCriticalNesting = 9999UL;
\r
113 /* Handlers for all the simulated software interrupts. The first two positions
\r
114 are used for the Yield and Tick interrupts so are handled slightly differently,
\r
115 all the other interrupts can be user defined. */
\r
116 static uint32_t (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
\r
118 /* Pointer to the TCB of the currently executing task. */
\r
119 extern void *pxCurrentTCB;
\r
121 /* Used to ensure nothing is processed during the startup sequence. */
\r
122 static BaseType_t xPortRunning = pdFALSE;
\r
124 /*-----------------------------------------------------------*/
\r
126 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
\r
128 TickType_t xMinimumWindowsBlockTime;
\r
129 TIMECAPS xTimeCaps;
\r
131 /* Set the timer resolution to the maximum possible. */
\r
132 if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
\r
134 xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin;
\r
135 timeBeginPeriod( xTimeCaps.wPeriodMin );
\r
137 /* Register an exit handler so the timeBeginPeriod() function can be
\r
138 matched with a timeEndPeriod() when the application exits. */
\r
139 SetConsoleCtrlHandler( prvEndProcess, TRUE );
\r
143 xMinimumWindowsBlockTime = ( TickType_t ) 20;
\r
146 /* Just to prevent compiler warnings. */
\r
147 ( void ) lpParameter;
\r
151 /* Wait until the timer expires and we can access the simulated interrupt
\r
152 variables. *NOTE* this is not a 'real time' way of generating tick
\r
153 events as the next wake time should be relative to the previous wake
\r
154 time, not the time that Sleep() is called. It is done this way to
\r
155 prevent overruns in this very non real time simulated/emulated
\r
157 if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime )
\r
159 Sleep( xMinimumWindowsBlockTime );
\r
163 Sleep( portTICK_PERIOD_MS );
\r
166 configASSERT( xPortRunning );
\r
168 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
170 /* The timer has expired, generate the simulated tick event. */
\r
171 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
173 /* The interrupt is now pending - notify the simulated interrupt
\r
175 if( ulCriticalNesting == 0 )
\r
177 SetEvent( pvInterruptEvent );
\r
180 /* Give back the mutex so the simulated interrupt handler unblocks
\r
181 and can access the interrupt handler variables. */
\r
182 ReleaseMutex( pvInterruptEventMutex );
\r
186 /* Should never reach here - MingW complains if you leave this line out,
\r
187 MSVC complains if you put it in. */
\r
191 /*-----------------------------------------------------------*/
\r
193 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType )
\r
195 TIMECAPS xTimeCaps;
\r
197 ( void ) dwCtrlType;
\r
199 if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
\r
201 /* Match the call to timeBeginPeriod( xTimeCaps.wPeriodMin ) made when
\r
202 the process started with a timeEndPeriod() as the process exits. */
\r
203 timeEndPeriod( xTimeCaps.wPeriodMin );
\r
208 /*-----------------------------------------------------------*/
\r
210 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
\r
212 xThreadState *pxThreadState = NULL;
\r
213 int8_t *pcTopOfStack = ( int8_t * ) pxTopOfStack;
\r
214 const SIZE_T xStackSize = 1024; /* Set the size to a small number which will get rounded up to the minimum possible. */
\r
216 /* In this simulated case a stack is not initialised, but instead a thread
\r
217 is created that will execute the task being created. The thread handles
\r
218 the context switching itself. The xThreadState object is placed onto
\r
219 the stack that was created for the task - so the stack buffer is still
\r
220 used, just not in the conventional way. It will not be used for anything
\r
221 other than holding this structure. */
\r
222 pxThreadState = ( xThreadState * ) ( pcTopOfStack - sizeof( xThreadState ) );
\r
224 /* Create the thread itself. */
\r
225 pxThreadState->pvThread = CreateThread( NULL, xStackSize, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, NULL );
\r
226 configASSERT( pxThreadState->pvThread ); /* See comment where TerminateThread() is called. */
\r
227 SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );
\r
228 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
229 SetThreadPriority( pxThreadState->pvThread, portTASK_THREAD_PRIORITY );
\r
231 return ( StackType_t * ) pxThreadState;
\r
233 /*-----------------------------------------------------------*/
\r
235 BaseType_t xPortStartScheduler( void )
\r
237 void *pvHandle = NULL;
\r
239 xThreadState *pxThreadState = NULL;
\r
240 SYSTEM_INFO xSystemInfo;
\r
242 /* This port runs windows threads with extremely high priority. All the
\r
243 threads execute on the same core - to prevent locking up the host only start
\r
244 if the host has multiple cores. */
\r
245 GetSystemInfo( &xSystemInfo );
\r
246 if( xSystemInfo.dwNumberOfProcessors <= 1 )
\r
248 printf( "This version of the FreeRTOS Windows port can only be used on multi-core hosts.\r\n" );
\r
255 /* The highest priority class is used to [try to] prevent other Windows
\r
256 activity interfering with FreeRTOS timing too much. */
\r
257 if( SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS ) == 0 )
\r
259 printf( "SetPriorityClass() failed\r\n" );
\r
262 /* Install the interrupt handlers used by the scheduler itself. */
\r
263 vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );
\r
264 vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );
\r
266 /* Create the events and mutexes that are used to synchronise all the
\r
268 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
\r
269 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
271 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )
\r
276 /* Set the priority of this thread such that it is above the priority of
\r
277 the threads that run tasks. This higher priority is required to ensure
\r
278 simulated interrupts take priority over tasks. */
\r
279 pvHandle = GetCurrentThread();
\r
280 if( pvHandle == NULL )
\r
286 if( lSuccess == pdPASS )
\r
288 if( SetThreadPriority( pvHandle, portSIMULATED_INTERRUPTS_THREAD_PRIORITY ) == 0 )
\r
292 SetThreadPriorityBoost( pvHandle, TRUE );
\r
293 SetThreadAffinityMask( pvHandle, 0x01 );
\r
296 if( lSuccess == pdPASS )
\r
298 /* Start the thread that simulates the timer peripheral to generate
\r
299 tick interrupts. The priority is set below that of the simulated
\r
300 interrupt handler so the interrupt event mutex is used for the
\r
301 handshake / overrun protection. */
\r
302 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, CREATE_SUSPENDED, NULL );
\r
303 if( pvHandle != NULL )
\r
305 SetThreadPriority( pvHandle, portSIMULATED_TIMER_THREAD_PRIORITY );
\r
306 SetThreadPriorityBoost( pvHandle, TRUE );
\r
307 SetThreadAffinityMask( pvHandle, 0x01 );
\r
308 ResumeThread( pvHandle );
\r
311 /* Start the highest priority task by obtaining its associated thread
\r
312 state structure, in which is stored the thread handle. */
\r
313 pxThreadState = ( xThreadState * ) *( ( size_t * ) pxCurrentTCB );
\r
314 ulCriticalNesting = portNO_CRITICAL_NESTING;
\r
316 /* Bump up the priority of the thread that is going to run, in the
\r
317 hope that this will assist in getting the Windows thread scheduler to
\r
318 behave as an embedded engineer might expect. */
\r
319 ResumeThread( pxThreadState->pvThread );
\r
321 /* Handle all simulated interrupts - including yield requests and
\r
322 simulated ticks. */
\r
323 prvProcessSimulatedInterrupts();
\r
326 /* Would not expect to return from prvProcessSimulatedInterrupts(), so should
\r
330 /*-----------------------------------------------------------*/
\r
332 static uint32_t prvProcessYieldInterrupt( void )
\r
336 /*-----------------------------------------------------------*/
\r
338 static uint32_t prvProcessTickInterrupt( void )
\r
340 uint32_t ulSwitchRequired;
\r
342 /* Process the tick itself. */
\r
343 configASSERT( xPortRunning );
\r
344 ulSwitchRequired = ( uint32_t ) xTaskIncrementTick();
\r
346 return ulSwitchRequired;
\r
348 /*-----------------------------------------------------------*/
\r
350 static void prvProcessSimulatedInterrupts( void )
\r
352 uint32_t ulSwitchRequired, i;
\r
353 xThreadState *pxThreadState;
\r
354 void *pvObjectList[ 2 ];
\r
357 /* Going to block on the mutex that ensured exclusive access to the simulated
\r
358 interrupt objects, and the event that signals that a simulated interrupt
\r
359 should be processed. */
\r
360 pvObjectList[ 0 ] = pvInterruptEventMutex;
\r
361 pvObjectList[ 1 ] = pvInterruptEvent;
\r
363 /* Create a pending tick to ensure the first task is started as soon as
\r
364 this thread pends. */
\r
365 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
366 SetEvent( pvInterruptEvent );
\r
368 xPortRunning = pdTRUE;
\r
372 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
\r
374 /* Used to indicate whether the simulated interrupt processing has
\r
375 necessitated a context switch to another task/thread. */
\r
376 ulSwitchRequired = pdFALSE;
\r
378 /* For each interrupt we are interested in processing, each of which is
\r
379 represented by a bit in the 32bit ulPendingInterrupts variable. */
\r
380 for( i = 0; i < portMAX_INTERRUPTS; i++ )
\r
382 /* Is the simulated interrupt pending? */
\r
383 if( ulPendingInterrupts & ( 1UL << i ) )
\r
385 /* Is a handler installed? */
\r
386 if( ulIsrHandler[ i ] != NULL )
\r
388 /* Run the actual handler. */
\r
389 if( ulIsrHandler[ i ]() != pdFALSE )
\r
391 ulSwitchRequired |= ( 1 << i );
\r
395 /* Clear the interrupt pending bit. */
\r
396 ulPendingInterrupts &= ~( 1UL << i );
\r
400 if( ulSwitchRequired != pdFALSE )
\r
402 void *pvOldCurrentTCB;
\r
404 pvOldCurrentTCB = pxCurrentTCB;
\r
406 /* Select the next task to run. */
\r
407 vTaskSwitchContext();
\r
409 /* If the task selected to enter the running state is not the task
\r
410 that is already in the running state. */
\r
411 if( pvOldCurrentTCB != pxCurrentTCB )
\r
413 /* Suspend the old thread. */
\r
414 pxThreadState = ( xThreadState *) *( ( size_t * ) pvOldCurrentTCB );
\r
415 SuspendThread( pxThreadState->pvThread );
\r
417 /* Ensure the thread is actually suspended by performing a
\r
418 synchronous operation that can only complete when the thread is
\r
419 actually suspended. The below code asks for dummy register
\r
421 xContext.ContextFlags = CONTEXT_INTEGER;
\r
422 ( void ) GetThreadContext( pxThreadState->pvThread, &xContext );
\r
424 /* Obtain the state of the task now selected to enter the
\r
426 pxThreadState = ( xThreadState * ) ( *( size_t *) pxCurrentTCB );
\r
427 ResumeThread( pxThreadState->pvThread );
\r
431 ReleaseMutex( pvInterruptEventMutex );
\r
434 /*-----------------------------------------------------------*/
\r
436 void vPortDeleteThread( void *pvTaskToDelete )
\r
438 xThreadState *pxThreadState;
\r
439 uint32_t ulErrorCode;
\r
441 /* Remove compiler warnings if configASSERT() is not defined. */
\r
442 ( void ) ulErrorCode;
\r
444 /* Find the handle of the thread being deleted. */
\r
445 pxThreadState = ( xThreadState * ) ( *( size_t *) pvTaskToDelete );
\r
447 /* Check that the thread is still valid, it might have been closed by
\r
448 vPortCloseRunningThread() - which will be the case if the task associated
\r
449 with the thread originally deleted itself rather than being deleted by a
\r
451 if( pxThreadState->pvThread != NULL )
\r
453 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
455 /* !!! This is not a nice way to terminate a thread, and will eventually
\r
456 result in resources being depleted if tasks frequently delete other
\r
457 tasks (rather than deleting themselves) as the task stacks will not be
\r
459 ulErrorCode = TerminateThread( pxThreadState->pvThread, 0 );
\r
460 configASSERT( ulErrorCode );
\r
462 ulErrorCode = CloseHandle( pxThreadState->pvThread );
\r
463 configASSERT( ulErrorCode );
\r
465 ReleaseMutex( pvInterruptEventMutex );
\r
468 /*-----------------------------------------------------------*/
\r
470 void vPortCloseRunningThread( void *pvTaskToDelete, volatile BaseType_t *pxPendYield )
\r
472 xThreadState *pxThreadState;
\r
474 uint32_t ulErrorCode;
\r
476 /* Remove compiler warnings if configASSERT() is not defined. */
\r
477 ( void ) ulErrorCode;
\r
479 /* Find the handle of the thread being deleted. */
\r
480 pxThreadState = ( xThreadState * ) ( *( size_t *) pvTaskToDelete );
\r
481 pvThread = pxThreadState->pvThread;
\r
483 /* Raise the Windows priority of the thread to ensure the FreeRTOS scheduler
\r
484 does not run and swap it out before it is closed. If that were to happen
\r
485 the thread would never run again and effectively be a thread handle and
\r
487 SetThreadPriority( pvThread, portDELETE_SELF_THREAD_PRIORITY );
\r
489 /* This function will not return, therefore a yield is set as pending to
\r
490 ensure a context switch occurs away from this thread on the next tick. */
\r
491 *pxPendYield = pdTRUE;
\r
493 /* Mark the thread associated with this task as invalid so
\r
494 vPortDeleteThread() does not try to terminate it. */
\r
495 pxThreadState->pvThread = NULL;
\r
497 /* Close the thread. */
\r
498 ulErrorCode = CloseHandle( pvThread );
\r
499 configASSERT( ulErrorCode );
\r
501 /* This is called from a critical section, which must be exited before the
\r
503 taskEXIT_CRITICAL();
\r
507 /*-----------------------------------------------------------*/
\r
509 void vPortEndScheduler( void )
\r
513 /*-----------------------------------------------------------*/
\r
515 void vPortGenerateSimulatedInterrupt( uint32_t ulInterruptNumber )
\r
517 configASSERT( xPortRunning );
\r
519 if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
\r
521 /* Yield interrupts are processed even when critical nesting is
\r
523 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
524 ulPendingInterrupts |= ( 1 << ulInterruptNumber );
\r
526 /* The simulated interrupt is now held pending, but don't actually
\r
527 process it yet if this call is within a critical section. It is
\r
528 possible for this to be in a critical section as calls to wait for
\r
529 mutexes are accumulative. */
\r
530 if( ulCriticalNesting == 0 )
\r
532 SetEvent( pvInterruptEvent );
\r
535 ReleaseMutex( pvInterruptEventMutex );
\r
538 /*-----------------------------------------------------------*/
\r
540 void vPortSetInterruptHandler( uint32_t ulInterruptNumber, uint32_t (*pvHandler)( void ) )
\r
542 if( ulInterruptNumber < portMAX_INTERRUPTS )
\r
544 if( pvInterruptEventMutex != NULL )
\r
546 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
547 ulIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
548 ReleaseMutex( pvInterruptEventMutex );
\r
552 ulIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
556 /*-----------------------------------------------------------*/
\r
558 void vPortEnterCritical( void )
\r
560 if( xPortRunning == pdTRUE )
\r
562 /* The interrupt event mutex is held for the entire critical section,
\r
563 effectively disabling (simulated) interrupts. */
\r
564 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
565 ulCriticalNesting++;
\r
569 ulCriticalNesting++;
\r
572 /*-----------------------------------------------------------*/
\r
574 void vPortExitCritical( void )
\r
576 int32_t lMutexNeedsReleasing;
\r
578 /* The interrupt event mutex should already be held by this thread as it was
\r
579 obtained on entry to the critical section. */
\r
581 lMutexNeedsReleasing = pdTRUE;
\r
583 if( ulCriticalNesting > portNO_CRITICAL_NESTING )
\r
585 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )
\r
587 ulCriticalNesting--;
\r
589 /* Were any interrupts set to pending while interrupts were
\r
590 (simulated) disabled? */
\r
591 if( ulPendingInterrupts != 0UL )
\r
593 configASSERT( xPortRunning );
\r
594 SetEvent( pvInterruptEvent );
\r
596 /* Mutex will be released now, so does not require releasing
\r
597 on function exit. */
\r
598 lMutexNeedsReleasing = pdFALSE;
\r
599 ReleaseMutex( pvInterruptEventMutex );
\r
604 /* Tick interrupts will still not be processed as the critical
\r
605 nesting depth will not be zero. */
\r
606 ulCriticalNesting--;
\r
610 if( pvInterruptEventMutex != NULL )
\r
612 if( lMutexNeedsReleasing == pdTRUE )
\r
614 configASSERT( xPortRunning );
\r
615 ReleaseMutex( pvInterruptEventMutex );
\r
619 /*-----------------------------------------------------------*/
\r