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