2 FreeRTOS V8.2.0rc1 - Copyright (C) 2014 Real Time Engineers Ltd.
\r
5 VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
\r
7 This file is part of the FreeRTOS distribution.
\r
9 FreeRTOS is free software; you can redistribute it and/or modify it under
\r
10 the terms of the GNU General Public License (version 2) as published by the
\r
11 Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
\r
13 >>! NOTE: The modification to the GPL is included to allow you to !<<
\r
14 >>! distribute a combined work that includes FreeRTOS without being !<<
\r
15 >>! obliged to provide the source code for proprietary components !<<
\r
16 >>! outside of the FreeRTOS kernel. !<<
\r
18 FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
\r
19 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
\r
20 FOR A PARTICULAR PURPOSE. Full license text is available on the following
\r
21 link: http://www.freertos.org/a00114.html
\r
25 ***************************************************************************
\r
27 * Having a problem? Start by reading the FAQ "My application does *
\r
28 * not run, what could be wrong?". Have you defined configASSERT()? *
\r
30 * http://www.FreeRTOS.org/FAQHelp.html *
\r
32 ***************************************************************************
\r
34 ***************************************************************************
\r
36 * FreeRTOS provides completely free yet professionally developed, *
\r
37 * robust, strictly quality controlled, supported, and cross *
\r
38 * platform software that is more than just the market leader, it *
\r
39 * is the industry's de facto standard. *
\r
41 * Help yourself get started quickly while simultaneously helping *
\r
42 * to support the FreeRTOS project by purchasing a FreeRTOS *
\r
43 * tutorial book, reference manual, or both: *
\r
44 * http://www.FreeRTOS.org/Documentation *
\r
46 ***************************************************************************
\r
48 ***************************************************************************
\r
50 * Investing in training allows your team to be as productive as *
\r
51 * possible as early as possible, lowering your overall development *
\r
52 * cost, and enabling you to bring a more robust product to market *
\r
53 * earlier than would otherwise be possible. Richard Barry is both *
\r
54 * the architect and key author of FreeRTOS, and so also the world's *
\r
55 * leading authority on what is the world's most popular real time *
\r
56 * kernel for deeply embedded MCU designs. Obtaining your training *
\r
57 * from Richard ensures your team will gain directly from his in-depth *
\r
58 * product knowledge and years of usage experience. Contact Real Time *
\r
59 * Engineers Ltd to enquire about the FreeRTOS Masterclass, presented *
\r
60 * by Richard Barry: http://www.FreeRTOS.org/contact
\r
62 ***************************************************************************
\r
64 ***************************************************************************
\r
66 * You are receiving this top quality software for free. Please play *
\r
67 * fair and reciprocate by reporting any suspected issues and *
\r
68 * participating in the community forum: *
\r
69 * http://www.FreeRTOS.org/support *
\r
73 ***************************************************************************
\r
75 http://www.FreeRTOS.org - Documentation, books, training, latest versions,
\r
76 license and Real Time Engineers Ltd. contact details.
\r
78 http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
\r
79 including FreeRTOS+Trace - an indispensable productivity tool, a DOS
\r
80 compatible FAT file system, and our tiny thread aware UDP/IP stack.
\r
82 http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
\r
83 Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
\r
85 http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
\r
86 Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
\r
87 licenses offer ticketed support, indemnification and commercial middleware.
\r
89 http://www.SafeRTOS.com - High Integrity Systems also provide a safety
\r
90 engineered and independently SIL3 certified version for use in safety and
\r
91 mission critical applications that require provable dependability.
\r
96 /* Standard includes. */
\r
99 /* Scheduler includes. */
\r
100 #include "FreeRTOS.h"
\r
104 #include "mmsystem.h"
\r
106 #pragma comment(lib, "winmm.lib")
\r
109 #define portMAX_INTERRUPTS ( ( uint32_t ) sizeof( uint32_t ) * 8UL ) /* The number of bits in an uint32_t. */
\r
110 #define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 )
\r
113 * Created as a high priority thread, this function uses a timer to simulate
\r
114 * a tick interrupt being generated on an embedded target. In this Windows
\r
115 * environment the timer does not achieve anything approaching real time
\r
116 * performance though.
\r
118 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );
\r
121 * Process all the simulated interrupts - each represented by a bit in
\r
122 * ulPendingInterrupts variable.
\r
124 static void prvProcessSimulatedInterrupts( void );
\r
127 * Interrupt handlers used by the kernel itself. These are executed from the
\r
128 * simulated interrupt handler thread.
\r
130 static uint32_t prvProcessYieldInterrupt( void );
\r
131 static uint32_t prvProcessTickInterrupt( void );
\r
134 * Called when the process exits to let Windows know the high timer resolution
\r
135 * is no longer required.
\r
137 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType );
\r
139 /*-----------------------------------------------------------*/
\r
141 /* The WIN32 simulator runs each task in a thread. The context switching is
\r
142 managed by the threads, so the task stack does not have to be managed directly,
\r
143 although the task stack is still used to hold an xThreadState structure this is
\r
144 the only thing it will ever hold. The structure indirectly maps the task handle
\r
145 to a thread handle. */
\r
148 /* Handle of the thread that executes the task. */
\r
153 /* Simulated interrupts waiting to be processed. This is a bit mask where each
\r
154 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */
\r
155 static volatile uint32_t ulPendingInterrupts = 0UL;
\r
157 /* An event used to inform the simulated interrupt processing thread (a high
\r
158 priority thread that simulated interrupt processing) that an interrupt is
\r
160 static void *pvInterruptEvent = NULL;
\r
162 /* Mutex used to protect all the simulated interrupt variables that are accessed
\r
163 by multiple threads. */
\r
164 static void *pvInterruptEventMutex = NULL;
\r
166 /* The critical nesting count for the currently executing task. This is
\r
167 initialised to a non-zero value so interrupts do not become enabled during
\r
168 the initialisation phase. As each task has its own critical nesting value
\r
169 ulCriticalNesting will get set to zero when the first task runs. This
\r
170 initialisation is probably not critical in this simulated environment as the
\r
171 simulated interrupt handlers do not get created until the FreeRTOS scheduler is
\r
173 static uint32_t ulCriticalNesting = 9999UL;
\r
175 /* Handlers for all the simulated software interrupts. The first two positions
\r
176 are used for the Yield and Tick interrupts so are handled slightly differently,
\r
177 all the other interrupts can be user defined. */
\r
178 static uint32_t (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };
\r
180 /* Pointer to the TCB of the currently executing task. */
\r
181 extern void *pxCurrentTCB;
\r
183 /* Used to ensure nothing is processed during the startup sequence. */
\r
184 static BaseType_t xPortRunning = pdFALSE;
\r
186 /*-----------------------------------------------------------*/
\r
188 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )
\r
190 TickType_t xMinimumWindowsBlockTime;
\r
191 TIMECAPS xTimeCaps;
\r
193 /* Set the timer resolution to the maximum possible. */
\r
194 if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
\r
196 xMinimumWindowsBlockTime = ( TickType_t ) xTimeCaps.wPeriodMin;
\r
197 timeBeginPeriod( xTimeCaps.wPeriodMin );
\r
199 /* Register an exit handler so the timeBeginPeriod() function can be
\r
200 matched with a timeEndPeriod() when the application exits. */
\r
201 SetConsoleCtrlHandler( prvEndProcess, TRUE );
\r
205 xMinimumWindowsBlockTime = ( TickType_t ) 20;
\r
208 /* Just to prevent compiler warnings. */
\r
209 ( void ) lpParameter;
\r
213 /* Wait until the timer expires and we can access the simulated interrupt
\r
214 variables. *NOTE* this is not a 'real time' way of generating tick
\r
215 events as the next wake time should be relative to the previous wake
\r
216 time, not the time that Sleep() is called. It is done this way to
\r
217 prevent overruns in this very non real time simulated/emulated
\r
219 if( portTICK_PERIOD_MS < xMinimumWindowsBlockTime )
\r
221 Sleep( xMinimumWindowsBlockTime );
\r
225 Sleep( portTICK_PERIOD_MS );
\r
228 configASSERT( xPortRunning );
\r
230 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
232 /* The timer has expired, generate the simulated tick event. */
\r
233 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
235 /* The interrupt is now pending - notify the simulated interrupt
\r
237 if( ulCriticalNesting == 0 )
\r
239 SetEvent( pvInterruptEvent );
\r
242 /* Give back the mutex so the simulated interrupt handler unblocks
\r
243 and can access the interrupt handler variables. */
\r
244 ReleaseMutex( pvInterruptEventMutex );
\r
248 /* Should never reach here - MingW complains if you leave this line out,
\r
249 MSVC complains if you put it in. */
\r
253 /*-----------------------------------------------------------*/
\r
255 static BOOL WINAPI prvEndProcess( DWORD dwCtrlType )
\r
257 TIMECAPS xTimeCaps;
\r
259 ( void ) dwCtrlType;
\r
261 if( timeGetDevCaps( &xTimeCaps, sizeof( xTimeCaps ) ) == MMSYSERR_NOERROR )
\r
263 /* Match the call to timeBeginPeriod( xTimeCaps.wPeriodMin ) made when
\r
264 the process started with a timeEndPeriod() as the process exits. */
\r
265 timeEndPeriod( xTimeCaps.wPeriodMin );
\r
270 /*-----------------------------------------------------------*/
\r
272 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
\r
274 xThreadState *pxThreadState = NULL;
\r
275 int8_t *pcTopOfStack = ( int8_t * ) pxTopOfStack;
\r
277 /* In this simulated case a stack is not initialised, but instead a thread
\r
278 is created that will execute the task being created. The thread handles
\r
279 the context switching itself. The xThreadState object is placed onto
\r
280 the stack that was created for the task - so the stack buffer is still
\r
281 used, just not in the conventional way. It will not be used for anything
\r
282 other than holding this structure. */
\r
283 pxThreadState = ( xThreadState * ) ( pcTopOfStack - sizeof( xThreadState ) );
\r
285 /* Create the thread itself. */
\r
286 pxThreadState->pvThread = CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );
\r
287 configASSERT( pxThreadState->pvThread );
\r
288 SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );
\r
289 SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );
\r
290 SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );
\r
292 return ( StackType_t * ) pxThreadState;
\r
294 /*-----------------------------------------------------------*/
\r
296 BaseType_t xPortStartScheduler( void )
\r
299 int32_t lSuccess = pdPASS;
\r
300 xThreadState *pxThreadState;
\r
302 /* Install the interrupt handlers used by the scheduler itself. */
\r
303 vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );
\r
304 vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );
\r
306 /* Create the events and mutexes that are used to synchronise all the
\r
308 pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
\r
309 pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
\r
311 if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )
\r
316 /* Set the priority of this thread such that it is above the priority of
\r
317 the threads that run tasks. This higher priority is required to ensure
\r
318 simulated interrupts take priority over tasks. */
\r
319 pvHandle = GetCurrentThread();
\r
320 if( pvHandle == NULL )
\r
325 if( lSuccess == pdPASS )
\r
327 if( SetThreadPriority( pvHandle, THREAD_PRIORITY_NORMAL ) == 0 )
\r
331 SetThreadPriorityBoost( pvHandle, TRUE );
\r
332 SetThreadAffinityMask( pvHandle, 0x01 );
\r
335 if( lSuccess == pdPASS )
\r
337 /* Start the thread that simulates the timer peripheral to generate
\r
338 tick interrupts. The priority is set below that of the simulated
\r
339 interrupt handler so the interrupt event mutex is used for the
\r
340 handshake / overrun protection. */
\r
341 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );
\r
342 if( pvHandle != NULL )
\r
344 SetThreadPriority( pvHandle, THREAD_PRIORITY_BELOW_NORMAL );
\r
345 SetThreadPriorityBoost( pvHandle, TRUE );
\r
346 SetThreadAffinityMask( pvHandle, 0x01 );
\r
349 /* Start the highest priority task by obtaining its associated thread
\r
350 state structure, in which is stored the thread handle. */
\r
351 pxThreadState = ( xThreadState * ) *( ( uint32_t * ) pxCurrentTCB );
\r
352 ulCriticalNesting = portNO_CRITICAL_NESTING;
\r
354 /* Bump up the priority of the thread that is going to run, in the
\r
355 hope that this will assist in getting the Windows thread scheduler to
\r
356 behave as an embedded engineer might expect. */
\r
357 ResumeThread( pxThreadState->pvThread );
\r
359 /* Handle all simulated interrupts - including yield requests and
\r
360 simulated ticks. */
\r
361 prvProcessSimulatedInterrupts();
\r
364 /* Would not expect to return from prvProcessSimulatedInterrupts(), so should
\r
368 /*-----------------------------------------------------------*/
\r
370 static uint32_t prvProcessYieldInterrupt( void )
\r
374 /*-----------------------------------------------------------*/
\r
376 static uint32_t prvProcessTickInterrupt( void )
\r
378 uint32_t ulSwitchRequired;
\r
380 /* Process the tick itself. */
\r
381 configASSERT( xPortRunning );
\r
382 ulSwitchRequired = ( uint32_t ) xTaskIncrementTick();
\r
384 return ulSwitchRequired;
\r
386 /*-----------------------------------------------------------*/
\r
388 static void prvProcessSimulatedInterrupts( void )
\r
390 uint32_t ulSwitchRequired, i;
\r
391 xThreadState *pxThreadState;
\r
392 void *pvObjectList[ 2 ];
\r
394 /* Going to block on the mutex that ensured exclusive access to the simulated
\r
395 interrupt objects, and the event that signals that a simulated interrupt
\r
396 should be processed. */
\r
397 pvObjectList[ 0 ] = pvInterruptEventMutex;
\r
398 pvObjectList[ 1 ] = pvInterruptEvent;
\r
400 /* Create a pending tick to ensure the first task is started as soon as
\r
401 this thread pends. */
\r
402 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
\r
403 SetEvent( pvInterruptEvent );
\r
405 xPortRunning = pdTRUE;
\r
409 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );
\r
411 /* Used to indicate whether the simulated interrupt processing has
\r
412 necessitated a context switch to another task/thread. */
\r
413 ulSwitchRequired = pdFALSE;
\r
415 /* For each interrupt we are interested in processing, each of which is
\r
416 represented by a bit in the 32bit ulPendingInterrupts variable. */
\r
417 for( i = 0; i < portMAX_INTERRUPTS; i++ )
\r
419 /* Is the simulated interrupt pending? */
\r
420 if( ulPendingInterrupts & ( 1UL << i ) )
\r
422 /* Is a handler installed? */
\r
423 if( ulIsrHandler[ i ] != NULL )
\r
425 /* Run the actual handler. */
\r
426 if( ulIsrHandler[ i ]() != pdFALSE )
\r
428 ulSwitchRequired |= ( 1 << i );
\r
432 /* Clear the interrupt pending bit. */
\r
433 ulPendingInterrupts &= ~( 1UL << i );
\r
437 if( ulSwitchRequired != pdFALSE )
\r
439 void *pvOldCurrentTCB;
\r
441 pvOldCurrentTCB = pxCurrentTCB;
\r
443 /* Select the next task to run. */
\r
444 vTaskSwitchContext();
\r
446 /* If the task selected to enter the running state is not the task
\r
447 that is already in the running state. */
\r
448 if( pvOldCurrentTCB != pxCurrentTCB )
\r
450 /* Suspend the old thread. */
\r
451 pxThreadState = ( xThreadState *) *( ( uint32_t * ) pvOldCurrentTCB );
\r
452 SuspendThread( pxThreadState->pvThread );
\r
454 /* Obtain the state of the task now selected to enter the
\r
456 pxThreadState = ( xThreadState * ) ( *( uint32_t *) pxCurrentTCB );
\r
457 ResumeThread( pxThreadState->pvThread );
\r
461 ReleaseMutex( pvInterruptEventMutex );
\r
464 /*-----------------------------------------------------------*/
\r
466 void vPortDeleteThread( void *pvTaskToDelete )
\r
468 xThreadState *pxThreadState;
\r
469 uint32_t ulErrorCode;
\r
471 /* Remove compiler warnings if configASSERT() is not defined. */
\r
472 ( void ) ulErrorCode;
\r
474 /* Find the handle of the thread being deleted. */
\r
475 pxThreadState = ( xThreadState * ) ( *( uint32_t *) pvTaskToDelete );
\r
477 /* Check that the thread is still valid, it might have been closed by
\r
478 vPortCloseRunningThread() - which will be the case if the task associated
\r
479 with the thread originally deleted itself rather than being deleted by a
\r
481 if( pxThreadState->pvThread != NULL )
\r
483 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
485 ulErrorCode = TerminateThread( pxThreadState->pvThread, 0 );
\r
486 configASSERT( ulErrorCode );
\r
488 ulErrorCode = CloseHandle( pxThreadState->pvThread );
\r
489 configASSERT( ulErrorCode );
\r
491 ReleaseMutex( pvInterruptEventMutex );
\r
494 /*-----------------------------------------------------------*/
\r
496 void vPortCloseRunningThread( void *pvTaskToDelete, volatile BaseType_t *pxPendYield )
\r
498 xThreadState *pxThreadState;
\r
500 uint32_t ulErrorCode;
\r
502 /* Remove compiler warnings if configASSERT() is not defined. */
\r
503 ( void ) ulErrorCode;
\r
505 /* Find the handle of the thread being deleted. */
\r
506 pxThreadState = ( xThreadState * ) ( *( uint32_t *) pvTaskToDelete );
\r
507 pvThread = pxThreadState->pvThread;
\r
509 /* Raise the Windows priority of the thread to ensure the FreeRTOS scheduler
\r
510 does not run and swap it out before it is closed. If that were to happen
\r
511 the thread would never run again and effectively be a thread handle and
\r
513 SetThreadPriority( pvThread, THREAD_PRIORITY_ABOVE_NORMAL );
\r
515 /* This function will not return, therefore a yield is set as pending to
\r
516 ensure a context switch occurs away from this thread on the next tick. */
\r
517 *pxPendYield = pdTRUE;
\r
519 /* Mark the thread associated with this task as invalid so
\r
520 vPortDeleteThread() does not try to terminate it. */
\r
521 pxThreadState->pvThread = NULL;
\r
523 /* Close the thread. */
\r
524 ulErrorCode = CloseHandle( pvThread );
\r
525 configASSERT( ulErrorCode );
\r
529 /*-----------------------------------------------------------*/
\r
531 void vPortEndScheduler( void )
\r
533 /* This function IS NOT TESTED! */
\r
534 TerminateProcess( GetCurrentProcess(), 0 );
\r
536 /*-----------------------------------------------------------*/
\r
538 void vPortGenerateSimulatedInterrupt( uint32_t ulInterruptNumber )
\r
540 configASSERT( xPortRunning );
\r
542 if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )
\r
544 /* Yield interrupts are processed even when critical nesting is non-zero. */
\r
545 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
546 ulPendingInterrupts |= ( 1 << ulInterruptNumber );
\r
548 /* The simulated interrupt is now held pending, but don't actually process it
\r
549 yet if this call is within a critical section. It is possible for this to
\r
550 be in a critical section as calls to wait for mutexes are accumulative. */
\r
551 if( ulCriticalNesting == 0 )
\r
553 SetEvent( pvInterruptEvent );
\r
556 ReleaseMutex( pvInterruptEventMutex );
\r
559 /*-----------------------------------------------------------*/
\r
561 void vPortSetInterruptHandler( uint32_t ulInterruptNumber, uint32_t (*pvHandler)( void ) )
\r
563 if( ulInterruptNumber < portMAX_INTERRUPTS )
\r
565 if( pvInterruptEventMutex != NULL )
\r
567 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
568 ulIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
569 ReleaseMutex( pvInterruptEventMutex );
\r
573 ulIsrHandler[ ulInterruptNumber ] = pvHandler;
\r
577 /*-----------------------------------------------------------*/
\r
579 void vPortEnterCritical( void )
\r
581 if( xPortRunning == pdTRUE )
\r
583 /* The interrupt event mutex is held for the entire critical section,
\r
584 effectively disabling (simulated) interrupts. */
\r
585 WaitForSingleObject( pvInterruptEventMutex, INFINITE );
\r
586 ulCriticalNesting++;
\r
590 ulCriticalNesting++;
\r
593 /*-----------------------------------------------------------*/
\r
595 void vPortExitCritical( void )
\r
597 int32_t lMutexNeedsReleasing;
\r
599 /* The interrupt event mutex should already be held by this thread as it was
\r
600 obtained on entry to the critical section. */
\r
602 lMutexNeedsReleasing = pdTRUE;
\r
604 if( ulCriticalNesting > portNO_CRITICAL_NESTING )
\r
606 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )
\r
608 ulCriticalNesting--;
\r
610 /* Were any interrupts set to pending while interrupts were
\r
611 (simulated) disabled? */
\r
612 if( ulPendingInterrupts != 0UL )
\r
614 configASSERT( xPortRunning );
\r
615 SetEvent( pvInterruptEvent );
\r
617 /* Mutex will be released now, so does not require releasing
\r
618 on function exit. */
\r
619 lMutexNeedsReleasing = pdFALSE;
\r
620 ReleaseMutex( pvInterruptEventMutex );
\r
625 /* Tick interrupts will still not be processed as the critical
\r
626 nesting depth will not be zero. */
\r
627 ulCriticalNesting--;
\r
631 if( pvInterruptEventMutex != NULL )
\r
633 if( lMutexNeedsReleasing == pdTRUE )
\r
635 configASSERT( xPortRunning );
\r
636 ReleaseMutex( pvInterruptEventMutex );
\r
640 /*-----------------------------------------------------------*/
\r