]> begriffs open source - freertos/blob - portable/MSVC-MingW/port.c
[AUTO][RELEASE]: Bump file header version to "10.5.1"
[freertos] / portable / MSVC-MingW / port.c
1 /*\r
2  * FreeRTOS Kernel V10.5.1\r
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\r
4  *\r
5  * SPDX-License-Identifier: MIT\r
6  *\r
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
8  * this software and associated documentation files (the "Software"), to deal in\r
9  * the Software without restriction, including without limitation the rights to\r
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
11  * the Software, and to permit persons to whom the Software is furnished to do so,\r
12  * subject to the following conditions:\r
13  *\r
14  * The above copyright notice and this permission notice shall be included in all\r
15  * copies or substantial portions of the Software.\r
16  *\r
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
23  *\r
24  * https://www.FreeRTOS.org\r
25  * https://github.com/FreeRTOS\r
26  *\r
27  */\r
28 \r
29 /* Standard includes. */\r
30 #include <stdio.h>\r
31 \r
32 /* Scheduler includes. */\r
33 #include "FreeRTOS.h"\r
34 #include "task.h"\r
35 \r
36 #ifdef __GNUC__\r
37         #include "mmsystem.h"\r
38 #else\r
39         #pragma comment(lib, "winmm.lib")\r
40 #endif\r
41 \r
42 #define portMAX_INTERRUPTS                              ( ( uint32_t ) sizeof( uint32_t ) * 8UL ) /* The number of bits in an uint32_t. */\r
43 #define portNO_CRITICAL_NESTING                 ( ( uint32_t ) 0 )\r
44 \r
45 /* The priorities at which the various components of the simulation execute. */\r
46 #define portDELETE_SELF_THREAD_PRIORITY                  THREAD_PRIORITY_TIME_CRITICAL /* Must be highest. */\r
47 #define portSIMULATED_INTERRUPTS_THREAD_PRIORITY THREAD_PRIORITY_TIME_CRITICAL\r
48 #define portSIMULATED_TIMER_THREAD_PRIORITY              THREAD_PRIORITY_HIGHEST\r
49 #define portTASK_THREAD_PRIORITY                                 THREAD_PRIORITY_ABOVE_NORMAL\r
50 \r
51 /*\r
52  * Created as a high priority thread, this function uses a timer to simulate\r
53  * a tick interrupt being generated on an embedded target.  In this Windows\r
54  * environment the timer does not achieve anything approaching real time\r
55  * performance though.\r
56  */\r
57 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );\r
58 \r
59 /*\r
60  * Process all the simulated interrupts - each represented by a bit in\r
61  * ulPendingInterrupts variable.\r
62  */\r
63 static void prvProcessSimulatedInterrupts( void );\r
64 \r
65 /*\r
66  * Interrupt handlers used by the kernel itself.  These are executed from the\r
67  * simulated interrupt handler thread.\r
68  */\r
69 static uint32_t prvProcessYieldInterrupt( void );\r
70 static uint32_t prvProcessTickInterrupt( void );\r
71 \r
72 /*\r
73  * Exiting a critical section will cause the calling task to block on yield\r
74  * event to wait for an interrupt to process if an interrupt was pended while\r
75  * inside the critical section.  This variable protects against a recursive\r
76  * attempt to obtain pvInterruptEventMutex if a critical section is used inside\r
77  * an interrupt handler itself.\r
78  */\r
79 volatile BaseType_t xInsideInterrupt = pdFALSE;\r
80 \r
81 /*\r
82  * Called when the process exits to let Windows know the high timer resolution\r
83  * is no longer required.\r
84  */\r
85 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType );\r
86 \r
87 /*-----------------------------------------------------------*/\r
88 \r
89 /* The WIN32 simulator runs each task in a thread.  The context switching is\r
90 managed by the threads, so the task stack does not have to be managed directly,\r
91 although the task stack is still used to hold an xThreadState structure this is\r
92 the only thing it will ever hold.  The structure indirectly maps the task handle\r
93 to a thread handle. */\r
94 typedef struct\r
95 {\r
96         /* Handle of the thread that executes the task. */\r
97         void *pvThread;\r
98 \r
99         /* Event used to make sure the thread does not execute past a yield point\r
100         between the call to SuspendThread() to suspend the thread and the\r
101         asynchronous SuspendThread() operation actually being performed. */\r
102         void *pvYieldEvent;\r
103 } ThreadState_t;\r
104 \r
105 /* Simulated interrupts waiting to be processed.  This is a bit mask where each\r
106 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */\r
107 static volatile uint32_t ulPendingInterrupts = 0UL;\r
108 \r
109 /* An event used to inform the simulated interrupt processing thread (a high\r
110 priority thread that simulated interrupt processing) that an interrupt is\r
111 pending. */\r
112 static void *pvInterruptEvent = NULL;\r
113 \r
114 /* Mutex used to protect all the simulated interrupt variables that are accessed\r
115 by multiple threads. */\r
116 static void *pvInterruptEventMutex = NULL;\r
117 \r
118 /* The critical nesting count for the currently executing task.  This is\r
119 initialised to a non-zero value so interrupts do not become enabled during\r
120 the initialisation phase.  As each task has its own critical nesting value\r
121 ulCriticalNesting will get set to zero when the first task runs.  This\r
122 initialisation is probably not critical in this simulated environment as the\r
123 simulated interrupt handlers do not get created until the FreeRTOS scheduler is\r
124 started anyway. */\r
125 static volatile uint32_t ulCriticalNesting = 9999UL;\r
126 \r
127 /* Handlers for all the simulated software interrupts.  The first two positions\r
128 are used for the Yield and Tick interrupts so are handled slightly differently,\r
129 all the other interrupts can be user defined. */\r
130 static uint32_t (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };\r
131 \r
132 /* Pointer to the TCB of the currently executing task. */\r
133 extern void * volatile pxCurrentTCB;\r
134 \r
135 /* Used to ensure nothing is processed during the startup sequence. */\r
136 static BaseType_t xPortRunning = pdFALSE;\r
137 \r
138 /*-----------------------------------------------------------*/\r
139 \r
140 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )\r
141 {\r
142 TickType_t xMinimumWindowsBlockTime;\r
143 TIMECAPS xTimeCaps;\r
144 \r
145         /* Set the timer resolution to the maximum possible. */\r
146         if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )\r
147         {\r
148                 xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin;\r
149                 timeBeginPeriod( xTimeCaps.wPeriodMin );\r
150 \r
151                 /* Register an exit handler so the timeBeginPeriod() function can be\r
152                 matched with a timeEndPeriod() when the application exits. */\r
153                 SetConsoleCtrlHandler( prvEndProcess, TRUE );\r
154         }\r
155         else\r
156         {\r
157                 xMinimumWindowsBlockTime = ( TickType_t ) 20;\r
158         }\r
159 \r
160         /* Just to prevent compiler warnings. */\r
161         ( void ) lpParameter;\r
162 \r
163         for( ;; )\r
164         {\r
165                 /* Wait until the timer expires and we can access the simulated interrupt\r
166                 variables.  *NOTE* this is not a 'real time' way of generating tick\r
167                 events as the next wake time should be relative to the previous wake\r
168                 time, not the time that Sleep() is called.  It is done this way to\r
169                 prevent overruns in this very non real time simulated/emulated\r
170                 environment. */\r
171                 if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime )\r
172                 {\r
173                         Sleep( xMinimumWindowsBlockTime );\r
174                 }\r
175                 else\r
176                 {\r
177                         Sleep( portTICK_PERIOD_MS );\r
178                 }\r
179 \r
180                 configASSERT( xPortRunning );\r
181 \r
182                 /* Can't proceed if in a critical section as pvInterruptEventMutex won't\r
183                 be available. */\r
184                 WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
185 \r
186                 /* The timer has expired, generate the simulated tick event. */\r
187                 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );\r
188 \r
189                 /* The interrupt is now pending - notify the simulated interrupt\r
190                 handler thread.  Must be outside of a critical section to get here so\r
191                 the handler thread can execute immediately pvInterruptEventMutex is\r
192                 released. */\r
193                 configASSERT( ulCriticalNesting == 0UL );\r
194                 SetEvent( pvInterruptEvent );\r
195 \r
196                 /* Give back the mutex so the simulated interrupt handler unblocks\r
197                 and can access the interrupt handler variables. */\r
198                 ReleaseMutex( pvInterruptEventMutex );\r
199         }\r
200 \r
201         #ifdef __GNUC__\r
202                 /* Should never reach here - MingW complains if you leave this line out,\r
203                 MSVC complains if you put it in. */\r
204                 return 0;\r
205         #endif\r
206 }\r
207 /*-----------------------------------------------------------*/\r
208 \r
209 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType )\r
210 {\r
211 TIMECAPS xTimeCaps;\r
212 \r
213         ( void ) dwCtrlType;\r
214 \r
215         if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )\r
216         {\r
217                 /* Match the call to timeBeginPeriod( xTimeCaps.wPeriodMin ) made when\r
218                 the process started with a timeEndPeriod() as the process exits. */\r
219                 timeEndPeriod( xTimeCaps.wPeriodMin );\r
220         }\r
221 \r
222         return pdFALSE;\r
223 }\r
224 /*-----------------------------------------------------------*/\r
225 \r
226 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )\r
227 {\r
228 ThreadState_t *pxThreadState = NULL;\r
229 int8_t *pcTopOfStack = ( int8_t * ) pxTopOfStack;\r
230 const SIZE_T xStackSize = 1024; /* Set the size to a small number which will get rounded up to the minimum possible. */\r
231 \r
232         /* In this simulated case a stack is not initialised, but instead a thread\r
233         is created that will execute the task being created.  The thread handles\r
234         the context switching itself.  The ThreadState_t object is placed onto\r
235         the stack that was created for the task - so the stack buffer is still\r
236         used, just not in the conventional way.  It will not be used for anything\r
237         other than holding this structure. */\r
238         pxThreadState = ( ThreadState_t * ) ( pcTopOfStack - sizeof( ThreadState_t ) );\r
239 \r
240         /* Create the event used to prevent the thread from executing past its yield\r
241         point if the SuspendThread() call that suspends the thread does not take\r
242         effect immediately (it is an asynchronous call). */\r
243         pxThreadState->pvYieldEvent = CreateEvent(  NULL,  /* Default security attributes. */\r
244                                                                                                 FALSE, /* Auto reset. */\r
245                                                                                                 FALSE, /* Start not signalled. */\r
246                                                                                                 NULL );/* No name. */\r
247 \r
248         /* Create the thread itself. */\r
249         pxThreadState->pvThread = CreateThread( NULL, xStackSize, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, NULL );\r
250         configASSERT( pxThreadState->pvThread ); /* See comment where TerminateThread() is called. */\r
251         SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );\r
252         SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );\r
253         SetThreadPriority( pxThreadState->pvThread, portTASK_THREAD_PRIORITY );\r
254 \r
255         return ( StackType_t * ) pxThreadState;\r
256 }\r
257 /*-----------------------------------------------------------*/\r
258 \r
259 BaseType_t xPortStartScheduler( void )\r
260 {\r
261 void *pvHandle = NULL;\r
262 int32_t lSuccess;\r
263 ThreadState_t *pxThreadState = NULL;\r
264 SYSTEM_INFO xSystemInfo;\r
265 \r
266         /* This port runs windows threads with extremely high priority.  All the\r
267         threads execute on the same core - to prevent locking up the host only start\r
268         if the host has multiple cores. */\r
269         GetSystemInfo( &xSystemInfo );\r
270         if( xSystemInfo.dwNumberOfProcessors <= 1 )\r
271         {\r
272                 printf( "This version of the FreeRTOS Windows port can only be used on multi-core hosts.\r\n" );\r
273                 lSuccess = pdFAIL;\r
274         }\r
275         else\r
276         {\r
277                 lSuccess = pdPASS;\r
278 \r
279                 /* The highest priority class is used to [try to] prevent other Windows\r
280                 activity interfering with FreeRTOS timing too much. */\r
281                 if( SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS ) == 0 )\r
282                 {\r
283                         printf( "SetPriorityClass() failed\r\n" );\r
284                 }\r
285 \r
286                 /* Install the interrupt handlers used by the scheduler itself. */\r
287                 vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );\r
288                 vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );\r
289 \r
290                 /* Create the events and mutexes that are used to synchronise all the\r
291                 threads. */\r
292                 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );\r
293                 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
294 \r
295                 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )\r
296                 {\r
297                         lSuccess = pdFAIL;\r
298                 }\r
299 \r
300                 /* Set the priority of this thread such that it is above the priority of\r
301                 the threads that run tasks.  This higher priority is required to ensure\r
302                 simulated interrupts take priority over tasks. */\r
303                 pvHandle = GetCurrentThread();\r
304                 if( pvHandle == NULL )\r
305                 {\r
306                         lSuccess = pdFAIL;\r
307                 }\r
308         }\r
309 \r
310         if( lSuccess == pdPASS )\r
311         {\r
312                 if( SetThreadPriority( pvHandle, portSIMULATED_INTERRUPTS_THREAD_PRIORITY ) == 0 )\r
313                 {\r
314                         lSuccess = pdFAIL;\r
315                 }\r
316                 SetThreadPriorityBoost( pvHandle, TRUE );\r
317                 SetThreadAffinityMask( pvHandle, 0x01 );\r
318         }\r
319 \r
320         if( lSuccess == pdPASS )\r
321         {\r
322                 /* Start the thread that simulates the timer peripheral to generate\r
323                 tick interrupts.  The priority is set below that of the simulated\r
324                 interrupt handler so the interrupt event mutex is used for the\r
325                 handshake / overrun protection. */\r
326                 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, CREATE_SUSPENDED, NULL );\r
327                 if( pvHandle != NULL )\r
328                 {\r
329                         SetThreadPriority( pvHandle, portSIMULATED_TIMER_THREAD_PRIORITY );\r
330                         SetThreadPriorityBoost( pvHandle, TRUE );\r
331                         SetThreadAffinityMask( pvHandle, 0x01 );\r
332                         ResumeThread( pvHandle );\r
333                 }\r
334 \r
335                 /* Start the highest priority task by obtaining its associated thread\r
336                 state structure, in which is stored the thread handle. */\r
337                 pxThreadState = ( ThreadState_t * ) *( ( size_t * ) pxCurrentTCB );\r
338                 ulCriticalNesting = portNO_CRITICAL_NESTING;\r
339 \r
340                 /* Start the first task. */\r
341                 ResumeThread( pxThreadState->pvThread );\r
342 \r
343                 /* Handle all simulated interrupts - including yield requests and\r
344                 simulated ticks. */\r
345                 prvProcessSimulatedInterrupts();\r
346         }\r
347 \r
348         /* Would not expect to return from prvProcessSimulatedInterrupts(), so should\r
349         not get here. */\r
350         return 0;\r
351 }\r
352 /*-----------------------------------------------------------*/\r
353 \r
354 static uint32_t prvProcessYieldInterrupt( void )\r
355 {\r
356         /* Always return true as this is a yield. */\r
357         return pdTRUE;\r
358 }\r
359 /*-----------------------------------------------------------*/\r
360 \r
361 static uint32_t prvProcessTickInterrupt( void )\r
362 {\r
363 uint32_t ulSwitchRequired;\r
364 \r
365         /* Process the tick itself. */\r
366         configASSERT( xPortRunning );\r
367         ulSwitchRequired = ( uint32_t ) xTaskIncrementTick();\r
368 \r
369         return ulSwitchRequired;\r
370 }\r
371 /*-----------------------------------------------------------*/\r
372 \r
373 static void prvProcessSimulatedInterrupts( void )\r
374 {\r
375 uint32_t ulSwitchRequired, i;\r
376 ThreadState_t *pxThreadState;\r
377 void *pvObjectList[ 2 ];\r
378 CONTEXT xContext;\r
379 \r
380         /* Going to block on the mutex that ensured exclusive access to the simulated\r
381         interrupt objects, and the event that signals that a simulated interrupt\r
382         should be processed. */\r
383         pvObjectList[ 0 ] = pvInterruptEventMutex;\r
384         pvObjectList[ 1 ] = pvInterruptEvent;\r
385 \r
386         /* Create a pending tick to ensure the first task is started as soon as\r
387         this thread pends. */\r
388         ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );\r
389         SetEvent( pvInterruptEvent );\r
390 \r
391         xPortRunning = pdTRUE;\r
392 \r
393         for(;;)\r
394         {\r
395                 xInsideInterrupt = pdFALSE;\r
396                 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );\r
397 \r
398                 /* Cannot be in a critical section to get here.  Tasks that exit a\r
399                 critical section will block on a yield mutex to wait for an interrupt to\r
400                 process if an interrupt was set pending while the task was inside the\r
401                 critical section.  xInsideInterrupt prevents interrupts that contain\r
402                 critical sections from doing the same. */\r
403                 xInsideInterrupt = pdTRUE;\r
404 \r
405                 /* Used to indicate whether the simulated interrupt processing has\r
406                 necessitated a context switch to another task/thread. */\r
407                 ulSwitchRequired = pdFALSE;\r
408 \r
409                 /* For each interrupt we are interested in processing, each of which is\r
410                 represented by a bit in the 32bit ulPendingInterrupts variable. */\r
411                 for( i = 0; i < portMAX_INTERRUPTS; i++ )\r
412                 {\r
413                         /* Is the simulated interrupt pending? */\r
414                         if( ( ulPendingInterrupts & ( 1UL << i ) ) != 0 )\r
415                         {\r
416                                 /* Is a handler installed? */\r
417                                 if( ulIsrHandler[ i ] != NULL )\r
418                                 {\r
419                                         /* Run the actual handler.  Handlers return pdTRUE if they\r
420                                         necessitate a context switch. */\r
421                                         if( ulIsrHandler[ i ]() != pdFALSE )\r
422                                         {\r
423                                                 /* A bit mask is used purely to help debugging. */\r
424                                                 ulSwitchRequired |= ( 1 << i );\r
425                                         }\r
426                                 }\r
427 \r
428                                 /* Clear the interrupt pending bit. */\r
429                                 ulPendingInterrupts &= ~( 1UL << i );\r
430                         }\r
431                 }\r
432 \r
433                 if( ulSwitchRequired != pdFALSE )\r
434                 {\r
435                         void *pvOldCurrentTCB;\r
436 \r
437                         pvOldCurrentTCB = pxCurrentTCB;\r
438 \r
439                         /* Select the next task to run. */\r
440                         vTaskSwitchContext();\r
441 \r
442                         /* If the task selected to enter the running state is not the task\r
443                         that is already in the running state. */\r
444                         if( pvOldCurrentTCB != pxCurrentTCB )\r
445                         {\r
446                                 /* Suspend the old thread.  In the cases where the (simulated)\r
447                                 interrupt is asynchronous (tick event swapping a task out rather\r
448                                 than a task blocking or yielding) it doesn't matter if the\r
449                                 'suspend' operation doesn't take effect immediately - if it\r
450                                 doesn't it would just be like the interrupt occurring slightly\r
451                                 later.  In cases where the yield was caused by a task blocking\r
452                                 or yielding then the task will block on a yield event after the\r
453                                 yield operation in case the 'suspend' operation doesn't take\r
454                                 effect immediately.  */\r
455                                 pxThreadState = ( ThreadState_t *) *( ( size_t * ) pvOldCurrentTCB );\r
456                                 SuspendThread( pxThreadState->pvThread );\r
457 \r
458                                 /* Ensure the thread is actually suspended by performing a\r
459                                 synchronous operation that can only complete when the thread is\r
460                                 actually suspended.  The below code asks for dummy register\r
461                                 data.  Experimentation shows that these two lines don't appear\r
462                                 to do anything now, but according to\r
463                                 https://devblogs.microsoft.com/oldnewthing/20150205-00/?p=44743\r
464                                 they do - so as they do not harm (slight run-time hit). */\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 allow 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;\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         lMutexNeedsReleasing = pdTRUE;\r
650 \r
651         if( ulCriticalNesting > portNO_CRITICAL_NESTING )\r
652         {\r
653                 ulCriticalNesting--;\r
654 \r
655                 /* Don't need to wait for any pending interrupts to execute if the\r
656                 critical section was exited from inside an interrupt. */\r
657                 if( ( ulCriticalNesting == portNO_CRITICAL_NESTING ) && ( xInsideInterrupt == pdFALSE ) )\r
658                 {\r
659                         /* Were any interrupts set to pending while interrupts were\r
660                         (simulated) disabled? */\r
661                         if( ulPendingInterrupts != 0UL )\r
662                         {\r
663                                 ThreadState_t *pxThreadState = ( ThreadState_t *) *( ( size_t * ) pxCurrentTCB );\r
664 \r
665                                 configASSERT( xPortRunning );\r
666 \r
667                                 /* The interrupt won't actually executed until\r
668                                 pvInterruptEventMutex is released as it waits on both\r
669                                 pvInterruptEventMutex and pvInterruptEvent.\r
670                                 pvInterruptEvent is only set when the simulated\r
671                                 interrupt is pended if the interrupt is pended\r
672                                 from outside a critical section - hence it is set\r
673                                 here. */\r
674                                 SetEvent( pvInterruptEvent );\r
675                                 /* The calling task is going to wait for an event to ensure the\r
676                                 interrupt that is pending executes immediately after the\r
677                                 critical section is exited - so make sure the event is not\r
678                                 already signaled. */\r
679                                 ResetEvent( pxThreadState->pvYieldEvent );\r
680 \r
681                                 /* Mutex will be released now so the (simulated) interrupt can\r
682                                 execute, so does not require releasing on function exit. */\r
683                                 lMutexNeedsReleasing = pdFALSE;\r
684                                 ReleaseMutex( pvInterruptEventMutex );\r
685                                 WaitForSingleObject( pxThreadState->pvYieldEvent, INFINITE );\r
686                         }\r
687                 }\r
688         }\r
689 \r
690         if( pvInterruptEventMutex != NULL )\r
691         {\r
692                 if( lMutexNeedsReleasing == pdTRUE )\r
693                 {\r
694                         configASSERT( xPortRunning );\r
695                         ReleaseMutex( pvInterruptEventMutex );\r
696                 }\r
697         }\r
698 }\r
699 /*-----------------------------------------------------------*/\r
700 \r