Managing Resources - cs.tut.fimobo/2008/luennot/resources.pdf · • Managing resources consumes...

Preview:

Citation preview

ManagingManaging ResourcesResources

ContentContent andand goalsgoals

•• CommonCommon concernsconcerns•• Mobile JavaMobile Java implementationimplementation•• SymbianSymbian OSOS implementationimplementation

–– ServerServer overviewoverview–– ServerServer implementationimplementation–– AdaptingAdapting serversservers

•• SummarySummary

ResourcesResources

•• HardwareHardware resourcesresources–– CameraCamera,, FileFile systemsystem ectect..

•• SoftwareSoftware resourcesresources–– SomeSome partsparts of softwareof software cancan bebe treatedtreated asas

resourcesresources

ResourceResource managersmanagersResource 1Resource 2

Resource 3

Resource 4

Resourcemanager 1

Resourcemanager 2

Resourcemanager 3 Resource

manager 4

EventEvent--drivendriven ExecutionExecution

Keyboard Screen Device IF UI mgr App

draw draw_figdraw_char

key_presskey_press

GroupingGrouping ResourceResource managersmanagers

Monolithic kernel

Resource 1

Resource 2

Application 1

Resource 3

Application 2

Resource access API

MonolithicMonolithic KernelKernel ConsiderationsConsiderations

•• PerformancePerformance–– ProceduralProcedural interfacesinterfaces cancan bebe usedused

•• FaultFault--tolerancetolerance–– PossiblePossible toto createcreate tangledtangled codecode

SeparatingSeparating ResourceResource managersmanagers

Message dispatching kernel

Resource 1

Resource 2

Resource 3

Application 1

Application 2

MessageMessage--PassingPassing KernelKernelConsiderationsConsiderations

•• PerformancePerformance–– MessageMessage passingpassing requirerequire severalseveral contextcontext

switchesswitches•• AddsAdds flexibilityflexibility•• BeneficialBeneficial ofof separationseparation ofof concernsconcerns

CommonCommon resourceresource--relatedrelatedconcernsconcerns

•• CommonCommon resourceresource--relatedrelated concernsconcerns–– ExtensionExtension andand adaptationadaptation–– PerformancePerformance–– EnergyEnergy consumptionconsumption–– InternalInternal resourceresource managementmanagement

•• RaisingRaising thethe levellevel ofof abstractionabstraction benefitsbenefitsthethe programmerprogrammer butbut resultsresults inin hardenedhardenedproblemsproblems withwith respectrespect toto leakingleakingabstractionsabstractions

ExtensionExtension andand AdaptationAdaptation

•• NeededNeeded forfor beingbeing ableable toto reusereuse thethe samesamecodecode inin differentdifferent devicesdevices andand contextscontexts whosewhosehardware and softwarehardware and software characteristicscharacteristics andandavailableavailable resourcesresources maymay differdiffer

•• CommonCommon partsparts inin oneone componentcomponent,, variantvariantpartsparts inin pluginsplugins ((oror otherother specializedspecializedmodulesmodules))–– HardwareHardware differencesdifferences ((screenscreen sizesize,, amountamount ofof

memorymemory,, keyboardkeyboard layout, ...)layout, ...)–– SoftwareSoftware differencesdifferences ((availabilityavailability ofof certaincertain

interfacesinterfaces, ...), ...)–– EffectEffect toto resourceresource consumptionconsumption ((memorymemory,, energyenergy))

PerformancePerformance

•• RequiresRequires specialspecial attentionattention becausebecause inin manymany casescasesmobilemobile devicedevice hardware ishardware is slowerslower thanthan workstationworkstationhardwarehardware

•• ResourcesResources commonlycommonly act as aact as a sourcesource of data forof data forapplicationsapplications–– CameraCamera,, filefile, radio, radio interfaceinterface, ..., ...

•• SeveralSeveral middlemiddle--menmen involvedinvolved–– HW,HW, driver(sdriver(s),), protocolsprotocols,, applicationapplication–– RepresentationRepresentation issueissue?? SharingSharing memorymemory oror messagemessage

passingpassing??•• AllocatingAllocating taskstasks toto processorsprocessors ((ifif moremore thanthan 1 is1 is

availableavailable))–– NoticeNotice thatthat thethe allocationallocation maymay bebe differentdifferent inin differentdifferent

devicesdevices andand eveneven whenwhen differentdifferent subsystemssubsystems havehave beenbeenturnedturned on/on/offoff

EnergyEnergy ConsumptionConsumption

•• EnergyEnergy consumptionconsumption ofof instructionsinstructions vs.vs. energyenergyconsumptionconsumption ofof instructionsinstructions andand theirtheir sideside--effectseffects

•• TimeoutsTimeouts as aas a practicalpractical implementationimplementation ofof switchingswitchingoffoff hardwarehardware–– UseUse forfor lowestlowest--prioritypriority threadthread??

•• RuleRule ofof thumbthumb:: ””GoodGood forfor performanceperformance isis goodgood forforenergyenergy consumptionconsumption””

•• TechniquesTechniques–– DifferentDifferent sleepsleep statesstates thatthat looseloose differentdifferent amountamount ofof contextcontext–– DynamicDynamic frequencyfrequency//voltagevoltage scalingscaling ((whowho decidesdecides scalingscaling

upup?)?)

ExampleExample:: IntelIntel’’ss powerpower modelmodel (2002?)(2002?)

Mechanicaloff

S5Soft off

S0Working

SxSleeping

SxSleeping

SxSleeping

S1-4Sleeping

C0

CPUC1

C2..n

D0LCD,audio,Com...

D1D2..4

powerfailure

wakeup

InternalInternal ResourceResource ManagementManagement

•• NeededNeeded forfor ensuringensuring thatthat thethe rightright resourcesresources areareavailableavailable at theat the rightright timetime

•• ManagingManaging resourcesresources consumesconsumes otherother resourcesresources((memorymemory,, processorprocessor timetime))

•• WhenWhen toto activateactivate aa resourceresource??–– StartStart--upup activationactivation–– ””ConvenientConvenient timetime”” activationactivation–– ApplicationApplication runrun timetime activationactivation

•• WhatWhat toto revealreveal of aof a resourceresource??–– ImplementationImplementation detailsdetails thatthat bearbear signifigancesignifigance–– E.gE.g.. SaveSave to theto the memorymemory spacespace ofof filefile managermanager vs.vs. savesave toto

thethe physicalphysical memorymemory•• HousekeepingHousekeeping performedperformed byby lowestlowest--prioritypriority threadthread

ContentContent andand goalsgoals

•• CommonCommon concernsconcerns•• Mobile JavaMobile Java implementationimplementation•• SymbianSymbian OSOS implementationimplementation

–– ServerServer overviewoverview–– ServerServer implementationimplementation–– AdaptingAdapting serversservers

•• SummarySummary

Mobile JavaMobile Java ImplementationImplementation

Resource Access API (message or API based)

Java Runtime Environment

midlet

Resourceinterface 1

Resourceinterface 2

Resourceinterface n

...

MIDP 1.0MIDP 1.0 InterfaceInterface DefinitionDefinition

•• UserUser interfaceinterface librarieslibraries•• NetworkingNetworking librarieslibraries•• PersistencePersistence librarieslibraries•• TimerTimer supportsupport•• SystemSystem propertiesproperties

–– E.gE.g.. namename of theof the devicedevice,, charactercharacter encodingencoding,,configurationconfiguration andand itsits version,version, profileprofile andand itsitsversion,version, languagelanguage and country, ...and country, ...

•• ResourceResource supportsupport ((accessaccess to JAR)to JAR)

MIDP 2.0MIDP 2.0 InterfaceInterface DefinitionDefinition

•• EnhancedEnhanced useruser interfaceinterface librarieslibraries•• ImprovedImproved networkingnetworking librarieslibraries

–– EncryptionEncryption,, socketssockets, ..., ...•• GamingGaming

–– UIUI layerslayers andand spritessprites•• SoundsSounds•• PublicPublic KeyKey InfrastructureInfrastructure

–– DigitalDigital signingsigning

OtherOther InterfacesInterfaces

•• JSR 46:JSR 46: FloatingFloating pointpoint 1.01.0•• JSR 66: RMIJSR 66: RMI•• JSR 75: PDAJSR 75: PDA OptionalOptional PackagesPackages•• JSR 80: USBJSR 80: USB•• JSR 82:JSR 82: BluetoothBluetooth•• JSR 135: Multimedia APIJSR 135: Multimedia API•• JSR 172: J2ME WebJSR 172: J2ME Web ServicesServices•• JSR 177:JSR 177: SecuritySecurity andand TrustTrust•• JSR 179:JSR 179: LocationLocation APIAPI•• JSR 253: MobileJSR 253: Mobile TelephonyTelephony•• JSR 259:JSR 259: AdAd HocHoc NetworkingNetworking•• JSR 278:JSR 278: ResourceResource Management API for Java MEManagement API for Java ME•• JSR 279: ServiceJSR 279: Service ConnectionConnection API for Java MEAPI for Java ME•• ......

ProblemsProblems??

•• GoogleGoogle ””WhyWhy J2MEJ2ME projectsprojects failfail??””•• DespiteDespite thethe standardstandard,, devicesdevices areare differentdifferent

–– AmountAmount ofof memorymemory–– AvailableAvailable interfacesinterfaces–– ImplementationImplementation ofof interfacesinterfaces cancan bebe differentdifferent–– SizeSize and layout of theand layout of the screenscreen–– KeyboardKeyboard layoutlayout–– LanguageLanguage versionsversions–– BugsBugs–– ......

PracticalPractical tipstips

•• StartStart withwith aa numbernumber ofof devicesdevices thatthat willwill bebe thethefirstfirst set onset on whichwhich thethe implementationimplementation isistargetedtargeted–– TypicalTypical,, lowlow--endend,, highhigh--endend,, lowestlowest--endend,, highesthighest--

endend•• ConsiderConsider whatwhat shouldshould happenhappen whenwhen

somethingsomething isis beingbeing executedexecuted andand e.ge.g. a. a callcallcomescomes inin

•• DoDo thethe necessarynecessary portingporting•• In the longIn the long runrun,, considerconsider tooltool supportsupport to helpto help

withwith practicalitiespracticalities

ContentContent andand goalsgoals

•• CommonCommon concernsconcerns•• Mobile JavaMobile Java implementationimplementation•• SymbianSymbian OSOS implementationimplementation

–– ServerServer overviewoverview–– ServerServer implementationimplementation–– AdaptingAdapting serversservers

•• SummarySummary

ServersServers

•• ServersServers areare thethe resourceresource--encapsulationencapsulation mechanismmechanisminin SymbianSymbian OSOS

•• ApplicableApplicable toto bothboth HW and SWHW and SW resourcesresources (in(in manymanycasescases usedused as aas a mechanismmechanism ofof abstractionabstraction))

•• AvailableAvailable inin differentdifferent flavorsflavors–– StartedStarted atat bootboot andand nevernever shutshut downdown–– StartedStarted whenwhen anan appapp isis runrun for thefor the firstfirst timetime andand nevernever shutshut

downdown–– StartedStarted whenwhen anan appapp isis runrun andand shutshut downdown whenwhen thethe

applicationapplication terminatesterminates•• CommonlyCommonly runrun inin differentdifferent processesprocesses,, althoughalthough somesome

serversservers shareshare resourcesresources forfor performanceperformance–– AlwaysAlways aa separateseparate threadthread

SomeSome SymbianSymbian OSOS ServersServers

•• FileFile Server ...Server ... FileFile accessaccess•• Windows Server ... GUIWindows Server ... GUI•• DatabaseDatabase Server ...Server ... ””GlobalGlobal”” datadata sharedshared byby appsapps•• CommsComms Server ...Server ... UseUse ofof e.ge.g.. serialserial portport•• SocketSocket Server ...Server ... SocketSocket communicationscommunications•• TelephonyTelephony Server ...Server ... TelecommunicationsTelecommunications featuresfeatures•• MessagingMessaging Server ...Server ... ManagesManages allall messagingmessaging•• CameraCamera Server ...Server ... ManagesManages cameracamera•• CONE Server ...CONE Server ... ControlControl environmentenvironment forfor usingusing GUIGUI•• Media Server ... Audio and multimediaMedia Server ... Audio and multimedia controlcontrol•• FontFont andand BitmapBitmap Server ...Server ... ManagesManages fontsfonts andand bitmapsbitmaps

ContentContent andand goalsgoals

•• CommonCommon concernsconcerns•• Mobile JavaMobile Java implementationimplementation•• SymbianSymbian OSOS implementationimplementation

–– ServerServer overviewoverview–– ServerServer implementationimplementation–– AdaptingAdapting serversservers

•• SummarySummary

ServersServers areare ActiveActive ObjectsObjectsclient client thread

RHandleBase

RSessionBase

RThread

RMessage

CSession CActiveSceduler

CActive

CServer- RServer(s)

WrappingWrapping MessagingMessaging

DLL wrapping the server

Serverthread

IPC

DLL serviceinterface

Conversionto messaging

Clientthread DLL

communication

ExampleExample:: usingusing filefile serverserver

__LIT(KFileNameLIT(KFileName, "C:, "C:\\\\file.txtfile.txt");");

voidvoid openFileLopenFileL()(){{

RFsRFs fsSessionfsSession; // handle to file server session; // handle to file server sessionRFileRFile file;file;

//// ConnectConnect toto filefile serverserverUser::LeaveIfErrorUser::LeaveIfError(( fsSession.ConnectfsSession.Connect() );() );CleanupClosePushL(fsSessionCleanupClosePushL(fsSession););//// OpenOpen filefile

User::LeaveIfErrorUser::LeaveIfError(( settingsFile.Open(fsSessionsettingsFile.Open(fsSession,, KFileNameKFileName,, EFileReadEFileRead) );) );

CleanupStack::PopAndDestroyCleanupStack::PopAndDestroy(); // pop and close(); // pop and close fsSessionfsSession}}

ExampleExample CodeCode:: OfferedOffered InterfaceInterface

EXPORT_CEXPORT_C TIntTInt RQASession::GetQuestionIdRQASession::GetQuestionId()(){{constconst TAnyTAny ** p[KMaxMessageArgumentsp[KMaxMessageArguments];];returnreturn SendReceive(EQuestionRequestCodeSendReceive(EQuestionRequestCode, p);, p);}}

EXPORT_CEXPORT_C TIntTInt RQASession::GetAnswerIdRQASession::GetAnswerId()(){{constconst TAnyTAny ** p[KMaxMessageArgumentsp[KMaxMessageArguments];];returnreturn SendReceive(EAnswerRequestCodeSendReceive(EAnswerRequestCode, p);, p);}}

ExampleExample CodeCode: Server: ServerImplementationImplementation

voidvoid CQASession::ServiceL(constCQASession::ServiceL(const RMessageRMessage && aMessageaMessage) {) {switch (switch (aMessage.FunctionaMessage.Function())())

{{casecase EQuestionRequestCodeEQuestionRequestCode::

GetQuestionId(aMessageGetQuestionId(aMessage););break;break;

casecase EAnswerRequestCodeEAnswerRequestCode::GetAnswerId(aMessageGetAnswerId(aMessage););break;break;

default:default:__LIT(KPanicLIT(KPanic, ", "QAServerQAServer");");aMessage.Panic(KPanicaMessage.Panic(KPanic,, KErrNotSupportedKErrNotSupported););

}}}}

ExampleExample CodeCode: Server: ServerImplementationImplementation

voidvoid CQASession::GetQuestionId(constCQASession::GetQuestionId(const RMessageRMessage && aMessageaMessage) {) {iQuestioniQuestion = (++= (++iQuestioniQuestion) %) % KQuestionCountKQuestionCount;;// Wrap integer to the message format.// Wrap integer to the message format.TPckgCTPckgC <<TIntTInt>> valueDes(iQuestionvalueDes(iQuestion););aMessage.WriteL(aMessage.Ptr0(),aMessage.WriteL(aMessage.Ptr0(), valueDesvalueDes););aMessage.Complete(KErrNoneaMessage.Complete(KErrNone););

}}

voidvoid CQASession::GetAnswerId(constCQASession::GetAnswerId(const RMessageRMessage && aMessageaMessage) {) {iAnsweriAnswer = (++= (++iAnsweriAnswer) %) % KAnswerCountKAnswerCount;;TPckgCTPckgC <<TIntTInt>> valueDes(iAnswervalueDes(iAnswer););aMessage.WriteL(aMessage.Ptr0(),aMessage.WriteL(aMessage.Ptr0(), valueDesvalueDes););aMessage.Complete(KErrNoneaMessage.Complete(KErrNone););

}}

ContentContent andand goalsgoals

•• CommonCommon concernsconcerns•• Mobile JavaMobile Java implementationimplementation•• SymbianSymbian OSOS implementationimplementation

–– ServerServer overviewoverview–– ServerServer implementationimplementation–– AdaptingAdapting serversservers

•• SummarySummary

AdaptingAdapting serversservers

•• SimilarlySimilarly toto otherother partsparts ofof SymbianSymbian OSOSneedingneeding adaptationadaptation,, alsoalso hardwarehardwareadaptationadaptation isis managedmanaged withwith pluginplugincomponentscomponents

AdaptingAdapting ServersServers withwith PluginsPlugins::ExampleExample

•• CSYCSY–– CommunicationCommunication subsystemsubsystem–– SpecializationSpecialization ofof communicationcommunication relatedrelated aspectsaspects to HW andto HW and

thethe usedused protocolsprotocols•• TSYTSY

–– TelephonyTelephony subsystemsubsystem–– SpecializationSpecialization forfor differentdifferent typestypes ofof telephonytelephony

•• PRTPRT–– ProtocolProtocol modulesmodules

•• MTMMTM–– MessageMessage typetype modulesmodules–– HandlingHandling ofof differentdifferent typestypes ofof messagesmessages usingusing thethe samesame

frameworkframework

ExampleExample

BT.PRT

device drivers

TCP.PRT

device drivers

Bluetooth TCP/IP with PPP

ECUART.CSY

HAYES.TSY

ProblemsProblems withwith serversservers

•• AA messagemessage passingpassing architecturearchitecture cancan bebeharmfulharmful toto performanceperformance

•• StartupStartup sequencesequence cancan bebe problematicproblematic•• InternalInternal errorserrors areare problematicproblematic•• ChangesChanges inin differentdifferent partsparts of theof the systemsystem

ContentContent andand goalsgoals

•• CommonCommon concernsconcerns•• IsolatingIsolating resourceresource managementmanagement•• Mobile JavaMobile Java implementationimplementation•• SymbianSymbian OSOS implementationimplementation

–– ServerServer overviewoverview–– ServerServer implementationimplementation

•• AdaptingAdapting serversservers•• SummarySummary

SummarySummary

•• ResourceResource managementmanagement encapsulationencapsulation helpshelps ininadaptingadapting toto changeschanges

•• ChallengesChallenges–– PerformancePerformance–– EnergyEnergy consumptionconsumption–– InternalInternal resourceresource managementmanagement

•• BalanceBalance betweenbetween flexibilityflexibility andand encapsulationencapsulation•• MonolithicMonolithic vs.vs. micromicro--kernelkernel•• LowestLowest--prioritypriority threadthread commonlycommonly usedused forfor internalinternal

resourceresource ((especiallyespecially energyenergy) management) management•• JavaJava implementationimplementation basedbased onon APIsAPIs•• SymbianSymbian OSOS implementationimplementation basedbased onon serversservers

Recommended