You are on page 1of 120

Memory Management

MemoryManagement

Objectives
Toprovideadetaileddescriptionofvariouswaysof
organizingmemoryhardware
ii
h d
Todiscussvariousmemorymanagementtechniques,
includingpagingandsegmentation
gp g g
g

Memory
Itconsistsofalargearrayofwordsorbytes,
g
y
y ,
eachwithitsownaddress.TheCPUfetches
instructionsfrommemoryaccordingtothe
y
g
valueoftheprogramcounter.

OperatingSystemConcepts

Background
Programmustbebroughtintomemoryandplacedwithin
aprocessforittoberun.
Aprocessmaybemovedbetweenmemoryanddisk
A process may be moved between memory and disk
duringexecution.
Theinputqueueisacollectionofprocessesonthedisk
that are waiting to be brought into memory to run the
thatarewaitingtobebroughtintomemorytorunthe
program.
Userprogramsgothroughseveralstepsbeforebeingrun.
Addresses are represented in different ways during these
Addressesarerepresentedindifferentwaysduringthese
steps.
Addressesinthesourceprogramaresymbolic(e.g.count)
Thecompilerbinds
The compiler binds thesymbolicaddressestorelocatable
the symbolic addresses to relocatable
addresses(e.g.14byesfromthebeginningofthemodule).
Thelinkerorloaderwillbindtherelocatable addressesto
absolute addresses(e.g.74014).
addresses (e.g. 74014).
OperatingSystemConcepts

Why we need memory management?


Whyweneedmemorymanagement?
Toensureprotectionofdifferentprocesses
fromeachother(sothattheydonotinterfere
witheachothersoperation))
Toplacetheprogramsinmemory(suchthat
thememoryisutilizedtoitsfullestandhigh
degreeofmultiprogrammingcanbeachieved).

OperatingSystemConcepts

Steps for Loading a Process in Memory


StepsforLoadingaProcessinMemory
System
Library

staticlinking

The
Thelinkercombinesobjectmodulesinto
linker combines object modules into
asingleexecutablebinaryfile(loadmodule)
Theloaderplacestheloadmoduleinphysical
The loader places the load module in physical
memory

Linking:combinealltheobject
modulesofaprogramintoa
binaryprogramimage

dynamiclinking

System
Library

AddressBinding Mappingfromoneaddress
spacetoanother
h
Addressrepresentation
Sourceprogram:symbolic(suchascount)
Source program: symbolic (such as count)
Aftercompiling:relocatableaddress
14bytesfromthebeginningofthismodule
Afterlinkageeditor,loaderorruntimereferring:absoluteaddress
Physicalmemoryaddress2014

2000
intI;
gotop1;

p1

2250

250

SymbolicAddress

RelocatableAddress

AbsoluteAddress
(PhysicalMemory)

BindingofInstructionsandDatatoMemory
Addressbindingofinstructionsanddatatomemoryaddressescan
happenatthreedifferentstages.

Compiletime:Ifmemorylocationknowna
priori,absolutecodecanbegenerated;must
recompile code if starting location changes
recompilecodeifstartinglocationchanges.
Loadtime:Thecompilermustgenerate
relocatable codeifmemorylocationisnot
kno n at compile time
knownatcompiletime.
Executiontime:Bindingisdelayeduntilrun
timeiftheprocesscanbemovedduringits
executionfromonememorysegmentto
another.Needhardwaresupportforaddress
maps(e.g.,base andlimitregisters).
OperatingSystemConcepts

Binding at Compile Time


BindingatCompileTime
Symbolic
Addresses

AbsoluteAddresses
Absolute
Addresses
(PhysicalMemoryAddresses)

PROGRAM

1024

JUMPi

JUMP1424

1424

LOADj

LOAD2224

Compile

Link

DATA
j

2224

S
SourceCode
C d

Ab l
AbsoluteLoadModule
L dM d l
TheCPUgeneratestheabsoluteaddresses

Binding at Compile Time (Cont.)


BindingatCompileTime(Cont.)
AbsoluteAddresses
Absolute
Addresses
(PhysicalMemoryAddresses)
1024
JUMP1424
1424

Load

LOAD2224

2224

P
ProcessImage(Part)
I
(P )
10

Binding at Loader Time


BindingatLoaderTime
Symbolic
Addresses

Relative(Relocatable)
Relative
(Relocatable)
Addresses

PROGRAM

JUMPi

JUMP400

400

LOADj

LOAD1200

Compile

Link

DATA
j

1200

S
SourceCode
C d

R l i L dM d l
RelativeLoadModule
11

Binding at Loader Time (Cont.)


BindingatLoaderTime(Cont.)
AbsoluteAddresses
Absolute
Addresses
(PhysicalMemoryAddresses)
1024
JUMP1424
1424

Load

LOAD2224

2224

P
ProcessImage(Part)
I
(P )
TheCPUgeneratestheabsoluteaddresses

12

AddressBinding(Cont.)
g(
)
Executiontime:Bindingdelayed
untilruntime
Theprocesscanbemoved
duringitsexecutionfromone
memory segment to another
memorysegmenttoanother
TheCPUgeneratestherelative
(virtual)addresses
Needhardwaresupportfor
Need hardware support for
addressmaps(e.g.,baseand
limitregisters)
MostgeneralpurposeOSuse
thismethod
Swapping,Paging,
Segmentation

Relative(Relocatable)
Addresses
0
JUMP400
400
LOAD1200

1200
MAX
13

=2000
2000

Relocation
CPUgenerateslogicaladdressesintherange0to
C
U ge e ates og ca add esses t e a ge 0 to
max.
TheMMUaddsabaseregister(value=r)tothe
logicaladdressestogetphysicaladdresses.
Physicaladdressspaceisr+0tor+max.
e.g.withr=14000,alogicaladdressof346gets
mappedtothephysicaladdress14346.

DynamicRelocationUsingaRelocation
Register
14000to
14000+MAX
Generated
Generated
ByCPU

SeenBy
MemoryUnit

0toMAX

Bindingatexecution
time (when reference is
time(whenreferenceis
made)

MapLA
toPA

15

Logical vs. Physical Address Space


Logicalvs.PhysicalAddressSpace
Theconceptofbindingalogical
p
g
g
addressspace
p
to
aphysical addressspace iscentraltoproper
memorymanagement
Logical
Logicaladdress
address generatedbytheCPU;alsoreferred
generated by the CPU; also referred
toasvirtualaddress
Physicaladdress addressseenbythememoryunit

Logicalandphysicaladdressesarethesamein
compiletimeandloadtimeaddressbinding
schemes
Logicalandphysicaladdressesdifferinexecution
timeaddressbindingscheme
16

MemoryManagement
Memory
ManagementUnit(MMU)
Unit (MMU)
Hardware
Hardwaredevicethatmapsvirtualtophysical
device that maps virtual to physical
address
InMMUscheme,thevalueintherelocation
In MMU scheme the value in the relocation
registerisaddedtoeveryaddressgenerated
by a user process (CPU) at the time it is sent to
byauserprocess(CPU)atthetimeitissentto
memory
Theuserprogramdealswithlogicaladdresses;
Th
d l i h l i l dd
itneverseestherealphysicaladdresses
17

Swapping
Aprocesscanbeswappedtemporarilyoutofmemorytoa
backingstore,andthenbroughtbackintomemoryfor
continuedexecution.

Backingstore afastdisklargeenoughtoaccommodate
copiesofallmemoryimagesforallusers;mustprovide
directaccesstothesememoryimages.
Rollout,rollin swappingvariantusedforprioritybased
schedulingalgorithms;lowerpriorityprocessisswappedout
sohigherpriorityprocesscanbeloadedandexecuted.
Majorpartofswaptimeistransfertime;totaltransfertime
isdirectlyproportionaltotheamount ofmemoryswapped.

OperatingSystemConcepts

Schematic View of Swapping


SchematicViewofSwapping

OperatingSystemConcepts

BaseandLimitRegisters

Apairofbase and limit registersdefinethelogicaladdressspace

Hardwareaddressprotectionwithbaseandlimitregisters
Every memoryaccessmadebyauserprocessischeckedagainstthesetworegisters,andifa
memoryaccessisattemptedoutsidethevalidrange,thenafatalerrorisgenerated.
TheOSobviouslyhasaccesstoallexistingmemorylocations,asthisisnecessarytoswap
users'codeanddatainandoutofmemory.
' d
dd
i
d
f
Itshouldalsobeobviousthatchangingthecontentsofthebaseandlimitregistersisa
privilegedactivity,allowedonlytotheOSkernel.

Memory management schemes


Memorymanagementschemes
Twotypes:
Contiguousstorageallocation
Noncontiguousstorageallocation
Paging
Segmentation
Pagingwithsegmentation
Paging with segmentation

OperatingSystemConcepts

HardwareSupportforRelocationandLimitRegisters

OperatingSystemConcepts

MemoryAllocation
y
Problem:howtoallocatememoryformultipleprocesses(ina
y
p p
(
multiprogrammingenvironment)
Solutions:
Contiguousallocation
Fixedpartitions
Dynamicpartitions
Dynamic partitions
Paging

ContiguousAllocation(FixedPartitions)
g
(
)

(a)
(b)

Separate input queues for each partition


Single input queue

Contiguous Allocation Strategies


ContiguousAllocationStrategies
Firstfit:allocatefromfirstholelargeenough
First
fit: allocate from first hole large enough
Bestfit: allocatefromsmallestholepossible
Worstfit:

allocatefromlargestholepossible

Simulationsshowfirstfitandbestfitareusuallybetter
Simulations
show first fit and best fit are usually better
thanworstfit,butnoclearwinner.

firstfit
OS
P1 12 KB
Initial memory
mapping
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

27

firstfit
OS
P1 12 KB
P4 of 3KB
arrives
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

28

firstfit
OS
P1 12 KB
P4 of 3KB
loaded here byy
FIRST FIT

P4 3 KB
<FREE> 7 KB
P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

29

firstfit
OS
P1 12 KB
P5 of 15KB
arrives
i

P4 3 KB
<FREE> 7 KB
P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

30

firstfit
OS
P1 12 KB
P5 of 15 KB
loaded here byy
FIRST FIT

P4 3 KB
<FREE> 7 KB
P2 20 KB
P5 15 KB
<FREE> 1 KB
P3 6 KB
<FREE> 4 KB

31

Bestfit
BestFit: Allocatethesmallestblockamongthosethatare
g
largeenoughforthenewprocess.

32

bestfit
OS
P1 12 KB
Initial memory
mapping
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

33

bestfit
OS
P1 12 KB
P4 of 3KB
arrives
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

34

bestfit
OS
P1 12 KB
P4 of 3KB
loaded here byy
BEST FIT

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
P4 3 KB
<FREE> 1 KB
35

bestfit
OS
P1 12 KB
P5 of 15KB
arrives
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
P4 3 KB
<FREE> 1 KB
36

bestfit
OS
P1 12 KB
P5 of 15 KB
loaded here byy
BEST FIT

<FREE> 10 KB

P2 20 KB
P5 15 KB
<FREE> 1 KB
P3 6 KB
P4 3 KB
<FREE> 1 KB
37

worstfit
WorstFit: Allocatethelargestblockamongthosethatare
g
g
largeenoughforthenewprocess.
Againasearchoftheentirelistorsortingitisneeded.
Thisalgorithmproducesthelargestoverblock.

38

worstfit
OS
P1 12 KB
Initial memory
mapping
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

39

worstfit
OS
P1 12 KB
P4 of 3KB
arrives
i

<FREE> 10 KB

P2 20 KB
<FREE> 16 KB

P3 6 KB
<FREE> 4 KB

40

worstfit
OS
P1 12 KB
P4 of 3KB
Loaded here byy
WORST FIT

<FREE> 10 KB

P2 20 KB
P4 3 KB
<FREE> 13 KB
P3 6 KB
<FREE> 4 KB

41

worstfit
OS
P1 12 KB
No place to load
P5 off 15K

<FREE> 10 KB

P2 20 KB
P4 3 KB
<FREE> 13 KB
P3 6 KB
<FREE> 4 KB

42

worstfit
OS
P1 12 KB
No place to load
P5 off 15K

<FREE> 10 KB

P2 20 KB
P4 3 KB
<FREE> 13 KB
Compaction is
needed !!

P3 6 KB
<FREE> 4 KB

43

Fragmentation

ExternalFragmentation totalmemoryspaceexiststosatisfyarequest,butitis
notcontiguous
InternalFragmentation allocatedmemorymaybeslightlylargerthanrequested
memory;thissizedifferenceismemoryinternaltoapartition,butnotbeingused
Reduceexternalfragmentationbycompaction
Shuffle
Shufflememorycontentstoplaceallfreememorytogetherinonelargeblock
memory contents to place all free memory together in one large block
Compactionispossibleonly ifrelocationisdynamic,andisdoneatexecutiontime
I/Oproblem
LatchjobinmemorywhileitisinvolvedinI/O
DoI/OonlyintoOSbuffers
/
ff

Canbeveryslow:256MBofmemory,copy4bytesin40ns compacting
memoryin2.7sec
Almostneverused
Almost never used

fragmentation
g
memory
OS
2K

P1 (2K)

6K

Empty (6K)

12K

P2 (9K)
empty
Empty (3K)

If a whole partition is
currently not being used,
then it is called an external
f
fragmentation.
i

If a partition is being
used by a process
requiring some memory
smaller than the partition
size, then it is called an
internal fragmentation.
fragmentation
45

Exercise
Givenmemorypartitionsof100K,500K,200K,300K,and
600K(inorder),howwouldeachoftheFirstfit,Bestfit,
(
),
,
,
andWorstfitalgorithmsplaceprocessesof212K,417K,
112K,and426K(inorder)?Whichalgorithmmakesthe
most efficient use of memory?
mostefficientuseofmemory?

OperatingSystemConcepts

Dealing with external fragmentation


Dealingwithexternal
Compaction:
Shuffleprocessesaroundinphysicalmemory
Shuffle processes around in physical memory
tocreatelargerholes
Onlyworksifprocessesarerelocatable
y
p
(dynamicaddressbinding)
Timeconsumingandcomplex(I/Ocompletion)

compaction
p
OS
P1 12 KB
Memory mapping
before
compaction

<FREE> 10 KB

P2 20 KB
P4 3 KB
<FREE> 13 KB
P3 6 KB
<FREE> 4 KB

48

compaction
p
OS
P1 12 KB

P2 20 KB
P4 3 KB

Swapout
Swap
out
P2

P3 6 KB

49

compaction
p
OS
P1 12 KB
P2 20 KB

Swapin
P2
Secondary
storage

P4 3 KB

P3 6 KB

50

compaction
p
OS
P1 12 KB
P2 20 KB

Secondary
storage
P4 3 KB

Swapout
P4

P3 6 KB

51

compaction
p
OS
P1 12 KB
P2 20 KB
P4 3 KB
Swapin
P4 with a
P4witha
different
starting
address

Secondary
storage

P3 6 KB

52

compaction
p
OS
P1 12 KB
P2 20 KB
P4 3 KB
Secondary
storage
Swapout
P3
P3 6 KB

53

compaction
p
OS
P1 12 KB
P2 20 KB
P4 3 KB
P3 6 KB

Swapin
Swap
in
P3
Secondary
storage

54

compaction
p
OS
P1 12 KB
Memory mapping
after
ft compaction
ti

P2 20 KB
P4 3 KB
P3 6 KB
<FREE> 27 KB

Now P5 of 15KB
can be loaded
here

55

compaction
p
OS
P1 12 KB
P2 20 KB
P4 3 KB
P3 6 KB
P5 12 KB
<FREE> 12 KB

P5 of 15KB is
loaded

56

Dealing with External Fragmentation


DealingwithExternalFragmentation
Bettersolutions:
Paging:breaklogicaladdressspaceintofixedsize
pages andallowpagestobeplacedarbitrarily
Segmentation:splitlogicaladdressspaceintoa
smallsetofvariablesizedsegments

Paging
g g
Logical
memory
In paging, the OS
divide the physical page
memory into frames
0
which are blocks of
1
small and fixed size
2
3

PAGE TABLE

Physical
memory

frame Attributes
4
3
1
5

59

Paging
g g
Logical
memory
In paging, the OS
divide P0
the physical page
memoryP1
into frames
0
which are
1
P2 blocks of
small and fixed size
2
P3
3

PAGE TABLE
frame Attributes
4
3
1
5

Physical
memory
f0
f1
f2
f3
f4
f5

60

Paging
g g
Logical
memory

OS divides
also the
PAGE
TABLE

logicalAttributes
memory
page frame
(program) into pages
0
4
which are blocks of
1 size3equal to frame
2
1 size.
3
5

Physical
memory
f0
f1
f2
f3
f4
f5

61

Paging
g g
Logical
memory
P0
P1
P2
P3

OS divides
also the
PAGE
TABLE

logicalAttributes
memory
page frame
(program) into pages
0
4
which are blocks of
1 size3equal to frame
2
1 size.
3
5

Physical
memory
f0
f1
f2
f3
f4
f5

62

Paging
g g
Logical
memory
P0
P1
P2
P3

PAGE TABLE
page
0
1
2
3

Physical
memory

frame Attributes
4
3
1
5

f0
f1
f2
f3
f4
f5

The OS uses a p
page
g table to map
p program
p g
pages
p g to
memory frames.
63

Paging
g g
Logical
memory
P0
P1
P2
P3

PAGE TABLE
page
0
1
2
3

frame Attributes
4
3
1
5

Physical
memory

P0

f0
f1
f2
f3
f4
f5

The OS uses a p
page
g table to map
p program
p g
pages
p g to
memory frames.
64

Paging
g g
Logical
memory
P0
P1
P2
P3

PAGE TABLE
page
0
1
2
3

frame Attributes
4
3
1
5

Physical
memory

P1
P0

f0
f1
f2
f3
f4
f5

The OS uses a p
page
g table to map
p program
p g
pages
p g to
memory frames.
65

Paging
g g
Logical
memory
P0
P1
P2
P3

PAGE TABLE
page
0
1
2
3

frame Attributes
4
3
1
5

Physical
memory
P2
P1
P0

f0
f1
f2
f3
f4
f5

The OS uses a p
page
g table to map
p program
p g
pages
p g to
memory frames.
66

Paging
g g
Logical
memory
P0
P1
P2
P3

PAGE TABLE
page
0
1
2
3

frame Attributes
4
3
1
5

Physical
memory
P2
P1
P0
P3

f0
f1
f2
f3
f4
f5

The OS uses a p
page
g table to map
p program
p g
pages
p g to
memory frames.
67

Paging
g g
Logical
memory
P0
P1
P2
P3

PAGE TABLE
page
0
1
2
3

Physical
memory

frame Attributes
4
3
1
5

P2
P1
P0
P3

f0
f1
f2
f3
f4
f5

Paging
g g permits
p
a program
p g
to allocate noncontiguous
g
blocks of memory
68

Address Translation Scheme


AddressTranslationScheme

AddressgeneratedbyCPUisdividedinto:
Pagenumber(p) usedasanindexintoapage table whichcontains
baseaddressofeachpageinphysicalmemory
Pageoffset(d)
g
( ) combinedwithbaseaddresstodefinethephysical
p y
memoryaddressthatissenttothememoryunit

page number
p
K bits

page offset
d
J bits

LogicaladdressRange:0 (2n 1),n=Noofaddressbits


Logicaladdressescanbedividedintotwoparts:thepagenumberandthe
displacementoroffset(p,d).

Page
Page#(p)isspecifiedbyupper(leftmost)k
# (p) is specified by upper (leftmost) k bitsoftheaddress,
bits of the address
displacement(d)bylowerj bits,wheren=k+j
Pagesize=2j,numberofpages=2k.

Example
Forn=4thereare24 =16possible
addresses: 0000 1111
addresses:0000
Letk=1andj=3;thereare2pages(0&1)
with8addressesperpage(000111)
(
)
Or,ifk=2andj=2thereare4pageswith
4addressesperpage

OperatingSystemConcepts

Paging Hardware
PagingHardware

PagingModelofLogicalandPhysicalMemory
g g
g
y
y

PagingExample
Page size 4bytesand32bytesofphysicalmemory
Pagesize
4 bytes and 32 bytes of physical memory

OperatingSystemConcepts

Exercise
Q1.Consideralogicaladdressspaceof64pagesof
2048 words each mapped into a physical memory
2048wordseach,mappedintoaphysicalmemory
of32frames.
a) How many bits are there in logical address?
a)Howmanybitsarethereinlogicaladdress?
b)Howmanybitsarethereinphysicaladdress?
Q2 Consider 16bit
Q2.Consider16
bitmachinewheretotal
machine where total
addressablephysicalmemorysize64Kwords
(e.g.2^16=65,538).Ifwewouldliketorun
processesasbigas128Kusing2K(2048word)
pages,howwouldlogicaladdresslooklike(show
page number and displacement fields in bits)?
pagenumberanddisplacementfieldsinbits)?

Process loading
Processloading
Splitprocesslogicaladdressspaceintopages.
Split
process logical address space into pages.
Findenoughfreeframesfortheprocesspages.
If necessary swap out an old process
Ifnecessary,swapoutanoldprocess.
Findasufficientnumberoffreeframes.
Copy process pages into their designated frames
Copyprocesspagesintotheirdesignatedframes.
Fillinthepagetable.

Process loading
Processloading

Implementation of Page Table


ImplementationofPageTable

Pagetableiskeptinmainmemory
Pagetable
Page
tablebaseregister(PTBR)
base register (PTBR) pointstothepagetable
points to the page table
Pagetablelengthregister(PTLR) indicatessizeofthepagetable

Foreverylogicalmemoryreference,two
memoryaccessesarerequired:
1. Toaccessthepagetableinthememory,inorder
to find the corresponding frame number
tofindthecorrespondingframenumber.
2. Toaccessthememorywordinthatframe

This
Thisischeapbutatimeconsuming
is cheap but a time consuming
method.

Keepthepagetableinmainmemory
PTBR:PageTableBaseRegister
PTLR:PageTableLengthRegister

logical address
logicaladdress

YES

P<PTLR

Access PT
entry
in Memory
at address
PTBR + p

NO

mat

physicaladdress

access
memoryy
mat

ERROR

EffectiveMemoryAccessTime:
emat=mat+mat=2mat
79

Thetwomemoryaccessproblemcanbe
solvedbytheuseofaspecialfastlookup
hardwarecachecalledassociativememoryor
translationlookasidebuffers(TLBs)

Associative Memory
AssociativeMemory

Associativememory parallelsearch
Page
g #

Frame #

Addresstranslation(p,d)
Ifpisinassociativeregister,getframe#out
Otherwisegetframe#frompagetableinmemory

Usecontentaddressableassociativeregisters
physicaladdress

logicaladdress

Found?

Yes(HIT)

N (MISS)
No(MISS)
P<PTLR
No
ERROR

Yes

search
PT in AR
rat

Access PT
entryy
in Memory
at address
PTBR + p

physicaladdress

mat

access
memory
mat

EffectiveMemoryAccessTime:h:hitratio
Emat=h*ematHIT+(1h)*ematMISS =h(rat+mat)+(1h)(rat+mat+mat)
82

Paging Hardware With TLB


PagingHardwareWithTLB

Effective Access Time


An 80-percent hit ratio, for example, means that we find the desired
page number in the TLB 80 percent of the time. If it takes 20
nanoseconds
d to
t searchh the
th TLB andd 100 nanoseconds
d to
t access
memory, then a mapped-memory access takes 120 nanoseconds when
the page number is in the TLB. If we fail to find the page number in the
TLB (20 nanoseconds), then we must first access memory for the page
table and frame number (100 nanoseconds) and then access the desired
byte in memory (100 nanoseconds), for a total of 220 nanoseconds.
To find the effective access time we weight the case by its probability:
effective
ff ti access time
ti = 0.80
0 80 x 120 + 0.20
0 20 x 220
= 140 nanoseconds.

Usecontentaddressableassociativeregisters
Assumewehaveapagingsystemwhichusesassociative
p g g y
registers.Theseassociativeregistershaveanaccesstimeof
30ns,andthememoryaccesstimeis470ns.Thesystemhas
a hit ratio of 90 %
ahitratioof90%.
rat=30ns
mat=470ns
h=0.9

85

Usecontentaddressableassociativeregisters
rat=30ns,mat=470ns,h=0.9
,
,
Now,ifthepagenumberisfoundinoneoftheassociative
registers,thentheeffectiveaccesstime:
ematHIT =30+470=500ns.
30 + 470 500 ns
Because
Becauseoneaccesstoassociativeregistersandoneaccessto
one access to associative registers and one access to
themainmemoryissufficient.

86

Usecontentaddressableassociativeregisters
rat=30ns,mat=470ns,h=0.9
,
,
Ontheotherhand,ifthepagenumberisnotfoundin
associativeregisters,thentheeffectiveaccesstime:
ematMISS =30+(470+470)=970ns.
Sinceoneaccesstoassociativeregistersandtwoaccessesto
y
q
themainmemoryarerequired.

87

Usecontentaddressableassociativeregisters
rat=30ns,mat=470ns,h=0.9
,
,
ematHIT =500ns,ematMISS =970ns.
Then,theematiscalculatedasfollows:
emat=h*ematHIT+(1h)*ematMISS
=0.9*500+0.1*970
*
*
=450+97=547ns

88

Exercise
Q1.Considerapagingsystemwiththepagetablestoredin
memory.
a)Ifamemoryreferencetakes200nanoseconds,howlong
doesapagedmemoryreferencetake?
b)Ifweaddassociativeregisters,and75percentofallpage
tablereferencesarefoundintheassociativeregisters,what
istheeffectivememoryreferencetime?(Assumethat
findingapagetableentryintheassociativeregisterstakes
zerotime,iftheentryisthere.)
Q2.Considertheaverageprocesssizeis128KBandthe
g p
numberofpageentriesis8.Whatwillbeappropriate
pagesize?

Answer

a)400nanoseconds;200nanosecondstoaccessthepagetableand200
nanosecondstoaccessthewordinmemory.
d
h
d
b)Effectiveaccesstime=0.75*(200nanoseconds)+0.25*(400nanoseconds)
=250nanoseconds.

Memory Protection
MemoryProtection

Memoryprotectionimplementedbyassociatingprotectionbitwith
eachframe

Validinvalid bitattachedtoeachentryinthepagetable:
validindicatesthattheassociatedpageisintheprocess
logicaladdressspace,andisthusalegalpage
invalidindicatesthatthepageisnotintheprocesslogical
addressspace

Shared Pages
SharedPages
Sharedcode
One
Onecopyofreadonly(reentrant)codesharedamongprocesses(i.e.,text
copy of read only (reentrant) code shared among processes (i e text
editors,compilers,windowsystems).
Sharedcodemustappearinsamelocationinthelogicaladdressspaceof
p
allprocesses.

Privatecodeanddata
Eachprocesskeepsaseparatecopyofthecodeanddata.
Thepagesfortheprivatecodeanddatacanappearanywhereinthelogical
addressspace.

OperatingSystemConcepts

Shared Pages Example


SharedPagesExample

OperatingSystemConcepts

Page Table Structure


PageTableStructure
HierarchicalPaging
HashedPageTables
InvertedPageTables
Inverted Page Tables

OperatingSystemConcepts

Hierarchical Page Tables


HierarchicalPageTables
Breakupthelogicaladdressspaceinto
multiple page tables
multiplepagetables.
Asimpletechniqueisatwolevelpagetable.

OperatingSystemConcepts

TwoLevelPagingExample

Alogicaladdress(on32bitmachinewith4Kpagesize)isdividedinto:
apagenumberconsistingof20bits.
apageoffsetconsistingof12bits.

Sincethepagetableispaged,thepagenumberisfurtherdividedinto:
a10bitpagenumber.
a10bitpageoffset.

Thus a logical address is as follows:


Thus,alogicaladdressisasfollows:

pagenumber
pi

p2

pageoffset
d

10
12
10
where pi isanindexintotheouterpagetable,andp2 isthedisplacementwithinthepage
p g
oftheouterpagetable.
OperatingSystemConcepts

TwoLevel
Two
LevelPage
PageTable
TableScheme
Scheme

OperatingSystemConcepts

AddressTranslation
Address
TranslationScheme
Scheme
Addresstranslationschemeforatwolevel32
p g g
bitpagingarchitecture

OperatingSystemConcepts

Threelevel
Three
levelPagingScheme
Paging Scheme
SPARCarchitecturesupportsthis

32bitMotorolaarchitecturesupportsfourlevelpaging

Hashed Page Tables


HashedPageTables
Commoninaddressspaces>32bits.
Thevirtualpagenumberishashedintoapage
table This page table contains a chain of
table.Thispagetablecontainsachainof
elementshashingtothesamelocation.
Virtualpagenumbersarecomparedinthischain
g
,
searchingforamatch.Ifamatchisfound,the
correspondingphysicalframeisextracted.

OperatingSystemConcepts

Hashed Page Table


HashedPageTable

OperatingSystemConcepts

Inverted Page Table


InvertedPageTable
Oneentryforeachrealpageofmemory.
Entry consists of the virtual address of the page
Entryconsistsofthevirtualaddressofthepage
storedinthatrealmemorylocation,with
informationabouttheprocessthatownsthat
page.
Decreasesmemoryneededtostoreeachpage
table, but increases time needed to search the
table,butincreasestimeneededtosearchthe
tablewhenapagereferenceoccurs.
Usehashtabletolimitthesearchtoone orat
mostafew pagetableentries.

OperatingSystemConcepts

Inverted Page Table Architecture


InvertedPageTableArchitecture

OperatingSystemConcepts

Segmentation
Memorymanagementschemethatsupportsuserviewof
memory.
Aprogramisacollectionofsegments.Asegmentisalogical
A program is a collection of segments A segment is a logical
unitsuchas:
mainprogram,
procedure,
procedure
function,
method,
object,
object
localvariables,globalvariables,
commonblock,
sta k
stack,
symboltable,arrays

OperatingSystemConcepts

UserssViewofaProgram
User
View of a Program

OperatingSystemConcepts

Logical View of Segmentation


LogicalViewofSegmentation
1
4

1
2

userspace

physicalmemoryspace

OperatingSystemConcepts

Segmentation Architecture
SegmentationArchitecture
Logicaladdressconsistsofatwotuple:
<segmentnumber,offset>,
Segmenttable mapstwodimensionalphysicaladdresses;
eachtableentryhas:
base
b
containsthestartingphysicaladdresswherethe
t i th t ti
h i l dd
h
th
segmentsresideinmemory
limit specifiesthelengthofthesegment
specifies the length of the segment
Segmenttablebaseregister(STBR) pointstothesegment
tableslocationinmemory
Segmenttablelengthregister(STLR) indicatesnumberof
segmentsusedbyaprogram;
segment number s islegalifs
segmentnumbers
is legal if s <STLR
< STLR

SegmentationArchitecture(Cont.)
Protection
Witheachentryinsegmenttableassociate:
validationbit=0 illegalsegment
read/write/executeprivileges
Protectionbitsassociatedwithsegments;codesharingoccurs
P
i bi
i d ih
d h i
atsegmentlevel
Sincesegmentsvaryinlength,memoryallocationisa
Since segments vary in length, memory allocation is a
dynamicstorageallocationproblem
Asegmentationexampleisshowninthefollowingdiagram

Segmentation Hardware
SegmentationHardware

OperatingSystemConcepts

Example of Segmentation
ExampleofSegmentation

OperatingSystemConcepts

Sharing of Segments
SharingofSegments

OperatingSystemConcepts

Exercise
Considerthefollowingsegmenttable:
Segment
BaseLength
0
0
219
219600
600
1
230014
2
90100
3
3
1327
1327580
580
4
195296
Whatarethephysicaladdressesforthefollowinglogicaladdresses?
a.0,430
,
b.1,10
c.2,500
d.3,400
e.4,112

OperatingSystemConcepts

Segmentation with Paging MULTICS


SegmentationwithPaging
TheMULTICSsystemsolvedproblemsof
external fragmentation and lengthy search
externalfragmentationandlengthysearch
timesbypagingthesegments.
Solutiondiffersfrompuresegmentationin
g
y
thatthesegmenttableentrycontainsnotthe
baseaddressofthesegment,butratherthe
baseaddressofapagetable forthis
segment.

OperatingSystemConcepts

MULTICS Address Translation Scheme


MULTICSAddressTranslationScheme

OperatingSystemConcepts

Q:Consideraswappingsysteminwhichmemory
consists of the following hole sizes in memory order:
consistsofthefollowingholesizesinmemoryorder:
10K,4K,20K,18K,7K,9K,12K,and15K.Which
h l i t k f
holeistakenforsuccessivesegmentrequestsof:
i
t
t f
I)12K
II)10K
III) 9K
III)9K
for
( ) Fi t fit?
(a)Firstfit?
(b)Bestfit?
(c)Worstfit?
OperatingSystemConcepts

OperatingSystemConcepts

Q:Foreachofthefollowingdecimalvirtual
Q
F
h f th f ll i d i l i t l
addressescompute,thevirtualpage
numberandoffsetfora4KBpageandan8
b
d ff f
d
KBpage:
a)20000
b)32768
c)60000
d)63540

OperatingSystemConcepts

OperatingSystemConcepts

E d f Ch t
EndofChapter

OperatingSystemConcepts