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