Coa Project
Coa Project
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
CERTIFICATE
This is to certify that the project entitled "CPU STIMULATOR" is a work carried out by:
In the part of individual project report of CPU stimulator laboratory under the guidance and
supervision
2
DEPT IT CMREC
TABLE OF CONTENTS
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.
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
CPUSimisantoolthatw
asdesignedtofacilitatesuc
hinteractivehands-
onlearning.
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),andstack-
basedCPU's,forexample,a
ndthey
can run programs on them
without the need of any
6
DEPT IT CMREC
7
DEPT IT CMREC
•
Microprogrammedrealizationo
ftheCPU
•
Controlunit;instructionfetch,
decode,andexecution
•
Instructiontypes(datamanip
ulation,control,I/O)
• Instructionformats
•
Assembly/machinelanguagepr
ogramming
• Addressingmodes
•
Mainmemoryorganizationan
doperations
The knowledge of a high-
level language is not a pr
8
DEPT IT CMREC
butitworkswellwithit.
TheprecursortoCPUSim
canbefoundin[Kerridge
etal.1980].CPUSimv
ersion
1.0.13 and its uses in the
classroom were discussed
in [Skrien et al. 1991].
A later
version(2.2)wasdiscussed
in[Skrien1994]Thecurr
entversionofCPUSim, v
ersion
3.1,was writtenusingJava
2 andtheSwingpackage
.Ithasbeentestedon
computers
runningMacOSX,Windows
98/NT/2000,andLinux.
10
DEPT IT CMREC
11
DEPT IT CMREC
nternaltothismainwindow.
The
internalwindowsincludeone
sthatdisplaythecontents
ofregistersandRAMsand
ones
thatcontaintextsuchasa
ssemblyprograms.Eachof
theseinnerwindowsand
manyof
themenuitemsarediscusse
dinlatersectionsofthis
paper.
Fig.1.CPUSim'smaindisplaywin
dow.
12
DEPT IT CMREC
3.DESIGNFEATURESOFCP
USIM
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,
andassemblylanguageinstru
ctionsforahypotheticalma
chine.
A machine instruction is im
plementedby a sequence o
f microinstructions called its
"executesequence".Theu
serspecifiestheexecutese
13
DEPT IT CMREC
quenceofallmachineinstru
ctions
andsotheuserhascompl
etecontroloverthesemanti
csofeveryinstruction.W
henCPU
Sim executes a program, it
repeatedly executes machin
e cycles that consist of a
fetch
sequence(asequenceofmi
croinstructionsspecifiedbyth
euser)followedbytheex
ecute
sequenceofthemachineins
tructionthatwasfetched.
3.1SpecifyingtheHardware
Components
14
DEPT IT CMREC
mberofregistersinthearr
ay,andthe
widthofallregisters.Thes
earraysarespecifiedthrou
ghthedialogboxshowni
nFigure
2. If an array of 16 r
egisters is named "A", then
CPU Sim automatically giv
es each
individualregisterinthearra
ythenames"A[0]","A[1]",..
.,"A[15]".
Figure2.Thedialogforeditedre
gisterarrays.
16
DEPT IT CMREC
17
DEPT IT CMREC
thecode,onetoholdth
estack,and
onetoholdtheheap,ort
heusermaywishtouse
onlyoneRAMtoholdever
ything.
Thelasttypeofhard
warecomponenttheusers
pecifiesisa"conditionbit"
(see
Figure3).Conditionbitsa
rejustspecificbitsofexist
ingregistersthatcanbes
etto1by
microinstructions and optionall
y by arithmetic operations
if an overflow or carry o
ut
18
DEPT IT CMREC
occurs.Forexample,aty
picalstatusregisterwithNZ
VCbitscanbespecifiedth
isway.
Theusercanalsospecify
whetherthesettingofac
onditionbitwillhalttheex
ecutionof
thecurrentprogram.
Figure3.Thedialogforeditingc
onditionbits.
3.2SpecifyingtheMicroinstruc
tions
The user next creates micr
oinstructions for manipulating
19
DEPT IT CMREC
21
DEPT IT CMREC
3. Transferoperationfrom
aregisterinanarrayto
aregister.Thisoperation
issimilar
totheprecedingkindofmi
croinstruction.
Figure4.Thedialogforeditingtr
ansfermicroinstructions.
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
whetheranyconditionbitss
houldbesetifoverflowor
carryoutoccurs.Noteth
at
thereisnofloatingpoints
upportinCPUSim.
5. Logical (boolean) operati
on. The user specifies th
e operation (and, or, nand,
nor,
xor,not),thesourceregister
s,andthedestinationregist
er.
6. Shiftoperation.Theu
serspecifiesthetypeofs
hift(logical,arithmetic,orc
yclical),
the direction of the shift
(left or right), the amount
23
DEPT IT CMREC
mparisontobeused(=,
<,>,
<=,>=),thevaluetobe
compared,theregister,the
bitsoftheregistertob
etested,
andtheamounttojumpif
thetestsucceeds.
8. Branchoperation.This
microinstructionislikeat
estmicroinstructionexceptth
atit
is an unconditional jump.
The user specifies the a
mount to jump, which can
be
positiveornegative.
9. Incrementoperation.T
heuserspecifiestheregist
25
DEPT IT CMREC
ertobeincremented,the
amount
oftheincrement,andwheth
eranyconditionbitsareto
besetifoverfloworcarr
yout
occurs.
10. Setoperation.Thiso
perationsetsaspecifiedpar
tofaregistertoaspecif
iedvalue.
Theuserchoosestheregist
er,theconsecutivebitsof
thatregisterthatareto
beset,
andthevalue.
11. Setconditionbitoperat
ion.Thisoperationsetsa
26
DEPT IT CMREC
conditionbitto0or1.
Theuser
choosestheconditionbitan
dthevaluetowhichitis
tobeset.
12. Memoryaccessoperation
.Theuserspecifiesada
taregister,anaddressregis
ter,the
RAM,andthedirectionofd
atamovement(readorwrit
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
instructiontobeexecuted.
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
fetchsequence,andsostart
anewmachinecycle.
3.3SpecifyingtheMachineI
nstructionsandtheFetchSe
quence
The user specifies the se
mantics of each machine
instruction by a sequence
of
29
DEPT IT CMREC
microinstructionscalledits"e
xecutesequence".Therefore
theusercancreateverysi
mple
instructionssuchasincremen
tingaregisteror veryco
mplexinstructionswithelabo
rate
addressing schemes involving
multiple registers and RA
Ms. The user can creat
e
instructionsthat are RISC-
like, in that they all have
the same length and layo
ut, or the
usercanchooseCISC-
likeinstructionswithvariable
30
DEPT IT CMREC
lengthsandavarietyof
layouts.
In addition to the execute
sequence, the user specifi
es a name for each mac
hine
instruction,anopcode,and
asequenceoffieldlengths.
Thesumofthefieldl
engthsis
thelength(inbits)ofthe
instruction.Thefirst field
correspondstotheopcode
andthe
remainingfieldscorrespondt
ooperandsoftheinstructio
n.SeeFigure5 forthe
dialog
31
DEPT IT CMREC
boxforeditingmachineinst
ructions.
CPUSimalsohasa
dialogbox(notshownhere)
inwhichtheusercansp
ecify
thefetchsequence.Thef
etchsequenceisasequenc
eofmicroinstructionsthatC
PUSim
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
machineinstruction,placeit
inaninstructionregister,
incrementaprogramcounter
,and
thendecodetheinstructioni
ntheinstructionregister.
Figure5.Thedialogforediting
machineinstructions.
3.4SavingandViewingthe
Specification
Onceanarchitecturehasbe
enspecified,theusercan
savethisspecificationinan
XML
file for later reloading into
CPU Sim and editing. T
33
DEPT IT CMREC
34
DEPT IT CMREC
35
DEPT IT CMREC
36
DEPT IT CMREC
37
DEPT IT CMREC
memorytospecifiedvalues
oran"include"directivetha
tinsertsthecontentsofa
nother
fileinthecurrentprogram
beforeassembly.
Onceanassemblyprogram
hasbeenwrittenandsaved
toafile,itcanbeass
embled.
TheCPUSimassemblerwill
checkforerrorsinthec
odeand,iftherearesuch
errors,it
willdisplayanerrormessag
eandhighlighttheoffendin
glineintheassemblycod
e.Ifno
38
DEPT IT CMREC
errorsoccur,theassembled
machinecodecanbeloaded
intoanyspecifiedRAM,th
euser
caninitializeanyofthere
gisterstospecifiedvalues,
andthenexecutionofthe
program
canbegin.
If during execution the use
r's program requests input
from the user, a dialog b
ox
appearsaskingtheuserto
typeinavalue.Ifthe
programspecifiesoutputto
theuser,this
outputappearsin adialog
box. Inputandoutput
39
DEPT IT CMREC
can alsobedirectedtoan
dfromtext
files.
Oncetheprogramhalts(bec
auseaconditionbitwasse
tto1,anerroroccurred,
orthe
user selected the "Stop" m
enu item) the user can i
nspect the state of the
machine,
includingthecontentsofthe
registersandRAMs.
5.SPECIALFEATURESOFCP
USIM
Someofthestrengthsof
CPUSimincludeitsdisplay
40
DEPT IT CMREC
ofregistersandRAMs,its
editing
and debugging aids, and its
help facilities, all of whic
h make it easier for the
user to
understandwhatishappening
asaprogramisexecuting
.
5.1DisplayingRegistersand
RAMs
Theusercanviewthecont
entsoftheregistersandR
AMsthoughwindows(forex
ample,
seethewindowslabeled"R
egisters"and"RAMMain"in
41
DEPT IT CMREC
Figure1).Thecontents
ofthe
registerscanbeviewedand
edited,ifdesired,ineithe
rdecimal,binary,orhexad
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
correspondingtothewords
izeofthearchitecturebein
gsimulated.Furthermore,
RAM
windowsincludeacolumnf
orcommentsassociatedwith
eachwordofmemory,w
hich
providesawayfortheuse
rtoindicatethecontentso
ftheword.Theassembler
initializes
thiscolumnwiththecomm
entsontheendofeach
lineofassemblycode.Th
atis,ifa
lineoftheassemblyprogra
mis:
add sum ; add sum to the acc
43
DEPT IT CMREC
thentheassemblerandloa
derwillputtheassembled
codeintheRAMandwil
lputthe
commentinthecorrespondin
gcommentcolumnofthe
RAMwindow.
5.2EditingandDebugging
CPUSimhasadebugging
modethatuserscanenter
whentheywishtostep
throughthe
executionoftheprogramon
emachineinstructionoron
emicroinstructionatatime.
(See
Figure7forthetoolbartha
tappearswhenusersenter
44
DEPT IT CMREC
debuggingmode.)Aftere
achsuch
step,theusercaninspect
andoptionallyeditthestate
ofthemachine.CPUSi
mcanalso
beconfiguredtohighlightc
ellsofRAMs whoseaddress
es areincertainregisters.
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
instructionatatime(allt
hewaybacktotheorigin
alstateofthemachinew
hendebug
modewasentered).This
abilitytostepforwardand
backwardthroughthecod
emakes
pinpointinghardwareorsoftw
areerrorsalmosttrivial.
If the program gets in
to an infinite loop, the us
er can choose "Stop" from
the
Executemenu,andtheprog
ramwillbehalted.
Figure7.Thedebuggingtoolbar.
46
DEPT IT CMREC
5.3GettingHelp
Virtually the whole user's m
anual is available online wi
th CPU Sim. In addition
to a
generalhelpwindow(seeFi
gure8),manydialogboxes
have"Help
"buttonsthatbringup
theonlinehelpforthatdial
ogbox.
Figure8.TheCPUSimhelpwind
ow.
6.SAMPLEASSIGNMENTSUSI
NGCPUSIM
47
DEPT IT CMREC
Aseriesofopenandclose
dlabexercisesusingCPU
Simhasbeencreatedbyt
heauthor
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(withregularinstruc
tionlayoutand arraysof
general-
purposeregisters), anda
stack-
basedmachine(theJavaVir
tualMachineorJVM).The
48
DEPT IT CMREC
labexercisesareassigned
approximatelyonceortwice
aweekina14-
weeksemester,withthefirs
tlaboccurringin
thesecondweekofthese
mester.Thestudentsare
givenaboutaweektoco
mpleteeach
assignment.
Thelabexercisesaresumm
arizedhere.Thecomplete
assignmentsandtheirsoluti
ons
canbeobtainedfromthea
uthor.
49
DEPT IT CMREC
6.1IntroductiontotheWom
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
machinewithonly12machi
neinstructions,nostack,an
donlydirectaddressing)an
dtwo
programs for that machine
written in binary machine l
anguage. The first progra
m is
50
DEPT IT CMREC
documentedandthesecond
isnot.Thestudentsare
askedtomodifythefirst
programto
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)toget
themtoappreciateassemb
51
DEPT IT CMREC
lylanguagebyhavingto
program
firstinbinarymachinelangu
age.
6.2IntroductiontoCPUSim
In the first (closed) lab, th
e students are introduced t
o CPU Sim and are asked
to step
throughtheintroductorytutor
ialgivenintheCPUSim
user'smanual.Thenthes
tudents
are asked to redo the pre
vious pre-
lab assignment using assemb
ly language instead of
52
DEPT IT CMREC
machinelanguage,andfinally
runtheresultingprogram
intheCPUSimenvironme
nt.
Afterthisfirstclosedlab,al
lassignmentsareopenlab
assignments.
6.3OptionalWombat1Interpr
eter
One option at this point is
to ask the students to
write a Wombat1 interpreter
in their
favoritehigh-
levellanguage.Theinterpr
etershouldtakeasinput
atextfilecontaininga
53
DEPT IT CMREC
54
DEPT IT CMREC
Wombat1thataccessesmem
oryfrequently.Afteradis
cussionofthecostsofacc
essing
memory,studentsaregiven
theWombat2,whichissimil
artotheWombat1except
ithas
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
56
DEPT IT CMREC
singmodes,buttheonlyw
aythe
Wombat2canaccomplishthis
taskiswithself-
modifyingcode.Thisexerci
senotonly
teachesthestudentsthelim
itationsofamachinewith
nostackandonlydirectad
dressing,
itprovidesagoodstarting
pointforadiscussionof
theadvantagesanddisadvan
tagesof
self-modifyingcode.
6.6Wombat3
For the next several assig
nments, the students are
57
DEPT IT CMREC
58
DEPT IT CMREC
thestack,toseehowmuc
heasierreversingalistof
integersisusingthenew
features.
6.7Wombat4
Thenextenhancement,whic
hresultsintheWombat4,
istoaddcallandreturn
machine
instructions, allowing subrouti
ne calls. Then students
are given assignments to w
rite
subprogramsusingvaluepar
ametersandrecursion.
Thestudentstypicallyhave
alittletroublewiththisas
59
DEPT IT CMREC
signmentsincethereisstill
no
addressingmodeintheWo
mbat4otherthandirectadd
ressing,whichmeansthatt
heonly
practicalwaytoaccessthe
valuesonthestackisby
poppingthemofffirst.
6.8Wombat5
Thestudentsarenextdirect
edtocreatetheWombat5
byaddingindirect,stack-
relative,
andimmediateaddressingm
odes,whichallowtheprope
rdevelopmentanduseof
stack
60
DEPT IT CMREC
canthencreatetheWom
bat6from
theWombat5by addingan
indexregisterandindexed-
addressingmode,atwhich
point
they can be told to redo
the previous array-
manipulation assignment usin
g indexed
addressing.
6.10Wombat7
TomaketheWombat6more
realistic,thefinalstepin
thisseriesofassignments
istoadd
bit operations (and, or, xor,
not), and shift operations
62
DEPT IT CMREC
cangetexposuretoaCI
SC-like
stack-
based architecture. This
machine is almost identical
to the IJVM discussed in
[Tanenbaum 1999] except th
at it containsonly 24 mac
hine instructions, none of w
hich
allowtheusertostoreval
uesinvariablesandsoreq
uirealldatatobestored
onthestack
bymeansofpushingand
popping.Thestudentsare
askedtowritesimplepro
gramsfor
64
DEPT IT CMREC
theJVM1togetusedto
thisnewarchitectureandt
henthey are askedtowrit
eslightly
harder programs that require
complex stack manipulations
due to the lack of varia
bles.
SeeFigure9forasimple
JVM1program.
6.12JVM2
Students are asked to creat
e the JVM2 from the JVM1
by adding three new ma
chine
instructionswhichallowstori
ng,loading,andincrementing
65
DEPT IT CMREC
localvariablesonthesta
ck
andthentheyareaskedto
redothepreviousassignme
nt.
6.13JVM3
The students create the JV
M3 from the JVM2 by add
ing procedure calls and ret
urns.
Afteraddingsuchinstructions
,studentsareaskedtowri
terecursiveprograms,such
asa
simplefactorialprogram,to
testthecallandreturnins
tructions.Thisturnsoutt
obea
66
DEPT IT CMREC
7.LIMITATIONSOFCPUSIM
Itwouldbequitedifficultto
constructasimulatorthat
engagesthestudentsinal
ltheCS-
2001architectureknowledge
areasandyetissimpleen
oughforstudentstousei
naCS3
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
architecturetopics.Theset
opicsinclude:
1. floatingpointnumberre
presentations,
2. computerorganizationbel
owthemicrocodelevel,suc
hastransistorsandgates,
3. issuesconcerningthesp
eedofexecution,includings
uchissuesaspipelining,par
allel
processing,andtheuseof
caches,
4. interruptsandtraps,
5. operatingsystemconcept
ssuchasvirtualmemorya
ndfilemanagement,
69
DEPT IT CMREC
6. thelinkingandloading
ofseparateassemblymodul
es.
AddingfeaturestoCPUSim
toaddressthesetopicsw
ouldhavemadeitsignifican
tly
more complex and so, in
the author's view, less peda
gogically useful for the inte
nded
audience.
8.CONCLUSION
CPUSimisaCPUsimulati
onprogramdesignedforus
ewithCS3coursesthatall
owsthe
70
DEPT IT CMREC
studentstocreateormodif
ythearchitecturesbeingst
udied.Itisaninteractive
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
texteditorsforwritingprog
rams,anassembler,on-
linehelp,andmanydebugg
ingtools
tohelptheusereasilymo
difythearchitecturesandt
71
DEPT IT CMREC
henwriteandexecuteprog
ramson
thosearchitecturesan 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
74
DEPT IT CMREC
python
Copy code
class TLB:
def __init__(self, size):
self.size = size
self.entries = []
def allocate_frame(self):
if self.free_frames:
return self.free_frames.pop(0)
else:
75
DEPT IT CMREC
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
# 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)
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
# 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()
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.
82
DEPT IT CMREC
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
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.
87
DEPT IT CMREC
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