aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore6
-rw-r--r--README.org159
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild-win.sh17
-rwxr-xr-xbuild.sh19
-rw-r--r--src/busses.c121
-rw-r--r--src/busses.h36
-rw-r--r--src/caches.c312
-rw-r--r--src/caches.h60
-rw-r--r--src/config.h74
-rw-r--r--src/connections.c183
-rw-r--r--src/connections.h82
-rw-r--r--src/cpus.c179
-rw-r--r--src/cpus.h24
-rw-r--r--src/export-font-as-code.c17
-rw-r--r--src/memory.c99
-rw-r--r--src/memory.h22
-rw-r--r--src/mesif-lru-simulation.c705
-rw-r--r--src/states.c75
-rw-r--r--src/states.h39
-rw-r--r--src/utils.h10
21 files changed, 2263 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d364c15
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
1*.html
2*.pdf
3*.tex
4
5/export-font-as-code
6/mesif-lru-simulation*
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..b2a580f
--- /dev/null
+++ b/README.org
@@ -0,0 +1,159 @@
1#+title: Cache coherency protocol and eviction policy simulation
2#+subtitle: MESIF-LRU
3#+date: 2024H1
4
5* Task
6:PROPERTIES:
7:CUSTOM_ID: task
8:END:
9#+begin_note
10This is a machine translation.[fn:1]
11#+end_note
12
13What needs to be done? Implement a model that demonstrates the
14operation of the memory subsystem in a symmetric multiprocessor
15system. As a reference, you can use the following demonstrator:
16https://www.scss.tcd.ie/Jeremy.Jones/vivio/caches/MESIHelp.htm -- this
17shows the operation of the MESI protocol with a direct‑mapped cache
18and without replacement policies.
19
20The conditions of your work are more complex:
211) the cache coherence protocol and replacement policy are determined
222) the number of processors in the system is 4;
233) the amount of main memory is 16 addressable cells of 1 byte each;
244) the size of the memory and cache line is 1 byte;
255) the number of cache lines is 4;
266) the cache associativity is 2.
27
28You determine all the necessary attributes for fixing and updating the
29time of the last access to a row or the frequency of access to it
30yourself. In all cases, the time unit is the clock cycle.
31
32The model must display:
331) the contents and address of each main memory cell;
342) tag, data, and state of each cache line (possible states determined
35 by the protocol from your option);
363) Replacement policy metric counter for each cache line;
374) requests via the address, data, and status buses and responses to
38 them (schematically, as in the reference model, without commenting
39 on each request and response);
405) a common machine time clock counter from the moment of startup or
41 reset.
42
43Control commands received from the user: for each processor, read and
44write operations on memory at the specified (selected) address, a
45general reset of the model’s state, the ability to “advance” manually
46through the clock cycles. Please note that the reference model
47implements the ability to perform operations on multiple processors
48simultaneously -- your model should also implement this. The initial
49state of the caches is that all lines are empty; the initial state of
50the memory is that all cells contain the value "0". By analogy with
51the reference model, the write operation increments the value by "1".
52
53Programming languages, frameworks, visualization tools -- any, as long
54as I can run your application on my work PC. If this requires any
55additional software, it would be better to package everything in the
56form of a virtual machine image or container. Beautiful animation,
57coloring, and other decorations are not required and will not be taken
58into account when evaluating the work.
59
60The work must be accompanied by a report. In addition to the
61substantive part, the report must indicate how the tasks are
62distributed among the members of the working group (this can be done
63in the conclusion or in the appendix).
64
65* Documentation
66:PROPERTIES:
67:CUSTOM_ID: documentation
68:END:
69The report has been lost to time, but I'm sure there was nothing
70interesting in it.
71
72* Showcase
73:PROPERTIES:
74:CUSTOM_ID: showcase
75:END:
76The CPU blocks allow you to issue commands: read, increment
77(read+write) or write (random byte), to a specific address. The whole
78timeline is being saved and you can scrub through it, go back in time
79and change the future. Bus access is animated through interpolation.
80
81#+caption: Initial state
82#+attr_html: :width 100%
83[[https://git.michalec.dev/uni/term-04/supercomp-arch/coursework/init.png][https://git.michalec.dev/uni/term-04/supercomp-arch/coursework/init.png]]
84
85#+caption: Increment (read+write) and read at the same time
86#+attr_html: :width 100%
87[[https://git.michalec.dev/uni/term-04/supercomp-arch/coursework/ir.png][https://git.michalec.dev/uni/term-04/supercomp-arch/coursework/ir.png]]
88
89#+caption: Write random byte
90#+attr_html: :width 100%
91[[https://git.michalec.dev/uni/term-04/supercomp-arch/coursework/w.png][https://git.michalec.dev/uni/term-04/supercomp-arch/coursework/w.png]]
92
93* Unlicense
94:PROPERTIES:
95:CUSTOM_ID: unlicense
96:END:
97#+include: UNLICENSE verse
98
99* Footnotes
100:PROPERTIES:
101:CUSTOM_ID: footnotes
102:END:
103[fn:1] Original text:
104#+HTML: <i>
105#+begin_quote
106Что нужно сделать? Реализовать модель, демонстрирующую работу
107подсистемы памяти в симметричной многопроцессорной системе. В качестве
108эталона можно использовать такой демонстратор:
109https://www.scss.tcd.ie/Jeremy.Jones/vivio/caches/MESIHelp.htm --
110здесь показана работа протокола MESI с кэшем прямого отображения и без
111политик замещения.
112
113Условия вашей работы более сложные:
1141) протокол кэш-когерентности и политика замещения определяются
115 выбранным вариантом;
1162) число процессоров в системе -- 4;
1173) объем основной памяти -- 16 адресуемых ячеек по 1 байт;
1184) размер строки памяти и кэша -- 1 байт;
1195) число строк кэша -- 4;
1206) ассоциативность кэша -- 2.
121
122Все необходимые атрибуты для фиксации и обновления времени последнего
123обращения к строке или частоты обращения к ней вы определяете
124самостоятельно, единицей времени во всех случаях является такт
125машинного времени.
126
127Модель обязательно должна отображать:
1281) содержимое и адрес каждой ячейки основной памяти;
1292) тэг, данные и состояние каждой строки кэша (возможные состояния
130 определяются протоколом из вашего варианта);
1313) счётчик метрики политики замещения для каждой строки кэша;
1324) запросы по шинам адреса, данных, состояний и ответы на них
133 (схематично, как в эталонной модели, без комментирования каждого
134 запроса и ответа);
1355) общий счётчик тактов машинного времени с момента запуска или
136 сброса.
137
138Команды управления, принимаемые от пользователя: для каждого
139процессора операции чтения и записи памяти по указанному (выбранному)
140адресу, общий сброс состояния модели, возможность «продвижения» по
141тактам вручную. Обратите внимание, что в эталонной модели реализована
142возможность выполнять операции на нескольких процессорах одновременно
143-- в вашей модели это тоже должно быть реализовано. Начальное
144состояние кэшей -- все строки пусты, начальное состояние памяти -- все
145ячейки содержат значение «0». По аналогии с эталонной моделью операция
146записи выполняет инкремент значения на «1».
147
148Языки программирования, фрэймворки, средства визуализации -- любые,
149лишь бы я мог запустить ваше приложение на своём рабочем ПК. Если для
150этого потребуется какое-то дополнительно ПО -- лучше будет собрать всё
151в виде образа виртуальной машины или контейнера. Красивая анимация,
152раскрашивание и другие декорации не требуются и не принимаются в
153расчёт при оценивании работы.
154
155Работа должна сопровождаться отчётом. В отчёте, помимо содержательной
156части, должно быть указано распределение задач по участникам рабочей
157группы (это можно сделать в заключении или в приложении).
158#+end_quote
159#+HTML: </i>
diff --git a/UNLICENSE b/UNLICENSE
new file mode 100644
index 0000000..efb9808
--- /dev/null
+++ b/UNLICENSE
@@ -0,0 +1,24 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
diff --git a/build-win.sh b/build-win.sh
new file mode 100755
index 0000000..591656d
--- /dev/null
+++ b/build-win.sh
@@ -0,0 +1,17 @@
1#!/bin/sh
2
3set -xe
4
5x86_64-w64-mingw32-gcc \
6 -std=gnu99 -ggdb3 \
7 -Wall -Wextra -Wno-parentheses -Wno-discarded-qualifiers \
8 -I ./src/ -I ./res/ \
9 -o mesif-lru-simulation.exe \
10 src/mesif-lru-simulation.c \
11 src/states.c \
12 src/connections.c \
13 src/busses.c \
14 src/caches.c \
15 src/cpus.c \
16 src/memory.c \
17 -lraylib -lgdi32 -lwinmm -lm
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..1c5cace
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,19 @@
1#!/bin/sh
2
3set -xe
4
5# gcc -std=gnu99 -ggdb3 -lraylib -I./src/ -o export-font-as-code \
6# src/export-font-as-code.c \
7
8# ./export-font-as-code
9
10gcc -std=gnu99 -ggdb3 \
11 -lraylib -lm -I./src/ -I./res/ -o mesif-lru-simulation \
12 -Wall -Wextra -Wno-discarded-qualifiers -Wno-parentheses \
13 src/mesif-lru-simulation.c \
14 src/states.c \
15 src/connections.c \
16 src/busses.c \
17 src/caches.c \
18 src/cpus.c \
19 src/memory.c
diff --git a/src/busses.c b/src/busses.c
new file mode 100644
index 0000000..ff6a86d
--- /dev/null
+++ b/src/busses.c
@@ -0,0 +1,121 @@
1#include "busses.h"
2#include <raymath.h>
3#include <string.h>
4#include "config.h"
5#include "connections.h"
6
7extern Font font;
8
9int *cache_locking_busses;
10int *bus_cycles;
11BUS data_bus;
12BUS addr_bus;
13BUS shared_bus;
14
15
16void
17init_bus (BUS bus, CONNECTION cache_cons[CPU_COUNT], CONNECTION memory_con, float y, float scale, Color color, char *label)
18{
19 *bus = (struct bus) {
20 .reserved_connection = CONNECTION_NONE,
21 .linked = false,
22 .memory_connection = memory_con,
23 .y = y,
24 .scale = scale,
25 .color = color,
26 .label = label,
27 .label_size = MeasureTextEx (font, label, FONT_SIZE, TEXT_SPACING),
28 };
29 memcpy (bus->cache_connections, cache_cons, sizeof (bus->cache_connections));
30}
31
32void
33draw_bus (BUS bus)
34{
35 const Vector2 pos_end = {
36 .x = (CPU_COUNT + 1)/2.*(BLOCK_WIDTH + BLOCK_MARGINH) - BLOCK_MARGINH + addr_bus->label_size.x,
37 .y = bus->y,
38 };
39
40 const Vector2 pos_start = {
41 .x = -1*pos_end.x,
42 .y = pos_end.y,
43 };
44
45 const Color color = (bus->linked
46 ? bus->color
47 : COLOR_BUS_INACTIVE);
48
49 const float thick = BUS_THICKNESS*bus->scale;
50 const float head_side = 2*thick;
51 const float head_height = head_side*sqrtf (3)/2;
52 const Vector2 dir = Vector2Normalize (Vector2Subtract (pos_end, pos_start));
53 const Vector2 line_offset = Vector2Scale (dir, head_height/bus->scale);
54 const Vector2 line_begin_pos = Vector2Add (pos_start, line_offset);
55 const Vector2 line_end_pos = Vector2Subtract (pos_end, line_offset);
56 DrawLineEx (line_begin_pos, line_end_pos, thick, color);
57 DrawTriangle(Vector2Add (line_begin_pos, Vector2Scale (dir, -head_height)),
58 Vector2Add (line_begin_pos, Vector2Rotate (Vector2Scale (dir, -head_side/2), -PI/2)),
59 Vector2Add (line_begin_pos, Vector2Rotate (Vector2Scale (dir, -head_side/2), PI/2)),
60 color);
61 DrawTriangle(Vector2Add (line_end_pos, Vector2Scale (dir, head_height)),
62 Vector2Add (line_end_pos, Vector2Rotate (Vector2Scale (dir, -head_side/2), PI/2)),
63 Vector2Add (line_end_pos, Vector2Rotate (Vector2Scale (dir, -head_side/2), -PI/2)),
64 color);
65
66 Vector2 label_pos = line_begin_pos;
67 label_pos.x += TEXT_MARGIN;
68 label_pos.y -= bus->label_size.y + TEXT_MARGIN;
69 DrawTextEx (font, bus->label, label_pos, FONT_SIZE, TEXT_SPACING, bus->color);
70}
71
72void
73bus_link_connection (BUS bus, CONNECTION con)
74{
75 bus->linked = true;
76
77 for (int i = 0; i < CPU_COUNT; ++i) {
78 if (!(bus->connection_targets & 1 << i))
79 continue;
80
81 CONNECTION_START_TRANSACTION_TO_FROM(bus->cache_connections[i], con->transaction_value);
82 }
83
84 if (bus->connection_targets & 1 << CPU_COUNT)
85 CONNECTION_START_TRANSACTION_TO_FROM(bus->memory_connection, con->transaction_value);
86}
87
88
89void
90bus_link_connections (BUS bus, CONNECTION cons[CPU_COUNT])
91{
92 bus->linked = true;
93
94 int target;
95 u8 data = 0;
96 for (int i = 0; i < CPU_COUNT; ++i) {
97 if (bus->connection_targets & 1 << i)
98 target = i;
99 else
100 data |= cons[i]->transaction_value;
101 }
102
103 CONNECTION_START_TRANSACTION_TO_FROM(bus->cache_connections[target], data);
104}
105
106
107void
108bus_unlink_connection (BUS bus)
109{
110 bus->linked = false;
111
112 for (int i = 0; i < CPU_COUNT; ++i) {
113 CONNECTION con = bus->cache_connections[i];
114 connection_end_transaction (con);
115 }
116
117 CONNECTION con = bus->memory_connection;
118 if (con) {
119 connection_end_transaction (con);
120 }
121}
diff --git a/src/busses.h b/src/busses.h
new file mode 100644
index 0000000..9c08f25
--- /dev/null
+++ b/src/busses.h
@@ -0,0 +1,36 @@
1#ifndef INCLUDED_BUSSES_H
2#define INCLUDED_BUSSES_H
3
4#include <raylib.h>
5#include <inttypes.h>
6#include "connections.h"
7
8#define IS_BUS_FREE(bus) ((bus)->reserved_connection == CONNECTION_NONE)
9#define FREE_BUS(bus) ((bus)->reserved_connection = CONNECTION_NONE)
10
11typedef struct bus {
12 int reserved_connection;
13 int connection_targets;
14 bool linked;
15 CONNECTION cache_connections[CPU_COUNT];
16 CONNECTION memory_connection;
17 float y;
18 float scale;
19 Color color;
20 char *label;
21 Vector2 label_size;
22} *BUS;
23
24extern int *cache_locking_busses;
25extern int *bus_cycles;
26extern BUS data_bus;
27extern BUS addr_bus;
28extern BUS shared_bus;
29
30void init_bus (BUS, CONNECTION caches[CPU_COUNT], CONNECTION memory, float y, float scale, Color, char *label);
31void draw_bus (BUS);
32void bus_link_connection (BUS, CONNECTION);
33void bus_unlink_connection (BUS);
34void bus_link_connections (BUS, CONNECTION cons[CPU_COUNT]);
35
36#endif
diff --git a/src/caches.c b/src/caches.c
new file mode 100644
index 0000000..4d710e6
--- /dev/null
+++ b/src/caches.c
@@ -0,0 +1,312 @@
1#include "caches.h"
2#include <raymath.h>
3#include <string.h>
4#include <stdio.h>
5#include "config.h"
6#include "connections.h"
7
8extern Font font;
9
10CACHE caches[CPU_COUNT];
11
12static char *cache_line_state_labels[] = {
13 [CACHE_LINE_STATE_MODIFIED ] = "M",
14 [CACHE_LINE_STATE_EXCLUSIVE] = "E",
15 [CACHE_LINE_STATE_SHARED ] = "S",
16 [CACHE_LINE_STATE_INVALID ] = "I",
17 [CACHE_LINE_STATE_FORWARD ] = "F",
18};
19
20void
21init_cache (CACHE cache, BUS lower_bus)
22{
23 int i = cache - caches[0];
24 int block_i = i < CACHE_COUNT/2 ? i : i + 1;
25 cache->rec = (Rectangle) {
26 .x = Remap (block_i, 0, CACHE_COUNT,
27 - CACHE_COUNT/2*(BLOCK_WIDTH + BLOCK_MARGINH) - BLOCK_WIDTH/2,
28 + CACHE_COUNT/2*(BLOCK_WIDTH + BLOCK_MARGINH) - BLOCK_WIDTH/2),
29 .y = lower_bus->y + lower_bus->scale*BUS_THICKNESS/2 + BLOCK_MARGINV,
30 .width = BLOCK_WIDTH,
31 .height = 2*BLOCK_PADDING + CACHE_LINE_COUNT*(ENTRY_HEIGHT + ENTRY_MARGIN) - ENTRY_MARGIN,
32 };
33
34 strcpy (cache->label, "CACHE 0");
35 cache->label[strlen (cache->label) - 1] += i;
36 cache->label_origin = Vector2Scale (MeasureTextEx (font, cache->label, FONT_SIZE, TEXT_SPACING), 0.5);
37 cache->label_position = (Vector2) {
38 .x = cache->rec.x - cache->label_origin.y/2 - TEXT_MARGIN,
39 .y = cache->rec.y + cache->rec.height/2,
40 };
41
42 float ys = cache->rec.y - LINE_THICKNESS;
43 float xd = cache->rec.width*1/4;
44 float xs = cache->rec.x + xd;
45 init_connection (cons_cache_bus_shared [i], xs + 0*xd, ys, shared_bus->y + shared_bus->scale*BUS_THICKNESS/2, COLOR_SHARED, shared_bus->scale);
46 init_connection (cons_cache_bus_addr [i], xs + 1*xd, ys, addr_bus->y + addr_bus->scale*BUS_THICKNESS/2, COLOR_ADDR, addr_bus->scale);
47 init_connection (cons_cache_bus_data [i], xs + 2*xd, ys, data_bus->y + data_bus->scale*BUS_THICKNESS/2, COLOR_DATA, data_bus->scale);
48
49 cache->highlighted = CACHE_LINE_COUNT;
50 cache->highlighted_pending = CACHE_LINE_COUNT;
51
52 for (int i = 0; i < CACHE_LINE_COUNT; ++i) {
53 cache->lines[i] = (struct cache_line) {
54 .age = 0,
55 .state = CACHE_LINE_STATE_INVALID,
56 .addr = 0,
57 .data = 0,
58 };
59 }
60}
61
62void
63draw_cache (CACHE cache)
64{
65 int i = cache - caches[0];
66
67 DrawRectangleRounded (cache->rec, ROUNDNESS, SEGMENTS, COLOR_BLOCK);
68 DrawTextPro (font, cache->label, cache->label_position, cache->label_origin, -90, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
69
70 for (int j = 0; j < CACHE_ASSOCIATIVITY; ++j) {
71 char set[2];
72 sprintf (set, "%d", j);
73 const Vector2 set_center = Vector2Scale (MeasureTextEx (font, set, FONT_SIZE, TEXT_SPACING), .5);
74 const Vector2 set_entry_center = {
75 .x = cache->rec.x + cache->rec.height/CACHE_LINE_COUNT/2,
76 .y = cache->rec.y + 2*(j + .5)*cache->rec.height/CACHE_LINE_COUNT,
77 };
78 const Vector2 set_pos = Vector2Subtract (set_entry_center, set_center);
79 DrawTextEx (font, set, set_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
80
81 if (j != 0) {
82 const Vector2 divider_start_pos = {
83 .x = cache->rec.x,
84 .y = cache->rec.y + 2*j*cache->rec.height/CACHE_LINE_COUNT,
85 };
86 const Vector2 divider_end_pos = {
87 .x = divider_start_pos.x + cache->rec.height/CACHE_LINE_COUNT,
88 .y = divider_start_pos.y,
89 };
90 DrawLineEx(divider_start_pos, divider_end_pos, 2, COLOR_BLOCK_EDGE);
91 }
92 }
93
94 for (int j = 0; j < CACHE_LINE_COUNT; ++j) {
95 Rectangle entry = {
96 .x = cache->rec.x + cache->rec.height/CACHE_LINE_COUNT,
97 .y = cache->rec.y + j*cache->rec.height/CACHE_LINE_COUNT,
98 .width = BLOCK_WIDTH - cache->rec.height/CACHE_LINE_COUNT,
99 .height = cache->rec.height/CACHE_LINE_COUNT,
100 };
101 if (cache->highlighted == j)
102 DrawRectangleRec (entry, GREEN);
103 else if (cache->highlighted_pending == j)
104 DrawRectangleRec (entry, DARKGREEN);
105
106 if (j != 0) {
107 const Vector2 divider_start_pos = {
108 .x = cache->rec.x + cache->rec.height/CACHE_LINE_COUNT,
109 .y = cache->rec.y + j*cache->rec.height/CACHE_LINE_COUNT,
110 };
111 const Vector2 divider_end_pos = {
112 .x = divider_start_pos.x + cache->rec.width - cache->rec.height/CACHE_LINE_COUNT,
113 .y = divider_start_pos.y,
114 };
115 DrawLineEx(divider_start_pos, divider_end_pos, 2, COLOR_BLOCK_EDGE);
116 }
117
118 char age[2];
119 age[0] = cache->lines[j].age < 10 ? '0' + cache->lines[j].age : '+';
120 age[1] = '\0';
121 const Vector2 age_center = Vector2Scale (MeasureTextEx (font, age, FONT_SIZE, TEXT_SPACING), .5);
122 const Vector2 age_entry_center = {
123 .x = cache->rec.x + 3*cache->rec.height/CACHE_LINE_COUNT/2,
124 .y = cache->rec.y + (j + .5)*cache->rec.height/CACHE_LINE_COUNT,
125 };
126 const Vector2 age_pos = Vector2Subtract (age_entry_center, age_center);
127 DrawTextEx (font, age, age_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
128
129 char *state = cache_line_state_labels[cache->lines[j].state];
130 const Vector2 state_center = Vector2Scale (MeasureTextEx (font, state, FONT_SIZE, TEXT_SPACING), .5);
131 const Vector2 state_entry_center = {
132 .x = cache->rec.x + 5*cache->rec.height/CACHE_LINE_COUNT/2,
133 .y = cache->rec.y + (j + .5)*cache->rec.height/CACHE_LINE_COUNT,
134 };
135 const Vector2 state_pos = Vector2Subtract (state_entry_center, state_center);
136 DrawTextEx (font, state, state_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
137
138 if (cache->lines[j].state != CACHE_LINE_STATE_INVALID || true) {
139 char tag[4];
140 sprintf (tag, "%d%d%d",
141 cache->lines[j].addr >> 3 & 1,
142 cache->lines[j].addr >> 2 & 1,
143 cache->lines[j].addr >> 1 & 1);
144 const Vector2 tag_center = Vector2Scale (MeasureTextEx (font, tag, FONT_SIZE, TEXT_SPACING), .5);
145 const Vector2 tag_entry_center = {
146 .x = cache->rec.x + 3*cache->rec.height/CACHE_LINE_COUNT +
147 (cache->rec.width - 3*cache->rec.height/CACHE_LINE_COUNT)*3/10,
148 .y = state_entry_center.y,
149 };
150 const Vector2 tag_pos = Vector2Subtract (tag_entry_center, tag_center);
151 DrawTextEx (font, tag, tag_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
152
153 char value[3];
154 sprintf (value, "%02hhX", cache->lines[j].data);
155 const Vector2 value_center = Vector2Scale (MeasureTextEx (font, value, FONT_SIZE, TEXT_SPACING), .5);
156 const Vector2 value_entry_center = {
157 .x = cache->rec.x + 3*cache->rec.height/CACHE_LINE_COUNT +
158 (cache->rec.width - 3*cache->rec.height/CACHE_LINE_COUNT)*4/5,
159 .y = state_entry_center.y,
160 };
161 const Vector2 value_pos = Vector2Subtract (value_entry_center, value_center);
162 DrawTextEx (font, value, value_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
163 }
164 }
165
166 DrawRectangleRoundedLinesEx (cache->rec, ROUNDNESS, SEGMENTS, LINE_THICKNESS, COLOR_BLOCK_EDGE);
167
168 const Vector2 set_divider_start_pos = {
169 .x = cache->rec.x + cache->rec.height/CACHE_LINE_COUNT,
170 .y = cache->rec.y,
171 };
172 const Vector2 set_divider_end_pos = {
173 .x = set_divider_start_pos.x,
174 .y = set_divider_start_pos.y + cache->rec.height,
175 };
176 DrawLineEx (set_divider_start_pos, set_divider_end_pos, 2, COLOR_BLOCK_EDGE);
177
178 const Vector2 age_divider_start_pos = {
179 .x = set_divider_start_pos.x + cache->rec.height/CACHE_LINE_COUNT,
180 .y = cache->rec.y,
181 };
182 const Vector2 age_divider_end_pos = {
183 .x = age_divider_start_pos.x,
184 .y = age_divider_start_pos.y + cache->rec.height,
185 };
186 DrawLineEx (age_divider_start_pos, age_divider_end_pos, 2, COLOR_BLOCK_EDGE);
187
188 const Vector2 state_divider_start_pos = {
189 .x = set_divider_start_pos.x + 2*cache->rec.height/CACHE_LINE_COUNT,
190 .y = cache->rec.y,
191 };
192 const Vector2 state_divider_end_pos = {
193 .x = state_divider_start_pos.x,
194 .y = state_divider_start_pos.y + cache->rec.height,
195 };
196 DrawLineEx (state_divider_start_pos, state_divider_end_pos, 2, COLOR_BLOCK_EDGE);
197
198 const Vector2 data_divider_start_pos = {
199 .x = state_divider_start_pos.x + (cache->rec.width - 3*cache->rec.height/CACHE_LINE_COUNT)*3/5,
200 .y = cache->rec.y,
201 };
202 const Vector2 data_divider_end_pos = {
203 .x = data_divider_start_pos.x,
204 .y = data_divider_start_pos.y + cache->rec.height,
205 };
206 DrawLineEx (data_divider_start_pos, data_divider_end_pos, 2, COLOR_BLOCK_EDGE);
207
208 draw_connection (cons_cache_bus_shared [i]);
209 draw_connection (cons_cache_bus_addr [i]);
210 draw_connection (cons_cache_bus_data [i]);
211}
212
213CACHE_LINE
214cache_get (CACHE cache, u8 addr, bool age)
215{
216 u8 offset = (addr % CACHE_ASSOCIATIVITY)*CACHE_LINES_PER_SET;
217 CACHE_LINE lines_begin = &cache->lines[offset];
218 CACHE_LINE lines_end = lines_begin + CACHE_LINES_PER_SET;
219 CACHE_LINE line = NULL;
220
221 for (CACHE_LINE iter_line = lines_begin; iter_line < lines_end; ++iter_line) {
222 if (iter_line->addr == addr &&
223 iter_line->state != CACHE_LINE_STATE_INVALID) {
224 line = iter_line;
225 line->age = 0;
226 cache->highlighted_pending = cache->highlighted;
227 cache->highlighted = line - cache->lines;
228 // printf ("%d %d\n", cache->highlighted, cache->highlighted_pending);
229 } else if (iter_line->state != CACHE_LINE_STATE_INVALID)
230 iter_line->age += age;
231 }
232
233 return line;
234}
235
236void
237cache_set (CACHE cache, CACHE_LINE line, u8 addr, u8 data, enum cache_line_state state, bool age)
238{
239 if (line)
240 goto set;
241
242 u8 offset = (addr % CACHE_ASSOCIATIVITY)*CACHE_LINES_PER_SET;
243 CACHE_LINE lines_begin = &cache->lines[offset];
244 CACHE_LINE lines_end = lines_begin + CACHE_LINES_PER_SET;
245
246 // Age cache lines
247 for (line = lines_begin; line < lines_end; ++line) {
248 if (line->state != CACHE_LINE_STATE_INVALID)
249 line->age += age;
250 }
251
252 // Find cache line with matching address
253 for (line = lines_begin; line < lines_end; ++line) {
254 if (line->addr == addr &&
255 line->state != CACHE_LINE_STATE_INVALID)
256 goto select;
257 }
258
259 // Find new spot for cache line
260 line = lines_begin;
261 if (line->state == CACHE_LINE_STATE_INVALID)
262 goto select;
263 for (CACHE_LINE iter_line = lines_begin + 1; iter_line < lines_end; ++iter_line) {
264 if (iter_line->state == CACHE_LINE_STATE_INVALID) {
265 line = iter_line;
266 break;
267 }
268 if (iter_line->age > line->age)
269 line = iter_line;
270 }
271
272 select:
273 // printf ("%d %d\n", cache->highlighted, cache->highlighted_pending);
274 cache->highlighted_pending = cache->highlighted;
275 cache->highlighted = line - cache->lines;
276 line->age = 0;
277 set:
278 line->state = state;
279 line->addr = addr;
280 line->data = data;
281}
282
283CACHE_LINE
284cache_to_replace (CACHE cache, u8 addr)
285{
286 u8 offset = (addr % CACHE_ASSOCIATIVITY)*CACHE_LINES_PER_SET;
287 CACHE_LINE lines_begin = &cache->lines[offset];
288 CACHE_LINE lines_end = lines_begin + CACHE_LINES_PER_SET;
289 CACHE_LINE line = NULL;
290
291 // Find cache line with matching address
292 for (line = lines_begin; line < lines_end; ++line) {
293 if (line->addr == addr &&
294 line->state != CACHE_LINE_STATE_INVALID)
295 return line;
296 }
297
298 // Find new spot for cache line
299 line = lines_begin;
300 if (line->state == CACHE_LINE_STATE_INVALID)
301 return line;
302 for (CACHE_LINE iter_line = lines_begin + 1; iter_line < lines_end; ++iter_line) {
303 if (iter_line->state == CACHE_LINE_STATE_INVALID) {
304 line = iter_line;
305 break;
306 }
307 if (iter_line->age > line->age)
308 line = iter_line;
309 }
310
311 return line;
312}
diff --git a/src/caches.h b/src/caches.h
new file mode 100644
index 0000000..b6af6ae
--- /dev/null
+++ b/src/caches.h
@@ -0,0 +1,60 @@
1#ifndef INCLUDED_CACHES_H
2#define INCLUDED_CACHES_H
3
4#include <raylib.h>
5#include <stdlib.h>
6#include "config.h"
7#include "busses.h"
8
9enum PACKED cache_line_state {
10 CACHE_LINE_STATE_MODIFIED = 2,
11 CACHE_LINE_STATE_EXCLUSIVE = 3,
12 CACHE_LINE_STATE_SHARED = 1,
13 CACHE_LINE_STATE_INVALID = 0,
14 CACHE_LINE_STATE_FORWARD = 4,
15 CACHE_LINE_STATE_COUNT,
16};
17
18typedef struct cache_line {
19 u8 age;
20 enum cache_line_state state;
21 u8 addr;
22 u8 data;
23} *CACHE_LINE;
24
25enum PACKED cache_state {
26 CACHE_STATE_WAIT,
27 CACHE_STATE_START_MEMORY_READ,
28 CACHE_STATE_START_MEMORY_WRITE,
29 CACHE_STATE_DATA_BUS_WAIT,
30};
31
32typedef struct cache {
33 struct cache_line lines[CACHE_LINE_COUNT];
34 enum cache_state state;
35 u8 addr_targets;
36 u8 data_targets;
37 u8 addr_value;
38 u8 data_value;
39 bool invalidate_others;
40 bool next_forward;
41 bool copy_back;
42 bool continue_addr;
43 bool continue_data;
44 Rectangle rec;
45 char label[8];
46 Vector2 label_origin;
47 Vector2 label_position;
48 int highlighted;
49 int highlighted_pending;
50} *CACHE;
51
52extern CACHE caches[CPU_COUNT];
53
54void init_cache (CACHE, BUS lower);
55void draw_cache (CACHE);
56CACHE_LINE cache_get (CACHE, u8 addr, bool age);
57void cache_set (CACHE, CACHE_LINE, u8 addr, u8 data, enum cache_line_state, bool age);
58CACHE_LINE cache_to_replace (CACHE cache, u8 addr);
59
60#endif
diff --git a/src/config.h b/src/config.h
new file mode 100644
index 0000000..5bc9557
--- /dev/null
+++ b/src/config.h
@@ -0,0 +1,74 @@
1#ifndef INCLUDED_CONFIG_H
2#define INCLUDED_CONFIG_H
3
4#include <stdint.h>
5
6#define INITIAL_SCREEN_WIDTH 500
7#define INITIAL_SCREEN_HEIGHT 500
8#define WINDOW_NAME "MERSI/MESIF LRU vizualization"
9
10#define CPU_COUNT 4
11#define CACHE_COUNT CPU_COUNT
12#define MEMORY_SIZE 16
13#define CACHE_LINE_SIZE 1
14#define CACHE_LINE_COUNT 4
15#define CACHE_ASSOCIATIVITY 2
16#define CACHE_LINES_PER_SET (CACHE_LINE_COUNT/CACHE_ASSOCIATIVITY)
17
18#define SCREEN_PADDING 25
19
20#define BUS_THICKNESS 10
21#define BUS_MARGIN 40
22#define BUS_SPACING 40
23#define BUS_ARROW_SIDE (2*BUS_THICKNESS)
24#define BUS_ARROW_HEIGHT (BUS_ARROW_SIDE*sqrt (3)/2)
25
26#define BLOCK_WIDTH 170
27#define BLOCK_MARGINH 50
28#define BLOCK_MARGINV 50
29#define BLOCK_PADDING 4
30
31#define TEXT_MARGIN 4
32#define TEXT_SPACING 4
33#define FONT_SIZE 24
34
35#define ENTRY_HEIGHT 20
36#define ENTRY_MARGIN 6
37
38#define ROUNDNESS 0.05
39#define SEGMENTS 16
40#define LINE_THICKNESS 2
41
42#define TRANSACTIONS_PER_SECOND 2
43#define TICKS_PER_TRANSACTION 20
44#define TICKS_PER_SECOND (TICKS_PER_TRANSACTION*TRANSACTIONS_PER_SECOND)
45#define TICK_SECONDS (1./TICKS_PER_SECOND)
46#define MAX_TIME (60*60)
47#define MAX_TICKS (MAX_TIME*TICKS_PER_SECOND)
48
49#define DARKDARKGRAY (Color) { 20, 20, 20, 255 }
50#define COLOR_DATA RED
51#define COLOR_ADDR BLUE
52#define COLOR_SHARED MAGENTA
53#define THEME_LIGHT 0
54#define THEME_DARK 1
55#define THEME THEME_LIGHT
56#if THEME == THEME_DARK
57#define COLOR_BACKGROUND BLACK
58#define COLOR_BUS_INACTIVE LIGHTGRAY
59#define COLOR_BLOCK BLACK
60#define COLOR_BLOCK_EDGE WHITE
61#define COLOR_BUTTON DARKDARKGRAY
62#define COLOR_BUTTON_HOVER COLOR_BACKGROUND
63#define COLOR_TEXT WHITE
64#else
65#define COLOR_BACKGROUND WHITE
66#define COLOR_BUS_INACTIVE DARKGRAY
67#define COLOR_BLOCK WHITE
68#define COLOR_BLOCK_EDGE BLACK
69#define COLOR_BUTTON LIGHTGRAY
70#define COLOR_BUTTON_HOVER COLOR_BACKGROUND
71#define COLOR_TEXT BLACK
72#endif
73
74#endif
diff --git a/src/connections.c b/src/connections.c
new file mode 100644
index 0000000..438eb29
--- /dev/null
+++ b/src/connections.c
@@ -0,0 +1,183 @@
1#include "connections.h"
2#include "config.h"
3#include <raymath.h>
4#include <stdio.h>
5
6bool transaction_proggressed;
7
8#define TRANSACTION_STATE_DIRECTION(con) ((con)->transaction_state & CONNECTION_TRANSACTION_STATE_DIRECTION_MASK)
9#define TRANSACTION_STATE_TYPE(con) ((con)->transaction_state & CONNECTION_TRANSACTION_STATE_TYPE_MASK)
10
11static inline float
12logistic (float x, float x0, float max, float rate)
13{
14 return max/(1 + exp (-rate*(x - x0)));
15}
16
17CONNECTION cons_cpu_cache_addr [CPU_COUNT];
18CONNECTION cons_cpu_cache_data [CPU_COUNT];
19CONNECTION cons_cache_bus_shared [CPU_COUNT];
20CONNECTION cons_cache_bus_addr [CPU_COUNT];
21CONNECTION cons_cache_bus_data [CPU_COUNT];
22CONNECTION con_memory_bus_addr;
23CONNECTION con_memory_bus_data;
24
25void
26init_connection (CONNECTION con, float x, float ys, float ye, Color c, float scale)
27{
28 *con = (struct connection) {
29 .transaction_state = CONNECTION_TRANSACTION_STATE_NONE,
30 .x = x,
31 .ys = ys,
32 .ye = ye,
33 .color = c,
34 .scale = scale,
35 };
36}
37
38void
39draw_connection (CONNECTION con)
40{
41 const float x = con->x;
42 float ys;
43 float ye;
44 int dir;
45
46 switch (TRANSACTION_STATE_DIRECTION(con)) {
47 case CONNECTION_TRANSACTION_DIRECTION_FROM_TO:
48 ys = con->ys;
49 ye = con->ye;
50 dir = +1;
51 break;
52 case CONNECTION_TRANSACTION_DIRECTION_TO_FROM:
53 ys = con->ye;
54 ye = con->ys;
55 dir = -1;
56 break;
57 }
58
59 const Vector2 pos_start = { x, ys };
60 const float thick = BUS_THICKNESS*con->scale;
61 const float head_side = 2*thick;
62 const float head_height = head_side*sqrt (3)/2;
63 const Vector2 head_offset_peak = { 0, dir*head_height };
64 const Vector2 head_offset_left = { +dir*head_side/2, 0 };
65 const Vector2 head_offset_right = { -dir*head_side/2, 0 };
66 const Vector2 line_begin_pos = { x, ys - dir*head_height };
67 const Vector2 line_end_pos = { x, ye + dir*head_height };
68
69 float fraction = (con->transaction_progress < 1
70 ? logistic (con->transaction_progress, 0.5, 1, 10) : 1);
71 Vector2 lerped_line_pos = Vector2Lerp (pos_start, line_end_pos, fraction);
72
73 switch (TRANSACTION_STATE_TYPE(con)) {
74 case CONNECTION_TRANSACTION_TYPE_NONE:
75 DrawLineEx (line_begin_pos, line_end_pos, thick, COLOR_BUS_INACTIVE);
76 DrawTriangle(Vector2Add (line_begin_pos, head_offset_peak),
77 Vector2Add (line_begin_pos, head_offset_left),
78 Vector2Add (line_begin_pos, head_offset_right),
79 COLOR_BUS_INACTIVE);
80 DrawTriangle(Vector2Subtract (line_end_pos, head_offset_peak),
81 Vector2Subtract (line_end_pos, head_offset_left),
82 Vector2Subtract (line_end_pos, head_offset_right),
83 COLOR_BUS_INACTIVE);
84 break;
85 case CONNECTION_TRANSACTION_TYPE_FORWARD:
86 DrawLineEx (pos_start, line_end_pos, thick, COLOR_BUS_INACTIVE);
87 DrawTriangle(Vector2Subtract (line_end_pos, head_offset_peak),
88 Vector2Subtract (line_end_pos, head_offset_left),
89 Vector2Subtract (line_end_pos, head_offset_right),
90 COLOR_BUS_INACTIVE);
91
92 DrawLineEx (pos_start, lerped_line_pos, thick, con->color);
93 DrawTriangle(Vector2Subtract (lerped_line_pos, head_offset_peak),
94 Vector2Subtract (lerped_line_pos, head_offset_left),
95 Vector2Subtract (lerped_line_pos, head_offset_right),
96 con->color);
97 break;
98 case CONNECTION_TRANSACTION_TYPE_TRAILING:
99 DrawTriangle(Vector2Add (line_begin_pos, head_offset_peak),
100 Vector2Add (line_begin_pos, head_offset_left),
101 Vector2Add (line_begin_pos, head_offset_right),
102 ColorAlpha (COLOR_BUS_INACTIVE, fraction));
103
104 DrawLineEx (Vector2Add (line_begin_pos, Vector2Scale (head_offset_peak, .5)),
105 line_end_pos, thick, COLOR_BUS_INACTIVE);
106 DrawTriangle(Vector2Subtract (line_end_pos, head_offset_peak),
107 Vector2Subtract (line_end_pos, head_offset_left),
108 Vector2Subtract (line_end_pos, head_offset_right),
109 COLOR_BUS_INACTIVE);
110
111 DrawLineEx (lerped_line_pos, line_end_pos, thick, con->color);
112 DrawTriangle(Vector2Subtract (line_end_pos, head_offset_peak),
113 Vector2Subtract (line_end_pos, head_offset_left),
114 Vector2Subtract (line_end_pos, head_offset_right),
115 con->color);
116 break;
117 }
118}
119
120void
121connection_start_transaction (CONNECTION con, enum connection_transaction_direction dir, u8 value)
122{
123 con->transaction_value = value;
124 con->transaction_progress = 0;
125 con->transaction_state = dir | CONNECTION_TRANSACTION_TYPE_FORWARD;
126}
127
128void
129connection_end_transaction (CONNECTION con)
130{
131 if (TRANSACTION_STATE_TYPE(con) != CONNECTION_TRANSACTION_TYPE_FORWARD)
132 return;
133
134 con->transaction_state = TRANSACTION_STATE_DIRECTION(con) |
135 CONNECTION_TRANSACTION_TYPE_TRAILING;
136 con->transaction_progress = 0;
137}
138
139bool
140connection_progress_transaction (CONNECTION con)
141{
142 if (!connection_is_transaction_ongoing (con) ||
143 con->transaction_progress == 1) {
144 return con->transaction_just_finished = false;
145 }
146
147 transaction_proggressed = true;
148 con->transaction_progress = fmin (con->transaction_progress +
149 GetFrameTime ()*TRANSACTIONS_PER_SECOND, 1);
150 if (con->transaction_progress == 1) {
151 con->transaction_just_finished_state = con->transaction_state;
152 return con->transaction_just_finished = true;
153 }
154
155 return con->transaction_just_finished = false;
156}
157
158bool
159connection_is_transaction_ongoing (CONNECTION con)
160{
161 return (TRANSACTION_STATE_TYPE(con) != CONNECTION_TRANSACTION_TYPE_NONE);
162}
163
164bool
165connection_is_transaction_complete (CONNECTION con)
166{
167 return (con->transaction_progress == 1 &&
168 connection_is_transaction_ongoing(con));
169}
170
171bool
172connection_is_transaction_direction_from_to (CONNECTION con)
173{
174 return (con->transaction_state != CONNECTION_TRANSACTION_STATE_NONE &&
175 TRANSACTION_STATE_DIRECTION(con) == CONNECTION_TRANSACTION_DIRECTION_FROM_TO);
176}
177
178bool
179connection_is_transaction_direction_to_from (CONNECTION con)
180{
181 return (con->transaction_state != CONNECTION_TRANSACTION_STATE_NONE &&
182 TRANSACTION_STATE_DIRECTION(con) == CONNECTION_TRANSACTION_DIRECTION_TO_FROM);
183}
diff --git a/src/connections.h b/src/connections.h
new file mode 100644
index 0000000..ed7245b
--- /dev/null
+++ b/src/connections.h
@@ -0,0 +1,82 @@
1#ifndef INCLUDED_CONNECTIONS_H
2#define INCLUDED_CONNECTIONS_H
3
4#include <raylib.h>
5#include <inttypes.h>
6#include "config.h"
7#include "utils.h"
8
9#define CONNECTION_NONE -1
10#define CONNECTION_MEMORY CPU_COUNT
11#define CONNECTION_CACHES ((1 << CPU_COUNT) - 1)
12
13#define CONNECTION_TRANSACTION_STATE_DIRECTION(con) ((con)->transaction_state & CONNECTION_TRANSACTION_STATE_DIRECTION_MASK)
14#define CONNECTION_TRANSACTION_STATE_TYPE(con) ((con)->transaction_state & CONNECTION_TRANSACTION_STATE_TYPE_MASK)
15
16#define CONNECTION_START_TRANSACTION_FROM_TO(con, val) connection_start_transaction ((con), CONNECTION_TRANSACTION_DIRECTION_FROM_TO, (val))
17#define CONNECTION_START_TRANSACTION_TO_FROM(con, val) connection_start_transaction ((con), CONNECTION_TRANSACTION_DIRECTION_TO_FROM, (val))
18#define CONNECTION_CLEAR_TRANSACTION(con) (con->transaction_state = CONNECTION_TRANSACTION_STATE_NONE)
19
20enum PACKED connection_transaction_direction {
21 CONNECTION_TRANSACTION_DIRECTION_FROM_TO,
22 CONNECTION_TRANSACTION_DIRECTION_TO_FROM,
23 CONNECTION_TRANSACTION_DIRECTION_LAST,
24};
25
26#define CONNECTION_TRANSACTION_DIRECTION_BITS (CONNECTION_TRANSACTION_DIRECTION_LAST - 1)
27
28enum PACKED connection_transaction_type {
29 CONNECTION_TRANSACTION_TYPE_NONE,
30 CONNECTION_TRANSACTION_TYPE_FORWARD = 0b01 << CONNECTION_TRANSACTION_DIRECTION_BITS,
31 CONNECTION_TRANSACTION_TYPE_TRAILING = 0b10 << CONNECTION_TRANSACTION_DIRECTION_BITS,
32 CONNECTION_TRANSACTION_TYPE_LAST,
33};
34
35#define CONNECTION_TRANSACTION_TYPE_BITS (CONNECTION_TRANSACTION_TYPE_LAST >> 1)
36
37#define CONNECTION_TRANSACTION_STATE_DIRECTION_MASK ((1 << CONNECTION_TRANSACTION_DIRECTION_BITS) - 1)
38#define CONNECTION_TRANSACTION_STATE_TYPE_MASK (((1 << CONNECTION_TRANSACTION_TYPE_BITS ) - 1) << CONNECTION_TRANSACTION_DIRECTION_BITS)
39
40enum PACKED connection_transaction_state {
41 CONNECTION_TRANSACTION_STATE_NONE,
42 CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD = CONNECTION_TRANSACTION_DIRECTION_FROM_TO | CONNECTION_TRANSACTION_TYPE_FORWARD ,
43 CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING = CONNECTION_TRANSACTION_DIRECTION_FROM_TO | CONNECTION_TRANSACTION_TYPE_TRAILING,
44 CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD = CONNECTION_TRANSACTION_DIRECTION_TO_FROM | CONNECTION_TRANSACTION_TYPE_FORWARD ,
45 CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING = CONNECTION_TRANSACTION_DIRECTION_TO_FROM | CONNECTION_TRANSACTION_TYPE_TRAILING,
46};
47
48typedef struct connection {
49 enum connection_transaction_state transaction_state;
50 u8 transaction_value;
51 float transaction_progress;
52 bool transaction_just_finished;
53 enum connection_transaction_state transaction_just_finished_state;
54 bool transaction_pending;
55 float x;
56 float ys;
57 float ye;
58 Color color;
59 float scale;
60} *CONNECTION;
61
62extern CONNECTION cons_cpu_cache_addr [CPU_COUNT];
63extern CONNECTION cons_cpu_cache_data [CPU_COUNT];
64extern CONNECTION cons_cache_bus_shared [CPU_COUNT];
65extern CONNECTION cons_cache_bus_addr [CPU_COUNT];
66extern CONNECTION cons_cache_bus_data [CPU_COUNT];
67extern CONNECTION con_memory_bus_addr;
68extern CONNECTION con_memory_bus_data;
69extern bool transaction_proggressed;
70
71void init_connection (CONNECTION, float x, float ys, float ye, Color, float scale);
72void draw_connection (CONNECTION);
73void connection_start_transaction (CONNECTION, enum connection_transaction_direction, u8 value);
74void connection_end_transaction (CONNECTION);
75void connection_reverse_transaction (CONNECTION);
76bool connection_progress_transaction (CONNECTION);
77bool connection_is_transaction_ongoing (CONNECTION);
78bool connection_is_transaction_complete (CONNECTION);
79bool connection_is_transaction_direction_from_to (CONNECTION);
80bool connection_is_transaction_direction_to_from (CONNECTION);
81
82#endif
diff --git a/src/cpus.c b/src/cpus.c
new file mode 100644
index 0000000..f2effc0
--- /dev/null
+++ b/src/cpus.c
@@ -0,0 +1,179 @@
1#include "cpus.h"
2#include <raymath.h>
3#include <string.h>
4#include <stdio.h>
5#include "caches.h"
6#include "connections.h"
7#include "config.h"
8
9extern Font font;
10extern Camera2D camera;
11
12CPU cpus[CPU_COUNT];
13int cpu_button_hover = CPU_COUNT*MEMORY_SIZE*3;
14
15void
16init_cpu (CPU cpu, CACHE cache)
17{
18 int i = cpu - cpus[0];
19 cpu->rec = (Rectangle) {
20 .x = cache->rec.x,
21 .y = cache->rec.y + cache->rec.height + BLOCK_MARGINV,
22 .width = BLOCK_WIDTH,
23 .height = 2*BLOCK_PADDING + MEMORY_SIZE*(ENTRY_HEIGHT + ENTRY_MARGIN) - ENTRY_MARGIN,
24 };
25
26 strcpy (cpu->label, "CPU 0");
27 cpu->label[strlen (cpu->label) - 1] += i;
28 cpu->label_origin = Vector2Scale (MeasureTextEx (font, cpu->label, FONT_SIZE, TEXT_SPACING), 0.5);
29 cpu->label_position = (Vector2) {
30 .x = cpu->rec.x - cpu->label_origin.y/2 - TEXT_MARGIN,
31 .y = cpu->rec.y + cpu->rec.height/2,
32 };
33
34 float ys = cpu->rec.y - LINE_THICKNESS;
35 float ye = cache->rec.y + cache->rec.height + LINE_THICKNESS;
36 float xd = cpu->rec.width*1/4;
37 float xs = cpu->rec.x + xd;
38 init_connection (cons_cpu_cache_addr[i], xs + 1*xd, ys, ye, COLOR_ADDR, 1.);
39 init_connection (cons_cpu_cache_data[i], xs + 2*xd, ys, ye, COLOR_DATA, 1.);
40
41 cpu->highlighted = 3*MEMORY_SIZE;
42}
43
44bool
45handle_cpu_buttons (CPU cpu)
46{
47 int i = cpu - cpus[0];
48 Vector2 mouse_pos = GetScreenToWorld2D (GetMousePosition (), camera);
49 if (!CheckCollisionPointRec (mouse_pos, cpu->rec))
50 return false;
51
52 for (int j = 0; j < MEMORY_SIZE; ++j) {
53 Rectangle read_rec = {
54 .x = cpu->rec.x + cpu->rec.width*1/4 + BLOCK_PADDING,
55 .y = cpu->rec.y + Remap (j, 0, MEMORY_SIZE - 1,
56 BLOCK_PADDING,
57 cpu->rec.height - BLOCK_PADDING - ENTRY_HEIGHT),
58 .width = cpu->rec.width*1/4. - 2*BLOCK_PADDING/3. - 2*LINE_THICKNESS/3. - ENTRY_MARGIN/2.,
59 .height = ENTRY_HEIGHT,
60 };
61 if (CheckCollisionPointRec (mouse_pos, read_rec)) {
62 cpu_button_hover = i*MEMORY_SIZE*3 + j*3 + 0;
63 return true;
64 }
65
66 Rectangle increment_rec = read_rec;
67 increment_rec.x += read_rec.width + ENTRY_MARGIN;
68 if (CheckCollisionPointRec (mouse_pos, increment_rec)) {
69 cpu_button_hover = i*MEMORY_SIZE*3 + j*3 + 1;
70 return true;
71 }
72
73 Rectangle write_rec = increment_rec;
74 write_rec.x += increment_rec.width + ENTRY_MARGIN;
75 if (CheckCollisionPointRec (mouse_pos, write_rec)) {
76 cpu_button_hover = i*MEMORY_SIZE*3 + j*3 + 2;
77 return true;
78 }
79 }
80
81 return false;
82}
83
84void
85draw_cpu (CPU cpu)
86{
87 int i = cpu - cpus[0];
88 const Color edge_color = cpu->highlighted < 2*MEMORY_SIZE ? GREEN : COLOR_BLOCK_EDGE;
89 DrawRectangleRounded (cpu->rec, ROUNDNESS, SEGMENTS, COLOR_BLOCK);
90 DrawRectangleRoundedLinesEx (cpu->rec, ROUNDNESS, SEGMENTS, LINE_THICKNESS, edge_color);
91 DrawTextPro (font, cpu->label, cpu->label_position, cpu->label_origin, -90, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
92
93 const Vector2 divider_start_pos = {
94 .x = cpu->rec.x + cpu->rec.width*1/4,
95 .y = cpu->rec.y,
96 };
97 const Vector2 divider_end_pos = {
98 .x = divider_start_pos.x,
99 .y = divider_start_pos.y + cpu->rec.height,
100 };
101 DrawLineEx (divider_start_pos, divider_end_pos, 2, COLOR_BLOCK_EDGE);
102 for (int j = 0; j < MEMORY_SIZE; ++j) {
103 if (j != 0) {
104 const Vector2 divider_start_pos = {
105 .x = cpu->rec.x,
106 .y = cpu->rec.y + j*cpu->rec.height/MEMORY_SIZE,
107 };
108 const Vector2 divider_end_pos = {
109 .x = divider_start_pos.x + cpu->rec.width/4,
110 .y = divider_start_pos.y,
111 };
112 DrawLineEx (divider_start_pos, divider_end_pos, 2, COLOR_BLOCK_EDGE);
113 }
114
115 char address[3];
116 sprintf (address, "#%hhX", j);
117 const Vector2 address_center = Vector2Scale (MeasureTextEx (font, address, FONT_SIZE, TEXT_SPACING), .5);
118 const Vector2 address_entry_center = {
119 .x = cpu->rec.x + cpu->rec.width*1/4/2.,
120 .y = cpu->rec.y + (j + .5)*cpu->rec.height/MEMORY_SIZE,
121 };
122 const Vector2 address_pos = Vector2Subtract (address_entry_center, address_center);
123 DrawTextEx (font, address, address_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
124
125 Rectangle read_rec = {
126 .x = divider_start_pos.x + BLOCK_PADDING + LINE_THICKNESS/3.,
127 .y = cpu->rec.y + Remap (j, 0, MEMORY_SIZE - 1,
128 BLOCK_PADDING,
129 cpu->rec.height - BLOCK_PADDING - ENTRY_HEIGHT),
130 .width = cpu->rec.width*1/4. - 2*BLOCK_PADDING/3. - 2*LINE_THICKNESS/3. - ENTRY_MARGIN/2.,
131 .height = ENTRY_HEIGHT,
132 };
133 const Color read_color = cpu_button_hover == i*MEMORY_SIZE*3 + j*3 + 0
134 ? COLOR_BUTTON_HOVER
135 : COLOR_BUTTON;
136 const Color read_edge_color = 3*j == cpu->highlighted ? RED : COLOR_BLOCK_EDGE;
137 DrawRectangleRounded (read_rec, ROUNDNESS, SEGMENTS, read_color);
138 DrawRectangleRoundedLinesEx (read_rec, ROUNDNESS, SEGMENTS, LINE_THICKNESS, read_edge_color);
139 const Vector2 read_text_center = MeasureTextEx (font, "R", FONT_SIZE, TEXT_SPACING);
140 const Vector2 read_text_pos = {
141 .x = read_rec.x + read_rec.width /2 - read_text_center.x/2,
142 .y = read_rec.y + read_rec.height/2 - read_text_center.y/2,
143 };
144 DrawTextEx (font, "R", read_text_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
145
146 Rectangle increment_rec = read_rec;
147 increment_rec.x += read_rec.width + ENTRY_MARGIN;
148 Color increment_color = cpu_button_hover == i*MEMORY_SIZE*3 + j*3 + 1
149 ? COLOR_BUTTON_HOVER
150 : COLOR_BUTTON;
151 const Color increment_edge_color = 3*j + 1 == cpu->highlighted ? RED : COLOR_BLOCK_EDGE;
152 DrawRectangleRounded (increment_rec, ROUNDNESS, SEGMENTS, increment_color);
153 DrawRectangleRoundedLinesEx (increment_rec, ROUNDNESS, SEGMENTS, LINE_THICKNESS, increment_edge_color);
154 const Vector2 increment_text_center = MeasureTextEx (font, "I", FONT_SIZE, TEXT_SPACING);
155 const Vector2 increment_text_pos = {
156 .x = increment_rec.x + increment_rec.width /2 - increment_text_center.x/2,
157 .y = increment_rec.y + increment_rec.height/2 - increment_text_center.y/2,
158 };
159 DrawTextEx (font, "I", increment_text_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
160
161 Rectangle write_rec = increment_rec;
162 write_rec.x += increment_rec.width + ENTRY_MARGIN;
163 Color write_color = cpu_button_hover == i*MEMORY_SIZE*3 + j*3 + 2
164 ? COLOR_BUTTON_HOVER
165 : COLOR_BUTTON;
166 const Color write_edge_color = 3*j + 2 == cpu->highlighted ? RED : COLOR_BLOCK_EDGE;
167 DrawRectangleRounded (write_rec, ROUNDNESS, SEGMENTS, write_color);
168 DrawRectangleRoundedLinesEx (write_rec, ROUNDNESS, SEGMENTS, LINE_THICKNESS, write_edge_color);
169 const Vector2 write_text_center = MeasureTextEx (font, "W", FONT_SIZE, TEXT_SPACING);
170 const Vector2 write_text_pos = {
171 .x = write_rec.x + write_rec.width /2 - write_text_center.x/2,
172 .y = write_rec.y + write_rec.height/2 - write_text_center.y/2,
173 };
174 DrawTextEx (font, "W", write_text_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
175 }
176
177 draw_connection (cons_cpu_cache_addr[i]);
178 draw_connection (cons_cpu_cache_data[i]);
179}
diff --git a/src/cpus.h b/src/cpus.h
new file mode 100644
index 0000000..71fde22
--- /dev/null
+++ b/src/cpus.h
@@ -0,0 +1,24 @@
1#ifndef INCLUDED_CPUS_H
2#define INCLUDED_CPUS_H
3
4#include <raylib.h>
5#include <stdbool.h>
6#include "config.h"
7#include "caches.h"
8
9typedef struct cpu {
10 Rectangle rec;
11 char label[6];
12 Vector2 label_origin;
13 Vector2 label_position;
14 int highlighted;
15} *CPU;
16
17extern CPU cpus[CPU_COUNT];
18extern int cpu_button_hover;
19
20void init_cpu (CPU, CACHE);
21bool handle_cpu_buttons (CPU);
22void draw_cpu (CPU);
23
24#endif
diff --git a/src/export-font-as-code.c b/src/export-font-as-code.c
new file mode 100644
index 0000000..1fedc3a
--- /dev/null
+++ b/src/export-font-as-code.c
@@ -0,0 +1,17 @@
1#include <stdlib.h>
2#include <raylib.h>
3#include "config.h"
4
5int
6main (int argc, char *argv[])
7{
8 InitWindow (INITIAL_SCREEN_WIDTH,
9 INITIAL_SCREEN_HEIGHT,
10 WINDOW_NAME);
11
12 // Font font = LoadFontEx ("res/KodeMono-VariableFont_wght.ttf", 4*FONT_SIZE, NULL, 0);
13 Font font = LoadFontEx ("res/KodeMono-VariableFont_wght.ttf", FONT_SIZE + 4, NULL, 0);
14 ExportFontAsCode (font, "res/font_data.h");
15
16 return EXIT_SUCCESS;
17}
diff --git a/src/memory.c b/src/memory.c
new file mode 100644
index 0000000..1124f32
--- /dev/null
+++ b/src/memory.c
@@ -0,0 +1,99 @@
1#include "memory.h"
2#include <raymath.h>
3#include <stdio.h>
4#include "config.h"
5#include "connections.h"
6
7MEMORY memory;
8
9extern Font font;
10
11void
12init_memory (MEMORY memory, CPU any_cpu)
13{
14 memory->rec = (Rectangle) {
15 .x = -BLOCK_WIDTH/2,
16 .y = any_cpu->rec.y,
17 .width = BLOCK_WIDTH,
18 .height = 2*BLOCK_PADDING + MEMORY_SIZE*(ENTRY_HEIGHT + ENTRY_MARGIN) - ENTRY_MARGIN,
19 };
20 memory->label = "MEMORY";
21 memory->label_origin = Vector2Scale (MeasureTextEx (font, memory->label, FONT_SIZE, TEXT_SPACING), 0.5);
22 memory->label_position = (Vector2) {
23 .x = memory->rec.x - memory->label_origin.y/2 - TEXT_MARGIN,
24 .y = memory->rec.y + memory->rec.height/2,
25 };
26
27 float ys = memory->rec.y - LINE_THICKNESS;
28 float xd = memory->rec.width*1/4;
29 float xs = memory->rec.x + xd;
30 init_connection (con_memory_bus_addr, xs + 1*xd, ys, addr_bus->y + addr_bus->scale*BUS_THICKNESS/2, COLOR_ADDR, 1);
31 init_connection (con_memory_bus_data, xs + 2*xd, ys, data_bus->y + data_bus->scale*BUS_THICKNESS/2, COLOR_DATA, 1);
32
33 memory->highlighted = MEMORY_SIZE;
34}
35
36void
37draw_memory (MEMORY memory)
38{
39 DrawRectangleRounded (memory->rec, ROUNDNESS, SEGMENTS, COLOR_BLOCK);
40 DrawTextPro (font, memory->label, memory->label_position, memory->label_origin, -90, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
41
42 for (int i = 0; i < MEMORY_SIZE; ++i) {
43 if (i == memory->highlighted) {
44 Rectangle entry = {
45 .x = memory->rec.x,
46 .y = memory->rec.y + i*memory->rec.height/MEMORY_SIZE,
47 .width = BLOCK_WIDTH,
48 .height = memory->rec.height/MEMORY_SIZE,
49 };
50 DrawRectangleRec (entry, GREEN);
51 }
52
53 if (i != 0) {
54 const Vector2 divider_start_pos = {
55 .x = memory->rec.x,
56 .y = memory->rec.y + i*memory->rec.height/MEMORY_SIZE,
57 };
58 const Vector2 divider_end_pos = {
59 .x = divider_start_pos.x + memory->rec.width,
60 .y = divider_start_pos.y,
61 };
62 DrawLineEx (divider_start_pos, divider_end_pos, 2, COLOR_BLOCK_EDGE);
63 }
64
65 char address[3];
66 sprintf (address, "#%X", i);
67 const Vector2 address_center = Vector2Scale (MeasureTextEx (font, address, FONT_SIZE, TEXT_SPACING), .5);
68 const Vector2 address_entry_center = {
69 .x = memory->rec.x + memory->rec.width*1/3/2,
70 .y = memory->rec.y + (i + .5)*memory->rec.height/MEMORY_SIZE,
71 };
72 const Vector2 address_pos = Vector2Subtract (address_entry_center, address_center);
73 DrawTextEx (font, address, address_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
74
75 char value[3];
76 sprintf (value, "%02hhX", memory->entries[i]);
77 const Vector2 value_center = Vector2Scale (MeasureTextEx (font, value, FONT_SIZE, TEXT_SPACING), .5);
78 const Vector2 value_entry_center = {
79 .x = memory->rec.x + memory->rec.width*2/3,
80 .y = address_entry_center.y,
81 };
82 const Vector2 value_pos = Vector2Subtract (value_entry_center, value_center);
83 DrawTextEx (font, value, value_pos, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
84 }
85 DrawRectangleRoundedLinesEx (memory->rec, ROUNDNESS, SEGMENTS, LINE_THICKNESS, COLOR_BLOCK_EDGE);
86
87 const Vector2 divider_start_pos = {
88 .x = memory->rec.x + memory->rec.width*1/3,
89 .y = memory->rec.y,
90 };
91 const Vector2 divider_end_pos = {
92 .x = divider_start_pos.x,
93 .y = divider_start_pos.y + memory->rec.height,
94 };
95 DrawLineEx (divider_start_pos, divider_end_pos, 2, COLOR_BLOCK_EDGE);
96
97 draw_connection (con_memory_bus_addr);
98 draw_connection (con_memory_bus_data);
99}
diff --git a/src/memory.h b/src/memory.h
new file mode 100644
index 0000000..9c348cf
--- /dev/null
+++ b/src/memory.h
@@ -0,0 +1,22 @@
1#ifndef INCLUDED_MEMORY_H
2#define INCLUDED_MEMORY_H
3
4#include <inttypes.h>
5#include <raylib.h>
6#include "cpus.h"
7
8typedef struct memory {
9 u8 entries[MEMORY_SIZE];
10 Rectangle rec;
11 const char *label;
12 Vector2 label_origin;
13 Vector2 label_position;
14 u8 highlighted;
15} *MEMORY;
16
17extern MEMORY memory;
18
19void init_memory (MEMORY, CPU any);
20void draw_memory (MEMORY);
21
22#endif
diff --git a/src/mesif-lru-simulation.c b/src/mesif-lru-simulation.c
new file mode 100644
index 0000000..45f99c4
--- /dev/null
+++ b/src/mesif-lru-simulation.c
@@ -0,0 +1,705 @@
1#include <stdbool.h>
2#define _GNU_SOURCE
3#include <stdlib.h>
4#include <string.h>
5#include <stdio.h>
6#include <assert.h>
7#include <time.h>
8#include <raylib.h>
9#include <raymath.h>
10
11#include "config.h"
12#include "font_data.h"
13#include "states.h"
14#include "busses.h"
15#include "connections.h"
16#include "caches.h"
17#include "cpus.h"
18#include "memory.h"
19
20Font font;
21Camera2D camera;
22
23bool is_paused;
24float seconds_since_last_tick;
25
26static inline int
27get_display_width (void)
28{
29 return IsWindowFullscreen ()
30 ? GetMonitorWidth (GetCurrentMonitor ())
31 : GetScreenWidth ();
32}
33
34static inline int
35get_display_height (void)
36{
37 return IsWindowFullscreen ()
38 ? GetMonitorHeight (GetCurrentMonitor ())
39 : GetScreenHeight ();
40}
41
42inline static void
43init_camera (void)
44{
45 camera = (Camera2D) {
46 .target = { 0, 0 },
47 .offset = { get_display_width ()/2., SCREEN_PADDING },
48 .rotation = 0.,
49 .zoom = 1.,
50 };
51}
52
53static inline void
54startup (void)
55{
56 SetConfigFlags (FLAG_MSAA_4X_HINT |
57 FLAG_WINDOW_RESIZABLE |
58 FLAG_VSYNC_HINT);
59 InitWindow (INITIAL_SCREEN_WIDTH,
60 INITIAL_SCREEN_HEIGHT,
61 WINDOW_NAME);
62 SetTargetFPS (60);
63
64 srand (time (NULL));
65
66 // font = LoadFontEx ("res/KodeMono-VariableFont_wght.ttf", 4*FONT_SIZE, NULL, 0);
67 font = LoadFont_FontData ();
68 SetTextureFilter (font.texture, TEXTURE_FILTER_TRILINEAR);
69 // SetTextureFilter (font.texture, TEXTURE_FILTER_ANISOTROPIC_16X);
70
71 init_camera ();
72 reset_state ();
73}
74
75static inline void
76shutdown (void)
77{
78 CloseWindow ();
79}
80
81static inline void
82toggle_fullscreen_window (void)
83{
84 static int window_width;
85 static int window_height;
86
87 if (!IsWindowFullscreen ()) {
88 window_width = GetScreenWidth ();
89 window_height = GetScreenHeight ();
90 int monitor = GetCurrentMonitor ();
91 SetWindowSize (GetMonitorWidth (monitor), GetMonitorHeight (monitor));
92 ToggleFullscreen ();
93 } else {
94 ToggleFullscreen ();
95 SetWindowSize (window_width, window_height);
96 }
97}
98
99static inline void
100handle_input (void)
101{
102 if (IsKeyPressed (KEY_SPACE)) is_paused = is_paused ? false : true;
103 if (IsKeyPressed (KEY_R)) reset_state ();
104
105 if (is_paused) {
106 float wheel = GetMouseWheelMove();
107 if (wheel > 0 && current_tick < last_tick)
108 set_state (current_tick + 1);
109 if (wheel < 0 && current_tick)
110 set_state (current_tick - 1);
111 } else
112 camera.zoom += .1*GetMouseWheelMove();
113
114 if (IsKeyPressed (KEY_F11)) toggle_fullscreen_window ();
115 if (IsKeyDown (KEY_RIGHT)) camera.target.x += 2;
116 if (IsKeyDown (KEY_LEFT )) camera.target.x -= 2;
117 if (IsKeyDown (KEY_DOWN )) camera.target.y += 2;
118 if (IsKeyDown (KEY_UP )) camera.target.y -= 2;
119 if (IsMouseButtonDown (MOUSE_MIDDLE_BUTTON)) camera.target = Vector2Add (camera.target, Vector2Scale (GetMouseDelta (), -1));
120 if (IsKeyDown (KEY_MINUS)) camera.zoom -= .01;
121 if (IsKeyDown (KEY_EQUAL)) camera.zoom += .01;
122 if (IsKeyDown (KEY_H)) {
123 camera.target = (Vector2) { 0 };
124 camera.zoom = 1.;
125 }
126
127 cpu_button_hover = CPU_COUNT*MEMORY_SIZE*3;
128 for (int i = 0; i < CPU_COUNT; ++i) {
129 if (handle_cpu_buttons (cpus[i]))
130 break;
131 }
132}
133
134static inline void
135update (void)
136{
137 camera.offset.x = get_display_width ()/2.;
138
139 // check for cpu button press
140 if (cpu_button_hover != CPU_COUNT*MEMORY_SIZE*3 &&
141 IsMouseButtonReleased (MOUSE_LEFT_BUTTON)) {
142 int i = cpu_button_hover/MEMORY_SIZE/3;
143 CPU cpu = cpus [i];
144 if (cpu->highlighted == MEMORY_SIZE*3) {
145 cpu->highlighted = cpu_button_hover - i*MEMORY_SIZE*3;
146 CONNECTION_START_TRANSACTION_FROM_TO(cons_cpu_cache_addr[i],
147 cpu->highlighted/3);
148 if (cpu->highlighted % 3 == 2) {
149 CONNECTION_START_TRANSACTION_FROM_TO(cons_cpu_cache_data[i], rand ()%(1 << 8));
150 }
151 }
152 }
153
154 // progress all transactions
155 if (!is_paused) {
156 transaction_proggressed = false;
157 for (int i = 0; i < CPU_COUNT; ++i){
158 connection_progress_transaction (cons_cpu_cache_addr [i]);
159 connection_progress_transaction (cons_cpu_cache_data [i]);
160 connection_progress_transaction (cons_cache_bus_shared [i]);
161 connection_progress_transaction (cons_cache_bus_addr [i]);
162 connection_progress_transaction (cons_cache_bus_data [i]);
163 }
164 connection_progress_transaction (con_memory_bus_addr);
165 connection_progress_transaction (con_memory_bus_data);
166 }
167
168 CONNECTION con;
169
170 // TODO(cmmm): extract state advancers into separate functions
171 for (int i = 0; i < CPU_COUNT; ++i) {
172 const CPU cpu = cpus [i];
173 const CACHE cache = caches [i];
174 const CONNECTION con_cpu_cache_addr = cons_cpu_cache_addr [i];
175 const CONNECTION con_cpu_cache_data = cons_cpu_cache_data [i];
176 const CONNECTION con_cache_bus_shared = cons_cache_bus_shared [i];
177 const CONNECTION con_cache_bus_addr = cons_cache_bus_addr [i];
178 const CONNECTION con_cache_bus_data = cons_cache_bus_data [i];
179
180 bool is_addr = false;
181 bool is_data = false;
182
183 con = con_cache_bus_shared;
184 if (con->transaction_just_finished) {
185 switch (con->transaction_just_finished_state) {
186 case CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD: {
187 switch (con_cache_bus_addr->transaction_state & CONNECTION_TRANSACTION_STATE_DIRECTION_MASK) {
188 case CONNECTION_TRANSACTION_DIRECTION_FROM_TO: {
189 bus_link_connection (shared_bus, con);
190 } break;
191 case CONNECTION_TRANSACTION_DIRECTION_TO_FROM: {
192 cons_cache_bus_shared[addr_bus->reserved_connection]->transaction_pending = true;
193 connection_end_transaction (con_cache_bus_shared);
194 } break;
195 }
196 } break;
197 case CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING: {
198 if ((con_cache_bus_addr->transaction_state &
199 CONNECTION_TRANSACTION_STATE_DIRECTION_MASK) ==
200 CONNECTION_TRANSACTION_DIRECTION_FROM_TO) {
201 bus_unlink_connection (shared_bus);
202 }
203 CONNECTION_CLEAR_TRANSACTION(con);
204 } break;
205 case CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD: {
206 switch (CONNECTION_TRANSACTION_STATE_DIRECTION(con_cache_bus_addr)) {
207 case CONNECTION_TRANSACTION_DIRECTION_FROM_TO: {
208 bus_unlink_connection (shared_bus);
209 if (!connection_is_transaction_ongoing (con_cache_bus_data)) {
210 cache->addr_targets = 1 << CONNECTION_MEMORY;
211 cache->addr_value = con_cpu_cache_addr->transaction_value;
212 con_cache_bus_addr->transaction_pending = true;
213 if (con_cache_bus_shared->transaction_value)
214 cache->next_forward = true;
215 }
216 } break;
217 case CONNECTION_TRANSACTION_DIRECTION_TO_FROM: {
218 u8 addr = con_cache_bus_addr->transaction_value;
219 CACHE_LINE line = cache_get (cache, addr, true);
220 if (line) line->state = con_cache_bus_shared->transaction_value;
221 } break;
222 }
223 } break;
224 case CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING: {
225 CONNECTION_CLEAR_TRANSACTION(con);
226 if (!connection_is_transaction_ongoing (con_cache_bus_data))
227 connection_end_transaction (con_cache_bus_addr);
228 } break;
229 default: break;
230 }
231 }
232
233 con = con_cache_bus_addr;
234 if (con->transaction_just_finished) {
235 switch (con->transaction_just_finished_state) {
236 case CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD: {
237 bus_link_connection (addr_bus, con);
238 } break;
239 case CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING: {
240 bus_unlink_connection (addr_bus);
241 FREE_BUS(addr_bus);
242 CONNECTION_CLEAR_TRANSACTION(con);
243 } break;
244 case CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD: {
245 if (con_cache_bus_shared->transaction_just_finished)
246 break;
247
248 CACHE_LINE line = cache_get (cache, con_cache_bus_addr->transaction_value, true);
249 enum cache_line_state state = line ? line->state : CACHE_LINE_STATE_INVALID;
250 if (!line) {
251 cache->highlighted_pending = cache->highlighted;
252 cache->highlighted = CPU_COUNT;
253 }
254 if (line &&
255 connection_is_transaction_ongoing (cons_cpu_cache_data[*cache_locking_busses])) {
256 switch (line->state) {
257 case CACHE_LINE_STATE_EXCLUSIVE:
258 case CACHE_LINE_STATE_FORWARD:
259 case CACHE_LINE_STATE_MODIFIED:
260 data_bus->reserved_connection = i;
261 data_bus->connection_targets = 1 << addr_bus->reserved_connection;
262 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_data, line->data);
263 /* fallthrough */
264 case CACHE_LINE_STATE_SHARED:
265 line->state = CACHE_LINE_STATE_INVALID;
266 break;
267 default: break;
268 }
269 } else {
270 switch (state) {
271 case CACHE_LINE_STATE_MODIFIED: {
272 data_bus->reserved_connection = i;
273 data_bus->connection_targets = 1 << addr_bus->reserved_connection |
274 1 << CONNECTION_MEMORY;
275 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_data, line->data);
276 cache_set (cache, line, line->addr, line->data, CACHE_LINE_STATE_SHARED, false);
277 } break;
278 case CACHE_LINE_STATE_EXCLUSIVE: {
279 data_bus->reserved_connection = i;
280 data_bus->connection_targets = 1 << addr_bus->reserved_connection;
281 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_data, line->data);
282 cache_set (cache, line, line->addr, line->data, CACHE_LINE_STATE_SHARED, false);
283 } break;
284 case CACHE_LINE_STATE_SHARED: {
285 } break;
286 case CACHE_LINE_STATE_FORWARD: {
287 data_bus->reserved_connection = i;
288 data_bus->connection_targets = 1 << addr_bus->reserved_connection;
289 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_data, line->data);
290 cache_set (cache, line, line->addr, line->data, CACHE_LINE_STATE_SHARED, false);
291 } break;
292 default: break;
293 }
294 }
295 con_cache_bus_shared->transaction_pending = true;
296 } break;
297 case CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING: {
298 CONNECTION_CLEAR_TRANSACTION(con);
299 connection_end_transaction (con_cache_bus_data);
300 cache->highlighted = cache->highlighted_pending;
301 cache->highlighted_pending = CACHE_LINE_COUNT;
302 } break;
303 default: break;
304 }
305 }
306
307 if (con_cache_bus_shared->transaction_pending &&
308 addr_bus->reserved_connection != i &&
309 *cache_locking_busses != i) {
310 // shared_bus.reserved_connection = i;
311 shared_bus->connection_targets = 1 << addr_bus->reserved_connection;
312 bool has = cache->highlighted != CACHE_LINE_COUNT &&
313 cache->lines[cache->highlighted].state != CACHE_LINE_STATE_INVALID;
314 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_shared, has << i);
315 con_cache_bus_shared->transaction_pending = false;
316 }
317
318 con = con_cache_bus_data;
319 if (con->transaction_just_finished) {
320 switch (con->transaction_just_finished_state) {
321 case CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD: {
322 if (cache->lines[cache->highlighted].state == CACHE_LINE_STATE_MODIFIED)
323 CONNECTION_START_TRANSACTION_TO_FROM(con_memory_bus_addr, cache->lines[cache->highlighted].addr);
324 bus_link_connection (data_bus, con);
325 } break;
326 case CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING: {
327 bus_unlink_connection (data_bus);
328 CONNECTION_CLEAR_TRANSACTION(con);
329 } break;
330 case CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD: {
331 if (connection_is_transaction_ongoing (con_cpu_cache_data)) { // RWITM finished
332 cache_set (cache, NULL,
333 con_cpu_cache_addr->transaction_value,
334 con_cpu_cache_data->transaction_value,
335 CACHE_LINE_STATE_MODIFIED, true);
336 con_cache_bus_addr->transaction_pending = false;
337 connection_end_transaction (con_cpu_cache_addr);
338 connection_end_transaction (con_cpu_cache_data);
339 } else {
340 enum cache_line_state next_state = data_bus->reserved_connection == CONNECTION_MEMORY && !cache->next_forward
341 ? CACHE_LINE_STATE_EXCLUSIVE
342 : CACHE_LINE_STATE_FORWARD;
343 cache->next_forward = false;
344 cache_set (cache, NULL,
345 con_cache_bus_addr->transaction_value,
346 con_cache_bus_data->transaction_value,
347 next_state, true);
348 CONNECTION_START_TRANSACTION_TO_FROM(con_cpu_cache_data,
349 con->transaction_value);
350 }
351 } break;
352 case CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING: {
353 if (!connection_is_transaction_complete (con_cpu_cache_data)) {
354 cache->highlighted = cache->highlighted_pending;
355 cache->highlighted_pending = CACHE_LINE_COUNT;
356 }
357 FREE_BUS(data_bus);
358 CONNECTION_CLEAR_TRANSACTION(con);
359 } break;
360 default: break;
361 }
362 }
363
364 con = con_cpu_cache_addr;
365 if (con->transaction_just_finished) {
366 switch (con->transaction_just_finished_state) {
367 case CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD: {
368 is_addr = true;
369 } break;
370 case CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING: {
371 cache->highlighted = cache->highlighted_pending;
372 cache->highlighted_pending = CACHE_LINE_COUNT;
373 if (CONNECTION_TRANSACTION_STATE_DIRECTION(con_cache_bus_addr) ==
374 CONNECTION_TRANSACTION_DIRECTION_FROM_TO) {
375 connection_end_transaction (con_cache_bus_addr);
376 }
377 connection_end_transaction (con_cpu_cache_data);
378 CONNECTION_CLEAR_TRANSACTION(con);
379 } break;
380 default: break;
381 }
382 }
383
384 con = con_cpu_cache_data;
385 if (con->transaction_just_finished) {
386 switch (con->transaction_just_finished_state) {
387 case CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD: {
388 is_data = true;
389 } break;
390 case CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING: {
391 connection_end_transaction (con_cache_bus_addr);
392 connection_end_transaction (con_cache_bus_shared);
393 cpu->highlighted = 3*MEMORY_SIZE;
394 *cache_locking_busses = CPU_COUNT;
395 CONNECTION_CLEAR_TRANSACTION(con);
396 } break;
397 case CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD: {
398 connection_end_transaction (con_cpu_cache_addr);
399 } break;
400 case CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING: {
401 cache->highlighted = cache->highlighted_pending;
402 cache->highlighted_pending = CACHE_LINE_COUNT;
403 CONNECTION_CLEAR_TRANSACTION(con);
404 if (cpu->highlighted % 3 == 1) {
405 CONNECTION_START_TRANSACTION_FROM_TO(con_cpu_cache_addr, con_cpu_cache_addr->transaction_value);
406 CONNECTION_START_TRANSACTION_FROM_TO(con_cpu_cache_data, con_cpu_cache_data->transaction_value + 1);
407 } else {
408 cpu->highlighted = 3*MEMORY_SIZE;
409 }
410 *cache_locking_busses = CPU_COUNT;
411 } break;
412 default: break;
413 }
414 }
415
416 // Process READ/WRITE request if any
417 if (is_addr || cache->continue_addr) {
418 cache->continue_addr = false;
419 u8 addr = con_cpu_cache_addr->transaction_value;
420 CACHE_LINE line = cache_get (cache, addr, true);
421 CACHE_LINE to_replace = cache_to_replace (cache, addr);
422 if (!line && !cache->copy_back && to_replace && to_replace->state == CACHE_LINE_STATE_MODIFIED) {
423 cache->invalidate_others = true;
424
425 cache->addr_targets = ~(1 << i) & CONNECTION_CACHES | 1 << CONNECTION_MEMORY;
426 cache->addr_value = to_replace->addr;
427 con_cache_bus_addr->transaction_pending = true;
428
429 cache->data_targets = 1 << CONNECTION_MEMORY;
430 cache->data_value = to_replace->data;
431 con_cache_bus_data->transaction_pending = true;
432
433 cache->copy_back = true;
434 } else {
435 cache->copy_back = false;
436 enum cache_line_state state = line ? line->state : CACHE_LINE_STATE_INVALID;
437 if (!is_data || cache->continue_data) { // Process CPU READ
438 cache->continue_data = false;
439 switch (state) {
440 case CACHE_LINE_STATE_MODIFIED:
441 case CACHE_LINE_STATE_EXCLUSIVE:
442 case CACHE_LINE_STATE_SHARED:
443 case CACHE_LINE_STATE_FORWARD: {
444 cache->data_targets = 1 << *cache_locking_busses;
445 CONNECTION_START_TRANSACTION_TO_FROM(con_cpu_cache_data, line->data);
446 } break;
447 case CACHE_LINE_STATE_INVALID: {
448 cache->addr_targets = ~(1 << i) & CONNECTION_CACHES;
449 cache->addr_value = con_cpu_cache_addr->transaction_value;
450 con_cache_bus_addr->transaction_pending = true;
451 } break;
452 default: break;
453 }
454 } else { // Process CPU WRITE
455 u8 data = con_cpu_cache_data->transaction_value;
456 switch (state) {
457 case CACHE_LINE_STATE_EXCLUSIVE: {
458 cache_set (cache, line, addr, data, CACHE_LINE_STATE_MODIFIED, false);
459 connection_end_transaction (con_cpu_cache_addr);
460 connection_end_transaction (con_cpu_cache_data);
461 } break;
462 case CACHE_LINE_STATE_MODIFIED: {
463 cache_set (cache, line, addr, data, CACHE_LINE_STATE_MODIFIED, false);
464 connection_end_transaction (con_cpu_cache_addr);
465 connection_end_transaction (con_cpu_cache_data);
466 } break;
467 case CACHE_LINE_STATE_FORWARD:
468 case CACHE_LINE_STATE_SHARED: {
469 cache_set (cache, line, addr, data, CACHE_LINE_STATE_MODIFIED, false);
470 cache->invalidate_others = true;
471
472 cache->addr_targets = ~(1 << i) & CONNECTION_CACHES;
473 cache->addr_value = con_cpu_cache_addr->transaction_value;
474 con_cache_bus_addr->transaction_pending = true;
475 } break;
476 case CACHE_LINE_STATE_INVALID: {
477 cache->addr_targets = ~(1 << i) & CONNECTION_CACHES;
478 cache->addr_value = con_cpu_cache_addr->transaction_value;
479 con_cache_bus_addr->transaction_pending = true;
480 } break;
481 default:
482 break;
483 }
484 }
485 }
486 }
487
488 CACHE_LINE line = NULL;
489 for (int i = 0; i < CACHE_LINE_COUNT; ++i) {
490 if (cache->lines[i].state != CACHE_LINE_STATE_INVALID &&
491 cache->lines[i].addr == cache->addr_value) {
492 line = &cache->lines[i];
493 }
494 }
495 if (con_cache_bus_addr->transaction_pending &&
496 con_cache_bus_data->transaction_pending &&
497 IS_BUS_FREE(addr_bus) &&
498 IS_BUS_FREE(data_bus) &&
499 !line) {
500 // cache_set (cache, line, cache->addr_value, cache->data_value, CACHE_LINE_STATE_MODIFIED);
501
502 *cache_locking_busses = i;
503 *bus_cycles += 1;
504 addr_bus->connection_targets = cache->addr_targets;
505 addr_bus->reserved_connection = i;
506 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_addr,
507 cache->addr_value);
508 con_cache_bus_addr->transaction_pending = false;
509
510 if (cache->invalidate_others) {
511 shared_bus->reserved_connection = i;
512 shared_bus->connection_targets = ~(1 << i) & CONNECTION_CACHES;
513 CONNECTION_START_TRANSACTION_FROM_TO (con_cache_bus_shared,
514 CACHE_LINE_STATE_INVALID);
515 con_cache_bus_shared->transaction_pending = false;
516 }
517 } else if (con_cache_bus_addr->transaction_pending &&
518 IS_BUS_FREE(addr_bus) &&
519 IS_BUS_FREE(data_bus) &&
520 !connection_is_transaction_ongoing (con_cache_bus_addr) &&
521 !connection_is_transaction_ongoing (con_cache_bus_data) &&
522 (*cache_locking_busses == CPU_COUNT ||
523 *cache_locking_busses == i)) {
524 *cache_locking_busses = i;
525 *bus_cycles += 1;
526 addr_bus->connection_targets = cache->addr_targets;
527 addr_bus->reserved_connection = i;
528 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_addr,
529 cache->addr_value);
530 con_cache_bus_addr->transaction_pending = false;
531
532 if (cache->invalidate_others) {
533 shared_bus->reserved_connection = i;
534 shared_bus->connection_targets = ~(1 << i) & CONNECTION_CACHES;
535 CONNECTION_START_TRANSACTION_FROM_TO (con_cache_bus_shared,
536 CACHE_LINE_STATE_INVALID);
537 cache->invalidate_others = false;
538 /* connection_end_transaction (con_cpu_cache_addr); */
539 /* connection_end_transaction (con_cpu_cache_data); */
540 }
541
542 if (con_cache_bus_data->transaction_pending &&
543 IS_BUS_FREE(data_bus)) {
544 data_bus->connection_targets = cache->data_targets;
545 data_bus->reserved_connection = i;
546 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_data,
547 cache->data_value);
548 con_cache_bus_data->transaction_pending = false;
549
550 shared_bus->reserved_connection = i;
551 shared_bus->connection_targets = ~(1 << i) & CONNECTION_CACHES;
552 CONNECTION_START_TRANSACTION_FROM_TO (con_cache_bus_shared,
553 CACHE_LINE_STATE_INVALID);
554 con_cache_bus_shared->transaction_pending = false;
555
556 if (cache->invalidate_others && line)
557 cache_set (cache, line, cache->addr_value, cache->data_value, CACHE_LINE_STATE_EXCLUSIVE, false);
558
559 cache->invalidate_others = false;
560 }
561 } else if (con_cache_bus_data->transaction_pending &&
562 IS_BUS_FREE(data_bus) &&
563 (*cache_locking_busses == CPU_COUNT ||
564 *cache_locking_busses == i)) {
565 *cache_locking_busses = i;
566 *bus_cycles += 1;
567 data_bus->connection_targets = cache->data_targets;
568 data_bus->reserved_connection = i;
569 CONNECTION_START_TRANSACTION_FROM_TO(con_cache_bus_data,
570 cache->data_value);
571 con_cache_bus_data->transaction_pending = false;
572 }
573 }
574
575 for (int i = 0; i < CPU_COUNT; ++i) {
576 if (cons_cache_bus_shared[i]->transaction_pending &&
577 addr_bus->reserved_connection == i) {
578 bus_link_connections (shared_bus, cons_cache_bus_shared); // BUG(cmmm): started twice on double READ
579 cons_cache_bus_shared[i]->transaction_pending = false;
580 }
581 }
582
583 con = con_memory_bus_addr;
584 if (con->transaction_just_finished) {
585 switch (con->transaction_just_finished_state) {
586 case CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD: {
587 int addr = con->transaction_value;
588 memory->highlighted = addr;
589 if (!connection_is_transaction_ongoing (con_memory_bus_data)) {
590 data_bus->reserved_connection = CONNECTION_MEMORY;
591 CONNECTION_START_TRANSACTION_FROM_TO(con_memory_bus_data, memory->entries[addr]);
592 } else if (connection_is_transaction_direction_from_to (cons_cache_bus_data[addr_bus->reserved_connection])) {
593 if (caches[addr_bus->reserved_connection]->copy_back) {
594 caches[addr_bus->reserved_connection]->continue_addr = connection_is_transaction_ongoing (cons_cpu_cache_addr[addr_bus->reserved_connection]);
595 caches[addr_bus->reserved_connection]->continue_data = connection_is_transaction_ongoing (cons_cpu_cache_data[addr_bus->reserved_connection]);
596 }
597 }
598 } break;
599 case CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING: {
600 FREE_BUS(addr_bus);
601 memory->highlighted = MEMORY_SIZE;
602 connection_end_transaction (con_memory_bus_data);
603 CONNECTION_CLEAR_TRANSACTION(con);
604 } break;
605 default: break;
606 }
607 }
608
609 con = con_memory_bus_data;
610 if (con->transaction_just_finished) {
611 switch (con->transaction_just_finished_state) {
612 case CONNECTION_TRANSACTION_STATE_FROM_TO_FORWARD: {
613 data_bus->connection_targets = 1 << addr_bus->reserved_connection;
614 bus_link_connection (data_bus, con_memory_bus_data);
615 } break;
616 case CONNECTION_TRANSACTION_STATE_FROM_TO_TRAILING: {
617 bus_unlink_connection (data_bus);
618 CONNECTION_CLEAR_TRANSACTION(con);
619 } break;
620 case CONNECTION_TRANSACTION_STATE_TO_FROM_FORWARD: {
621 memory->entries[con_memory_bus_addr->transaction_value] = con->transaction_value;
622 if (connection_is_transaction_ongoing (cons_cpu_cache_data[data_bus->reserved_connection]) &&
623 connection_is_transaction_direction_to_from (cons_cpu_cache_data[data_bus->reserved_connection])) {
624 connection_end_transaction (cons_cpu_cache_addr[addr_bus->reserved_connection]);
625 connection_end_transaction (cons_cpu_cache_data[data_bus->reserved_connection]);
626 } else {
627 connection_end_transaction (cons_cache_bus_shared[data_bus->reserved_connection]);
628 connection_end_transaction (cons_cache_bus_addr[data_bus->reserved_connection]);
629 connection_end_transaction (cons_cache_bus_data[data_bus->reserved_connection]);
630 }
631 } break;
632 case CONNECTION_TRANSACTION_STATE_TO_FROM_TRAILING: {
633 FREE_BUS(data_bus);
634 CONNECTION_CLEAR_TRANSACTION(con);
635 } break;
636 default: break;
637 }
638 }
639
640 // Save state
641 if (!is_paused && transaction_proggressed) {
642 if (seconds_since_last_tick >= TICK_SECONDS) {
643 seconds_since_last_tick = 0;
644 save_state ();
645 } else
646 seconds_since_last_tick += GetFrameTime ();
647 }
648}
649
650static inline void
651draw (void)
652{
653 BeginDrawing ();
654 ClearBackground (COLOR_BACKGROUND);
655 BeginMode2D (camera);
656
657 draw_bus (data_bus);
658 draw_bus (addr_bus);
659 draw_bus (shared_bus);
660 for (int i = 0; i < CPU_COUNT; ++i) {
661 draw_cache (caches[i]);
662 draw_cpu (cpus[i]);
663 }
664 draw_memory (memory);
665
666 EndMode2D();
667
668 if (is_paused) {
669 DrawRectangle ( 5, 5, 10, 40, GRAY);
670 DrawRectangle (25, 5, 10, 40, GRAY);
671
672 // draw tick
673 char *tick_text;
674 asprintf (&tick_text, "%lu", current_tick);
675 DrawTextEx (font, tick_text, (Vector2) { 5, 43 }, FONT_SIZE, TEXT_SPACING, GRAY);
676 free (tick_text);
677 }
678
679 char *bus_cycles_text;
680 asprintf (&bus_cycles_text, "BUS CYCLES: %d", *bus_cycles);
681 float bus_cycles_text_width = MeasureTextEx (font, bus_cycles_text, FONT_SIZE, TEXT_SPACING).x;
682 Color bus_cycles_text_color = IS_BUS_FREE(data_bus) && IS_BUS_FREE(addr_bus) ? COLOR_TEXT : COLOR_DATA;
683 DrawTextEx (font, bus_cycles_text, (Vector2) { GetScreenWidth ()/2 - bus_cycles_text_width/2, 0 }, FONT_SIZE, TEXT_SPACING, bus_cycles_text_color);
684 free (bus_cycles_text);
685
686 const char *info_text = "Press R to reset...";
687 float info_text_width = MeasureTextEx (font, info_text, FONT_SIZE, TEXT_SPACING).x;
688 DrawTextEx (font, info_text, (Vector2) { GetScreenWidth () - info_text_width, 0 }, FONT_SIZE, TEXT_SPACING, COLOR_TEXT);
689
690 // DrawFPS (2, 0);
691 EndDrawing ();
692}
693
694int
695main (void)
696{
697 startup ();
698 while (!WindowShouldClose ()) {
699 handle_input ();
700 update ();
701 draw ();
702 } shutdown ();
703
704 return EXIT_SUCCESS;
705}
diff --git a/src/states.c b/src/states.c
new file mode 100644
index 0000000..3bf80ca
--- /dev/null
+++ b/src/states.c
@@ -0,0 +1,75 @@
1#include "states.h"
2#include <string.h>
3
4extern bool is_paused;
5
6struct state states[MAX_TICKS];
7size_t current_tick = 0;
8size_t last_tick = 0;
9
10void
11init_state (void)
12{
13 *cache_locking_busses = CPU_COUNT;
14 *bus_cycles = 0;
15 init_bus (data_bus, cons_cache_bus_data, con_memory_bus_data, 0*BUS_SPACING + BUS_THICKNESS, 1.00, COLOR_DATA, "DATA BUS");
16 init_bus (addr_bus, cons_cache_bus_addr, con_memory_bus_addr, 1*BUS_SPACING + BUS_THICKNESS, 1.00, COLOR_ADDR, "ADDRESS BUS");
17 init_bus (shared_bus, cons_cache_bus_shared, NULL, 2*BUS_SPACING + BUS_THICKNESS, 0.75, COLOR_SHARED, "SHARED BUS");
18 for (int i = 0; i < CPU_COUNT; ++i) {
19 init_cache (caches[i], shared_bus);
20 init_cpu (cpus[i], caches[i]);
21 }
22 init_memory (memory, cpus[0]);
23}
24
25void
26reset_state (void)
27{
28 set_state (0);
29 init_state ();
30 is_paused = false;
31}
32
33void
34set_state (size_t tick)
35{
36 cache_locking_busses = &states[tick].cache_locking_busses;
37 bus_cycles = &states[tick].bus_cycles;
38 data_bus = &states[tick].data_bus;
39 addr_bus = &states[tick].addr_bus;
40 shared_bus = &states[tick].shared_bus;
41 memory = &states[tick].memory;
42 for (int i = 0; i < CPU_COUNT; ++i) {
43 caches [i] = &states[tick].caches [i];
44 cpus [i] = &states[tick].cpus [i];
45 cons_cpu_cache_addr [i] = &states[tick].cons_cpu_cache_addr [i];
46 cons_cpu_cache_data [i] = &states[tick].cons_cpu_cache_data [i];
47 cons_cache_bus_shared [i] = &states[tick].cons_cache_bus_shared [i];
48 cons_cache_bus_addr [i] = &states[tick].cons_cache_bus_addr [i];
49 cons_cache_bus_data [i] = &states[tick].cons_cache_bus_data [i];
50 }
51 con_memory_bus_addr = &states[tick].con_memory_bus_addr;
52 con_memory_bus_data = &states[tick].con_memory_bus_data;
53
54 current_tick = tick;
55}
56
57void
58save_state (void)
59{
60 memcpy (&states[current_tick + 1],
61 &states[current_tick + 0],
62 sizeof (struct state));
63 set_state (current_tick + 1);
64 last_tick = current_tick;
65
66 // re-link bus connections
67 for (int i = 0; i < CPU_COUNT; ++i) {
68 states[current_tick] . data_bus.cache_connections [i] = &states[current_tick].cons_cache_bus_data [i];
69 states[current_tick] . addr_bus.cache_connections [i] = &states[current_tick].cons_cache_bus_addr [i];
70 states[current_tick] . shared_bus.cache_connections [i] = &states[current_tick].cons_cache_bus_shared [i];
71 }
72 states[current_tick] . data_bus.memory_connection = &states[current_tick].con_memory_bus_data;
73 states[current_tick] . addr_bus.memory_connection = &states[current_tick].con_memory_bus_addr;
74 states[current_tick] . shared_bus.memory_connection = NULL;
75}
diff --git a/src/states.h b/src/states.h
new file mode 100644
index 0000000..4baf72c
--- /dev/null
+++ b/src/states.h
@@ -0,0 +1,39 @@
1#ifndef INCLUDED_STATES_H
2#define INCLUDED_STATES_H
3
4#include <stdlib.h>
5#include "config.h"
6#include "busses.h"
7#include "caches.h"
8#include "cpus.h"
9#include "memory.h"
10#include "connections.h"
11
12struct state {
13 int cache_locking_busses;
14 int bus_cycles;
15 struct bus data_bus;
16 struct bus addr_bus;
17 struct bus shared_bus;
18 struct cache caches [CPU_COUNT];
19 struct cpu cpus [CPU_COUNT];
20 struct connection cons_cpu_cache_addr [CPU_COUNT];
21 struct connection cons_cpu_cache_data [CPU_COUNT];
22 struct connection cons_cache_bus_shared [CPU_COUNT];
23 struct connection cons_cache_bus_addr [CPU_COUNT];
24 struct connection cons_cache_bus_data [CPU_COUNT];
25 struct connection con_memory_bus_addr;
26 struct connection con_memory_bus_data;
27 struct memory memory;
28};
29
30extern struct state states[MAX_TICKS];
31extern size_t current_tick;
32extern size_t last_tick;
33
34void set_state (size_t tick);
35void reset_state (void);
36void init_state (void);
37void save_state (void);
38
39#endif
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..56c33fb
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,10 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <inttypes.h>
5
6#define PACKED __attribute__((__packed__))
7
8typedef uint8_t u8;
9
10#endif