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/.
搬瓦工vps(bandwagonhost)现在面向中国大陆有3条顶级线路:美国 cn2 gia,香港 cn2 gia,日本软银(softbank)。详细带宽是:美国cn2 gia、日本软银,都是2.5Gbps~10Gbps带宽,香港 cn2 gia为1Gbps带宽,搬瓦工是目前为止,全球所有提供这三种带宽的VPS(云服务器)商家里面带宽最大的,成本最高的,没有第二家了! 官方网站:https...
DMIT怎么样?DMIT是一家美国主机商,主要提供KVM VPS、独立服务器等,主要提供香港CN2、洛杉矶CN2 GIA等KVM VPS,稳定性、网络都很不错。支持中文客服,可Paypal、支付宝付款。2020年推出的香港国际线路的KVM VPS,大带宽,适合中转落地使用。现在有永久9折优惠码:July-4-Lite-10OFF,季付及以上还有折扣,非 中国路由优化;AS4134,AS4837 均...
HostKvm也发布了开年促销方案,针对香港国际和美国洛杉矶两个机房的VPS主机提供7折优惠码,其他机房业务提供8折优惠码。商家成立于2013年,提供基于KVM架构的VPS主机,可选数据中心包括日本、新加坡、韩国、美国、中国香港等多个地区机房,均为国内直连或优化线路,延迟较低,适合建站或者远程办公等。下面列出几款主机配置信息。美国洛杉矶套餐:美国 US-Plan1CPU:1core内存:2GB硬盘...
waitingforreboot为你推荐
虚拟空间主机有了虚拟主机和空间怎么用云主机租用我想租用云主机,请问下该如何操作?虚拟主机推荐谁能推荐个性价比高的虚拟主机?网站服务器租用网站服务器租用100m网站空间做网站100M的空间够用吗?下载虚拟主机电脑虚拟机怎么弄虚拟主机mysql在虚拟主机如何打开数据库?shopex虚拟主机浙江新锐网络科技有限公司是一家骗子虚拟主机商厦门虚拟主机我想用我自己的电脑做虚拟主机怎么弄啊域名邮箱有谁知道域名邮箱是干什么的啊?有什么作用吗?
apache虚拟主机 域名注册信息查询 拜登买域名批特朗普 免费cn域名 greengeeks 60g硬盘 iis安装教程 青果网 godaddy域名证书 河南m值兑换 免费phpmysql空间 idc查询 流媒体加速 google台湾 百度云加速 免费asp空间 酸酸乳 免费稳定空间 重庆服务器 黑科云 更多