Anne Bracy CS 3410 - Home | Department of Computer · PDF file · 2017-08-20The...

Preview:

Citation preview

AnneBracyCS3410

ComputerScienceCornellUniversity

P&HChapter 4.9,pages445–452,appendixA.7

The slides were originally created by Deniz ALTINBUKEN.

• Managesallofthesoftwareandhardwareonthecomputer

• Manyprocessesrunningatthesametime,requiringresources• CPU,Memory,Storage,etc.

• TheOperatingSystemmultiplexes theseresourcesamongstdifferentprocesses,andisolates andprotects processesfromoneanother!

2

• OperatingSystem(OS)isatrustedmediator:• Safecontroltransferbetweenprocesses• Isolation(memory,registers)ofprocesses

3

P1 P2 P3 P4

VM filesystem net

driver driver

untrusted

disk networkcard

MMU CPU

trustedsoftware

hardware

OS

Youarewhatyouexecute.

Personalities:hailstone_recursiveMicrosoftWordMinecraftLinuxß yes,thisisjustsoftwarelike

everyotherprogramthatrunsontheCPU

Aretheyallequal?4

Brain

• Onlytrusted processesshouldaccess&changeimportantthings• EditingTLB,PageTables,OScode,OS$sp,

OS$fp…

• Ifanuntrusted processcouldchangetheOS’$sp/$fp/$gp/etc.,OSwouldcrash!

5

CPUModeBitin ProcessStatusRegister• Manybitsaboutthecurrentprocess• Modebitisjustoneofthem

• Modebit:• 0=usermode=untrusted:“Privileged”instructionsandregistersaredisabledbyCPU

• 1=kernelmode=trustedAllinstructionsandregistersareenabled

6

1. Bootsequence• loadfirstsectorofdisk(containingOScode)topredeterminedaddressinmemory

• Modeß 1;PCß predeterminedaddress

2.OStakesover• initializesdevices,MMU,timers,etc.• loadsprogramsfromdisk,setsuppagetables,etc.• Modeß 0;PCß programentrypoint

– UserprogramsregularlyyieldcontrolbacktoOS

7

Ifanuntrustedprocessdoesnothaveprivilegestousesystemresources,howcanit

• Usethescreentoprint?• Sendmessageonthenetwork?• Allocatepages?• Scheduleprocesses?

Solution:SystemCalls

8

putc(): Printcharactertoscreen• Needtomultiplexscreenbetweencompetingprocesses

send(): Sendapacketonthenetwork• Needtomanipulatetheinternalsofadevice

sbrk(): Allocateapage• Needstoupdatepagetables&MMU

sleep(): putcurrentprog tosleep,wakeother• Needtoupdatepagetablebaseregister

9

Systemcall:Notjustafunctioncall• Don’tletprocessjumpjustanywhereinOScode• OScan’ttrustprocess’registers(sp,fp,gp,etc.)

SYSCALLinstruction: safecontroltransfertoOS

MIPSsystemcallconvention:• Exceptionhandlersavestempregs,savesra,…• $v0=systemcallnumber,whichspecifiestheoperationtheapplicationisrequesting

10

CompilersdonotemitSYSCALLinstructions• Compilerdoesn’tknowOSinterface

LibrariesimplementstandardAPIfromsystemAPIlibc (standardClibrary):• gets()à getc()• getc()à syscall• sbrk()à syscall• printf()à write()• write()à syscall• malloc()à sbrk()• …

11

char *gets(char *buf) {while (...) {buf[i] = getc();

}}

int getc() {asm("addiu $v0, $0, 4");asm("syscall");

}

12

13

0xfffffffc

0x00000000

0x7ffffffc0x80000000

0x10000000

0x00400000

systemreserved

stack

systemreserved

code(text)

staticdata

dynamicdata(heap)

getsgetc

??

Initsownaddressspace?– Syscallhastoswitchtoadifferentaddressspace– Hardtosupportsyscallargumentspassedaspointers...So,NOPE

Inthesameaddressspaceastheuserprocess?• Protectionbitspreventusercodefromwritingkernel• Higherpartofvirtualmemory• Lowerpartofphysicalmemory...Yes,thisishowwedoit.

14

Allkerneltext&mostdata:• Atsamevirtualaddressin

everyaddressspace

OSisomnipresent,availabletohelpuser-levelapplications• Typicallyinhighmemory

15VirtualMemory

0xfffffffc

0x00000000

0x7ffffffc0x80000000

0x10000000

0x00400000

stack

systemreserved

code(text)

staticdata

dynamicdata(heap)

OSHeapOSData

OSStack

OSText

16VirtualMemory

OSTextOSDataOSHeap

OSStack

PhysicalMemory

0xfffffffc

0x00000000

0x7ffffffc0x80000000

0x10000000

0x00400000

stack

systemreserved

code(text)

staticdata

dynamicdata(heap)

OSHeapOSData

OSStack

OSText

0x00...00

17

0xfffffffc

0x00000000

0x7ffffffc0x80000000

0x10000000

0x00400000

systemreserved

stack

systemreserved

code(text)

staticdata

dynamicdata(heap)

getsgetc

implementation of getc() syscall

WhichstatementisFALSE?

A) OSmanagestheCPU,Memory,Devices,andStorage.

B) OSprovidesaconsistentAPItobeusedbyotherprocesses.

C) TheOSkernelisalwayspresentonDisk.D) TheOSkernelisalwayspresentinMemory.E) AnyprocesscanfetchandexecuteOScodein

usermode.18

SYSCALL instructiondoesanatomicjumptoacontrolledlocation(i.e.MIPS0x80000180)• Switchesthesp tothekernelstack• Savestheold(user)SPvalue• Savestheold(user)PCvalue(=returnaddress)• Savestheoldprivilegemode• Setsthenewprivilegemodeto1• SetsthenewPCtothekernelsyscallhandler

20

Kernelsystemcallhandlercarriesoutthedesiredsystemcall• Savescallee-saveregisters• Examinesthesyscallnumber• Checksargumentsforsanity• Performsoperation• Storesresultinv0• Restorescallee-saveregisters• Performsa“returnfromsyscall”(ERET)instruction,whichrestorestheprivilegemode,SPandPC

21

Anythingthatisn’tauserprogramexecutingitsownuser-levelinstructions.

SystemCalls:• justonetypeofexceptionalcontrolflow• ProcessrequestingaservicefromtheOS• Intentional– it’sintheexecutable!

22

23

TrapIntentionalExamples:System call

(OS performs service)Breakpoint trapsPrivileged instructions

AbortUnintentionalNot recoverableExamples:Parity error

FaultUnintentional butPossibly recoverableExamples:Division by zeroPage fault

Oneofmany ontology/terminologytrees.

Exceptionprogramcounter(EPC)• 32-bitregister,holdsaddr ofaffectedinstruction• Syscallcase:AddressofSYSCALL

Causeregister• Registertoholdthecauseoftheexception• Syscallcase:8,Sys

SpecialinstructionstoloadTLB• Onlydo-ablebykernel

24

PreciseHardwareguarantees• Previousinstructionscomplete• Laterinstructionsareflushed• EPCandcauseregisterareset• JumptoprearrangedaddressinOS• Whenyoucomeback,restart instruction

• Disableexceptionswhilerespondingtoone– OtherwisecanoverwriteEPCandcause

25

26

Hardware interruptsAsynchronous= caused by events external to CPU

Software exceptionsSynchronous= caused by CPU executing an instruction

MaskableCan be turned off by CPUExample: alert from network device that a packet just arrived, clock notifying CPU of clock tick

UnmaskableCannot be ignoredExample: alert from the power supply that electricity is about to go out

AKA Exceptions

NoSYSCALL instruction.Hardware stepsin:• SavesPCofexceptioninstruction(EPC)• Savescauseoftheinterrupt/privilege(Causeregister)• Switchesthesp tothekernelstack• Savestheold(user)SPvalue• Savestheold(user)PCvalue• Savestheoldprivilegemode• Setsthenewprivilegemodeto1• SetsthenewPCtothekernelsyscallhanderinterrupt/exceptionhandler

27

SYSCALL

28

Kernelsystemcallhandlercarriesoutsystemcallall

• Savescallee-saveregisters• Examinesthesyscallnumbercause• Checksargumentsforsanity• Performsoperation• Storesresultinv0• Restorescallee-saveregisters• PerformsaERETinstruction(restorestheprivilegemode,SPandPC)

interrupt/exceptionhandlerhandlesevent

all

WhatothertaskrequiresbothHardwareandSoftware?

A) VirtualtoPhysicalAddressTranslationB) BranchingandJumpingC)ClearingthecontentsofaregisterD)PipelininginstructionsintheCPUE)Whatareweeventalkingabout?

29

Virtualà physicaladdresstranslation!Hardware• hasaconceptofoperatinginphysicalorvirtualmode• helpsmanagetheTLB• raisespagefaults• keepsPageTableBaseRegister(PTBR)andProcessIDSoftware/OS• managesPageTablestorage• handlesPageFaults• updatesDirtyandReferencebitsinthePageTables• keepsTLBvalidoncontextswitch:

• FlushTLBwhennewprocessruns(x86)• Storeprocessid(MIPS) 31

1. TLBmiss2. Traptokernel3. WalkPageTable4. Findpageisinvalid5. Convertvirtual

addresstofile+offset6. Allocatepageframe

• Evictpageifneeded7. Initiatediskblockread

intopageframe

8. DiskinterruptwhenDMAcomplete

9. Markpageasvalid10. LoadTLBentry11. Resumeprocessat

faultinginstruction12. Executeinstruction

32

Recommended