-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel.c
141 lines (117 loc) · 2.82 KB
/
kernel.c
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <stdio.h>
#include <stdlib.h>
#include "shell.h"
#include "pcb.h"
#include "kernel.h"
#include "ram.h"
#include "cpu.h"
#include "memorymanager.h"
#include "constants.h"
int pageFaultInterrupt(PCB *pcb);
int myinit(PCB *pcb);
int scheduler();
void addToReady(PCB *pcb);
void moveRqHeadToEnd();
void removeSwapFile(int _pid);
void freePCB();
PCB* head = NULL;
PCB* tail = NULL;
int myinit(PCB *pcb){
int _f = pcb->pageTable[0];
pcb->PC = findFrameIdxInRAM(_f);
addToReady(pcb);
return 0;
}
void removeSwapFile(int _pid){
char command[100];
snprintf(command, 99, "rm -rf BackingStore/swap-%d.txt", _pid);
system(command);
}
PCB* peekHead(){
return head;
}
int scheduler(){
while(head != NULL) {
while(isCPUAvailable() == -1) ;
int _ip = head->PC + head->PC_offset;
setCPU_IP(_ip);
int _err = 0;
if(head->PC_offset == PAGE_LENGTH - 1) {
_err = run(CPU_QUANTA-1);
++head->PC_offset;
}
else {
_err = run(CPU_QUANTA);
head->PC_offset+=2;
}
if(_err == -1 || head->PC_offset == PAGE_LENGTH)
pageFaultInterrupt(head);
if(head->PC_offset < PAGE_LENGTH) {
if(head->next == NULL) continue;
moveRqHeadToEnd();
} else {
//done.
PCB* newHead = head->next;
free(head);
head = newHead;
}
}
return 0;
}
int pageFaultInterrupt(PCB* pcb){
++pcb->PC_page;
if(pcb->PC_page >= pcb->pages_max) {
removeSwapFile(pcb->pid);
return -1;
}
if(pcb->pageTable[pcb->PC_page] == -1) {
char filename[100];
snprintf(filename, 99, "BackingStore/swap-%d.txt", pcb->pid);
FILE *fp = fopen(filename, "rt");
findFrameAndLoadPage(pcb, fp, pcb->PC_page);
fclose(fp);
}
pcb->PC = findFrameIdxInRAM(pcb->pageTable[pcb->PC_page]);
pcb->PC_offset = 0;
return 0;
}
void moveRqHeadToEnd(){
PCB* newHead = head->next;
head->next = NULL;
tail->next = head;
tail = tail->next;
tail->next = NULL;
head = newHead;
}
void addToReady(PCB* pcb){
if(pcb == NULL) return;
if(head == NULL) {
head = pcb;
tail = pcb;
} else if(head->next == NULL){
head->next = pcb;
tail = pcb;
} else {
tail->next = pcb;
tail = pcb;
}
}
void freePCB(){
while(head!=NULL){
PCB* next = head->next;
free(head);
head = next;
}
}
int kernel(){
return shellUI();
}
void boot(){
//prepare backing store
char *_command = "rm -rf BackingStore && mkdir BackingStore";
system(_command);
}
int main(){
boot();
return kernel();
}