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