FreeRTOS Melot
FreeRTOS Melot
FreeRTOS Melot
NicolasMelot
Operatingsystemsforembeddeddevices
Sommaire
Introduction........................................................................................................................................................................4
1Tasks.................................................................................................................................................................................5
1.1AtaskinFreeRTOS..................................................................................................................................................5
1.1.1Lifecycleofatask............................................................................................................................................5
1.2Creatinganddeletingatask......................................................................................................................................6
2Scheduling........................................................................................................................................................................8
2.1Priorities....................................................................................................................................................................8
2.2Priorityequallytasks................................................................................................................................................9
2.3Starvation..................................................................................................................................................................9
3Queuemanagement.........................................................................................................................................................9
3.1Readinginaqueue..................................................................................................................................................10
3.2Writingtoaqueue...................................................................................................................................................10
3.3Creatingaqueue......................................................................................................................................................11
4Resourcesmanagement.................................................................................................................................................12
4.1Binarysemaphores..................................................................................................................................................12
4.1.1Handlebinarysemaphores..............................................................................................................................13
4.1.1.1Creationofasemaphore.........................................................................................................................13
4.1.1.2Takingasemaphore................................................................................................................................13
4.1.1.3Givingasemaphore................................................................................................................................13
4.2Mutexes...................................................................................................................................................................15
4.2.1Priorityinheritance.........................................................................................................................................15
4.3Countingsemaphores..............................................................................................................................................15
4.3.1Countingsemaphoreroutines.........................................................................................................................15
4.3.1.1Creation..................................................................................................................................................15
4.3.1.2Take&giveoperations...........................................................................................................................16
5Handlinginterrupts.......................................................................................................................................................16
5.1Manageinterruptsusingabinarysemaphore..........................................................................................................17
5.2Criticalsections.......................................................................................................................................................18
5.2.1Suspendinterrupts..........................................................................................................................................18
5.2.2Stopthescheduler...........................................................................................................................................19
6Memorymanagement....................................................................................................................................................19
6.1Prototypes................................................................................................................................................................19
6.2Memoryallocatedonceforall................................................................................................................................20
6.3Constantsizedandnumberedmemory...................................................................................................................20
6.4Freememoryallocationanddeallocation...............................................................................................................21
Conclusion........................................................................................................................................................................23
References.........................................................................................................................................................................24
7Illustrations....................................................................................................................................................................25
8Appendix.........................................................................................................................................................................26
8.1AnexampleofFreeRTOSConfig.h.........................................................................................................................27
8.2heap_1.c..................................................................................................................................................................29
8.3heap_2.c...................................................................................................................................................................31
8.4heap_3.c..................................................................................................................................................................37
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Introduction
FreeRTOSisanfreeandopensourceRealTimeOperatingsystemdevelopedbyRealTimeEngineersLtd.Its
design has been developed tofit on very small embedded systems and implements onlya very minimalist set of
functions:verybasichandleoftasksandmemorymanagement,justsufficientAPIconcerningsynchronization,and
absolutelynothingisprovidedfornetworkcommunication,driversforexternalhardware,oraccesstoafilesystem.
However, among its features are the following characteristics: preemptive tasks, a support for 23 microcontroller
architectures1 by its developers, a small footprint2 (4.3Kbytes on an ARM7 after compilation 3), written in C and
compiledwithvariousCcompiler(someportsarecompiledwithgcc,otherswithopenwatcomorborlandc++).Italso
allowsanunlimitednumberoftaskstorunatthesametimeandnolimitationabouttheirprioritiesaslongasused
hardwarecanaffordit.Finally,itimplementsqueues,binaryandcountingsemaphoresandmutexes.
1 http://www.freertos.org/a00090.html
2 http://www.freertos.org/FAQMem.html#QSize
3 http://www.freertos.org/FreeRTOS_Features.html
4
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Tasks
1 Tasks
1.1 AtaskinFreeRTOS
FreeRTOSallowsanunlimitednumberoftaskstoberunaslongashardwareandmemorycanhandleit.Asa
realtimeoperatingsystem,FreeRTOSisabletohandlebothcyclicandacyclictasks.InRTOS,ataskisdefinedbya
simpleCfunction,takingavoid*parameterandreturningnothing(void).
Several functions are available to manage tasks: task creation (vTaskCreate()), destruction (vTaskDelete()),
priority management (uxTaskPriorityGet(), vTaskPrioritySet()) or delay/resume ((vTaskDelay(), vTaskDelayUntil(),
vTaskSuspend(),vTaskResume(),vTaskResumeFromISR()).Moreoptionsareavailabletouser,forinstancetocreatea
criticalsequenceormonitorthetaskfordebuggingpurpose.
1.1.1 Lifecycleofatask
Thissectionwilldescribemorepreciselyhowcanataskevolvefromthemomentitiscreatedtowhenitis
destroyed.Inthiscontext,wewillconsidertobeavailableonlyonemicrocontrollercore,whichmeansonlyone
calculation,oronlyonetask,canberunatagiventime.Anygiventaskcanbeinoneoftwosimplestates:running
ornotrunning.Aswesupposethereisonlyonecore,onlyonetaskcanberunningatagiventime;allothertasksare
inthenotrunningtask.Figure1givesasimplifiedrepresentationofthislifecycle.Whenataskchangesitsstatefrom
Notrunningtorunning,itissaidswappedinorswitchedinwhereasitiscalledswappedoutorswitchedout
whenchangingtoNotrunningstate.
Not running
Not running
Not running
Running
Figure1:Simplifiedlifecycleofa
task:Onlyonetaskcanbe
"running"atagiventime,
whereasthenotrunningstate
canbeexpanded.
Asthereareseveralreasonsforatasknottoberunning,theNotrunningstatecanbeexpandedasshows
Figure2.Ataskcanbepreemptedbecauseofamoreprioritytask(schedulingisdescribedinsection2),becauseithas
beendelayedorbecauseitwaitsforaevent.Whenataskcanrunsbutiswaitingfortheprocessortobeavailable,its
stateissaid Ready.Thiscanhappenwhenataskhasitneedseverythingtorunbutthereisamoreprioritytask
runningatthistime.Whenataskisdelayedoriswaitingforanothertask(synchronisationthroughsemaphoresor
mutextes) a task is said to be Blocked. Finally, a call to vTaskSuspend() and vTaskResume() or
xTaskResumeFromISR()makesthetaskgoinginandoutthestateSuspend.
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Tasks
ItisimportanttounderlinethataifataskcanleavebyitselftheRunningstate(delay,suspendorwaitforan
event),onlytheschedulercanswitchinagainthistask.Whenataskwantstorunagain,itsstateturnstoReadyan
onlytheschedulercanchoosewhichReadytaskisrunatagiventime.
Not running
Suspended
VtaskSuspend()
called
VtaskSuspend()
called
VtaskResume()
called
Ready
VtaskSuspend()
called
Event
Scheduler
activity
Running
Blocking API
function called
Blocked
Figure2:Lifecycleofatask
1.2 Creatinganddeletingatask
AtaskdefinedbyasimpleCfunction,takingonevoid*argumentandreturningnothing(seeText1)
voidATaskFunction(void*pvParameters);
Text1:Atypicaltasksignature
Anycreatedtaskshouldneverendbeforeitisdestroyed.Itiscommonfortask'scodetobewrappedinaninfinite
loop,ortoinvokevTaskDestroy(NULL)beforeitreachesitsfinalbrace.Asanycodeininfiniteloopcanfailandexit
thisloop,itissaferevenforarepetitivetask,toinvokevTaskDelete()beforeitsfinalbrace.Anexampleofatypicaltask
implementationisavailableonText3.
AtaskcanbecreatedusingvTaskCreate()(Text2).Thisfunctiontakesasargumentthefollowinglist:
pvTaskCode:apointertothefunctionwherethetaskisimplemented.
pcName:givennametothetask.ThisisuselesstoFreeRTOSbutisintentedtodebuggingpurposeonly.
usStackDepth:lengthofthestackforthistaskin words.Theactualsizeofthestackdependsonthe
microcontroller.Ifstackwithis32bits(4bytes)andusStackDepthis100,then400bytes(4times100)willbe
allocatedforthetask.
pvParameters:apointertoargumentsgiventothetask.Agoodpracticeconsistsincreatingadedicated
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Tasks
structure,instantiateandfillitthengiveitspointertothetask.
uxPriority: priority given to the task, a number between 0 and MAX_PRIORITIES 1. This is
discussedinsection2.
pxCreatedTask:apointertoanidentifierthatallowstohandlethetask.Ifthetaskdoesnothavetobe
handledinthefuture,thiscanbeleavedNULL.
portBASE_TYPExTaskCreate(pdTASK_CODEpvTaskCode,
constsignedportCHAR*constpcName,
unsignedportSHORTusStackDepth,
void*pvParameters,
unsignedportBASE_TYPEuxPriority,
xTaskHandle*pxCreatedTask
);
Text2:Taskcreationroutine
voidATaskFunction(void*pvParameters)
{
/*Variablescanbedeclaredjustasperanormalfunction.Eachinstance
ofataskcreatedusingthisfunctionwillhaveitsowncopyofthe
iVariableExamplevariable.Thiswouldnotbetrueifthevariablewas
declaredstaticinwhichcaseonlyonecopyofthevariablewouldexist
andthiscopywouldbesharedbyeachcreatedinstanceofthetask.*/
intiVariableExample=0;
/*Ataskwillnormallybeimplementedasininfiniteloop.*/
for(;;)
{
/*Thecodetoimplementthetaskfunctionalitywillgohere.*/
}
/*Shouldthetaskimplementationeverbreakoutoftheaboveloop
thenthetaskmustbedeletedbeforereachingtheendofthisfunction.
TheNULLparameterpassedtothevTaskDelete()functionindicatesthat
thetasktobedeletedisthecalling(this)task.*/
vTaskDelete(NULL);
}
Text3:Atypicaltask(fromUsingtheFreeRTOSRealTimeKernel).
AtaskisdestroyedusingxTaskDestroy()routine.IttakesasargumentpxCreatedTaskwhichisgivenwhenthe
taskwascreated.SignatureofthisroutineisgiveninText4andanexamplecanbefoundinText3.
voidvTaskDelete(xTaskHandlepxTask);
Text4:Deletingatask
Whenataskisdeleted,itisresponsibilityofidletasktofreeallallocatedmemorytothistaskbykernel.Notice
thatallmemorydynamicallyallocatedmustbemanuallyfreed.
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Scheduling
2 Scheduling
TaskschedulingaimstodecidewhichtaskinReadystatehastoberunatagiventime.FreeRTOSachieves
thispurposewithprioritiesgiventotaskswhiletheyarecreated(see 1.2).Priorityofataskistheonlyelementthe
schedulertakesintoaccounttodecidewhichtaskhastobeswitchedin.
Everyclocktickmakestheschedulertodecidewhichtaskhastobewakenup,asshowninFigure3.
Kernel decides which
task to run
Kernel decides which
task to run
Tick interrupt
Kernel
Task 1
Task 2
t1
Time
t3
Figure3:Everyclocktickmakesthe
schedulertoruna"Ready"statetask
andtoswitchouttherunningtask.
2.1 Priorities
FreeRTOSimplementstasksprioritiestohandlemultitasksscheduling.Apriorityisanumbergiventoatask
whileitiscreatedorchangedmanuallyusingvTaskPriorityGet()andvTaskPrioritySet()(SeeFreeRTOSmanual).There
isnoautomaticmanagementofprioritieswhichmeanataskalwayskeepsthesamepriorityunlesstheprogrammer
changeitexplicitly.Alowvaluemeansalowpriority:Apriorityof0istheminimalpriorityataskcouldhaveandthis
levelshouldbestrictlyreservedfortheidletask.Thelastavailablepriorityintheapplication(thehighervalue)isthe
highest priority available for task. FreeRTOS has no limitation concerning the number of priorities it handles.
MaximumnumberofprioritiesisdefinedinMAX_PRIORITIESconstantinFreeRTOSConfig.h(seesection8.1),and
hardwarelimitation(widthoftheMAX_PRIORITIEStype).Ifanhighervalueisgiventoatask,thenFreeRTOScutsit
toMAX_PRIORITIES1.Figure4givesanexampleofaapplicationruninFreeRTOS.Task1andtask3areevent
basedtasks(theystartwhenaeventoccurs,runthenwaitfortheeventtooccuragain),Task2isperiodicandidletask
makessurethereisalwaysataskrunning.
This taskmanagement allows animplementation ofRateMonotonic for taskscheduling: tasks withhigher
frequenciesaregivenanhigherprioritywhereaslowfrequenciestasksdeservealowpriority.Eventbasedorcontinuous
tasksarepreemptedbyperiodictasks.
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Task 2 preempts task 3
Scheduling
t1 t2
Time
t5 t6 t7 t8
t3 t4
Figure4:AnhypotheticFreeRTOSapplicationschedule
2.2 Priorityequallytasks
Taskscreatedwithanequalpriorityaretreatedequallybythescheduler:Iftwoofthemarereadytorun,the
schedulersharesrunningtimeamongallofthem:ateachclocktick,theschedulerchoosesadifferenttaskamongthe
readytaskswithhighestpriority.ThisimplementsaRoundRobinimplementationwherequantumisthetimebetween
eachclocktick.ThisvalueisavailableinTICK_RATE_HZconstant,inFreeRTOSConfig.h(section8.1).
Time t1: Task 1 enters
running state and runs
until scheduler
preempt it for task 2
Task 1
Task 2
t1
t2
Time
t3
t4
t5
Figure5:Twotaskswithaequivalentpriorityare
runaftereachotherinturn.
2.3 Starvation
ThereisnomechanismimplementedinFreeRTOSthatpreventstaskstarvation:theprogrammerhastomake
surethereisnohigherprioritytasktakingallrunningtimeforitself.Itisalsoagoodideatolettheidletasktorun,
sinceitcanhandlesomeimportantworksuchasfreememoryfromdeletedtasks,orswitchingthedeviceintoa
sleepingmode.
3 Queuemanagement
Queues are an underlying mechanism beyond all tasks communication or synchronization in a FreeRTOS
environment.Theyareanimportantsubjecttounderstandasitisunavoidabletobeabletobuildacomplexapplication
withtaskscooperatingwitheachother.Theyareameantostoreaandfinitenumber(namedlength)offixedsize
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Queuemanagement
data.Theyareabletobereadandwrittenbyseveraldifferenttasks,anddon'tbelongtoanytaskinparticular.Aqueue
isnormallyaFIFOwhichmeanselementsarereadintheordertheyhavebeenwritten.Thisbehaviordependsonthe
writingmethod:twowritingfunctionscanbeusedtowriteeitheratthebeginningorattheendofthisqueue.
3.1 Readinginaqueue
Whenasingletaskreadsinaqueue,itismovedtoBlockedstateandmovedbacktoReadyassoonasdata
hasbeenwritteninthequeuebyanothertaskoraninterrupt.Ifseveraltasksaretryingtoreadaqueue,thehighest
prioritytaskreadsitfirst.Finally,ifseveraltaskswiththesamepriorityaretryingtoread,thefirsttaskwhoaskedfora
readoperationischosen.Ataskcanalsospecifyamaximumwaitingtimeforthequeuetoallowittoberead.Afterthis
time,thetaskswitchesbackautomaticallytoReadystate.
portBASE_TYPExQueueReceive(
xQueueHandlexQueue,
constvoid*pvBuffer,
portTickTypexTicksToWait
);
Text5:normalmethodtoreadinaqueue:itreadsanelementthenremovesit.
xqueueistheidentifierofthequeuetoberead
pvBufferisapointertothebufferwherethereadvaluewillbecopiedto.Thismemorymustbeallocatedand
mustbelargeenoughtohandletheelementreadfromthequeue.
xTicksToWait defines the maximum time to wait. 0 prevents the task from waiting even if a value is not
available, whereas if INCLUDE_vTaskSuspend is set and xTicksToWait equals MAX_DELAY, the task waits
indefinitely.
pdPASSisreturnedifavaluewassucessfullyreadbeforexTicksToWaitisreached.Ifnot,errQUEUE_EMPTY
isreturnedfromxQueueReceive().
Afterreadinganelementinaqueue,thiselementisnormallyremovedfromit;however,anotherreadfunction
giveninallowstoreadanelementwithouthavingittobedeletedfromthequeue.
portBASE_TYPExQueuePeek(
xQueueHandlexQueue,
constvoid*pvBuffer,
portTickTypexTicksToWait
);
Text6:Italsopossibletoreadinaqueuewithoutwithoutremovingtheelementfromit.
3.2 Writingtoaqueue
Writingonaqueueobeystothesamerulesasreadingit.Whenatasktriestowriteonaqueue,ithastowaitfor
ittohavesomefreespace:thetaskisblockeduntilanothertaskreadsthequeueandfreesomespace.Ifseveraltasks
10
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Queuemanagement
attempttowriteonthesamequeue,thehigherprioritytaskischosenfirst.Ifseveraltaskswiththesamepriorityare
tryingtowriteonaqueue,thenthefirstonetowaitischosen.Figure6givesagoodillustrationonhowqueueswork.
A prototype is available on Text 7. It describes the normal method towrite on a queue. Text 8 gives the
underlyingfunctionbehindxQueueSendandthefunctiontobeusediftheuserwantsthelastwrittenelementtoberead
first(LastIn,FirstOutorLIFO).
portBASE_TYPExQueueSend(xQueueHandlexQueue,
constvoid*pvItemToQueue,
portTickTypexTicksToWait
);
Text7:functiontowriteonaqueueinFIFOmode
xQueueisthequeuetowriteon.Thisvalueisreturnedbythequeuecreationmethod.
pvItemToQueueisapointertoanelementwhichiswantedtobecopied(byvalue)tothequeue.
xticksToWaitisthenumberoftickstowaitbeforethetaskgivesuptowriteonthisqueue.IfxTicksToWaitis0,
thetaskwon'twaitatallifthequeueisfull.IfINCLUDE_vTaskSuspendifdefinedto1infFreeRTOSConfig.h(section
8.1)andxTicksToWaitequalsMAX_DELAY,thenthetaskhasnotimelimittowait.
XqueueSendreturnspdPASSiftheelementwassuccessfullywrittentothequeuebeforethemaximumwaiting
timewasreached,orerrQUEUE_FULLifthemaximumtimewaselapsedbeforethetaskcouldwriteonthequeue.
portBASE_TYPExQueueSendToBack(xQueueHandlexQueue,
constvoid*pvItemToQueue,
portTickTypexTicksToWait
);
portBASE_TYPExQueueSendToFront(xQueueHandlexQueue,
constvoid*pvItemToQueue,
portTickTypexTicksToWait
);
Text8:xQueueSendToBack:asynonymforxQueSend;xQueueSendToFrontwriteonaqueuein
LIFOmode.
3.3 Creatingaqueue
Lengthofaqueueanditswidth(thesizeofitselements)aregivenwhenthequeueiscreated.Text9givesthe
functionsignatureavailabletocreateaqueue.
xQueueHandlexQueueCreate(unsignedportBASE_TYPEuxQueueLength,
unsignedportBASE_TYPEuxItemSize
);
Text9:Queuecreationfunction
uxQueueLenghtgivesthenumberofelementsthisqueuewillbeabletohandleatanygiventime.uxItemSizeis
thesizeinbyteofanyelementstoredinthequeue.xQueueCreatereturnsNULLifthequeuewasnotcreatedduetolack
11
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Queuemanagement
ofmemoryavailable;ifnot,thereturnedvalueshouldbekepttohandlethenewlycreatedqueue.
A queue is created to allow task 1 and task B to communicate. The queue can hold a maximum
of 5 values. When a queue is created, it doesn't contain any value so it's empty
Task 1
Task 2
Task 1 writes a value on the queue; the value is sent to the back. Since the queue was
previously empty, the value is now both the first and the last value in the queue.
Task 1
10
Task 2
Task 1 sends again an other value. The queue contains now the previously written value and
this newly added value. The previous value remains at the front of the queue while the new one
is now at its back. Three spaces are still available.
20
Task 1
10
Task 2
Task 2 reads a value in the queue. It will receive the value in the front of the queue, which is the
first task one inserted.
Task 1
20
10
Task 2
Task 2 has removed an item. The second item is moved to be the one in the front of the queue.
This is the value task 2 will read next time it tries to read a value. 4 spaces are now available.
Task 1
20
Task 2
Figure6:Possiblescenariowithaqueueandtwotasks
4 Resourcesmanagement
4.1 Binarysemaphores
Binarysemaphoresarethesimplesteffectivewaytosynchronizetasks,anotherevenmoresimple,butnotas
effective,consistsinpollinganinputoraresource.Abinarysemaphorecanbeseenasaqueuewhichcontainsonlyone
element.Figure7givesanideaonitsmechanism.
12
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Resourcesmanagement
4.1.1 Handlebinarysemaphores
4.1.1.1 Creationofasemaphore
voidvSemaphoreCreateBinary(xSemaphoreHandlexSemaphore);
Text10:creatingasemaphore
xSemaphore:semaphoretobecreated.
4.1.1.2 Takingasemaphore
ThisoperationisequivalenttoaP()operation,orifcomparedtoqueues,toaReceive()operation.Atasktaking
thesemaphoremustwaitittobeavailableandisblockeduntilitisoruntiladelayiselapsed(ifapplicable).
portBASE_TYPExSemaphoreTake(xSemaphoreHandlexSemaphore,portTickType
xTicksToWait);
Text11:takingasemaphore
xSsemaphoreisthesemaphoretotake.
xTicksToWaitisthetime,inclockticks,forthetasktowaitbeforeitgivesupwithtakingthesemaphore.If
xTicksToWaitequalsMAX_DELAYandINCLUDE_vTaskSuspendis1,thenthetaskwon'tstopwaiting.
Ifthetakeoperationsucceedintime,thefunctionreturnspdPASS.Ifnot,pdFALSEisreturned.
4.1.1.3 Givingasemaphore
GivingasemaphorecanbecomparedtoaV()operationortowritingonaqueue.
portBASE_TYPExSemaphoreGive(xSemaphoreHandlexSemaphore);
Text12:givingasemaphore
xSemaphoreisthesemaphoretobegiven.
ThefunctionreturnspdPASSifthegiveoperationwassuccessful,orpdFAILifthesemaphorewasalready
available,orifthetaskdidnotholdit.
13
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
The semaphore is not available, so the task is blocked, wating for the semaphore.
xSemaphoreTake()
xGiveSemaphoreFromISR()
xSemaphoreTake()
xGiveSemaphoreFromISR()
xSemaphoreTake()
xSemaphoreTake()
Another interrupt occurs and gives another semaphore. In the meanwhile, the task is processing
the first interrupt.
xGiveSemaphoreFromISR()
xSemaphoreTake()
When the task has finished to preccess its first work, it waits for another semaphore and gets it
directly, since an interrupt occurred. The task is now able to process the second interrupt.
xSemaphoreTake()
Figure7:Abinarysemaphoreisequivalenttoaqueuewhich
cancontainoneelement
14
Resourcesmanagement
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Resourcesmanagement
4.2 Mutexes
Mutexes are designed to prevent mutual exclusion or deadlocking. A mutex is used similarly to a binary
semaphore,exceptthetaskwhichtakethesemaphoremustgiveitback.Thiscanbethoughwithatokenassociatedwith
theresourcetoaccessto.Ataskholdsthetoken,workswiththeresourcethengivesbackthetoken;inthemeanwhile,
noothertokencanbegiventothemutex.AgoodillustrationisshowninFigure8.
Two tasks want to access a resource. But only a task which holds the mutext is allowed to work
with it.
Task 2 is blocked until Task 1 has finished to work with the resource, and has given back the
mutex.
Task 1
Mutext
Task 1
Ressource to
protect
Mutext
Task 2
Task 1 tries to take the mutex. Since it is available, it gets it and is allowed to work with the
resource.
Task 1
Ressource to
protect
Mutext
Task 2
Task 2 tries to take the same mutex, but task 1 stil has it.Task 2 is not permitted to access the
resource.
Ressource to
protect
Task 2
Task 2 gives back the mutex. It is now available to whichever task that need to work with the
associated resource.
Task 1
Mutext
Task 2
Task 1 has given back the mutex and task 2 can take it and is allowed to work with the resource.
Task 1
Mutext
Ressource to
protect
Task 1
Ressource to
protect
Mutext
Task 2
Ressource to
protect
Task 2
Figure8:Usualusecaseofamutex
4.2.1 Priorityinheritance
Priorityinheritanceisactuallytheonlydifferencebetweenabinarysemaphoreandamutex.Whenseveraltasks
asksforamutex,themutexholder'spriorityissettothehighestwaitingtaskpriority.Thismechanismhelpsagainst
priorityinversionphenomenonalthoughitdoesn'tabsolutelypreventitfromhappening.Theuseofamutexraisesthe
applicationglobalcomplexityandthereforeshouldbeavoidedwheneveritispossible.
4.3 Countingsemaphores
A counting semaphore is a semaphore that can be taken several (but limited) times before is becomes
unavailable.Itmaintainsavaluewhichisincreasedasthesemaphoreisgiven,anddecreasedwhenisistaken.Isis
comparabletoaqueuewithacertainamountofelements.Whencreated,acountingsemaphorecanbeinitializedtobe
availableanarbitrarynumberoftimes.
4.3.1 Countingsemaphoreroutines
4.3.1.1 Creation
As describedabove,acounting semaphorecanbe takena limitedmaximum times andis initializedtobe
availableforanarbitrarynumberoftakeoperations.Thesecharacteristicsaregivenwhenthesemaphoreiscreated.
15
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Resourcesmanagement
xSemaphoreHandlexSemaphoreCreateCounting(unsignedportBASE_TYPEuxMaxCount,
unsignedportBASE_TYPE
uxInitialCount);
Text13:Creationofacountingsemaphore.
uxMaxCountisthecapacityofthecountingsemaphore,itsmaximumabilitytobetaken.
uxInitialCountisthenewsemaphore'savailabilityafteritiscreated.
ReturnedvalueisNULLifthesemaphorewasnotcreated,becauseofalackofmemory,orapointertothenew
semaphoreandcanbeusedtohandleit.
4.3.1.2 Take&giveoperations
P()andV()operationtocountingsemaphoresarerealizedusingthesamefunctionastheonedescribedin
sections4.1.1.2and4.1.1.3.
5 Handlinginterrupts
An interrupt is a mechanism fully implemented and handled by hardware. Software and more particularly
FreeRTOStasksorkernelcanonlygivemethodstohandleagiveninterrupt,oritcanraisesomebycallinganhardware
instruction.Wewillsupposeweareusingamicrocontrollerthathandles7differentlevelsofinterrupts.Themorean
interruptnumberisimportant,themoreitwillbepriorityoverotherinterrupts.Dependingonhardware,thisisnot
alwaysthecase.interruptsprioritiesarenot,inanycase,relatedtotaskspriorities,andwillalwayspreemptthem.
AfunctiondefinedasaninterrupthandlercannotusefreelyFreeRTOSAPI:accesstoqueuesorsemaphoresis
forbidden through the normal functions described in previous section, but FreeRTOS provides some specialized
functionstobeusedinthatcontext:forinstance,inaninterrupthandler,aV()operationtoasemaphoremustbe
realized using xSemaphoreGiveFromISR() instead of xSemaphoreGive(). The prototypes for these method can be
different as they can involve some particular problems (this is the case of xSemaphoreGiveFromISR() which
implementsamechanismtomaketheusertobeawarethatthisgiveoperationmakestheinterrupttobepreemptedbya
higherpriorityinterruptunlockedbythisgiveoperation).
InterruptmanagementcanbeconfiguredinFreeRTOSusingconstantsavailableinFreeRTOSConfig.h.
configKERNEL_INTERRUPT_PRIORITYsetstheinterruptprioritylevelforthetickinterrupt.
interruptsthatuseinterruptsafeFreeRTOSAPIfunctions.Ifthisconstantisnotdefined,thenanyinterrupt
handler function that makes a use of FreeRTOS API must execute at
configKERNEL_INTERRUPT_PRIORITY.
Any interrupt whose priority level is greater than configMAX_SYSCALL_INTERRUPT_PRIORITY or
configKERNEL_INTERRUPT_PRIORITYifconfigMAX_SYSCALL_INTERRUPT_PRIORITYisnotdefined,will
16
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Handlinginterrupts
neverbepreemptedbythekernel,butareforbiddentouseFreeRTOSAPIfunctions.
Micro-controller provides 7 levels of interrupt
configMAX_SYSTEM_INTERRUPT_PRIORITY = 3
configKERNEL_INTERRUPT_PRIORITY = 1
Priority 7
Interrupts using
this level will never
be preemted by the
kernel
Priority 6
Priority 5
Can be used by all
interrupts that don't
use any FreeRTOS
API function
Priority 4
Priority 3
Interrupts using
these priorities can
use API functions
Priority 2
Priority 1
Figure9:InterruptorganizationinFreeRTOS
5.1 Manageinterruptsusingabinarysemaphore
InterrupthandlersarepiecesofcoderunbythemicrocontrollerandthereforearenothandledbyFreeRTOS.
This can potentiallycreate problems withmemory access since the operating system cannot handle these context
changes.Thisisareasonwhyseveralfunctionsexistsintwoversions:oneforregulartasksandanotherisintendedto
interrupts handler. This is the case of queue management functions like xQueueReceive() and
wQueueReceiveFromISR().Forthisreason,itisnecessarytomakeinterruptshandlers'executionasshortaspossible.
Onwaytoachievethisgoalconsistsinthecreationoftaskswaitingforaninterrupttooccurwithasemaphore,andlet
thissaferportionofcodeactuallyhandletheinterrupt.
Figure10proposesasolutiontoreducesignificantlythetimeanISRcanrun.AnISRgivesasemaphoreand
unblocka'HandlertaskthatisabletohandlertheISR,makingtheISRexecutionmuchshorter.
The ISR executes and
use a semaphore to
unblock the 'handle'
task
ISR
When handler task has
finished its job, it waits
again the semaphore the
next ISR will provide, and
allow the lower priority
task to run again
'Handler' task
Task 1
t1
t2 t3
Time
t4
Figure10:Deferredinterruptprocessing:aregulartasks
waitsforaninterrupttooccurwithasemaphore,and
handleit.
17
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Handlinginterrupts
5.2 Criticalsections
Sometimesaportionofcodeneedstobeprotectedfromanycontextchangesoastopreventacalculationfrom
beingcorruptedoranI/Ooperationbeingcutormixedwithanother.FreeRTOSprovidestwomechanismstoprotect
someassmallportionsaspossible;someprotectsfromanycontextchange,eitherfromascheduleroperation,oran
interruptevent,othersonlypreventsschedulerfrompreemptingthetask.
Handlingthiscanbeveryimportantasmanyinstructions,affectationsforinstance,maylookatomicbutrequire
severalhardwareinstructions(loadvariableaddresstoaregistry,loadavaluetoanotherregistryandmovethevalueto
thematchingmemoryaddressusingthetworegistries).
5.2.1 Suspendinterrupts
Thisformorcriticalsectionisveryefficientbutmustbekeptasshortaspossiblesinceitmakesthewhole
systeminsuchastatethatanyotherportionofcodecannotbeexecuted.Thiscanbeaproblemforatasktomeetits
timeconstraint,oranexternaleventtobetreatedbyaninterruption.
/*EnsureaccesstothePORTAregistercannotbeinterruptedby
placingitwithinacriticalsection.Enterthecriticalsection.*/
taskENTER_CRITICAL();
/*Aswitchtoanothertaskcannotoccurbetweenthecallto
taskENTER_CRITICAL()andthecalltotaskEXIT_CRITICAL().Interrupts
maystillexecuteonFreeRTOSportsthatallowinterruptnesting,but
onlyinterruptswhosepriorityisabovethevalueassignedtothe
configMAX_SYSCALL_INTERRUPT_PRIORITYconstantandthoseinterruptsare
notpermittedtocallFreeRTOSAPIfunctions.*/
PORTA|=0x01;
/*WehavefinishedaccessingPORTAsocansafelyleavethecritical
section.*/
taskEXIT_CRITICAL();
Text14:Acriticalsectionprotectedagainstbothschedulerswitchoutoperations,and
hardwareinterrupts.
AtaskcanstartacriticalsectionwithtaskENTER_CRITICAL()andstopitusingtaskEXIT_CRITICAL().The
systemallowacriticalsectiontobestartedwhileanotheroneisalreadyopened:thismakesmucheasiertocallexternal
functionsthatcanneedsuchasectionwhereasthecallingfunctionalsoneedit.However,itisimportanttonoticethatin
ordertoendacriticalsection,taskEXIT_CRITICAL()mustbecalledexactlyasmuchastaskSTART_CRITICALwas.
Generalyspeaking,thesetwofunctionsmustbecalledascloseaspossibleinthecodetomakethissectionveryshort.
Such a critical section is not protected from interrupts which priority is greater than
configMAX_SYSCALL_INTERRUPT_PRIORITY(ifdefinedinFreeRTOSConfig.h;ifnot, prefertoconsiderthe
valueconfigKERNEL_INTERRUPT_PRIORITYinstead)tocreateacontextchange.
18
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Handlinginterrupts
5.2.2 Stopthescheduler
Alessdrasticmethodtocreateacriticalsectionconsistsinpreventinganytaskfrompreemptingit,butlet
interruptstodotheirjob.ThisgoalcanbeachievebypreventinganytasktoleavetheReadystatetoRunning,itcan
beunderstoodasstoppingthescheduler,orstoppingallthetasks.
NoticeitisimportantthatFreeRTOSAPIfunctionsmustnotbecalledwhentheschedulerisstopped.
/*Writethestringtostdout,suspendingtheschedulerasamethod
ofmutualexclusion.*/
vTaskSuspendAll();
{
printf("%s",pcString);
fflush(stdout);
}
xTaskResumeAll();
Text15:Creationofacountingsemaphore.
When Calling xTaskResumeAll() is called, it returns pdTRUE if no task requested a context change while
schedulerwassuspendedandreturnspdFALSEiftherewas.
6 Memorymanagement
Inasmallembeddedsystem,usingmalloc()andfree()toallocatememoryfortasks,queuesorsemaphorescan
cause various problems: preemption while allocating some memory, memory allocation and free can be an
nondeterministicoperations,oncecompiled,theyconsumealotofspaceorsufferfrommemoryfragmentation.
Instead,FreeRTOSprovidesthreedifferentwaystoallocatememory,eachadaptedtoadifferentsituationbutall
trytoprovideasolutionadaptedtosmallembeddedsystems.Oncethepropersituationidentified,theprogrammercan
choosetherightmemorymanagementmethodonceforall,forkernelactivityincluded.Itispossibletoimplementits
ownmethod,oruseoneofthethreeFreeRTOSproposesandwhichcanbefoundinheap_1.c,heap_2.corheap_3.c(or
respecctivelyinsections8.2,8.3and8.4).
6.1 Prototypes
Allimplementationsrespectthesameallocation/freememoryfunctionprototypes.Theseprototypesstandsin
twofunctions.
void*pvPortMalloc(size_txWantedSize);
voidpvPortFree(void*pv);
Text16:Prototypesformemoryallocation/deallocation
xWantedsizeisthesize,inbyte,tobeallocated,pvisapointertothememorytobefreed.pvPortMallocreturns
apointertothememoryallocated.
19
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Memorymanagement
6.2 Memoryallocatedonceforall
Itispossibleinsmallembeddedsystems,toallocatealltasks,queuesandsemaphores,thenstartthescheduler
andruntheentireapplication,whichwillneverhavetoreallocatefreeanyofstructuresalreadyallocated,orallocate
somenew.Thisextremelysimplifiedcasemakesuselesstheuseofafunctiontofreememory:onlypvPortMallocis
implemented.ThisimplementationcanbefoundinSource/portable/MemMang/heap_1.corappendix8.2
Sincetheuseofthisschemesupposeallmemoryisallocatedbeforetheapplicationactuallystarts,andtherewill
havenoneedtoreallocateorfreememory,FreeRTOSsimplyaddsataskTCB(TaskControlBlock,thestructure
FreeRTOSusestohandletasks)thenallmemoryitneeds,andrepeatthisjobforallimplementedtasks.Figure11gives
aillustrationabouthowthememoryismanaged.
This memory management allocates a simple array sized after the constant configTOTAL_HEAP_SIZE in
FreeRTOSConfig.h,anddividesitinsmallerpartswhichareallocatedformemoryalltasksrequire.Thismakesthe
applicationtoappeartoconsumealotofmemory,evenbeforeanymemoryallocation.
Free space
ConfigTOTAL_HEAP_SIZE
Stack
TCB
Stack
TCB
Stack
Stack
TCB
TCB
Figure11:InA:nomemoryisallocatedyet;inB,memoryhas
beenallocatedforbluetask;inC,allrequiredmemoryis
allocated
6.3 Constantsizedandnumberedmemory
Anapplicationcanrequiretoallocateanddeallocationdynamicallymemory.Ifineverytasks'lifecycle,number
ofvariablesandit'ssizeremainsconstant,thenthissecondmechanismcanbesetup.Itsimplementationcanbefound
inSource/portable/MemMang/heap_2.corappendix8.3.
Asthepreviousstrategy,FreeRTOSusesalargeinitialarray,whichsizedependsonconfigTOTAL_HEAP_SIZE
andmakestheapplicationtoappearstoconsumehugeRAM.Adifferencewiththeprevioussolutionconsistsinan
implementationofvPortFree().Asmemorycanbefreed,thememoryallocationisalsoadapted.Let'sconsiderthebig
initialarraytobeallocatedandfreedinsuchawaythattherearethreeconsecutivefreespacesavailable.Firstis5bytes,
secondis25andthelastoneis100byteslarge.AcalltopvPortMalloc(20)requires20bytestobefreesohastoreserve
20
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Memorymanagement
itandreturnbackitsreference.Thisalgorithmwillreturnthesecondfreespace,25byteslargeandwillkeepthe
remaining5bytesforalatercalltopvPortMalloc().Itwillalwayschoosethesmallestfreespacewherecanfitthe
Stack
Stack
Stack
TCB
TCB
TCB
Stack
Free space
ConfigTOTAL_HEAP_SIZE
requestedsize.
Stack
TCB
TCB
Stack
Stack
Stack
TCB
TCB
TCB
Figure12:Thealgorithmwillalwaysusethesmallestfreespace
wheretherequestedportioncanfit.
Suchanalgorithmcangeneratealotoffragmentationinmemoryifallocationsarenotregular,butitfitsif
allocationsremainsconstantinsizeandnumber.
6.4 Freememoryallocationanddeallocation
Thislaststrategymakespossibleeverymanipulation,butsuffersfromthesamedrawbacksasusingmalloc()and
free():largecompiledcodeornondeterministicexecution.Thisimplementationwrapsthetwofunctions,butmakethem
thread safe by suspending the scheduler while allocating or deallocating. Text 17 And section 8.4 give the
implementationforthismemorymanagementstrategy.
21
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Memorymanagement
void*pvPortMalloc(size_txWantedSize)
{
void*pvReturn;
vTaskSuspendAll();
{
pvReturn=malloc(xWantedSize);
}
xTaskResumeAll();
returnpvReturn;
}
voidvPortFree(void*pv)
{
if(pv!=NULL)
{
vTaskSuspendAll();
{
free(pv);
}
xTaskResumeAll();
}
}
Text17:Threadsafewrappersformalloc()andfree()areanothersolutiontomanagememory.
22
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Memorymanagement
Conclusion
FreeRTOSisanoperatingsystemdesignedforsmallembeddedsystem:butifitsmemoryfootprintcanbevery
small,itsfunctionalitiesarealsoverylimited:nosupportforthread,minimalistmemorymanagement,nodriveris
availabletohandleresourcesonusualbussuchasUSBorPCI,nosupportforanycommunicationprotocolssuchasan
IPstackandnothingisavailabletohandleanyfilesystem;eveninputoutputprimitivesarenotavailable.Howeverbasic
functionsofanoperatingsystemareimplemented;thisisenoughforthedesignofverysmallandrathercomplex
applications.
23
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Memorymanagement
References
This works makes references to FreeRTOS documentation books Using the FreeRTOS Real Time kernel
availabletodownloadonhttp://www.freertos.org/a00104.html.Illustrationsusedinthisreportcanbefoundinthisbook.
ThisreportalsomakesreferencetoFreeRTOSAPIpublishedonhttp://www.freertos.org/a00106.htmlandonthebook
FreeRTOSReferencemanualhttp://www.freertos.org/a00104.html.
24
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Illustrations
7 Illustrations
Figure1:Simplifiedlifecycleofatask:Onlyonetaskcanbe"running"atagiventime,whereasthenotrunningstate
canbeexpanded..................................................................................................................................................................7
Figure2:Lifecycleofatask................................................................................................................................................9
Figure3:Everyclocktickmakestheschedulertoruna"Ready"statetaskandtoswitchouttherunningtask...............13
Figure4:AnhypotheticFreeRTOSapplicationschedule..................................................................................................15
Figure5:Twotaskswithaequivalentpriorityarerunaftereachotherinturn..................................................................15
Figure6:Possiblescenariowithaqueueandtwotasks.....................................................................................................21
Figure7:Abinarysemaphoreisequivalenttoaqueuewhichcancontainoneelement...................................................25
Figure8:Usualusecaseofamutex...................................................................................................................................27
Figure9:InterruptorganizationinFreeRTOS....................................................................................................................31
Text1:Atypicaltasksignature............................................................................................................................................6
Text2:Taskcreationroutine.................................................................................................................................................7
Text3:Atypicaltask(fromUsingtheFreeRTOSRealTimeKernel).............................................................................7
Text4:Deletingatask..........................................................................................................................................................7
Text5:normalmethodtoreadinaqueue:itreadsanelementthenremovesit.................................................................10
Text6:Italsopossibletoreadinaqueuewithoutwithoutremovingtheelementfromit.................................................10
Text7:functiontowriteonaqueueinFIFOmode............................................................................................................11
Text8:xQueueSendToBack:asynonymforxQueSend;xQueueSendToFrontwriteonaqueueinLIFOmode..............11
Text9:Queuecreationfunction..........................................................................................................................................11
Text10:creatingasemaphore.............................................................................................................................................13
Text11:takingasemaphore................................................................................................................................................13
Text12:givingasemaphore...............................................................................................................................................13
Text13:Creationofacountingsemaphore.........................................................................................................................16
Text14:Acriticalsectionprotectedagainstbothschedulerswitchoutoperations,andhardwareinterrupts................18
Text15:Creationofacountingsemaphore........................................................................................................................19
Text16:Prototypesformemoryallocation/deallocation....................................................................................................19
Text17:Threadsafewrappersformalloc()andfree()areanothersolutiontomanagememory........................................22
25
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
8 Appendix
8Appendix.........................................................................................................................................................................26
8.1AnexampleofFreeRTOSConfig.h.........................................................................................................................27
8.2heap_1.c..................................................................................................................................................................29
8.3heap_2.c...................................................................................................................................................................31
8.4heap_3.c..................................................................................................................................................................37
26
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
8.1 AnexampleofFreeRTOSConfig.h
/*
FreeRTOSV6.0.0Copyright(C)2009RealTimeEngineersLtd.
***************************************************************************
**
*Ifyouare:*
**
*+NewtoFreeRTOS,*
*+WantingtolearnFreeRTOSormultitaskingingeneralquickly*
*+Lookingforbasictraining,*
*+WantingtoimproveyourFreeRTOSskillsandproductivity*
**
*thentakealookattheFreeRTOSeBook*
**
*"UsingtheFreeRTOSRealTimeKernelaPracticalGuide"*
*http://www.FreeRTOS.org/Documentation*
**
*Apdfreferencemanualisalsoavailable.Bothareusuallydelivered*
*toyourinboxwithin20minutestotwohourswhenpurchasedbetween8am*
*and8pmGMT(althoughpleaseallowupto24hoursincaseof*
*exceptionalcircumstances).Thankyouforyoursupport!*
**
***************************************************************************
ThisfileispartoftheFreeRTOSdistribution.
FreeRTOSisfreesoftware;youcanredistributeitand/ormodifyitunder
thetermsoftheGNUGeneralPublicLicense(version2)aspublishedbythe
FreeSoftwareFoundationANDMODIFIEDBYtheFreeRTOSexception.
***NOTE***TheexceptiontotheGPLisincludedtoallowyoutodistribute
acombinedworkthatincludesFreeRTOSwithoutbeingobligedtoprovidethe
sourcecodeforproprietarycomponentsoutsideoftheFreeRTOSkernel.
FreeRTOSisdistributedinthehopethatitwillbeuseful,butWITHOUT
ANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYor
FITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicensefor
moredetails.YoushouldhavereceivedacopyoftheGNUGeneralPublic
LicenseandtheFreeRTOSlicenseexceptionalongwithFreeRTOS;ifnotit
canbeviewedhere:http://www.freertos.org/a00114.htmlandalsoobtained
bywritingtoRichardBarry,contactdetailsforwhomareavailableonthe
FreeRTOSWEBsite.
1tab==4spaces!
http://www.FreeRTOS.orgDocumentation,latestinformation,licenseand
contactdetails.
http://www.SafeRTOS.comAversionthatiscertifiedforuseinsafety
criticalsystems.
http://www.OpenRTOS.comCommercialsupport,development,porting,
licensingandtrainingservices.
*/
#ifndefFREERTOS_CONFIG_H
#defineFREERTOS_CONFIG_H
27
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
#include<i86.h>
#include<conio.h>
/*
*Applicationspecificdefinitions.
*
*Thesedefinitionsshouldbeadjustedforyourparticularhardwareand
*applicationrequirements.
*
*THESEPARAMETERSAREDESCRIBEDWITHINTHE'CONFIGURATION'SECTIONOFTHE
*FreeRTOSAPIDOCUMENTATIONAVAILABLEONTHEFreeRTOS.orgWEBSITE.
*
*Seehttp://www.freertos.org/a00110.html.
**/
#defineconfigUSE_PREEMPTION
#defineconfigUSE_IDLE_HOOK
#defineconfigUSE_TICK_HOOK
#defineconfigTICK_RATE_HZ
#defineconfigMINIMAL_STACK_SIZE
bemadesmallerifrequired.*/
#defineconfigTOTAL_HEAP_SIZE
#defineconfigMAX_TASK_NAME_LEN
#defineconfigUSE_TRACE_FACILITY
#defineconfigUSE_16_BIT_TICKS
#defineconfigIDLE_SHOULD_YIELD
#defineconfigUSE_CO_ROUTINES
#defineconfigUSE_MUTEXES
#defineconfigUSE_COUNTING_SEMAPHORES
#defineconfigUSE_ALTERNATIVE_API
#defineconfigUSE_RECURSIVE_MUTEXES
#defineconfigCHECK_FOR_STACK_OVERFLOW
port.*/
#defineconfigUSE_APPLICATION_TASK_TAG
#defineconfigQUEUE_REGISTRY_SIZE
1
1
1
((portTickType)1000)
((unsignedshort)256)/*Thiscan
((size_t)(32*1024))
(16)
1
1
1
1
1
1
1
1
0/*DonotusethisoptiononthePC
1
0
#defineconfigMAX_PRIORITIES
((unsignedportBASE_TYPE)10)
#defineconfigMAX_CO_ROUTINE_PRIORITIES(2)
/*Setthefollowingdefinitionsto1toincludetheAPIfunction,orzero
toexcludetheAPIfunction.*/
#defineINCLUDE_vTaskPrioritySet 1
#defineINCLUDE_uxTaskPriorityGet 1
#defineINCLUDE_vTaskDelete 1
#defineINCLUDE_vTaskCleanUpResources 1
#defineINCLUDE_vTaskSuspend 1
#defineINCLUDE_vTaskDelayUntil
1
#defineINCLUDE_vTaskDelay
1
#defineINCLUDE_uxTaskGetStackHighWaterMark0/*Donotusethisoptiononthe
PCport.*/
/*Anexample"taskswitchedin"hookmacrodefinition.*/
#definetraceTASK_SWITCHED_IN()xTaskCallApplicationTaskHook(NULL,(void*)
0xabcd)
28
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
externvoidvMainQueueSendPassed(void);
#definetraceQUEUE_SEND(pxQueue)vMainQueueSendPassed()
#endif/*FREERTOS_CONFIG_H*/
8.2 heap_1.c
/*
FreeRTOSV6.0.0Copyright(C)2009RealTimeEngineersLtd.
***************************************************************************
**
*Ifyouare:*
**
*+NewtoFreeRTOS,*
*+WantingtolearnFreeRTOSormultitaskingingeneralquickly*
*+Lookingforbasictraining,*
*+WantingtoimproveyourFreeRTOSskillsandproductivity*
**
*thentakealookattheFreeRTOSeBook*
**
*"UsingtheFreeRTOSRealTimeKernelaPracticalGuide"*
*http://www.FreeRTOS.org/Documentation*
**
*Apdfreferencemanualisalsoavailable.Bothareusuallydelivered*
*toyourinboxwithin20minutestotwohourswhenpurchasedbetween8am*
*and8pmGMT(althoughpleaseallowupto24hoursincaseof*
*exceptionalcircumstances).Thankyouforyoursupport!*
**
***************************************************************************
ThisfileispartoftheFreeRTOSdistribution.
FreeRTOSisfreesoftware;youcanredistributeitand/ormodifyitunder
thetermsoftheGNUGeneralPublicLicense(version2)aspublishedbythe
FreeSoftwareFoundationANDMODIFIEDBYtheFreeRTOSexception.
***NOTE***TheexceptiontotheGPLisincludedtoallowyoutodistribute
acombinedworkthatincludesFreeRTOSwithoutbeingobligedtoprovidethe
sourcecodeforproprietarycomponentsoutsideoftheFreeRTOSkernel.
FreeRTOSisdistributedinthehopethatitwillbeuseful,butWITHOUT
ANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYor
FITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicensefor
moredetails.YoushouldhavereceivedacopyoftheGNUGeneralPublic
LicenseandtheFreeRTOSlicenseexceptionalongwithFreeRTOS;ifnotit
canbeviewedhere:http://www.freertos.org/a00114.htmlandalsoobtained
bywritingtoRichardBarry,contactdetailsforwhomareavailableonthe
FreeRTOSWEBsite.
1tab==4spaces!
http://www.FreeRTOS.orgDocumentation,latestinformation,licenseand
contactdetails.
http://www.SafeRTOS.comAversionthatiscertifiedforuseinsafety
criticalsystems.
http://www.OpenRTOS.comCommercialsupport,development,porting,
licensingandtrainingservices.
29
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
*/
/*
*ThesimplestpossibleimplementationofpvPortMalloc().Notethatthis
*implementationdoesNOTallowallocatedmemorytobefreedagain.
*
*Seeheap_2.candheap_3.cforalternativeimplementations,andthememory
*managementpagesofhttp://www.FreeRTOS.orgformoreinformation.
*/
#include<stdlib.h>
/*DefiningMPU_WRAPPERS_INCLUDED_FROM_API_FILEpreventstask.hfromredefining
alltheAPIfunctionstousetheMPUwrappers.Thatshouldonlybedonewhen
task.hisincludedfromanapplicationfile.*/
#defineMPU_WRAPPERS_INCLUDED_FROM_API_FILE
#include"FreeRTOS.h"
#include"task.h"
#undefMPU_WRAPPERS_INCLUDED_FROM_API_FILE
/*Allocatethememoryfortheheap.Thestructisusedtoforcebyte
alignmentwithoutusinganynonportablecode.*/
staticunionxRTOS_HEAP
{
#ifportBYTE_ALIGNMENT==8
volatileportDOUBLEdDummy;
#else
volatileunsignedlongulDummy;
#endif
unsignedcharucHeap[configTOTAL_HEAP_SIZE];
}xHeap;
staticsize_txNextFreeByte=(size_t)0;
/**/
void*pvPortMalloc(size_txWantedSize)
{
void*pvReturn=NULL;
/*Ensurethatblocksarealwaysalignedtotherequirednumberofbytes.
*/
#ifportBYTE_ALIGNMENT!=1
if(xWantedSize&portBYTE_ALIGNMENT_MASK)
{
/*Bytealignmentrequired.*/
xWantedSize+=(portBYTE_ALIGNMENT(xWantedSize&
portBYTE_ALIGNMENT_MASK));
}
#endif
vTaskSuspendAll();
{
/*Checkthereisenoughroomleftfortheallocation.*/
if(((xNextFreeByte+xWantedSize)<configTOTAL_HEAP_SIZE)&&
((xNextFreeByte+xWantedSize)>xNextFreeByte) )/*Check
foroverflow.*/
30
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
{
/*Returnthenextfreebytethenincrementtheindexpast
this
block.*/
pvReturn=&(xHeap.ucHeap[xNextFreeByte]);
xNextFreeByte+=xWantedSize;
}
}
xTaskResumeAll();
#if(configUSE_MALLOC_FAILED_HOOK==1)
{
if(pvReturn==NULL)
{
externvoidvApplicationMallocFailedHook(void);
vApplicationMallocFailedHook();
}
}
#endif
returnpvReturn;
}
/**/
voidvPortFree(void*pv)
{
/*Memorycannotbefreedusingthisscheme.Seeheap_2.candheap_3.c
foralternativeimplementations,andthememorymanagementpagesof
http://www.FreeRTOS.orgformoreinformation.*/
(void)pv;
}
/**/
voidvPortInitialiseBlocks(void)
{
/*Onlyrequiredwhenstaticmemoryisnotcleared.*/
xNextFreeByte=(size_t)0;
}
/**/
size_txPortGetFreeHeapSize(void)
{
return(configTOTAL_HEAP_SIZExNextFreeByte);
}
8.3 heap_2.c
/*
FreeRTOSV6.0.0Copyright(C)2009RealTimeEngineersLtd.
***************************************************************************
**
*Ifyouare:*
**
*+NewtoFreeRTOS,*
*+WantingtolearnFreeRTOSormultitaskingingeneralquickly*
*+Lookingforbasictraining,*
*+WantingtoimproveyourFreeRTOSskillsandproductivity*
31
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
**
*thentakealookattheFreeRTOSeBook*
**
*"UsingtheFreeRTOSRealTimeKernelaPracticalGuide"*
*http://www.FreeRTOS.org/Documentation*
**
*Apdfreferencemanualisalsoavailable.Bothareusuallydelivered*
*toyourinboxwithin20minutestotwohourswhenpurchasedbetween8am*
*and8pmGMT(althoughpleaseallowupto24hoursincaseof*
*exceptionalcircumstances).Thankyouforyoursupport!*
**
***************************************************************************
ThisfileispartoftheFreeRTOSdistribution.
FreeRTOSisfreesoftware;youcanredistributeitand/ormodifyitunder
thetermsoftheGNUGeneralPublicLicense(version2)aspublishedbythe
FreeSoftwareFoundationANDMODIFIEDBYtheFreeRTOSexception.
***NOTE***TheexceptiontotheGPLisincludedtoallowyoutodistribute
acombinedworkthatincludesFreeRTOSwithoutbeingobligedtoprovidethe
sourcecodeforproprietarycomponentsoutsideoftheFreeRTOSkernel.
FreeRTOSisdistributedinthehopethatitwillbeuseful,butWITHOUT
ANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYor
FITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicensefor
moredetails.YoushouldhavereceivedacopyoftheGNUGeneralPublic
LicenseandtheFreeRTOSlicenseexceptionalongwithFreeRTOS;ifnotit
canbeviewedhere:http://www.freertos.org/a00114.htmlandalsoobtained
bywritingtoRichardBarry,contactdetailsforwhomareavailableonthe
FreeRTOSWEBsite.
1tab==4spaces!
http://www.FreeRTOS.orgDocumentation,latestinformation,licenseand
contactdetails.
http://www.SafeRTOS.comAversionthatiscertifiedforuseinsafety
criticalsystems.
http://www.OpenRTOS.comCommercialsupport,development,porting,
licensingandtrainingservices.
*/
/*
*AsampleimplementationofpvPortMalloc()andvPortFree()thatpermits
*allocatedblockstobefreed,butdoesnotcombineadjacentfreeblocks
*intoasinglelargerblock.
*
*Seeheap_1.candheap_3.cforalternativeimplementations,andthememory
*managementpagesofhttp://www.FreeRTOS.orgformoreinformation.
*/
#include<stdlib.h>
/*DefiningMPU_WRAPPERS_INCLUDED_FROM_API_FILEpreventstask.hfromredefining
alltheAPIfunctionstousetheMPUwrappers.Thatshouldonlybedonewhen
task.hisincludedfromanapplicationfile.*/
#defineMPU_WRAPPERS_INCLUDED_FROM_API_FILE
#include"FreeRTOS.h"
32
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
#include"task.h"
#undefMPU_WRAPPERS_INCLUDED_FROM_API_FILE
/*Allocatethememoryfortheheap.Thestructisusedtoforcebyte
alignmentwithoutusinganynonportablecode.*/
staticunionxRTOS_HEAP
{
#ifportBYTE_ALIGNMENT==8
volatileportDOUBLEdDummy;
#else
volatileunsignedlongulDummy;
#endif
unsignedcharucHeap[configTOTAL_HEAP_SIZE];
}xHeap;
/*Definethelinkedliststructure.Thisisusedtolinkfreeblocksinorder
oftheirsize.*/
typedefstructA_BLOCK_LINK
{
structA_BLOCK_LINK*pxNextFreeBlock;
/*<<Thenextfreeblockinthe
list.*/
size_txBlockSize;
/*<<Thesizeofthe
freeblock.*/
}xBlockLink;
staticconstunsignedshortheapSTRUCT_SIZE
=(sizeof(xBlockLink)+
portBYTE_ALIGNMENT(sizeof(xBlockLink)%portBYTE_ALIGNMENT));
#defineheapMINIMUM_BLOCK_SIZE
((size_t)(heapSTRUCT_SIZE*2))
/*Createacoupleoflistlinkstomarkthestartandendofthelist.*/
staticxBlockLinkxStart,xEnd;
/*Keepstrackofthenumberoffreebytesremaining,butsaysnothingabout
fragmentation.*/
staticsize_txFreeBytesRemaining;
/*STATICFUNCTIONSAREDEFINEDASMACROSTOMINIMIZETHEFUNCTIONCALLDEPTH.
*/
/*
*Insertablockintothelistoffreeblockswhichisorderedbysizeof
*theblock.Smallblocksatthestartofthelistandlargeblocksattheend
*ofthelist.
*/
#defineprvInsertBlockIntoFreeList(pxBlockToInsert)
\
{
\
xBlockLink*pxIterator;
\
size_txBlockSize;
\
\
xBlockSize=pxBlockToInsert>xBlockSize;
\
33
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
\
/*Iteratethroughthelistuntilablockisfoundthathasalargersize
*/
\
/*thantheblockweareinserting.*/
\
for(pxIterator=&xStart;pxIterator>pxNextFreeBlock>xBlockSize<
xBlockSize;pxIterator=pxIterator>pxNextFreeBlock)
\
{
\
/*Thereisnothingtodoherejustiteratetothecorrect
position.*/
\
}
\
\
/*Updatethelisttoincludetheblockbeinginsertedinthecorrect*/
\
/*position.*/
\
pxBlockToInsert>pxNextFreeBlock=pxIterator>pxNextFreeBlock;
\
pxIterator>pxNextFreeBlock=pxBlockToInsert;
\
}
/**/
#defineprvHeapInit()
\
{
\
xBlockLink*pxFirstFreeBlock;
\
*/
\
/*xStartisusedtoholdapointertothefirstiteminthelistoffree
\
/*blocks.Thevoidcastisusedtopreventcompilerwarnings.*/
\
xStart.pxNextFreeBlock=(void*)xHeap.ucHeap;
\
xStart.xBlockSize=(size_t)0;
\
\
/*xEndisusedtomarktheendofthelistoffreeblocks.*/
\
xEnd.xBlockSize=configTOTAL_HEAP_SIZE;
\
xEnd.pxNextFreeBlock=NULL;
\
\
/*Tostartwiththereisasinglefreeblockthatissizedtotakeupthe
\
entireheapspace.*/
\
pxFirstFreeBlock=(void*)xHeap.ucHeap;
34
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
\
pxFirstFreeBlock>xBlockSize=configTOTAL_HEAP_SIZE;
\
pxFirstFreeBlock>pxNextFreeBlock=&xEnd;
\
\
xFreeBytesRemaining=configTOTAL_HEAP_SIZE;
\
}
/**/
void*pvPortMalloc(size_txWantedSize)
{
xBlockLink*pxBlock,*pxPreviousBlock,*pxNewBlockLink;
staticportBASE_TYPExHeapHasBeenInitialised=pdFALSE;
void*pvReturn=NULL;
vTaskSuspendAll();
{
/*Ifthisisthefirstcalltomallocthentheheapwillrequire
initialisationtosetupthelistoffreeblocks.*/
if(xHeapHasBeenInitialised==pdFALSE)
{
prvHeapInit();
xHeapHasBeenInitialised=pdTRUE;
}
/*ThewantedsizeisincreasedsoitcancontainaxBlockLink
structureinadditiontotherequestedamountofbytes.*/
if(xWantedSize>0)
{
xWantedSize+=heapSTRUCT_SIZE;
/*Ensurethatblocksarealwaysalignedtotherequired
numberofbytes.*/
if(xWantedSize&portBYTE_ALIGNMENT_MASK)
{
/*Bytealignmentrequired.*/
xWantedSize+=(portBYTE_ALIGNMENT(xWantedSize&
portBYTE_ALIGNMENT_MASK));
}
}
if((xWantedSize>0)&&(xWantedSize<configTOTAL_HEAP_SIZE))
{
/*Blocksarestoredinbyteordertraversethelistfrom
thestart
(smallest)blockuntiloneofadequatesizeisfound.*/
pxPreviousBlock=&xStart;
pxBlock=xStart.pxNextFreeBlock;
while((pxBlock>xBlockSize<xWantedSize)&&(pxBlock
>pxNextFreeBlock))
{
pxPreviousBlock=pxBlock;
pxBlock=pxBlock>pxNextFreeBlock;
}
35
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
/*Ifwefoundtheendmarkerthenablockofadequatesize
wasnotfound.*/
if(pxBlock!=&xEnd)
{
/*ReturnthememoryspacejumpingoverthexBlockLink
structure
atitsstart.*/
pvReturn=(void*)(((unsignedchar*)
pxPreviousBlock>pxNextFreeBlock)+heapSTRUCT_SIZE);
/*Thisblockisbeingreturnedforusesomustbetaken
ourofthe
listoffreeblocks.*/
pxPreviousBlock>pxNextFreeBlock=pxBlock
>pxNextFreeBlock;
/*Iftheblockislargerthanrequireditcanbesplit
intotwo.*/
if((pxBlock>xBlockSizexWantedSize)>
heapMINIMUM_BLOCK_SIZE)
{
/*Thisblockistobesplitintotwo.Createa
newblock
followingthenumberofbytesrequested.Thevoid
castis
usedtopreventbytealignmentwarningsfromthe
compiler.*/
pxNewBlockLink=(void*)(((unsignedchar
*)pxBlock)+xWantedSize);
/*Calculatethesizesoftwoblockssplitfrom
thesingle
block.*/
pxNewBlockLink>xBlockSize=pxBlock>xBlockSize
xWantedSize;
pxBlock>xBlockSize=xWantedSize;
/*Insertthenewblockintothelistoffree
blocks.*/
prvInsertBlockIntoFreeList((pxNewBlockLink));
}
xFreeBytesRemaining=xWantedSize;
}
}
}
xTaskResumeAll();
#if(configUSE_MALLOC_FAILED_HOOK==1)
{
if(pvReturn==NULL)
{
externvoidvApplicationMallocFailedHook(void);
vApplicationMallocFailedHook();
}
}
#endif
36
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
returnpvReturn;
}
/**/
voidvPortFree(void*pv)
{
unsignedchar*puc=(unsignedchar*)pv;
xBlockLink*pxLink;
if(pv)
{
/*ThememorybeingfreedwillhaveanxBlockLinkstructure
immediately
beforeit.*/
puc=heapSTRUCT_SIZE;
/*Thiscastingistokeepthecompilerfromissuingwarnings.*/
pxLink=(void*)puc;
vTaskSuspendAll();
{
/*Addthisblocktothelistoffreeblocks.*/
prvInsertBlockIntoFreeList(((xBlockLink*)pxLink));
xFreeBytesRemaining+=pxLink>xBlockSize;
}
xTaskResumeAll();
}
}
/**/
size_txPortGetFreeHeapSize(void)
{
returnxFreeBytesRemaining;
}
/**/
voidvPortInitialiseBlocks(void)
{
/*Thisjustexiststokeepthelinkerquiet.*/
}
8.4 heap_3.c
/*
FreeRTOSV6.0.0Copyright(C)2009RealTimeEngineersLtd.
***************************************************************************
**
*Ifyouare:*
**
*+NewtoFreeRTOS,*
*+WantingtolearnFreeRTOSormultitaskingingeneralquickly*
*+Lookingforbasictraining,*
*+WantingtoimproveyourFreeRTOSskillsandproductivity*
**
*thentakealookattheFreeRTOSeBook*
**
*"UsingtheFreeRTOSRealTimeKernelaPracticalGuide"*
37
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
Appendix
*http://www.FreeRTOS.org/Documentation*
**
*Apdfreferencemanualisalsoavailable.Bothareusuallydelivered*
*toyourinboxwithin20minutestotwohourswhenpurchasedbetween8am*
*and8pmGMT(althoughpleaseallowupto24hoursincaseof*
*exceptionalcircumstances).Thankyouforyoursupport!*
**
***************************************************************************
ThisfileispartoftheFreeRTOSdistribution.
FreeRTOSisfreesoftware;youcanredistributeitand/ormodifyitunder
thetermsoftheGNUGeneralPublicLicense(version2)aspublishedbythe
FreeSoftwareFoundationANDMODIFIEDBYtheFreeRTOSexception.
***NOTE***TheexceptiontotheGPLisincludedtoallowyoutodistribute
acombinedworkthatincludesFreeRTOSwithoutbeingobligedtoprovidethe
sourcecodeforproprietarycomponentsoutsideoftheFreeRTOSkernel.
FreeRTOSisdistributedinthehopethatitwillbeuseful,butWITHOUT
ANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYor
FITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicensefor
moredetails.YoushouldhavereceivedacopyoftheGNUGeneralPublic
LicenseandtheFreeRTOSlicenseexceptionalongwithFreeRTOS;ifnotit
canbeviewedhere:http://www.freertos.org/a00114.htmlandalsoobtained
bywritingtoRichardBarry,contactdetailsforwhomareavailableonthe
FreeRTOSWEBsite.
1tab==4spaces!
http://www.FreeRTOS.orgDocumentation,latestinformation,licenseand
contactdetails.
http://www.SafeRTOS.comAversionthatiscertifiedforuseinsafety
criticalsystems.
http://www.OpenRTOS.comCommercialsupport,development,porting,
licensingandtrainingservices.
*/
/*
*ImplementationofpvPortMalloc()andvPortFree()thatreliesonthe
*compilersownmalloc()andfree()implementations.
*
*Thisfilecanonlybeusedifthelinkerisconfiguredtotogenerate
*aheapmemoryarea.
*
*Seeheap_2.candheap_1.cforalternativeimplementations,andthememory
*managementpagesofhttp://www.FreeRTOS.orgformoreinformation.
*/
#include<stdlib.h>
/*DefiningMPU_WRAPPERS_INCLUDED_FROM_API_FILEpreventstask.hfromredefining
alltheAPIfunctionstousetheMPUwrappers.Thatshouldonlybedonewhen
task.hisincludedfromanapplicationfile.*/
#defineMPU_WRAPPERS_INCLUDED_FROM_API_FILE
#include"FreeRTOS.h"
38
NicolasMelot
Studyofanoperatingsystem:FreeRTOS
#include"task.h"
#undefMPU_WRAPPERS_INCLUDED_FROM_API_FILE
/**/
void*pvPortMalloc(size_txWantedSize)
{
void*pvReturn;
vTaskSuspendAll();
{
pvReturn=malloc(xWantedSize);
}
xTaskResumeAll();
#if(configUSE_MALLOC_FAILED_HOOK==1)
{
if(pvReturn==NULL)
{
externvoidvApplicationMallocFailedHook(void);
vApplicationMallocFailedHook();
}
}
#endif
returnpvReturn;
}
/**/
voidvPortFree(void*pv)
{
if(pv)
{
vTaskSuspendAll();
{
free(pv);
}
xTaskResumeAll();
}
}
39
Appendix