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 //FILE *pfTraceFile = NULL;
\r
60 //#define vPortTrace( x ) if( pfTraceFile == NULL ) pfTraceFile = fopen( "c:/temp/trace.txt", "w" ); if( pfTraceFile != NULL ) fprintf( pfTraceFile, x )
\r
61 #define vPortTrace( x ) ( void ) x
\r
63 #define portMAX_INTERRUPTS ( ( unsigned long ) sizeof( unsigned long ) * 8UL ) /* The number of bits in an unsigned long. */
\r
64 #define portNO_CRITICAL_NESTING ( ( unsigned long ) 0 )
\r
67 * Created as a high priority thread, this function uses a timer to simulate
\r
68 * a tick interrupt being generated on an embedded target. In this Windows
\r
69 * environment the timer does not achieve anything approaching real time
\r
70 * performance though.
\r
72 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );
\r
75 * Process all the simulated interrupts - each represented by a bit in
\r
76 * ulPendingInterrupts variable.
\r
78 static void prvProcessPseudoInterrupts( void );
\r
80 /*-----------------------------------------------------------*/
\r
82 /* The WIN32 simulator runs each task in a thread. The context switching is
\r
83 managed by the threads, so the task stack does not have to be managed directly,
\r
84 although the task stack is still used to hold an xThreadState structure this is
\r
85 the only thing it will ever hold. The structure indirectly maps the task handle
\r
86 to a thread handle. */
\r
89 /* Set to true if the task run by the thread yielded control to the pseudo
\r
90 interrupt handler manually - either by yielding or when exiting a critical
\r
91 section while pseudo interrupts were pending. */
\r
92 long lWaitingInterruptAck;
\r
94 /* Handle of the thread that executes the task. */
\r
98 /* Pseudo interrupts waiting to be processed. This is a bit mask where each
\r
99 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
\r
100 static volatile unsigned long ulPendingInterrupts = 0UL;
\r
102 /* An event used to inform the pseudo interrupt processing thread (a high
\r
103 priority thread that simulated interrupt processing) that an interrupt is
\r
105 static void *pvInterruptEvent = NULL;
\r
107 /* Mutex used to protect all the pseudo interrupt variables that are accessed
\r
108 by multiple threads. */
\r
109 static void *pvInterruptEventMutex = NULL;
\r
111 /* Events used to manage sequencing. */
\r
112 static void *pvTickAcknowledgeEvent = NULL, *pvInterruptAcknowledgeEvent = NULL;
\r
114 /* The critical nesting count for the currently executing task. This is
\r
115 initialised to a non-zero value so interrupts do not become enabled during
\r
116 the initialisation phase. As each task has its own critical nesting value
\r
117 ulCriticalNesting will get set to zero when the first task runs. This
\r
118 initialisation is probably not critical in this simulated environment as the
\r
119 pseudo interrupt handlers do not get created until the FreeRTOS scheduler is
\r
121 static unsigned long ulCriticalNesting = 9999UL;
\r
123 /* Handlers for all the simulated software interrupts. The first two positions
\r
124 are used for the Yield and Tick interrupts so are handled slightly differently,
\r
125 all the other interrupts can be user defined. */
\r
126 static void (*vIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
\r
128 /* Pointer to the TCB of the currently executing task. */
\r
129 extern void *pxCurrentTCB;
\r
131 /*-----------------------------------------------------------*/
\r
133 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
\r
135 /* Just to prevent compiler warnings. */
\r
136 ( void ) lpParameter;
\r
140 vPortTrace( "prvSimulatedPeripheralTimer: Tick acked, re-Sleeping()\r\n" );
\r
142 /* Wait until the timer expires and we can access the pseudo interrupt
\r
143 variables. *NOTE* this is not a 'real time' way of generating tick
\r
144 events as the next wake time should be relative to the previous wake
\r
145 time, not the time that Sleep() is called. It is done this way to
\r
146 prevent overruns in this very non real time simulated/emulated
\r
148 Sleep( portTICK_RATE_MS );
\r
150 vPortTrace( "prvSimulatedPeripheralTimer: Sleep expired, waiting interrupt event mutex\r\n" );
\r
151 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
152 vPortTrace( "prvSimulatedPeripheralTimer: Got interrupt event mutex\r\n" );
\r
154 /* A thread will hold the interrupt event mutex while in a critical
\r
155 section, so ulCriticalSection should be zero for this tick event to be
\r
157 if( ulCriticalNesting != 0 )
\r
159 /* For a break point only. */
\r
163 /* The timer has expired, generate the simulated tick event. */
\r
164 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
166 /* The interrupt is now pending - notify the simulated interrupt
\r
168 vPortTrace( "prvSimulatedPeripheralTimer: Setting interrupt event to signal tick\r\n" );
\r
169 SetEvent( pvInterruptEvent );
\r
171 /* Give back the mutex so the pseudo interrupt handler unblocks
\r
172 and can access the interrupt handler variables. This high priority
\r
173 task will then loop back round after waiting for the lower priority
\r
174 pseudo interrupt handler thread to acknowledge the tick. */
\r
175 vPortTrace( "prvSimulatedPeripheralTimer: Releasing interrupt event mutex so tick can be processed\r\n" );
\r
176 SignalObjectAndWait( pvInterruptEventMutex, pvTickAcknowledgeEvent, INFINITE, FALSE );
\r
179 /*-----------------------------------------------------------*/
\r
181 portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
\r
183 xThreadState *pxThreadState = NULL;
\r
185 /* In this simulated case a stack is not initialised, but instead a thread
\r
186 is created that will execute the task being created. The thread handles
\r
187 the context switching itself. The xThreadState object is placed onto
\r
188 the stack that was created for the task - so the stack buffer is still
\r
189 used, just not in the conventional way. It will not be used for anything
\r
190 other than holding this structure. */
\r
191 pxThreadState = ( xThreadState * ) ( pxTopOfStack - sizeof( xThreadState ) );
\r
193 /* Create the thread itself. */
\r
194 pxThreadState->pvThread = ( void * ) CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );
\r
195 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
196 pxThreadState->lWaitingInterruptAck = pdFALSE;
\r
197 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
199 return ( portSTACK_TYPE * ) pxThreadState;
\r
201 /*-----------------------------------------------------------*/
\r
203 portBASE_TYPE xPortStartScheduler( void )
\r
206 long lSuccess = pdPASS;
\r
207 xThreadState *pxThreadState;
\r
209 /* Create the events and mutexes that are used to synchronise all the
\r
211 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
\r
212 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
213 pvTickAcknowledgeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
214 pvInterruptAcknowledgeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
216 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) || ( pvTickAcknowledgeEvent == NULL ) || ( pvInterruptAcknowledgeEvent == NULL ) )
\r
221 /* Set the priority of this thread such that it is above the priority of
\r
222 the threads that run tasks. This higher priority is required to ensure
\r
223 pseudo interrupts take priority over tasks. */
\r
224 SetPriorityClass( GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS );
\r
225 pvHandle = GetCurrentThread();
\r
226 if( pvHandle == NULL )
\r
231 if( lSuccess == pdPASS )
\r
233 if( SetThreadPriority( pvHandle, THREAD_PRIORITY_HIGHEST ) == 0 )
\r
237 SetThreadPriorityBoost( pvHandle, TRUE );
\r
240 if( lSuccess == pdPASS )
\r
242 /* Start the thread that simulates the timer peripheral to generate
\r
243 tick interrupts. */
\r
244 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );
\r
245 if( pvHandle != NULL )
\r
247 SetThreadPriority( pvHandle, THREAD_PRIORITY_HIGHEST );
\r
248 SetThreadPriorityBoost( pvHandle, TRUE );
\r
251 /* Start the highest priority task by obtaining its associated thread
\r
252 state structure, in which is stored the thread handle. */
\r
253 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
254 ulCriticalNesting = portNO_CRITICAL_NESTING;
\r
256 vPortTrace( "Created system threads, starting task" );
\r
258 /* Bump up the priority of the thread that is going to run, in the
\r
259 hope that this will asist in getting the Windows thread scheduler to
\r
260 behave as an embedded engineer might expect. */
\r
261 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
262 ResumeThread( pxThreadState->pvThread );
\r
264 /* Handle all pseudo interrupts - including yield requests and
\r
265 simulated ticks. */
\r
266 prvProcessPseudoInterrupts();
\r
269 /* Would not expect to return from prvProcessPseudoInterrupts(), so should
\r
273 /*-----------------------------------------------------------*/
\r
275 static void prvProcessPseudoInterrupts( void )
\r
277 long lSwitchRequired;
\r
278 xThreadState *pxThreadState;
\r
279 void *pvObjectList[ 2 ];
\r
281 //char cTraceBuffer[ 256 ];
\r
283 vPortTrace( "Entering prvProcessPseudoInterrupts\r\n" );
\r
285 /* Going to block on the mutex that ensured exclusive access to the pseudo
\r
286 interrupt objects, and the event that signals that a pseudo interrupt
\r
287 should be processed. */
\r
288 pvObjectList[ 0 ] = pvInterruptEventMutex;
\r
289 pvObjectList[ 1 ] = pvInterruptEvent;
\r
293 vPortTrace( "prvProcessPseudoInterrupts: Waiting for next interrupt event\r\n" );
\r
294 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
\r
295 vPortTrace( "prvProcessPseudoInterrupts: Got interrupt event and mutex\r\n" );
\r
297 /* A thread will hold the interrupt event mutex while in a critical
\r
298 section, so this pseudo interrupt handler should only run when
\r
299 critical nesting is zero. */
\r
300 if( ulCriticalNesting != 0 )
\r
302 /* For a break point only. */
\r
306 /* Used to indicate whether the pseudo interrupt processing has
\r
307 necessitated a context switch to another task/thread. */
\r
308 lSwitchRequired = pdFALSE;
\r
310 /* For each interrupt we are interested in processing, each of which is
\r
311 represented by a bit in the 32bit ulPendingInterrupts variable. */
\r
312 for( i = 0; i < portMAX_INTERRUPTS; i++ )
\r
314 /* Is the pseudo interrupt pending? */
\r
315 if( ulPendingInterrupts & ( 1UL << i ) )
\r
319 case portINTERRUPT_YIELD:
\r
321 vPortTrace( "prvProcessPseudoInterrupts: Processing Yield\r\n" );
\r
322 lSwitchRequired = pdTRUE;
\r
324 /* Clear the interrupt pending bit. */
\r
325 ulPendingInterrupts &= ~( 1UL << portINTERRUPT_YIELD );
\r
328 case portINTERRUPT_TICK:
\r
330 /* Tick interrupts should only be processed if the
\r
331 critical nesting count is zero. The critical nesting
\r
332 count represents the interrupt mask on real target
\r
333 hardware. The thread that genereates ticks will not
\r
334 actually ask for the tick to be processed unless the
\r
335 critical nesting count is zero anyway, but it is
\r
336 possible that a tick is pending when a yield is
\r
337 performed (depending on if the simulation/emulation is
\r
338 set up to process yields while within a critical
\r
340 vPortTrace( "prvProcessPseudoInterrupts: Processing tick event\r\n" );
\r
341 /* Process the tick itself. */
\r
342 vPortTrace( "prvProcessPseudoInterrupts: Incrementing tick\r\n" );
\r
343 vTaskIncrementTick();
\r
344 #if( configUSE_PREEMPTION != 0 )
\r
346 /* A context switch is only automatically
\r
347 performed from the tick interrupt if the
\r
348 pre-emptive scheduler is being used. */
\r
349 lSwitchRequired = pdTRUE;
\r
353 /* Clear the interrupt pending bit. */
\r
354 ulPendingInterrupts &= ~( 1UL << portINTERRUPT_TICK );
\r
356 vPortTrace( "prvProcessPseudoInterrupts: Acking tick\r\n" );
\r
357 SetEvent( pvTickAcknowledgeEvent );
\r
362 /* Is a handler installed? */
\r
363 if( vIsrHandler[ i ] != NULL )
\r
365 lSwitchRequired = pdTRUE;
\r
367 /* Run the actual handler. */
\r
368 vIsrHandler[ i ]();
\r
370 /* Clear the interrupt pending bit. */
\r
371 ulPendingInterrupts &= ~( 1UL << i );
\r
373 /* TODO: Need to have some sort of handshake
\r
374 event here for non-tick and none yield
\r
382 if( lSwitchRequired != pdFALSE )
\r
384 void *pvOldCurrentTCB;
\r
386 pvOldCurrentTCB = pxCurrentTCB;
\r
388 /* Select the next task to run. */
\r
389 vTaskSwitchContext();
\r
391 /* If the task selected to enter the running state is not the task
\r
392 that is already in the running state. */
\r
393 if( pvOldCurrentTCB != pxCurrentTCB )
\r
395 /* Suspend the old thread. */
\r
396 pxThreadState = ( xThreadState *) *( ( unsigned long * ) pvOldCurrentTCB );
\r
397 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
398 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
399 SuspendThread( pxThreadState->pvThread );
\r
403 /* NOTE! - Here lies a problem when the preemptive scheduler is
\r
404 used. It would seem Win32 threads do not stop as soon as a
\r
405 call to suspend them is made. The co-operative scheduler gets
\r
406 around this by having the thread block on a semaphore
\r
407 immediately after yielding so it cannot execute any more task
\r
408 code until it is once again scheduled to run. This cannot be
\r
409 done if the task is pre-empted though, and I have not found an
\r
410 equivalent work around for the preemptive situation. */
\r
414 //sprintf( cTraceBuffer, "Event processor: suspending %s, resuming %s\r\n", ((xTCB*)pvOldCurrentTCB)->pcTaskName, ((xTCB*)pxCurrentTCB)->pcTaskName );
\r
415 //vPortTrace( cTraceBuffer );
\r
417 /* Obtain the state of the task now selected to enter the
\r
419 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );
\r
421 /* Boost the priority of the thread selected to run a little
\r
422 in an attempt to get the Windows thread scheduler to act a
\r
423 little more like an embedded engineer might expect. */
\r
424 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
425 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
426 ResumeThread( pxThreadState->pvThread );
\r
430 /* On exiting a critical section a task may have blocked on the
\r
431 interrupt event when only a tick needed processing, in which case
\r
432 it will not have been released from waiting on the event yet. */
\r
433 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );
\r
434 if( pxThreadState->lWaitingInterruptAck == pdTRUE )
\r
436 pxThreadState->lWaitingInterruptAck = pdFALSE;
\r
437 vPortTrace( "prvProcessPseudoInterrupts: Acking interrupt even though a yield has not been performed.\r\n" );
\r
438 SetEvent( pvInterruptAcknowledgeEvent );
\r
441 ReleaseMutex( pvInterruptEventMutex );
\r
444 /*-----------------------------------------------------------*/
\r
446 void vPortEndScheduler( void )
\r
449 /*-----------------------------------------------------------*/
\r
451 void vPortGeneratePseudoInterrupt( unsigned long ulInterruptNumber )
\r
453 xThreadState *pxThreadState;
\r
455 if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
\r
457 /* Yield interrupts are processed even when critical nesting is non-zero. */
\r
458 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
459 ulPendingInterrupts |= ( 1 << ulInterruptNumber );
\r
461 /* The pseudo interrupt is now held pending, but don't actually process it
\r
462 yet if this call is within a critical section. It is possible for this to
\r
463 be in a critical section as calls to wait for mutexes are accumulative. */
\r
464 if( ulCriticalNesting == 0 )
\r
466 /* The event handler needs to know to signal the interrupt acknowledge event
\r
467 the next time this task runs. */
\r
468 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
469 pxThreadState->lWaitingInterruptAck = pdTRUE;
\r
471 vPortTrace( "vPortGeneratePseudoInterrupt: Got interrupt mutex, about to signal interrupt event\r\n" );
\r
472 SetEvent( pvInterruptEvent );
\r
474 /* The interrupt ack event should not be signaled yet - if it is then there
\r
475 is an error in the logical simulation. */
\r
476 if( WaitForSingleObject( pvInterruptAcknowledgeEvent, 0 ) != WAIT_TIMEOUT )
\r
478 /* This line is for a break point only. */
\r
482 SignalObjectAndWait( pvInterruptEventMutex, pvInterruptAcknowledgeEvent, INFINITE, FALSE );
\r
483 vPortTrace( "vPortGeneratePseudoInterrupt: Interrupt event mutex released, going to wait for interrupt ack\r\n" );
\r
487 ReleaseMutex( pvInterruptEventMutex );
\r
491 /*-----------------------------------------------------------*/
\r
493 void vPortSetInterruptHandler( unsigned long ulInterruptNumber, void (*pvHandler)( void ) )
\r
495 if( ulInterruptNumber < portMAX_INTERRUPTS )
\r
497 if( pvInterruptEventMutex != NULL )
\r
499 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
500 vIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
501 ReleaseMutex( pvInterruptEventMutex );
\r
505 vIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
509 /*-----------------------------------------------------------*/
\r
511 void vPortEnterCritical( void )
\r
513 if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
\r
515 /* The interrupt event mutex is held for the entire critical section,
\r
516 effectively disabling (pseudo) interrupts. */
\r
517 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
518 ulCriticalNesting++;
\r
522 ulCriticalNesting++;
\r
525 /*-----------------------------------------------------------*/
\r
527 void vPortExitCritical( void )
\r
529 xThreadState *pxThreadState;
\r
530 long lMutexNeedsReleasing;
\r
532 /* The interrupt event mutex should already be held by this thread as it was
\r
533 obtained on entry to the critical section. */
\r
535 lMutexNeedsReleasing = pdTRUE;
\r
537 if( ulCriticalNesting > portNO_CRITICAL_NESTING )
\r
539 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )
\r
541 ulCriticalNesting--;
\r
543 /* Were any interrupts set to pending while interrupts were
\r
544 (pseudo) disabled? */
\r
545 if( ulPendingInterrupts != 0UL )
\r
547 SetEvent( pvInterruptEvent );
\r
549 /* The event handler needs to know to signal the interrupt
\r
550 acknowledge event the next time this task runs. */
\r
551 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );
\r
552 pxThreadState->lWaitingInterruptAck = pdTRUE;
\r
554 /* Mutex will be released now, so does not require releasing
\r
555 on function exit. */
\r
556 lMutexNeedsReleasing = pdFALSE;
\r
557 SignalObjectAndWait( pvInterruptEventMutex, pvInterruptAcknowledgeEvent, INFINITE, FALSE );
\r
558 vPortTrace( "vPortExitCritical: Interrupt acknowledged, leaving critical section code\r\n" );
\r
563 /* Tick interrupts will still not be processed as the critical
\r
564 nesting depth will not be zero. */
\r
565 ulCriticalNesting--;
\r
569 if( lMutexNeedsReleasing == pdTRUE )
\r
571 ReleaseMutex( pvInterruptEventMutex );
\r