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