-
Notifications
You must be signed in to change notification settings - Fork 0
/
pager.c
97 lines (77 loc) · 2.72 KB
/
pager.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
//
// Created by Colin Peppler on 1/9/20.
//
#include "pager.h"
Pager *pager_open(const char *filename) {
int file_descriptor = open(filename,
O_RDWR | // Read/Write mode
O_CREAT, // Create file if it doesn't exist already
S_IWUSR | // User write permission
S_IRUSR // User read permission
);
if (file_descriptor == -1) {
printf("Unable to open file\n");
exit(EXIT_FAILURE);
}
off_t file_length = lseek(file_descriptor, 0, SEEK_END);
Pager *pager = malloc(sizeof(Pager));
pager->file_descriptor = file_descriptor;
pager->file_length = file_length;
pager->num_pages = file_length / PAGE_SIZE;
if (file_length % PAGE_SIZE != 0) {
printf("Db file is not a whole number of pages. Corrupt file.\n");
exit(EXIT_FAILURE);
}
for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++) {
pager->pages[i] = NULL;
}
return pager;
}
void pager_flush(Pager *pager, uint32_t page_num) {
if (pager->pages[page_num] == NULL) {
printf("Tried to flush null pager\n");
exit(EXIT_FAILURE);
}
off_t offset = lseek(pager->file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
if (offset == -1) {
printf("Error soeeking: %d\n", errno);
exit(EXIT_FAILURE);
}
ssize_t bytes_written = write(pager->file_descriptor, pager->pages[page_num], PAGE_SIZE);
if (bytes_written == -1) {
printf("Error writing: %d\n", errno);
exit(EXIT_FAILURE);
}
}
void *get_page(Pager *pager, uint32_t page_num) {
if (page_num > TABLE_MAX_PAGES) {
printf("Tried to fetch page number out of bounds. %d > %d\n", page_num, TABLE_MAX_PAGES);
exit(EXIT_FAILURE);
}
// Cache miss
if (pager->pages[page_num] == NULL) {
// Allocate memory and load from file.
void *page = malloc(PAGE_SIZE);
uint32_t num_pages = pager->file_length / PAGE_SIZE;
// EDGE CASE: last page is a partial page
if (pager->file_length % PAGE_SIZE) {
num_pages += 1;
}
if (page_num <= num_pages) {
lseek(pager->file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
ssize_t bytes_read = read(pager->file_descriptor, page, PAGE_SIZE);
if (bytes_read == -1) {
printf("Error reading file: %d\n", errno);
exit(EXIT_FAILURE);
}
}
pager->pages[page_num] = page;
if (page_num >= pager->num_pages) {
pager->num_pages = page_num + 1;
}
}
return pager->pages[page_num];
}
uint32_t get_unused_page_num(Pager *pager) {
return pager->num_pages;
}