-
Notifications
You must be signed in to change notification settings - Fork 0
/
memoryManager.cpp
109 lines (90 loc) · 2.7 KB
/
memoryManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
CMPSC 473
Project 3
Team: Jinwei Liu, Ghunley Zhang
Date modified: 4/28/2017
*/
#include "memoryManager.h"
#include <iostream>
memoryManager::memoryManager(ReplacementPolicy p, unsigned int pS, unsigned int nF, unsigned int vA)
: virtualMemoryManagerInterface(p, pS, nF, vA){
isFramesFull = false;
// initialize the table with -1 (empty)
for (unsigned int i = 0; i < numFrames; i++){
Frame f;
f.framePosition = i;
f.address = -1;
frames.push_back(f);
}
};
memoryManager::~memoryManager(){
isFramesFull = false;
frames.clear();
}
unsigned long long memoryManager::memoryAccess(unsigned long long address) {
// the table is not fully used yet, compulsory miss and push
auto frame_i = frames.begin();
if (!isFramesFull) {
while (frame_i != frames.end()) {
if (frame_i->address == -1) {
// place the page in frames
frame_i->address = address;
order.push_back((unsigned int)frame_i->framePosition); // store the position
//cout << "\t**" << address << " is stored at frame " << frame_i->framePosition << endl;
return frame_i->framePosition;
}
frame_i++;
}
}
// no compulsory miss
isFramesFull = true; // do not need to check compulsory miss
// find if the address is already in memory
auto pos = order.begin();
while (pos != order.end()) {
if (frames[*pos].address == address)
break;
pos++;
}
// hit, do not need to swap
if (pos != order.end()) {
// update least recent used since this frame has just been referenced
unsigned int framePos = *pos;
//cout << "\t**" << address << " hits, stored at frame " << framePos << endl;
if (policy == LRU) {
unsigned int orderPos;
// find position in order that store *pos
for (unsigned int i = 0; i < numFrames; i++){
if (order[i] == framePos) {
orderPos = i;
break;
}
}
// erase and push it to the last
order.erase(order.begin() + orderPos);
order.push_back(framePos);
}
return frames[framePos].framePosition;
}
// miss, swap
unsigned int posToBeSwapped = order.front();
//cout << "\t**" << address << " misses, swap to frame " << posToBeSwapped << endl;
swap(order.front(), address);
order.erase(order.begin());
order.push_back(posToBeSwapped);
/*
// print order
for (unsigned int i = 0; i < numFrames; i++){
cout << order[i] << " ";
}
cout << endl;
*/
return frames[posToBeSwapped].framePosition;
}
void memoryManager::swap(unsigned int frameNumber, unsigned int pageNumber) {
frames[frameNumber].address = pageNumber;
numSwaps++;
//cout << "\t\tnumswap: " << numSwaps << "\n";
}
unsigned long long& memoryManager::numberPageSwaps() {
return numSwaps;
}