Title | Operating systems lecture notes stanford cs140 |
---|---|
Course | Information Technology |
Institution | Walter Sisulu University |
Pages | 97 |
File Size | 1.6 MB |
File Type | |
Total Downloads | 61 |
Total Views | 151 |
hgx,jhc.ycvh jvu.uoh/ijipj...
OperatingSystemsLectureNotes (StanfordCS140) From:CS140:OperatingSystems(Spring2014)
Introduction LectureNotesforCS140 Spring2014 JohnOusterhout Evolutionofoperatingsystems,phase1: Hardwareexpensive,humanscheap Oneuseratatime,workingdirectlyatconsole First"operatingsystem":I/Osubroutinelibrariessharedbyusers Simplebatchmonitor:getuserawayfromthecomputer.OS= programtoloadandrunuserjobs,takedumps. Datachannels,interrupts,overlapofI/Oandcomputation. Memoryprotectionandrelocationenablemultitasking:several userssharethesystem OSmustmanageinteractions,concurrency Bymid-1960'soperatingsystemshadbecomelarge,complicated. OSfieldemergesasimportantdisciplinewithprinciples Evolutionofoperatingsystems,phase2: Hardwarecheap,humansexpensive Interactivetimesharing Fancyfilesystems Issuesofresponsetime,thrashing Personalcomputers:computersarecheap,soputoneineach terminal. Networking:allowsharingandcommunicationbetweenmachines. Embeddeddevices:putcomputersincellphones,stereoplayers,
TVs,lightswitches Areallthefancyfeaturesdevelopedfortimesharingstillneeded? ThefutureofOSes: Verysmall(devices) Verylarge(datacenters,cloud) CharacteristicsofcurrentOSes: Enormous:millionsoflinesofcode,100-1000engineer-years Complex:asynchronous,hardwareidiosyncrasies,performanceis crucial. Poorlyunderstood Mostofanoperatingsystem'sfunctionsfallinthecategoryof coordination:allowingseveralthingstoworktogetherefficientlyand fairly: Concurrency:allowseveraldifferenttaskstobeunderwayatthe sametime,asifeachhadaprivatemachine.Tokeeptrackof everything,processesandthreadswereinvented. I/Odevices.Don'twantCPUtositidlewhileanI/Odeviceis working. Memory:howcanasinglememorybesharedamongseveral processes? Files:allowmanyfiles,formanydifferentusers,tosharespaceon thesamephysicaldisk. Networks:allowgroupsofcomputerstoworktogether. Security:howtoallowinteractionswhileprotectingeach participantfromabusebytheothers?
Threads,Processes,andDispatching LectureNotesforCS140 Spring2014 JohnOusterhout ReadingsforthistopicfromOperatingSystems:Principlesand Practice:Chapter4.
ThreadsandProcesses Thread:asequentialexecutionstream Executesaseriesofinstructionsinorder(onlyonethinghappens atatime). Process:oneormorethreads,alongwiththeirexecutionstate. Executionstate:everythingthatcanaffect,orbeaffectedby,a thread: Code,data,registers,callstack,openfiles,network connections,timeofday,etc. Partoftheprocessstateisprivatetoathread Partissharedamongallthreadsintheprocess Evolutionofoperatingsystemprocessmodel: Earlyoperatingsystemssupportedasingleprocesswithasingle threadatatime(singletasking).Theyranbatchjobs(oneuserat atime). Someearlypersonalcomputeroperatingsystemsusedsingletasking(e.g.MS-DOS),butthesesystemsarealmostunheardof today. Bylate1970'smostoperatingsystemsweremultitaskingsystems:
theysupportedmultipleprocesses,buteachprocesshadonlya singlethread. Inthe1990'smostsystemsconvertedtomultithreading:multiple threadswithineachprocess. Isaprocessthesameasaprogram?
Dispatching Almostallcomputerstodaycanexecutemultiplethreads simultaneously: Eachprocessorchiptypicallycontainsmultiplecores EachcorecontainsacompleteCPUcapableofexecutingthreads Manymodernprocessorssupporthyperthreading:eachphysical corebehavesasifitisactuallytwocores,soitcanruntwo threadssimultaneously(e.g.executeonethreadwhiletheotheris waitingonacachemiss). Forexample,aservermightcontain2IntelXeonE5-2670 processors,eachwith8coresthatsupports2-wayhyperthreading. Overall,thiscomputercanrun32threadssimultaneously. Mayhavemorethreadsthancores Atanygiventime,mostthreadsdonotneedtoexecute(theyare waitingforsomething). OSusesaprocesscontrolblocktokeeptrackofeachprocess: Executionstateforeachthread(savedregisters,etc.) Schedulinginformation Informationaboutmemoryusedbythisprocess Informationaboutopenfiles Accountingandothermiscellaneousinformation
Atanygiventimeathreadisinoneof3states: Running Blocked:waitingforanevent(diskI/O,incomingnetworkpacket, etc.) Ready:waitingforCPUtime Dispatcher:innermostportionoftheOSthatrunsoneachcore: Runathreadforawhile Saveitsstate Loadstateofanotherthread Runit... Contextswitch:changingthethreadcurrentlyrunningonacoreby firstsavingthestateoftheoldprocess,thenloadingthestateofthe newthread. Note:thedispatcherisnotitselfathread! Corecanonlydoonethingatatime.Ifathreadisexecuting, dispatcherisn't:OShaslostcontrol.HowdoesOSregaincontrolof core? Traps(eventsoccurringincurrentthreadthatcauseachangeof controlintotheoperatingsystem): Systemcall. Error(illegalinstruction,addressingviolation,etc.). Pagefault. Interrupts(eventsoccurringoutsidethecurrentthreadthatcausea stateswitchintotheoperatingsystem): Charactertypedatkeyboard. Completionofdiskoperation. Timer:tomakesureOSeventuallygetscontrol. Howdoesdispatcherdecidewhichthreadtorunnext?
Plan0:searchprocesstablefromfront,runfirstreadythread. Plan1:linktogetherthereadythreadsintoaqueue.Dispatcher grabsfirstthreadfromthequeue.Whenthreadsbecomeready, insertatbackofqueue. Plan2:giveeachthreadapriority,organizethequeueaccording topriority.Or,perhapshavemultiplequeues,oneforeachpriority class.
ProcessCreation Howtheoperatingsystemcreatesaprocess: Loadcodeanddataintomemory. Createandinitializeprocesscontrolblock. Createfirstthreadwithcallstack. Provideinitialvaluesfor"savedstate"forthethread Makethreadknowntodispatcher;dispatcher"resumes"tostartof newprogram. SystemcallsforprocesscreationinUNIX: forkmakescopyofcurrentprocess,withonethread. execreplacesmemorywithcodeanddatafromagiven executablefile.Doesn'treturn("returns"tostartingpointofnew program). waitpidwaitsforagivenprocesstoexit. Example: intpid=fork(); if(pid==0){ /*Childprocess*/ exec("foo"); }else{ /*Parentprocess*/
waitpid(pid,&status,options); } Advantage:canmodifyprocessstatebeforecallingexec(e.g. changeenvironment,openfiles). Disadvantage:wastedwork(mostofforkedstategetsthrown away). SystemcallsforprocesscreationinWindows: CreateProcesscombinesforkandexec BOOLCreateProcess( LPCTSTRlpApplicationName, LPTSTRlpCommandLine, LPSECURITY_ATTRIBUTESlpProcessAttributes, LPSECURITY_ATTRIBUTESlpThreadAttributes, BOOLbInheritHandles, DWORDdwCreationFlags, PVOIDlpEnvironment, LPCTSTRlpCurrentDirectory, LPSTARTUPINFOlpStartupInfo, LPPROCESS_INFORMATIONlpProcessInformation ); Mustpassargumentsforanystatechangesbetweenparentand child. ProcesscreationinPintos:execcombinesUNIXforkandexec.
Concurrency LectureNotesforCS140 Spring2014 JohnOusterhout ReadingsforthistopicfromOperatingSystems:Principlesand Practice:Chapter5upthroughSection5.1.
IndependentandCooperatingThreads Independentthread:onethatcan'taffectorbeaffectedbytherestof theuniverse. Itsstateisn'tsharedinanywaybyanyotherthread. Deterministic:inputstatealonedeterminesresults. Reproducible. Canstopandcontinuewithnobadeffects(onlytimevaries). Therearemanydifferentwaysinwhichacollectionofindependent threadsmightbeexecutedonacomputer: Single-tasking:eachthreadrunstocompletionbeforethenextone starts. Multitaskingwithonecorethatissharedamongseveralthreads. Doestheorderofdispatchingaffectthebehavior? Multitaskingwithseveralcores(multiprocessing):runthreadsin parallelonseparatecores. Agiventhreadrunsononlyonecoreatatime. Athreadmayrunondifferentcoreatdifferenttimes(move state,assumeprocessorsareidentical). Fromthestandpointofathread,can'ttellthedifference
betweenonecoreandmanycores. Cooperatingthreads:thosethatsharestate. Behaviorisnondeterministic:dependsonrelativeexecution sequenceandcannotbepredictedinadvance. Behaviormaybeirreproducible. Example:onethreadwrites"ABC"toaconsolewindow,another writes"CBA"concurrently. Whypermitthreadstocooperate? Basicassumptionforcooperatingthreadsisthattheorderofsome operationsisirrelevant;certainoperationsareindependentofcertain otheroperations.Examples: Thread1:A=1; Thread2:B=2; Thread1:A=B+1; Thread2:B=2*B;
AtomicOperations BeforewecansayANYTHINGaboutcooperatingthreads,wemust knowthatsomeoperationisatomic:iteitherhappensinitsentirety withoutinterruption,ornotatall.Cannotbeinterruptedinthemiddle. Referencesandassignmentsareatomicinalmostallsystems. A=BwillalwaysreadacleanvalueforBandsetacleanvaluefor A(butnotnecessarilytrueforarraysorrecords). Inuniprocessorsystems,anythingbetweeninterruptsisatomic. Ifyoudon'thaveanatomicoperation,youcan'tmakeone. Fortunately,hardwaredesignersgiveusatomicops. Ifyouhaveanyatomicoperation,youcanuseittogenerate
higher-levelconstructsandmakeparallelprogramsworkcorrectly. Thisistheapproachwe'lltakeinthisclass.
The"TooMuchMilk"Problem Thebasicproblem: PersonAPersonB 3:00Lookinfridge:nomilk 3:05Leaveforstore 3:10ArriveatstoreLookinf 3:15LeavestoreLeavehom 3:20Arrivehome,putmilkawayArriveat 3:25Leavesto 3:30Arriveho Whatisthecorrectbehavior? Moredefinitions: Synchronization:usingatomicoperationstoensurecorrect operationofcooperatingthreads. Criticalsection:asectionofcode,orcollectionofoperations,in whichonlyonethreadmaybeexecutingatagiventime.E.g. shopping. Mutualexclusion:mechanismsusedtocreatecriticalsections. Typically,mutualexclusionachievedwithalockingmechanism: preventothersfromdoingsomething.Forexample,beforeshopping, leaveanoteontherefrigerator:don'tshopifthereisanote. Firstattemptatcomputerizedmilkbuying(assumeatomicreadsand writes): 1if(milk==0){ 2if(note==0){
3note=1; 4buy_milk(); 5note=0; 6} 7} Secondattempt:changemeaningofnote.Abuysifnonote,Bbuysif thereisanote. ThreadA 1if(note==0){ 2if(milk==0){ 3buy_milk(); 4} 5note=1; 6} ThreadB 1if(note==1){ 2if(milk==0){ 3buy_milk(); 4} 5note=0; 6} Thirdattempt:useseparatenotesforAandB. ThreadA 1noteA=1; 2if(noteB==0){ 3if(milk==0){ 4buy_milk(); 5} 6} 7noteA=0;
ThreadB 1noteB=1; 2if(noteA==0){ 3if(milk==0){ 4buy_milk(); 5} 6} 7noteB=0; Fourthattempt:justneedawaytodecidewhowillbuymilkwhenboth leavenotes(somebodyhastohangaroundtomakesurethatthejob getsdone): ThreadB 1noteB=1; 2while(noteA==1){ 3//donothing; 4} 5if(milk==0){ 6 buy_milk(); 7} 8noteB=0; Thissolutionworksbuthastwodisadvantages: Asymmetric(andcomplex)code. WhileBiswaitingitisconsumingresources(busy-waiting). Forasymmetricsolutionwithoutbusy-waiting,seePeterson's Algorithm.
DemandPaging LectureNotesforCS140 Spring2014 JohnOusterhout ReadingsforthistopicfromOperatingSystems:Principlesand Practice:Chapter9. Demandpaging:notallofaprocess'svirtualaddressspaceneedsto beloadedinmainmemoryatanygiventime.Eachpagecanbe either: Inmemory(physicalpageframe) Ondisk(backingstore)
PageFaults Whathappenswhenaprocessreferencesapagethatisinthe backingstore? Forpagesinthebackingstore,thepresentbitisclearedinthe pagetableentries. Ifpresentisnotset,thenareferencetothepagecausesatrapto theoperatingsystem. Thesetrapsarecalledpagefaults. Tohandleapagefault,theoperatingsystem Findsafreepageframeinmemory Readsthepageinfrombackingstoretothepageframe Updatesthepagetableentry,settingpresent Resumesexecutionofthethread HowdoestheOSfigureoutwhichpagegeneratedthefault?
x86:hardwaresavesthevirtualaddressthatcausedthefault (CR2register) OnearliermachinesOSgotonlyaddressoffaultinginstruction, mustsimulatetheinstructionandtryeveryaddresstofindtheone thatgeneratedthefault Restartingprocessexecutionafterapagefaultistricky,sincethefault mayhaveoccurredinthemiddleofaninstruction. Ifinstructionsareidempotent,justrestartthefaultinginstruction (hardwaresavesinstructionaddressduringpagefault). Non-idempotentinstructionsaremoredifficulttorestart: MOV+(SP),R2 Withouthardwaresupportitmaybeimpossibletoresumea processsafelyafterapagefault.Hardwaremustkeeptrackof sideeffects: Undoallsideeffectsduringapagefault? Saveinfoaboutsideeffects,useittorestartinstruction"inthe middle"
PageFetching Oncethebasicpagefaultmechanismisworking,theOShastwo schedulingdecisionstomake: Pagefetching:whentobringpagesintomemory. Pagereplacement:whichpagestothrowoutofmemory. Overallgoal:makephysicalmemorylooklargerthanitis. Locality:mostprogramsspendmostoftheirtimeusingasmall fractionoftheircodeanddata. Keepinmemorytheinformationthatisbeingused.
Keepunusedinformationondiskinpagingfile(alsocalledbacking store,orswapspace) Ideally:pagingproducesamemorysystemwiththeperformance ofmainmemoryandthecost/capacityofdisk! MostmodernOSesusedemandfetching: Startprocesswithnopagesloaded,don'tloadapageinto memoryuntilitisreferenced. Thepagesforaprocessdivideintothreegroups: Read-onlycodepages:readfromtheexecutablefilewhen needed. Initializeddatapages:onfirstaccess,readfromexecutable file.Onceloaded,savetothepagingfilesincecontentsmay havechanged. Uninitializeddatapages:onfirstaccess,justclearmemoryto allzeros.Whenpagingout,savetothepagingfile. Prefetching:trytopredictwhenpageswillbeneededandloadthem aheadoftimetoavoidpagefaults. Requirespredictingthefuture,sohardtodo. Oneapproach:whentakingapagefault,readmanypagesinstead ofjustone(winsifprogramaccessesmemorysequentially).
PageReplacement Onceallofmemoryisinuse,willneedtothrowoutonepageeach timethereisapagefault. Random:pickanypageatrandom(workssurprisinglywell!) FIFO:throwoutthepagethathasbeeninmemorylongest. MIN:Theoptimalalgorithmrequiresustopredictthefuture. LeastRecentlyUsed(LRU):usethepasttopredictthefuture.
ImplementingLRU:needhardwaresupporttokeeptrackofwhich pageshavebeenusedrecently. PerfectLRU? Keepahardwareregisterforeachpage,storesystemclock intothatregisteroneachmemoryreference. Tochoosepageforplacement,scanthroughallpagestofind theonewiththeoldestclock. Hardwarecostsprohibitiveintheearlydaysofpaging;also, expensivetoscanallpagesduringreplacement. Nomachineshaveactuallyimplementedthis. Currentcomputerssettleforanapproximationthatisefficient.Just findanoldpage,notnecessarilytheoldest. Clockalgorithm(alsocalledsecondchancealgorithm):keep referencebitforeachpageframe,hardwaresetsthereferencebit wheneverapageisreadorwritten.Tochoosepageforplacement: Cyclethroughpagesinorder(circularly). Ifthenextpagehasbeenreferenced,thendon'treplaceit;just clearthereferencebitandcontinuetothenextpage. Ifthepagehasnotbeenreferencedsincethelasttimewe checkedit,thenreplacethatpage. Dirtybit:onebitforeachpageframe,setbyhardwarewheneverthe pageismodified.Ifadirtypageisreplaced,itmustbewrittentodisk beforeitspageframeisreused. Theclockalgorithmtypicallygivesadditionalpreferencetodirty pages.Forexample,ifthereferencebitforapageisclear,butthe dirtybitisset,don'treplacethispagenow,butclearthedirtybitand startwritingthepagetodisk. Freepagepool:manysystemskeepasmalllistofcleanpagesthat
areavailableimmediatelyforreplacement. Duringreplacement,takethepagethathasbeeninthefreepool thelongest,thenrunthereplacementalgorithmtoaddanewpage tothefreepool. Pagesinthefreepoolhavetheirpresentbitoff,soanyreferences tothosepagescauseapagefault Ifapagefaultoccursforapageinthefreepool,removeitfrom thefreepoolandputitbackinservice;muchfasterthanreading fromdisk. Providesanextraopportunityforrecoveryifwemakeapoorpage replacementdecision. Howtoimplementpagereplacementwhentherearemultiple processesrunninginthesystem? Globalreplacement:allpagesfromallprocessesarelumpedinto asinglereplacementpool.Eachprocesscompeteswithallthe otherprocessesforpageframes. Per-processreplacement:eachprocesshasaseparatepoolof pages.Apagefaultinoneprocesscanonlyreplaceoneofthat process'sframes.Thiseliminatesinterferencefromother processes. Unfortunately,per-processreplacementcreatesanewscheduling dilemma:howmanypageframestoallocatetoeachprocess?If thisdecisionismadeincorrectly,itcanresultininefficientmemory usage. Mostsystemsuseglobalreplacement.
ThrashingandWorkingSets LectureNotesforCS140 Spring2014 JohnOusterhout ReadingsforthistopicfromOperatingSystems:Principlesand Practice:Section9.7. Normally,ifathreadtakesapagefaultandmustwaitforthepageto bereadfromdisk,theoperatingsystemrunsadifferentthreadwhile theI/Oisoccurring.Thuspagefaultsare"free"? Whathappensifmemorygetsovercommitted? Supposethepagesbeingactivelyusedbythecurrentthreads don'tallfitinphysicalmemory. Eachpagefaultcausesoneoftheactivepagestobemovedto disk,soanotherpagefaultwilloccursoon. Thesystemwillspendallitstimereadingandwritingpages,and won'tgetmuchworkdone. Thissituationiscalledthrashing;itwasaseriousprobleminearly demandpagingsystems. Howtodealwiththrashing? Ifasingleprocessistoolargeformemory,thereisnothingtheOS cando.Thatprocesswillsimplythrash. Iftheproblemarisesbecauseofthesumofseveralprocesses: Figureouthowmuchmemoryeachprocessneedstoprevent thrashing.Thisiscalleditsworkingset. Onlyallowafewprocessestoexecuteatatime,suchthattheir
workingsetsfitinmemory. Pagefaultfrequency:onetechniqueforcomputingworkingsets Atanygiventime,eachprocessisallocatedafixednumberof physicalpageframes(assumesper-processreplacement). Monitortherateatwhichpagefaultsareoccurringforeach process. Iftherategetstoohighforaprocess,assumethatitsmemoryis overcommitted;increasethesizeofitsmemorypool. Iftherategetstoolowforaprocess,assumethatitsmemorypool canbereducedinsize. Schedulingwithworkingsets Ifthesumofallworkingsetsofallprocessesexceedsthesizeof memory,thenstoprunningsomeoftheprocessesforawhile. Divideprocessesintotwogroups:activeandinactive: Whenaprocessisactiveitsentireworkingsetmustalwaysbe inmemory:neverexecuteathreadwhoseworkingsetisnot resident. Whenaprocessbecomesinactive,itsworkingsetcanmigrate todisk. Threadsfrom...