LightweightIOVirtualizationOnMPUEnabledMicrocontrollersFrancescoPaciUniversityofBolognaBologna,Italyf.
paci@unibo.
itDavideBrunelliUniversityofTrentoTrento,Italydavide.
brunelli@unitn.
itLucaBeniniUniversityofBolognaBologna,ItalyETHZZürich,Switzerlandluca.
benini@unibo.
itluca.
benini@iis.
ee.
ethz.
chABSTRACTIntheeraoftheInternetofThings(IoT),millionsofde-vicesandembeddedplatformsbasedonlow-costandlim-itedresourcesmicrocontrollerunits(MCUs)willbeusedincontinuousoperation.
Evenifover-the-airrmwareupdateistodayacommonfeature,manyapplicationsmightrequirenottorebootortosupporthardwareresourcesharing.
Insuchacontextstop,updateandreboottheplatformisun-practicalanddynamicloadingofnewusercodeisrequired.
ThisinturnrequiresmechanismstoprotecttheMCUhard-wareresourcesandthecontinuouslyexecutingsystemtasksfromuncontrolledperturbationcausedbynewusercodebe-ingdynamicallyloaded.
Inthispaper,wepresentaframe-workwhichprovidesalightweightvirtualizationoftheIOandplatformperipheralsandpermitsthedynamicloadingofnewusercode.
Theaimofthisworkistosupportcriticalisolationfeaturestypicalofvirtualization-readyCPUsonlow-costlow-powermicrocontrollerswithnoMMU(Mem-oryManagementUnit),IOMMUordedicatedinstructionextensions.
OurapproachonlyleveragestheMemoryPro-tectionUnit(MPU),whichisgenerallyavailableinallARMCortex-M3andCortex-M4microcontrollers.
Experimentalevaluationsdemonstratenotonlythefeasibility,butalsoasatisfactorylevelofperformanceoftheproposedframeworkintermsofmemoryrequirementsandoverhead.
KeywordsVirtualization,MPU,Microcontrollers,DynamicLinking1.
INTRODUCTIONManyIoTapplicationsenvisionthedeploymentoflargenumbersofmicrocontroller-basedsmartsensornodesinhard-to-reachlocations[1,2].
Thisnotonlymeansthattheyaresupposedtooperateunattended,withoutdirectmain-tenance,andlikelywiththesamebatteryformanyyears;butalsothatthesoftwarecouldbeupdated(ifnecessary)onlyremotely;andinmanyscenariositisexpectedthatbugxes,functionalimprovements,recongurationwillbenecessaryoverthetime.
Clearlytheoldfashionstyleforreprogrammingembeddedsystemsbasedonstoppingthedevice,updatingthermwareandrestart,becomeunfeasi-blewhenmillionsoflowcostdevicesarespreadalloverandareexpectedtobeupdatedwithnewfunctionalitymanytimesovertheirlifespan.
Inaddition,IoTdevicesareexpectedtoprovidemoreandEWiLi'16,October6th,2016,Pittsburgh,USA.
Copyrightretainedbytheauthors.
moreservicesonthesamehardware.
Thepossibilitytohavemultiple"applicationtasks"runningonthesamehardware,possiblycomingfromdierentdevelopers,introducesthechallengeofprotectingtheresourcesfrommisusesandtoguaranteeadequatecomputingbandwidthtoallthetasksortopreventover-allocationofresourcesthatwouldleadtocollectivestarvation.
Insuchascenario,well-knownvirtualizationtechnologiesalreadyusedincomputingservers,gatewaysandotherhigh-endcomputingsystemsbecomefundamentalalsoinlow-endandultra-lowcostprogrammableend-nodesforIoT.
First,thevirtualizationofthehardwareresourcesbecomesnec-essarytoexecutesecurelymulti-functionsoftwareanddif-ferentapplicationswithwell-controlledinterference.
Then,thecapabilitytoremotelydownloadnewpartsofcode,tolinkdynamicallythebinaryandtoexecuteruntimewithinthemainapplication,avoidson-sitemaintenanceorperiodicdown-timeandreboot.
ThesetworequirementshighlighttheimportanceofIOvirtualizationanddynamiclinkingonlow-cost,low-powermicrocontrollers.
However,ifthistechnologyiswellknownandavailableinoperatingsystemsforhigh-endembeddedsystems(e.
g.
LinuxonARMCortex-Amicroprocessors),providingmechanismsfordynamiclinkinginlow-resourcemicrocontrollerbasedembeddedplatforms,suchasARMCortex-Mclass,isstillachallenge,andonlyfewandlimitedsolutionshavebeenproposedsofar.
ThedynamiclinkingproposedinthisworkexecutesontheFreeRTOS[3]operatingsystemanditisbasedontheframeworkpresentedin[4]whichaddressedthecapabilitytodownloadnewfunctionsremotely.
Themaincontributionsofthispaperare:aLightweightVirtualizationlayerwhichseparatestheuserspacefromthekernelspace,thereforenowallthephysicalperipheralsarevirtualized.
Suchavir-tualizationisaprotectiontowardssystemtamperandreadytobeextendedtoprotectpossibleconictsonthehardwareassignments;oursolutionisintegratedwithFreeRTOSandexploitsstandardcommunicationAPIprovidedbytheoperat-ingsystem.
Thus,itcanbeeasilyportedalsoonothermicrocontrollers.
weprovidethecapabilitytohavethedynamiclinkingofnewusercode,managingitslifecycleaswellasitsorderlyshutdownincaseofattemptedviolationsofprotectedmemoryregions;Thepaperisorganizedasfollows.
Section2givesanoverviewofworksrelatedtoourcontribution,Section3de-scribesindepththeframeworkarchitectureandprovidesalltechnicaldetailsofthissolution,Section4detailsourper-formanceandmemoryfootprint,whileSection5concludesthepaper.
2.
RELATEDWORKSVirtualizationsupportforembeddedsystemsbasedonhigh-endCPUs,suchastheARMCortex-Aseries,hasbeenextensivelyexploredintheacademicliteratureandhasreachedindustrialmaturity[5].
Thisclassofdevicesexploitsthehardwareaccelerationextensionstoprovidehardwareab-stractionandprotectiontocriticalresources.
RecentCortex-ACPUsfeaturenativevirtualizationsupportlikeMMUandIOMMUaddresstranslation,interruptvirtualization,Trust-Zones[6,7],etc.
Cortex-MMCUsdonotcomewithanyofthosehardwareextensions.
Furthermore,availablememoryandcomputationalresourcesaremuchmorelimited.
OurworkandtherelatedworkssurveyedbelowdealwithCortex-M3andCortex-M4classofdevices,wherevirtualizationisnotamaturetechnologyandseveralcompromiseswithre-specttofullhardware-supportedvirtualizationhavetobemade.
AbstractVirtualMachinesandInterpretersOneofthemostcommonapproachesforvirtualizationonMCUsisbasedoninterpreter-basedvirtualmachines,whichhavebeenoriginallyconceivedwiththemainpurposeofcreatinghigh-leveleasy-to-uselanguagesandrun-timesatahigherabstractionlevelthanthetraditionalClanguage.
Python[8,9],Java[10,11],Javascript[12],Lua[13]arealllightweightmulti-paradigmscriptinglanguagesemployedinVirtualMachinesforembeddedsystems.
Theirmainbene-tisthecross-platformsupport.
Theyareinterpretedbyanativevirtualmachineloadedonthemicrocontroller,thustheyintroducehighoverheadintermoflatencyofaccesstotheresourcesincomparisontovirtualizationlayerswritteninnativecode,buttheyaredesignedforeasysoftwareap-plicationdevelomentandtomeettheincreasingdemandoffastruntimecustomization,withouttheneedofcomplexordedicatedcompilingtoolchains.
Suchakindofvirtualiza-tion,usually,isfocusedonimprovingportability,extensibil-ity,ease-of-useindevelopmentandprotectionbutlacksofperformance,multipleuserlevelaccessesandlow-levelhard-warecontrol.
Onlytheexposedhighlevelresourcescanbeleveragedbytheuser.
Boglioloetal.
[14]presentedVirtualSense,asensornodewhichexecutesjava-compatiblevirtualmachinecalledDar-jeelingVM[11]ontopofContikiOS[15].
Thisworkisclosetooursintheemphasisonsupportingresourceallo-cationandprotectionformultipleindependentusertasksontheMCU.
Howeverthissolution,besidestheoverheadintroducedbytheinterpreter,isorientedtoshareonlynet-workstackbetweenDarjeelingVMtasks,whileourworkisgeneraltoallperipherals.
JustInTime/AheadofTimeCompilationAwell-exploredapproachtoreducetherun-timeoverheadofVMinterpetersisJustinTimeorAheadofTimeCompi-lation.
Micropython[8]developers,forexample,introducedintheirplatformtheconceptofdecoratortoemitARMnativeopcodeandtousenativeCtypes,butnotallna-tiveCtypesaresupportedandtheimplementationofthisoptimizationisplatformdependent.
AsolutioncanbetoextendwithCwrappedfunctionscalledfrompython,buttherearedrawbacks:marshalingandunmarshalingofdataisveryexpensiveintermsofcomputationalresourcesandwiththissolutiontheprogrammerlosesthelowlevelab-straction.
Incomparison,usingoursolution,thedeveloperimplementsCfunctionswhichwillbeexecutedinuserleveltasks.
Ingeneraltheseapproachesrequireahighermemoryfootprinttohostthejust-in-timeorahead-of-timecompileprocessanddonotachievetheperformanceofnativecodeexecution.
Furthermore,theyarediculttouseincontextswherereal-timeconstraintscannottoleratethejitterintro-ducedbyon-linecompilation.
NativeImplementationsNativevirtualizationistheclosesttohardwareandextremelydesirableforresourceandperformance-limiteddevices.
ThistechniqueusuallyreliesontheuseofMPUthatistheonlyhardwareunitavailableforsecurityinlow-endsystems.
Bhattietal.
[3]presentedacompleteoperatingsystemde-signedforWSN(WirelessSensorNetwork)andoptimizedtosimultaneousexecutionofthreadswhichcanbeloadeddynamically.
TheirworkreliesonMantisOS,acustomop-eratingsystem.
TheytargetAtmelandtheirsolutionishighlycustomized,thusisnotgeneral,whileourworkreliesonFreeRTOSthereforeitishighlyextensibleandportabletootherplatforms.
Moreovertheydonotexplicitlyaddresssecurityandprotection.
Tothebestofourknowledgewendonlyoneveryrecentworkthataddressestheprobleminabroadandgeneralsense,similarlytooursolution.
Andersenetal.
[16]pre-sentedanembeddedplatformthatreliesonTinyOS.
TheyuseamixedparadigmthatpermitstohaveLuaVMbutthecomputationalintensivepartofcodecanbewritteninnativeC.
Toaddresssecuritytheyuseataskreceivingeventbasedsystemcalls,toseparatekerneltouserspacetasks.
OurworkdierentiatesfromthelatterbypermittingtohavebothsystemcallsupportandEventbasedperipheralvir-tualization.
MoreoverAndersenetal.
donotprovideanyinformationontheperformanceoftheeventbasedsystemcallparadigm.
3.
SOFTWAREARCHITECTUREInthissectionwepresentallthesoftwarelayersinourruntimesystem,focusingonsoftwareprotection.
Figure1showsthelayerstackingfromthreeviewpoints,rstfromahardwarepointofview,thenfromaddressspaceaccess,dividedinIOandFlash/RAM.
WedividedcorehardwarefromperipheralsintwodierentstackstounderlinethattheOScanexposesystemcallstoaccesstothecorehardwareresources,whiletheVirtualIOLayerisdesignedtoaccesstotheperipherals.
Thelaststackshowsthattheaccesstomemoriesisdirectforprivilegedtasks,whiletheaccessfromusermodetasksisstrictlyregulatedbyMPU.
Twodierentkindsoftasksaredened:privilegedtasksandusermodetasks,whichwillbediscussedinnextsection.
AnotherimportantlayerdepictedinFigure1isFreeR-TOS[17],awellknownRealTimeOperatingSystemforabroadrangeofEmbeddedSystemsfrom8to32bit,includ-inglowpowerandultra-lowpowerMCUs.
WeimplementedourframeworkonanSTM32F4basedplatform,andevenifsomedetailsinthefollowingdescriptionarerelatedtothisspecicmicrocontroller,ourframeworkcanbeeasilyextendedtobeplatformindependent.
InSections3.
1and3.
2wefocusontherstandthirdstack,namelyonexploitingtheMPUandprovidingSafetyExtensions,whileinSection3.
4wediscussthesecondstack.
3.
1RealTimeOSThemainreasonforusingFreeRTOSisitsversatility:manyMCUsaresupportedandthecodeismaintainedandupgradedoftenbyRealTimeEngineersLtd.
Moreoveritismodularandtherearesomeextensionsavailable(e.
g.
MPUextension),whichcanbeaddedtothecorerelease.
Theopensourcenaturemakespossibletoextendit.
Ithasmore-overasmallmemoryfootprintandsourcesconsistofasmallnumberofles.
Theschedulersupportsreal-timeoperation,Figure1:Hardware,IOandMemorieslayers.
bothtime-triggeredbyacongurablesystemtickandwithsupportforprioritieswithpreemption.
3.
2FreeRTOSAdditionsTostrengthenthesecurityofthesystem,theFreeRTOSMPUmodulehasbeenintegratedtoenabletheusageoftheMemoryProtectionUnitimplementedonthemicrocon-trollerandtoactivatethetwolevelsofprivilegesforthetasksexecution.
However,theoriginalmoduleisanex-perimentalrelease,becauseofsomelimitationsthatwead-dressedinourwork:1.
Itdoesnothaveaproperwaytoaccesssystemre-sources.
Itprovidesonlyonesystemcall.
Thissystemcallraisestheprivilegesofthecallerfromusermodetoprivileged,executesthecallandthensetstheprivilegesbacktouserspace.
Thisbehaviorhassucientprotec-tioninanenvironmentwhereasingledeveloperwantstokeepseparationbetweentasks,i.
e.
thecasewhereasinglecompanydevelopsallthermware.
Whileinthecasewewanttogivetoathird-partyusertheca-pabilitytodevelophisowncode,theknowledgeoftheexistenceofthisbackdoorisreallydangerousforpro-tection.
2.
TheexploitationoftheMPUisstatic.
TheprotectionsectionsoftheMPUarenotrecongurableatrun-timebyprivilegedtasks.
3.
Thetaskterminationisnotcorrectlyhandled.
WhenausermodetaskraisesanMPUtraptheexceptionendsthesystemexecution.
Henceitwouldbeextremelyeasytocreatedenialofserviceattacks.
Innextsub-sectionswedescribeourproposedsolutionstotheselimitations.
3.
2.
1MPUExtensionAsalreadystated,thismodulepermitstograntdierentaccessprivilegesonatask-by-taskbasis.
ForeachtasktheMPUsettingsarestoredinthetaskdescriptor,calledTaskControlBlock(TCB)inFreeRTOS.
Whenataskiscreated,itcanbestartedwithoneoutoftwolevelsofprivileges:1.
PrivilegedTasks(similartoLinuxKernelModeexe-cution).
Thetaskexecuteswithpermissiongrantedtoaccessallsystemresources,memoriesandperipherals.
2.
UsermodeTasks(similartoLinuxKernelUserMode,alsocalledunprivilegedtasks).
ThetaskisexecutedinmorerestrictiveenvironmentandhasaccessonlytoalimitedsubsetofmemoryandIOaddresses.
STM32Cortex-M4haseightcongurableMPUregions.
Whenactivatedtheprotectionpolicyiswhite-listbased:toaccesstoaspecicpositionintheaddressspace,thetaskshouldhaveagrantononeMPUregion.
TheprivilegesonanMPUregioncanbe:NONE,READONLYANDREAD-WRITE.
InFreeRTOStheseMPUregionsareconguredasfollows:Region0FLASHprotectionProtectswholeFLASHprovidingread-onlyprivi-legestobothprivilegedandusermodetasks.
Region1OSFLASHprotectionProtectsfromaccessesbyusermodetaskstotheOScodeinFLASHRegion2OSRAMaccessProvidespermissiontoprivilegedtasktoaccesstheOSstructuresstoredinRAMRegion3PeripheralaccessUsedtoenableordisabletheaccesstoperipherals.
Region4TaskStackaccessUsedtogiveaccesstotasksownstack.
Region5-7NotusedThesethreeregionsarenotusedbyFreeRTOSMPUmodule,thustheyareopentodeveloperpurposes.
InTable1,weshowalistofMPUcongurationsusedinoursolution.
Asthereadercannotice,thereisnoaccesstoperipheralsgrantedtousermodetasks.
ThisaccesscanbeonlyallowedthroughtheIOVirtualizationArchitecture.
OneofthemainconstraintsoftheFreeRTOSMPUmod-uleisthatitpermitstocongurethelastregions(from5to7)atcompiletimeonly.
Thus,weimplementedaspecicsoftwaremoduletoreconguretheseregionsatrun-timeforeachtask.
Thisisdoneforthefollowingreasons:1.
AccesstoVirtualIOLayer(deeplyexplainedinSub-section3.
4)canberestrictedbyanMPURegionandmustbeaskedbyatask.
ThismakestheVirtualIOLayerawareaboutthenumberoftasksthatareusingit.
2.
Moreoveraccesstoheaporothermemoryregionscanbegrantedatrun-time.
Thisisopentoseveralfutureapplications.
3.
2.
2SafetyExtensionsAspreviouslystated,thesinglesystemcallparadigmisnotsafe.
Theraiseprivilegesystemcallhasbeenremovedandreplacedbymorespecicsystemcallsforrequiredcases.
ForexampletograntaccesstoFreeRTOSQueuesandDi-rectTaskNotication,thefollowinglistofsystemcallsareadded:MPUxTaskGenericNotify:DirecttasknoticationNo-tifyfunctionMPUQueueReceive:ReceiveamessageonaqueueMPUxGetCurrentTaskHandle:GetthecurrenttaskhandleIOLayerREGISTER:RegistrationtoVirtualIOLayerTable1:DefaultMPUregionsettinginFreeRTOSPrivilegedPerm.
UserModePerm.
RegionDesc.
READONLYREADONLYallFlashProtectionREADONLYNONEOSCodeSegmentinFLASHREADWRITENONEOSRAMProtectionREADWRITENONEPeripheralsREADWRITEREADWRITETaskStackNOTUSEDNOTUSEDUsercongurableNOTUSEDNOTUSEDUsercongurableNOTUSEDNOTUSEDUsercongurable3.
2.
3GracefulTaskTermination-KillerTaskFreeRTOSdoesnotprovidetasktermination.
Thus,whenanunprivilegedtasktriestoaccessamemoryaddresswith-outpermissionatrapisgeneratedfromtheMPUandtheOSendsitsexecutioninanendlessloop.
Thisisnotaccept-ableifwewanttokeepallothertasksandOSinexecution.
Thedesiredbehavioristhatthetaskcausingthetrap,isabortedwhilethesystemcontinuesitsexecution.
Thusamemorytraphandlerandaspecictask,calledKillerTask,havebeencreatedtomanagetheterminationofthetaskthatraisedthetrap.
TheKillerTaskisaprivilegedtaskcreatedatboottimeanditisinsleepstate,whentheMCUisinnormalusage.
Whenatrapoccursthetaskisactivated.
TheKillerTaskgetsthetaskhandlesofthetaskthatgen-eratedthetrapandremovesitfromtheschedulerexecutionqueue.
Thenitresumestheschedulerexecutionandgoesbackintosleep,waitingforthenexttrap.
3.
3SoftwareProtectionInasoftwareprotectionperspective,theMPUenablestheOStokeepthecontrolontheusermodetasks.
Thus,withtheMPUallusermodetaskscannottamperthewholesystem.
Ontheotherhand,ifwewanttoenableathirdpartysoftwaredevelopertoaccessonlyasmallsubsetofperipherals,anegraincontrolonaddressspacemustbeimplemented.
UsuallyinaMCUallperipheralsaddressesaregroupedfromastartingtoanendingaddress.
However,ifwewanttoprovidenegrainaccesstoasubsetofthem,threefreeMPUregionsarereallylimiting.
Moreoverthereareothertwolimitations:oneisthattheminimumareaforanMPUregionsisusually32Bytes(i.
e.
onSTM32f4)thatisusuallylargerthantheregisterpoolofaperipheral.
Theotheristhatregistersetofseveralperipheralsconsistsofbothcontrolregisters,andreading/writingports,atsubse-quentmemorypositions.
Thusitisnotpossibletogranttheaccesstoaread-onlyregisteranddenyingthepermissiontoacontiguouscongurationregister.
3.
4IOVirtualizationArchitectureTheVirtualIOLayerarchitectureconsistsoftwomainparts:(1)ataskcalledVirtualIOTaskthatinvokesthecallbackstoaccesstoIOandtoperipheralsthroughthehardwareabstractionlayer(HAL);(2)alibrarynamedVir-tualIOLibrarythatcontainsthefront-endcallsforwardedtransparentlytotheVirtualIOTaskandtheback-endcallsinvokedbytheVirtualIOTasktoaccesstheHALLibrary.
TheVirtualIOTaskisaFreeRTOStaskthathandlesalltheIOcallsfromtheusermodetaskstotheperipherals.
AsshowninFigure2:thistaskactsasatask-in-the-middlethatreceivesallcallsfromusermodetasksthatattempttoac-cesstotheperipherals,checksthepermissionsandforwardstherequeststhroughtheHALlibrary.
3.
4.
1VirtualIOLibraryFigure2:IOVirtualizationHighLevelArchitectureThelibraryconsistsoftwosubsets:afront-endfunctionssubsetandtherelativeback-endfunctionssubset.
Whenausermodetaskwantstoaccessperipherals,itneedstosubscribetotheVirtualIOLayer,usingonespe-cialfront-endfunction.
Registrationisrequiredfortwopur-poses:1.
TheusermodetaskmusthavereadonlyaccesstotheVirtualIOtaskhandle.
ThisisneededtousetheOSeventnoticationstonotifytheVirtualIOtask.
Therefore,oneoftheMPUregionsofthetaskmustberun-timeconguredtoread-onlyaccesstoVirtualIOtaskhandler.
2.
Usermodetasksarenotauthorizedtouseinterrupthandlers,becauseinterrupthandlercodeisexecutedinprivilegedmode.
Weusedaqueuesystemtocom-municatefrominterrupthandlerstousermodetasks.
Hencetheregistrationroutinecreatesanewqueueandsavesthequeuehandlerinastructure.
Thiswillbeusedafterwardsifthetaskwillrequestaccesstooneperipheralininterruptmode.
Theregistrationisdonethroughasystemcallthatwaspreviouslymentionedinsubsection3.
2.
2,hiddenbyafront-endcall.
ThesystemcallisneededtocongureanMPUregiondescribedintheformerpurpose.
Theregistrationprocedureworksasfollows:(1)Theusermodetaskin-vokestheIOLayerinit()routine,whichthrough(2)theIOLayerREGISTERsystemcall(3)setsanMPUregionofthecallertasktoaccesstoVirtualIOTaskdescriptorinread-onlymode.
ThisisneededtosendNotications.
ThentheframeworkcreateandinitializesaSystemQueue(4)forusingtheDMA(theprocedureisdescribedinBackEndSubsetsubsection).
Beforereturning,iftheprocedurewassuccessful,thetaskisaddedtothelistofVirtualIOsubscribedtasks.
FrontEndSubsetTheFrontEndsubsetisintendedtobecalledfromtheusermodetasks.
ThesecallshavethesamesignatureoftheoriginalHALlibrarycalls,besidethefunctionname,whichisextendedwithaprextomaketheprogrammerawarethatisusingtheVirtualIOLayerand,obviously,toavoidanamespaceconict.
ThusforeachHALlibraryfunctionthatwewanttoexposetothethirdpartydeveloperafunctionmustbewritten.
Eachfunctiondeclaresastructurethatcontains:1.
Theuser-modetasktaskhandler.
2.
Apointertotherelativeback-endfunctiontobecalledbytheVirtualIOTask3.
ApointerforeachoriginalHALLibraryfunctionar-gument.
4.
IftheoriginalHALfunctionreturnsanon-voidvalue,aeldtostoreit.
WerefertothisstructurewiththenameHALLibraryAr-gumentEmbeddingStructure(HAEStructure).
ThenHAEstructureisinstantiatedinthefunction,onthestack,andallstructure'seldsareassignedwiththeirvalues.
Anoti-cationissenttotheVirtualIOLayerTaskwithapointertothisstructure.
AttheendoptionallytheHALLibraryre-turnvalueisreturnedifthefunctionisnon-void.
ArecapoftheembeddingofthisfunctionisshowninrighttopcornerofFigure2.
BackEndSubsetThebackend(orcallbackfunctions)isthepartofthelibrarymeanttobecalledbytheVirtualIOTask.
Foreachfront-endfunction,thereisonecorrespondingback-endonethattakesininputasingleargument,avoidpointer.
ItsbodycontainsadeclarationoftheHAEstructurewrittenforthecorrespondingfront-endfunction.
Thevoidpointeristhencastinthisstructure,argumentsarethenusedtocalltheoriginalHALfunction.
WhentheHALLibrarycallendsup,thereturnargumentiswritteninthestructure,thatstillresidesintheuser-modestackthencontrolreturntotheVirtualIOTask.
ThentheVirtualIOTasksuspendsitsexecutionwaitingforthenextcall.
Thisarchitecturehastwoadvantages:(1)theeaseofuse,theprogrammerdoesnotneedtolearnanewinterfacetousetheHAL.
(2)Allfront-endcallsandback-endcallshavethesameformat,sotheycanbewrittenbyaprogrammerorgeneratedbyanautomatictool.
ToHandleDMAasynchronouscallsandtogetnotiedwhenaDMAtransferiscompleted,weusetheQueuere-turnedwhentheusermodetasksubscribestheVirtualIOLayer.
Forsecurityitisimportantthatalltheinterruptser-viceroutines(ISR)areimplementedbythesystem.
More-overinsideeachserviceroutinethereisaQueueSendopera-tionusedtonotifythetaskthatwantstousetheDMAthattheroutineiscalled.
Tocorrectlynotifythecorrespondingusermodequeueareferencetableisused.
Thisreferenceta-bleissetbytheback-end,whentheusermodetaskinvokesoneoftheDMAHALLibraryfunctions.
3.
4.
2VirtualIOTaskTheVirtualIOTaskisaprivilegedtaskthathandlesthecommunicationfromusermodetaskstoperipherals.
ItstartswhentheVirtualIOlayerisinitialized,typicallyatsystemboottime.
ThecommunicationishandledviaDi-rectTaskNotication.
Whenstartedthistaskhangsinsuspendedstatewaitingforacallfromoneoftheusermoderegisteredtasksthroughthefront-end.
Thepriorityofthistaskishigherthanallusermodetasks.
Thus,whenthenoticationisthrownfromthefront-end,theusermodetaskwaitsthattheVirtualIOtaskendsitsexecution.
Thereforeeveniftasknoticationsareasyn-chronous,thecalltoHALLibraryisblockingbecauseinFreeRTOSthepreemptionoftheschedulerisprioritybased.
Thebodyofthistask,besidestheTaskNotifyWait,con-sistsofanAccessControlList(ACL),showninFigure2,thatchecksthatthecalleeHALLibraryfunctioncanbein-vokedbythecaller.
ThepointertoHAEStructureiscasttoagenericstructurecommonforallHAEStructures(wealwaysknowthatthersttwoeldsarexed:theuser-modetasktaskhandlerandthepointertothecall-backfunction),thentheACLpermissioncheckoccurs.
ifthecheckingpassed,theback-endfunctionisinvoked.
3.
5DynamicLinkingThedynamiclinkingpermitsatasktobeaddedtotheruntimetaskswithoutrebootingthesystem.
Weimple-menteddynamiclinkingtodemonstratetheusageofthewholesystem.
Therefore,weimplementedaprivilegedtaskinchargeofdynamiclinkingotherusermodetasks.
Tasksarecross-compiledandunresolveddependenciestosystemlibrarycallsarerun-timelinkedandthetaskisaddedtoschedulerexecutionqueue.
Thelibraryinchargeofdynamiclinkingusermodetasksisderivedfromtheworkof[4].
InFlashmemorywereservedasectiontostorethesenewtasksbinariestobelinkedandthenaddedtoFreeRTOSschedulerreadytasklist.
4.
EXPERIMENTALRESULTSInthissectionwepresentresultsintermofperformanceandmemoryfootprint.
AlltestswereconductedonanSTM32F411RENUCLEO-64Board[18].
Thisisaplat-formbySTMicroelectronics,itembedsanARMR32-bitCortexR-M4CPUrunningupto100MHzwithFPUandMPU.
Itfeatures512KBofFlashmemoryand128KBofRAMmemory.
InoursoftwaresetupweusethenewdriverforaccessinghardwareperipheralsprovidedbySTcalledHardwareAbstractionLayerDriver(HALDriver)[19].
Weidentiedtwomainusecases,i.
e.
waystoaccesspe-ripheralsinaMicrocontrollerunit,thatmustbeconsideredseparately:1.
AtomicAction:ThisisthecaseinwhichwecallaHALDriverroutineeachtimeweaccessaperipheral.
Inotherwords,wejustwanttoaccessonceanIOaddressorwemayac-cessitinaloop,butcalldoesnotinvolveperipheraltransferafterit.
AnexampleofthisbehavioriswhenwewanttocongureorreadaGPIOPIN,orwritesomethingontheUART.
2.
ContinuousAction(orTunnelingAction):Inthissecondcaseweconsideralltheperipheralus-agesthatinvolvetheuseofDMA.
ForexamplewhenwewanttosetAnalogtoDigitalconverterandreaditatregularintervalsbytheDMA.
4.
1VirtualIOLayerTimingThetimeofaccessingaperipheralusingtheVirtualIOLayerisreportedinTable2.
Therstrowgivesthecyclestogetthetaskhandlethroughasystemcall.
TheMPU-xTaskGenericNotify()isthedirecttasknoticationsystemcall.
ThethirdrowreportsthecyclesrequiredtonotifytheVirtualIOTask.
Thelastrowgivesthenumberofcyclestoreturncontrol,aftertheHALDrivercallbacktotheUsermodetask.
ThecyclesmeasurementhasbeendonewiththeDWTCYCCNThardwarecyclecountregisteroftheCortex-M4MCU.
Itisworthmentioningthatwiththisparadigm,continu-ousmodeoperationspaytheoverheadjustonce,whenthesetupoftheperipheralorIOisperformed.
ThuswhentheDMAisworkingtheonlyoverheadisthequeueusedtosyn-chronizetheISRwiththeusermodetask.
ThecyclesoverheadtocheckifthefunctionthattheusermodetaskwantstouseispermittedbytheACLgrowslin-earlywiththenumberofchecksthatoccurs.
InTableareVirtualizationStepVIO(Cycles)getTaskHandle97MPUxTaskGenericNotify47xTaskNotify+CS490Notifywait+CSback293TOTAL926Table2:TimingoverheadofaccessingtheIOusingtheVirtualIOLayerinCyclesFigure3:OverheadofthecontrolintheACL.
wereportthetheoverheadAsexpectedthenumberofcy-clesareproportionaltothenumberoffunctionaddressestoverify.
4.
2VirtualIOLayerMemoryFootprintTheoverheadintermsofmemoryfootprintisdescribedinTable3.
WeshowthecodesizeofthelibraryandoftheVirtualIOTaskseparately,incasethecompilerisinvokedwiththeagforperformance(-O3)orspace(-OS)optimiza-tion.
TheSizeoftheVirtualIOLibraryismeasuredwithanaveragesizeof50functions(frontend+backend).
Aswecannoticefromtheresults,thememoryfootprintismin-imal,evenifitscaleswiththenumberofdriverfunctionsthatwewanttoprovidetotheusermodetasks.
OptimizationVIOTaskVIOLibrary-O3592B2876B-OS464B2314BTable3:VirtualizationLayercodesizeAsaconcludingnote,itisimportanttostressthefactthattheruntimeoftaskswhennotinteractingwiththeIOsisexactlythesameasnativeFreeRTOStasks,withnoperfor-manceoverheadformemoryprotectionastheMPUiscom-pletelytransparentfromtheperformanceviewpoint.
Thisisverysimilartowhathappensinvirtualmachineexecutionforhigh-endcores,andinsharpcontrastwithinterpretedvirtualmachinesorevenJIT-basedsystems.
5.
CONCLUSIONSInthispaperwehavepresentedavirtualizationlayerforlow-costmicrocontrollerswhichcreatesaseparationbetweenkernelmodeandusermodeandprotectsthehardwarere-sourcesfrommisuseswhenconcurrenttasksorfunctionarewrittenbydierentdevelopers.
Moreoverwedemonstratedtheeectivenessofamechanismcapabletoexecutenewrun-timecode,withouttheneedofsystemreboot.
Wehavefocusedonsmallsizeoftheframeworkandonlowerover-head,becausetargetedforlow-costandlimitedcomputingcapabilitiesmicrocontrollerssuchastheonesdesignedforIoTandWSN.
Experimentalresultsdemonstratethattheoverheadislimitedandtimedelayisnegligibleconsideringthetypicalapplicationscenarios.
Futureworkswillextenddynamiclinkingtowardmultipleuploadchannelsandwillimplementdierentpermissionpoliciestoperipheralsfromdierentusermodetasks.
6.
ACKNOWLEDGMENTSThisworkwaspartiallysupportedbyEUProjectEu-roCPSH2020-ICT-2014underGrant644090andincollab-orationwithSTMicroelectronics.
7.
REFERENCES[1]LuTanetal.
.
Futureinternet:Theinternetofthings.
In20103rdInternationalConferenceonAdvancedComputerTheoryandEngineering(ICACTE),volume5,pagesV5–376–V5–380,Aug2010.
[2]AlaAl-Fuqahaetal.
.
Internetofthings:Asurveyonenablingtechnologies,protocols,andapplications.
IEEECommunicationsSurveysTutorials,17(4):2347–2376,Fourthquarter2015.
[3]ShahBhattietal.
.
Mantisos:Anembeddedmultithreadedoperatingsystemforwirelessmicrosensorplatforms.
Mob.
Netw.
Appl.
,10(4):563–579,August2005.
[4]SimonHolmbackaetal.
Lightweightframeworkforruntimeupdatingofc-basedsoftwareinembeddedsystems.
InPresentedaspartofthe5thWorkshoponHotTopicsinSoftwareUpgrades,Berkeley,CA,2013.
USENIX.
[5]ARMVirtualizationExtension.
https://www.
arm.
com/.
[6]ARMSecurityTechnology-BuildingaSecureSystemusingTrustZoneTechnology.
Whitepaper,April2009.
[7]T.
AlvesandD.
Felton.
Trustzone:Integratedhardwareandsoftwaresecurity-enablingtrustedcomputinginembeddedsystems.
Whitepaper,arm,july2004.
[8]Micropythonwebsite.
http://micropython.
org/.
[9]PyMite.
https://wiki.
python.
org/moin/PyMite.
[10]OracleJavaMEEmbedded.
http://www.
oracle.
com/.
[11]NielsBrouwersetal.
.
Darjeeling,afeature-richvmfortheresourcepoor.
InProceedingsofthe7thACMConferenceonEmbeddedNetworkedSensorSystems,SenSys'09,pages169–182,NewYork,NY,USA,2009.
ACM.
[12]EspruinoJavascriptInterpreter.
http://www.
espruino.
com/.
[13]EmbeddedpowerdrivenbyLua.
http://www.
eluaproject.
net/.
[14]AlessandroBoglioloetal.
.
Virtualsense:Ajava-basedopenplatformforultra-low-powerwirelesssensornodes.
InternationalJournalofDistributedSensorNetworks,2012,2012.
[15]Contiki:TheOpenSourceOSfortheInternetofThings.
http://www.
contiki-os.
org/.
[16]MichaelP.
Andersenetal.
.
Systemdesignforasynergistic,lowpowermote/bleembeddedplatform.
InProceedingsofthe15thInternationalConferenceonInformationProcessinginSensorNetworks,IPSN'16,pages17:1–17:12,Piscataway,NJ,USA,2016.
IEEEPress.
[17]FreeRTOSwebsite.
http://www.
freertos.
org/.
[18]STMicroelectronicsNucleoBoards.
http://www.
st.
com/.
[19]STMicroelectronicsHardwareAbstractionLayerDriver.
http://www.
st.
com/.
80vps怎么样?80vps最近新上了香港服务器、美国cn2服务器,以及香港/日本/韩国/美国多ip站群服务器。80vps之前推荐的都是VPS主机内容,其实80VPS也有独立服务器业务,分布在中国香港、欧美、韩国、日本、美国等地区,可选CN2或直连优化线路。如80VPS香港独立服务器最低月付420元,美国CN2 GIA独服月付650元起,中国香港、日本、韩国、美国洛杉矶多IP站群服务器750元/月...
菠萝云国人商家,今天分享一下菠萝云的广州移动机房的套餐,广州移动机房分为NAT套餐和VDS套餐,NAT就是只给端口,共享IP,VDS有自己的独立IP,可做站,商家给的带宽起步为200M,最高给到800M,目前有一个8折的优惠,另外VDS有一个下单立减100元的活动,有需要的朋友可以看看。菠萝云优惠套餐:广州移动NAT套餐,开放100个TCP+UDP固定端口,共享IP,8折优惠码:gzydnat-8...
ShockHosting商家在前面文章中有介绍过几次。ShockHosting商家成立于2013年的美国主机商,目前主要提供虚拟主机、VPS主机、独立服务器和域名注册等综合IDC业务,现有美国洛杉矶、新泽西、芝加哥、达拉斯、荷兰阿姆斯特丹、英国和澳大利亚悉尼七大数据中心。这次有新增日本东京机房。而且同时有推出5折优惠促销,而且即刻使用支付宝下单的话还可获赠10美金的账户信用额度,折扣相比之前的常规...
waitingforreboot为你推荐
linux虚拟主机基于linux操作系统的虚拟主机控制面板有哪些?域名购买如何申请购买 永久域名国外主机空间2个国外主机空间,都放了BLOG,看看哪个更快?免费网站空间申请需要一个免费的网站空间申请地址。虚拟主机服务商哪个虚拟主机的服务商比较好?mysql虚拟主机如何建立支持PHP+MySQL的虚拟主机?美国免费虚拟主机美国虚拟主机怎么样?美国虚拟主机那个比较好?shopex虚拟主机浙江新锐网络科技有限公司是一家骗子虚拟主机商www二级域名请问 www.aaa.bbb.com 是一级域名还是二级域名啊?能否备案?怎么备案?备案域名购买在哪里可以买到已备案域名啊?
美国vps租用 怎么注册域名 新世界机房 inmotionhosting googleapps evssl mysql主机 丹弗 java虚拟主机 免空 howfile me空间社区 老左正传 免费活动 免费asp空间 smtp服务器地址 net空间 lamp怎么读 带宽测试 mteam 更多