Visit to download the full and correct content document: https://textbookfull.com/product/operating-systems-three-easy-pieces-remzi-h-arpacidusseau/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Survey of Operating Systems Jane Holcombe
https://textbookfull.com/product/survey-of-operating-systemsjane-holcombe/

Guide to Operating Systems Greg Tomsho
https://textbookfull.com/product/guide-to-operating-systems-gregtomsho/

Survey of Operating Systems Jane Holcombe
https://textbookfull.com/product/survey-of-operating-systemsjane-holcombe-2/

Modern Operating Systems, 5th Global Edition Andrew Tanenbaum
https://textbookfull.com/product/modern-operating-systems-5thglobal-edition-andrew-tanenbaum/

Easy Renaissance Pieces for Classical Guitar: With a CD of Performances Book/CD Jerry Willard (Editor)
https://textbookfull.com/product/easy-renaissance-pieces-forclassical-guitar-with-a-cd-of-performances-book-cd-jerry-willardeditor/

How to read Nancy The elements of comics in three easy panels Karasik
https://textbookfull.com/product/how-to-read-nancy-the-elementsof-comics-in-three-easy-panels-karasik/

Missing Pieces Tim Weaver
https://textbookfull.com/product/missing-pieces-tim-weaver/

Operating Systems Foundations with Linux on the Raspberry Pi Wim Vanderbauwhede
https://textbookfull.com/product/operating-systems-foundationswith-linux-on-the-raspberry-pi-wim-vanderbauwhede/

Embedded Systems VOL. 3: Real-Time Operating Systems for ARM Cortex-M Microcontrollers Jonathan Valvano
https://textbookfull.com/product/embedded-systems-vol-3-realtime-operating-systems-for-arm-cortex-m-microcontrollersjonathan-valvano/
Preface
ToEveryone
Welcometothisbook!Wehopeyou’llenjoyreadingitasmuchasweenjoyed writingit.Thebookiscalled OperatingSystems:ThreeEasyPieces (available at http://www.ostep.org),andthetitleisobviouslyanhomagetooneofthe greatestsetsoflecturenotesevercreated,byoneRichardFeynmanonthetopicof Physics[F96].Whilethisbookwillundoubtedlyfallshortofthehighstandardset bythatfamousphysicist,perhapsitwillbegoodenoughforyouinyourquestto understandwhatoperatingsystems(andmoregenerally,systems)areallabout.
Thethreeeasypiecesrefertothethreemajorthematicelements thebookis organizedaround: virtualization, concurrency,and persistence.Indiscussing theseconcepts,we’llendupdiscussingmostoftheimportantthingsanoperating systemdoes;hopefully,you’llalsohavesomefunalongtheway.Learningnew thingsisfun,right?Atleast,itshouldbe.
Eachmajorconceptisdividedintoasetofchapters,mostofwhichpresenta particularproblemandthenshowhowtosolveit.Thechapters areshort,andtry (asbestaspossible)toreferencethesourcematerialwheretheideasreallycame from.Oneofourgoalsinwritingthisbookistomakethepathsofhistoryasclear aspossible,aswethinkthathelpsastudentunderstandwhatis,whatwas,and whatwillbemoreclearly.Inthiscase,seeinghowthesausagewasmadeisnearly asimportantasunderstandingwhatthesausageisgoodfor1
Thereareacoupledevicesweusethroughoutthebookwhichareprobably worthintroducinghere.Thefirstisthe crux oftheproblem.Anytimeweare tryingtosolveaproblem,wefirsttrytostatewhatthemostimportantissueis; sucha cruxoftheproblem isexplicitlycalledoutinthetext,andhopefullysolved viathetechniques,algorithms,andideaspresentedintherestofthetext.
Inmanyplaces,we’llexplainhowasystemworksbyshowingitsbehavior overtime.These timelines areattheessenceofunderstanding;ifyouknowwhat happens,forexample,whenaprocesspagefaults,youareonyourwaytotruly understandinghowvirtualmemoryoperates.Ifyoucomprehendwhattakesplace whenajournalingfilesystemwritesablocktodisk,youhavetakenthefirststeps towardsmasteryofstoragesystems.
Therearealsonumerous asides and tips throughoutthetext,addingalittle colortothemainlinepresentation.Asidestendtodiscusssomethingrelevant(but perhapsnotessential)tothemaintext;tipstendtobegeneral lessonsthatcanbe
1 Hint:eating!Orifyou’reavegetarian,runningawayfrom.
appliedtosystemsyoubuild.Anindexattheendofthebooklists allofthesetips andasides(aswellascruces,theoddpluralofcrux)foryourconvenience.
Weuseoneoftheoldestdidacticmethods,the dialogue,throughoutthebook, asawayofpresentingsomeofthematerialinadifferentlight. Theseareusedto introducethemajorthematicconcepts(inapeachyway,aswewillsee),aswellas toreviewmaterialeverynowandthen.Theyarealsoachanceto writeinamore humorousstyle.Whetheryoufindthemuseful,orhumorous,well,that’sanother matterentirely.
Atthebeginningofeachmajorsection,we’llfirstpresentan abstraction thatan operatingsystemprovides,andthenworkinsubsequentchaptersonthemechanisms,policies,andothersupportneededtoprovidetheabstraction.Abstractions arefundamentaltoallaspectsofComputerScience,soitisperhapsnosurprise thattheyarealsoessentialinoperatingsystems.
Throughoutthechapters,wetrytouse realcode (not pseudocode)wherepossible,soforvirtuallyallexamples,youshouldbeabletotypethemupyourselfand runthem.Runningrealcodeonrealsystemsisthebestwaytolearn aboutoperatingsystems,soweencourageyoutodosowhenyoucan.Wearealso makingcode availableat https://github.com/remzi-arpacidusseau/ostep-code for yourviewingpleasure.
Invariouspartsofthetext,wehavesprinkledinafew homeworks toensure thatyouareunderstandingwhatisgoingon.Manyofthesehomeworksarelittle simulations ofpiecesoftheoperatingsystem;youshoulddownloadthehomeworks,andrunthemtoquizyourself.Thehomeworksimulatorshavethefollowingfeature:bygivingthemadifferentrandomseed,youcangenerateavirtually infinitesetofproblems;thesimulatorscanalsobetoldtosolve theproblemsfor you.Thus,youcantestandre-testyourselfuntilyouhaveachievedagoodlevel ofunderstanding.
Themostimportantaddendumtothisbookisasetof projects inwhichyou learnabouthowrealsystemsworkbydesigning,implementing,andtestingyour owncode.Allprojects(aswellasthecodeexamples,mentionedabove)arein the Cprogramminglanguage [KR88];Cisasimpleandpowerfullanguagethat underliesmostoperatingsystems,andthusworthaddingtoyourtool-chestof languages.Twotypesofprojectsareavailable(seetheonlineappendixforideas). Thefirstare systemsprogramming projects;theseprojectsaregreatforthosewho arenewtoCandU NIX andwanttolearnhowtodolow-levelCprogramming. ThesecondtypearebasedonarealoperatingsystemkerneldevelopedatMIT calledxv6[CK+08];theseprojectsaregreatforstudentsthat alreadyhavesomeC andwanttogettheirhandsdirtyinsidetheOS.AtWisconsin,we’verunthecourse inthreedifferentways:eitherallsystemsprogramming,allxv6 programming,or amixofboth.
Weareslowlymakingprojectdescriptions,andatestingframework,available.See https://github.com/remzi-arpacidusseau/ostep-projects formoreinformation.Ifnotpartofaclass,thiswillgiveyoua chancetodothese projectsonyourown,tobetterlearnthematerial.Unfortunately,youdon’thave aTAtobugwhenyougetstuck,butnoteverythinginlifecanbefree(butbooks canbe!).
ToEducators
Ifyouareaninstructororprofessorwhowishestousethisbook,pleasefeel freetodoso.Asyoumayhavenoticed,theyarefreeandavailableon-linefrom thefollowingwebpage: http://www.ostep.org
Youcanalsopurchaseaprintedcopyfrom lulu.com.Lookforitontheweb pageabove.
The(current)propercitationforthebookisasfollows:
OperatingSystems:ThreeEasyPieces
RemziH.Arpaci-DusseauandAndreaC.Arpaci-Dusseau Arpaci-DusseauBooks
August,2018(Version1.00) http://www.ostep.org
Thecoursedividesfairlywellacrossa15-weeksemester,inwhichyoucan covermostofthetopicswithinatareasonablelevelofdepth. Crammingthe courseintoa10-weekquarterprobablyrequiresdroppingsomedetailfromeach ofthepieces.Therearealsoafewchaptersonvirtualmachinemonitors,whichwe usuallysqueezeinsometimeduringthesemester,eitherrightatend ofthelarge sectiononvirtualization,orneartheendasanaside.
Oneslightlyunusualaspectofthebookisthatconcurrency,atopicatthefront ofmanyOSbooks,ispushedoffhereinuntilthestudenthasbuiltan understandingofvirtualizationoftheCPUandofmemory.Inourexperiencein teaching thiscoursefornearly20years,studentshaveahardtimeunderstandinghowthe concurrencyproblemarises,orwhytheyaretryingtosolveit,iftheydon’tyetunderstandwhatanaddressspaceis,whataprocessis,orwhycontextswitchescan occuratarbitrarypointsintime.Oncetheydounderstandthese concepts,however,introducingthenotionofthreadsandtheproblemsthatariseduetothem becomesrathereasy,oratleast,easier.
Asmuchasispossible,weuseachalkboard(orwhiteboard)todeliveralecture.Onthesemoreconceptualdays,wecometoclasswithafewmajorideas andexamplesinmindandusetheboardtopresentthem.Handoutsareuseful togivethestudentsconcreteproblemstosolvebasedonthematerial.Onmore practicaldays,wesimplyplugalaptopintotheprojectorandshowrealcode;this styleworksparticularlywellforconcurrencylecturesaswell asforanydiscussionsectionswhereyoushowstudentscodethatisrelevantfortheirprojects.We don’tgenerallyuseslidestopresentmaterial,buthavenowmade asetavailable forthosewhopreferthatstyleofpresentation.
Ifyou’dlikeacopyofanyofthesematerials,pleasedropusanemail.We havealreadysharedthemwithmanyothersaroundtheworld,and othershave contributedtheirmaterialsaswell.
Onelastrequest:ifyouusethefreeonlinechapters,pleasejust link tothem, insteadofmakingalocalcopy.Thishelpsustrackusage(over1millionchapters downloadedinthepastfewyears!)andalsoensuresstudentsgetthelatest(and greatest?)version.
ToStudents
Ifyouareastudentreadingthisbook,thankyou!Itisanhonorforusto providesomematerialtohelpyouinyourpursuitofknowledgeabout operating systems.Weboththinkbackfondlytowardssometextbooksofourundergraduate days(e.g.,HennessyandPatterson[HP90],theclassicbook oncomputerarchitecture)andhopethisbookwillbecomeoneofthosepositivememoriesforyou.
Youmayhavenoticedthisbookisfreeandavailableonline2 .Thereisonemajor reasonforthis:textbooksaregenerallytooexpensive.Thisbook,wehope,isthe firstofanewwaveoffreematerialstohelpthoseinpursuitoftheireducation, regardlessofwhichpartoftheworldtheycomefromorhowmuchtheyarewilling tospendforabook.Failingthat,itisonefreebook,whichis betterthannone.
Wealsohope,wherepossible,topointyoutotheoriginalsourcesofmuch ofthematerialinthebook:thegreatpapersandpersonswhohaveshapedthe fieldofoperatingsystemsovertheyears.Ideasarenotpulledoutoftheair;they comefromsmartandhard-workingpeople(includingnumerousTuring-award winners3 ),andthusweshouldstrivetocelebratethoseideasandpeople where possible.Indoingso,wehopefullycanbetterunderstandtherevolutionsthat havetakenplace,insteadofwritingtextsasifthosethoughts havealwaysbeen present[K62].Further,perhapssuchreferenceswillencourageyoutodigdeeper onyourown;readingthefamouspapersofourfieldiscertainlyone ofthebest waystolearn.
2 Adigressionhere:“free”inthewayweuseitheredoesnotmeanopen source,andit doesnotmeanthebookisnotcopyrightedwiththeusualprotections–itis!Whatitmeansis thatyoucandownloadthechaptersandusethemtolearnaboutoperating systems.Whynot anopen-sourcebook,justlikeLinuxisanopen-sourcekernel?Well,webelieveitisimportant forabooktohaveasinglevoicethroughout,andhaveworkedhardtoprovidesuchavoice. Whenyou’rereadingit,thebookshouldkindoffeellikeadialoguewiththepersonexplaining somethingtoyou.Hence,ourapproach.
3 TheTuringAwardisthehighestawardinComputerScience;itisliketheNobelPrize, exceptthatyouhaveneverheardofit.
Acknowledgments
Thissectionwillcontainthankstothosewhohelpedusputthebooktogether. Theimportantthingfornow: yournamecouldgohere! But,youhavetohelp.So sendussomefeedbackandhelpdebugthisbook.Andyoucouldbefamous!Or, atleast,haveyournameinsomebook.
Thepeoplewhohavehelpedsofarinclude: AaronGember(Colgate),Aashrith HGovindraj(USF),AbhinavMehra,AbhiramiSenthilkumaran*,AdamDrescher*(WUSTL), AdamEggum,AdityaVenkataraman,AdrianaIamnitchiandclass(USF),AhmadJarara,Ahmed Fikri*,AjaykrishnaRaghavan,AkielKhan,AlexCurtis,AlexWyler,AlexZhao(U.Coloradoat ColoradoSprings),AliRazeen(Duke),AlistairMartin,AmirBehzad Eslami,AnandMundada, AndrewMahler,AndrewValencik(SaintMary’s),AngelaDemkeBrown(Toronto),Antonella Bernobich(UoPeople)*,ArekBulski,B.BrahmanandaReddy(Minnesota),BalaSubrahmanyam Kambala,BartMiller,BenKushigian(U.Mass),BenitaBose,BiswajitMazumder(Clemson), BobbyJack,BjornLindberg,BrandonHarshe(U.Minn),BrennanPayne,BrianGorman,Brian Kroth,CalebSumner(SouthernAdventist),CaraLauritzen,CharlotteKissinger,ChengSu, Chien-ChungShen(Delaware)*,ChristianStober,ChristophJaeger,C.J. Stanbridge(Memorial U.ofNewfoundland),CodyHanson,ConstantinosGeorgiades,DakotaCrane(U.WashingtonTacoma),DanSoendergaard(U.Aarhus),DanTsafrir(Technion),DaniloBruschi(Universita DegliStudiDiMilano),DarbyAsherNoamHaller,DavidHanle(Grinnell),DavidHartman, DeepikaMuthukumar,DemirDelic,DennisZhou,DheerajShetty(NorthCarolinaState),DorianArnold(NewMexico),DustinMetzler,DustinPassofaro,Eduardo Stelmaszczyk,Emad Sadeghi,EmilHessman,EmilyJacobson,EmmettWitchel(Texas),EricFreudenthal(UTEP), EricJohansson,ErikTurk,ErnstBiersack(France),FangjunKuang(U.Stuttgart),FengZhang (IBM),FinnKuusisto*,GiovanniLagorio(DIBRIS),GlennBruns(CSUMontereyBay),Glen Granzow(CollegeofIdaho),GuilhermeBaptista,HamidRezaGhasemi,HaoChen,Henry Abbey,HilmarGustafsson(AalborgUniversity),HrishikeshAmur,HuanchenZhang*,Huseyin Sular,HugoDiaz,IlyaOblomkov,ItaiHass(Toronto),Jackson“Jake”Haenchen(Texas),JagannathanEachambadi,JakeGillberg,JakobOlandt,JamesEarley,James Perry(U.MichiganDearborn)*,JanReineke(UniversitatdesSaarlandes),JasonMacLafferty(SouthernAdventist),JasonWaterman(Vassar),JayLim,JerodWeinman(Grinnell),Jhih-Cheng Luo,JiaoDong (Rutgers),Jia-ShenBoon,JiawenBao,JingxinLi,JoeJean(NYU),JoelKuntz(SaintMary’s), JoelSommers(Colgate),JohnBrady(Grinnell),JohnKomenda,JonathanPerry(MIT),Joshua Carpenter(NCSU),JunHe,KarlWallinger,KartikSinghal,KatherineDudenas,KatieCoyle (GeorgiaTech),KaushikKannan,KemalBıc¸akcı,KevinLiu*,LanyueLu, LauraXu,LeiTian (U.Nebraska-Lincoln),LeonardoMedici(U.Milan),LeslieSchultz,LiangYin, LihaoWang, Looserof,ManavBatra(IIIT-Delhi),ManuAwasthi(Samsung),MarcelvanderHolst,Marco Guazzone(U.PiemonteOrientale),MartOskamp,MarthaFerris,MasashiKishikawa(Sony), MattReichoff,MattiaMonga(U.Milan),MattyWilliams,MengHuang,MichaelMachtel (HochschuleKonstanz),MichaelWalfish(NYU),MichaelWu(UCLA),MikeGriepentrog,Ming Chen(Stonybrook),MohammedAlali(Delaware),MohamedOmran(GUST),MuruganKandaswamy,NadeemShaikh,NatashaEilbert,NatashaStopa,NathanDipiazza,NathanSullivan,NeerajBadlani(N.C.State),NeilPerry,NelsonGomez,NghiaHuynh(Texas),Nicholas Mandal,NickWeinandt,PatelPratyushAshesh(BITS-Pilani),PatricioJara,PavleKostovic, PerryKivolowitz,PeterPeterson(Minnesota),PieterKockx,RadfordSmith,RiccardoMutschlechner,RipudamanSingh,RobertOrd ´ onezandclass(SouthernAdventist),RogerWattenhofer(ETH),RohanDas(Toronto)*,RohanPasalkar(Minnesota),RohanPuri,Ross Aiken,RuslanKiselev,RylandHerrick,SamKelly,SamNoh(UNIST),SamerAl-Kiswany,SandeepUmmadi(Minnesota),SankaralingamPanneerselvam,SatishChebrolu(NetApp),Satyanarayana
Shanmugam*,ScottCatlin,ScottLee(UCLA),SethPollen,SharadPunuganti,ShreevatsaR., SimonPratt(Waterloo),SivaramanSivaraman*,SongJiang(WayneState),SpencerHarston (WeberState),SrinivasanThirunarayanan*,StefanDekanski,StephenBye,Suriyhaprakhas BalaramSankari,SyJinCheah,TeriZhao(EMC),ThanumalayanS.Pillai,ThomasGriebel, ThomasScrace,TianxiaBai,TongHe,TongxinZheng,TonyAdkins,TorinRudeen(Princeton), TuoWang,TylerCouto,VarunVats,VikasGoel,WaciumaWanjohi,WilliamRoyle(Grinnell), XiangPeng,XuDi,YifanHao,YuanyuanChen,YubinRuan,YudongSun,YueZhuo(Texas A&M),YufuiRen,ZefRosnBrick,ZeyuanHu(Texas),ZiHanZheng(USTC),Zuyu Zhang. Specialthankstothosemarkedwithanasteriskabove,whohavegoneaboveand beyondintheirsuggestionsforimprovement.
Inaddition,aheartythankstoProfessorJoeMeehean(Lynchburg)forhisdetailednotesoneachchapter,toProfessorJerodWeinman(Grinnell)andhisentire classfortheirincrediblebooklets,toProfessorChien-ChungShen(Delaware)for hisinvaluableanddetailedreadingandcomments,toAdamDrescher(WUSTL) forhiscarefulreadingandsuggestions,toGlenGranzow(CollegeofIdaho)forhis incrediblydetailedcommentsandtips,MichaelWalfish(NYU)forhisenthusiasm anddetailedsuggestionsforimprovement,PeterPeterson(UMD) forhismany bitsofusefulfeedbackandcommentary,MarkKampe(Pomona)fordetailedcriticism(weonlywishwecouldfixallsuggestions!),andYoujipWon (Hanyang)for histranslationworkintoKorean(!)andnumerousinsightfulsuggestions.Allhave helpedtheseauthorsimmeasurablyintherefinementofthematerialsherein.
Also,manythankstothehundredsofstudentswhohavetaken537overthe years.Inparticular,theFall’08classwhoencouragedthefirstwrittenformof thesenotes(theyweresickofnothavinganykindoftextbooktoread—pushy students!),andthenpraisedthemenoughforustokeepgoing(includingonehilarious“ZOMG!Youshouldtotallywriteatextbook!”commentinour course evaluationsthatyear).
Agreatdebtofthanksisalsoowedtothebravefewwhotookthe xv6project labcourse,muchofwhichisnowincorporatedintothemain537course.From Spring’09:JustinCherniak,PatrickDeline,MattCzech,TonyGregerson,Michael Griepentrog,TylerHarter,RyanKroiss,EricRadzikowski, WesleyReardan,Rajiv Vaidyanathan,andChristopherWaclawik.FromFall’09:NickBearson,Aaron Brown,AlexBird,DavidCapel,KeithGould,TomGrim,JeffreyHugo,Brandon Johnson,JohnKjell,BoyanLi,JamesLoethen,WillMcCardell,RyanSzaroletta,SimonTso,andBenYule.FromSpring’10:PatrickBlesi,AidanDennis-Oehling, ParasDoshi,JakeFriedman,BenjaminFrisch,EvanHanson,PikkiliHemanth, MichaelJeung,AlexLangenfeld,ScottRick,MikeTreffert,GarretStaus,Brennan Wall,HansWerner,Soo-YoungYang,andCarlosGriffin(almost).
Althoughtheydonotdirectlyhelpwiththebook,ourgraduatestudentshave taughtusmuchofwhatweknowaboutsystems.Wetalkwiththemregularly whiletheyareatWisconsin,buttheydoalltherealwork—andbytellingusabout whattheyaredoing,welearnnewthingseveryweek.Thislist includesthefollowingcollectionofcurrentandformerstudentsandpost-docswithwhomwehave publishedpapers;anasteriskmarksthosewhoreceivedaPh.D. underourguidance:AbhishekRajimwale,AishwaryaGanesan,AndrewKrioukov,Ao Ma,Brian Forney,ChrisDragga,DeepakRamamurthi,DennisZhou,EdwardOakes,FlorentinaPopovici*,HariharanGopalakrishnan,HaryadiS.Gunawi*,JamesNugent, JoeMeehean*,JohnBent*,JunHe,KevinHouck,LanyueLu*,Lakshmi Bairavasundaram*,LaxmanVisampalli,LeoArulraj*,LeonYang,MeenaliRungta,Muthian
Sivathanu*,NathanBurnett*,NitinAgrawal*,RamAlagappan,SamerAl-Kiswany, ScottHendrickson,SriramSubramanian*,StephenToddJones*,StephenSturdevant,SudarsunKannan,SuliYang*,SwaminathanSundararaman*,SwethaKrishnan,ThanhDo*,ThanumalayanS.Pillai*,TimothyDenehy*,TylerHarter*,Venkat Venkataramani,VijayChidambaram*,VijayanPrabhakaran*,YiyingZhang*,Yupu Zhang*,YuvrajPatel,ZevWeiss*.
OurgraduatestudentshavelargelybeenfundedbytheNationalScienceFoundation(NSF),theDepartmentofEnergyOfficeofScience(DOE), andbyindustry grants.WeareespeciallygratefultotheNSFfortheirsupport overmanyyears,as ourresearchhasshapedthecontentofmanychaptersherein.
WethankThomasGriebel,whodemandedabettercoverforthebook.Althoughwedidn’ttakehisspecificsuggestion(adinosaur,canyoubelieveit?),the beautifulpictureofHalley’scometwouldnotbefoundonthecoverwithouthim.
AfinaldebtofgratitudeisalsoowedtoAaronBrown,whofirsttookthiscourse manyyearsago(Spring’09),thentookthexv6labcourse(Fall’09),andfinallywas agraduateteachingassistantforthecoursefortwoyearsorso (Fall’10through Spring’12).Histirelessworkhasvastlyimprovedthestateoftheprojects(particularlythoseinxv6land)andthushashelpedbetterthelearningexperiencefor countlessundergraduatesandgraduateshereatWisconsin.AsAaronwouldsay (inhisusualsuccinctmanner):“Thx.”
FinalWords
Yeatsfamouslysaid“Educationisnotthefillingofapailbutthelightingofa fire.”Hewasrightbutwrongatthesametime4 .Youdohaveto“fillthepail”abit, andthesenotesarecertainlyheretohelpwiththatpartofyoureducation;afterall, whenyougotointerviewatGoogle,andtheyaskyouatrickquestionabouthow tousesemaphores,itmightbegoodtoactuallyknowwhatasemaphoreis,right?
ButYeats’slargerpointisobviouslyonthemark:therealpoint ofeducation istogetyouinterestedinsomething,tolearnsomethingmoreaboutthesubject matteronyourownandnotjustwhatyouhavetodigesttogetagood gradein someclass.Asoneofourfathers(Remzi’sdad,VedatArpaci)usedto say,“Learn beyondtheclassroom”.
Wecreatedthesenotestosparkyourinterestinoperatingsystems,toreadmore aboutthetopiconyourown,totalktoyourprofessoraboutallthe excitingresearchthatisgoingoninthefield,andeventogetinvolvedwiththatresearch.It isagreatfield(!),fullofexcitingandwonderfulideasthathaveshapedcomputing historyinprofoundandimportantways.Andwhileweunderstandthisfirewon’t lightforallofyou,wehopeitdoesformany,orevenafew.Becauseoncethatfire islit,well,thatiswhenyoutrulybecomecapableofdoingsomethinggreat.And thustherealpointoftheeducationalprocess:togoforth,tostudymanynewand fascinatingtopics,tolearn,tomature,andmostimportantly,tofindsomething thatlightsafireforyou.
AndreaandRemzi
Marriedcouple ProfessorsofComputerScienceattheUniversityofWisconsin ChiefLightersofFires,hopefully5
4 Ifheactuallysaidthis;aswithmanyfamousquotes,thehistoryofthisgemismurky.
5 Ifthissoundslikeweareadmittingsomepasthistoryasarsonists,youareprobably missingthepoint.Probably.Ifthissoundscheesy,well,that’sbecauseitis,butyou’lljusthave toforgiveusforthat.
References
[CK+08]“Thexv6OperatingSystem”byRussCox,FransKaashoek,RobertMorris,Nickolai Zeldovich.From: http://pdos.csail.mit.edu/6.828/2008/index.html xv6was developedasaportoftheoriginal U NIX version6andrepresentsabeautiful,clean,andsimplewayto understandamodernoperatingsystem.
[F96]“SixEasyPieces:EssentialsOfPhysicsExplainedByItsMostBrilliantTeacher”by RichardP.Feynman.BasicBooks,1996. ThisbookreprintsthesixeasiestchaptersofFeynman’s LecturesonPhysics,from1963.IfyoulikePhysics,itisafantasticread [HP90]“ComputerArchitectureaQuantitativeApproach”(1sted.)byDavidA.Pattersonand JohnL.Hennessy.Morgan-Kaufman,1990. Abookthatencouragedeachofusatourundergraduate institutionstopursuegraduatestudies;welaterbothhadthepleasureofworking withPatterson,who greatlyshapedthefoundationsofourresearchcareers.
[KR88]“TheCProgrammingLanguage”byBrianKernighanandDennisRitchie. PrenticeHall,April1988. TheCprogrammingreferencethateveryoneshouldhave,bythepeoplewhoinvented thelanguage.
[K62]“TheStructureofScientificRevolutions”byThomasS.Kuhn.UniversityofChicago Press,1962. Agreatandfamousreadaboutthefundamentalsofthescientificprocess.Mop-upwork, anomaly,crisis,andrevolution.Wearemostlydestinedtodomop-upwork,alas.
6Mechanism:LimitedDirectExecution49
6.1BasicTechnique:LimitedDirectExecution.........49
7Scheduling:Introduction
7.1WorkloadAssumptions....................65
7.2SchedulingMetrics.......................66
7.3FirstIn,FirstOut(FIFO)....................66
7.4ShortestJobFirst(SJF).....................68
7.5ShortestTime-to-CompletionFirst(STCF)..........69
7.6ANewMetric:ResponseTime................70
8Scheduling: TheMulti-LevelFeedbackQueue77
8.1MLFQ:BasicRules.......................78
8.2Attempt#1:HowToChangePriority............79
8.3Attempt#2:ThePriorityBoost................83
8.4Attempt#3:BetterAccounting................84
8.5TuningMLFQAndOtherIssues...............84
9Scheduling:ProportionalShare89
9.1BasicConcept:TicketsRepresentYourShare........89
9.2TicketMechanisms.......................91
9.3Implementation.........................92
9.4AnExample...........................93
9.5HowToAssignTickets?....................94
9.6WhyNotDeterministic?....................94
9.7TheLinuxCompletelyFairScheduler(CFS).........95
9.8Summary............................100 References...............................101 Homework(Simulation).......................102
10MultiprocessorScheduling(Advanced)103
10.1Background:MultiprocessorArchitecture..........104 10.2Don’tForgetSynchronization.................106
10.3OneFinalIssue:CacheAffinity................107 10.4Single-QueueScheduling...................107
10.5Multi-QueueScheduling....................109
10.6LinuxMultiprocessorSchedulers...............112
10.7Summary............................112 References...............................113 Homework(Simulation).......................114
11SummaryDialogueonCPUVirtualization117
12ADialogueonMemoryVirtualization119
13TheAbstraction:AddressSpaces121 13.1EarlySystems..........................121 13.2MultiprogrammingandTimeSharing............122 13.3TheAddressSpace.......................123 13.4Goals...............................125 13.5Summary............................127 References...............................128 Homework(Code)...........................129
14Interlude:MemoryAPI 131
14.1TypesofMemory........................131
14.2The malloc() Call......................132 14.3The free() Call........................134 14.4CommonErrors........................134
14.5UnderlyingOSSupport....................137 14.6OtherCalls...........................138 14.7Summary............................138 References...............................139 Homework(Code)...........................140
15Mechanism:AddressTranslation141
15.1Assumptions..........................142
15.2AnExample...........................142
15.3Dynamic(Hardware-based)Relocation...........145
15.4HardwareSupport:ASummary...............148
15.5OperatingSystemIssues....................149
15.6Summary............................152
16Segmentation 155
16.1Segmentation:GeneralizedBase/Bounds..........155
16.2WhichSegmentAreWeReferringTo?............158
16.3WhatAboutTheStack?....................159
16.4SupportforSharing......................160
16.5Fine-grainedvs.Coarse-grainedSegmentation.......161
16.6OSSupport...........................161
16.7Summary............................163 References...............................164 Homework(Simulation).......................165
17Free-SpaceManagement 167
17.1Assumptions..........................168
17.2Low-levelMechanisms....................169
17.3BasicStrategies.........................177
17.4OtherApproaches.......................179
17.5Summary............................181
18Paging:Introduction 185
18.1ASimpleExampleAndOverview..............185
18.2WhereArePageTablesStored?................189
18.3What’sActuallyInThePageTable?.............190
18.4Paging:AlsoTooSlow.....................191
18.5AMemoryTrace........................192
18.6Summary............................195 References...............................196 Homework(Simulation).......................197
19Paging:FasterTranslations(TLBs)199
19.1TLBBasicAlgorithm......................199
19.2Example:AccessingAnArray................201 19.3WhoHandlesTheTLBMiss?.................203
19.4TLBContents:What’sInThere?...............205
19.5TLBIssue:ContextSwitches.................206
19.6Issue:ReplacementPolicy...................208
C ONTENTS
19.7ARealTLBEntry........................209 19.8Summary............................210 References...............................211
Homework(Measurement)......................212
20Paging:SmallerTables 215
20.1SimpleSolution:BiggerPages................215
20.2HybridApproach:PagingandSegments..........216
20.3Multi-levelPageTables....................219
20.4InvertedPageTables......................226
20.5SwappingthePageTablestoDisk..............227
20.6Summary............................227 References...............................228
Homework(Simulation).......................229
21BeyondPhysicalMemory:Mechanisms231 21.1SwapSpace...........................232 21.2ThePresentBit.........................233
21.3ThePageFault.........................234
21.4WhatIfMemoryIsFull?....................235
21.5PageFaultControlFlow....................236
21.6WhenReplacementsReallyOccur..............237
21.7Summary............................238 References...............................239
Homework(Measurement)......................240
22BeyondPhysicalMemory:Policies243
22.1CacheManagement......................243
22.2TheOptimalReplacementPolicy...............244
22.3ASimplePolicy:FIFO.....................246
22.4AnotherSimplePolicy:Random...............248
22.5UsingHistory:LRU......................249
22.6WorkloadExamples......................250
22.7ImplementingHistoricalAlgorithms.............253
22.8ApproximatingLRU......................254
22.9ConsideringDirtyPages....................255
22.10OtherVMPolicies.......................256
22.11Thrashing............................256
22.12Summary............................257 References...............................258
Homework(Simulation).......................259
23CompleteVirtualMemorySystems261
23.1VAX/VMSVirtualMemory..................262
23.2TheLinuxVirtualMemorySystem..............268
23.3Summary............................277 References...............................278
26Concurrency:AnIntroduction287
26.1WhyUseThreads?.......................288
26.2AnExample:ThreadCreation................289
26.3WhyItGetsWorse:SharedData...............292
26.4TheHeartOfTheProblem:UncontrolledScheduling...294
26.5TheWishForAtomicity....................296
26.6OneMoreProblem:WaitingForAnother..........298
26.7Summary:WhyinOSClass?.................298
28Locks 315
28.1Locks:TheBasicIdea.....................315
28.2PthreadLocks..........................316
28.3BuildingALock........................317
28.4EvaluatingLocks........................317
28.5ControllingInterrupts.....................318
28.6AFailedAttempt:JustUsingLoads/Stores.........319
28.7BuildingWorkingSpinLockswithTest-And-Set......320
28.8EvaluatingSpinLocks.....................322
28.9Compare-And-Swap......................323
28.10Load-LinkedandStore-Conditional.............324
28.11Fetch-And-Add.........................326
28.12TooMuchSpinning:WhatNow?...............327
28.13ASimpleApproach:JustYield,Baby.............328
28.14UsingQueues:SleepingInsteadOfSpinning........329
28.15DifferentOS,DifferentSupport................332
28.16Two-PhaseLocks........................332
28.17Summary............................334 References...............................335
29Lock-basedConcurrentDataStructures337
30ConditionVariables
30.1DefinitionandRoutines....................352
30.2TheProducer/Consumer(BoundedBuffer)Problem....355
31Semaphores
31.1Semaphores:ADefinition...................367 31.2BinarySemaphores(Locks)..................369
31.3SemaphoresForOrdering...................370
31.4TheProducer/Consumer(BoundedBuffer)Problem....372
31.5Reader-WriterLocks......................376
31.6TheDiningPhilosophers...................378
31.7HowToImplementSemaphores...............381
32CommonConcurrencyProblems385
33Event-basedConcurrency(Advanced)401
33.1TheBasicIdea:AnEventLoop................401
33.2AnImportantAPI: select() (or poll()).........402
33.3Using select() ........................403
33.4WhySimpler?NoLocksNeeded...............404
33.5AProblem:BlockingSystemCalls..............405
33.6ASolution:AsynchronousI/O................405
33.7AnotherProblem:StateManagement............408
33.8WhatIsStillDifficultWithEvents..............409 33.9Summary............................409 References...............................410 Homework(Code)...........................411 34SummaryDialogueonConcurrency413
36I/ODevices 419
36.1SystemArchitecture......................419
36.2ACanonicalDevice......................421
36.3TheCanonicalProtocol....................422
36.4LoweringCPUOverheadWithInterrupts..........423
36.5MoreEfficientDataMovementWithDMA.........424
36.6MethodsOfDeviceInteraction................425
36.7FittingIntoTheOS:TheDeviceDriver............426
36.8CaseStudy:ASimpleIDEDiskDriver............427
36.9HistoricalNotes........................430 36.10Summary............................430 References...............................431
37HardDiskDrives 433
37.1TheInterface..........................433
37.2BasicGeometry.........................434
37.3ASimpleDiskDrive......................435
37.4I/OTime:DoingTheMath..................438
37.5DiskScheduling........................442
37.6Summary............................446 References...............................447 Homework(Simulation).......................448
38RedundantArraysofInexpensiveDisks(RAIDs)449
38.1InterfaceAndRAIDInternals.................450
38.2FaultModel...........................451
38.3HowToEvaluateARAID...................451
38.4RAIDLevel0:Striping.....................452
38.5RAIDLevel1:Mirroring....................455
38.6RAIDLevel4:SavingSpaceWithParity...........458
38.7RAIDLevel5:RotatingParity................462
38.8RAIDComparison:ASummary...............463
38.9OtherInterestingRAIDIssues................464
38.10Summary............................464 References...............................465
Homework(Simulation).......................466
39Interlude:FilesandDirectories467
39.1FilesAndDirectories......................467
39.2TheFileSystemInterface...................469
39.3CreatingFiles..........................469
39.4ReadingAndWritingFiles..................470
39.5ReadingAndWriting,ButNotSequentially.........472
39.6SharedFileTableEntries: fork() And dup() .......475
39.7WritingImmediatelyWith fsync() .............477
39.8RenamingFiles.........................478
39.9GettingInformationAboutFiles...............479
39.13DeletingDirectories......................482 39.14HardLinks...........................482
39.15SymbolicLinks.........................484
39.16PermissionBitsAndAccessControlLists..........485
40FileSystemImplementation493
40.1TheWayToThink.......................493
40.2OverallOrganization......................494
40.3FileOrganization:TheInode.................496
40.4DirectoryOrganization....................501
40.5FreeSpaceManagement....................501
40.6AccessPaths:ReadingandWriting..............502
40.7CachingandBuffering.....................506
40.8Summary............................508 References...............................509 Homework(Simulation).......................510
41LocalityandTheFastFileSystem511
41.1TheProblem:PoorPerformance...............511
41.2FFS:DiskAwarenessIsTheSolution.............513
41.3OrganizingStructure:TheCylinderGroup.........513
41.4Policies:HowToAllocateFilesandDirectories.......515
41.5MeasuringFileLocality....................517
41.6TheLarge-FileException...................518
41.7AFewOtherThingsAboutFFS................520
41.8Summary............................522 References...............................523 Homework(Simulation).......................524
42CrashConsistency:FSCKandJournaling525
42.1ADetailedExample......................526
42.2Solution#1:TheFileSystemChecker............529
42.3Solution#2:Journaling(orWrite-AheadLogging).....531
42.4Solution#3:OtherApproaches................541
42.5Summary............................542 References...............................543
Homework(Simulation).......................545
43Log-structuredFileSystems 547
43.1WritingToDiskSequentially.................548
43.2WritingSequentiallyAndEffectively.............549
43.3HowMuchToBuffer?.....................550
43.4Problem:FindingInodes...................551
43.5SolutionThroughIndirection:TheInodeMap.......551
43.6CompletingTheSolution:TheCheckpointRegion.....553
43.7ReadingAFileFromDisk:ARecap.............553
43.8WhatAboutDirectories?...................554
43.9ANewProblem:GarbageCollection.............555
43.10DeterminingBlockLiveness..................556
43.11APolicyQuestion:WhichBlocksToClean,AndWhen?..557
43.12CrashRecoveryAndTheLog.................558
43.13Summary............................558 References...............................560 Homework(Simulation).......................561
44Flash-basedSSDs 563
44.1StoringaSingleBit.......................563
44.2FromBitstoBanks/Planes..................564
44.3BasicFlashOperations.....................565
44.4FlashPerformanceAndReliability..............567
44.5FromRawFlashtoFlash-BasedSSDs............568
44.6FTLOrganization:ABadApproach.............569
44.7ALog-StructuredFTL.....................570
44.8GarbageCollection.......................572
44.9MappingTableSize......................574
44.10WearLeveling.........................579
44.11SSDPerformanceAndCost..................579
44.12Summary............................581 References...............................583
Homework(Simulation).......................585
45DataIntegrityandProtection587
45.1DiskFailureModes.......................587
45.2HandlingLatentSectorErrors................589
45.3DetectingCorruption:TheChecksum............590
45.4UsingChecksums.......................593
45.5ANewProblem:MisdirectedWrites.............594
45.6OneLastProblem:LostWrites................595
45.7Scrubbing............................595
45.8OverheadsOfChecksumming................596
45.9Summary............................596 References...............................597 Homework(Simulation).......................598 Homework(Code)...........................599
46SummaryDialogueonPersistence601
47ADialogueonDistribution 603
48DistributedSystems 605
48.1CommunicationBasics.....................606
48.2UnreliableCommunicationLayers..............607
48.3ReliableCommunicationLayers...............609
48.4CommunicationAbstractions.................611
48.5RemoteProcedureCall(RPC).................613
48.6Summary............................618 References...............................619 Homework(Code)...........................620
49Sun’sNetworkFileSystem(NFS)621
49.1ABasicDistributedFileSystem................622
49.2OnToNFS............................623
49.3Focus:SimpleAndFastServerCrashRecovery.......623
49.4KeyToFastCrashRecovery:Statelessness.........624
49.5TheNFSv2Protocol......................625
49.6FromProtocolToDistributedFileSystem..........627
49.7HandlingServerFailureWithIdempotentOperations...629
49.8ImprovingPerformance:Client-sideCaching........631
49.9TheCacheConsistencyProblem...............631
49.10AssessingNFSCacheConsistency..............633
49.11ImplicationsOnServer-SideWriteBuffering........633
49.12Summary............................635 References...............................637 Homework(Measurement)......................638
50TheAndrewFileSystem(AFS)639
50.1AFSVersion1..........................639
50.2ProblemswithVersion1....................641
50.3ImprovingtheProtocol....................642
50.4AFSVersion2..........................642
50.5CacheConsistency.......................644
50.6CrashRecovery.........................646
50.7ScaleAndPerformanceOfAFSv2..............646
ADialogueontheBook
Professor: Welcometothisbook!It’scalled OperatingSystemsinThreeEasy Pieces,andIamheretoteachyouthethingsyouneedtoknowaboutoperating systems.Iamcalled“Professor”;whoareyou?
Student: HiProfessor!Iamcalled“Student”,asyoumighthaveguessed.And Iamhereandreadytolearn!
Professor: Soundsgood.Anyquestions?
Student: Sure!Whyisitcalled“ThreeEasyPieces”?
Professor: That’saneasyone.Well,yousee,therearethesegreatlectures on PhysicsbyRichardFeynman...
Student: Oh!Theguywhowrote“SurelyYou’reJoking,Mr.Feynman”,right? Greatbook!Isthisgoingtobehilariouslikethatbookwas?
Professor: Um...well,no.Thatbookwasgreat,andI’mgladyou’vereadit. HopefullythisbookismorelikehisnotesonPhysics.Someofthebasicswere summedupinabookcalled“SixEasyPieces”.HewastalkingaboutPhysics; we’regoingtodoThreeEasyPiecesonthefinetopicofOperatingSystems.This isappropriate,asOperatingSystemsareabouthalfashardasPhysics.
Student: Well,Ilikedphysics,sothatisprobablygood.Whatarethosepieces?
Professor: Theyarethethreekeyideaswe’regoingtolearnabout: virtualization, concurrency,and persistence.Inlearningabouttheseideas,we’lllearn allabouthowanoperatingsystemworks,includinghowitdecideswhatprogram torunnextonaCPU,howithandlesmemoryoverloadinavirtualmemorysystem,howvirtualmachinemonitorswork,howtomanageinformationondisks, andevenalittleabouthowtobuildadistributedsystemthatworkswhenparts havefailed.Thatsortofstuff.
Student: Ihavenoideawhatyou’retalkingabout,really.
Professor: Good!Thatmeansyouareintherightclass.
Student: Ihaveanotherquestion:what’sthebestwaytolearnthisstuff?
Professor: Excellentquery!Well,eachpersonneedstofigurethisoutontheir
ADIALOGUEONTHE BOOK
own,ofcourse,buthereiswhatIwoulddo:gotoclass,tohearthe professor introducethematerial.Then,attheendofeveryweek,readthesenotes,tohelp theideassinkintoyourheadabitbetter.Ofcourse,sometimelater (hint:before theexam!),readthenotesagaintofirmupyourknowledge.Ofcourse,yourprofessorwillnodoubtassignsomehomeworksandprojects,soyoushoulddothose; inparticular,doingprojectswhereyouwriterealcodetosolvereal problemsis thebestwaytoputtheideaswithinthesenotesintoaction.AsConfuciussaid...
Student: Oh,Iknow!’IhearandIforget.IseeandIremember.IdoandI understand.’Orsomethinglikethat.
Professor: (surprised)HowdidyouknowwhatIwasgoingtosay?!
Student: Itseemedtofollow.Also,IamabigfanofConfucius,andaneven biggerfanofXunzi,whoactuallyisabettersourceforthisquote1
Professor: (stunned)Well,Ithinkwearegoingtogetalongjustfine!Justfine indeed.
Student: Professor–justonemorequestion,ifImay.Whatarethesedialogues for?Imean,isn’tthisjustsupposedtobeabook?Whynotpresentthematerial directly?
Professor: Ah,goodquestion,goodquestion!Well,Ithinkitissometimes usefultopullyourselfoutsideofanarrativeandthinkabit;thesedialoguesare thosetimes.SoyouandIaregoingtoworktogethertomakesense ofallofthese prettycomplexideas.Areyouupforit?
Student: Sowehavetothink?Well,I’mupforthat.Imean,whatelsedoIhave todoanyhow?It’snotlikeIhavemuchofalifeoutsideofthisbook.
Professor: Meneither,sadly.Solet’sgettowork!
1 Accordingtothiswebsite(http://www.barrypopik.com/index.php/new york city/ entry/tell me and i forget teach me and i may remember involve me and i will lear/), ConfucianphilosopherXunzisaid“Nothavingheardsomethingisnotasgoodashaving heardit;havinghearditisnotasgoodashavingseenit;havingseenitisnotasgoodas knowingit;knowingitisnotasgoodasputtingitintopractice.”Later on,thewisdomgot attachedtoConfuciusforsomereason.ThankstoJiaoDong(Rutgers)fortellingus!
IntroductiontoOperatingSystems
Ifyouaretakinganundergraduateoperatingsystemscourse,you should alreadyhavesomeideaofwhatacomputerprogramdoeswhenitruns. Ifnot,thisbook(andthecorrespondingcourse)isgoingtobedifficult —soyoushouldprobablystopreadingthisbook,orruntothenearestbookstoreandquicklyconsumethenecessarybackgroundmaterial beforecontinuing(bothPatt&Patel[PP03]andBryant&O’Hallaron [BOH10]areprettygreatbooks).
Sowhathappenswhenaprogramruns?
Well,arunningprogramdoesoneverysimplething:itexecutesinstructions.Manymillions(andthesedays,evenbillions)oftimeseverysecond,theprocessor fetches aninstructionfrommemory, decodes it(i.e.,figuresoutwhichinstructionthisis),and executes it(i.e.,itdoes thethingthatitissupposedtodo,likeaddtwonumberstogether,access memory,checkacondition,jumptoafunction,andsoforth).After itis donewiththisinstruction,theprocessormovesontothenextinstruction, andsoon,andsoon,untiltheprogramfinallycompletes1
Thus,wehavejustdescribedthebasicsofthe VonNeumann modelof computing2.Soundssimple,right?Butinthisclass,wewillbelearning thatwhileaprogramruns,alotofotherwildthingsaregoingonwith theprimarygoalofmakingthesystem easytouse. Thereisabodyofsoftware,infact,thatisresponsibleformaking it easytorunprograms(evenallowingyoutoseeminglyrunmanyatthe sametime),allowingprogramstosharememory,enablingprogramsto interactwithdevices,andotherfunstufflikethat.Thatbody ofsoftware
1Ofcourse,modernprocessorsdomanybizarreandfrighteningthingsunderneaththe hoodtomakeprogramsrunfaster,e.g.,executingmultipleinstructionsatonce,andevenissuingandcompletingthemoutoforder!Butthatisnotourconcernhere;wearejustconcerned withthesimplemodelmostprogramsassume:thatinstructionsseeminglyexecuteoneata time,inanorderlyandsequentialfashion.
2VonNeumannwasoneoftheearlypioneersofcomputingsystems.Healsodidpioneeringworkongametheoryandatomicbombs,andplayedintheNBAforsix years.OK,oneof thosethingsisn’ttrue.
THE CRUXOFTHE PROBLEM:
HOW TO VIRTUALIZE RESOURCES
Onecentralquestionwewillanswerinthisbookisquitesimple: how doestheoperatingsystemvirtualizeresources?Thisisthecruxofour problem. Why theOSdoesthisisnotthemainquestion,astheanswer shouldbeobvious:itmakesthesystemeasiertouse.Thus,wefocuson the how:whatmechanismsandpoliciesareimplementedbytheOSto attainvirtualization?HowdoestheOSdosoefficiently?Whathardware supportisneeded?
Wewillusethe“cruxoftheproblem”,inshadedboxessuchasthis one, asawaytocalloutspecificproblemswearetryingtosolveinbuilding anoperatingsystem.Thus,withinanoteonaparticulartopic,you may findoneormore cruces (yes,thisistheproperplural)whichhighlightthe problem.Thedetailswithinthechapter,ofcourse,presentthe solution, oratleastthebasicparametersofasolution.
iscalledthe operatingsystem (OS)3,asitisinchargeofmakingsurethe systemoperatescorrectlyandefficientlyinaneasy-to-usemanner.
TheprimarywaytheOSdoesthisisthroughageneraltechniquethat wecall virtualization.Thatis,theOStakesa physical resource(suchas theprocessor,ormemory,oradisk)andtransformsitintoamoregeneral,powerful,andeasy-to-use virtual formofitself.Thus,wesometimes refertotheoperatingsystemasa virtualmachine
Ofcourse,inordertoallowuserstotelltheOSwhattodoandthus makeuseofthefeaturesofthevirtualmachine(suchasrunning aprogram,orallocatingmemory,oraccessingafile),theOSalsoprovides someinterfaces(APIs)thatyoucancall.AtypicalOS,infact,exports afewhundred systemcalls thatareavailabletoapplications.Because theOSprovidesthesecallstorunprograms,accessmemoryanddevices, andotherrelatedactions,wealsosometimessaythattheOSprovidesa standardlibrary toapplications.
Finally,becausevirtualizationallowsmanyprogramstorun(thussharingtheCPU),andmanyprogramstoconcurrentlyaccesstheirown instructionsanddata(thussharingmemory),andmanyprogramsto access devices(thussharingdisksandsoforth),theOSissometimesknownas a resourcemanager.EachoftheCPU,memory,anddiskisa resource ofthesystem;itisthustheoperatingsystem’sroleto manage thoseresources,doingsoefficientlyorfairlyorindeedwithmanyotherpossible goalsinmind.TounderstandtheroleoftheOSalittlebitbetter,let’stake alookatsomeexamples.
3AnotherearlynamefortheOSwasthe supervisor oreventhe mastercontrolprogram Apparently,thelattersoundedalittleoverzealous(seethemovieTronfordetails)andthus, thankfully,“operatingsystem”caughtoninstead.
main(intargc,char *argv[])
Figure2.1: SimpleExample:CodeThatLoopsAndPrints(cpu.c)
Figure2.1depictsourfirstprogram.Itdoesn’tdomuch.Infact,all itdoesiscall Spin(),afunctionthatrepeatedlychecksthetimeand returnsonceithasrunforasecond.Then,itprintsoutthestring thatthe userpassedinonthecommandline,andrepeats,forever.
Let’ssaywesavethisfileas cpu.c anddecidetocompileandrunit onasystemwithasingleprocessor(or CPU aswewillsometimescallit). Hereiswhatwewillsee:
prompt>gcc-ocpucpu.c-Wall prompt>./cpu"A"
ˆC prompt>
Nottoointerestingofarun—thesystembeginsrunningtheprogram, whichrepeatedlychecksthetimeuntilasecondhaselapsed.Onceasecondhaspassed,thecodeprintstheinputstringpassedinbythe user (inthisexample,theletter“A”),andcontinues.Notetheprogramwill runforever;onlybypressing“Control-c”(whichonUNIX-basedsystems willterminatetheprogramrunningintheforeground)canwehaltthe program.
Now,let’sdothesamething,butthistime,let’srunmanydifferentinstancesofthissameprogram.Figure2.2showstheresultsofthis slightly morecomplicatedexample.
prompt>./cpuA&;./cpuB&;./cpuC&;./cpuD& [1]7353 [2]7354 [3]7355 [4]7356