2 FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.
\r
5 VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
\r
7 ***************************************************************************
\r
9 * FreeRTOS provides completely free yet professionally developed, *
\r
10 * robust, strictly quality controlled, supported, and cross *
\r
11 * platform software that has become a de facto standard. *
\r
13 * Help yourself get started quickly and support the FreeRTOS *
\r
14 * project by purchasing a FreeRTOS tutorial book, reference *
\r
15 * manual, or both from: http://www.FreeRTOS.org/Documentation *
\r
19 ***************************************************************************
\r
21 This file is part of the FreeRTOS distribution.
\r
23 FreeRTOS is free software; you can redistribute it and/or modify it under
\r
24 the terms of the GNU General Public License (version 2) as published by the
\r
25 Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
\r
27 >>! NOTE: The modification to the GPL is included to allow you to distribute
\r
28 >>! a combined work that includes FreeRTOS without being obliged to provide
\r
29 >>! the source code for proprietary components outside of the FreeRTOS
\r
32 FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
\r
33 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
\r
34 FOR A PARTICULAR PURPOSE. Full license text is available from the following
\r
35 link: http://www.freertos.org/a00114.html
\r
39 ***************************************************************************
\r
41 * Having a problem? Start by reading the FAQ "My application does *
\r
42 * not run, what could be wrong?" *
\r
44 * http://www.FreeRTOS.org/FAQHelp.html *
\r
46 ***************************************************************************
\r
48 http://www.FreeRTOS.org - Documentation, books, training, latest versions,
\r
49 license and Real Time Engineers Ltd. contact details.
\r
51 http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
\r
52 including FreeRTOS+Trace - an indispensable productivity tool, a DOS
\r
53 compatible FAT file system, and our tiny thread aware UDP/IP stack.
\r
55 http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
\r
56 Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS
\r
57 licenses offer ticketed support, indemnification and middleware.
\r
59 http://www.SafeRTOS.com - High Integrity Systems also provide a safety
\r
60 engineered and independently SIL3 certified version for use in safety and
\r
61 mission critical applications that require provable dependability.
\r
66 /* Scheduler includes. */
\r
67 #include "FreeRTOS.h"
\r
72 #include "mmsystem.h"
\r
74 #pragma comment(lib, "winmm.lib")
\r
77 #define portMAX_INTERRUPTS ( ( unsigned long ) sizeof( unsigned long ) * 8UL ) /* The number of bits in an unsigned long. */
\r
78 #define portNO_CRITICAL_NESTING ( ( unsigned long ) 0 )
\r
81 * Created as a high priority thread, this function uses a timer to simulate
\r
82 * a tick interrupt being generated on an embedded target. In this Windows
\r
83 * environment the timer does not achieve anything approaching real time
\r
84 * performance though.
\r
86 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );
\r
89 * Process all the simulated interrupts - each represented by a bit in
\r
90 * ulPendingInterrupts variable.
\r
92 static void prvProcessSimulatedInterrupts( void );
\r
95 * Interrupt handlers used by the kernel itself. These are executed from the
\r
96 * simulated interrupt handler thread.
\r
98 static unsigned long prvProcessYieldInterrupt( void );
\r
99 static unsigned long prvProcessTickInterrupt( void );
\r
102 * Called when the process exits to let Windows know the high timer resolution
\r
103 * is no longer required.
\r
105 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType );
\r
107 /*-----------------------------------------------------------*/
\r
109 /* The WIN32 simulator runs each task in a thread. The context switching is
\r
110 managed by the threads, so the task stack does not have to be managed directly,
\r
111 although the task stack is still used to hold an xThreadState structure this is
\r
112 the only thing it will ever hold. The structure indirectly maps the task handle
\r
113 to a thread handle. */
\r
116 /* Handle of the thread that executes the task. */
\r
121 /* Simulated interrupts waiting to be processed. This is a bit mask where each
\r
122 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
\r
123 static volatile unsigned long ulPendingInterrupts = 0UL;
\r
125 /* An event used to inform the simulated interrupt processing thread (a high
\r
126 priority thread that simulated interrupt processing) that an interrupt is
\r
128 static void *pvInterruptEvent = NULL;
\r
130 /* Mutex used to protect all the simulated interrupt variables that are accessed
\r
131 by multiple threads. */
\r
132 static void *pvInterruptEventMutex = NULL;
\r
134 /* The critical nesting count for the currently executing task. This is
\r
135 initialised to a non-zero value so interrupts do not become enabled during
\r
136 the initialisation phase. As each task has its own critical nesting value
\r
137 ulCriticalNesting will get set to zero when the first task runs. This
\r
138 initialisation is probably not critical in this simulated environment as the
\r
139 simulated interrupt handlers do not get created until the FreeRTOS scheduler is
\r
141 static unsigned long ulCriticalNesting = 9999UL;
\r
143 /* Handlers for all the simulated software interrupts. The first two positions
\r
144 are used for the Yield and Tick interrupts so are handled slightly differently,
\r
145 all the other interrupts can be user defined. */
\r
146 static unsigned long (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
\r
148 /* Pointer to the TCB of the currently executing task. */
\r
149 extern void *pxCurrentTCB;
\r
151 /* Used to ensure nothing is processed during the startup sequence. */
\r
152 static portBASE_TYPE xPortRunning = pdFALSE;
\r
154 /*-----------------------------------------------------------*/
\r
156 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
\r
158 portTickType xMinimumWindowsBlockTime;
\r
159 TIMECAPS xTimeCaps;
\r
161 /* Set the timer resolution to the maximum possible. */
\r
162 if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
\r
164 xMinimumWindowsBlockTime = ( portTickType ) xTimeCaps.wPeriodMin;
\r
165 timeBeginPeriod( xTimeCaps.wPeriodMin );
\r
167 /* Register an exit handler so the timeBeginPeriod() function can be
\r
168 matched with a timeEndPeriod() when the application exits. */
\r
169 SetConsoleCtrlHandler( prvEndProcess, TRUE );
\r
173 xMinimumWindowsBlockTime = ( portTickType ) 20;
\r
176 /* Just to prevent compiler warnings. */
\r
177 ( void ) lpParameter;
\r
181 /* Wait until the timer expires and we can access the simulated interrupt
\r
182 variables. *NOTE* this is not a 'real time' way of generating tick
\r
183 events as the next wake time should be relative to the previous wake
\r
184 time, not the time that Sleep() is called. It is done this way to
\r
185 prevent overruns in this very non real time simulated/emulated
\r
187 if( portTICK_RATE_MS < xMinimumWindowsBlockTime )
\r
189 Sleep( xMinimumWindowsBlockTime );
\r
193 Sleep( portTICK_RATE_MS );
\r
196 configASSERT( xPortRunning );
\r
198 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
200 /* The timer has expired, generate the simulated tick event. */
\r
201 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
203 /* The interrupt is now pending - notify the simulated interrupt
\r
205 if( ulCriticalNesting == 0 )
\r
207 SetEvent( pvInterruptEvent );
\r
210 /* Give back the mutex so the simulated interrupt handler unblocks
\r
211 and can access the interrupt handler variables. */
\r
212 ReleaseMutex( pvInterruptEventMutex );
\r
216 /* Should never reach here - MingW complains if you leave this line out,
\r
217 MSVC complains if you put it in. */
\r
221 /*-----------------------------------------------------------*/
\r
223 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType )
\r
225 TIMECAPS xTimeCaps;
\r
227 ( void ) dwCtrlType;
\r
229 if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
\r
231 /* Match the call to timeBeginPeriod( xTimeCaps.wPeriodMin ) made when
\r
232 the process started with a timeEndPeriod() as the process exits. */
\r
233 timeEndPeriod( xTimeCaps.wPeriodMin );
\r
238 /*-----------------------------------------------------------*/
\r
240 portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
\r
242 xThreadState *pxThreadState = NULL;
\r
243 char *pcTopOfStack = ( char * ) pxTopOfStack;
\r
245 /* In this simulated case a stack is not initialised, but instead a thread
\r
246 is created that will execute the task being created. The thread handles
\r
247 the context switching itself. The xThreadState object is placed onto
\r
248 the stack that was created for the task - so the stack buffer is still
\r
249 used, just not in the conventional way. It will not be used for anything
\r
250 other than holding this structure. */
\r
251 pxThreadState = ( xThreadState * ) ( pcTopOfStack - sizeof( xThreadState ) );
\r
253 /* Create the thread itself. */
\r
254 pxThreadState->pvThread = CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );
\r
255 configASSERT( pxThreadState->pvThread );
\r
256 SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );
\r
257 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
258 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
260 return ( portSTACK_TYPE * ) pxThreadState;
\r
262 /*-----------------------------------------------------------*/
\r
264 portBASE_TYPE xPortStartScheduler( void )
\r
267 long lSuccess = pdPASS;
\r
268 xThreadState *pxThreadState;
\r
270 /* Install the interrupt handlers used by the scheduler itself. */
\r
271 vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );
\r
272 vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );
\r
274 /* Create the events and mutexes that are used to synchronise all the
\r
276 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
\r
277 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
279 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )
\r
284 /* Set the priority of this thread such that it is above the priority of
\r
285 the threads that run tasks. This higher priority is required to ensure
\r
286 simulated interrupts take priority over tasks. */
\r
287 pvHandle = GetCurrentThread();
\r
288 if( pvHandle == NULL )
\r
293 if( lSuccess == pdPASS )
\r
295 if( SetThreadPriority( pvHandle, THREAD_PRIORITY_NORMAL ) == 0 )
\r
299 SetThreadPriorityBoost( pvHandle, TRUE );
\r
300 SetThreadAffinityMask( pvHandle, 0x01 );
\r
303 if( lSuccess == pdPASS )
\r
305 /* Start the thread that simulates the timer peripheral to generate
\r
306 tick interrupts. The priority is set below that of the simulated
\r
307 interrupt handler so the interrupt event mutex is used for the
\r
308 handshake / overrun protection. */
\r
309 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );
\r
310 if( pvHandle != NULL )
\r
312 SetThreadPriority( pvHandle, THREAD_PRIORITY_BELOW_NORMAL );
\r
313 SetThreadPriorityBoost( pvHandle, TRUE );
\r
314 SetThreadAffinityMask( pvHandle, 0x01 );
\r
317 /* Start the highest priority task by obtaining its associated thread
\r
318 state structure, in which is stored the thread handle. */
\r
319 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
320 ulCriticalNesting = portNO_CRITICAL_NESTING;
\r
322 /* Bump up the priority of the thread that is going to run, in the
\r
323 hope that this will assist in getting the Windows thread scheduler to
\r
324 behave as an embedded engineer might expect. */
\r
325 ResumeThread( pxThreadState->pvThread );
\r
327 /* Handle all simulated interrupts - including yield requests and
\r
328 simulated ticks. */
\r
329 prvProcessSimulatedInterrupts();
\r
332 /* Would not expect to return from prvProcessSimulatedInterrupts(), so should
\r
336 /*-----------------------------------------------------------*/
\r
338 static unsigned long prvProcessYieldInterrupt( void )
\r
342 /*-----------------------------------------------------------*/
\r
344 static unsigned long prvProcessTickInterrupt( void )
\r
346 unsigned long ulSwitchRequired;
\r
348 /* Process the tick itself. */
\r
349 configASSERT( xPortRunning );
\r
350 ulSwitchRequired = ( unsigned long ) xTaskIncrementTick();
\r
352 return ulSwitchRequired;
\r
354 /*-----------------------------------------------------------*/
\r
356 static void prvProcessSimulatedInterrupts( void )
\r
358 unsigned long ulSwitchRequired, i;
\r
359 xThreadState *pxThreadState;
\r
360 void *pvObjectList[ 2 ];
\r
362 /* Going to block on the mutex that ensured exclusive access to the simulated
\r
363 interrupt objects, and the event that signals that a simulated interrupt
\r
364 should be processed. */
\r
365 pvObjectList[ 0 ] = pvInterruptEventMutex;
\r
366 pvObjectList[ 1 ] = pvInterruptEvent;
\r
368 /* Create a pending tick to ensure the first task is started as soon as
\r
369 this thread pends. */
\r
370 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
371 SetEvent( pvInterruptEvent );
\r
373 xPortRunning = pdTRUE;
\r
377 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
\r
379 /* Used to indicate whether the simulated interrupt processing has
\r
380 necessitated a context switch to another task/thread. */
\r
381 ulSwitchRequired = pdFALSE;
\r
383 /* For each interrupt we are interested in processing, each of which is
\r
384 represented by a bit in the 32bit ulPendingInterrupts variable. */
\r
385 for( i = 0; i < portMAX_INTERRUPTS; i++ )
\r
387 /* Is the simulated interrupt pending? */
\r
388 if( ulPendingInterrupts & ( 1UL << i ) )
\r
390 /* Is a handler installed? */
\r
391 if( ulIsrHandler[ i ] != NULL )
\r
393 /* Run the actual handler. */
\r
394 if( ulIsrHandler[ i ]() != pdFALSE )
\r
396 ulSwitchRequired |= ( 1 << i );
\r
400 /* Clear the interrupt pending bit. */
\r
401 ulPendingInterrupts &= ~( 1UL << i );
\r
405 if( ulSwitchRequired != pdFALSE )
\r
407 void *pvOldCurrentTCB;
\r
409 pvOldCurrentTCB = pxCurrentTCB;
\r
411 /* Select the next task to run. */
\r
412 vTaskSwitchContext();
\r
414 /* If the task selected to enter the running state is not the task
\r
415 that is already in the running state. */
\r
416 if( pvOldCurrentTCB != pxCurrentTCB )
\r
418 /* Suspend the old thread. */
\r
419 pxThreadState = ( xThreadState *) *( ( unsigned long * ) pvOldCurrentTCB );
\r
420 SuspendThread( pxThreadState->pvThread );
\r
422 /* Obtain the state of the task now selected to enter the
\r
424 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );
\r
425 ResumeThread( pxThreadState->pvThread );
\r
429 ReleaseMutex( pvInterruptEventMutex );
\r
432 /*-----------------------------------------------------------*/
\r
434 void vPortDeleteThread( void *pvTaskToDelete )
\r
436 xThreadState *pxThreadState;
\r
437 unsigned long ulErrorCode;
\r
439 /* Remove compiler warnings if configASSERT() is not defined. */
\r
440 ( void ) ulErrorCode;
\r
442 /* Find the handle of the thread being deleted. */
\r
443 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pvTaskToDelete );
\r
445 /* Check that the thread is still valid, it might have been closed by
\r
446 vPortCloseRunningThread() - which will be the case if the task associated
\r
447 with the thread originally deleted itself rather than being deleted by a
\r
449 if( pxThreadState->pvThread != NULL )
\r
451 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
453 ulErrorCode = TerminateThread( pxThreadState->pvThread, 0 );
\r
454 configASSERT( ulErrorCode );
\r
456 ulErrorCode = CloseHandle( pxThreadState->pvThread );
\r
457 configASSERT( ulErrorCode );
\r
459 ReleaseMutex( pvInterruptEventMutex );
\r
462 /*-----------------------------------------------------------*/
\r
464 void vPortCloseRunningThread( void *pvTaskToDelete, volatile portBASE_TYPE *pxPendYield )
\r
466 xThreadState *pxThreadState;
\r
468 unsigned long ulErrorCode;
\r
470 /* Remove compiler warnings if configASSERT() is not defined. */
\r
471 ( void ) ulErrorCode;
\r
473 /* Find the handle of the thread being deleted. */
\r
474 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pvTaskToDelete );
\r
475 pvThread = pxThreadState->pvThread;
\r
477 /* Raise the Windows priority of the thread to ensure the FreeRTOS scheduler
\r
478 does not run and swap it out before it is closed. If that were to happen
\r
479 the thread would never run again and effectively be a thread handle and
\r
481 SetThreadPriority( pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
483 /* This function will not return, therefore a yield is set as pending to
\r
484 ensure a context switch occurs away from this thread on the next tick. */
\r
485 *pxPendYield = pdTRUE;
\r
487 /* Mark the thread associated with this task as invalid so
\r
488 vPortDeleteThread() does not try to terminate it. */
\r
489 pxThreadState->pvThread = NULL;
\r
491 /* Close the thread. */
\r
492 ulErrorCode = CloseHandle( pvThread );
\r
493 configASSERT( ulErrorCode );
\r
497 /*-----------------------------------------------------------*/
\r
499 void vPortEndScheduler( void )
\r
501 /* This function IS NOT TESTED! */
\r
502 TerminateProcess( GetCurrentProcess(), 0 );
\r
504 /*-----------------------------------------------------------*/
\r
506 void vPortGenerateSimulatedInterrupt( unsigned long ulInterruptNumber )
\r
508 configASSERT( xPortRunning );
\r
510 if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
\r
512 /* Yield interrupts are processed even when critical nesting is non-zero. */
\r
513 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
514 ulPendingInterrupts |= ( 1 << ulInterruptNumber );
\r
516 /* The simulated interrupt is now held pending, but don't actually process it
\r
517 yet if this call is within a critical section. It is possible for this to
\r
518 be in a critical section as calls to wait for mutexes are accumulative. */
\r
519 if( ulCriticalNesting == 0 )
\r
521 SetEvent( pvInterruptEvent );
\r
524 ReleaseMutex( pvInterruptEventMutex );
\r
527 /*-----------------------------------------------------------*/
\r
529 void vPortSetInterruptHandler( unsigned long ulInterruptNumber, unsigned long (*pvHandler)( void ) )
\r
531 if( ulInterruptNumber < portMAX_INTERRUPTS )
\r
533 if( pvInterruptEventMutex != NULL )
\r
535 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
536 ulIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
537 ReleaseMutex( pvInterruptEventMutex );
\r
541 ulIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
545 /*-----------------------------------------------------------*/
\r
547 void vPortEnterCritical( void )
\r
549 if( xPortRunning == pdTRUE )
\r
551 /* The interrupt event mutex is held for the entire critical section,
\r
552 effectively disabling (simulated) interrupts. */
\r
553 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
554 ulCriticalNesting++;
\r
558 ulCriticalNesting++;
\r
561 /*-----------------------------------------------------------*/
\r
563 void vPortExitCritical( void )
\r
565 long lMutexNeedsReleasing;
\r
567 /* The interrupt event mutex should already be held by this thread as it was
\r
568 obtained on entry to the critical section. */
\r
570 lMutexNeedsReleasing = pdTRUE;
\r
572 if( ulCriticalNesting > portNO_CRITICAL_NESTING )
\r
574 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )
\r
576 ulCriticalNesting--;
\r
578 /* Were any interrupts set to pending while interrupts were
\r
579 (simulated) disabled? */
\r
580 if( ulPendingInterrupts != 0UL )
\r
582 configASSERT( xPortRunning );
\r
583 SetEvent( pvInterruptEvent );
\r
585 /* Mutex will be released now, so does not require releasing
\r
586 on function exit. */
\r
587 lMutexNeedsReleasing = pdFALSE;
\r
588 ReleaseMutex( pvInterruptEventMutex );
\r
593 /* Tick interrupts will still not be processed as the critical
\r
594 nesting depth will not be zero. */
\r
595 ulCriticalNesting--;
\r
599 if( pvInterruptEventMutex != NULL )
\r
601 if( lMutexNeedsReleasing == pdTRUE )
\r
603 configASSERT( xPortRunning );
\r
604 ReleaseMutex( pvInterruptEventMutex );
\r
608 /*-----------------------------------------------------------*/
\r