]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/MSVC-MingW/port.c
Update version numbers to V7.4.1.
[freertos] / FreeRTOS / Source / portable / MSVC-MingW / port.c
1 /*\r
2     FreeRTOS V7.4.1 - Copyright (C) 2013 Real Time Engineers Ltd.\r
3 \r
4     FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME.  PLEASE VISIT\r
5     http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     ***************************************************************************\r
8      *                                                                       *\r
9      *    FreeRTOS tutorial books are available in pdf and paperback.        *\r
10      *    Complete, revised, and edited pdf reference manuals are also       *\r
11      *    available.                                                         *\r
12      *                                                                       *\r
13      *    Purchasing FreeRTOS documentation will not only help you, by       *\r
14      *    ensuring you get running as quickly as possible and with an        *\r
15      *    in-depth knowledge of how to use FreeRTOS, it will also help       *\r
16      *    the FreeRTOS project to continue with its mission of providing     *\r
17      *    professional grade, cross platform, de facto standard solutions    *\r
18      *    for microcontrollers - completely free of charge!                  *\r
19      *                                                                       *\r
20      *    >>> See http://www.FreeRTOS.org/Documentation for details. <<<     *\r
21      *                                                                       *\r
22      *    Thank you for using FreeRTOS, and thank you for your support!      *\r
23      *                                                                       *\r
24     ***************************************************************************\r
25 \r
26 \r
27     This file is part of the FreeRTOS distribution.\r
28 \r
29     FreeRTOS is free software; you can redistribute it and/or modify it under\r
30     the terms of the GNU General Public License (version 2) as published by the\r
31     Free Software Foundation AND MODIFIED BY the FreeRTOS exception.\r
32 \r
33     >>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to\r
34     distribute a combined work that includes FreeRTOS without being obliged to\r
35     provide the source code for proprietary components outside of the FreeRTOS\r
36     kernel.\r
37 \r
38     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
39     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
40     FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\r
41     details. You should have received a copy of the GNU General Public License\r
42     and the FreeRTOS license exception along with FreeRTOS; if not it can be\r
43     viewed here: http://www.freertos.org/a00114.html and also obtained by\r
44     writing to Real Time Engineers Ltd., contact details for whom are available\r
45     on the FreeRTOS WEB site.\r
46 \r
47     1 tab == 4 spaces!\r
48 \r
49     ***************************************************************************\r
50      *                                                                       *\r
51      *    Having a problem?  Start by reading the FAQ "My application does   *\r
52      *    not run, what could be wrong?"                                     *\r
53      *                                                                       *\r
54      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
55      *                                                                       *\r
56     ***************************************************************************\r
57 \r
58 \r
59     http://www.FreeRTOS.org - Documentation, books, training, latest versions, \r
60     license and Real Time Engineers Ltd. contact details.\r
61 \r
62     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
63     including FreeRTOS+Trace - an indispensable productivity tool, and our new\r
64     fully thread aware and reentrant UDP/IP stack.\r
65 \r
66     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High \r
67     Integrity Systems, who sell the code with commercial support, \r
68     indemnification and middleware, under the OpenRTOS brand.\r
69     \r
70     http://www.SafeRTOS.com - High Integrity Systems also provide a safety \r
71     engineered and independently SIL3 certified version for use in safety and \r
72     mission critical applications that require provable dependability.\r
73 */\r
74 \r
75 /* Scheduler includes. */\r
76 #include "FreeRTOS.h"\r
77 #include "task.h"\r
78 #include <stdio.h>\r
79 \r
80 #define portMAX_INTERRUPTS                              ( ( unsigned long ) sizeof( unsigned long ) * 8UL ) /* The number of bits in an unsigned long. */\r
81 #define portNO_CRITICAL_NESTING                 ( ( unsigned long ) 0 )\r
82 \r
83 /*\r
84  * Created as a high priority thread, this function uses a timer to simulate\r
85  * a tick interrupt being generated on an embedded target.  In this Windows\r
86  * environment the timer does not achieve anything approaching real time \r
87  * performance though.\r
88  */\r
89 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter );\r
90 \r
91 /* \r
92  * Process all the simulated interrupts - each represented by a bit in \r
93  * ulPendingInterrupts variable.\r
94  */\r
95 static void prvProcessSimulatedInterrupts( void );\r
96 \r
97 /*\r
98  * Interrupt handlers used by the kernel itself.  These are executed from the\r
99  * simulated interrupt handler thread.\r
100  */\r
101 static unsigned long prvProcessYieldInterrupt( void );\r
102 static unsigned long prvProcessTickInterrupt( void );\r
103 \r
104 /*-----------------------------------------------------------*/\r
105 \r
106 /* The WIN32 simulator runs each task in a thread.  The context switching is\r
107 managed by the threads, so the task stack does not have to be managed directly,\r
108 although the task stack is still used to hold an xThreadState structure this is\r
109 the only thing it will ever hold.  The structure indirectly maps the task handle \r
110 to a thread handle. */\r
111 typedef struct\r
112 {\r
113         /* Handle of the thread that executes the task. */\r
114         void *pvThread;\r
115 \r
116 } xThreadState;\r
117 \r
118 /* Simulated interrupts waiting to be processed.  This is a bit mask where each\r
119 bit represents one interrupt, so a maximum of 32 interrupts can be simulated. */\r
120 static volatile unsigned long ulPendingInterrupts = 0UL;\r
121 \r
122 /* An event used to inform the simulated interrupt processing thread (a high \r
123 priority thread that simulated interrupt processing) that an interrupt is\r
124 pending. */\r
125 static void *pvInterruptEvent = NULL;\r
126 \r
127 /* Mutex used to protect all the simulated interrupt variables that are accessed \r
128 by multiple threads. */\r
129 static void *pvInterruptEventMutex = NULL;\r
130 \r
131 /* The critical nesting count for the currently executing task.  This is \r
132 initialised to a non-zero value so interrupts do not become enabled during \r
133 the initialisation phase.  As each task has its own critical nesting value \r
134 ulCriticalNesting will get set to zero when the first task runs.  This \r
135 initialisation is probably not critical in this simulated environment as the\r
136 simulated interrupt handlers do not get created until the FreeRTOS scheduler is \r
137 started anyway. */\r
138 static unsigned long ulCriticalNesting = 9999UL;\r
139 \r
140 /* Handlers for all the simulated software interrupts.  The first two positions\r
141 are used for the Yield and Tick interrupts so are handled slightly differently,\r
142 all the other interrupts can be user defined. */\r
143 static unsigned long (*ulIsrHandler[ portMAX_INTERRUPTS ])( void ) = { 0 };\r
144 \r
145 /* Pointer to the TCB of the currently executing task. */\r
146 extern void *pxCurrentTCB;\r
147 \r
148 /*-----------------------------------------------------------*/\r
149 \r
150 static DWORD WINAPI prvSimulatedPeripheralTimer( LPVOID lpParameter )\r
151 {\r
152 portTickType xMinimumWindowsBlockTime = ( portTickType ) 20;\r
153 \r
154         /* Just to prevent compiler warnings. */\r
155         ( void ) lpParameter;\r
156 \r
157         for(;;)\r
158         {\r
159                 /* Wait until the timer expires and we can access the simulated interrupt \r
160                 variables.  *NOTE* this is not a 'real time' way of generating tick \r
161                 events as the next wake time should be relative to the previous wake \r
162                 time, not the time that Sleep() is called.  It is done this way to \r
163                 prevent overruns in this very non real time simulated/emulated \r
164                 environment. */\r
165                 if( portTICK_RATE_MS < xMinimumWindowsBlockTime )\r
166                 {\r
167                         Sleep( xMinimumWindowsBlockTime );\r
168                 }\r
169                 else\r
170                 {\r
171                         Sleep( portTICK_RATE_MS );\r
172                 }\r
173 \r
174                 WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
175 \r
176                 /* The timer has expired, generate the simulated tick event. */\r
177                 ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );\r
178 \r
179                 /* The interrupt is now pending - notify the simulated interrupt \r
180                 handler thread. */\r
181                 SetEvent( pvInterruptEvent );\r
182 \r
183                 /* Give back the mutex so the simulated interrupt handler unblocks \r
184                 and can access the interrupt handler variables. */\r
185                 ReleaseMutex( pvInterruptEventMutex );\r
186         }\r
187 \r
188         #ifdef __GNUC__\r
189                 /* Should never reach here - MingW complains if you leave this line out,\r
190                 MSVC complains if you put it in. */\r
191                 return 0;\r
192         #endif\r
193 }\r
194 /*-----------------------------------------------------------*/\r
195 \r
196 portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )\r
197 {\r
198 xThreadState *pxThreadState = NULL;\r
199 \r
200         /* In this simulated case a stack is not initialised, but instead a thread\r
201         is created that will execute the task being created.  The thread handles\r
202         the context switching itself.  The xThreadState object is placed onto\r
203         the stack that was created for the task - so the stack buffer is still\r
204         used, just not in the conventional way.  It will not be used for anything\r
205         other than holding this structure. */\r
206         pxThreadState = ( xThreadState * ) ( pxTopOfStack - sizeof( xThreadState ) );\r
207 \r
208         /* Create the thread itself. */\r
209         pxThreadState->pvThread = CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) pxCode, pvParameters, CREATE_SUSPENDED, NULL );\r
210         SetThreadAffinityMask( pxThreadState->pvThread, 0x01 );\r
211         SetThreadPriorityBoost( pxThreadState->pvThread, TRUE );\r
212         SetThreadPriority( pxThreadState->pvThread, THREAD_PRIORITY_IDLE );\r
213         \r
214         return ( portSTACK_TYPE * ) pxThreadState;\r
215 }\r
216 /*-----------------------------------------------------------*/\r
217 \r
218 portBASE_TYPE xPortStartScheduler( void )\r
219 {\r
220 void *pvHandle;\r
221 long lSuccess = pdPASS;\r
222 xThreadState *pxThreadState;\r
223 \r
224         /* Install the interrupt handlers used by the scheduler itself. */\r
225         vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );\r
226         vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );\r
227 \r
228         /* Create the events and mutexes that are used to synchronise all the\r
229         threads. */\r
230         pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );\r
231         pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
232 \r
233         if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )\r
234         {\r
235                 lSuccess = pdFAIL;\r
236         }\r
237 \r
238         /* Set the priority of this thread such that it is above the priority of \r
239         the threads that run tasks.  This higher priority is required to ensure\r
240         simulated interrupts take priority over tasks. */\r
241         pvHandle = GetCurrentThread();\r
242         if( pvHandle == NULL )\r
243         {\r
244                 lSuccess = pdFAIL;\r
245         }\r
246         \r
247         if( lSuccess == pdPASS )\r
248         {\r
249                 if( SetThreadPriority( pvHandle, THREAD_PRIORITY_NORMAL ) == 0 )\r
250                 {\r
251                         lSuccess = pdFAIL;\r
252                 }\r
253                 SetThreadPriorityBoost( pvHandle, TRUE );\r
254                 SetThreadAffinityMask( pvHandle, 0x01 );\r
255         }\r
256 \r
257         if( lSuccess == pdPASS )\r
258         {\r
259                 /* Start the thread that simulates the timer peripheral to generate\r
260                 tick interrupts.  The priority is set below that of the simulated \r
261                 interrupt handler so the interrupt event mutex is used for the\r
262                 handshake / overrun protection. */\r
263                 pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );\r
264                 if( pvHandle != NULL )\r
265                 {\r
266                         SetThreadPriority( pvHandle, THREAD_PRIORITY_BELOW_NORMAL );\r
267                         SetThreadPriorityBoost( pvHandle, TRUE );\r
268                         SetThreadAffinityMask( pvHandle, 0x01 );\r
269                 }\r
270                 \r
271                 /* Start the highest priority task by obtaining its associated thread \r
272                 state structure, in which is stored the thread handle. */\r
273                 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );\r
274                 ulCriticalNesting = portNO_CRITICAL_NESTING;\r
275 \r
276                 /* Bump up the priority of the thread that is going to run, in the\r
277                 hope that this will asist in getting the Windows thread scheduler to\r
278                 behave as an embedded engineer might expect. */\r
279                 ResumeThread( pxThreadState->pvThread );\r
280 \r
281                 /* Handle all simulated interrupts - including yield requests and \r
282                 simulated ticks. */\r
283                 prvProcessSimulatedInterrupts();\r
284         }       \r
285         \r
286         /* Would not expect to return from prvProcessSimulatedInterrupts(), so should \r
287         not get here. */\r
288         return 0;\r
289 }\r
290 /*-----------------------------------------------------------*/\r
291 \r
292 static unsigned long prvProcessYieldInterrupt( void )\r
293 {\r
294         return pdTRUE;\r
295 }\r
296 /*-----------------------------------------------------------*/\r
297 \r
298 static unsigned long prvProcessTickInterrupt( void )\r
299 {\r
300 unsigned long ulSwitchRequired;\r
301 \r
302         /* Process the tick itself. */\r
303         vTaskIncrementTick();\r
304         #if( configUSE_PREEMPTION != 0 )\r
305         {\r
306                 /* A context switch is only automatically performed from the tick\r
307                 interrupt if the pre-emptive scheduler is being used. */\r
308                 ulSwitchRequired = pdTRUE;\r
309         }\r
310         #else\r
311         {\r
312                 ulSwitchRequired = pdFALSE;\r
313         }\r
314         #endif\r
315 \r
316         return ulSwitchRequired;\r
317 }\r
318 /*-----------------------------------------------------------*/\r
319 \r
320 static void prvProcessSimulatedInterrupts( void )\r
321 {\r
322 unsigned long ulSwitchRequired, i;\r
323 xThreadState *pxThreadState;\r
324 void *pvObjectList[ 2 ];\r
325 \r
326         /* Going to block on the mutex that ensured exclusive access to the simulated \r
327         interrupt objects, and the event that signals that a simulated interrupt\r
328         should be processed. */\r
329         pvObjectList[ 0 ] = pvInterruptEventMutex;\r
330         pvObjectList[ 1 ] = pvInterruptEvent;\r
331 \r
332         for(;;)\r
333         {\r
334                 WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );\r
335 \r
336                 /* Used to indicate whether the simulated interrupt processing has\r
337                 necessitated a context switch to another task/thread. */\r
338                 ulSwitchRequired = pdFALSE;\r
339 \r
340                 /* For each interrupt we are interested in processing, each of which is\r
341                 represented by a bit in the 32bit ulPendingInterrupts variable. */\r
342                 for( i = 0; i < portMAX_INTERRUPTS; i++ )\r
343                 {\r
344                         /* Is the simulated interrupt pending? */\r
345                         if( ulPendingInterrupts & ( 1UL << i ) )\r
346                         {\r
347                                 /* Is a handler installed? */\r
348                                 if( ulIsrHandler[ i ] != NULL )\r
349                                 {\r
350                                         /* Run the actual handler. */\r
351                                         if( ulIsrHandler[ i ]() != pdFALSE )\r
352                                         {\r
353                                                 ulSwitchRequired |= ( 1 << i );\r
354                                         }\r
355                                 }\r
356 \r
357                                 /* Clear the interrupt pending bit. */\r
358                                 ulPendingInterrupts &= ~( 1UL << i );\r
359                         }\r
360                 }\r
361 \r
362                 if( ulSwitchRequired != pdFALSE )\r
363                 {\r
364                         void *pvOldCurrentTCB;\r
365 \r
366                         pvOldCurrentTCB = pxCurrentTCB;\r
367 \r
368                         /* Select the next task to run. */\r
369                         vTaskSwitchContext();\r
370 \r
371                         /* If the task selected to enter the running state is not the task\r
372                         that is already in the running state. */\r
373                         if( pvOldCurrentTCB != pxCurrentTCB )\r
374                         {\r
375                                 /* Suspend the old thread. */\r
376                                 pxThreadState = ( xThreadState *) *( ( unsigned long * ) pvOldCurrentTCB );\r
377                                 SuspendThread( pxThreadState->pvThread );\r
378 \r
379                                 /* Obtain the state of the task now selected to enter the \r
380                                 Running state. */\r
381                                 pxThreadState = ( xThreadState * ) ( *( unsigned long *) pxCurrentTCB );\r
382                                 ResumeThread( pxThreadState->pvThread );\r
383                         }\r
384                 }\r
385 \r
386                 ReleaseMutex( pvInterruptEventMutex );\r
387         }\r
388 }\r
389 /*-----------------------------------------------------------*/\r
390 \r
391 void vPortDeleteThread( void *pvTaskToDelete )\r
392 {\r
393 xThreadState *pxThreadState;\r
394 \r
395         WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
396 \r
397         /* Find the handle of the thread being deleted. */\r
398         pxThreadState = ( xThreadState * ) ( *( unsigned long *) pvTaskToDelete );\r
399         TerminateThread( pxThreadState->pvThread, 0 );\r
400 \r
401         ReleaseMutex( pvInterruptEventMutex );\r
402 }\r
403 /*-----------------------------------------------------------*/\r
404 \r
405 void vPortEndScheduler( void )\r
406 {\r
407         /* This function IS NOT TESTED! */\r
408         TerminateProcess( GetCurrentProcess(), 0 );\r
409 }\r
410 /*-----------------------------------------------------------*/\r
411 \r
412 void vPortGenerateSimulatedInterrupt( unsigned long ulInterruptNumber )\r
413 {\r
414 xThreadState *pxThreadState;\r
415 \r
416         if( ( ulInterruptNumber < portMAX_INTERRUPTS ) && ( pvInterruptEventMutex != NULL ) )\r
417         {\r
418                 /* Yield interrupts are processed even when critical nesting is non-zero. */\r
419                 WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
420                 ulPendingInterrupts |= ( 1 << ulInterruptNumber );\r
421 \r
422                 /* The simulated interrupt is now held pending, but don't actually process it\r
423                 yet if this call is within a critical section.  It is possible for this to\r
424                 be in a critical section as calls to wait for mutexes are accumulative. */\r
425                 if( ulCriticalNesting == 0 )\r
426                 {\r
427                         /* The event handler needs to know to signal the interrupt acknowledge event\r
428                         the next time this task runs. */\r
429                         pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );\r
430                         SetEvent( pvInterruptEvent );                   \r
431                 }\r
432 \r
433                 ReleaseMutex( pvInterruptEventMutex );\r
434         }\r
435 }\r
436 /*-----------------------------------------------------------*/\r
437 \r
438 void vPortSetInterruptHandler( unsigned long ulInterruptNumber, unsigned long (*pvHandler)( void ) )\r
439 {\r
440         if( ulInterruptNumber < portMAX_INTERRUPTS )\r
441         {\r
442                 if( pvInterruptEventMutex != NULL )\r
443                 {\r
444                         WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
445                         ulIsrHandler[ ulInterruptNumber ] = pvHandler;\r
446                         ReleaseMutex( pvInterruptEventMutex );\r
447                 }\r
448                 else\r
449                 {\r
450                         ulIsrHandler[ ulInterruptNumber ] = pvHandler;\r
451                 }\r
452         }\r
453 }\r
454 /*-----------------------------------------------------------*/\r
455 \r
456 void vPortEnterCritical( void )\r
457 {\r
458         if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )\r
459         {\r
460                 /* The interrupt event mutex is held for the entire critical section,\r
461                 effectively disabling (simulated) interrupts. */\r
462                 WaitForSingleObject( pvInterruptEventMutex, INFINITE );\r
463                 ulCriticalNesting++;\r
464         }\r
465         else\r
466         {\r
467                 ulCriticalNesting++;\r
468         }       \r
469 }\r
470 /*-----------------------------------------------------------*/\r
471 \r
472 void vPortExitCritical( void )\r
473 {\r
474 xThreadState *pxThreadState;\r
475 long lMutexNeedsReleasing;\r
476 \r
477         /* The interrupt event mutex should already be held by this thread as it was\r
478         obtained on entry to the critical section. */\r
479 \r
480         lMutexNeedsReleasing = pdTRUE;\r
481 \r
482         if( ulCriticalNesting > portNO_CRITICAL_NESTING )\r
483         {\r
484                 if( ulCriticalNesting == ( portNO_CRITICAL_NESTING + 1 ) )\r
485                 {\r
486                         ulCriticalNesting--;\r
487 \r
488                         /* Were any interrupts set to pending while interrupts were \r
489                         (simulated) disabled? */\r
490                         if( ulPendingInterrupts != 0UL )\r
491                         {\r
492                                 SetEvent( pvInterruptEvent );\r
493 \r
494                                 /* The event handler needs to know to signal the interrupt \r
495                                 acknowledge event the next time this task runs. */\r
496                                 pxThreadState = ( xThreadState * ) *( ( unsigned long * ) pxCurrentTCB );\r
497 \r
498                                 /* Mutex will be released now, so does not require releasing\r
499                                 on function exit. */\r
500                                 lMutexNeedsReleasing = pdFALSE;\r
501                                 ReleaseMutex( pvInterruptEventMutex );\r
502                         }\r
503                 }\r
504                 else\r
505                 {\r
506                         /* Tick interrupts will still not be processed as the critical\r
507                         nesting depth will not be zero. */\r
508                         ulCriticalNesting--;\r
509                 }\r
510         }\r
511 \r
512         if( lMutexNeedsReleasing == pdTRUE )\r
513         {\r
514                 ReleaseMutex( pvInterruptEventMutex );\r
515         }\r
516 }\r
517 /*-----------------------------------------------------------*/\r
518 \r