summaryrefslogtreecommitdiff
path: root/src/storage/cache.cc
blob: 2031367f68318841fce72d4db245def99530b37a (plain)
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
#include "cache.h"
#include "definitions.h"
#include "response.h"
#include "utils.h"
#include <bits/stdc++.h>

Cache::Cache(Storage *lower, int delay)
{
	this->data = new std::vector<std::array<signed int, LINE_SIZE>>;
	this->data->resize(L1_CACHE_SIZE);
	this->delay = delay;
	this->is_waiting = false;
	this->lower = lower;
	this->meta.fill({-1, -1});
	this->requester = IDLE;
	this->wait_time = this->delay;
}

Cache::~Cache() { delete this->data; }

Response Cache::write(Accessor accessor, signed int data, int address)
{
	Response r = WAIT;

	/* Do this first--then process the first cycle immediately. */
	if (this->requester == IDLE)
		this->requester = accessor;

	if (this->requester == accessor) {
		fetch_resource(address);
		if (this->is_waiting)
			r = BLOCKED;
		else if (this->wait_time == 0) {
			int tag, index, offset;
			get_bit_fields(address, &tag, &index, &offset);
			this->data->at(index).at(offset) = data;
			this->meta[index].at(1) = 1;
			r = OK;
		}
	}

	return r;
}

Response Cache::read(
	Accessor accessor, int address, std::array<signed int, LINE_SIZE> &data)
{
	return WAIT;
}

void Cache::fetch_resource(int expected)
{
	Response r = OK;
	int tag, index, offset;
	std::array<signed int, LINE_SIZE> actual;
	std::array<int, 2> *meta;

	get_bit_fields(expected, &tag, &index, &offset);
	meta = &this->meta.at(index);

	if (meta->at(0) != tag) {
		// address not in cache
		if (meta->at(1) >= 0) {
			// occupant is dirty
			// TODO
			r = WAIT;
		} else {
			actual = this->data->at(index);
			r = this->lower->read(L1CACHE, expected, actual);
			if (r == OK) {
				meta->at(0) = tag;
				meta->at(1) = -1;
			}
		}
	}

	this->is_waiting = (r == OK) ? false : true;
}