interrupts and system calls - computer science · 2016. 7. 29. · • lab 1 due friday 2/5 ... 11...

48
CSE 506: Opera.ng Systems Interrupts and System Calls Don Porter CSE 506 1

Upload: others

Post on 29-Jan-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

  • CSE506:Opera.ngSystems

    InterruptsandSystemCalls

    DonPorterCSE506

    1

  • CSE506:Opera.ngSystems

    Housekeeping•  NextTuesday’sclasshasareadingassignment•  Lab1dueFriday2/5•  AllstudentsshouldhaveVMsandprivaterepossoon–  Alotofthelabisreading,soyoucangoaheadandstartiftheyarenotavailable

    2

  • CSE506:Opera.ngSystems

    LogicalDiagram

    MemoryManagement

    CPUScheduler

    User

    Kernel

    Hardware

    BinaryFormats

    Consistency

    SystemCalls

    Interrupts Disk Net

    RCU FileSystem

    DeviceDrivers

    Networking Sync

    MemoryAllocators Threads

    Today’sLecture

    3

  • CSE506:Opera.ngSystems

    Background:ControlFlow

    // x = 2, y = true if (y) {

    2 /= x; printf(x);

    } //...

    void printf(va_args) {

    //...

    }

    Regularcontrolflow:branchesandcalls(logicallyfollowssourcecode)

    pc

    4

  • CSE506:Opera.ngSystems

    Background:ControlFlow

    // x = 0, y = true if (y) {

    2 /= x; printf(x);

    } //...

    void handle_divzero(){

    x = 2;

    }

    Irregularcontrolflow:excepYons,systemcalls,etc.

    pc Dividebyzero!Programcan’tmake

    progress!

    5

  • CSE506:Opera.ngSystems

    Lecturegoal•  Understandthehardwaretoolsavailableforirregularcontrolflow.–  I.e.,thingsotherthanabranchinarunningprogram

    •  Buildingblocksforcontextswitching,devicemanagement,etc.

    6

  • CSE506:Opera.ngSystems

    Twotypesofinterrupts•  Synchronous:willhappeneveryYmeaninstrucYonexecutes(withagivenprogramstate)–  Dividebyzero–  Systemcall–  Badpointerdereference

    •  Asynchronous:causedbyanexternalevent–  UsuallydeviceI/O–  TimerYcks(well,clockscanbeconsideredadevice)

    7

  • CSE506:Opera.ngSystems

    Intelnomenclature•  Interrupt–onlyreferstoasynchronousinterrupts•  ExcepYon–synchronouscontroltransfer

    •  Note:fromtheprogrammer’sperspecYve,thesearehandledwiththesameabstracYons

    8

  • CSE506:Opera.ngSystems

    Lectureoutline•  Overview•  Howinterruptsworkinhardware•  Howinterrupthandlersworkinsoaware•  Howsystemcallswork•  Newsystemcallhardwareonx86

    9

  • CSE506:Opera.ngSystems

    Interruptoverview•  EachinterruptorexcepYonincludesanumberindicaYngitstype

    •  E.g.,14isapagefault,3isadebugbreakpoint•  Thisnumberistheindexintoaninterrupttable

    10

  • CSE506:Opera.ngSystems

    x86interrupttable

    0 255

    31

    … …

    47

    ReservedfortheCPU

    SoawareConfigurable

    DeviceIRQs 48=JOSSystemCall

    128=LinuxSystemCall

    11

  • CSE506:Opera.ngSystems

    x86interruptoverview•  Eachtypeofinterruptisassignedanindexfrom0—255.

    •  0—31areforprocessorinterrupts;generallyfixedbyIntel–  E.g.,14isalwaysforpagefaults

    •  32—255aresoawareconfigured–  32—47arefordeviceinterrupts(IRQs)inJOS

    •  Mostdevice’sIRQlinecanbeconfigured•  LookupAPICsformoreinfo(Ch4ofBovetandCesaY)

    –  0x80issuessystemcallinLinux(moreonthislater)

    12

  • CSE506:Opera.ngSystems

    Soawareinterrupts•  Theint instrucYonallowssoawaretoraiseaninterrupt–  0x80isjustaLinuxconvenYon.JOSuses0x30.

    •  Therearealotofspareindices–  YoucouldhavemulYplesystemcalltablesfordifferentpurposesortypesofprocesses!•  Windowsdoes:oneforthekernelandoneforwin32k

    13

  • CSE506:Opera.ngSystems

    Soawareinterrupts,cont•  OSsetsringlevelrequiredtoraiseaninterrupt–  Generally,userprogramscan’tissueanint 14 (pagefault)manually

    –  AnunauthorizedintinstrucYoncausesageneralprotecYonfault•  Interrupt13

    14

  • CSE506:Opera.ngSystems

    Whathappens(generally):•  Controljumpstothekernel–  Ataprescribedaddress(theinterrupthandler)

    •  Theregisterstateoftheprogramisdumpedonthekernel’sstack–  SomeYmes,extrainfoisloadedintoCPUregisters–  E.g.,pagefaultsstoretheaddressthatcausedthefaultinthecr2register

    •  Kernelcoderunsandhandlestheinterrupt•  Whenhandlercompletes,resumeprogram(seeiretinstr.)

    15

  • CSE506:Opera.ngSystems

    Howitworks(HW)•  HowdoesHWknowwhattoexecute?•  WheredoestheHWdumptheregisters;whatdoesituseastheinterrupthandler’sstack?

    16

  • CSE506:Opera.ngSystems

    Howisthisconfigured?•  KernelcreatesanarrayofInterruptdescriptorsinmemory,calledInterruptDescriptorTable,orIDT–  Canbeanywhereinmemory–  Pointedtobyspecialregister(idtr)

    •  c.f.,segmentregistersandgdtr andldtr

    •  Entry0configuresinterrupt0,andsoon

    17

  • CSE506:Opera.ngSystems

    x86interrupttable

    0 255

    31

    … …

    47

    idtr

    LinearAddressofInterruptTable

    18

  • CSE506:Opera.ngSystems

    x86interrupttable

    0 255

    31

    … …

    47

    idtr

    Code Segment: Kernel Code Segment Offset: &page_fault_handler //linear addr Ring: 0 // kernel Present: 1 Gate Type: Exception

    14

    19

  • CSE506:Opera.ngSystems

    InterruptDescriptor•  Codesegmentselector–  Almostalwaysthesame(kernelcodesegment)–  Recall,thiswasdesignedbeforepagingonx86!

    •  Segmentoffsetofthecodetorun–  Kernelsegmentis“flat”,sothisisjustthelinearaddress

    •  PrivilegeLevel(ring)–  RingthatcanraisethisinterruptwithanintinstrucYon

    •  Presentbit–disableunusedinterrupts•  Gatetype(interruptortrap/excepYon)–moreinabit

    20

  • CSE506:Opera.ngSystems

    x86interrupttable

    0 255

    31

    … …

    47

    idtr

    Code Segment: Kernel Code Segment Offset: &breakpoint_handler //linear addr Ring: 3 // user Present: 1 Gate Type: Exception

    3

    21

  • CSE506:Opera.ngSystems

    InterruptDescriptors,ctd.•  In-memorylayoutisabitconfusing–  Likealotofthex86architecture,manyinterfaceswerelaterdeprecated

    •  WorthcomparingCh9.5ofthei386manualwithinc/mmu.hintheJOSsourcecode

    22

  • CSE506:Opera.ngSystems

    Howitworks(HW)•  HowdoesHWknowwhattoexecute?–  Interruptdescriptortablespecifieswhatcodetorun

    •  Andatwhatprivilege(viacodesegment)–  Thiscanbesetuponceduringbootforthewholesystem

    •  WheredoestheHWdumptheregisters;whatdoesituseastheinterrupthandler’sstack?–  SpecifiedintheTaskStateSegment

    23

  • CSE506:Opera.ngSystems

    TaskStateSegment(TSS)•  Anothersegment,justlikethecodeanddatasegment–  AdescriptorcreatedintheGDT(cannotbeinLDT)–  Selectedbyspecialtaskregister(tr)–  Unlikeothers,hasahardware-specifiedlayout

    •  Lotsoffieldsforrarely-usedfeatures•  TwofeatureswecareaboutinamodernOS:–  1)LocaYonofkernelstack(fieldsss0/esp0)–  2)I/OPortprivileges(moreinalaterlecture)

    24

  • CSE506:Opera.ngSystems

    TSS,cont.•  Simplemodel:specifyaTSSforeachprocess–  Note:Only2^13entriesintheGDT

    •  OpYmizaYon(JOS):–  Ourkernelispreuysimple(uniprocessoronly)– WhynotjustshareoneTSSandkernelstackper-process?

    •  LinuxgeneralizaYon:–  OneTSSperCPU– ModifyTSSfieldsaspartofcontextswitching

    25

  • CSE506:Opera.ngSystems

    Summary•  Mostinterrupthandlinghardwarestatesetduringboot

    •  EachinterrupthasanIDTentryspecifying:– Whatcodetoexecute,privilegeleveltoraisetheinterrupt

    •  StacktousespecifiedintheTSS

    26

  • CSE506:Opera.ngSystems

    Comment•  Again,segmentaYonrearsitshead•  Youcan’tprogramOS-levelcodeonx86withoutgevngyourhandsdirtywithit

    •  Helpstoknowwhichfeaturesareimportantwhenreadingthemanuals

    27

  • CSE506:Opera.ngSystems

    Lectureoutline•  Overview•  Howinterruptsworkinhardware•  Howinterrupthandlersworkinso>ware•  Howsystemcallswork•  Newsystemcallhardwareonx86

    28

  • CSE506:Opera.ngSystems

    High-levelgoal•  Respondtosomeevent,returncontroltotheappropriateprocess

    •  Whattodoon:–  Networkpacketarrives–  DiskreadcompleYon–  Dividebyzero–  Systemcall

    29

  • CSE506:Opera.ngSystems

    InterruptHandlers•  Justplainoldkernelcode

    30

  • CSE506:Opera.ngSystems

    Example

    User Kernel

    Stack Stack

    if (x) { printf(“Boo”); ...

    printf(va_args…){

    ...

    Disk_handler (){ ...

    }

    RSP

    RIP

    RSP

    RIP

    DiskInterrupt!

    31

  • CSE506:Opera.ngSystems

    ComplicaYon:•  WhathappensifI’minaninterrupthandler,andanotherinterruptcomesin?–  Note:kernelstackonlychangesonprivilegelevelchange–  Nestedinterruptsjustpushthenextframeonthestack

    •  Whatcouldgowrong?–  Violatecodeinvariants–  Deadlock–  Exhaustthestack(iftoomanyfireatonce)

    32

  • CSE506:Opera.ngSystems

    Example

    User Kernel

    Stack Stack

    if (x) { printf(“Boo”); ...

    printf(va_args…){

    ...

    disk_handler (){ lock_kernel(); ... unlock_kernel();

    ...

    RSP

    RIP

    net_handler (){ lock_kernel(); …

    NetworkInterrupt!

    WillHangForever!AlreadyLocked!!!

    33

  • CSE506:Opera.ngSystems

    BouomLine:•  InterruptservicerouYnesmustbereentrantorsynchronize

    •  Period.

    34

  • CSE506:Opera.ngSystems

    Hardwareinterruptsync.•  WhileaCPUisservicinganinterruptonagivenIRQline,thesameIRQwon’traiseanotherinterruptunYltherouYnecompletes–  Bouom-line:deviceinterrupthandlerdoesn’thavetoworryaboutbeinginterruptedbyitself

    •  Adifferentdevicecaninterruptthehandler–  ProblemaYciftheysharedatastructures–  Likealistoffreephysicalpages…– Whatifbothtrytograbalockforthefreelist?

    35

  • CSE506:Opera.ngSystems

    Disablinginterrupts•  Anx86CPUcandisableI/Ointerrupts–  Clearbit9oftheEFLAGSregister(IFFlag)–  cliandstiinstrucYonsclearandsetthisflag

    •  Beforetouchingashareddatastructure(orgrabbingalock),aninterrupthandlershoulddisableI/Ointerrupts

    36

  • CSE506:Opera.ngSystems

    Gatetypes•  Recall:anIDTentrycanbeaninterruptoranexcepYongate

    •  Difference?–  AninterruptgateautomaYcallydisablesallotherinterrupts(i.e.,clearsandsetsIFonenter/exit)

    –  AnexcepYongatedoesn’t•  Thisisjustaprogrammerconvenience:youcoulddothesamethinginsoaware

    37

  • CSE506:Opera.ngSystems

    ExcepYons•  Youcan’tmaskexcepYons– Whynot?

    •  Can’tmakeprogressaaeradivide-by-zero–  DoubleandTriplefaultsdetectfaultsinthekernel

    •  DoexcepYonhandlersneedtobereentrant?–  Notifyourkernelhasnobugs(orsystemcallsinitself)–  Incertaincases,Linuxallowsnestedpagefaults

    •  E.g.,todetecterrorscopyinguser-providedbuffers

    38

  • CSE506:Opera.ngSystems

    Summary•  Interrupthandlersneedtosynchronize,bothwithlocks(mulY-processor)andbydisablinginterrupts(sameCPU)

    •  ExcepYonhandlerscan’tbemasked–  NestedexcepYonsgenerallyavoided

    39

  • CSE506:Opera.ngSystems

    Lectureoutline•  Overview•  Howinterruptsworkinhardware•  Howinterrupthandlersworkinsoaware•  Howsystemcallswork•  Newsystemcallhardwareonx86

    40

  • CSE506:Opera.ngSystems

    Systemcall“interrupt”•  Originally,systemcallsissuedusingintinstrucYon•  DispatchrouYnewasjustaninterrupthandler•  Likeinterrupts,systemcallsarearrangedinatable–  Seearch/x86/kernel/syscall_table*.SinLinuxsource

    •  Programselectstheoneitwantsbyplacingindexineaxregister–  ArgumentsgointheotherregistersbycallingconvenYon–  Returnvaluegoesineax

    41

  • CSE506:Opera.ngSystems

    Lectureoutline•  Overview•  Howinterruptsworkinhardware•  Howinterrupthandlersworkinsoaware•  Howsystemcallswork•  Newsystemcallhardwareonx86

    42

  • CSE506:Opera.ngSystems

    AroundP4era…•  Processorsgotverydeeplypipelined–  Pipelinestalls/flushesbecameveryexpensive–  Cachemissescancausepipelinestalls

    •  SystemcallstooktwiceaslongfromP3toP4– Why?–  IDTentrymaynotbeinthecache–  DifferentpermissionsconstraininstrucYonreordering

    43

  • CSE506:Opera.ngSystems

    Idea•  WhatifwecachetheIDTentryforasystemcallinaspecialCPUregister?–  NomorecachemissesfortheIDT!– MaybewecanalsodomoreopYmizaYons

    •  AssumpYon:systemcallsarefrequentenoughtobeworththetransistorbudgettoimplementthis– Whatelsecouldyoudowithextratransistorsthathelpsperformance?

    44

  • CSE506:Opera.ngSystems

    AMD:syscall/sysret•  TheseinstrucYonsuseMSRs(machinespecificregisters)tostore:–  Syscallentrypointandcodesegment–  Kernelstack

    •  Adrop-inreplacementforint 0x80•  Everyoneloveditandadopteditwholesale–  EvenIntel!

    45

  • CSE506:Opera.ngSystems

    Aaermath•  Getpid()onmydesktopmachine(recentAMD6-core):–  Int80:371cycles–  Syscall:231cycles

    •  Sosystemcallsaredefinitelyfasterasaresult!

    46

  • CSE506:Opera.ngSystems

    InJOS•  YouwillusetheintinstrucYontoimplementsystemcalls

    •  Thereisachallengeprobleminlab3(i.e.,extracredit)tousesystenter/sysexit–  Notethattherearesomemoredetailsaboutregistersavingtodealwith

    –  Syscall/sysretisabittootrivialforextracredit•  ButsYllcoolifyougetitworking!

    47

  • CSE506:Opera.ngSystems

    Summary•  InterrupthandlersarespecifiedintheIDT•  Understandwhennestedinterruptscanhappen–  Andhowtopreventthemwhenunsafe

    •  UnderstandopYmizedsystemcallinstrucYons–  Beabletoexplainsyscallvs.int80

    48