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