// Jack Sangdahl
// CSCI3753 SP24
// PA8 Predict
#include "../common/simulator.h"
#include <stdbool.h>
#include <string.h>
static const float transition[MAXPROCESSES][MAXPROCPAGES] = {
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0.93, 0, 0, 0, 0, 0, 0.07, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0.15, 0, 0, 0, 0, 0, 0.85, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0.04, 0, 0, 0, 0, 0, 0, 0, 0.57, 0, 0, 0.39, 0, 0, 0, 0, 0, 0, 0, 0},
{0.81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.12, 0, 0, 0, 0, 0, 0.08, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
{0.14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.86, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0.29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.71, 0, 0, 0}};
void pageit(Pentry q[MAXPROCESSES]) {
static bool initialised = false;
static int prev[MAXPROCESSES], tick = 1;
static int row_sum[MAXPROCESSES][MAXPROCPAGES];
static int prediction[MAXPROCESSES][MAXPROCPAGES][MAXPROCPAGES];
bool swap[MAXPROCPAGES] = {false};
if (!initialised) {
for (int i = 0; i < MAXPROCESSES; i++)
prev[i] = -1;
memset(row_sum, 0, sizeof(row_sum));
memset(prediction, 0, sizeof(prediction));
initialised = true;
}
for (int proc = 0; proc < MAXPROCESSES; proc++)
if (q[proc].active) {
int curr = q[proc].pc / PAGESIZE;
if (prev[proc] != -1 && prev[proc] != curr) {
row_sum[proc][prev[proc]]++;
prediction[proc][prev[proc]][curr]++;
}
prev[proc] = curr;
swap[curr] = true;
if (tick > PAGEWAIT && row_sum[proc][curr]) {
for (int i = 0; i < MAXPROCPAGES; i++)
if ((double)prediction[proc][curr][i] / row_sum[proc][curr]) {
swap[i] = true;
if (row_sum[proc][i])
for (int j = 0; j < MAXPROCPAGES; j++)
if ((double)prediction[proc][i][j] / row_sum[proc][i])
swap[j] = true;
}
} else {
for (int i = 0; i < MAXPROCPAGES; i++)
if (transition[curr][i]) {
swap[i] = true;
if (transition[curr][i] > 0.9)
for (int j = 0; j < MAXPROCPAGES; j++)
if (transition[i][j] * transition[curr][i] > 0.025)
swap[j] = true;
}
}
for (int i = 0; i < q[proc].npages; i++)
if (!swap[i] && q[proc].pages[i])
pageout(proc, i);
if (!q[proc].pages[curr])
pagein(proc, curr);
for (int i = 0; i < q[proc].npages; i++)
if (swap[i] && !q[proc].pages[i])
pagein(proc, i);
memset(swap, false, sizeof(swap));
}
tick++;
}