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 /* Set to true if the task run by the thread yielded control to the pseudo
\r
86 interrupt handler manually - either by yielding or when exiting a critical
\r
87 section while pseudo interrupts were pending. */
\r
88 long lWaitingInterruptAck;
\r
90 /* Handle of the thread that executes the task. */
\r
94 /* Pseudo interrupts waiting to be processed. This is a bit mask where each
\r
95 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
\r
96 static volatile unsigned long ulPendingInterrupts = 0UL;
\r
98 /* An event used to inform the pseudo interrupt processing thread (a high
\r
99 priority thread that simulated interrupt processing) that an interrupt is
\r
101 static void *pvInterruptEvent = NULL;
\r
103 /* Mutex used to protect all the pseudo interrupt variables that are accessed
\r
104 by multiple threads. */
\r
105 static void *pvInterruptEventMutex = NULL;
\r
107 /* Events used to manage sequencing. */
\r
108 static void *pvTickAcknowledgeEvent = NULL, *pvInterruptAcknowledgeEvent = NULL;
\r
110 /* The critical nesting count for the currently executing task. This is
\r
111 initialised to a non-zero value so interrupts do not become enabled during
\r
112 the initialisation phase. As each task has its own critical nesting value
\r
113 ulCriticalNesting will get set to zero when the first task runs. This
\r
114 initialisation is probably not critical in this simulated environment as the
\r
115 pseudo interrupt handlers do not get created until the FreeRTOS scheduler is
\r
117 static unsigned long ulCriticalNesting = 9999UL;
\r
119 /* Handlers for all the simulated software interrupts. The first two positions
\r
120 are used for the Yield and Tick interrupts so are handled slightly differently,
\r
121 all the other interrupts can be user defined. */
\r
122 static void (*vIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
\r
124 /* Pointer to the TCB of the currently executing task. */
\r
125 extern void *pxCurrentTCB;
\r
127 /*-----------------------------------------------------------*/
\r
129 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
\r
131 /* Just to prevent compiler warnings. */
\r
132 ( void ) lpParameter;
\r
136 /* Wait until the timer expires and we can access the pseudo interrupt
\r
137 variables. *NOTE* this is not a 'real time' way of generating tick
\r
138 events as the next wake time should be relative to the previous wake
\r
139 time, not the time that Sleep() is called. It is done this way to
\r
140 prevent overruns in this very non real time simulated/emulated
\r
142 Sleep( portTICK_RATE_MS );
\r
144 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
146 /* A thread will hold the interrupt event mutex while in a critical
\r
147 section, so ulCriticalSection should be zero for this tick event to be
\r
149 if( ulCriticalNesting != 0 )
\r
151 /* For a break point only. */
\r
155 /* The timer has expired, generate the simulated tick event. */
\r
156 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
158 /* The interrupt is now pending - notify the simulated interrupt
\r
160 SetEvent( pvInterruptEvent );
\r
162 /* Give back the mutex so the pseudo interrupt handler unblocks
\r
163 and can access the interrupt handler variables. This high priority
\r
164 task will then loop back round after waiting for the lower priority
\r
165 pseudo interrupt handler thread to acknowledge the tick. */
\r
166 SignalObjectAndWait( pvInterruptEventMutex, pvTickAcknowledgeEvent, INFINITE, FALSE );
\r
169 /*-----------------------------------------------------------*/
\r
171 portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
\r
173 xThreadState *pxThreadState = NULL;
\r
175 /* In this simulated case a stack is not initialised, but instead a thread
\r
176 is created that will execute the task being created. The thread handles
\r
177 the context switching itself. The xThreadState object is placed onto
\r
178 the stack that was created for the task - so the stack buffer is still
\r
179 used, just not in the conventional way. It will not be used for anything
\r
180 other than holding this structure. */
\r
181 pxThreadState = ( xThreadState * ) ( pxTopOfStack - sizeof( xThreadState ) );
\r
183 /* Create the thread itself. */
\r
184 pxThreadState->pvThread = ( void * ) CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );
\r
185 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
186 pxThreadState->lWaitingInterruptAck = pdFALSE;
\r
187 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
189 return ( portSTACK_TYPE * ) pxThreadState;
\r
191 /*-----------------------------------------------------------*/
\r
193 portBASE_TYPE xPortStartScheduler( void )
\r
196 long lSuccess = pdPASS;
\r
197 xThreadState *pxThreadState;
\r
199 /* Create the events and mutexes that are used to synchronise all the
\r
201 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
\r
202 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
203 pvTickAcknowledgeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
204 pvInterruptAcknowledgeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
206 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) || ( pvTickAcknowledgeEvent == NULL ) || ( pvInterruptAcknowledgeEvent == NULL ) )
\r
211 /* Set the priority of this thread such that it is above the priority of
\r
212 the threads that run tasks. This higher priority is required to ensure
\r
213 pseudo interrupts take priority over tasks. */
\r
214 SetPriorityClass( GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS );
\r
215 pvHandle = GetCurrentThread();
\r
216 if( pvHandle == NULL )
\r
221 if( lSuccess == pdPASS )
\r
223 if( SetThreadPriority( pvHandle, THREAD_PRIORITY_HIGHEST ) == 0 )
\r
227 SetThreadPriorityBoost( pvHandle, TRUE );
\r
230 if( lSuccess == pdPASS )
\r
232 /* Start the thread that simulates the timer peripheral to generate
\r
233 tick interrupts. */
\r
234 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );
\r
235 if( pvHandle != NULL )
\r
237 SetThreadPriority( pvHandle, THREAD_PRIORITY_HIGHEST );
\r
238 SetThreadPriorityBoost( pvHandle, TRUE );
\r
241 /* Start the highest priority task by obtaining its associated thread
\r
242 state structure, in which is stored the thread handle. */
\r
243 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
244 ulCriticalNesting = portNO_CRITICAL_NESTING;
\r
246 /* Bump up the priority of the thread that is going to run, in the
\r
247 hope that this will asist in getting the Windows thread scheduler to
\r
248 behave as an embedded engineer might expect. */
\r
249 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
250 ResumeThread( pxThreadState->pvThread );
\r
252 /* Handle all pseudo interrupts - including yield requests and
\r
253 simulated ticks. */
\r
254 prvProcessPseudoInterrupts();
\r
257 /* Would not expect to return from prvProcessPseudoInterrupts(), so should
\r
261 /*-----------------------------------------------------------*/
\r
263 static void prvProcessPseudoInterrupts( void )
\r
265 long lSwitchRequired;
\r
266 xThreadState *pxThreadState;
\r
267 void *pvObjectList[ 2 ];
\r
270 /* Going to block on the mutex that ensured exclusive access to the pseudo
\r
271 interrupt objects, and the event that signals that a pseudo interrupt
\r
272 should be processed. */
\r
273 pvObjectList[ 0 ] = pvInterruptEventMutex;
\r
274 pvObjectList[ 1 ] = pvInterruptEvent;
\r
278 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
\r
280 /* A thread will hold the interrupt event mutex while in a critical
\r
281 section, so this pseudo interrupt handler should only run when
\r
282 critical nesting is zero. */
\r
283 if( ulCriticalNesting != 0 )
\r
285 /* For a break point only. */
\r
289 /* Used to indicate whether the pseudo interrupt processing has
\r
290 necessitated a context switch to another task/thread. */
\r
291 lSwitchRequired = pdFALSE;
\r
293 /* For each interrupt we are interested in processing, each of which is
\r
294 represented by a bit in the 32bit ulPendingInterrupts variable. */
\r
295 for( i = 0; i < portMAX_INTERRUPTS; i++ )
\r
297 /* Is the pseudo interrupt pending? */
\r
298 if( ulPendingInterrupts & ( 1UL << i ) )
\r
302 case portINTERRUPT_YIELD:
\r
304 lSwitchRequired = pdTRUE;
\r
306 /* Clear the interrupt pending bit. */
\r
307 ulPendingInterrupts &= ~( 1UL << portINTERRUPT_YIELD );
\r
310 case portINTERRUPT_TICK:
\r
312 /* Process the tick itself. */
\r
313 vTaskIncrementTick();
\r
314 #if( configUSE_PREEMPTION != 0 )
\r
316 /* A context switch is only automatically
\r
317 performed from the tick interrupt if the
\r
318 pre-emptive scheduler is being used. */
\r
319 lSwitchRequired = pdTRUE;
\r
323 /* Clear the interrupt pending bit. */
\r
324 ulPendingInterrupts &= ~( 1UL << portINTERRUPT_TICK );
\r
325 SetEvent( pvTickAcknowledgeEvent );
\r
330 /* Is a handler installed? */
\r
331 if( vIsrHandler[ i ] != NULL )
\r
333 lSwitchRequired = pdTRUE;
\r
335 /* Run the actual handler. */
\r
336 vIsrHandler[ i ]();
\r
338 /* Clear the interrupt pending bit. */
\r
339 ulPendingInterrupts &= ~( 1UL << i );
\r
341 /* TODO: Need to have some sort of handshake
\r
342 event here for non-tick and none yield
\r
350 if( lSwitchRequired != pdFALSE )
\r
352 void *pvOldCurrentTCB;
\r
354 pvOldCurrentTCB = pxCurrentTCB;
\r
356 /* Select the next task to run. */
\r
357 vTaskSwitchContext();
\r
359 /* If the task selected to enter the running state is not the task
\r
360 that is already in the running state. */
\r
361 if( pvOldCurrentTCB != pxCurrentTCB )
\r
363 /* Suspend the old thread. */
\r
364 pxThreadState = ( xThreadState *) *( ( unsigned long * ) pvOldCurrentTCB );
\r
365 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
366 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
367 SuspendThread( pxThreadState->pvThread );
\r
371 /* NOTE! - Here lies a problem when the preemptive scheduler is
\r
372 used. It would seem Win32 threads do not stop as soon as a
\r
373 call to suspend them is made. The co-operative scheduler gets
\r
374 around this by having the thread block on a semaphore
\r
375 immediately after yielding so it cannot execute any more task
\r
376 code until it is once again scheduled to run. This cannot be
\r
377 done if the task is pre-empted though, and I have not found an
\r
378 equivalent work around for the preemptive situation. */
\r
382 /* Obtain the state of the task now selected to enter the
\r
384 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );
\r
386 /* Boost the priority of the thread selected to run a little
\r
387 in an attempt to get the Windows thread scheduler to act a
\r
388 little more like an embedded engineer might expect. */
\r
389 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
390 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
391 ResumeThread( pxThreadState->pvThread );
\r
395 /* On exiting a critical section a task may have blocked on the
\r
396 interrupt event when only a tick needed processing, in which case
\r
397 it will not have been released from waiting on the event yet. */
\r
398 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );
\r
399 if( pxThreadState->lWaitingInterruptAck == pdTRUE )
\r
401 pxThreadState->lWaitingInterruptAck = pdFALSE;
\r
402 SetEvent( pvInterruptAcknowledgeEvent );
\r
405 ReleaseMutex( pvInterruptEventMutex );
\r
408 /*-----------------------------------------------------------*/
\r
410 void vPortEndScheduler( void )
\r
413 /*-----------------------------------------------------------*/
\r
415 void vPortGeneratePseudoInterrupt( unsigned long ulInterruptNumber )
\r
417 xThreadState *pxThreadState;
\r
419 if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
\r
421 /* Yield interrupts are processed even when critical nesting is non-zero. */
\r
422 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
423 ulPendingInterrupts |= ( 1 << ulInterruptNumber );
\r
425 /* The pseudo interrupt is now held pending, but don't actually process it
\r
426 yet if this call is within a critical section. It is possible for this to
\r
427 be in a critical section as calls to wait for mutexes are accumulative. */
\r
428 if( ulCriticalNesting == 0 )
\r
430 /* The event handler needs to know to signal the interrupt acknowledge event
\r
431 the next time this task runs. */
\r
432 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
433 pxThreadState->lWaitingInterruptAck = pdTRUE;
\r
435 SetEvent( pvInterruptEvent );
\r
437 /* The interrupt ack event should not be signaled yet - if it is then there
\r
438 is an error in the logical simulation. */
\r
439 if( WaitForSingleObject( pvInterruptAcknowledgeEvent, 0 ) != WAIT_TIMEOUT )
\r
441 /* This line is for a break point only. */
\r
445 SignalObjectAndWait( pvInterruptEventMutex, pvInterruptAcknowledgeEvent, INFINITE, FALSE );
\r
449 ReleaseMutex( pvInterruptEventMutex );
\r
453 /*-----------------------------------------------------------*/
\r
455 void vPortSetInterruptHandler( unsigned long ulInterruptNumber, void (*pvHandler)( void ) )
\r
457 if( ulInterruptNumber < portMAX_INTERRUPTS )
\r
459 if( pvInterruptEventMutex != NULL )
\r
461 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
462 vIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
463 ReleaseMutex( pvInterruptEventMutex );
\r
467 vIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
471 /*-----------------------------------------------------------*/
\r
473 void vPortEnterCritical( void )
\r
475 if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
\r
477 /* The interrupt event mutex is held for the entire critical section,
\r
478 effectively disabling (pseudo) interrupts. */
\r
479 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
480 ulCriticalNesting++;
\r
484 ulCriticalNesting++;
\r
487 /*-----------------------------------------------------------*/
\r
489 void vPortExitCritical( void )
\r
491 xThreadState *pxThreadState;
\r
492 long lMutexNeedsReleasing;
\r
494 /* The interrupt event mutex should already be held by this thread as it was
\r
495 obtained on entry to the critical section. */
\r
497 lMutexNeedsReleasing = pdTRUE;
\r
499 if( ulCriticalNesting > portNO_CRITICAL_NESTING )
\r
501 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )
\r
503 ulCriticalNesting--;
\r
505 /* Were any interrupts set to pending while interrupts were
\r
506 (pseudo) disabled? */
\r
507 if( ulPendingInterrupts != 0UL )
\r
509 SetEvent( pvInterruptEvent );
\r
511 /* The event handler needs to know to signal the interrupt
\r
512 acknowledge event the next time this task runs. */
\r
513 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
514 pxThreadState->lWaitingInterruptAck = pdTRUE;
\r
516 /* Mutex will be released now, so does not require releasing
\r
517 on function exit. */
\r
518 lMutexNeedsReleasing = pdFALSE;
\r
519 SignalObjectAndWait( pvInterruptEventMutex, pvInterruptAcknowledgeEvent, INFINITE, FALSE );
\r
524 /* Tick interrupts will still not be processed as the critical
\r
525 nesting depth will not be zero. */
\r
526 ulCriticalNesting--;
\r
530 if( lMutexNeedsReleasing == pdTRUE )
\r
532 ReleaseMutex( pvInterruptEventMutex );
\r
535 /*-----------------------------------------------------------*/
\r
537 void vPortCheckCorrectThreadIsRunning( void )
\r
539 xThreadState *pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
541 /* When switching threads, Windows does not always seem to run the selected
\r
542 thread immediately. This function can be called to check if the thread
\r
543 that is currently running is the thread that is responsible for executing
\r
544 the task selected by the real time scheduler. */
\r
545 if( GetCurrentThread() != pxThreadState->pvThread )
\r