]> git.sur5r.net Git - freertos/blobdiff - FreeRTOS/Source/portable/MSVC-MingW/port.c
Fix spelling issues.
[freertos] / FreeRTOS / Source / portable / MSVC-MingW / port.c
index 77d6efa9987ef7811e270e1c1eca32005636c897..ec2341748b8539e909cabb25ec0c1c69153941b2 100644 (file)
@@ -1,72 +1,36 @@
 /*\r
-    FreeRTOS V7.5.3 - Copyright (C) 2013 Real Time Engineers Ltd. \r
-    All rights reserved\r
-\r
-    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
-\r
-    ***************************************************************************\r
-     *                                                                       *\r
-     *    FreeRTOS provides completely free yet professionally developed,    *\r
-     *    robust, strictly quality controlled, supported, and cross          *\r
-     *    platform software that has become a de facto standard.             *\r
-     *                                                                       *\r
-     *    Help yourself get started quickly and support the FreeRTOS         *\r
-     *    project by purchasing a FreeRTOS tutorial book, reference          *\r
-     *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
-     *                                                                       *\r
-     *    Thank you!                                                         *\r
-     *                                                                       *\r
-    ***************************************************************************\r
-\r
-    This file is part of the FreeRTOS distribution.\r
-\r
-    FreeRTOS is free software; you can redistribute it and/or modify it under\r
-    the terms of the GNU General Public License (version 2) as published by the\r
-    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
-\r
-    >>! NOTE: The modification to the GPL is included to allow you to distribute\r
-    >>! a combined work that includes FreeRTOS without being obliged to provide\r
-    >>! the source code for proprietary components outside of the FreeRTOS\r
-    >>! kernel.\r
-\r
-    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
-    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
-    FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
-    link: http://www.freertos.org/a00114.html\r
-\r
-    1 tab == 4 spaces!\r
-\r
-    ***************************************************************************\r
-     *                                                                       *\r
-     *    Having a problem?  Start by reading the FAQ "My application does   *\r
-     *    not run, what could be wrong?"                                     *\r
-     *                                                                       *\r
-     *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
-     *                                                                       *\r
-    ***************************************************************************\r
-\r
-    http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
-    license and Real Time Engineers Ltd. contact details.\r
-\r
-    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
-    including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
-    compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
-\r
-    http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
-    Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
-    licenses offer ticketed support, indemnification and middleware.\r
-\r
-    http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
-    engineered and independently SIL3 certified version for use in safety and\r
-    mission critical applications that require provable dependability.\r
-\r
-    1 tab == 4 spaces!\r
-*/\r
+ * FreeRTOS Kernel V10.2.1\r
+ * Copyright (C) 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+ * this software and associated documentation files (the "Software"), to deal in\r
+ * the Software without restriction, including without limitation the rights to\r
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+ * the Software, and to permit persons to whom the Software is furnished to do so,\r
+ * subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included in all\r
+ * copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+ *\r
+ * http://www.FreeRTOS.org\r
+ * http://aws.amazon.com/freertos\r
+ *\r
+ * 1 tab == 4 spaces!\r
+ */\r
+\r
+/* Standard includes. */\r
+#include <stdio.h>\r
 \r
 /* Scheduler includes. */\r
 #include "FreeRTOS.h"\r
 #include "task.h"\r
-#include <stdio.h>\r
 \r
 #ifdef __GNUC__\r
        #include "mmsystem.h"\r
        #pragma comment(lib, "winmm.lib")\r
 #endif\r
 \r
-#define portMAX_INTERRUPTS                             ( ( unsigned long ) sizeof( unsigned long ) * 8UL ) /* The number of bits in an unsigned long. */\r
-#define portNO_CRITICAL_NESTING                ( ( unsigned long ) 0 )\r
+#define portMAX_INTERRUPTS                             ( ( uint32_t ) sizeof( uint32_t ) * 8UL ) /* The number of bits in an uint32_t. */\r
+#define portNO_CRITICAL_NESTING                ( ( uint32_t ) 0 )\r
+\r
+/* The priorities at which the various components of the simulation execute. */\r
+#define portDELETE_SELF_THREAD_PRIORITY                         THREAD_PRIORITY_TIME_CRITICAL /* Must be highest. */\r
+#define portSIMULATED_INTERRUPTS_THREAD_PRIORITY THREAD_PRIORITY_TIME_CRITICAL\r
+#define portSIMULATED_TIMER_THREAD_PRIORITY             THREAD_PRIORITY_HIGHEST\r
+#define portTASK_THREAD_PRIORITY                                THREAD_PRIORITY_ABOVE_NORMAL\r
 \r
 /*\r
  * Created as a high priority thread, this function uses a timer to simulate\r
  * a tick interrupt being generated on an embedded target.  In this Windows\r
- * environment the timer does not achieve anything approaching real time \r
+ * environment the timer does not achieve anything approaching real time\r
  * performance though.\r
  */\r
 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );\r
 \r
-/* \r
- * Process all the simulated interrupts - each represented by a bit in \r
+/*\r
+ * Process all the simulated interrupts - each represented by a bit in\r
  * ulPendingInterrupts variable.\r
  */\r
 static void prvProcessSimulatedInterrupts( void );\r
@@ -95,8 +65,17 @@ static void prvProcessSimulatedInterrupts( void );
  * Interrupt handlers used by the kernel itself.  These are executed from the\r
  * simulated interrupt handler thread.\r
  */\r
-static unsigned long prvProcessYieldInterrupt( void );\r
-static unsigned long prvProcessTickInterrupt( void );\r
+static uint32_t prvProcessYieldInterrupt( void );\r
+static uint32_t prvProcessTickInterrupt( void );\r
+\r
+/*\r
+ * Exiting a critical section will cause the calling task to block on yield\r
+ * event to wait for an interrupt to process if an interrupt was pended while\r
+ * inside the critical section.  This variable protects against a recursive\r
+ * attempt to obtain pvInterruptEventMutex if a critical section is used inside\r
+ * an interrupt handler itself.\r
+ */\r
+volatile BaseType_t xInsideInterrupt = pdFALSE;\r
 \r
 /*\r
  * Called when the process exits to let Windows know the high timer resolution\r
@@ -109,56 +88,63 @@ static BOOL WINAPI prvEndProcess( DWORD dwCtrlType );
 /* The WIN32 simulator runs each task in a thread.  The context switching is\r
 managed by the threads, so the task stack does not have to be managed directly,\r
 although the task stack is still used to hold an xThreadState structure this is\r
-the only thing it will ever hold.  The structure indirectly maps the task handle \r
+the only thing it will ever hold.  The structure indirectly maps the task handle\r
 to a thread handle. */\r
 typedef struct\r
 {\r
        /* Handle of the thread that executes the task. */\r
        void *pvThread;\r
 \r
-} xThreadState;\r
+       /* Event used to make sure the thread does not execute past a yield point\r
+       between the call to SuspendThread() to suspend the thread and the\r
+       asynchronous SuspendThread() operation actually being performed. */\r
+       void *pvYieldEvent;\r
+} ThreadState_t;\r
 \r
 /* Simulated interrupts waiting to be processed.  This is a bit mask where each\r
 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */\r
-static volatile unsigned long ulPendingInterrupts = 0UL;\r
+static volatile uint32_t ulPendingInterrupts = 0UL;\r
 \r
-/* An event used to inform the simulated interrupt processing thread (a high \r
+/* An event used to inform the simulated interrupt processing thread (a high\r
 priority thread that simulated interrupt processing) that an interrupt is\r
 pending. */\r
 static void *pvInterruptEvent = NULL;\r
 \r
-/* Mutex used to protect all the simulated interrupt variables that are accessed \r
+/* Mutex used to protect all the simulated interrupt variables that are accessed\r
 by multiple threads. */\r
 static void *pvInterruptEventMutex = NULL;\r
 \r
-/* The critical nesting count for the currently executing task.  This is \r
-initialised to a non-zero value so interrupts do not become enabled during \r
-the initialisation phase.  As each task has its own critical nesting value \r
-ulCriticalNesting will get set to zero when the first task runs.  This \r
+/* The critical nesting count for the currently executing task.  This is\r
+initialised to a non-zero value so interrupts do not become enabled during\r
+the initialisation phase.  As each task has its own critical nesting value\r
+ulCriticalNesting will get set to zero when the first task runs.  This\r
 initialisation is probably not critical in this simulated environment as the\r
-simulated interrupt handlers do not get created until the FreeRTOS scheduler is \r
+simulated interrupt handlers do not get created until the FreeRTOS scheduler is\r
 started anyway. */\r
-static unsigned long ulCriticalNesting = 9999UL;\r
+static volatile uint32_t ulCriticalNesting = 9999UL;\r
 \r
 /* Handlers for all the simulated software interrupts.  The first two positions\r
 are used for the Yield and Tick interrupts so are handled slightly differently,\r
 all the other interrupts can be user defined. */\r
-static unsigned long (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };\r
+static uint32_t (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };\r
 \r
 /* Pointer to the TCB of the currently executing task. */\r
-extern void *pxCurrentTCB;\r
+extern void * volatile pxCurrentTCB;\r
+\r
+/* Used to ensure nothing is processed during the startup sequence. */\r
+static BaseType_t xPortRunning = pdFALSE;\r
 \r
 /*-----------------------------------------------------------*/\r
 \r
 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )\r
 {\r
-portTickType xMinimumWindowsBlockTime;\r
+TickType_t xMinimumWindowsBlockTime;\r
 TIMECAPS xTimeCaps;\r
 \r
        /* Set the timer resolution to the maximum possible. */\r
        if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )\r
        {\r
-               xMinimumWindowsBlockTime = ( portTickType ) xTimeCaps.wPeriodMin;\r
+               xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin;\r
                timeBeginPeriod( xTimeCaps.wPeriodMin );\r
 \r
                /* Register an exit handler so the timeBeginPeriod() function can be\r
@@ -167,40 +153,47 @@ TIMECAPS xTimeCaps;
        }\r
        else\r
        {\r
-               xMinimumWindowsBlockTime = ( portTickType ) 20;\r
+               xMinimumWindowsBlockTime = ( TickType_t ) 20;\r
        }\r
 \r
        /* Just to prevent compiler warnings. */\r
        ( void ) lpParameter;\r
 \r
-       for(;;)\r
+       for( ;; )\r
        {\r
-               /* Wait until the timer expires and we can access the simulated interrupt \r
-               variables.  *NOTE* this is not a 'real time' way of generating tick \r
-               events as the next wake time should be relative to the previous wake \r
-               time, not the time that Sleep() is called.  It is done this way to \r
-               prevent overruns in this very non real time simulated/emulated \r
+               /* Wait until the timer expires and we can access the simulated interrupt\r
+               variables.  *NOTE* this is not a 'real time' way of generating tick\r
+               events as the next wake time should be relative to the previous wake\r
+               time, not the time that Sleep() is called.  It is done this way to\r
+               prevent overruns in this very non real time simulated/emulated\r
                environment. */\r
-               if( portTICK_RATE_MS < xMinimumWindowsBlockTime )\r
+               if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime )\r
                {\r
                        Sleep( xMinimumWindowsBlockTime );\r
                }\r
                else\r
                {\r
-                       Sleep( portTICK_RATE_MS );\r
+                       Sleep( portTICK_PERIOD_MS );\r
                }\r
 \r
+               configASSERT( xPortRunning );\r
+\r
+               /* Can't proceed if in a critical section as pvInterruptEventMutex won't\r
+               be available. */\r
                WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
 \r
                /* The timer has expired, generate the simulated tick event. */\r
                ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );\r
 \r
-               /* The interrupt is now pending - notify the simulated interrupt \r
-               handler thread. */\r
+               /* The interrupt is now pending - notify the simulated interrupt\r
+               handler thread.  Must be outside of a critical section to get here so\r
+               the handler thread can execute immediately pvInterruptEventMutex is\r
+               released. */\r
+               configASSERT( ulCriticalNesting == 0UL );\r
                SetEvent( pvInterruptEvent );\r
 \r
-               /* Give back the mutex so the simulated interrupt handler unblocks \r
-               and can access the interrupt handler variables. */\r
+               /* Give back the mutex so the simulated interrupt handler unblocks\r
+               and can access the interrupt handler variables. */\r
                ReleaseMutex( pvInterruptEventMutex );\r
        }\r
 \r
@@ -225,65 +218,97 @@ TIMECAPS xTimeCaps;
                timeEndPeriod( xTimeCaps.wPeriodMin );\r
        }\r
 \r
-       return pdPASS;\r
+       return pdFALSE;\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
-portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )\r
+StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )\r
 {\r
-xThreadState *pxThreadState = NULL;\r
-char *pcTopOfStack = ( char * ) pxTopOfStack;\r
+ThreadState_t *pxThreadState = NULL;\r
+int8_t *pcTopOfStack = ( int8_t * ) pxTopOfStack;\r
+const SIZE_T xStackSize = 1024; /* Set the size to a small number which will get rounded up to the minimum possible. */\r
 \r
        /* In this simulated case a stack is not initialised, but instead a thread\r
        is created that will execute the task being created.  The thread handles\r
-       the context switching itself.  The xThreadState object is placed onto\r
+       the context switching itself.  The ThreadState_t object is placed onto\r
        the stack that was created for the task - so the stack buffer is still\r
        used, just not in the conventional way.  It will not be used for anything\r
        other than holding this structure. */\r
-       pxThreadState = ( xThreadState * ) ( pcTopOfStack - sizeof( xThreadState ) );\r
+       pxThreadState = ( ThreadState_t * ) ( pcTopOfStack - sizeof( ThreadState_t ) );\r
+\r
+       /* Create the event used to prevent the thread from executing past its yield\r
+       point if the SuspendThread() call that suspends the thread does not take\r
+       effect immediately (it is an asynchronous call). */\r
+       pxThreadState->pvYieldEvent = CreateEvent(  NULL,  /* Default security attributes. */\r
+                                                                                               FALSE, /* Auto reset. */\r
+                                                                                               FALSE, /* Start not signalled. */\r
+                                                                                               NULL );/* No name. */\r
 \r
        /* Create the thread itself. */\r
-       pxThreadState->pvThread = CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );\r
+       pxThreadState->pvThread = CreateThread( NULL, xStackSize, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, NULL );\r
+       configASSERT( pxThreadState->pvThread ); /* See comment where TerminateThread() is called. */\r
        SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );\r
        SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );\r
-       SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );\r
-       \r
-       return ( portSTACK_TYPE * ) pxThreadState;\r
+       SetThreadPriority( pxThreadState->pvThread, portTASK_THREAD_PRIORITY );\r
+\r
+       return ( StackType_t * ) pxThreadState;\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
-portBASE_TYPE xPortStartScheduler( void )\r
+BaseType_t xPortStartScheduler( void )\r
 {\r
-void *pvHandle;\r
-long lSuccess = pdPASS;\r
-xThreadState *pxThreadState;\r
-\r
-       /* Install the interrupt handlers used by the scheduler itself. */\r
-       vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );\r
-       vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );\r
-\r
-       /* Create the events and mutexes that are used to synchronise all the\r
-       threads. */\r
-       pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );\r
-       pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
-\r
-       if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )\r
+void *pvHandle = NULL;\r
+int32_t lSuccess;\r
+ThreadState_t *pxThreadState = NULL;\r
+SYSTEM_INFO xSystemInfo;\r
+\r
+       /* This port runs windows threads with extremely high priority.  All the\r
+       threads execute on the same core - to prevent locking up the host only start\r
+       if the host has multiple cores. */\r
+       GetSystemInfo( &xSystemInfo );\r
+       if( xSystemInfo.dwNumberOfProcessors <= 1 )\r
        {\r
+               printf( "This version of the FreeRTOS Windows port can only be used on multi-core hosts.\r\n" );\r
                lSuccess = pdFAIL;\r
        }\r
-\r
-       /* Set the priority of this thread such that it is above the priority of \r
-       the threads that run tasks.  This higher priority is required to ensure\r
-       simulated interrupts take priority over tasks. */\r
-       pvHandle = GetCurrentThread();\r
-       if( pvHandle == NULL )\r
+       else\r
        {\r
-               lSuccess = pdFAIL;\r
+               lSuccess = pdPASS;\r
+\r
+               /* The highest priority class is used to [try to] prevent other Windows\r
+               activity interfering with FreeRTOS timing too much. */\r
+               if( SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS ) == 0 )\r
+               {\r
+                       printf( "SetPriorityClass() failed\r\n" );\r
+               }\r
+\r
+               /* Install the interrupt handlers used by the scheduler itself. */\r
+               vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );\r
+               vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );\r
+\r
+               /* Create the events and mutexes that are used to synchronise all the\r
+               threads. */\r
+               pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );\r
+               pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
+\r
+               if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )\r
+               {\r
+                       lSuccess = pdFAIL;\r
+               }\r
+\r
+               /* Set the priority of this thread such that it is above the priority of\r
+               the threads that run tasks.  This higher priority is required to ensure\r
+               simulated interrupts take priority over tasks. */\r
+               pvHandle = GetCurrentThread();\r
+               if( pvHandle == NULL )\r
+               {\r
+                       lSuccess = pdFAIL;\r
+               }\r
        }\r
-       \r
+\r
        if( lSuccess == pdPASS )\r
        {\r
-               if( SetThreadPriority( pvHandle, THREAD_PRIORITY_NORMAL ) == 0 )\r
+               if( SetThreadPriority( pvHandle, portSIMULATED_INTERRUPTS_THREAD_PRIORITY ) == 0 )\r
                {\r
                        lSuccess = pdFAIL;\r
                }\r
@@ -294,50 +319,51 @@ xThreadState *pxThreadState;
        if( lSuccess == pdPASS )\r
        {\r
                /* Start the thread that simulates the timer peripheral to generate\r
-               tick interrupts.  The priority is set below that of the simulated \r
+               tick interrupts.  The priority is set below that of the simulated\r
                interrupt handler so the interrupt event mutex is used for the\r
                handshake / overrun protection. */\r
-               pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );\r
+               pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, CREATE_SUSPENDED, NULL );\r
                if( pvHandle != NULL )\r
                {\r
-                       SetThreadPriority( pvHandle, THREAD_PRIORITY_BELOW_NORMAL );\r
+                       SetThreadPriority( pvHandle, portSIMULATED_TIMER_THREAD_PRIORITY );\r
                        SetThreadPriorityBoost( pvHandle, TRUE );\r
                        SetThreadAffinityMask( pvHandle, 0x01 );\r
+                       ResumeThread( pvHandle );\r
                }\r
-               \r
-               /* Start the highest priority task by obtaining its associated thread \r
+\r
+               /* Start the highest priority task by obtaining its associated thread\r
                state structure, in which is stored the thread handle. */\r
-               pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );\r
+               pxThreadState = ( ThreadState_t * ) *( ( size_t * ) pxCurrentTCB );\r
                ulCriticalNesting = portNO_CRITICAL_NESTING;\r
 \r
-               /* Bump up the priority of the thread that is going to run, in the\r
-               hope that this will asist in getting the Windows thread scheduler to\r
-               behave as an embedded engineer might expect. */\r
+               /* Start the first task. */\r
                ResumeThread( pxThreadState->pvThread );\r
 \r
-               /* Handle all simulated interrupts - including yield requests and \r
+               /* Handle all simulated interrupts - including yield requests and\r
                simulated ticks. */\r
                prvProcessSimulatedInterrupts();\r
-       }       \r
-       \r
-       /* Would not expect to return from prvProcessSimulatedInterrupts(), so should \r
+       }\r
+\r
+       /* Would not expect to return from prvProcessSimulatedInterrupts(), so should\r
        not get here. */\r
        return 0;\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
-static unsigned long prvProcessYieldInterrupt( void )\r
+static uint32_t prvProcessYieldInterrupt( void )\r
 {\r
+       /* Always return true as this is a yield. */\r
        return pdTRUE;\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
-static unsigned long prvProcessTickInterrupt( void )\r
+static uint32_t prvProcessTickInterrupt( void )\r
 {\r
-unsigned long ulSwitchRequired;\r
+uint32_t ulSwitchRequired;\r
 \r
        /* Process the tick itself. */\r
-       ulSwitchRequired = ( unsigned long ) xTaskIncrementTick();\r
+       configASSERT( xPortRunning );\r
+       ulSwitchRequired = ( uint32_t ) xTaskIncrementTick();\r
 \r
        return ulSwitchRequired;\r
 }\r
@@ -345,20 +371,36 @@ unsigned long ulSwitchRequired;
 \r
 static void prvProcessSimulatedInterrupts( void )\r
 {\r
-unsigned long ulSwitchRequired, i;\r
-xThreadState *pxThreadState;\r
+uint32_t ulSwitchRequired, i;\r
+ThreadState_t *pxThreadState;\r
 void *pvObjectList[ 2 ];\r
+CONTEXT xContext;\r
 \r
-       /* Going to block on the mutex that ensured exclusive access to the simulated \r
+       /* Going to block on the mutex that ensured exclusive access to the simulated\r
        interrupt objects, and the event that signals that a simulated interrupt\r
        should be processed. */\r
        pvObjectList[ 0 ] = pvInterruptEventMutex;\r
        pvObjectList[ 1 ] = pvInterruptEvent;\r
 \r
+       /* Create a pending tick to ensure the first task is started as soon as\r
+       this thread pends. */\r
+       ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );\r
+       SetEvent( pvInterruptEvent );\r
+\r
+       xPortRunning = pdTRUE;\r
+\r
        for(;;)\r
        {\r
+               xInsideInterrupt = pdFALSE;\r
                WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );\r
 \r
+               /* Cannot be in a critical section to get here.  Tasks that exit a\r
+               critical section will block on a yield mutex to wait for an interrupt to\r
+               process if an interrupt was set pending while the task was inside the\r
+               critical section.  xInsideInterrupt prevents interrupts that contain\r
+               critical sections from doing the same. */\r
+               xInsideInterrupt = pdTRUE;\r
+\r
                /* Used to indicate whether the simulated interrupt processing has\r
                necessitated a context switch to another task/thread. */\r
                ulSwitchRequired = pdFALSE;\r
@@ -368,14 +410,16 @@ void *pvObjectList[ 2 ];
                for( i = 0; i < portMAX_INTERRUPTS; i++ )\r
                {\r
                        /* Is the simulated interrupt pending? */\r
-                       if( ulPendingInterrupts & ( 1UL << i ) )\r
+                       if( ( ulPendingInterrupts & ( 1UL << i ) ) != 0 )\r
                        {\r
                                /* Is a handler installed? */\r
                                if( ulIsrHandler[ i ] != NULL )\r
                                {\r
-                                       /* Run the actual handler. */\r
+                                       /* Run the actual handler.  Handlers return pdTRUE if they\r
+                                       necessitate a context switch. */\r
                                        if( ulIsrHandler[ i ]() != pdFALSE )\r
                                        {\r
+                                               /* A bit mask is used purely to help debugging. */\r
                                                ulSwitchRequired |= ( 1 << i );\r
                                        }\r
                                }\r
@@ -398,17 +442,49 @@ void *pvObjectList[ 2 ];
                        that is already in the running state. */\r
                        if( pvOldCurrentTCB != pxCurrentTCB )\r
                        {\r
-                               /* Suspend the old thread. */\r
-                               pxThreadState = ( xThreadState *) *( ( unsigned long * ) pvOldCurrentTCB );\r
+                               /* Suspend the old thread.  In the cases where the (simulated)\r
+                               interrupt is asynchronous (tick event swapping a task out rather\r
+                               than a task blocking or yielding) it doesn't matter if the\r
+                               'suspend' operation doesn't take effect immediately - if it\r
+                               doesn't it would just be like the interrupt occurring slightly\r
+                               later.  In cases where the yield was caused by a task blocking\r
+                               or yielding then the task will block on a yield event after the\r
+                               yield operation in case the 'suspend' operation doesn't take\r
+                               effect immediately.  */\r
+                               pxThreadState = ( ThreadState_t *) *( ( size_t * ) pvOldCurrentTCB );\r
                                SuspendThread( pxThreadState->pvThread );\r
 \r
-                               /* Obtain the state of the task now selected to enter the \r
+                               /* Ensure the thread is actually suspended by performing a\r
+                               synchronous operation that can only complete when the thread is\r
+                               actually suspended.  The code below asks for dummy register\r
+                               data. Experimentation shows that these two lines don't appear\r
+                               to do anything now, but according to\r
+                               https://devblogs.microsoft.com/oldnewthing/20150205-00/?p=44743\r
+                               they do - so as they do not harm (slight run-time hit). */\r
+                               xContext.ContextFlags = CONTEXT_INTEGER;\r
+                               ( void ) GetThreadContext( pxThreadState->pvThread, &xContext );\r
+\r
+                               /* Obtain the state of the task now selected to enter the\r
                                Running state. */\r
-                               pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );\r
+                               pxThreadState = ( ThreadState_t * ) ( *( size_t *) pxCurrentTCB );\r
+\r
+                               /* pxThreadState->pvThread can be NULL if the task deleted\r
+                               itself - but a deleted task should never be resumed here. */\r
+                               configASSERT( pxThreadState->pvThread != NULL );\r
                                ResumeThread( pxThreadState->pvThread );\r
                        }\r
                }\r
 \r
+               /* If the thread that is about to be resumed stopped running\r
+               because it yielded then it will wait on an event when it resumed\r
+               (to ensure it does not continue running after the call to\r
+               SuspendThread() above as SuspendThread() is asynchronous).\r
+               Signal the event to ensure the thread can proceed now it is\r
+               valid for it to do so.  Signaling the event is benign in the case that\r
+               the task was switched out asynchronously by an interrupt as the event\r
+               is reset before the task blocks on it. */\r
+               pxThreadState = ( ThreadState_t * ) ( *( size_t *) pxCurrentTCB );\r
+               SetEvent( pxThreadState->pvYieldEvent );\r
                ReleaseMutex( pvInterruptEventMutex );\r
        }\r
 }\r
@@ -416,47 +492,123 @@ void *pvObjectList[ 2 ];
 \r
 void vPortDeleteThread( void *pvTaskToDelete )\r
 {\r
-xThreadState *pxThreadState;\r
+ThreadState_t *pxThreadState;\r
+uint32_t ulErrorCode;\r
 \r
-       WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
+       /* Remove compiler warnings if configASSERT() is not defined. */\r
+       ( void ) ulErrorCode;\r
 \r
        /* Find the handle of the thread being deleted. */\r
-       pxThreadState = ( xThreadState * ) ( *( unsigned long *) pvTaskToDelete );\r
-       TerminateThread( pxThreadState->pvThread, 0 );\r
+       pxThreadState = ( ThreadState_t * ) ( *( size_t *) pvTaskToDelete );\r
+\r
+       /* Check that the thread is still valid, it might have been closed by\r
+       vPortCloseRunningThread() - which will be the case if the task associated\r
+       with the thread originally deleted itself rather than being deleted by a\r
+       different task. */\r
+       if( pxThreadState->pvThread != NULL )\r
+       {\r
+               WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
+\r
+               /* !!! This is not a nice way to terminate a thread, and will eventually\r
+               result in resources being depleted if tasks frequently delete other\r
+               tasks (rather than deleting themselves) as the task stacks will not be\r
+               freed. */\r
+               ulErrorCode = TerminateThread( pxThreadState->pvThread, 0 );\r
+               configASSERT( ulErrorCode );\r
+\r
+               ulErrorCode = CloseHandle( pxThreadState->pvThread );\r
+               configASSERT( ulErrorCode );\r
 \r
-       ReleaseMutex( pvInterruptEventMutex );\r
+               ReleaseMutex( pvInterruptEventMutex );\r
+       }\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+void vPortCloseRunningThread( void *pvTaskToDelete, volatile BaseType_t *pxPendYield )\r
+{\r
+ThreadState_t *pxThreadState;\r
+void *pvThread;\r
+uint32_t ulErrorCode;\r
+\r
+       /* Remove compiler warnings if configASSERT() is not defined. */\r
+       ( void ) ulErrorCode;\r
+\r
+       /* Find the handle of the thread being deleted. */\r
+       pxThreadState = ( ThreadState_t * ) ( *( size_t *) pvTaskToDelete );\r
+       pvThread = pxThreadState->pvThread;\r
+\r
+       /* Raise the Windows priority of the thread to ensure the FreeRTOS scheduler\r
+       does not run and swap it out before it is closed.  If that were to happen\r
+       the thread would never run again and effectively be a thread handle and\r
+       memory leak. */\r
+       SetThreadPriority( pvThread, portDELETE_SELF_THREAD_PRIORITY );\r
+\r
+       /* This function will not return, therefore a yield is set as pending to\r
+       ensure a context switch occurs away from this thread on the next tick. */\r
+       *pxPendYield = pdTRUE;\r
+\r
+       /* Mark the thread associated with this task as invalid so\r
+       vPortDeleteThread() does not try to terminate it. */\r
+       pxThreadState->pvThread = NULL;\r
+\r
+       /* Close the thread. */\r
+       ulErrorCode = CloseHandle( pvThread );\r
+       configASSERT( ulErrorCode );\r
+\r
+       /* This is called from a critical section, which must be exited before the\r
+       thread stops. */\r
+       taskEXIT_CRITICAL();\r
+       CloseHandle( pxThreadState->pvYieldEvent );\r
+       ExitThread( 0 );\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
 void vPortEndScheduler( void )\r
 {\r
-       /* This function IS NOT TESTED! */\r
-       TerminateProcess( GetCurrentProcess(), 0 );\r
+       exit( 0 );\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
-void vPortGenerateSimulatedInterrupt( unsigned long ulInterruptNumber )\r
+void vPortGenerateSimulatedInterrupt( uint32_t ulInterruptNumber )\r
 {\r
+ThreadState_t *pxThreadState = ( ThreadState_t *) *( ( size_t * ) pxCurrentTCB );\r
+\r
+       configASSERT( xPortRunning );\r
+\r
        if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )\r
        {\r
-               /* Yield interrupts are processed even when critical nesting is non-zero. */\r
                WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
                ulPendingInterrupts |= ( 1 << ulInterruptNumber );\r
 \r
-               /* The simulated interrupt is now held pending, but don't actually process it\r
-               yet if this call is within a critical section.  It is possible for this to\r
-               be in a critical section as calls to wait for mutexes are accumulative. */\r
-               if( ulCriticalNesting == 0 )\r
+               /* The simulated interrupt is now held pending, but don't actually\r
+               process it yet if this call is within a critical section.  It is\r
+               possible for this to be in a critical section as calls to wait for\r
+               mutexes are accumulative.  If in a critical section then the event\r
+               will get set when the critical section nesting count is wound back\r
+               down to zero. */\r
+               if( ulCriticalNesting == portNO_CRITICAL_NESTING )\r
                {\r
-                       SetEvent( pvInterruptEvent );                   \r
+                       SetEvent( pvInterruptEvent );\r
+\r
+                       /* Going to wait for an event - make sure the event is not already\r
+                       signaled. */\r
+                       ResetEvent( pxThreadState->pvYieldEvent );\r
                }\r
 \r
                ReleaseMutex( pvInterruptEventMutex );\r
+               if( ulCriticalNesting == portNO_CRITICAL_NESTING )\r
+               {\r
+                       /* An interrupt was pended so ensure to block to allow it to\r
+                       execute.  In most cases the (simulated) interrupt will have\r
+                       executed before the next line is reached - so this is just to make\r
+                       sure. */\r
+                       WaitForSingleObject( pxThreadState->pvYieldEvent, INFINITE );\r
+               }\r
        }\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
-void vPortSetInterruptHandler( unsigned long ulInterruptNumber, unsigned long (*pvHandler)( void ) )\r
+void vPortSetInterruptHandler( uint32_t ulInterruptNumber, uint32_t (*pvHandler)( void ) )\r
 {\r
        if( ulInterruptNumber < portMAX_INTERRUPTS )\r
        {\r
@@ -476,23 +628,20 @@ void vPortSetInterruptHandler( unsigned long ulInterruptNumber, unsigned long (*
 \r
 void vPortEnterCritical( void )\r
 {\r
-       if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )\r
+       if( xPortRunning == pdTRUE )\r
        {\r
                /* The interrupt event mutex is held for the entire critical section,\r
                effectively disabling (simulated) interrupts. */\r
                WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
-               ulCriticalNesting++;\r
        }\r
-       else\r
-       {\r
-               ulCriticalNesting++;\r
-       }       \r
+\r
+       ulCriticalNesting++;\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
 void vPortExitCritical( void )\r
 {\r
-long lMutexNeedsReleasing;\r
+int32_t lMutexNeedsReleasing, lWaitForYield = pdFALSE;\r
 \r
        /* The interrupt event mutex should already be held by this thread as it was\r
        obtained on entry to the critical section. */\r
@@ -501,33 +650,51 @@ long lMutexNeedsReleasing;
 \r
        if( ulCriticalNesting > portNO_CRITICAL_NESTING )\r
        {\r
-               if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )\r
-               {\r
-                       ulCriticalNesting--;\r
+               ulCriticalNesting--;\r
 \r
-                       /* Were any interrupts set to pending while interrupts were \r
+               /* Don't need to wait for any pending interrupts to execute if the\r
+               critical section was exited from inside an interrupt. */\r
+               if( ( ulCriticalNesting == portNO_CRITICAL_NESTING ) && ( xInsideInterrupt == pdFALSE ) )\r
+               {\r
+                       /* Were any interrupts set to pending while interrupts were\r
                        (simulated) disabled? */\r
                        if( ulPendingInterrupts != 0UL )\r
                        {\r
-                               SetEvent( pvInterruptEvent );\r
+                               ThreadState_t *pxThreadState = ( ThreadState_t *) *( ( size_t * ) pxCurrentTCB );\r
 \r
-                               /* Mutex will be released now, so does not require releasing\r
-                               on function exit. */\r
+                               configASSERT( xPortRunning );\r
+\r
+                               /* The interrupt won't actually executed until\r
+                               pvInterruptEventMutex is released as it waits on both\r
+                               pvInterruptEventMutex and pvInterruptEvent.\r
+                               pvInterruptEvent is only set when the simulated\r
+                               interrupt is pended if the interrupt is pended\r
+                               from outside a critical section - hence it is set\r
+                               here. */\r
+                               SetEvent( pvInterruptEvent );\r
+                               /* The calling task is going to wait for an event to ensure the\r
+                               interrupt that is pending executes immediately after the\r
+                               critical section is exited - so make sure the event is not\r
+                               already signaled. */\r
+                               ResetEvent( pxThreadState->pvYieldEvent );\r
+                               lWaitForYield = pdTRUE;\r
+\r
+                               /* Mutex will be released now so the (simulated) interrupt can\r
+                               execute, so does not require releasing on function exit. */\r
                                lMutexNeedsReleasing = pdFALSE;\r
                                ReleaseMutex( pvInterruptEventMutex );\r
+                               WaitForSingleObject( pxThreadState->pvYieldEvent, INFINITE );\r
                        }\r
                }\r
-               else\r
-               {\r
-                       /* Tick interrupts will still not be processed as the critical\r
-                       nesting depth will not be zero. */\r
-                       ulCriticalNesting--;\r
-               }\r
        }\r
 \r
-       if( lMutexNeedsReleasing == pdTRUE )\r
+       if( pvInterruptEventMutex != NULL )\r
        {\r
-               ReleaseMutex( pvInterruptEventMutex );\r
+               if( lMutexNeedsReleasing == pdTRUE )\r
+               {\r
+                       configASSERT( xPortRunning );\r
+                       ReleaseMutex( pvInterruptEventMutex );\r
+               }\r
        }\r
 }\r
 /*-----------------------------------------------------------*/\r