Course Outline • Prerequisites – COMPXXXXDatastructuresandalgorithms • Stacks,queues,hashtables,lists,trees,heaps,. Introduction – COMPXXXXMicroprocessorandInterfacing • Assemblyprogramming • Mappingofhighlevelprocedurallanguagetoassembly language COMP3231/9201/3891/9283 • Interrupts (Extended)OperatingSystems – Youareexpectedtobecompetentprogrammers!!!! • WewillbeusingtheCprogramminglanguage KevinElphinstone – ThedominantlanguageforOSimplementation. – Needtounderstandpointers,pointerarithmetic,explicitmemory allocation. 2

Why does this fail? Lectures • Commonforallcourses(3231/3891/9201/9283) void func(int *x, int *y) • Wednesday,13pm,ElecEngG25 { • Thursday,12pm,WebsterTheatreA *x = 1; *y = 2; – ExtendedOSThursday23pmWebster250 • startsinweek2 } – Thelecturenoteswillbeavailableonthecoursewebsite void main() • Availablepriortolectures,whenpossible. { • Slidenumbersfornotetaking – ThelecturenotesandtextbookareNOTasubstitutefor int *a, *b; attendinglectures. func(a,b); printf(“%d %d\n”,*a,*b);

} 3 4

Tutorials Assignments • Startinweek2 • Assignmentsformasubstantialcomponentof yourassessment. • Atutorialparticipationmarkwill • Theyarechallenging!!!! contributetoyourfinalassessment. – Becauseoperatingsystemsarechallenging – Participationmeansparticipation,NOT • WewillbeusingOS/161, attendance. – aneducationaloperatingsystem – Comp3891/9283studentsexcluded – developedbythe SystemsGroupAtHarvard – Itcontainsroughly20,000linesofcodeand – Comp9201optional comments • Youwillonlygetparticipationmarksin yourenrolledtutorial. 5 6

1 Assignments Assignments • Assignmentsareinpairs • Don’tunderestimatethetimeneededtodothe – Infoonhowtopairupavailablesoon assignments. • Weusuallyofferadvancedversionsofthe • Ifyoustartacoupledaysbeforetheyaredue,you assignments willbelate. – Availablebonusmarksaresmallcomparedtoamountof • Toencourageyoutostartearly, effortrequired. – Bonus10%ofmaxmarkoftheassignmentforfinishinga – Studentshoulddoitforthechallenge,notthemarks. weekearly – Attemptingtheadvancedcomponentisnotavalidexcuse – Toironoutanypotentialproblemswiththespec,5%bonus forfailuretocompletethenormalcomponentofthe forfinishingwithin48hoursofassignmentrelease. assignment – Seecoursehandoutforexactdetails • ExtendedOSstudents(COMP3891/9283)are • Readthefineprint!!!! expectedtoattempttheadvancedassignments

7 8

Assignments Assignments

• Threeassignments • Latepenalty – dueroughlyweek3,6,11 – 4%oftotalassignmentvalueperday • Thefirstoneistrivial • Assignmentisworth20% • Youget18,andare2dayslate – It’sawarmuptohaveyoufamiliarize • Finalmark=18– (20*0.04*2)=16 (16.4) yourselfwiththeenvironmentandeasy marks. • Assignmentsareonlyacceptedupto – Donotuseitasagaugeforjudgingthe oneweeklate. 8+days=0 difficultyofthefollowingassignments.

9 10

Assignments Plagiarism

• Tohelpyouwiththeassignments • Wetakecheatingseriously!!! – Wededicateatutorialperassignmentto • Wesystematicallycheckforplagiarisedcode discussissuesrelatedtotheassignment – Penaltiesaregenerallysufficienttomakeitdifficult – Prepareforthem!!!!! topass

11 12

2 Cheating Statistics Exams

Session 1998/S1 1999/S1 2000/S1 2001/S1 2001/S2 2002/S1 2002/S2 2003/S1 2003/S2 enrolment 178 410 320 300 107 298 156 333 133 • ThereisNOmidsession suspected cheaters 10(6%) 26(6%) 22(7%) 26(9%) 20(19%) 15(5%) ???(?%) 13(4%) ???(?%) • Thefinalwrittenexamis2hours full penalties * * * * 2 6 9 14 10 9 5 2 1 reduced penalties 7 15 7 7 5 4 2 2 9 • Supplementaryexamsare oral . cheaters failed 4 10 16 16 10 12 5 4 ? cheaters – Supplementariesareavailableaccordingto suspended 0 0 1 0 0 1 0 0 0 UNSW&schoolpolicy,notasasecond chance.

*Note:Fullpenalty0FLnotappliedpriorto2001/S1 13 14

Assessment 3891/9283

• ExamMark • ClassMark • Notutorialparticipationcomponent Component Component • Assignmentmarksscaledto100 – Maxmarkof100 – Maxmarkof100 • Basedsolelyonthe • 10%tutorial finalexam participation • 90%Assignments

15 16

9201 Undergrad Assessment

• Optionaltutorialparticipation,we’ll • Thefinalassessmentistheharmonic awardthebettermarkof meanoftheexamandclass – Tutorialparticipationincludedasfor component. comp3231 • IfE>=40, – Classmarkedbasedsolelyonthe assignments 2EC M = E + C

17 18

3 Postgrads (9201/9283) Assessment • Maximumofa50/50weightedharmonic meananda20/80harmonicmean • IfE<40 – Canweightfinalmarkheavilyonexamifyoucan’t committhetimetotheassignments – Youarerewardedforseriouslyattemptingthe assignments  2EC  M = min44,  • ifE>=40,  E + C  2EC 5EC M = max( E+C , E+4C )

19 20

Harmonic Mean (Class Mark = 100 - Exam Mark) Final M ark = 50

100 100

90 90

80 80

70 70 Harm50/50 60 60 Arith50/50 Harm 50/50 50 50 Arith20/80 Harm 20/80

Final Mark Final 40 Harm20/80 40 30 30

20 20 ExamMark Required to Pass 10 10

0 0 0 10 20 30 40 50 60 70 80 90 100 0 10 20 30 40 50 60 70 80 90 100 Exam Mark Class Mark

21 22

Assessment Textbook

• Youneedtoperformreasonably • Andrew consistentlyinbothexamandclass Tanenbaum, components. Modern Operating • Harmonicmeanonlyhassignificant Systems, 3rd effectwithsignificantvariation. Edition,Prentice Hall • Reservetherighttoscale,andscale coursesindividuallyifrequired. – Warning:Wehavenotscaledinthepast.

23 24

4 References Consultations/Questions

• A.SilberschatzandP.B.Galvin, Concepts , • Questionsshouldbedirectedtotheforum. th th th 5 ,6 ,or7 edition,AddisonWesley • AdminrelatedqueriestoNicholasFitzroyDale • WilliamStallings, Operating Systems: Internals and Design Principles, 4thor5 th edition,PrenticeHall. [email protected] • A.Tannenbaum,A.Woodhull, Operating Systems--Design and • Personalqueriescanbedirectedtome Implementation ,2 nd editionPrenticeHall [email protected] • JohnO'Gorman, Operating Systems ,MacMillan,2000 • Wereservetherighttoignoreemailsentdirectlyto • UreshVahalla, UNIX Internals: The New Frontiers ,Prentice us(includingtutors)ifitshouldhavebeendirectedto Hall,1996 theforum. • McKusicketal., The Design and Implementation of the 4.4 BSD Operating System ,AddisonWesley,1996 • ConsultationTimes – TBA

25 26

Course Outline Course Outline

• “thecourseaimstoeducatestudentsin • Processesandthreads thebasicconceptsandcomponentsof • Concurrencycontrol operatingsystems,therelevant • MemoryManagement characteristicsofhardware,andthe tradeoffsbetweenconflictingobjectives • FileSystems facedbyoperatingsystemsinefficiently • I/OandDevices supportingawiderangeof • Security applications.” • Scheduling

27 28

Learning Outcomes

• Highlevelunderstandwhatisan Introduction to Operating operatingsystemandtheroleitplays Systems • Appreciatetheevolutionofoperating systemstrackstheevolutionof Chapter1– 1.3 hardware,andthatevolutionisrepeated ineachnewhardwareera.

30

5 What is an Operating System?

31 32

Viewing the Operating System as an Abstract Disk Users Machine • Extendsthebasichardwarewithadded Memory functionality

• Provideshighlevelabstractions CPU – Moreprogrammerfriendly – Commoncoreforallapplications Network • Ithidesthedetailsofthehardware Bandwidth – Makesapplicationcodeportable

33 34

Dated View: the Operating Viewing the Operating System System as the Privileged as a Resource Manager PrivilegedMode Component • Responsibleforallocatingresourcestousers andprocesses OperatingSystem • Mustensure – NoStarvation – Progress Requests Applications – Allocationisaccordingtosomedesiredpolicy • Firstcome,firstserved;Fairshare;Weightedfairshare; (SystemCalls) limits(quotas),etc UserMode – Overall,thatthesystemisefficientlyused Applications Applications

35 36

6 The Operating System is Why Study Operating Privileged Systems? • Applicationsshouldnotbeabletointerfereorbypass • Therearemanyinterestingproblemsin theoperatingsystem operatingsystems. – OScanenforcethe“extendedmachine” • Foracomplete,toptobottomviewofa – OScanenforceitsresourceallocationpolicies system. – Preventapplicationsfrominterferingwitheachother • Understandperformanceimplicationsof applicationbehaviour. • Note:SomeEmbeddedOSshavenoprivileged component,e.g.PalmOS • Understandingandprogramminglarge, – CanimplementOSfunctionality,butcannotenforceit. complex,softwaresystemsisagoodskillto • Note:Someoperatingsystemsimplementsignificant acquire. OSfunctionalityinusermode,e.g.Usermode 37 38

Second Generation Machines (A brief) Operating System History • Largelyparallelshardware Batch Systems development • IBM7094 • FirstGenerationmachines – 0.35MIPS,32Kx36bit memory – Vacuumtubes – 3.5milliondollars – Plugboards • Programmingviawiring • Batchingusedtomore • Usersweresimultaneously efficientlyusethe designers,engineers,and hardware programmers – Sharemachineamongst • “singleuser” manyusers • difficulttodebug(hardware) – Oneatatime – NoOperatingSystem – Debuggingapain • Drinkcoffeeuntiljobs finished 39 40

Batch System Issue: Keeping Batch Operating Systems Systems Busy • Readingtapesorpunchcardswastime • Sometimescalled“residentjobmonitor” consuming • ManagedtheHardware • ExpensiveCPUwasidlewaitingforinput • SimpleJobControlLanguage(JCL) – Loadcompiler – Compilejob – Runjob – Endjob • Noresourceallocationissues

– “oneuser” 41 42

7 Third Generation Systems - Multiprogramming Example Multiprogramming • Dividedmemoryamongseveral loadedjobs Memory • Whileonejobisloading,CPU worksonanother Job1 • Withenoughjobs,CPU100% busy Job2 • Needsspecialhardwareto isolatememorypartitionsfrom eachother Job3 – Thishardwarewasnotablyabsent onearlybatchsystems OS 43 44

Job turn-around time was Time sharing still an issue. • Batchsystemswerewellsuitedto • Eachuserhadhis/herownterminal – Scientificcalculations connectedtothemachine – Dataprocessing • Alluser’sjobsweremultiprogrammed • Forprogrammers,debuggingwasmuch – Regularlyswitchbetweeneachjob – Doitfast easieronolderfirstgen.machinesas theprogrammerhadthemachineto • Givestheillusionthattheprogrammer hasthemachinetohimself himself. • Earlyexamples:CompatibleTime • Wordprocessingonabatchsystem? SharingSystem(CTSS),MULTICS 45 46

The Advent of the PC An then… • LargeScaleIntegration(LSI)madesmall, • Furtherdevelopments(hardwareand fast(ish),cheapcomputerspossible software)resultedinimprovedtechniques, • OSsfollowedasimilarpathaswiththe concepts,andoperatingsystems.. mainframes – CAP,Hydra,Mach,UNIXV6,BSDUNIX,THE, – Simple“singleuser”systems(DOS) Thoth,Sprite,Accent,UNIXSysV,Linux,EROS, – Multiprogrammingwithoutprotection,(80286era, KeyKOS,OS/360,VMS,HPUX,ApolloDomain, Window3.1,95,98,ME,etc,MacOS<=9) Nemesis,L3,L4,CP/M,DOS,Exokernel,Angel, Mungi,BEOS,CacheKernel,Choices,V,Inferno, – “Real”operatingsystems(UNIX,WinNT,MacOS Grasshopper,MOSIX,Opal,SPIN,VINO,OS9, Xetc..) Plan/9,QNX,Synthetix,Tornado,xkernel, VxWorks,Solaris. 47 48

8 Operating System Time Line

Computer Hardware Review

Chapter1.4

49

Learning Outcomes Operating Systems

• Understandthebasiccomponentsof • Exploitthehardwareavailable computerhardware • Provideasetofhighlevelservicesthat – CPU,buses,memory,devicescontrollers, representorareimplementedbythe DMA,Interrupts,harddisks hardware. • Understandtheconceptsofmemory • Managesthehardwarereliablyand hierarchyandcaching,andhowthey efficiently affectperformance. • Understanding operating systems requires a basic understanding of the underlying hardware 51 52

Basic Computer Elements Basic Computer Elements • CPU – Performscomputations – Loaddatato/frommemoryviasystembus • Devicecontrollers – Controloperationoftheirparticulardevice – OperateinparallelwithCPU – Canalsoload/storetomemory(DirectMemoryAccess,DMA) – ControlregisterappearasmemorylocationstoCPU • OrI/Oports – SignaltheCPUwith“interrupts” • MemoryController – ResponsibleforrefreshingdynamicRAM – ArbitratingaccessbetweendifferentdevicesandCPU

53 54

9 The real world is logically similar, A Simple Model of CPU but a little more complex Computation • Thefetchexecutecycle

55 56

A Simple Model of CPU A Simple Model of CPU Computation Computation • StackPointer • Thefetchexecutecycle CPURegisters CPURegisters • StatusRegister – Loadmemorycontentsfrom – Conditioncodes addressinprogramcounter • Positiveresult PC:0x0300 (PC) PC:0x0300 • Zeroresult SP:0xcbf3 • Theinstruction SP:0xcbf3 • Negativeresult Status – Executetheinstruction Status • GeneralPurposeRegisters R1 – IncrementPC R1  – Holdsoperandsofmost – Repeat  instructions Rn Rn – Enablesprogrammersto minimisememoryreferences. 57 58

‘Safe’ registers and Privileged-mode Operation CPURegisters instructions • Toprotectoperatingsystem InterruptMask • Registersandinstructionsaresafeif execution,twoormoreCPU ExceptionType – Onlyaffectthestateoftheapplicationitself modesofoperationexist MMUregs – Privilegedmode(system, Others – Theycannotbeusedtouncontrollably kernelmode) PC:0x0300 interferewith • Allinstructionsandregistersare SP:0xcbf3 • Theoperatingsystem available Status • Otherapplications – Usermode R1 • Uses‘safe’subsetofthe – Theycannotbeusedtoviolateacorrectly instructionset  – E.g.nodisableinterrupts Rn implementedoperatingsystempolicy. instruction

• Only‘safe’registersare 59 60 accessible

10 Privileged-mode Operation I/O and Interrupts AddressSpace • I/Oevents(keyboard,mouse,incomingnetwork • Theaccessibilityof 0xFFFFFFFF packets)happenatunpredictabletimes Accessibleonly • HowdoestheCPUknowwhentoserviceanI/O addresseswithinan to event? addressspace Kernelmode changesdepending 0x80000000 onoperatingmode – Toprotectkernelcode Accessibleto anddata User and Kernelmode

0x00000000 61 62

Interrupts Interrupt Cycle • Aninterruptionofthenormalsequenceof execution • Processorchecksforinterrupts • Asuspensionofprocessingcausedbyanevent • Ifnointerrupts,fetchthenextinstruction externaltothatprocessing,andperformedin • Ifaninterruptispending,diverttothe suchawaythattheprocessingcanberesumed. interrupthandler • Improvesprocessingefficiency – Allowstheprocessortoexecuteotherinstructions whileanI/Ooperationisinprogress – Avoidsunnecessarycompletionchecking(polling)

63 64

Classes of Interrupts Interrupt Handler

• Programexceptions • Asoftwareroutinethatdeterminesthe (alsocalled synchronous interrupts ) natureoftheinterruptandperforms – Arithmeticoverflow whateveractionsareneeded. – Divisionbyzero – Executinganillegal/privilegedinstruction • Controlistransferredtothehandlerby – Referenceoutsideuser’smemoryspace. hardware . • Asynchronous(external)events • Thehandlerisgenerallypartofthe – Timer operatingsystem. – I/O

– Hardwareorpowerfailure 65 66

11 Memory Hierarchy Simple Interrupt • Goingdownthe hierarchy Application – Decreasingcostper UserMode bit – Increasingcapacity – Increasingaccess time – Decreasing KernelMode frequencyofaccess tothememorybythe processor Interrupt • Hopefully Handler • Principleoflocality!!!!! 67 68

Cache Memory Hierarchy WordTransfer BlockTransfer CPU Cache MainMemory • Roughapproximationofmemoryhierarchy Registers

• CacheisfastmemoryplacedbetweentheCPUandmainmemory – 1toafewcyclesaccesstimecomparedtoRAMaccesstimeoftens– hundredsofcycles • Holdsrecentlyuseddataorinstructionstosavememoryaccesses. • MatchesslowRAMaccesstimetoCPUspeedifhighhitrate • Ishardwaremaintainedand(mostly)transparenttosoftware • SizesrangefromfewkBtoseveralMB. • Usuallyahierarchyofcaches(2–5levels),on andoffchip. • Blocktransferscanachievehighertransferbandwidththansingle words. – Alsoassumesprobabilityofusingnewlyfetchdataishigherthanthe probabilityofreuseejecteddata.

69 70

Processor-DRAM Gap (latency) Moving-Head Disk Mechanism Proc 1000 CPU 60%/yr. “Moore’sLaw” 100 Processor-Memory Performance Gap: (grows 50% / year) 10 DRAM

Performance DRAM 7%/yr. 1 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 Time 71 72

Slide originally from Dave Patterson, Parcon 98

12 A Strategy: Avoid Waiting for Example Disk Access Times Disk Access • Diskcanread/writedatarelativelyfast • Keepasubsetofthedisk’sdatain – 15,000rpmdrive 80MB/sec memory – 1KBblockisreadin12microseconds cache • Accesstimedominatedbytimetolocatethe ⇒ Main memory acts as a of disk headoverdata contents – Rotationallatency • Halfonerotationis2milliseconds – Seektime • Fullinsidetooutsideis8milliseconds • Tracktotrack.5milliseconds • 2millisecondsis164KBin“lostbandwidth” 73 74

Two-level Memories and Hit Effective Access Time Rates • Givenatwolevelmemory, – cachememoryandmainmemory(RAM) – mainmemoryanddisk Teff = H × T1 + (1 − H) × (T1 + T2) T whatistheeffectiveaccesstime? 1 = access time of memory 1 T2 = access time of memory 2 H = hit rate in memory 1

• Answer:Itdependsonthehitrateinthe Teff = effective access time of system firstlevel.

75 76

Example • Cachememoryaccesstime1ns • Mainmemoryaccesstime10ns • Hitrateof95%

9 Teff = 0.95 × 1 × 10− + 9 9 0.05 × (1 × 10− + 10 × 10− ) 9 = 1.5 × 10−

77

13