/* * FreeRTOS Kernel V10.2.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* Standard includes. */ #include #include /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" #ifdef __GNUC__ #include "mmsystem.h" #else #pragma comment(lib, "winmm.lib") #endif #define portMAX_INTERRUPTS ( ( uint32_t ) sizeof( uxPendingInterrupts ) * 8UL ) /* The number of bits in uxPendingInterrupts. */ #define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 ) /* The priorities at which the various components of the simulation execute. */ #define portDELETE_SELF_THREAD_PRIORITY THREAD_PRIORITY_HIGHEST /* Must be highest. */ #define portSIMULATED_INTERRUPTS_THREAD_PRIORITY THREAD_PRIORITY_HIGHEST #define portSIMULATED_TIMER_THREAD_PRIORITY THREAD_PRIORITY_ABOVE_NORMAL #define portTASK_THREAD_PRIORITY THREAD_PRIORITY_NORMAL /* * Created as a high priority thread, this function uses a timer to simulate * a tick interrupt being generated on an embedded target. In this Windows * environment the timer does not achieve anything approaching real time * performance though. */ static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter ); /* * Process all the simulated interrupts - each represented by a bit in * uxPendingInterrupts variable. */ static void prvProcessSimulatedInterrupts( void ); /* * Interrupt handlers used by the kernel itself. These are executed from the * simulated interrupt handler thread. */ static uint32_t prvProcessYieldInterrupt( void ); static uint32_t prvProcessTickInterrupt( void ); /* * Called when the process exits to let Windows know the high timer resolution * is no longer required. */ static BOOL WINAPI prvEndProcess( DWORD dwCtrlType ); /*-----------------------------------------------------------*/ /* The WIN32 simulator runs each task in a thread. The context switching is managed by the threads, so the task stack does not have to be managed directly, although the task stack is still used to hold an xThreadState structure this is the only thing it will ever hold. The structure indirectly maps the task handle to a thread handle. */ typedef struct { /* Handle of the thread that executes the task. */ void *pvThread; /* An event that is used to block the task until it is scheduled to run */ void* pvTaskScheduledEvent; /* Notifies the scheduler when the task initialization is complete */ void* pvTaskReadyEvent; TaskFunction_t pxCode; void* pvParameters; } xThreadState; /* Simulated interrupts waiting to be processed. */ static volatile UBaseType_t uxPendingInterrupts = 0UL; /* An event used to inform the simulated interrupt processing thread (a high priority thread that simulated interrupt processing) that an interrupt is pending. */ static void *pvInterruptEvent = NULL; /* Mutex used to protect all the simulated interrupt variables that are accessed by multiple threads. */ static void *pvInterruptEventMutex = NULL; /* An event used to enable/disable the simulated timer peripheral */ static void* pvTimerEnabledEvent = NULL; /* The critical nesting count for the currently executing task. This is initialised to a non-zero value so interrupts do not become enabled during the initialisation phase. As each task has its own critical nesting value ulCriticalNesting will get set to zero when the first task runs. This initialisation is probably not critical in this simulated environment as the simulated interrupt handlers do not get created until the FreeRTOS scheduler is started anyway. */ static uint32_t ulCriticalNesting = 9999UL; /* Handlers for all the simulated software interrupts. The first two positions are used for the Yield and Tick interrupts so are handled slightly differently, all the other interrupts can be user defined. */ static uint32_t (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 }; /* Pointer to the TCB of the currently executing task. */ extern void *pxCurrentTCB; static DWORD xThreadStateTlsSlot = TLS_OUT_OF_INDEXES; UBaseType_t uxPortInISR = 0u; static const LONGLONG xTickPeriodUs = 1000000LL / configTICK_RATE_HZ; static LONGLONG xTickAccumulator; static LARGE_INTEGER xLastTickTime; static LARGE_INTEGER xPerformanceFrequency; /*-----------------------------------------------------------*/ static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter ) { TickType_t xMinimumWindowsBlockTime; TIMECAPS xTimeCaps; /* Set the timer resolution to the maximum possible. */ if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR ) { xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin; timeBeginPeriod( xTimeCaps.wPeriodMin ); /* Register an exit handler so the timeBeginPeriod() function can be matched with a timeEndPeriod() when the application exits. */ SetConsoleCtrlHandler( prvEndProcess, TRUE ); } else { xMinimumWindowsBlockTime = ( TickType_t ) 20; } /* Just to prevent compiler warnings. */ ( void ) lpParameter; for( ;; ) { WaitForSingleObject( pvTimerEnabledEvent, INFINITE ); /* Wait until the timer expires and we can access the simulated interrupt variables. *NOTE* this is not a 'real time' way of generating tick events as the next wake time should be relative to the previous wake time, not the time that Sleep() is called. It is done this way to prevent overruns in this very non real time simulated/emulated environment. */ if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime ) { Sleep( xMinimumWindowsBlockTime ); } else { Sleep( portTICK_PERIOD_MS ); } vPortGenerateSimulatedInterrupt( portINTERRUPT_TICK ); } #ifdef __GNUC__ /* Should never reach here - MingW complains if you leave this line out, MSVC complains if you put it in. */ return 0; #endif } /*-----------------------------------------------------------*/ static BOOL WINAPI prvEndProcess( DWORD dwCtrlType ) { TIMECAPS xTimeCaps; ( void ) dwCtrlType; if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR ) { /* Match the call to timeBeginPeriod( xTimeCaps.wPeriodMin ) made when the process started with a timeEndPeriod() as the process exits. */ timeEndPeriod( xTimeCaps.wPeriodMin ); } return pdFALSE; } /*-----------------------------------------------------------*/ static DWORD xTaskThreadProc( LPVOID lpParameter ) { xThreadState* pxThreadState = ( xThreadState * ) lpParameter; /* set the thread affinity and priority */ SetThreadAffinityMask( pxThreadState->pvThread, (1u << configCPU_AFFINITY) ); SetThreadPriorityBoost( pxThreadState->pvThread, TRUE ); SetThreadPriority( pxThreadState->pvThread, portTASK_THREAD_PRIORITY ); /* indicate that we're ready to run */ SetEvent( pxThreadState->pvTaskReadyEvent ); /* wait until we've been scheduled to run */ WaitForSingleObject( pxThreadState->pvTaskScheduledEvent, INFINITE ); /* enter a critical section so we can safely call Windows API functions */ taskENTER_CRITICAL(); /* store the thread state in the thread local storage slot */ configASSERT( xThreadStateTlsSlot != TLS_OUT_OF_INDEXES ); TlsSetValue( xThreadStateTlsSlot, pxThreadState ); /* set the thread description for easy debugging (only available in Windows 10) */ #if defined(_MSC_VER) && (_WIN32_WINNT >= _WIN32_WINNT_WIN10) { WCHAR pxThreadDescription[128]; swprintf(pxThreadDescription, sizeof(pxThreadDescription) / sizeof(pxThreadDescription[0]), L"FreeRTOS Task: %hs", pcTaskGetName(NULL)); SetThreadDescription(pxThreadState->pvThread, pxThreadDescription); } #endif taskEXIT_CRITICAL(); /* call the task function */ pxThreadState->pxCode( pxThreadState->pvParameters ); return 0; } /*-----------------------------------------------------------*/ StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) { xThreadState *pxThreadState = NULL; int8_t *pcTopOfStack = ( int8_t * ) pxTopOfStack; const SIZE_T xStackSize = 1024; /* Set the size to a small number which will get rounded up to the minimum possible. */ /* In this simulated case a stack is not initialised, but instead a thread is created that will execute the task being created. The thread handles the context switching itself. The xThreadState object is placed onto the stack that was created for the task - so the stack buffer is still used, just not in the conventional way. It will not be used for anything other than holding this structure. */ pxThreadState = ( xThreadState * ) ( pcTopOfStack - sizeof( xThreadState ) ); memset(pxThreadState, 0, sizeof(*pxThreadState)); pxThreadState->pxCode = pxCode; pxThreadState->pvParameters = pvParameters; /* Create the task ready event */ pxThreadState->pvTaskReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL); configASSERT( pxThreadState->pvTaskReadyEvent ); /* Create the task scheduled event */ pxThreadState->pvTaskScheduledEvent = CreateEvent(NULL, TRUE, FALSE, NULL); configASSERT( pxThreadState->pvTaskScheduledEvent ); /* Create the thread itself. */ pxThreadState->pvThread = CreateThread( NULL, xStackSize, xTaskThreadProc, pxThreadState, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL ); configASSERT( pxThreadState->pvThread ); /* See comment where TerminateThread() is called. */ /* Wait for the task ready event. We must be sure that the thread is fully initialized before returning from this function so the scheduler does not try to suspend it during initialization. */ WaitForSingleObject( pxThreadState->pvTaskReadyEvent, INFINITE ); return ( StackType_t * ) pxThreadState; } /*-----------------------------------------------------------*/ BaseType_t xPortStartScheduler( void ) { void *pvHandle = NULL; int32_t lSuccess; xThreadState *pxThreadState = NULL; SYSTEM_INFO xSystemInfo; /* This port runs windows threads with extremely high priority. All the threads execute on the same core - to prevent locking up the host only start if the host has multiple cores. */ GetSystemInfo( &xSystemInfo ); if( xSystemInfo.dwNumberOfProcessors <= 1 ) { printf( "This version of the FreeRTOS Windows port can only be used on multi-core hosts.\r\n" ); lSuccess = pdFAIL; } else { lSuccess = pdPASS; /* Install the interrupt handlers used by the scheduler itself. */ vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt ); vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt ); /* Create the events and mutexes that are used to synchronise all the threads. */ pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL ); pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); pvTimerEnabledEvent = CreateEvent( NULL, TRUE, TRUE, NULL ); if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) || ( pvTimerEnabledEvent == NULL ) ) { lSuccess = pdFAIL; } /* Allocate the thread state tls slot */ xThreadStateTlsSlot = TlsAlloc(); if ( xThreadStateTlsSlot == TLS_OUT_OF_INDEXES ) { lSuccess = pdFAIL; } /* Set the priority of this thread such that it is above the priority of the threads that run tasks. This higher priority is required to ensure simulated interrupts take priority over tasks. */ pvHandle = GetCurrentThread(); if( pvHandle == NULL ) { lSuccess = pdFAIL; } } if( lSuccess == pdPASS ) { if( SetThreadPriority( pvHandle, portSIMULATED_INTERRUPTS_THREAD_PRIORITY ) == 0 ) { lSuccess = pdFAIL; } SetThreadPriorityBoost( pvHandle, TRUE ); SetThreadAffinityMask( pvHandle, (1u << configCPU_AFFINITY)); } if( lSuccess == pdPASS ) { /* Start the thread that simulates the timer peripheral to generate tick interrupts. The priority is set below that of the simulated interrupt handler so the interrupt event mutex is used for the handshake / overrun protection. */ pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, CREATE_SUSPENDED, NULL ); if( pvHandle != NULL ) { SetThreadPriority( pvHandle, portSIMULATED_TIMER_THREAD_PRIORITY ); SetThreadPriorityBoost( pvHandle, TRUE ); SetThreadAffinityMask( pvHandle, (1u << configCPU_AFFINITY)); ResumeThread( pvHandle ); } /* Start the highest priority task by obtaining its associated thread state structure, in which is stored the thread handle. */ pxThreadState = ( xThreadState * ) *( ( size_t * ) pxCurrentTCB ); ulCriticalNesting = portNO_CRITICAL_NESTING; /* Bump up the priority of the thread that is going to run, in the hope that this will assist in getting the Windows thread scheduler to behave as an embedded engineer might expect. */ ResumeThread( pxThreadState->pvThread ); /* Handle all simulated interrupts - including yield requests and simulated ticks. */ prvProcessSimulatedInterrupts(); } /* Would not expect to return from prvProcessSimulatedInterrupts(), so should not get here. */ return 0; } /*-----------------------------------------------------------*/ static uint32_t prvProcessYieldInterrupt( void ) { return pdTRUE; } /*-----------------------------------------------------------*/ static uint32_t prvProcessTickInterrupt( void ) { LARGE_INTEGER xCurrentTime; BaseType_t xReschedule = pdFALSE; QueryPerformanceCounter(&xCurrentTime); xTickAccumulator += ((xCurrentTime.QuadPart - xLastTickTime.QuadPart) * 1000000LL) / xPerformanceFrequency.QuadPart; xLastTickTime = xCurrentTime; if (xTickAccumulator >= 10u * xTickPeriodUs) { xTickAccumulator = 0u; } while (xTickAccumulator >= xTickPeriodUs) { xTickAccumulator -= xTickPeriodUs; if (xTaskIncrementTick() == pdTRUE) { xReschedule = pdTRUE; } } return (uint32_t)xReschedule; } /*-----------------------------------------------------------*/ static void prvProcessSimulatedInterrupts( void ) { uint32_t i; BaseType_t xSwitchRequired; xThreadState *pxThreadState; void *pvObjectList[ 2 ]; CONTEXT xContext; /* Going to block on the mutex that ensured exclusive access to the simulated interrupt objects, and the event that signals that a simulated interrupt should be processed. */ pvObjectList[ 0 ] = pvInterruptEventMutex; pvObjectList[ 1 ] = pvInterruptEvent; QueryPerformanceFrequency(&xPerformanceFrequency); QueryPerformanceCounter(&xLastTickTime); /* Create a pending tick to ensure the first task is started as soon as this thread pends. */ uxPendingInterrupts |= ( 1U << portINTERRUPT_TICK ); SetEvent( pvInterruptEvent ); for(;;) { WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE ); /* Used to indicate whether the simulated interrupt processing has necessitated a context switch to another task/thread. */ xSwitchRequired = pdFALSE; /* Obtain the current thread state */ pxThreadState = (xThreadState*)(*(size_t*)pxCurrentTCB); /* Tell the task that it is not scheduled to run */ ResetEvent( pxThreadState->pvTaskScheduledEvent ); uxPortInISR = 1u; /* For each interrupt we are interested in processing, each of which is represented by a bit in the uxPendingInterrupts variable. */ for( i = 0; i < portMAX_INTERRUPTS && uxPendingInterrupts != 0U; i++ ) { /* Is the simulated interrupt pending? */ if( uxPendingInterrupts & ( 1U << i ) ) { /* Is a handler installed? */ if( ulIsrHandler[ i ] != NULL ) { /* Run the actual handler. */ if( ulIsrHandler[ i ]() != pdFALSE ) { xSwitchRequired = pdTRUE; } } /* Clear the interrupt pending bit. */ uxPendingInterrupts &= ~( 1U << i ); } } uxPortInISR = 0U; if( xSwitchRequired != pdFALSE ) { void *pvOldCurrentTCB; pvOldCurrentTCB = pxCurrentTCB; /* Select the next task to run. */ vTaskSwitchContext(); /* If the task selected to enter the running state is not the task that is already in the running state. */ if( pvOldCurrentTCB != pxCurrentTCB ) { /* Suspend the old thread. */ pxThreadState = ( xThreadState *) *( ( size_t * ) pvOldCurrentTCB ); SuspendThread( pxThreadState->pvThread ); /* Ensure the thread is actually suspended by performing a synchronous operation that can only complete when the thread is actually suspended. The below code asks for dummy register data. */ xContext.ContextFlags = CONTEXT_INTEGER; ( void ) GetThreadContext( pxThreadState->pvThread, &xContext ); /* Obtain the state of the task now selected to enter the Running state. */ pxThreadState = ( xThreadState * ) ( *( size_t *) pxCurrentTCB ); ResumeThread( pxThreadState->pvThread ); } } /* Notify the task that it can run again */ SetEvent( pxThreadState->pvTaskScheduledEvent ); ReleaseMutex( pvInterruptEventMutex ); } } /*-----------------------------------------------------------*/ void vPortDeleteThread( void *pvTaskToDelete ) { xThreadState *pxThreadState; uint32_t ulErrorCode; /* Remove compiler warnings if configASSERT() is not defined. */ ( void ) ulErrorCode; /* Find the handle of the thread being deleted. */ pxThreadState = ( xThreadState * ) ( *( size_t *) pvTaskToDelete ); /* Check that the thread is still valid, it might have been closed by vPortCloseRunningThread() - which will be the case if the task associated with the thread originally deleted itself rather than being deleted by a different task. */ if( pxThreadState->pvThread != NULL ) { WaitForSingleObject( pvInterruptEventMutex, INFINITE ); /* !!! This is not a nice way to terminate a thread, and will eventually result in resources being depleted if tasks frequently delete other tasks (rather than deleting themselves) as the task stacks will not be freed. */ ulErrorCode = TerminateThread( pxThreadState->pvThread, 0 ); configASSERT( ulErrorCode ); /* Close the task ready event handle */ ulErrorCode = CloseHandle( pxThreadState->pvTaskReadyEvent ); configASSERT(ulErrorCode); pxThreadState->pvTaskReadyEvent = NULL; /* Close the task scheduled event handle */ ulErrorCode = CloseHandle( pxThreadState->pvTaskScheduledEvent ); configASSERT( ulErrorCode ); pxThreadState->pvTaskScheduledEvent = NULL; ulErrorCode = CloseHandle( pxThreadState->pvThread ); configASSERT( ulErrorCode ); ReleaseMutex( pvInterruptEventMutex ); } } /*-----------------------------------------------------------*/ void vPortCloseRunningThread( void *pvTaskToDelete, volatile BaseType_t *pxPendYield ) { xThreadState *pxThreadState; void *pvThread; uint32_t ulErrorCode; /* Remove compiler warnings if configASSERT() is not defined. */ ( void ) ulErrorCode; /* Find the handle of the thread being deleted. */ pxThreadState = ( xThreadState * ) ( *( size_t *) pvTaskToDelete ); pvThread = pxThreadState->pvThread; /* Raise the Windows priority of the thread to ensure the FreeRTOS scheduler does not run and swap it out before it is closed. If that were to happen the thread would never run again and effectively be a thread handle and memory leak. */ SetThreadPriority( pvThread, portDELETE_SELF_THREAD_PRIORITY ); /* This function will not return, therefore a yield is set as pending to ensure a context switch occurs away from this thread on the next tick. */ *pxPendYield = pdTRUE; /* Mark the thread associated with this task as invalid so vPortDeleteThread() does not try to terminate it. */ pxThreadState->pvThread = NULL; /* Remove the thread state from TLS slot */ TlsSetValue( xThreadStateTlsSlot, NULL ); /* Close the interrupt done event handle */ ulErrorCode = CloseHandle( pxThreadState->pvTaskScheduledEvent ); configASSERT( ulErrorCode ); pxThreadState->pvTaskScheduledEvent = NULL; /* Close the thread. */ ulErrorCode = CloseHandle( pvThread ); configASSERT( ulErrorCode ); /* This is called from a critical section, which must be exited before the thread stops. */ taskEXIT_CRITICAL(); ExitThread( 0 ); } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { exit( 0 ); } /*-----------------------------------------------------------*/ static inline xThreadState* prvPortGetThreadState(void) { return (xThreadState*)TlsGetValue(xThreadStateTlsSlot); } /*-----------------------------------------------------------*/ void vPortGenerateSimulatedInterrupt(uint32_t ulInterruptNumber) { taskENTER_CRITICAL(); uxPendingInterrupts |= ( 1U << ulInterruptNumber ); SetEvent( pvInterruptEvent ); taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ void vPortSetInterruptHandler( uint32_t ulInterruptNumber, uint32_t (*pvHandler)( void ) ) { if( ulInterruptNumber < portMAX_INTERRUPTS ) { InterlockedExchangePointer( (PVOID volatile*)&ulIsrHandler[ulInterruptNumber], (PVOID)pvHandler ); } } /*-----------------------------------------------------------*/ void vPortEnterCritical( void ) { if ( pvInterruptEventMutex != NULL ) { WaitForSingleObject( pvInterruptEventMutex, INFINITE ); } ulCriticalNesting++; } /*-----------------------------------------------------------*/ void vPortExitCritical( void ) { xThreadState* pxThreadState = prvPortGetThreadState(); configASSERT( ulCriticalNesting != 0UL ); ulCriticalNesting--; if ( pxThreadState != NULL && ulCriticalNesting == 0UL && uxPendingInterrupts != 0U ) { ResetEvent( pxThreadState->pvTaskScheduledEvent ); } if ( pvInterruptEventMutex != NULL ) { ReleaseMutex( pvInterruptEventMutex ); } if ( pxThreadState != NULL ) { /* Wait until we're scheduled to run again. This will keep the task from returning if it has been suspended but it hasn't taken affect yet. */ WaitForSingleObject( pxThreadState->pvTaskScheduledEvent, INFINITE ); } } /*-----------------------------------------------------------*/ #if configUSE_TICKLESS_IDLE /* Define the function that is called by portSUPPRESS_TICKS_AND_SLEEP(). */ void vPortSupressTicksAndSleep( TickType_t xExpectedIdleTime ) { eSleepModeStatus eSleepStatus; /* Read the current time from a time source that will remain operational while the microcontroller is in a low power state. */ /* We'll use xLastTickTime for this */ /* Stop the timer that is generating the tick interrupt. */ /* Enter a critical section that will not effect interrupts bringing the MCU out of sleep mode. */ ResetEvent( pvTimerEnabledEvent ); /* Ensure it is still ok to enter the sleep mode. */ eSleepStatus = eTaskConfirmSleepModeStatus(); if( eSleepStatus == eAbortSleep ) { /* A task has been moved out of the Blocked state since this macro was executed, or a context siwth is being held pending. Do not enter a sleep state. Restart the tick and exit the critical section. */ SetEvent( pvTimerEnabledEvent ); } else { if( eSleepStatus == eNoTasksWaitingTimeout ) { /* It is not necessary to configure an interrupt to bring the microcontroller out of its low power state at a fixed time in the future. */ WaitForSingleObject(pvInterruptEvent, INFINITE); } else { /* Configure an interrupt to bring the microcontroller out of its low power state at the time the kernel next needs to execute. The interrupt must be generated from a source that remains operational when the microcontroller is in a low power state. */ WaitForSingleObject(pvInterruptEvent, (xExpectedIdleTime * 1000UL) / configTICK_RATE_HZ); /* Determine how long the microcontroller was actually in a low power state for, which will be less than xExpectedIdleTime if the microcontroller was brought out of low power mode by an interrupt other than that configured by the vSetWakeTimeInterrupt() call. Note that the scheduler is suspended before portSUPPRESS_TICKS_AND_SLEEP() is called, and resumed when portSUPPRESS_TICKS_AND_SLEEP() returns. Therefore no other tasks will execute until this function completes. */ /* Correct the kernels tick count to account for the time the microcontroller spent in its low power state. */ prvProcessTickInterrupt(); } /* Exit the critical section - it might be possible to do this immediately after the prvSleep() calls. */ /* Restart the timer that is generating the tick interrupt. */ SetEvent( pvTimerEnabledEvent ); } } #endif