2 FreeRTOS V6.1.0 - Copyright (C) 2010 Real Time Engineers Ltd.
\r
4 ***************************************************************************
\r
8 * + New to FreeRTOS, *
\r
9 * + Wanting to learn FreeRTOS or multitasking in general quickly *
\r
10 * + Looking for basic training, *
\r
11 * + Wanting to improve your FreeRTOS skills and productivity *
\r
13 * then take a look at the FreeRTOS books - available as PDF or paperback *
\r
15 * "Using the FreeRTOS Real Time Kernel - a Practical Guide" *
\r
16 * http://www.FreeRTOS.org/Documentation *
\r
18 * A pdf reference manual is also available. Both are usually delivered *
\r
19 * to your inbox within 20 minutes to two hours when purchased between 8am *
\r
20 * and 8pm GMT (although please allow up to 24 hours in case of *
\r
21 * exceptional circumstances). Thank you for your support! *
\r
23 ***************************************************************************
\r
25 This file is part of the FreeRTOS distribution.
\r
27 FreeRTOS is free software; you can redistribute it and/or modify it under
\r
28 the terms of the GNU General Public License (version 2) as published by the
\r
29 Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
\r
30 ***NOTE*** The exception to the GPL is included to allow you to distribute
\r
31 a combined work that includes FreeRTOS without being obliged to provide the
\r
32 source code for proprietary components outside of the FreeRTOS kernel.
\r
33 FreeRTOS is distributed in the hope that it will be useful, but WITHOUT
\r
34 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
\r
35 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
\r
36 more details. You should have received a copy of the GNU General Public
\r
37 License and the FreeRTOS license exception along with FreeRTOS; if not it
\r
38 can be viewed here: http://www.freertos.org/a00114.html and also obtained
\r
39 by writing to Richard Barry, contact details for whom are available on the
\r
44 http://www.FreeRTOS.org - Documentation, latest information, license and
\r
47 http://www.SafeRTOS.com - A version that is certified for use in safety
\r
50 http://www.OpenRTOS.com - Commercial support, development, porting,
\r
51 licensing and training services.
\r
54 /* Scheduler includes. */
\r
55 #include "FreeRTOS.h"
\r
59 #define portMAX_INTERRUPTS ( ( unsigned long ) sizeof( unsigned long ) * 8UL ) /* The number of bits in an unsigned long. */
\r
60 #define portNO_CRITICAL_NESTING ( ( unsigned long ) 0 )
\r
63 * Created as a high priority thread, this function uses a timer to simulate
\r
64 * a tick interrupt being generated on an embedded target. In this Windows
\r
65 * environment the timer does not achieve anything approaching real time
\r
66 * performance though.
\r
68 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );
\r
71 * Process all the simulated interrupts - each represented by a bit in
\r
72 * ulPendingInterrupts variable.
\r
74 static void prvProcessPseudoInterrupts( void );
\r
76 /*-----------------------------------------------------------*/
\r
78 /* The WIN32 simulator runs each task in a thread. The context switching is
\r
79 managed by the threads, so the task stack does not have to be managed directly,
\r
80 although the task stack is still used to hold an xThreadState structure this is
\r
81 the only thing it will ever hold. The structure indirectly maps the task handle
\r
82 to a thread handle. */
\r
85 /* Handle of the thread that executes the task. */
\r
90 /* Pseudo interrupts waiting to be processed. This is a bit mask where each
\r
91 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
\r
92 static volatile unsigned long ulPendingInterrupts = 0UL;
\r
94 /* An event used to inform the pseudo interrupt processing thread (a high
\r
95 priority thread that simulated interrupt processing) that an interrupt is
\r
97 static void *pvInterruptEvent = NULL;
\r
99 /* Mutex used to protect all the pseudo interrupt variables that are accessed
\r
100 by multiple threads. */
\r
101 static void *pvInterruptEventMutex = NULL;
\r
103 /* Events used to manage sequencing. */
\r
104 static void *pvTickAcknowledgeEvent = NULL;
\r
106 /* The critical nesting count for the currently executing task. This is
\r
107 initialised to a non-zero value so interrupts do not become enabled during
\r
108 the initialisation phase. As each task has its own critical nesting value
\r
109 ulCriticalNesting will get set to zero when the first task runs. This
\r
110 initialisation is probably not critical in this simulated environment as the
\r
111 pseudo interrupt handlers do not get created until the FreeRTOS scheduler is
\r
113 static unsigned long ulCriticalNesting = 9999UL;
\r
115 /* Handlers for all the simulated software interrupts. The first two positions
\r
116 are used for the Yield and Tick interrupts so are handled slightly differently,
\r
117 all the other interrupts can be user defined. */
\r
118 static void (*vIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
\r
120 /* Pointer to the TCB of the currently executing task. */
\r
121 extern void *pxCurrentTCB;
\r
123 /*-----------------------------------------------------------*/
\r
125 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
\r
127 /* Just to prevent compiler warnings. */
\r
128 ( void ) lpParameter;
\r
132 /* Wait until the timer expires and we can access the pseudo interrupt
\r
133 variables. *NOTE* this is not a 'real time' way of generating tick
\r
134 events as the next wake time should be relative to the previous wake
\r
135 time, not the time that Sleep() is called. It is done this way to
\r
136 prevent overruns in this very non real time simulated/emulated
\r
138 Sleep( portTICK_RATE_MS );
\r
140 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
142 /* The timer has expired, generate the simulated tick event. */
\r
143 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
145 /* The interrupt is now pending - notify the simulated interrupt
\r
147 SetEvent( pvInterruptEvent );
\r
149 /* Give back the mutex so the pseudo interrupt handler unblocks
\r
150 and can access the interrupt handler variables. This high priority
\r
151 task will then loop back round after waiting for the lower priority
\r
152 pseudo interrupt handler thread to acknowledge the tick. */
\r
153 SignalObjectAndWait( pvInterruptEventMutex, pvTickAcknowledgeEvent, INFINITE, FALSE );
\r
156 /* Should never reach here. */
\r
159 /*-----------------------------------------------------------*/
\r
161 portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
\r
163 xThreadState *pxThreadState = NULL;
\r
165 /* In this simulated case a stack is not initialised, but instead a thread
\r
166 is created that will execute the task being created. The thread handles
\r
167 the context switching itself. The xThreadState object is placed onto
\r
168 the stack that was created for the task - so the stack buffer is still
\r
169 used, just not in the conventional way. It will not be used for anything
\r
170 other than holding this structure. */
\r
171 pxThreadState = ( xThreadState * ) ( pxTopOfStack - sizeof( xThreadState ) );
\r
173 /* Create the thread itself. */
\r
174 pxThreadState->pvThread = CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );
\r
175 SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );
\r
176 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
177 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
179 return ( portSTACK_TYPE * ) pxThreadState;
\r
181 /*-----------------------------------------------------------*/
\r
183 portBASE_TYPE xPortStartScheduler( void )
\r
186 long lSuccess = pdPASS;
\r
187 xThreadState *pxThreadState;
\r
189 /* Create the events and mutexes that are used to synchronise all the
\r
191 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
\r
192 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
193 pvTickAcknowledgeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
195 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) || ( pvTickAcknowledgeEvent == NULL ) )
\r
200 /* Set the priority of this thread such that it is above the priority of
\r
201 the threads that run tasks. This higher priority is required to ensure
\r
202 pseudo interrupts take priority over tasks. */
\r
203 SetPriorityClass( GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS );
\r
204 pvHandle = GetCurrentThread();
\r
205 if( pvHandle == NULL )
\r
210 if( lSuccess == pdPASS )
\r
212 if( SetThreadPriority( pvHandle, THREAD_PRIORITY_HIGHEST ) == 0 )
\r
216 SetThreadPriorityBoost( pvHandle, TRUE );
\r
217 SetThreadAffinityMask( pvHandle, 0x01 );
\r
220 if( lSuccess == pdPASS )
\r
222 /* Start the thread that simulates the timer peripheral to generate
\r
223 tick interrupts. */
\r
224 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );
\r
225 if( pvHandle != NULL )
\r
227 SetThreadPriority( pvHandle, THREAD_PRIORITY_HIGHEST );
\r
228 SetThreadPriorityBoost( pvHandle, TRUE );
\r
229 SetThreadAffinityMask( pvHandle, 0x01 );
\r
232 /* Start the highest priority task by obtaining its associated thread
\r
233 state structure, in which is stored the thread handle. */
\r
234 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
235 ulCriticalNesting = portNO_CRITICAL_NESTING;
\r
237 /* Bump up the priority of the thread that is going to run, in the
\r
238 hope that this will asist in getting the Windows thread scheduler to
\r
239 behave as an embedded engineer might expect. */
\r
240 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
241 ResumeThread( pxThreadState->pvThread );
\r
243 /* Handle all pseudo interrupts - including yield requests and
\r
244 simulated ticks. */
\r
245 prvProcessPseudoInterrupts();
\r
248 /* Would not expect to return from prvProcessPseudoInterrupts(), so should
\r
252 /*-----------------------------------------------------------*/
\r
254 static void prvProcessPseudoInterrupts( void )
\r
256 long lSwitchRequired;
\r
257 xThreadState *pxThreadState;
\r
258 void *pvObjectList[ 2 ];
\r
261 /* Going to block on the mutex that ensured exclusive access to the pseudo
\r
262 interrupt objects, and the event that signals that a pseudo interrupt
\r
263 should be processed. */
\r
264 pvObjectList[ 0 ] = pvInterruptEventMutex;
\r
265 pvObjectList[ 1 ] = pvInterruptEvent;
\r
269 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
\r
271 /* Used to indicate whether the pseudo interrupt processing has
\r
272 necessitated a context switch to another task/thread. */
\r
273 lSwitchRequired = pdFALSE;
\r
275 /* For each interrupt we are interested in processing, each of which is
\r
276 represented by a bit in the 32bit ulPendingInterrupts variable. */
\r
277 for( i = 0; i < portMAX_INTERRUPTS; i++ )
\r
279 /* Is the pseudo interrupt pending? */
\r
280 if( ulPendingInterrupts & ( 1UL << i ) )
\r
284 case portINTERRUPT_YIELD:
\r
286 lSwitchRequired = pdTRUE;
\r
288 /* Clear the interrupt pending bit. */
\r
289 ulPendingInterrupts &= ~( 1UL << portINTERRUPT_YIELD );
\r
292 case portINTERRUPT_TICK:
\r
294 /* Process the tick itself. */
\r
295 vTaskIncrementTick();
\r
296 #if( configUSE_PREEMPTION != 0 )
\r
298 /* A context switch is only automatically
\r
299 performed from the tick interrupt if the
\r
300 pre-emptive scheduler is being used. */
\r
301 lSwitchRequired = pdTRUE;
\r
305 /* Clear the interrupt pending bit. */
\r
306 ulPendingInterrupts &= ~( 1UL << portINTERRUPT_TICK );
\r
307 SetEvent( pvTickAcknowledgeEvent );
\r
312 /* Is a handler installed? */
\r
313 if( vIsrHandler[ i ] != NULL )
\r
315 lSwitchRequired = pdTRUE;
\r
317 /* Run the actual handler. */
\r
318 vIsrHandler[ i ]();
\r
320 /* Clear the interrupt pending bit. */
\r
321 ulPendingInterrupts &= ~( 1UL << i );
\r
323 /* TODO: Need to have some sort of handshake
\r
324 event here for non-tick and none yield
\r
332 if( lSwitchRequired != pdFALSE )
\r
334 void *pvOldCurrentTCB;
\r
336 pvOldCurrentTCB = pxCurrentTCB;
\r
338 /* Select the next task to run. */
\r
339 vTaskSwitchContext();
\r
341 /* If the task selected to enter the running state is not the task
\r
342 that is already in the running state. */
\r
343 if( pvOldCurrentTCB != pxCurrentTCB )
\r
345 /* Suspend the old thread. */
\r
346 pxThreadState = ( xThreadState *) *( ( unsigned long * ) pvOldCurrentTCB );
\r
347 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
348 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
349 SuspendThread( pxThreadState->pvThread );
\r
353 /* NOTE! - Here lies a problem when the preemptive scheduler is
\r
354 used. It would seem Win32 threads do not stop as soon as a
\r
355 call to suspend them is made. The co-operative scheduler gets
\r
356 around this by having the thread block on a semaphore
\r
357 immediately after yielding so it cannot execute any more task
\r
358 code until it is once again scheduled to run. This cannot be
\r
359 done if the task is pre-empted though, and I have not found an
\r
360 equivalent work around for the preemptive situation. */
\r
364 /* Obtain the state of the task now selected to enter the
\r
366 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );
\r
368 /* Boost the priority of the thread selected to run a little
\r
369 in an attempt to get the Windows thread scheduler to act a
\r
370 little more like an embedded engineer might expect. */
\r
371 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
372 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
373 ResumeThread( pxThreadState->pvThread );
\r
377 ReleaseMutex( pvInterruptEventMutex );
\r
380 /*-----------------------------------------------------------*/
\r
382 void vPortEndScheduler( void )
\r
385 /*-----------------------------------------------------------*/
\r
387 void vPortGeneratePseudoInterrupt( unsigned long ulInterruptNumber )
\r
389 xThreadState *pxThreadState;
\r
391 if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
\r
393 /* Yield interrupts are processed even when critical nesting is non-zero. */
\r
394 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
395 ulPendingInterrupts |= ( 1 << ulInterruptNumber );
\r
397 /* The pseudo interrupt is now held pending, but don't actually process it
\r
398 yet if this call is within a critical section. It is possible for this to
\r
399 be in a critical section as calls to wait for mutexes are accumulative. */
\r
400 if( ulCriticalNesting == 0 )
\r
402 /* The event handler needs to know to signal the interrupt acknowledge event
\r
403 the next time this task runs. */
\r
404 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
405 SetEvent( pvInterruptEvent );
\r
408 ReleaseMutex( pvInterruptEventMutex );
\r
411 /*-----------------------------------------------------------*/
\r
413 void vPortSetInterruptHandler( unsigned long ulInterruptNumber, void (*pvHandler)( void ) )
\r
415 if( ulInterruptNumber < portMAX_INTERRUPTS )
\r
417 if( pvInterruptEventMutex != NULL )
\r
419 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
420 vIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
421 ReleaseMutex( pvInterruptEventMutex );
\r
425 vIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
429 /*-----------------------------------------------------------*/
\r
431 void vPortEnterCritical( void )
\r
433 if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
\r
435 /* The interrupt event mutex is held for the entire critical section,
\r
436 effectively disabling (pseudo) interrupts. */
\r
437 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
438 ulCriticalNesting++;
\r
442 ulCriticalNesting++;
\r
445 /*-----------------------------------------------------------*/
\r
447 void vPortExitCritical( void )
\r
449 xThreadState *pxThreadState;
\r
450 long lMutexNeedsReleasing;
\r
452 /* The interrupt event mutex should already be held by this thread as it was
\r
453 obtained on entry to the critical section. */
\r
455 lMutexNeedsReleasing = pdTRUE;
\r
457 if( ulCriticalNesting > portNO_CRITICAL_NESTING )
\r
459 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )
\r
461 ulCriticalNesting--;
\r
463 /* Were any interrupts set to pending while interrupts were
\r
464 (pseudo) disabled? */
\r
465 if( ulPendingInterrupts != 0UL )
\r
467 SetEvent( pvInterruptEvent );
\r
469 /* The event handler needs to know to signal the interrupt
\r
470 acknowledge event the next time this task runs. */
\r
471 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
473 /* Mutex will be released now, so does not require releasing
\r
474 on function exit. */
\r
475 lMutexNeedsReleasing = pdFALSE;
\r
476 ReleaseMutex( pvInterruptEventMutex );
\r
481 /* Tick interrupts will still not be processed as the critical
\r
482 nesting depth will not be zero. */
\r
483 ulCriticalNesting--;
\r
487 if( lMutexNeedsReleasing == pdTRUE )
\r
489 ReleaseMutex( pvInterruptEventMutex );
\r
492 /*-----------------------------------------------------------*/
\r