Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
AnneBracy CS3410 ComputerScience CornellUniversity The slides were originally created by Deniz ALTINBUKEN. P&HChapter 4.9,pages445–452,appendix A.7 Towhatextentdoestheclickergradecomponent affectyourclassattendance? A) Theclickersdonotaffectmyclassattendance. B) Iattendthisclassslightlymoreoftenbecauseof theclickers. C) Iftherewerenoclickers,Iwouldbeherewayless often. D) Myclickerisansweringthisquestion,becausemy friendisholdingmyclicker.Iamstillinbed. E) Noneofthesedescribesme. 2 • Managesallofthesoftwareandhardware onthecomputer • Manyprocessesrunningatthesametime, requiringresources • CPU,Memory,Storage,etc. • TheOperatingSystemmultiplexes these resourcesamongstdifferentprocesses, andisolates andprotects processesfrom oneanother! 3 • OperatingSystem(OS)isatrustedmediator: • Safecontroltransferbetweenprocesses • Isolation(memory,registers)ofprocesses untrusted trusted P1 P2 P3 P4 VM filesystem net driver driver OS MMU CPU disk network card software hardware 4 Youarewhatyouexecute. Brain Personalities: hailstone_recursive MicrosoftWord Minecraft Linuxß yes,thisisjustsoftwarelike everyotherprogram thatrunsontheCPU Aretheyallequal? 5 • Onlytrusted processesshouldaccess& changeimportantthings • EditingTLB,PageTables,OScode,OS$sp, OS$fp… • Ifanuntrusted processcouldchangethe OS’$sp/$fp/$gp/etc.,OSwouldcrash! 6 CPUModeBitin ProcessStatusRegister • Manybitsaboutthecurrentprocess • Modebitisjustoneofthem • Modebit: • 0=usermode=untrusted: “Privileged”instructionsandregistersare disabledbyCPU • 1=kernelmode=trusted Allinstructionsandregistersareenabled 7 1. Bootsequence • loadfirstsectorofdisk(containingOScode)to predeterminedaddressinmemory • Modeß 1;PCß predeterminedaddress 2.OStakesover • initializesdevices,MMU,timers,etc. • loadsprogramsfromdisk,setsuppagetables,etc. • Modeß 0;PCß programentrypoint – UserprogramsregularlyyieldcontrolbacktoOS 8 Ifanuntrustedprocessdoesnothaveprivilegesto usesystemresources,howcanit • • • • Usethescreentoprint? Sendmessageonthenetwork? Allocatepages? Scheduleprocesses? Solution:SystemCalls 9 putc(): Printcharactertoscreen • Needtomultiplexscreenbetweencompeting processes send(): Sendapacketonthenetwork • Needtomanipulatetheinternalsofadevice sbrk(): Allocateapage • Needstoupdatepagetables&MMU sleep(): putcurrentprog tosleep,wakeother • Needtoupdatepagetablebaseregister 10 Systemcall:Notjustafunctioncall • Don’tletprocessjumpjustanywhereinOScode • OScan’ttrustprocess’registers(sp,fp,gp,etc.) SYSCALLinstruction: safecontroltransfertoOS MIPSsystemcallconvention: • Exceptionhandlersavestempregs,savesra,… • $v0=systemcallnumber,whichspecifiesthe operationtheapplicationisrequesting 11 CompilersdonotemitSYSCALLinstructions • Compilerdoesn’tknowOSinterface LibrariesimplementstandardAPIfromsystemAPI libc (standardClibrary): • • • • • • • gets()à getc() getc()à syscall sbrk()à syscall printf()à write() write()à syscall malloc()à sbrk() … 12 char *gets(char *buf) { while (...) { buf[i] = getc(); } } int getc() { asm("addiu $v0, $0, 4"); asm("syscall"); } 13 0xfffffffc systemreserved 0x80000000 0x7ffffffc stack dynamicdata(heap) 0x10000000 0x00400000 0x00000000 staticdata ?? gets code(text)getc systemreserved 14 Initsownaddressspace? – Syscallhastoswitchtoadifferentaddressspace – Hardtosupportsyscallargumentspassedaspointers ...So,NOPE Inthesameaddressspaceastheuserprocess? • Protectionbitspreventusercodefromwritingkernel • Higherpartofvirtualmemory • Lowerpartofphysicalmemory ...Yes,thisishowwedoit. 15 Allkerneltext&mostdata: • Atsamevirtualaddressin everyaddressspace 0xfffffffc OSStack 0x80000000 OSHeap OSData OSText 0x7ffffffc OSisomnipresent,availableto helpuser-levelapplications • Typicallyinhighmemory stack dynamicdata(heap) 0x10000000 staticdata 0x00400000 code(text) 0x00000000 systemreserved 16 VirtualMemory 0xfffffffc 0x80000000 0x7ffffffc OSStack OSHeap OSData OSText stack dynamicdata(heap) 0x10000000 staticdata 0x00400000 code(text) 0x00000000 systemreserved VirtualMemory OSStack 0x00...00 OSHeap OSData OSText 17 PhysicalMemory 0xfffffffc 0x80000000 0x7ffffffc systemreserved implementation of getc() syscall stack dynamicdata(heap) 0x10000000 0x00400000 0x00000000 staticdata gets code(text)getc systemreserved 18 WhichstatementisFALSE? A) OSmanagestheCPU,Memory,Devices,and Storage. B) OSprovidesaconsistentAPItobeusedbyother processes. C) TheOSkernelisalwayspresentonDisk. D) TheOSkernelisalwayspresentinMemory. E) AnyprocesscanfetchandexecuteOScodein usermode. 19 SYSCALL instructiondoesanatomicjumptoa controlledlocation(i.e.MIPS0x80000180) • • • • • • Switchesthesp tothekernelstack Savestheold(user)SPvalue Savestheold(user)PCvalue(=returnaddress) Savestheoldprivilegemode Setsthenewprivilegemodeto1 SetsthenewPCtothekernelsyscallhandler 21 Kernelsystemcallhandlercarriesoutthedesired systemcall • • • • • • • Savescallee-saveregisters Examinesthesyscallnumber Checksargumentsforsanity Performsoperation Storesresultinv0 Restorescallee-saveregisters Performsa“returnfromsyscall”(ERET)instruction, whichrestorestheprivilegemode,SPandPC 22 Anythingthatisn’tauserprogramexecutingits ownuser-levelinstructions. SystemCalls: • justonetypeofexceptionalcontrolflow • ProcessrequestingaservicefromtheOS • Intentional– it’sintheexecutable! 23 Trap Intentional Examples: System call (OS performs service) Breakpoint traps Privileged instructions Fault Unintentional but Possibly recoverable Examples: Division by zero Page fault Abort Unintentional Not recoverable Examples: Parity error 24 Exceptionprogramcounter(EPC) • 32-bitregister,holdsaddr ofaffectedinstruction • Syscallcase:AddressofSYSCALL Causeregister • Registertoholdthecauseoftheexception • Syscallcase:8,Sys SpecialinstructionstoloadTLB • Onlydo-ablebykernel 25 Precise Hardwareguarantees • • • • • Previousinstructionscomplete Laterinstructionsareflushed EPCandcauseregisterareset JumptoprearrangedaddressinOS Whenyoucomeback,restart instruction • Disableexceptionswhilerespondingtoone – OtherwisecanoverwriteEPCandcause 26 AKA Exceptions Hardware interrupts Asynchronous = caused by events external to CPU Software exceptions Synchronous = caused by CPU executing an instruction Maskable Can be turned off by CPU Unmaskable Cannot be ignored Example: alert from network device that a packet just arrived, clock notifying CPU of clock tick Example: alert from the power supply that electricity is about to go out 27 NoSYSCALL instruction.Hardware stepsin: • • • • • • • • SavesPCofexceptioninstruction(EPC) Savescauseoftheinterrupt/privilege(Causeregister) Switchesthesp tothekernelstack Savestheold(user)SPvalue Savestheold(user)PCvalue SYSCALL Savestheoldprivilegemode Setsthenewprivilegemodeto1 SetsthenewPCtothekernelsyscallhander interrupt/exceptionhandler 28 interrupt/exceptionhandlerhandlesevent Kernelsystemcallhandlercarriesoutsystemcall • • • • • • • all Savescallee-saveregisters Examinesthesyscallnumbercause Checksargumentsforsanity Performsoperation Storesresultinv0 all Restorescallee-saveregisters PerformsaERETinstruction(restorestheprivilege mode,SPandPC) 29 WhatothertaskrequiresbothHardwareand Software? A) VirtualtoPhysicalAddressTranslation B) BranchingandJumping C)Clearingthecontentsofaregister D)PipelininginstructionsintheCPU E)Whatareweeventalkingabout? 30 Virtualà physicaladdresstranslation! Hardware • hasaconceptofoperatinginphysicalorvirtualmode • helpsmanagetheTLB • raisespagefaults • keepsPageTableBaseRegister(PTBR)andProcessID Software/OS • managesPageTablestorage • handlesPageFaults • updatesDirtyandReferencebitsinthePageTables • keepsTLBvalidoncontextswitch: • FlushTLBwhennewprocessruns(x86) • Storeprocessid(MIPS) 32 I/ODevices:monitor,disk,keyboard,network, mouse,etc. Network Keyboard Disk Display 33 Modernsystemsseparatehigh-performanceprocessor, memory,displayinterconnectfromlower-performance interconnect Core0 Cache Core1 Cache HighPerformance Interconnect Memory Controller I/O Controller LowerPerformance LegacyInterconnect I/O Controller I/O Controller I/O Controller Disk Keyboard Network Memory Display Aside:Memory-MappedI/O 0xFFFFFFFF Virtual Address Space 0x00FFFFFF I/O Controller Physical Address Space I/O Controller Display Disk I/O Controller Keyboard I/O Controller Network 0x00000000 0x00000000 Less-favoredalternative=ProgrammedI/O: • SyscallinstructionsthatcommunicatewithI/O • Communicateviaspecialdeviceregisters ProgrammedI/O • • • • Requiresspecialinstructions Canrequirededicatedhardwareinterfacetodevices Protectionenforcedviakernelmodeaccesstoinstructions Virtualizationcanbedifficult Memory-MappedI/O • • • • Re-usesstandardload/storeinstructions Re-usesstandardmemoryhardwareinterface Protectionenforcedwithnormalmemoryprotectionscheme Virtualizationenabledwithnormalmemoryvirtualization scheme Howdoesprogramlearndeviceisready/done? 1.Polling: PeriodicallycheckI/Ostatusregister • Commoninsmall,cheap,orreal-timeembeddedsystems + Predictabletiming,inexpensive – WastesCPUcycles 2.Interrupts: DevicesendsinterrupttoCPU • • + – – Causeregisteridentifiestheinterruptingdevice Interrupthandlerexaminesdevice,decideswhattodo Onlyinterruptwhendeviceready/done ForcedtosaveCPUcontext(PC,SP,registers,etc.) Unpredictable,eventarrivaldependsonotherdevices’activity Whichoneisthewinner?Whichoneistheloser? 1.ProgrammedI/O:Deviceßà CPUßà RAM for(i =1..n) • CPUissuesreadrequest • Deviceputsdataonbus &CPUreadsintoregisters • CPUwritesdatatomemory CPU RAM DISK 2.DirectMemoryAccess(DMA):Deviceßà RAM • CPUsetsupDMArequest • for(i =1...n) Deviceputsdataonbus &RAMacceptsit • DeviceinterruptsCPUafterdone CPU RAM DISK Whichoneisthewinner?Whichoneistheloser? DiverseI/Odevicesrequirehierarchicalinterconnect whichismorerecentlytransitioningtopoint-to-point topologies. Memory-mappedI/Oisaneleganttechniqueto read/writedeviceregisterswithstandardload/stores. Interrupt-basedI/Oavoidsthewastedworkin polling-basedI/Oandisusuallymoreefficient. Modernsystemscombinememory-mappedI/O, interrupt-basedI/O,anddirect-memoryaccess tocreatesophisticatedI/Odevicesubsystems.