0% found this document useful (0 votes)
26 views89 pages

Coa Project

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views89 pages

Coa Project

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

DEPT IT CMREC

PROJECT WORK
On
VIRTUAL MEMORY SIMULATION
Submitted to CMREC(UGC Autonomus)
In Partial Full filment of the requirements for the Award of Degree
of
BACHELOR OF TECHNOLOGY
IN
INFORMATION TECHNOLOGY
Submitted By
G.SAI TEJA REDDY 238R1A12F3
Under the guidence of
MRS.G.USHA RANI
Assistant Professor,Department of IT

DEPARTMENT OF INFORMATION TECHNOLOGY


CMR ENGINEERING COLLEGE
UGC AUTONOMOUS
(Approved by AICTE-New Delhi & J.N.T.U, Hyderabad) Kandlakoya (v),
Medchal Road, Hyderabad-501 401, Telangana State, India.
1
DEPT IT CMREC

CERTIFICATE

This is to certify that the project entitled "CPU STIMULATOR" is a work carried out by:

G.SAI TEJA REDDY 238R1A12F3

In the part of individual project report of CPU stimulator laboratory under the guidance and
supervision

Project coordinator Head of the department


Mrs. Usha Rani Dr. Madhavi Pingili
Assistant professor, Assoc Professor and HOD,
Department of IT, Department of IT,
CMREC, Hyderabad CMREC, Hyderabad

2
DEPT IT CMREC

TABLE OF CONTENTS

CONTENT PAGE NUMBER

ABSTRACT 4

INTRODUCTION 5

DIAGRAM,TABLE AND 6 - 22
EXPLANAION

CONCLUSION 23

3
DEPT IT CMREC

ABSTRACT
This simulation aims to model the core principles of virtual memory, providing a practical demonstration of
how modern operating systems manage memory through techniques such as paging and segmentation. Virtual
memory enables programs to use more memory than is physically available by leveraging disk storage as an
extension of RAM. The simulation covers key concepts including address translation, page tables, page faults,
and the implementation of common page replacement algorithms (e.g., FIFO, LRU, and Optimal). By
simulating the allocation, mapping, and swapping of memory pages, this tool allows users to visualize the
interaction between the virtual address space and physical memory. The simulation also provides insights into
the performance implications of memory management strategies, helping users understand trade-offs between
system efficiency, response times, and resource utilization. This project serves as an educational tool for
understanding the internal workings of virtual memory management and its impact on system performance.

Virtual memory is a critical concept in modern computing, enabling the abstraction of physical memory and
allowing programs to operate in a larger, more flexible address space than what is physically available on the
system. This simulation focuses on modeling the core mechanisms behind virtual memory management,
including the translation of virtual addresses to physical addresses, page fault handling, and the implementation
of page replacement algorithms.The virtual memory system employs an address translation process where
virtual addresses generated by a program are mapped to physical addresses in the computer's memory (RAM).
This mapping is facilitated by a page table, which stores the mappings between virtual pages and
corresponding physical pages. The simulation demonstrates how the operating system uses the page table to
handle memory accesses and address translation, including how it updates the table upon encountering page
faults. In the context of paging, the virtual address space is divided into fixed-size pages, while the physical
memory is divided into equal-sized blocks called frames. When a program accesses a memory location, the
virtual address is split into a page number and an offset. The page number is used to locate the corresponding
physical frame, and the offset within the page determines the exact location within the frame. The simulation
models the behavior of paging systems, allowing users to visualize the mapping of virtual pages to physical
frames and how these mappings evolve as processes execute.

The virtual memory simulation provides an invaluable, interactive learning environment for understanding the
intricate workings of modern memory management systems. By focusing on essential concepts such as paging,
segmentation, address translation, and page replacement, the simulation offers a detailed view of how virtual
memory management impacts the performance and efficiency of computing systems. By experimenting with
different algorithms and configurations, users can gain deeper insights into the fundamental trade-offs between
memory utilization, speed, and system responsiveness. This tool is particularly useful for students, developers,
and system architects aiming to understand or optimize memory management in real-world computing
environments.

4
DEPT IT CMREC

INTRODUCTION :
Virtual memory is a critical component of modern operating systems, providing the illusion of a larger,
contiguous block of memory than is physically available. By leveraging secondary storage (typically a hard
drive or solid-state drive), virtual memory allows a computer to run programs that require more memory than
the available RAM. This memory abstraction helps facilitate multitasking, system stability, and efficient
resource management, making it an essential feature of modern computing environments.

At the heart of virtual memory is the concept of mapping virtual addresses used by applications to physical
addresses in the computer's actual RAM. This process, known as address translation, allows each process to
operate within its own isolated memory space, preventing interference from other processes. Virtual memory
also enables a more efficient use of memory resources by allowing the system to swap data between RAM and
disk as needed. However, managing virtual memory is not without its challenges, especially when it comes to
optimizing performance and minimizing overhead.

The virtual memory simulation aims to provide an interactive and educational tool for understanding the
internal mechanisms of virtual memory systems. It models how the operating system handles memory
allocation, address translation, and the management of page faults (which occur when data is accessed but not
currently in memory). Additionally, the simulation explores how different page replacement algorithms—
such as First-In-First-Out (FIFO), Least Recently Used (LRU), and Optimal—affect memory management
performance.

Key concepts explored in this simulation include:

 Paging: The division of both virtual memory and physical memory into fixed-size blocks called pages
and frames, respectively. This simplifies memory management and allows for efficient memory
utilization.
 Address Translation: The process by which virtual addresses are mapped to physical addresses using a
page table. This enables the operating system to locate the data a program needs, even if it is not stored
in the immediate physical memory.
 Page Faults: An event that occurs when a program accesses data that is not currently in physical
memory, triggering the operating system to retrieve the data from disk and load it into memory.
 Page Replacement Algorithms: Techniques used by the operating system to determine which page
should be swapped out of memory when new pages need to be loaded. Common algorithms like FIFO
and LRU are implemented and their performance compared in the simulation.

By simulating these processes, the tool allows users to visualize the relationship between virtual memory and
physical memory, observe how memory pages are allocated, evicted, and swapped, and understand the impact
of memory management decisions on system performance. Users can experiment with different parameters,
such as the number of available memory frames or the frequency of page accesses, to see how these factors
influence memory management efficiency and overall system responsiveness.

The ultimate goal of this simulation is to provide a deeper understanding of virtual memory's role in modern
operating systems, the challenges associated with memory management, and the impact of various algorithms
on performance. It serves as an invaluable educational resource for students, developers, and system designers
looking to explore the complexities of memory management and optimize system performance.

5
DEPT IT CMREC

CPUSimisantoolthatw
asdesignedtofacilitatesuc
hinteractivehands-
onlearning.
With CPU Sim, students ca
n design their own archite
ctures from scratch or mo
dify
architectures given to them.
  They can simulate a
variety of architectures, incl
uding
accumulator-based,register-
based(RISC),andstack-
basedCPU's,forexample,a
ndthey
can run programs on them
 without the need of any
6
DEPT IT CMREC

 physical hardware other th


an the
computeronwhichCPUSim
isrun.
WithCPUSiminstructorsca
ngivestudentshands-
onexperiencewiththefollo
wing
topicsintheIEEE/
ACMComputingCurriculum[I
EEE/ACM2001]

Numericdatarepresentation
andnumberbases

Representationofnonnumeric
data

7
DEPT IT CMREC


Microprogrammedrealizationo
ftheCPU

Controlunit;instructionfetch,
decode,andexecution

Instructiontypes(datamanip
ulation,control,I/O)
• Instructionformats

Assembly/machinelanguagepr
ogramming
• Addressingmodes

Mainmemoryorganizationan
doperations
The knowledge of a high-
level language is not a pr
8
DEPT IT CMREC

erequisite to understanding a


nd
usingCPUSimbutanappr
eciationofwhatisinvolved
inprogrammingwithahi
gh-level
languageisuseful.
Theauthorhassuccessfully
usedCPUSiminhisintro
ductorymachineorganization

classes since 1989, in conj
unction with the text "Stru
ctured Computer Organization
"
[Tanenbaum,1999].CPUSi
mwasnotdesignedspecifi
callytobeusedwiththat
book,
9
DEPT IT CMREC

butitworkswellwithit.
TheprecursortoCPUSim
canbefoundin[Kerridge
etal.1980].CPUSimv
ersion
1.0.13 and its uses in the
 classroom were discussed
in [Skrien et al. 1991]. 
A later
version(2.2)wasdiscussed
in[Skrien1994]Thecurr
entversionofCPUSim, v
ersion
3.1,was writtenusingJava
2 andtheSwingpackage
.Ithasbeentestedon
computers
runningMacOSX,Windows
98/NT/2000,andLinux.
10
DEPT IT CMREC

This paper discusses the fe


atures of CPU Sim 3.1, ho
w to use it, and gives s
ome
sample assignments.  The d
etails of those assignments
and their solutions are avail
able
fromtheauthor.

2.MAINDISPLAYOFCPUSI
M
WhenCPUSimisstarted,
themaindisplaywindowap
pears(seeFigure1).Exc
eptfor
somedialogboxesandhelp
windows,allwindowsarei

11
DEPT IT CMREC

nternaltothismainwindow.
The
internalwindowsincludeone
sthatdisplaythecontents
ofregistersandRAMsand
ones
thatcontaintextsuchasa
ssemblyprograms.Eachof
theseinnerwindowsand
manyof
themenuitemsarediscusse
dinlatersectionsofthis
paper.


Fig.1.CPUSim'smaindisplaywin
dow.

12
DEPT IT CMREC

3.DESIGNFEATURESOFCP
USIM
In CPU Sim, architectures a
re designed at the register-
transfer level.  That is, th
e user
specifies the registers, main
 memories (RAM), microinstru
ctions, machine instructions,
andassemblylanguageinstru
ctionsforahypotheticalma
chine.
A machine instruction is im
plementedby a sequence o
f microinstructions called its

"executesequence".Theu
serspecifiestheexecutese

13
DEPT IT CMREC

quenceofallmachineinstru
ctions
andsotheuserhascompl
etecontroloverthesemanti
csofeveryinstruction.W
henCPU
Sim executes a program, it
 repeatedly executes machin
e cycles that consist of a
 fetch
sequence(asequenceofmi
croinstructionsspecifiedbyth
euser)followedbytheex
ecute
sequenceofthemachineins
tructionthatwasfetched.

3.1SpecifyingtheHardware
Components
14
DEPT IT CMREC

If users are building a ne


w architecture from scratch,
 they will need to create
 first the
basichardwarecomponentso
ftheCPU.Onetypeof
componentisaregistero
rregister
array.
Users can create as many
 registers and register array
s as they wish, with arbitr
ary
widths(numberofbits).F
oreachregister,theuser
specifiesanameandthe
width.For
eachregisterarray,theuser
specifiesaname,thenu
15
DEPT IT CMREC

mberofregistersinthearr
ay,andthe
widthofallregisters.Thes
earraysarespecifiedthrou
ghthedialogboxshowni
nFigure
2.  If an array of 16 r
egisters is named "A", then
 CPU Sim automatically giv
es each
individualregisterinthearra
ythenames"A[0]","A[1]",..
.,"A[15]".


Figure2.Thedialogforeditedre
gisterarrays.

16
DEPT IT CMREC

 Another type of hardwa


re component that the user
 must specify is memory
or
RAM.ARAMisbyte-
addressableandeachRAMi
saccessiblebytheCPUon
lythrough
"memory access" microinstruct
ions, which transfer data b
etween registers and RAMs.

Theusercanspecifyasm
anyRAMsasdesired,each
withtheirownsize.For
example,
theusermaywishtocreat
ethreeRAMs,onetohold

17
DEPT IT CMREC

thecode,onetoholdth
estack,and
onetoholdtheheap,ort
heusermaywishtouse
onlyoneRAMtoholdever
ything.
 Thelasttypeofhard
warecomponenttheusers
pecifiesisa"conditionbit"
(see
Figure3).Conditionbitsa
rejustspecificbitsofexist
ingregistersthatcanbes
etto1by
microinstructions and optionall
y by arithmetic operations
if an overflow or carry o
ut

18
DEPT IT CMREC

occurs.Forexample,aty
picalstatusregisterwithNZ
VCbitscanbespecifiedth
isway.
Theusercanalsospecify
whetherthesettingofac
onditionbitwillhalttheex
ecutionof
thecurrentprogram.
 

Figure3.Thedialogforeditingc
onditionbits.

3.2SpecifyingtheMicroinstruc
tions
The user next creates micr
oinstructions for manipulating

19
DEPT IT CMREC

 the data in the registers


 and
RAMs.Themicroinstructions
involvingarithmeticoperatio
nsassumethatintegervalu
es
arestoredintwo'scomple
mentrepresentation.There
are15kindsofmicroinstr
uctions
thatcanbecreated:
1. Transfer(orcopy)oper
ationbetweentworegisters.
Theuserspecifiesther
egisters,
the subset of consecutive b
its of the source register t
hat are to be copied, and
 the
20
DEPT IT CMREC

subset of consecutive bits


of the destination register i
nto which the data is to
 be
copied.SeeFigure4for
thedialogforeditingtransfe
rmicroinstructions.
2. Transfer operation from
 a register to a register
 in an array. 
In addition to the
register-to-
register transfer specifications,
 the user specifies which
bits of which
registercontaintheindexof
thedestinationregisterin
thearray.

21
DEPT IT CMREC

3. Transferoperationfrom
aregisterinanarrayto
aregister.Thisoperation
issimilar
totheprecedingkindofmi
croinstruction.


Figure4.Thedialogforeditingtr
ansfermicroinstructions.

4. Integer arithmetic operati
on (addition, subtraction, mu
ltiplication, division).  The
user specifies the operation,
 the two source registers,
the destination register, and

22
DEPT IT CMREC

whetheranyconditionbitss
houldbesetifoverflowor
carryoutoccurs.Noteth
at
thereisnofloatingpoints
upportinCPUSim.
5. Logical (boolean) operati
on.  The user specifies th
e operation (and, or, nand,
 nor,
xor,not),thesourceregister
s,andthedestinationregist
er.
6. Shiftoperation.Theu
serspecifiesthetypeofs
hift(logical,arithmetic,orc
yclical),
the direction of the shift
(left or right), the amount
23
DEPT IT CMREC

 of shift, and the source


 and
destinationregisters.
7. Testoperationonbits
ofaregister.Thesemicro
instructionsallowjumpingto
other
microinstructionsforwardorb
ackwardwithinamicroinstru
ctionsequence.Thetest
microinstructioncomparesthe
valueinpartofaregist
erwithagivenvalue.If
the
comparison succeeds, then a
 number of successive micr
oinstructionsin the current
sequenceareskippedover.
Theuserspecifiestheco
24
DEPT IT CMREC

mparisontobeused(=,
<,>,
<=,>=),thevaluetobe
compared,theregister,the
bitsoftheregistertob
etested,
andtheamounttojumpif
thetestsucceeds.
8. Branchoperation.This
microinstructionislikeat
estmicroinstructionexceptth
atit
is an unconditional jump.
 The user specifies the a
mount to jump, which can
 be
positiveornegative.
9. Incrementoperation.T
heuserspecifiestheregist
25
DEPT IT CMREC

ertobeincremented,the
amount
oftheincrement,andwheth
eranyconditionbitsareto
besetifoverfloworcarr
yout
occurs.
10. Setoperation.Thiso
perationsetsaspecifiedpar
tofaregistertoaspecif
iedvalue.
Theuserchoosestheregist
er,theconsecutivebitsof
thatregisterthatareto
beset,
andthevalue.
11. Setconditionbitoperat
ion.Thisoperationsetsa

26
DEPT IT CMREC

conditionbitto0or1.
Theuser
choosestheconditionbitan
dthevaluetowhichitis
tobeset.
12. Memoryaccessoperation
.Theuserspecifiesada
taregister,anaddressregis
ter,the
RAM,andthedirectionofd
atamovement(readorwrit
e).
13. I/
O operation.  The user sp
ecifies a buffer register to
 or from which data is t
o be
moved, the direction of dat
a movement (input or outp
27
DEPT IT CMREC

ut), the type of data bein


g
moved (integer, ASCII, or U
nicode), and the external s
ource or destination of the

data(eitheradialogbox f
orinteractionwiththeuser
oratext filespecifiedb
ythe
userforbatchmode).
14. Decode operation.  Thi
s operation is used in th
e fetch sequence and caus
es the
contentsof a specified instr
uction register to be decod
ed and thedecoded machin
e
28
DEPT IT CMREC

instructiontobeexecuted.
15. End operation.  This
operation indicates the end
 of the execution of the
 current
machine instruction and tells
 CPU Sim to jump to the
 first microinstruction in the

fetchsequence,andsostart
anewmachinecycle.

3.3SpecifyingtheMachineI
nstructionsandtheFetchSe
quence
The user specifies the se
mantics of each machine
instruction by a sequence
of
29
DEPT IT CMREC

microinstructionscalledits"e
xecutesequence".Therefore
theusercancreateverysi
mple
instructionssuchasincremen
tingaregisteror veryco
mplexinstructionswithelabo
rate
addressing schemes involving
 multiple registers and RA
Ms.  The user can creat
e
instructionsthat are RISC-
like, in that they all have
 the same length and layo
ut, or the
usercanchooseCISC-
likeinstructionswithvariable

30
DEPT IT CMREC

lengthsandavarietyof
layouts.
In addition to the execute
 sequence, the user specifi
es a name for each mac
hine
instruction,anopcode,and
asequenceoffieldlengths.
Thesumofthefieldl
engthsis
thelength(inbits)ofthe
instruction.Thefirst field
correspondstotheopcode
andthe
remainingfieldscorrespondt
ooperandsoftheinstructio
n.SeeFigure5 forthe
dialog

31
DEPT IT CMREC

boxforeditingmachineinst
ructions.
 CPUSimalsohasa
dialogbox(notshownhere)
inwhichtheusercansp
ecify
thefetchsequence.Thef
etchsequenceisasequenc
eofmicroinstructionsthatC
PUSim
executes at the beginning
of each machine cycle. Use
rs can specify any sequenc
e they
wish, but the fetch sequen
ce usually includes microins
tructions that fetch the ne
xt

32
DEPT IT CMREC

machineinstruction,placeit
inaninstructionregister,
incrementaprogramcounter
,and
thendecodetheinstructioni
ntheinstructionregister.


Figure5.Thedialogforediting
machineinstructions.

3.4SavingandViewingthe
Specification
Onceanarchitecturehasbe
enspecified,theusercan
savethisspecificationinan
XML
file for later reloading into
 CPU Sim and editing.  T
33
DEPT IT CMREC

he user can also save the


 machine
specificationinanHTMLfile
whichcanbeviewedwith
anywebbrowser.

4.WRITINGANDRUNNINGP
ROGRAMSINCPUSIM
Once a complete CPU arch
itecture has been specified,
 the user can write mac
hine
languageorassemblylangua
geprogramsandrunthem
onthatCPUthroughsimu
lation.
For writing such programs,
 CPU Sim has a built-

34
DEPT IT CMREC

in text editor, including all


 the
cut/copy/paste/find/replace/
printfacilitiesdesiredofsuc
haneditor.
Machinelanguageprograms
arewrittenastextinthe
formof asequenceof0
's and
1'soneachline followed
optionallybycomments.T
heseprogramscanbeload
edinto
any specified RAM and the
n executed.  See Figure 6
 for a sample machine lan
guage
program.

35
DEPT IT CMREC

In assembly language an


instruction is written using
 the name of a machin
e
instructionfollowedbyalist
ofvalues(eitherconstants
orsymbols),oneforeach
fieldof
theinstruction.Forexampl
e,aninstructiontoaddth
econtentsofregisterA[0]
toA[1]
mightlooklike
add A0, A1
whereA0andA1areequa
teswithvalues0and1,
indicatingtheindicesofthe
registers

36
DEPT IT CMREC

to be added.  See the


window labeled "W1-
0.a" in Figure 1 fo
r a sample assembly
languageprogram.
 

Figure6.Asimplemachinelangua
geprogram.

Assembly programs can also
 include the definition of
equates, the definitions and

callsofmacros,andpseudo
instructionssuchasa"data
"directivethatinitializespa
rtsof

37
DEPT IT CMREC

memorytospecifiedvalues
oran"include"directivetha
tinsertsthecontentsofa
nother
fileinthecurrentprogram
beforeassembly.
Onceanassemblyprogram
hasbeenwrittenandsaved
toafile,itcanbeass
embled.
TheCPUSimassemblerwill
checkforerrorsinthec
odeand,iftherearesuch
errors,it
willdisplayanerrormessag
eandhighlighttheoffendin
glineintheassemblycod
e.Ifno

38
DEPT IT CMREC

errorsoccur,theassembled
machinecodecanbeloaded
intoanyspecifiedRAM,th
euser
caninitializeanyofthere
gisterstospecifiedvalues,
andthenexecutionofthe
program
canbegin.
If during execution the use
r's program requests input
from the user, a dialog b
ox
appearsaskingtheuserto
typeinavalue.Ifthe
programspecifiesoutputto
theuser,this
outputappearsin adialog
box.  Inputandoutput
39
DEPT IT CMREC

can alsobedirectedtoan
dfromtext
files.
Oncetheprogramhalts(bec
auseaconditionbitwasse
tto1,anerroroccurred,
orthe
user selected the "Stop" m
enu item) the user can i
nspect the state of the
machine,
includingthecontentsofthe
registersandRAMs.

5.SPECIALFEATURESOFCP
USIM
Someofthestrengthsof
CPUSimincludeitsdisplay

40
DEPT IT CMREC

ofregistersandRAMs,its
editing
and debugging aids, and its
 help facilities, all of whic
h make it easier for the
 user to
understandwhatishappening
asaprogramisexecuting
.

5.1DisplayingRegistersand
RAMs
Theusercanviewthecont
entsoftheregistersandR
AMsthoughwindows(forex
ample,
seethewindowslabeled"R
egisters"and"RAMMain"in

41
DEPT IT CMREC

Figure1).Thecontents
ofthe
registerscanbeviewedand
edited,ifdesired,ineithe
rdecimal,binary,orhexad
ecimal.
A decimal value is conver
ted to or from a binary
 value using two's comple
ment
representation.  The values
 in each RAM can also
be displayed in these base
s.  In
addition, the RAM values c
an be displayed and edite
d in groups of 1 to 8
 bytes,

42
DEPT IT CMREC

correspondingtothewords
izeofthearchitecturebein
gsimulated.Furthermore,
RAM
windowsincludeacolumnf
orcommentsassociatedwith
eachwordofmemory,w
hich
providesawayfortheuse
rtoindicatethecontentso
ftheword.Theassembler
initializes
thiscolumnwiththecomm
entsontheendofeach
lineofassemblycode.Th
atis,ifa
lineoftheassemblyprogra
mis:
add sum ; add sum to the acc
43
DEPT IT CMREC

thentheassemblerandloa
derwillputtheassembled
codeintheRAMandwil
lputthe
commentinthecorrespondin
gcommentcolumnofthe
RAMwindow.

5.2EditingandDebugging
CPUSimhasadebugging
modethatuserscanenter
whentheywishtostep
throughthe
executionoftheprogramon
emachineinstructionoron
emicroinstructionatatime.
(See
Figure7forthetoolbartha
tappearswhenusersenter
44
DEPT IT CMREC

debuggingmode.)Aftere
achsuch
step,theusercaninspect
andoptionallyeditthestate
ofthemachine.CPUSi
mcanalso
beconfiguredtohighlightc
ellsofRAMs whoseaddress
es areincertainregisters.
For
example, the top of the s
tack can be highlighted, as
 well as the next instructi
on to be
executed.  At any point w
hen in debug mode, the u
ser can also back up one
 machine

45
DEPT IT CMREC

instructionatatime(allt
hewaybacktotheorigin
alstateofthemachinew
hendebug
modewasentered).This
abilitytostepforwardand
backwardthroughthecod
emakes
pinpointinghardwareorsoftw
areerrorsalmosttrivial.
 If the program gets in
to an infinite loop, the us
er can choose "Stop" from
 the
Executemenu,andtheprog
ramwillbehalted.


Figure7.Thedebuggingtoolbar.
46
DEPT IT CMREC


5.3GettingHelp
Virtually the whole user's m
anual is available online wi
th CPU Sim.  In addition
 to a
generalhelpwindow(seeFi
gure8),manydialogboxes
have"Help
"buttonsthatbringup
theonlinehelpforthatdial
ogbox.


Figure8.TheCPUSimhelpwind
ow.

6.SAMPLEASSIGNMENTSUSI
NGCPUSIM
47
DEPT IT CMREC

Aseriesofopenandclose
dlabexercisesusingCPU
Simhasbeencreatedbyt
heauthor
to introduce CS3 students
gradually to more and more
 complex machine architectur
es.
These exercises expose the
 students to an accumulat
or-based machine, a RISC-
like
machine(withregularinstruc
tionlayoutand arraysof
general-
purposeregisters), anda
stack-
basedmachine(theJavaVir
tualMachineorJVM).The
48
DEPT IT CMREC

labexercisesareassigned

approximatelyonceortwice
aweekina14-
weeksemester,withthefirs
tlaboccurringin
thesecondweekofthese
mester.Thestudentsare
givenaboutaweektoco
mpleteeach
assignment.
Thelabexercisesaresumm
arizedhere.Thecomplete
assignmentsandtheirsoluti
ons
canbeobtainedfromthea
uthor.

49
DEPT IT CMREC

6.1IntroductiontotheWom
bat1
Before learning to use CPU
 Sim, the students are giv
en an exercise in which t
hey are
presented with a hypothetic
al machine (the "Wombat1",
 a simple accumulator-
based
machinewithonly12machi
neinstructions,nostack,an
donlydirectaddressing)an
dtwo
programs for that machine
written in binary machine l
anguage.  The first progra
m is

50
DEPT IT CMREC

documentedandthesecond
isnot.Thestudentsare
askedtomodifythefirst
programto
do something slightly differe
nt and to figure out what
 the second machine langu
age
program does.  The purpo
se of this pre-
lab assignment is (a) to
get the students
comfortable with the archite
cture of the Wombat1 befo
re seeing it in the CPU
Sim
environment,and(b)toget
themtoappreciateassemb

51
DEPT IT CMREC

lylanguagebyhavingto
program
firstinbinarymachinelangu
age.

6.2IntroductiontoCPUSim

In the first (closed) lab, th
e students are introduced t
o CPU Sim and are asked
 to step
throughtheintroductorytutor
ialgivenintheCPUSim
user'smanual.Thenthes
tudents
are asked to redo the pre
vious pre-
lab assignment using assemb
ly language instead of
52
DEPT IT CMREC

machinelanguage,andfinally
runtheresultingprogram
intheCPUSimenvironme
nt.
Afterthisfirstclosedlab,al
lassignmentsareopenlab
assignments.

6.3OptionalWombat1Interpr
eter
One option at this point is
 to ask the students to
write a Wombat1 interpreter
 in their
favoritehigh-
levellanguage.Theinterpr
etershouldtakeasinput
atextfilecontaininga

53
DEPT IT CMREC

Wombat1 machine language


program (in 0's and 1's a
s described above) and sh
ould
executethatprogram.This
projecthelpsthestudents
understandtheWombat1b
etterand
givesthemafeelingforho
wsimulationandinterpretatio
nworks.

6.4IntroductiontotheWom
bat2
Thenextassignmentisto
writeamorecomplicatedas
semblylanguageprogramfor
the

54
DEPT IT CMREC

Wombat1thataccessesmem
oryfrequently.Afteradis
cussionofthecostsofacc
essing
memory,studentsaregiven
theWombat2,whichissimil
artotheWombat1except
ithas
an array of 4 general-
purpose registers and all
machine instructions refer t
o those
registers instead of an accu
mulator.  The students are
 then asked to redo the
previous
assignment, this time minimi
zing memory references thro

55
DEPT IT CMREC

ugh efficient use of the


4
general-
purposeregistersforholding
intermediateresults.

6.5LimitationsoftheWomb
at2
Thenextassignmentaskst
hestudentstowriteapro
gramfortheWombat2that
reverses
anarbitrarilylonglistofin
tegers.Suchaprogramc
aneasilybewrittenfora
CPUwitha
stackorwithinstructionswit
hindirectorindexedaddres

56
DEPT IT CMREC

singmodes,buttheonlyw
aythe
Wombat2canaccomplishthis
taskiswithself-
modifyingcode.Thisexerci
senotonly
teachesthestudentsthelim
itationsofamachinewith
nostackandonlydirectad
dressing,
itprovidesagoodstarting
pointforadiscussionof
theadvantagesanddisadvan
tagesof
self-modifyingcode.

6.6Wombat3
For the next several assig
nments, the students are
57
DEPT IT CMREC

not given any more hypoth


etical
architectures.Instead,they
areaskedtograduallyenha
ncetheWombat2themselves
,to
giveitmorepower.For
example,thestudentsarea
skedtocreatetheWombat3
fromthe
Wombat2 by adding a stac
k, a new stack pointer re
gister, and push and pop
machine
instructionstotheWombat2.
Theythenareaskedto
redothepreviousassignme
ntusing

58
DEPT IT CMREC

thestack,toseehowmuc
heasierreversingalistof
integersisusingthenew
features.

6.7Wombat4
Thenextenhancement,whic
hresultsintheWombat4,
istoaddcallandreturn
machine
instructions, allowing subrouti
ne calls.  Then students
are given assignments to w
rite
subprogramsusingvaluepar
ametersandrecursion.
Thestudentstypicallyhave
alittletroublewiththisas

59
DEPT IT CMREC

signmentsincethereisstill
no
addressingmodeintheWo
mbat4otherthandirectadd
ressing,whichmeansthatt
heonly
practicalwaytoaccessthe
valuesonthestackisby
poppingthemofffirst.

6.8Wombat5
Thestudentsarenextdirect
edtocreatetheWombat5
byaddingindirect,stack-
relative,
andimmediateaddressingm
odes,whichallowtheprope
rdevelopmentanduseof
stack
60
DEPT IT CMREC

frames and allow call-by-


address parameters in subro
utine calls.  Students are
asked to
rewrite previous programs us
ing subroutines thatuse an
d maintain stack frames. 
They
are also asked to manipul
ate arrays on the stack
via indirect addressing. 
Such
manipulationsmightincludefi
ndingtheminimumofors
ortingthearray.

6.9Wombat6
Tomakeworkingwitharray
seveneasier,thestudents
61
DEPT IT CMREC

canthencreatetheWom
bat6from 
theWombat5by addingan
indexregisterandindexed-
addressingmode,atwhich
point
they can be told to redo
 the previous array-
manipulation assignment usin
g indexed
addressing.

6.10Wombat7
TomaketheWombat6more
realistic,thefinalstepin
thisseriesofassignments
istoadd
bit operations (and, or, xor,
 not), and shift operations
62
DEPT IT CMREC

 to form the Wombat7. 


Thenthe
students are asked to write
 a program using these n
ew operations to manipulate
 data
storedinbinary-
codeddecimalformat.


Figure9.AsimpleJVMprogram.

6.11JVM1
About two-
thirds of the way through
 the semester, the students
 are given a simplified
versionoftheJavaVirtual
Machine(JVM),sothatthey
63
DEPT IT CMREC

cangetexposuretoaCI
SC-like
stack-
based architecture.  This
machine is almost identical
 to the IJVM discussed in

[Tanenbaum 1999] except th
at it containsonly 24 mac
hine instructions, none of w
hich
allowtheusertostoreval
uesinvariablesandsoreq
uirealldatatobestored
onthestack
bymeansofpushingand
popping.Thestudentsare
askedtowritesimplepro
gramsfor
64
DEPT IT CMREC

theJVM1togetusedto
thisnewarchitectureandt
henthey are askedtowrit
eslightly
harder programs that require
 complex stack manipulations
due to the lack of varia
bles.
SeeFigure9forasimple
JVM1program.

6.12JVM2
Students are asked to creat
e the JVM2 from the JVM1
 by adding three new ma
chine
instructionswhichallowstori
ng,loading,andincrementing

65
DEPT IT CMREC

localvariablesonthesta
ck
andthentheyareaskedto
redothepreviousassignme
nt.

6.13JVM3
The students create the JV
M3 from the JVM2 by add
ing procedure calls and ret
urns.
Afteraddingsuchinstructions
,studentsareaskedtowri
terecursiveprograms,such
asa
simplefactorialprogram,to
testthecallandreturnins
tructions.Thisturnsoutt
obea
66
DEPT IT CMREC

quite difficult assignment if


 the JVM stack frames f
ollow the layout described
 in
[Tanenbaum1999].

6.14JVM4
The final improvement, whic
h leads to the JVM4, is
the addition to the JVM3
of
instructionsthatperformthe
creationofandallowacce
sstoarraysintheheap.
Students
areaskedtowriteasortin
groutineforsuchanarray.


67
DEPT IT CMREC

7.LIMITATIONSOFCPUSIM

Itwouldbequitedifficultto
constructasimulatorthat
engagesthestudentsinal
ltheCS-
2001architectureknowledge
areasandyetissimpleen
oughforstudentstousei
naCS3
class, and at the same ti
me allows students to con
struct and test hypothetical
 CPUs
themselves. Therefore the a
uthor intentionally left out
of CPU Sim some importan
t

68
DEPT IT CMREC

architecturetopics.Theset
opicsinclude:
1. floatingpointnumberre
presentations,
2. computerorganizationbel
owthemicrocodelevel,suc
hastransistorsandgates,
3. issuesconcerningthesp
eedofexecution,includings
uchissuesaspipelining,par
allel
processing,andtheuseof
caches,
4. interruptsandtraps,
5. operatingsystemconcept
ssuchasvirtualmemorya
ndfilemanagement,

69
DEPT IT CMREC

6. thelinkingandloading
ofseparateassemblymodul
es.
AddingfeaturestoCPUSim
toaddressthesetopicsw
ouldhavemadeitsignifican
tly
more complex and so, in
the author's view, less peda
gogically useful for the inte
nded
audience.

8.CONCLUSION
CPUSimisaCPUsimulati
onprogramdesignedforus
ewithCS3coursesthatall
owsthe

70
DEPT IT CMREC

studentstocreateormodif
ythearchitecturesbeingst
udied.Itisaninteractive
learning
environment in which stude
nts can create, study, and
 modify a variety of sim
ple
architectures at the register-
transfer level.  It is a full
y-
integrated package that inclu
des
texteditorsforwritingprog
rams,anassembler,on-
linehelp,andmanydebugg
ingtools
tohelptheusereasilymo
difythearchitecturesandt
71
DEPT IT CMREC

henwriteandexecuteprog
ramson
thosearchitecturesan architecture and a series of
assignments that repeatedly ask the students to add and implement new features for it, such as
new addressing modes, new machine instructions, or new registers, to make programming
easier for that architecture. At each stage, the students could also be given assembly language
programming assignments that emphasize the advantages of the new features being added.
1. Detailed Components of Virtual Memory
To simulate virtual memory effectively, it's essential to understand its core components and their interactions in
detail.
Virtual Address Space
 Definition: The range of addresses that a process can use. It is typically larger than the physical
memory, allowing for abstraction and isolation between processes.
 Structure: Typically divided into segments like code, data, heap, and stack.
Physical Address Space
 Definition: The actual addresses in the physical RAM.
 Structure: Divided into fixed-size blocks called Page Frames.
Pages and Page Frames
 Page: A fixed-size block of virtual memory (commonly 4KB).
 Page Frame: A fixed-size block of physical memory that holds a page.
 Page Size: Determines the granularity of memory management (commonly powers of 2, like 4KB).
Page Table
 Purpose: Maintains the mapping between virtual pages and physical frames.
 Structure: Each entry (Page Table Entry - PTE) corresponds to a virtual page and contains:
o Frame Number: Indicates the physical frame where the page is loaded.
o Present Bit: Indicates if the page is currently in physical memory.
o Dirty Bit: Indicates if the page has been modified.
o Reference Bit: Used for page replacement algorithms to track usage.
o Access Permissions: Read, write, execute permissions for the page.

72
DEPT IT CMREC

Translation Lookaside Buffer (TLB)


 Purpose: A cache for recent virtual-to-physical address translations to speed up memory access.
 Structure: Contains a small number of PTEs.
 Operation: On a virtual address access, the TLB is checked first. If a match is found (TLB Hit), the
physical address is retrieved quickly. Otherwise (TLB Miss), the page table is consulted, and the TLB is
updated with the new translation.
Page Replacement Policies
 Purpose: Decide which page to evict from physical memory when a new page needs to be loaded, and
memory is full.
 Common Policies:
o FIFO (First-In-First-Out)
o LRU (Least Recently Used)
o Clock (Second Chance)
o Random Replacement
Page Fault Handling
 Definition: Occurs when a program accesses a page not currently in physical memory.
 Steps to Handle:
1. Interrupt: CPU signals a page fault.
2. OS Intervention: The operating system determines which page to evict (if necessary).
3. Load Page: The required page is loaded from secondary storage (e.g., disk) into a free frame.
4. Update Structures: The page table and TLB are updated accordingly.
5. Resume Execution: The instruction causing the fault is retried.

2. Step-by-Step Implementation Guide


Let's outline how to build a virtual memory simulation step by step. We'll use Python for its simplicity and
readability, but the principles apply to other programming languages as well.
Define System Parameters
Start by setting the fundamental parameters of your simulation.
python
Copy code
PAGE_SIZE = 4096 # 4KB
73
DEPT IT CMREC

VIRTUAL_MEMORY_SIZE = 16 * 1024 * 1024 # 16MB


PHYSICAL_MEMORY_SIZE = 8 * 1024 * 1024 # 8MB
NUM_VIRTUAL_PAGES = VIRTUAL_MEMORY_SIZE // PAGE_SIZE # 4096 pages
NUM_PHYSICAL_FRAMES = PHYSICAL_MEMORY_SIZE // PAGE_SIZE # 2048 frames
TLB_SIZE = 16 # Number of entries in the TLB
Create Data Structures
Page Table Entry (PTE)
python
Copy code
class PageTableEntry:
def __init__(self, frame_number=None, present=False, dirty=False, referenced=False):
self.frame_number = frame_number
self.present = present
self.dirty = dirty
self.referenced = referenced
Page Table
python
Copy code
class PageTable:
def __init__(self, num_pages):
self.entries = [PageTableEntry() for _ in range(num_pages)]
TLB Entry
python
Copy code
class TLBEntry:
def __init__(self, virtual_page_number, frame_number):
self.virtual_page_number = virtual_page_number
self.frame_number = frame_number
TLB

74
DEPT IT CMREC

python
Copy code
class TLB:
def __init__(self, size):
self.size = size
self.entries = []

def lookup(self, virtual_page_number):


for entry in self.entries:
if entry.virtual_page_number == virtual_page_number:
return entry.frame_number
return None

def add_entry(self, virtual_page_number, frame_number):


if len(self.entries) >= self.size:
self.entries.pop(0) # FIFO replacement for TLB
self.entries.append(TLBEntry(virtual_page_number, frame_number))
Physical Memory Frames
python
Copy code
class PhysicalMemory:
def __init__(self, num_frames):
self.frames = [None] * num_frames # None indicates free frame
self.free_frames = list(range(num_frames)) # List of free frame indices

def allocate_frame(self):
if self.free_frames:
return self.free_frames.pop(0)
else:

75
DEPT IT CMREC

return None # No free frames available

def free_frame(self, frame_number):


self.frames[frame_number] = None
self.free_frames.append(frame_number)
Implement Page Replacement Policies
Here, we'll implement the LRU (Least Recently Used) policy as an example.
python
Copy code
class LRUPageReplacement:
def __init__(self, num_frames):
self.num_frames = num_frames
self.frame_usage = {} # frame_number: last_used_time
self.time = 0

def access_frame(self, frame_number):


self.time += 1
self.frame_usage[frame_number] = self.time

def select_victim_frame(self):
# Select the frame with the oldest last_used_time
victim_frame = min(self.frame_usage, key=self.frame_usage.get)
return victim_frame
Simulate Memory Accesses
Define a function to simulate memory accesses (reads and writes).
python
Copy code
def simulate_memory_accesses(memory_access_sequence, page_table, tlb, physical_memory,
page_replacement_policy):
page_faults = 0
76
DEPT IT CMREC

tlb_hits = 0
tlb_misses = 0

for access in memory_access_sequence:


operation, virtual_address = access # e.g., ('read', 0x1A3F)
virtual_page_number = virtual_address // PAGE_SIZE
offset = virtual_address % PAGE_SIZE

# Check TLB
frame_number = tlb.lookup(virtual_page_number)
if frame_number is not None:
tlb_hits += 1
page_table.entries[virtual_page_number].referenced = True
page_replacement_policy.access_frame(frame_number)
else:
tlb_misses += 1
# Check Page Table
pte = page_table.entries[virtual_page_number]
if pte.present:
frame_number = pte.frame_number
tlb.add_entry(virtual_page_number, frame_number)
pte.referenced = True
page_replacement_policy.access_frame(frame_number)
else:
# Page Fault Handling
page_faults += 1
frame_number = physical_memory.allocate_frame()
if frame_number is None:
# No free frames, need to evict one

77
DEPT IT CMREC

victim_frame = page_replacement_policy.select_victim_frame()
# Find the virtual page that maps to the victim frame
victim_virtual_page = None
for vp, entry in enumerate(page_table.entries):
if entry.present and entry.frame_number == victim_frame:
victim_virtual_page = vp
break
if victim_virtual_page is not None:
# Evict the victim page
page_table.entries[victim_virtual_page].present = False
# If dirty, write back to disk (simulated)
if page_table.entries[victim_virtual_page].dirty:
pass # Simulate writing back
# Update physical memory
physical_memory.free_frame(victim_frame)
frame_number = victim_frame
else:
raise Exception("No victim found for replacement.")
# Load the new page into the frame (simulated)
page_table.entries[virtual_page_number].present = True
page_table.entries[virtual_page_number].frame_number = frame_number
page_table.entries[virtual_page_number].dirty = (operation == 'write')
page_table.entries[virtual_page_number].referenced = True
tlb.add_entry(virtual_page_number, frame_number)
page_replacement_policy.access_frame(frame_number)

# Handle write operations


if operation == 'write' and frame_number is not None:
page_table.entries[virtual_page_number].dirty = True

78
DEPT IT CMREC

return {
'page_faults': page_faults,
'tlb_hits': tlb_hits,
'tlb_misses': tlb_misses
}
Generate a Memory Access Sequence
For simulation purposes, create a sequence of memory accesses. This can be randomized or based on specific
patterns.
python
Copy code
import random

def generate_memory_access_sequence(num_accesses, num_pages):


sequence = []
for _ in range(num_accesses):
operation = random.choice(['read', 'write'])
virtual_page_number = random.randint(0, num_pages - 1)
virtual_address = virtual_page_number * PAGE_SIZE + random.randint(0, PAGE_SIZE - 1)
sequence.append((operation, virtual_address))
return sequence
Putting It All Together
python
Copy code
def main():
# Initialize components
page_table = PageTable(NUM_VIRTUAL_PAGES)
tlb = TLB(TLB_SIZE)
physical_memory = PhysicalMemory(NUM_PHYSICAL_FRAMES)
page_replacement_policy = LRUPageReplacement(NUM_PHYSICAL_FRAMES)
79
DEPT IT CMREC

# Generate a memory access sequence


memory_access_sequence = generate_memory_access_sequence(10000, NUM_VIRTUAL_PAGES)

# Simulate memory accesses


stats = simulate_memory_accesses(memory_access_sequence, page_table, tlb, physical_memory,
page_replacement_policy)

# Display statistics
print(f"Total Memory Accesses: {len(memory_access_sequence)}")
print(f"TLB Hits: {stats['tlb_hits']}")
print(f"TLB Misses: {stats['tlb_misses']}")
print(f"TLB Hit Rate: {stats['tlb_hits'] / len(memory_access_sequence) * 100:.2f}%")
print(f"Page Faults: {stats['page_faults']}")
print(f"Page Fault Rate: {stats['page_faults'] / len(memory_access_sequence) * 100:.2f}%")

if __name__ == "__main__":
main()

3. Example Simulation Run


Let's walk through an example scenario to understand how the simulation operates step-by-step.
Initial State
 Virtual Pages: 4096 (0 to 4095)
 Physical Frames: 2048 (0 to 2047)
 TLB: Empty
 Page Table: All pages not present
 Physical Memory: All frames free
First Memory Access: Read from Virtual Address 0x0000 (Page 0)
1. TLB Lookup: Miss (TLB is empty).
2. Page Table Lookup: Page 0 not present → Page Fault.
80
DEPT IT CMREC

3. Page Fault Handling:


o Allocate Frame 0.
o Load Page 0 into Frame 0.
o Update Page Table: Page 0 → Frame 0, Present = True.
o Update TLB: Add (Page 0 → Frame 0).
4. Access Physical Address: Frame 0 + Offset 0x0000 → Physical Address 0x0000.
5. Statistics Update:
o TLB Misses: 1
o Page Faults: 1
Second Memory Access: Write to Virtual Address 0x1000 (Page 1)
1. TLB Lookup: Miss.
2. Page Table Lookup: Page 1 not present → Page Fault.
3. Page Fault Handling:
o Allocate Frame 1.
o Load Page 1 into Frame 1.
o Update Page Table: Page 1 → Frame 1, Present = True, Dirty = True.
o Update TLB: Add (Page 1 → Frame 1).
4. Access Physical Address: Frame 1 + Offset 0x0000 → Physical Address 0x1000.
5. Statistics Update:
o TLB Misses: 2
o Page Faults: 2
Third Memory Access: Read from Virtual Address 0x0000 (Page 0)
1. TLB Lookup: Hit (Page 0 → Frame 0).
2. Access Physical Address: Frame 0 + Offset 0x0000 → Physical Address 0x0000.
3. Statistics Update:
o TLB Hits: 1
Subsequent Accesses
Continue processing each memory access similarly, updating the TLB, handling page faults, and applying the
page replacement policy when necessary.

81
DEPT IT CMREC

Final Statistics
After processing all accesses, you might get statistics like:
yaml
Copy code
Total Memory Accesses: 10000
TLB Hits: 8000
TLB Misses: 2000
TLB Hit Rate: 80.00%
Page Faults: 1500
Page Fault Rate: 15.00%
Note: The actual numbers will vary based on the generated access sequence and the behavior of the
replacement policy.

4. Enhanced Features and Considerations


To make your simulation more realistic and comprehensive, consider implementing the following features:
Multi-Level Page Tables
Modern systems use multi-level page tables to handle large virtual address spaces efficiently. Implementing a
two-level or multi-level page table can simulate more complex memory hierarchies.
Segmentation
Beyond paging, segmentation divides memory into variable-sized segments (e.g., code, data). Incorporate
segmentation to handle different memory regions with distinct attributes.
Demand Paging vs. Pre-Paging
 Demand Paging: Load pages into memory only when they are accessed.
 Pre-Paging: Predict and load pages before they are accessed to reduce page faults.
Implementing pre-paging can enhance performance but adds complexity to the simulation.
Working Set Model
Track the working set of a process (the set of pages actively used) to optimize page replacement decisions and
reduce thrashing.
Page Coloring and NUMA Considerations
For simulations involving Non-Uniform Memory Access (NUMA) architectures, consider page coloring to
optimize memory placement and access speeds.

82
DEPT IT CMREC

5. Performance Analysis and Visualization


Analyzing the performance of your virtual memory simulation is crucial to understand its efficiency and the
impact of different configurations.
Metrics to Track
 TLB Hit Rate: Percentage of memory accesses resolved by the TLB.
 Page Fault Rate: Frequency of page faults per memory access.
 Average Memory Access Time (AMAT):
AMAT=TLBhit×TTLB+TLBmiss×(TPageTable+TMemory)AMAT = TLB_{hit} \times T_{TLB} +
TLB_{miss} \times (T_{PageTable} + T_{Memory})AMAT=TLBhit×TTLB+TLBmiss×(TPageTable
+TMemory)
 Page Replacement Overhead: Time spent handling page faults and evictions.
 Memory Utilization: Percentage of physical memory in use.
Visualization Techniques
 Graphs and Charts:
o TLB Hit/Miss Rates: Line charts showing hit/miss rates over time.
o Page Fault Trends: Bar charts depicting the number of page faults under different policies.
o Memory Utilization: Pie charts or area charts illustrating used vs. free memory.
 Heatmaps: Visualize memory access patterns and hot pages.
 Statistical Reports: Summarize key performance metrics in tables for comparison.
Sample Visualization with Matplotlib (Python)
Here's how you might visualize TLB hits and page faults using Python's matplotlib library.
python
Copy code
import matplotlib.pyplot as plt

def visualize_statistics(stats):
labels = ['TLB Hits', 'TLB Misses', 'Page Faults']
values = [stats['tlb_hits'], stats['tlb_misses'], stats['page_faults']]

plt.figure(figsize=(8,6))
83
DEPT IT CMREC

plt.bar(labels, values, color=['green', 'red', 'blue'])


plt.title('Virtual Memory Simulation Statistics')
plt.ylabel('Count')
for i, v in enumerate(values):
plt.text(i, v + max(values)*0.01, str(v), ha='center', va='bottom')
plt.show()
Usage:
python
Copy code
# After running the simulation
visualize_statistics(stats)
This will produce a bar chart displaying the counts of TLB hits, TLB misses, and page faults.

6. Advanced Simulation Enhancements


To further enrich your simulation, consider incorporating the following advanced features:
Simulating Secondary Storage (Disk)
Implement a representation of secondary storage (e.g., disk) where pages are stored when not in physical
memory. Track the time or cost associated with loading pages from disk.
python
Copy code
class Disk:
def __init__(self, num_pages):
self.storage = {vp: None for vp in range(num_pages)} # Simulate disk storage

def load_page(self, virtual_page_number):


# Simulate loading a page from disk
pass

def write_page(self, virtual_page_number, data):


# Simulate writing a page to disk
84
DEPT IT CMREC

pass
Supporting Multiple Processes
Extend the simulation to handle multiple processes, each with its own virtual address space and page tables.
Manage inter-process isolation and shared pages.
Incorporating Swap Space
Implement swap space to temporarily hold pages that have been evicted from physical memory. This adds
realism to how operating systems handle memory pressure.
Simulating Access Patterns
Use realistic memory access patterns based on benchmarks or real-world applications to evaluate the
simulation's behavior under different workloads.
Implementing Advanced Replacement Policies
Explore and implement more sophisticated page replacement algorithms like NRU (Not Recently Used), MFU
(Most Frequently Used), or WSClock to compare their effectiveness.

7. Sample Code Walkthrough


Let's walk through a sample memory access sequence and see how the simulation handles it.
Sample Access Sequence
python
Copy code
memory_access_sequence = [
('read', 0x0000), # Page 0
('write', 0x1000), # Page 1
('read', 0x2000), # Page 2
('read', 0x0000), # Page 0 (TLB Hit)
('write', 0x3000), # Page 3
('read', 0x4000), # Page 4
('read', 0x1000), # Page 1 (TLB Hit)
('write', 0x5000), # Page 5
# ... more accesses
]
Simulation Steps
85
DEPT IT CMREC

1. Access 1: Read Page 0


o TLB Miss → Page Fault
o Load Page 0 into Frame 0
o Update TLB with (Page 0 → Frame 0)
2. Access 2: Write Page 1
o TLB Miss → Page Fault
o Load Page 1 into Frame 1
o Set Dirty Bit for Page 1
o Update TLB with (Page 1 → Frame 1)
3. Access 3: Read Page 2
o TLB Miss → Page Fault
o Load Page 2 into Frame 2
o Update TLB with (Page 2 → Frame 2)
4. Access 4: Read Page 0
o TLB Hit (Page 0 → Frame 0)
5. Access 5: Write Page 3
o TLB Miss → Page Fault
o Load Page 3 into Frame 3
o Set Dirty Bit for Page 3
o Update TLB with (Page 3 → Frame 3)
6. Access 6: Read Page 4
o TLB Miss → Page Fault
o Load Page 4 into Frame 4
o Update TLB with (Page 4 → Frame 4)
7. Access 7: Read Page 1
o TLB Hit (Page 1 → Frame 1)
8. Access 8: Write Page 5
o TLB Miss → Page Fault
o Load Page 5 into Frame 5
86
DEPT IT CMREC

o Set Dirty Bit for Page 5


o Update TLB with (Page 5 → Frame 5)
Post-Access State
 TLB Entries:
o Page 0 → Frame 0
o Page 1 → Frame 1
o Page 2 → Frame 2
o Page 3 → Frame 3
o Page 4 → Frame 4
o Page 5 → Frame 5
 Page Table Entries:
o Pages 0-5: Present = True, with respective frame numbers.
o Dirty Bits set for Pages 1, 3, and 5.
 Physical Memory:
o Frames 0-5: Occupied by Pages 0-5.
o Frames 6-2047: Free.
 Statistics:
o TLB Hits: 2
o TLB Misses: 6
o Page Faults: 6

8. Testing and Validation


To ensure your simulation is accurate and robust, perform thorough testing and validation.
Unit Tests
 Page Table Operations: Verify that page table lookups, updates, and evictions work correctly.
 TLB Operations: Ensure that TLB lookups, additions, and evictions follow the intended policy.
 Page Replacement Policies: Test each replacement algorithm to confirm correct victim selection.
 Memory Allocation: Check that frames are allocated and freed properly without overlaps.
Simulation Scenarios

87
DEPT IT CMREC

 Sequential Access: Access pages in sequential order to observe cache-like behavior.


 Random Access: Access pages randomly to test the general case.
 Localized Access: Access a small subset of pages repeatedly to simulate locality of reference.
 Stress Testing: Generate high volumes of accesses to evaluate performance under heavy load.
Compare with Expected Results
Manually calculate expected statistics for small access sequences and compare them with simulation outputs to
verify correctness.

9. Extending the Simulation for Educational Purposes


To enhance the educational value of your simulation, consider adding features that illustrate advanced concepts
and allow interactive exploration.
Interactive Visualization
Create a GUI or web-based interface to visualize the state of the TLB, page table, and physical memory in real-
time as memory accesses occur.
Step-by-Step Execution
Allow users to execute memory accesses step-by-step, observing how each access affects the system's state.
Configurable Parameters
Provide options to adjust system parameters like page size, number of frames, TLB size, and replacement
policies to see their impact on performance.
Logging and Debugging Tools
Implement detailed logging to trace memory accesses, page faults, and replacements. Include debugging tools
to inspect the internal state at any point.
Educational Tutorials
Incorporate tutorials or guided exercises that explain virtual memory concepts using the simulation as a
teaching aid.

88
DEPT IT CMREC

Conclusion
Creating a virtual memory simulation is an excellent way to understand the intricate mechanisms of memory
management in computer systems. By following the detailed implementation steps, incorporating advanced
features, and performing thorough testing, you can develop a robust simulation that not only serves as a
valuable project but also as an educational tool.

89

You might also like