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