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