+ All Categories
Home > Documents > Final Review - University of California, San...

Final Review - University of California, San...

Date post: 26-Sep-2020
Category:
Upload: others
View: 1 times
Download: 0 times
Share this document with a friend
97
Final Review CSE 120: Principles of Opera:ng Systems UC San Diego: Summer Session I, 2009 Frank Uyeda
Transcript
Page 1: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

FinalReviewCSE120:PrinciplesofOpera:ngSystems

UCSanDiego:SummerSessionI,2009FrankUyeda

Page 2: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Announcements

•  Project3milestonetonight•  Project3dueonMonday8/3atmidnight.

– HardDeadline!– Noexcep:ons,slipdays,etc.

•  Finaltomorrow(Saturday)from3p‐5p.– Youwillhave2hourstocompletethetest.– Coverseverythingwe’vetalkedabout(exceptSecurity,RAID&Logfilesystems)

2

Page 3: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PeerWise

•  Whichtypeofdiskschedulingservicesrequestsinonedirec:on,thenreversesandservicesrequestsintheotherdirec:on?– FIFO– SSTF– SCAN– C‐SCAN

3

Page 4: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PeerWise

•  RAIDis– Onlyafilesystem

– Afilesystemandastoragesystem– Onlyastoragesystem– Neitherafilesystem,norastoragesystem

4

Page 5: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ContentfortheFinal

•  RoleofanOpera:ngSystem•  ConcurrencyandSynchroniza:on

– Whatarethechallengestosupportmul:tasking?•  CPUScheduling

– WhogetstheCPUandwhendotheygetit?•  MemoryManagement

–  Howdoprogramssharefinitememory?•  FileSystemsandStorageManagement

–  Howisdatastoredandwhathappenswhenthingsfail?•  Selec:onofSpecialTopics(:mepermicng)

–  Security,VirtualMachineMonitors,…..

5

Page 6: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PhysicalDiskStructure

•  Diskcomponents–  Plafers(2surfaces)–  Tracks–  Sectors–  Cylinders– Arm– Heads(1perside)

•  Logically,diskbrokendownintosectors– Addressedbycylinder,head,sector

6

Arm Heads Plafers

Cylinder

TopView

Track

Sector

Page 7: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DiskPerformance

•  Diskrequestperformancedependsupon…..–  I/Orequestoverhead:issuingthecommandtothedisk

•  Processfileaccesstrapsintokernel,whichneedstoissuehwrequest–  Seek:movingthediskarmtothecorrectcylinder

•  Dependsonhowfastthediskarmcanmove(increasingveryslowly)–  Rota:on:wai:ngforthesectortorotateunderthehead

•  Dependsuponrota:onrateofdisk(increasing,butslowly)–  Transfer:transferringdatafromsurfaceintodiskcontroller

electronics,sendingitbacktothehost•  Dependsondensity(increasingquickly)•  Fasterfortracksneartheouteredgeofthedisk–why?

•  TheOStriestominimizethecostofallofthesesteps–  Par:cularlyseeksandrota:on(why?)

7

Page 8: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DiskScheduling

•  Becauseseeksaresoexpensive(milliseconds!),ithelpstoschedulediskrequeststhatarequeuedwai:ngforthedisk–  FCFS/FIFO(donothing)

•  Reasonablewhenloadislow•  Longwai:ng:mesforlongrequestqueues

–  SSTF(shortestseek:mefirst)•  Minimizearmmovement(seek:me),maximizerequestrate•  Favorsmiddletracks

–  SCAN(elevator)•  Servicerequestsinonedirec:onun:ldone,thenreverse•  Discriminatesagainstthehighestandlowesttracks

–  C‐SCAN•  LikeSCAN,butonlygoinonedirec:on(typewriter)•  Reducevarianceinseek:mes

8

Page 9: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DiskLayoutStrategies

Con:guousalloca:on•  Idea:Allocatespaceforfilelike

doneforcon:guousmemoryorganiza:on

•  Pros:Fastfileaccess

•  Cons:Fragmenta:on,needscompac:on–  Whathappenswhenyou

needtogrow?

v

DiskBlocks

Disk

File

9

Page 10: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DiskLayoutStrategies

LinkedAlloca:on•  Idea:Linkedlistofblocks,

eachpoin:ngtonext

•  Pros:Easytogrow;fastsequen:alaccess

•  Cons:Slownon‐sequen:alaccess;whathappensifyouhaveonebadblock?

v

DiskBlocks

Disk

File

10

Page 11: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DiskLayoutStrategies

IndexedAlloca:on•  Idea:Storeorderedlist

ofblockpointers

•  Pros:Goodforrandomaccess,notbadforsequen:al

•  Cons:Sizelimit,notasfastforsequen:alaccess

v

DiskBlocks

Disk

File

11

Page 12: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

UnixInodes

•  Unixusesanindexedalloca:onstructure–  Aninode(indexnode)storesbothmetadata

andthepointerstodiskblocks•  Metadataisinforma:onaboutthefile(protec:on,:mestamp,length,refcount,etc….)

•  Eachinodecontains15blockpointers–  First12aredirectblocks

(e.g.,4KBdiskblocks)–  Thensingle,double,triple

indirectblocks Metadata

01

121314

DiskDataBlocks

?? 12

Page 13: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DirectoryInternals

•  Adirectoryisalistofentries–  <name,loca:on>

–  Nameisjustthenameofthefileordirectory–  Loca:ondependsuponhowfileisrepresentedondisk

•  Listisusuallyunordered(effec:velyrandom)–  Entriesusuallysortedbyprogramthatreadsdirectory

•  Directoriestypicallystoredinfiles–  Onlyneedtomanageonekindofsecondarystorageunit

13

Page 14: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ResolvingFileLoca:on/Data

•  Inodesdescribewhereondisktheblocksforafileareplaced–  Unixinodesarenotdirectories–  Directoresarerepresentedinternallyasfiles

•  Whatdoesthismeanforhowinodesarestored?

•  Directoryentriesmapfilenamestoinodes–  Wanttoaccess“/foo”

DataforFooisinhere

firstdatablockforfile“/foo”

inodeforfile“/foo”

Inode18Metadata

0

12

inodefordirectory“/”

Inode0Metadata

0

12

foo,18bar,451baz,123…

firstdatablockfordirectoryfile“/”

14

Page 15: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DataandInodePlacementProblem

•  OriginalUnixFShadtwoplacementproblems:– Datablocksallocatedrandomlyinagingfilesystems–  Inodesallocatedfarfromblocks

•  BSDFFSSolu:on:CylinderGroups– Diskpar::onedintogroupsofcylinders– Datablocksinsamefileallocatedinsamecylinder–  Filesinsamedirectoryallocatedinsamecylinder–  Inodesforfilesallocatedinsamecylinderasfiledatablocks

15

Page 16: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

MaximumFileSize:4KBBlocks•  RecallUnixinodeshave:

–  12directblocks–  1singleindirectblock,1doubleindirectblock,

1tripleindirectblock•  Howlargecanafilebewith4KBblocks?•  Singleindirectblock:

–  Assuming32‐bitaddresses,wehave4bytesperblockpointer,so4KB/4=1024Bblocks

–  So…1024*1KB=1MB•  Double‐indirectblock:

–  1024*1024*1KB=1GB•  TripleIndirectblock:

–  1024*1024*1024*1KB=1TB•  Total:~1TB

16

Page 17: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

VirtualAddresses•  Processesaccessmemoryusingavirtualaddress

–  ThevirtualaddressisnotthesameasthephysicalRAMaddressinwhichitresides–  TheOS(hardwareMMU)translatesthevirtualaddressintothephysicalRAMaddress–  Whodeterminesthemappingforthetransla:on?

17

Stack

Heap

DataSegment

TextSegment

SP

PC0x00…….(Star:ngAddress)

0xFFF…..(EndingAddress)

AddressSpace

Stack

Heap

DataSegment

TextSegment

PhysicalMemory

MMU

…..

VirtualMemory

Page 18: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

VirtualMemory

•  Virtualmemoryenablesprogramstoexecutewithoutrequiringtheiren:readdressspaceresideinphysicalmemory

–  Savesspace•  Manyprogramsdonotneedalloftheircodeanddataatonce(orever),sothereisnoneedtoallocatememoryforit

–  Allowsflexibilityforapplica:onandOS•  Indirec:onallowsmovingprogramsaroundinmemory;OScanadjustamountofmemoryallocatedbaseduponitsrun‐:mebehavior

•  Allowsprocessestoaddressmoreorlessmemorythanphysicallyinstalledinthemachine

–  Isola:onandprotec:on•  Oneprocesscannotaccessmemoryaddressesinothers

•  Excep:on:sharedmemory,whichwe’vealreadycovered18

Page 19: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

MemoryManagementRequirements

•  Protec:on–  Restrictwhichphysicaladdressesprocessescanuse,sotheycan’tstomponeachother

•  Fasttransla:on–  Accessingmemorymustbefast,regardlessoftheprotec:onscheme

•  Fastcontextswitching–  Overheadofupda:ngmemoryhardwareonacontextswitchmustbelow

•  Requireshardwaresupportforefficientimplementa:on

19

Page 20: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

MemoryAlloca:on

20

•  Howshouldweallocatememorytoprocesses?

PhysicalMemory

MMU

Page 21: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

FixedPar::ons

21

P1

P2

P3

P4

P5

PhysicalMemory

BaseRegisterP4’sBase

VirtualAddressOffset +

•  Physicalmemoryisbrokenupintofixedpar::ons–  Hardwarerequirements:baseregister

–  Physicaladdress=virtualaddress+baseregister

Page 22: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

VariablePar::ons

22

P1

P2

P3

PhysicalMemoryBaseRegister

P4’sBase

VirtualAddressOffset +

LimitRegisterP3’sBase

<Yes?

No?

Protec:onFault

Page 23: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Paging

•  Pagingsolvestheexternalfragmenta:onproblembyusingfixedsizedunitsinbothphysicalandvirtualmemory

23

Page1

Page2

Page3

Page4

Page5

PhysicalMemory

Page1

Page2

PageN

VirtualMemory

…..

Page 24: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Paging

2424

Page1

Page2

Page3

PageP

PhysicalMemoryPage1

Page2

Process1’sVAS

…..

0x00000000

0x00040000

0x00000400

...

PageN

..

PageM

Page3

…..

Page1

Page2

Process2’sVAS

PageQ

Page3

MMU

TLB

PageTable

V PageFrame

1 0x04

1 0x01

1 0x05

1 0x07

V PageFrame

1 0x04

1 0x01

1 0x05

1 0x07

Page 25: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Recap:VirtualMemory

•  MemoryManagementUnit(MMU)–  Hardwareunitthattranslatesavirtualaddresstoaphysicaladdress

•  Transla:onTable–  Storedinmainmemory–  EachPageTableEntrystorespermissionandbookkeepingbits.

•  Transla:onLookasideBuffer(TLB)–  HardwarecachefortheMMU’svirtual‐to‐physicaltransla:onstable

25

CPUTransla:on

TableMMU

Memory

VirtualAddress

PhysicalAddress

TLB

PageFrameNumberProtVRM

Page 26: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Recap:PageTables

26

Page1

Page2

Page3

PageN

PhysicalMemory…..

Pageframe Offset

PhysicalAddress

Pagenumber Offset

VirtualAddress

Pagetableentry

PageTable

0xFFFFFFFF

0x00000000

Problem:PageTablescanbelarge!

Page 27: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Recap:2LevelPageTable

27

Page1

Page2

Page3

PageN

PhysicalMemory…..

Pageframe Offset

PhysicalAddress

Secondary Offset

VirtualAddress

SecondaryPageTable(s)

0xFFFFFFFF

0x00000000

Master

Pagetableentry

MasterPageTable

Pageframe(PTE)Pageframe(PTE)

Page 28: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

InvertedPageTable

28

Page1

Page2

Page3

PageN

PhysicalMemory…..

index Offset

PhysicalAddress

VPN Offset

VirtualAddress

0xFFFFFFFF

0x00000000

PID

<PID,VPN>

InvertedPageTable

index

Page 29: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

InvertedPageTable

•  Oneglobalpagetable–  Onepagetableentryperphysicalpage.–  EntrieskeyedbyPIDandvirtualpagenumber.–  Physicalframenumber=indexinpagetable.

•  Advantages–  Boundedamountofmemoryforpagetable(s).

•  32‐bitaddressspace,4Kpages,4GBRAM,4BperPTE•  1‐levelpagetable:_____x#processes.•  InvertedTable:______MB

•  Disadvantages–  Costlytransla:on

•  Usinghashingcanhelp

29

Page 30: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Recap:Segmenta:on

30

Heap

Text

Data

Stack

Page 31: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Recap:Segmenta:on

31

PhysicalMemorySegmentTable

limit baseVirtualAddress

Segment# Offset

< +Yes?

No?

Protec:onFault

Page 32: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PagingvsSegmenta:onConsidera<on Paging Segmenta<on

Needtheprogrammerbeawarethatthistechniqueisbeingused?

Howmanylinearaddressspacesarethere?

Canthetotaladdressspaceexceedthesizeofphysicalmemory?

Canproceduresanddatabedis:nguishedandseparatelyprotected?

Issharingofproceduresbetweenusersfacilitated?

32Note:ImageadaptedfromTanenbaum,MOS3/e

Page 33: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

MemoryManagementReview

•  Forwhichofthefollowingdoweneedtosplitavirtualaddressintomul:pleparts?–  A)PurePaging–  B)PureSegmenta:on–  C)FixedPar::ons–  D)VariablePar::ons–  E)Alloftheabove–  F)Noneoftheabove

33

0x0A15D 121

VPN Offset

0x0A15D121

VirtualAddress

i.e.

Page 34: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DemandPagingExampleProcess’sVirtualAddressSpace PhysicalMemory

/swap~/program.coff

Disk

PC

PC

0x00 1 0x000x01 0 ‐‐‐0x02 0 ‐‐‐0x03 0 ‐‐‐

0x11 0 ‐‐‐0x10 0 ‐‐‐

VPN V PPNPageTable

0x01 1 0x01

34

Page 35: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DemandPagingExampleProcess’sVirtualAddressSpace PhysicalMemory

/swap~/program.coff

Disk

PC

0x00 1 0x000x01 0 ‐‐‐0x02 1 0x020x03 1 0x03

0x11 0 ‐‐‐0x10 1 0x09

VPN V PPNPageTable

0x01 1 0x01

0x10 0 0x00??

0x04 1 0x09

0x00

0x090x0A

35

Page 36: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Review:DemandPaging

•  MemoryManagementUnit(MMU)–  Hardwareunitthattranslatesavirtualaddresstoaphysicaladdress

•  Transla:onTable–  Storedinmainmemory

•  Transla:onLookasideBuffer(TLB)–  HardwarecachefortheMMU’svirtual‐to‐physicaltransla:onstable

36

CPUTransla:on

TableMMU

Memory

VirtualAddress

PhysicalAddress

TLB

PageFaultshandledsilentlybyOS

PageFault

Disk

Page 37: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PageFaults

•  Whathappenswhenaprocessaccessesapagethathasbeenevicted(orisotherwisenotinmemory)?–  1.Whenitevictsapage,theOSsetsthePTEasinvalidand

storestheloca:onofthepageintheswapfileinthePTE–  2.Whenaprocessaccessesthepage,theinvalidPTEwill

causeatrap(pagefault)–  3.ThetrapwillruntheOSpagefaulthandler–  4.HandlerusestheinvalidPTEtolocatepageinswapfile–  5.Readspageintoaphysicalframe,updatesPTEtopointtoit–  6.Restartsprocess

•  Butwheredoesitputit?Hastoevictsomethingelse–  OSusuallykeepsapooloffreepagesaroundsothatalloca:ons

donotalwayscauseevic:ons

37

Page 38: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Example

•  AssumeweareusingPagingand:– Memoryaccess=5us–  TLBsearch=500ns

•  Whatistheavg.memoryaccess:mewithouttheTLB?•  Whatistheavg.memoryaccess:mewith50%TLBhitrate?•  Whatistheavg.memoryaccess:mewith90%TLBhitrate?

38

CPUTransla:on

TableMMU

Memory

VirtualAddress

PhysicalAddress

TLB

Page 39: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PageSharingEmacsbuffer#1

PhysicalMemory

0x00 1 0x03

0x01 0 ‐‐‐0x10 1 0x120x11 1 0x15

VPN V PPN

0x03 1 0x11

0x00 1 0x03

0x01 0 ‐‐‐0x10 1 0x140x11 1 0x16

VPN V PPN

0x03 1 0x13

Emacsbuffer#2

..

Whatifsharedpageismodified?

0x04

39

Page 40: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Copy‐On‐Write

•  OSesspendalotof:mecopyingdata–  Systemcallargumentsbetweenuser/kernelspace–  En:readdressspacestoimplementfork()

•  UseCopy‐on‐Write(CoW)todeferlargecopiesaslongaspossible,hopingtoavoidthemaltogether–  Insteadofcopyingpages,createsharedmappingsofparentpagesinchildvirtualaddressspace

–  Sharedpagesareprotectedasread‐onlyinchild•  Readshappenasusual•  Writesgenerateaprotec:onfault,traptoOS,copypage,changepagemappinginclientpagetable,restartwriteinstruc:on

40

Page 41: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PageSharing:CoWEmacsbuffer#1

PhysicalMemory

0x00 1 0x03

0x01 0 ‐‐‐0x10 1 0x120x11 1 0x15

VPN V PPN

0x03 1 0x11

Emacsbuffer#2

..

0M

000

0x00 1 0x03

0x01 0 ‐‐‐0x10 1 0x120x11 1 0x16

VPN V PPN

0x03 1 0x13

0M

000

BuffersshareVPN0x12Processwritestopage

1

41

Page 42: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PageSharing:CoWEmacsbuffer#1

PhysicalMemory

0x00 1 0x03

0x01 0 ‐‐‐0x10 1 0x120x11 1 0x15

VPN V PPN

0x03 1 0x11

Emacsbuffer#2

..

0M

000

0x00 1 0x03

0x01 0 ‐‐‐0x10 1 0x140x11 1 0x16

VPN V PPN

0x03 1 0x13

0M

000

BuffersshareVPN0x12ProcesswritestopageNewpageisallocated

42

Page 43: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Locality

•  Allpagingschemesdependonlocality–  Processesreferencepagesinlocalizedpaferns

•  Temporallocality–  Loca:onsreferencedrecentlylikelytobereferencedagain

•  Spa:allocality–  Loca:onsnearrecentlyreferencedloca:onsarelikelytobereferencedsoon

•  Althoughthecostofpagingishigh,ifitisinfrequentenoughitisacceptable–  Processesusuallyexhibitbothkindsoflocalityduringtheirexecu:on,makingpagingprac:cal

43

Page 44: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PageReplacementSummary

•  Pagereplacementalgorithms–  Belady’s

•  Replacepageusedfarthestinthefuture•  op:malreplacement(min#faults)

–  FIFO•  replacepageloadedfurthestinpast•  Belady’sanomaly

–  LRU•  replacepagereferencedfurthestinpast

–  LRUClock•  replacepagethatis“oldenough”

44

Page 45: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PageReplacementSummary

•  Globalvslocalreplacementpolicies– Shouldaprocessreplaceitsownpage,orthatofanother?

•  WorkingSet–  keepthesetofpagesinmemorythathasminimalfaultrate(the“workingset”)

– PageFaultFrequency–grow/shrinkpagesetasafunc:onoffaultratetoavoidthrashing

45

Page 46: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PFFandMul:programming•  Whatdoesthepagefaultfrequencyofprocessestellyou?

Degreeofmul:programming(#concurrentprocesses)

Thrashing!

System“goodput”(#ofprograms’instruc:onsexecuted)

46

Page 47: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

WhatisanOpera:ngSystem?

Applica:ons

Opera:ngSystems

Hardware

)

VM

Abstrac:onstoeaseapplica:ondevelopmentManageresourceaccessamongapplica:ons

47

Page 48: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

TypesofHardwareSupport

•  Protec:on–  OSwantstocontrolhardwareaccess–  OSwantstokeeppar:culardata(registers,memory)privateandisolated

•  Eventhandling–  OSneedstobeawareofexternalevents–  OSneedsawaytorespondtoexternalevents

•  Performanceimprovements–  Commonlyusedthreadsynchroniza:onprimi:ves

– Memoryaccess/Diskaccessspeed‐ups

48

Page 49: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Suppor:ngPrivilegedInstruc:ons

•  HowdoesanOSorCPUuseprotec:onlevels?–  ThereisaspecialregisterontheCPUindica:ngthemode

–  CPUchecksmodebitwhenexecu:ngprivilegedinstruc:ons

– Userprogramsexecuteinusermode

– OSexecutesinkernelmode•  Fornow,thinkofthekernelasequivalenttoanOS

49

Page 50: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Events

•  Twotypesofevents–  Interrupts:causedbyexternalevent–  Excep:ons:causedbyaninstruc:on

•  Eventscanbe:–  Unexpected–  Deliberate

Unexpected Deliberate

Excep<on(sync) Fault Syscalltrap

Interrupt(async) Interrupt So}wareInterrupt

50

Page 51: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SystemCalls

•  Applica:oninvokesasystemcalltoexecuteaprivilegedopera:on– Raisesanexcep:on,whichinvokeskernelhandler– Passesparameterstohandler

•  PredefinedSystemCallcode,anyotherarguments…

– Kernelhandlerdoestherest•  savescallercontext(state)•  callspropersystemcallrou:ne•  restorescalledstateandreturns

51

Page 52: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Concurrency

•  Uniprogramming– OSrunsasinglejobun:litiscompleted.

•  Mul:programming– OShasaqueueofjobs–  Selectsonejobtorun–  IfthejobhastowaitforI/Oorhasrunforawhile,theOSsavesitsstateandputsitbackintothequeue.

–  Repeatlast2stepsun:lalljobscomplete.

52

Page 53: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

WhatisinaProcess?

•  ProgramInforma:on–  Addressspace,Code,Data,Stack,Registers(SP,PC,FP,..)

•  Opera:ngSystemresources–  Openfiles,opennetworksockets

•  Execu:onstate–  Running:currentlyusingtheCPU–  Ready:readytousetheCPU(wai:ngforit)

•  AnotherprocesshasCPU– Wai:ng:wai:ngforanevent(nottheCPU)suchasI/O

•  Cannotmakeprogressun:lsignaled

53

Page 54: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ContextSwitchTwoprocesses:P0andP1

TheOSconsumesafairamountofprocessing:me

This:meisreferredtoascontextswitchingoverhead

Toomuchcontextswitchingoverheadisabadthing(why?)

Note:imagecourtesyofSilberschatz,200554

Page 55: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SchedulingQueuesTheOSkeepstrackofnon‐runningprocessesinschedulingqueues

head

tail

ReadyqueueFirefoxPCB XServerPCB IdlePCB

head

tail

DiskI/OPCBEmacsPCB BashPCB

TerminalPCBTheremaybemanywaitqueues

• seeNachos.threads.ThreadedQueue 55

Page 56: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ProcessCrea:oninUnix

•  fork()systemcallisusedtocreateanewprocessint fork() –  Createsandini:alizesanewPCB–  Createsanewaddressspace–  Fillschild’saddressspacewithacopyoftheparent’sen:re

addressspace–  Ini:alizeskernelresourcestopointtoparent’s–  PutsPCBonthereadyqueue

•  So…..howdoweknowwhichoneiswhich?–  EachprocesshasadifferentPID–  fork()returnstwice:

•  child’sPIDtotheparent•  “0”tothechild

56

Page 57: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Unixfork()exampleint main(int argc, char *argv[]) { char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) { printf(“Child of %s is %d\n”, name, getpid()); return 0; } else { printf(“My child is %d\n”, child_pid); return 0; { }

Whatdoesthisprogramprint?

Note:ThisexamplecourtesyofAlexSnoeren57

Page 58: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SharedMemoryvs.MessagePassing

ProcessA

ProcessB

PhysicalMemory

Kernel

helloworld

helloworld(stdout)

shared_mem

ProcessA

ProcessB

Kernel

PhysicalMemory

58

Page 59: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

InterprocessCommunica:on

•  Eachcoopera:ngmustknowthenameoftheother•  SharedMemory

–  Canperformfrequentandlargetransfers– Mustsynchronize

•  MessagePassing–  Noexplicitneedforsynchroniza:on

•  Handledbyread(),write()syscalls.–  Kerneloverheadpermessage

•  Othercommonvaria:onsofIPC–  Unixpipes(e.g.,“ls|wc”)– WindowsLocalProcedureCalls(LPCs)

59

Page 60: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Threads

•  Separatetheconceptofaprocessfromitsexecu:onstate–  Process:addressspace,privileges,resources–  Execu:onstate:registers,PC,SP,FP

•  Execu:onstateiscalledathreadofcontrol–  Eachthreadbelongstoaprocess–  Eachprocesshasatleastonethread–  Threadsaretheunitsofscheduling(sortof)

•  CPUrunsonethreadata:me•  Threadsexecutewithinthecontextofaprocess

60

Page 61: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ThreadinaProcess

Stack

Heap

DataSegment

TextSegment

SP1

PC1

0x00…….(Star:ngAddress)

0xFFF…..(EndingAddress)

AddressSpace

61

Page 62: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ThreadsinaProcess

Stack(Thread1)

Heap

DataSegment

TextSegment

SP1

PC1

0x00…….(Star:ngAddress)

0xFFF…..(EndingAddress)

AddressSpace

Stack(Thread2)

Stack(Thread3)

SP2

SP3

PC2PC3

Thread3Thread2

Thread1

62

Page 63: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Mul:‐processWebServer

while (1) { int sock = accept(); if ((child_pid = fork())== 0) { Handle client request

Close socket and exit } else { Close socket } }

Usingfork()forconcurrency Before

A}er

63

Page 64: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Mul:‐threadedWebServer

… while (1) { int sock = accept(); thread_fork(handle_req, sock); } }

handle_req(int sock) { Handle client request close(sock) }

Usingthread_fork()forconcurrency Before

A}er

64

Page 65: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SchedulingThreads

•  Processdecides(user‐level)– OSschedulers:llschedulesper‐process– ThreadsrunincontextofcurrentPCB

•  Kerneldecides(kernel‐level)– Kernelmaintainsthreadcontrolblocks(TCB).– Kernelschedulesreadythreadstorun.

65

Page 66: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Non‐Preemp:veScheduling

•  ThreadvoluntarilygivesuptheCPUwiththread_yield()

while (1) {

printf(“ping\n”);

thread_yield();

}

while (1) {

printf(“pong\n”);

thread_yield();

}

PingThread PongThread

Whatistheoutputofrunningthesetwothreads?

66

Page 67: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ThreadsSummary

•  Parallelismusefulformanyapplica:ons–  Processesareo}entooheavyweight–  Separa:ngparalleltasksasthreadsimprovesefficiencyofmul:tasking

•  Twoprimarytypesofthreads–  Kernel‐levelthreads:canbeefficient,buthasoverhead–  User‐levelthreads:muchfaster,butnotsupportedwellbyOS

•  Arethereanydrawbackstothreads?–  Difficulttoprogramcorrectly

•  Nolongerassumeexclusiveuseoftheresources.–  It’shardtogetthemtocooperate

67

Page 68: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

WhenAreResourcesShared?

•  Localvariablesarenotshared(private)–  Refertodataonthestack–  Eachthreadhasitsownstack–  Shouldneverpass/shareapointertoalocalvariableonthestackforthreadT1toanotherthreadT2

•  Globalvariablesandsta:cobjectsareshared–  Storedinsta:cdatasegment– Accessiblebyanythread

•  Dynamicobjects(heap)areshared– Allocatedfromheapwithmalloc/freeornew/delete

68

Page 69: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ThreadingAssump:ons

•  Weassumethattheonlyatomicac:onsarereadsandwritesofwords– Notalwaysthecaseonsomearchitectures

•  Weassumethatacontextswitchcanoccuratany:me.

•  Weassumethatyoucandelayathreadaslongasyoulikeaslongasit’snotdelayedforever.

69

Page 70: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ClassicExample

•  We’llrepresentthesitua:onbycrea:ngathreadforeachpersontodothewithdrawals

•  ThesethreadsruninthesameBankprocess

•  What’stheproblemwiththisimplementa:on?–  Thinkaboutthepoten:alsequenceofexecu:onsforthesethreads

withdraw(account, amount) { balance = get_balance(account); balance = balance - amount; put_balance(account, balance); return balance; }

withdraw(account, amount) { balance = get_balance(account); balance = balance - amount; put_balance(account, balance); return balance; }

70

Page 71: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

InterleavedSchedule•  Theproblemisthattheexecu:onofthetwothreadscanbe

interleaved:

•  Whatisthebalanceoftheaccount?•  Thisisknownasaracecondi:on:

–  Theoutcomeofacomputa:onisdependentonthe:mingorinterleavingofinstruc:ons.

put_balance(account, balance);

balance = get_balance(account); balance = balance - amount; put_balance(account, balance);

balance = get_balance(account); balance = balance – amount;

ContextswitchExecu:onsequence

seenbyCPU

71

Page 72: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Cri:calSec:onRequirements

1.  Mutualexclusion–  Ifonethreadisinthecri:calsec:on,thennootheris

2.  Progress–  IfsomethreadTisnotinthecri8calsec8on,thenT

cannotpreventsomeotherthreadSfromenteringthecri:calsec:on

3.  Boundedwai:ng(nostarva:on)–  IfsomethreadTiswai:ngonthecri:calsec:on,thenT

willeventuallyenterthecri:calsec:on4.  Noassump:onsonperformance

–  RequirementsmustbemetwithanynumberofCPUswitharbitraryrela:vespeeds

72

Page 73: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Locks

•  Onewaytoimplementcri:calsec:onsisto“lockthedoor”onthewayin,andunlockitagainonthewayout

•  Alockisanobjectinmemoryprovidingtwoopera:ons–  acquire():beforeenteringthecri:calsec:on–  release():a}erleavingacri:calsec:on

•  Threadspaircallstoacquire()andrelease()–  Betweenacquire()/release(),thethreadholdsthelock–  acquire()doesnotreturnun:lanypreviousholderreleases

73

Page 74: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Locks

•  Whatarethethreewaystoimplementlocks?•  Whatarethepros/consofeachmethod?

74

Page 75: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

ProblemswithSpinLocks

•  Theproblemwithspinlocksisthattheyarewasteful–  Ifathreadisspinningonalock,thenthethreadholdingthelock

cannotmakeprogress

•  HowdidthelockholdergiveuptheCPUinthefirstplace?–  Lockholdercallsyieldorsleep–  Involuntarycontextswitch

•  Onlywanttousespinlocksasprimi:vestobuildhigher‐levelsynchroniza:onconstructs

75

Page 76: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SummarizeWhereWeAre

•  Goal:Usemutualexclusiontoprotectcri:calsec:onsofthataccesssharedresources

•  Method:Uselocks(spinlocksordisableinterrupts)•  Problem:Cri:calsec:onscanbelong

Spinlocks:• Threadswai:ngtoacquirelockspinintest‐and‐setloop• WastesCPUcycles• LongertheCS,thelongerthespin• Greaterthechanceforlockholdertobeinterrupted

DisablingInterrupts:• Shouldnotdisableinterruptsforlongperiodsof:me• Canmissordelayimportantevents(e.g.,:mer,I/O)

acquire(lock)…Cri8calSec8on…release(lock)

76

Page 77: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Higher‐LevelSynchroniza:on

•  Needhigher‐levelsynchroniza:onprimi:vesthat:–  Blockwaiters–  Leaveinterruptsenabledwithinthecri:calsec:on

•  Allsynchroniza:onrequiresatomicity•  Sowe’lluseour“atomic”locksasprimi:vestoimplementthem

77

Page 78: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Semaphores

•  Semaphoresareanotherdatastructurethatprovidesmutualexclusiontocri:calsec:ons–  Blockwaiters,interruptsenabledwithincri:calsec:on

•  Semaphoressupporttwoopera:ons:–  wait(semaphore):blockun:lsemaphoreisopen,decrement

•  Blockingthreadsareputonawaitqueue.–  signal(semaphore):increment,allowanotherthreadtoenter

•  Ifnothreadsarewai:ngonthequeue,thesignalisrememberedforthenextthread

•  Inotherwords,signal()has“history”

•  Semaphorescanalsobeusedasatomiccounters

78

Page 79: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SemaphoreTypes

•  Semaphorescomeintwotypes–  Determinedbysemaphore“value”(aka“count”)

•  Mutexsemaphore(count=1)–  Representssingleaccesstoaresource–  Guaranteesmutualexclusiontoacri:calsec:on

•  Coun:ngsemaphore(count=N)–  Representsaresourcewithmanyunitsavailable,oraresourcethat

allowscertainkindsofunsynchronizedconcurrentaccess(e.g.,reading)

–  Nthreadscanpassthesemaphore

79

Page 80: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SemaphoreSummary

•  Semaphoredrawbacks–  Theyareessen:allysharedglobalvariables

•  Canpoten:allybeaccessedanywhereinprogram

–  Noconnec:onbetweenthesemaphoreandthedatabeingcontrolledbythesemaphore

–  Usedbothforcri:calsec:ons(mutualexclusion)andcoordina:on(scheduling)

•  NotethatIhadtousecommentsinthecodetodis:nguish

–  Nocontrolorguaranteeofproperusage•  Some:meshardtouseandpronetobugs

–  Anotherapproach:Useprogramminglanguagesupport

80

Page 81: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Monitors

•  Amonitorisaprogramminglanguageconstructthatcontrolsaccesstoshareddata–  Synchroniza:oncodeaddedbycompiler,enforcedatrun:me–  Whyisthisanadvantage?

•  Amonitorisamodulethatencapsulates–  Shareddatastructures–  Proceduresthatoperateontheshareddatastructures–  Synchroniza:onbetweenconcurrentthreadsthatinvokethe

procedures

•  Amonitorprotectsitsdatafromunstructuredaccess

•  Itguaranteesthatthreadsaccessingitsdatathroughitsproceduresinteractonlyinlegi:mateways

81

Page 82: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

MonitorSeman:cs

•  Amonitorguaranteesmutualexclusion–  Onlyonethreadcanexecuteanymonitorprocedureatany:me(thethreadis“inthemonitor”)

–  Ifasecondthreadinvokesamonitorprocedurewhenafirstthreadisalreadyexecu:ngone,itblocks

•  Sothemonitorhastohaveawaitqueue…

–  Ifathreadwithinamonitorblocks,anotheronecanenter

82

Page 83: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Condi:onVariables

•  Condi:onvariablesprovideamechanismtowaitforevents(a“rendezvouspoint”)

•  Condi:onvariablessupportthreeopera:ons:– Wait:releasemonitorlock,waitforC/Vtobesignaled

•  SoCVshavewaitqueuestoo–  Signal:wakeuponewai:ngthread–  Broadcast:wakeupallwai:ngthreads

83

Page 84: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

HoarevsMesaMonitors

•  Hoare(immediatelyswitchtowai:ngthread)if (empty)

wait(condition)

•  Mesa(putwai:ngthreadonreadyqueue)while(empty)

wait(condition)

•  Tradeoffs– Mesamonitorseasiertouse,moreefficient

•  Fewercontextswitches,easytosupportbroadcast–  Hoaremonitorsleavelesstochance

•  Easiertoreasonabouttheprogram84

Page 85: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Condi:onVariablesandLocks

•  Condi:onvariablesarealsousedwithoutmonitorsinconjunc:onwithblockinglocks

•  Amonitoris“justlike”amodulewhosestateincludesacondi:onvariableandalock–  Differenceissyntac:c;withmonitors,compileraddsthecode

•  Itis“justasif”eachprocedureinthemodulecallsacquire()onentryandrelease()onexit–  Butcanbedoneanywhereinprocedure,atfinergranularity

•  Withcondi:onvariables,themodulemethodsmaywaitandsignalonindependentcondi:ons

85

Page 86: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

UsingCondi:onVariablesandLocks

•  Alterna:onoftwothreads(ping‐pong)•  Eachexecutesthefollowing:Lock lock; Condition cond;

void ping() { acquire(lock); while(1) { printf(“ping\n”); signal(cond, lock); wait(cond, lock); } release(lock); }

Mustacquirelockbeforeyoucanwait(similartoneedinginterruptsdisabledtocallsleepinNachos)

Waitatomicallyreleaseslockandblocksun:lsignal()

Waitatomicallyacquireslockbeforeitreturns

86

Page 87: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Synchroniza:onSummary

•  Semaphores–  wait()/signal()implementblockingmutualexclusion–  Alsousedasatomiccounters(coun:ngsemaphores)–  Canbeinconvenienttouse

•  Monitors–  Synchronizesexecu:onwithinproceduresthatmanipulate

encapsulateddatasharedamongprocedures•  Onlyonethreadcanexecutewithinamonitorata:me

–  Reliesuponhigh‐levellanguagesupport•  Condi:onvariables

–  Usedbythreadsasasynchroniza:onpointtowaitforevents–  Insidemonitors,oroutsidewithlocks

87

Page 88: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SchedulingHorizons

•  Schedulingworksattwolevelsinanopera:ngsystem– Long‐termschedulinghappensrela:velyinfrequently•  Significantoverheadinswappingaprocessouttodisk

– Short‐termschedulinghappensrela:velyfrequently• Wanttominimizetheoverheadofscheduling

88

Page 89: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SchedulingGoals

•  Schedulingalgorithmscanhavemanydifferentgoals:–  CPUu:liza:on–  I/Ou:liza:on–  Jobthroughput(#jobs/unit:me)

–  Turnaround:me(Tfinish–Tarrival)

–  Wai:ng:me(Avg(Twait):avg:mespentonwaitqueues)

–  Response:me(Avg(Tready):avg:mespentonreadyqueue)

•  Batchsystems–  Striveforjobthroughput,turnaround:me(supercomputers)

•  Interac:vesystems–  Strivetominimizeresponse:meforinterac:vejobs(PC)

89

Page 90: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Starva:on

•  Starva:onoccurswhenajobcannotmakeprogressbecausesomeotherjobhastheresourceitrequires– We’veseenlocks,Monitors,Semaphores,etc.

– ThesamethingcanhappenwiththeCPU!

90

Page 91: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

SchedulingAlgorithms

•  First‐comefirst‐served(FCFS),first‐infirst‐out(FIFO)–  Jobsarescheduledinorderofarrivaltoreadyqueue

•  ShortestJobFirst(SJF)–  ChoosethejobwiththesmallestexpectedCPUburst

•  Personwithsmallestnumberofitemstobuy–  Provablyop:malminimumaveragewai:ng:me

•  RoundRobin–  Readyqueueistreatedasacircularqueue(FIFO)–  Eachjobisgivena:meslicecalledaquantum

•  PriorityScheduling–  Choosenextjobbasedonhighestpriority

91

Page 92: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

CombiningAlgorithms

•  Schedulingalgorithmscanbecombined–  Havemul:plequeues–  Useadifferentalgorithmforeachqueue– Moveprocessesamongqueues

•  Mul:pleLevelFeedbackQueues(MLFQ)– Mul:plequeuesrepresen:ngdifferentjobtypes

•  Interac:ve,CPU‐bound,batch,system,etc.

–  Queueshavepriori:es,jobsonsamequeuescheduledRR–  Jobscanmoveamongqueuesbaseduponexecu:onhistory

•  Feedback:Switchfrominterac:vetoCPU‐boundbehavior

92

Page 93: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

PriorityInversion

•  Problemdescrip:on–  Ahighprioritythreadisstuckwai:ngforalowprioritythreadto

finish–  Inthiscase,themediumprioritythreadwasholdingupthelow‐

prioritythread

•  Solu:on:PriorityInheritance–  Allowathreadtoinheritthepriorityofanythreadthatis

wai:ngforit–  Blocked,higherprioritythreads“donate”theirprioritytolower

prioritythreads•  Dona:ononlyoccursaslongasthehigherprioritythreadisblocked–oncethisisnolongertrue,threadsretaintheiroriginalpriority

93

Page 94: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DeadlockDefini:on

•  Defini:on:Deadlockexistsamongasetofprocessesifeveryprocessiswai:ngforaneventthatcanbecausedonlybyanotherprocessintheset.

94

Page 95: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Condi:onsforDeadlock

Deadlockcanexistifandonlyiffourcondi:onshold:•  Mutualexclusion–Atleastoneresourcemustbeheld

inanon‐sharablemode(i.e.,onlyoneinstance)•  Holdandwait–Theremustbeoneprocessholding

oneresourceandwai:ngforanotherresource•  Nopreemp:on–resourcescannotbepreempted

(i.e.,cri:calsec:onscannotbeabortedexternally)•  Circularwait–Theremustexistasetofprocesses{P1,

P2,P3,…,Pn}suchthatP1iswai:ngforaresourceheldbyP2,P2iswai:ngforP3,…,andPnforP1

95

Page 96: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

DealingwithDeadlock

Therearefourwaystodealwithdeadlock:•  Ignoreit

–  Doyoufeellucky?•  Preven:on

–  Makeoneofthefourcondi:onsimpossible•  Avoidance

–  Controlalloca:onofresources(Banker’sAlgorithm)•  Detec:onandrecovery

–  Lookforacycleindependencies–  Preemptorabort

96

Page 97: Final Review - University of California, San Diegocseweb.ucsd.edu/classes/su09/cse120/lectures/FinalReview.pdf · Content for the Final • Role of an Operang System • Concurrency

Starva:onandDeadlock•  Starva:on:

–  Athreadnevermakesprogressbecauseotherthreadsareusingaresourceitneeds

•  Deadlock:–  Acircularresourcedependencybetweenmul:plethreadssuchthatnoneofthemcanmakeprogress.

•  Starva:onisnotthesameasdeadlock

97


Recommended