伯克利操作系统课件lec12io_第1页
伯克利操作系统课件lec12io_第2页
伯克利操作系统课件lec12io_第3页
伯克利操作系统课件lec12io_第4页
伯克利操作系统课件lec12io_第5页
已阅读5页,还剩26页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

CS162

OperatingSystemsand

SystemsProgramming

Lecture12

Kernel/User,I/OOctober14,2013AnthonyD.JosephandJohnCanny/~cs162DemandpagingleveragesseveralPTEbits“V”:Valid/NotValid“V=1”:ValidPageinmemory,PTEpointsatphysicalpage“V=0”:NotValidPagenotinmemory;useinfoinPTEtofindpageondiskifnecessary“D=1”:PagemodifiedNeedtowriteitbacktodiskbeforereplacingit“U=1”:PagereferencedGivepageasecondchancebeforebeingreplacedwhenusingSecondChancealgorithmSomeotherPTEbits:“R/W”:specifieswhetherthepagecanbemodifiedorisreadonlyPageAccessCount:implementmoreaccurateLRUalgorithmsReview:DemandPagingMechanismsSupposeuserreferencespagewithinvalidPTE?MemoryManagementUnit(MMU)trapstoOSResultingtrapisa“PageFault”WhatdoesOSdoonaPageFault?:ChooseanoldpagetoreplaceIfoldpagemodified(“D=1”),writecontentsbacktodiskChangeitsPTEandanycachedTLBtobeinvalidLoadnewpageintomemoryfromdiskUpdatepagetableentry,invalidateTLBfornewentryContinuethreadfromoriginalfaultinglocationTLBfornewpagewillbeloadedwhenthreadcontinued!Whilepullingpagesoffdiskforoneprocess,OSrunsanotherprocessfromreadyqueueSuspendedprocesssitsonwaitqueueCacheReview:DemandPagingMechanismsFinishDemandPaging:TrashingandWorkingSetsDualModeOperation:KernelversusUserModeI/OSystemsHardwareAccessDeviceDriversDiskPerformanceHardwareperformanceparametersNote:Someslidesand/orpicturesinthefollowingareadaptedfromslides©2005Silberschatz,Galvin,andGagne.ManyslidesgeneratedfrommylecturenotesbyKubiatowicz.GoalsforTodayThrashingIfaprocessdoesnothave“enough”pages,thefaultrateisveryhigh.Thisleadsto:lowCPUutilizationoperatingsystemspendsmostofitstimeswappingtodiskThrashingaprocessisbusyswappingpagesinandoutQuestions:HowdowedetectThrashing?WhatisbestresponsetoThrashing?ProgramMemoryAccessPatternshavetemporalandspatiallocalityGroupofPagesaccessedalongagiventimeslicecalledthe“WorkingSet”WorkingSetdefinesminimumnumberofpagesneededforprocesstobehavewellNotenoughmemoryforWorkingSetThrashingBettertoswapoutprocess?LocalityInAMemory-ReferencePatternWorking-SetModelworking-setwindowfixednumberofpagereferencesExample:10,000instructionsWSi(workingsetofProcessPi)=totalsetofpagesreferencedinthemostrecent(variesintime)iftoosmallwillnotencompassentirelocalityiftoolargewillencompassseverallocalitiesif=willencompassentireprogramD=|WSi|totaldemandframesifD>physical

memoryThrashingPolicy:ifD>physicalmemory,thensuspend/swapoutprocessesThiscanimproveoverallsystembehaviorbyalot!WhataboutCompulsoryMisses?Recallthatcompulsorymissesaremissesthatoccurthefirsttimethatapageisseen PagesthataretouchedforthefirsttimePagesthataretouchedafterprocessisswappedout/swappedbackinClustering:Onafault,bringinmultiplepages“around”thefaultingpageSinceefficiencyofdiskreadsincreaseswithsequentialreads,makessensetoreadseveralsequentialpagesTradeoff:Prefetchingmayevictotherin-usepagesfornever-usedprefetchedpagesWorkingSetTracking:UsealgorithmtotrytotrackworkingsetofapplicationWhenswappingprocessbackin,swapinworkingsetReview:ExampleofGeneralAddressTranslationProg1VirtualAddressSpace1Prog2VirtualAddressSpace2CodeDataHeapStackCodeDataHeapStackData2Stack1Heap1OSheap&StacksCode1Stack2Data1Heap2Code2OScodeOSdataTranslationMap1TranslationMap2PhysicalAddressSpaceDual-ModeOperationCananapplicationmodifyitsowntranslationmapsorPTEbits?Ifitcould,couldgetaccesstoallofphysicalmemoryHastoberestrictedsomehowToassistwithprotection,hardwareprovidesatleasttwomodes(Dual-ModeOperation):“Kernel”mode(or“supervisor”or“protected”)“User”mode(Normalprogrammode)Modesetwithbitsinspecialcontrolregisteronlyaccessibleinkernel-modeIntelprocessorsactuallyhavefour“rings”ofprotection:PL(PrivilegeLevel)from0–3PL0hasfullaccess,PL3hasleastTypicalOSkernelsonIntelprocessorsonlyusePL0(“kernel”)andPL3(“user”)ForProtection,LockUser-ProgramsinAsylumIdea:Lockuserprogramsinpaddedcell

withnoexitorsharpobjectsCannotchangemodetokernelmodeCannotmodifytranslationmapsLimitedaccesstomemory:cannot

adverselyeffectotherprocessesWhatelseneedstobeprotected?AcoupleofissuesHowtoshareCPUbetweenkernelanduserprograms?Howdoesoneswitchbetweenkernelandusermodes?OSuser(kernelusermode):gettingintocellUserOS(userkernelmode):gettingoutofcellHowtogetfromKernelUserWhatdoesthekerneldotocreateanewuserprocess?AllocateandinitializeprocesscontrolblockReadprogramoffdiskandstoreinmemoryAllocateandinitializetranslationmapPointatcodeinmemorysoprogramcanexecutePossiblypointatstaticallyinitializeddataRunProgram:SetmachineregistersSethardwarepointertotranslationtableSetprocessorstatuswordforusermodeJumptostartofprogramHowdoeskernelswitchbetweenprocesses(welearnedaboutthis!)?Samesaving/restoringofregistersasbeforeSave/restorehardwarepointertotranslationmapUserKernel(SystemCall)Can’tletinmate(user)getoutofpaddedcellonownWoulddefeatpurposeofprotection!So,howdoestheuserprogramgetbackintokernel?Systemcall:VoluntaryprocedurecallintokernelHardwareforcontrolledUserKerneltransitionCananykernelroutinebecalled?No!OnlyspecificonesSystemcallIDencodedintosystemcallinstructionIndexforceswell-definedinterfacewithkernelI/O:open,close,read,write,lseekFiles:delete,mkdir,rmdir,chownProcess:fork,exit,joinNetwork:socketcreate,selectSystemCall(cont’d)Aresystemcallsthesameacrossoperatingsystems?Notentirely,buttherearelotsofcommonalitiesAlsosomestandardizationattempts(POSIX)Whathappensatbeginningofsystemcall?Onentrytokernel,setssystemtokernelmodeHandleraddressfetchedfromtable,andHandlerstartedSystemCallargumentpassing:Inregisters(notverymuchcanbepassed)Writeintousermemory,kernelcopiesintokernelmemoryEveryargumentmustbeexplicitlychecked!UserKernel(Exceptions:TrapsandInterrupts)Systemcallinstr.causesasynchronousexception(or“trap”)Infact,oftencalledasoftware“trap”instructionOthersourcesofSynchronousExceptions:Dividebyzero,Illegalinstruction,Buserror(badaddress,e.g.unalignedaccess)SegmentationFault(addressoutofrange)PageFaultInterruptsareAsynchronousExceptionsExamples:timer,diskready,network,etc….Interruptscanbedisabled,trapscannot!SUMMARY–Onsystemcall,exception,orinterrupt:HardwareenterskernelmodewithinterruptsdisabledSavesPC,thenjumpstoappropriatehandlerinkernelForsomeprocessors(x86),processoralsosavesregisters,changesstack,etc.ModernI/OSystemsWhatistheRoleofI/O?WithoutI/O,computersareuseless(disembodiedbrains?)But…thousandsofdevices,eachslightlydifferentHowcanwestandardizetheinterfacestothesedevices?Devicesunreliable:mediafailuresandtransmissionerrorsHowcanwemakethemreliable???Devicesunpredictableand/orslowHowcanwemanagethemifwedon’tknowwhattheywilldoorhowtheywillperform?AdministriviaProject2DesignDocdueThursday10/17at11:59PMMidtermexamTBAin2roomsClosedbook,nocalculatorsCoverslectures/readings#1-13(Wednesday)andprojectoneOnedouble-sidedhandwrittenpageofnotesallowedReviewsession:TBAPleasefilltheanonymouscoursesurveyatXXXXXXWe’lltrytomakechangesthissemesterbasedonyourfeedback5minBreakOperationalParametersforI/ODatagranularity:Bytevs.BlockSomedevicesprovidesinglebyteatatime(e.g.,keyboard)Othersprovidewholeblocks(e.g.,disks,networks,etc.)Accesspattern:Sequentialvs.RandomSomedevicesmustbeaccessedsequentially(e.g.,tape)Otherscanbeaccessedrandomly(e.g.,disk,cd,etc.)Transfermechanism:Pollingvs.InterruptsSomedevicesrequirecontinualmonitoringOthersgenerateinterruptswhentheyneedserviceExampleDevice-TransferRates(SunEnterprise6000)DeviceRatesvaryovermanyordersofmagnitudeSystembetterbeabletohandlethiswiderangeBetternothavehighoverhead/byteforfastdevices!BetternotwastetimewaitingforslowdevicesTheGoaloftheI/OSubsystemProvideuniforminterfaces,despitewiderangeofdifferentdevicesThiscodeworksonmanydifferentdevices:

FILEfd=fopen(“/dev/something”,“rw”);

for(inti=0;i<10;i++){

fprintf(fd,“Count%d\n”,i);

}

close(fd);Why?Becausecodethatcontrolsdevices(“devicedriver”)implementsstandardinterfaceWewilltrytogetaflavorforwhatisinvolvedinactuallycontrollingdevicesinrestoflectureCanonlyscratchsurface!

WantStandardInterfacestoDevicesBlockDevices:

e.g.,

diskdrives,tapedrives,DVD-ROMAccessblocksofdataCommandsincludeopen(),read(),write(),seek()RawI/Oorfile-systemaccessMemory-mappedfileaccesspossibleCharacter/ByteDevices:

e.g.,

keyboards,mice,serialports,someUSBdevicesSinglecharactersatatimeCommandsincludeget(),put()LibrarieslayeredontopallowlineeditingNetworkDevices:e.g.,

Ethernet,Wireless,BluetoothDifferentenoughfromblock/charactertohaveowninterfaceUnixandWindowsincludesocketinterfaceSeparatesnetworkprotocolfromnetworkoperationIncludesselect()

functionalityHowDoesUserDealwithTiming?BlockingInterface:“Wait”Whenrequestdata(e.g.,

read()

systemcall),putprocesstosleepuntildataisreadyWhenwritedata(e.g.,

write()

systemcall),putprocesstosleepuntildeviceisreadyfordataNon-blockingInterface:“Don’tWait”ReturnsquicklyfromreadorwriterequestwithcountofbytessuccessfullytransferredtokernelReadmayreturnnothing,writemaywritenothingAsynchronousInterface:“TellMeLater”Whenrequestingdata,takepointertouser’sbuffer,returnimmediately;laterkernelfillsbufferandnotifiesuserWhensendingdata,takepointertouser’sbuffer,returnimmediately;laterkerneltakesdataandnotifiesuserDeviceControllerreadwritecontrolstatusAddressableMemoryand/orQueuesRegisters(port0x20)HardwareControllerMemoryMappedRegion:0x8f008020BusInterfaceHowDoestheProcessorTalktoDevices?CPUinteractswithaControllerContainsasetofregistersthat

canbereadandwrittenMaycontainmemoryforrequest

queuesorbit-mappedimagesRegardlessofthecomplexityoftheconnectionsandbuses,processoraccessesregistersintwoways:I/Oinstructions:in/outinstructions(e.g.,Intel’s0x21,AL)MemorymappedI/O:load/storeinstructionsRegisters/memoryappearinphysicaladdressspaceI/OaccomplishedwithloadandstoreinstructionsAddress+DataInterruptRequestProcessorMemoryBusCPURegularMemoryOtherDevicesorBusesInterruptControllerBusAdaptorBusAdaptorExample:Memory-MappedDisplayControllerMemory-Mapped:HardwaremapscontrolregistersanddisplaymemoryintophysicaladdressspaceAddressessetbyhardwarejumpersorprogrammingatboottimeSimplywritingtodisplaymemory(alsocalledthe“framebuffer”)changesimageonscreenAddr:0x8000F000—0x8000FFFFWritinggraphicsdescriptiontocommand-queueareaSayenterasetoftrianglesthatdescribesomesceneAddr:0x80010000—0x8001FFFFWritingtothecommandregistermaycauseon-boardgraphicshardwaretodosomethingSayrendertheabovesceneAddr:0x0007F004CanprotectwithaddresstranslationDisplayMemory0x8000F0000x80010000PhysicalAddressSpaceStatus0x0007F000Command0x0007F004GraphicsCommandQueue0x80020000TransferringDataTo/FromControllerProgrammedI/O:Eachbytetransferredviaprocessorin/outorload/storePro:Simplehardware,easytoprogramCon:ConsumesprocessorcyclesproportionaltodatasizeDirectMemoryAccess:GivecontrolleraccesstomemorybusAskittotransferdatato/frommemorydirectlySampleinteractionwithDMAcontroller(frombook):I/ODeviceNotifyingtheOSTheOSneedstoknowwhen:TheI/OdevicehascompletedanoperationTheI/OoperationhasencounteredanerrorI/OInterrupt:DevicegeneratesaninterruptwheneveritneedsservicePro:handlesunpredictableeventswellCon:interruptsrelativelyhighoverheadPolling:OSperiodicallychecksadevice-specificstatusregisterI/OdeviceputscompletioninformationinstatusregisterPro:lowoverheadCon:maywastemanycyclesonpollingifinfrequentorunpredictableI/OoperationsActualdevicescombinebothpollingandinterruptsForinstance–High-bandwidthnetworkadapter:InterruptforfirstincomingpacketPollforfollowingpacketsuntilhardwarequeuesareemptyI/OPerformanceResponseTime=Queue+I/OdeviceservicetimeUserThreadQueue[OSPaths]ControllerI/OdevicePerformanceofI/OsubsystemMetrics:ResponseTime,ThroughputContributingfactorstolatency:Softwarepaths(canbelooselymodeledbyaqueue)HardwarecontrollerI/OdeviceservicetimeQueuingbehavior:Canleadtobigincreasesoflatencyasutilizationapproaches100%100%ResponseTime(ms)Throughput(Utilization)(%totalBW)01002003000%Q1:True_False_Withanasynchronousinterface,thewritermayneedtoblockuntilthedatais

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论