Clean mmap.c a bit

This commit is contained in:
augustin64 2024-03-26 17:40:15 +01:00
parent 0f6830b34d
commit ea10ad5df1

View File

@ -3,6 +3,8 @@
#include <string.h>
#include <errno.h>
#define CHECK_FERROR(f) { if (ferror(f)) {fprintf(stderr, "IO Error"); exit(1);} }
#include "mmap.h"
struct MMap* mmap_init(){
@ -70,31 +72,25 @@ int check_page_alloc(struct MMap *mmap) {
int move_to_swap(struct MMap *mmap, struct PageInfo *page) {
int key = -1;
fseek(mmap->swap, 0, SEEK_SET);
if( ferror(mmap->swap) ) {
return -1;
}
CHECK_FERROR(mmap->swap);
for (int i = 0; i < 100*sizeof(int); i+=sizeof(int)) {
fread(&key, sizeof(int), 1, mmap->swap);
if( ferror(mmap->swap) ) {
return -1;
}
CHECK_FERROR(mmap->swap);
if (key == -1) {
fseek(mmap->swap, i, SEEK_SET);
if( ferror(mmap->swap) ) {
return -1;
}
CHECK_FERROR(mmap->swap);
fwrite(&page->key, sizeof(int), 1, mmap->swap);
if( ferror(mmap->swap) ) {
return -1;
}
CHECK_FERROR(mmap->swap);
fseek(mmap->swap, 100*sizeof(int) + (i/sizeof(int))*4096, SEEK_SET);
if( ferror(mmap->swap) ) {
return -1;
}
CHECK_FERROR(mmap->swap);
fwrite(page->data, 4096, 1, mmap->swap);
if( ferror(mmap->swap) ) {
return -1;
}
CHECK_FERROR(mmap->swap);
return 0;
}
}
@ -104,36 +100,29 @@ int move_to_swap(struct MMap *mmap, struct PageInfo *page) {
struct PageInfo* read_from_swap(struct MMap* mmap, struct PageInfo *page) {
int key = -1;
fseek(mmap->swap, 0, SEEK_SET);
if( ferror(mmap->swap) ) {
return NULL;
}
CHECK_FERROR(mmap->swap);
for (int i = 0; i < 100*sizeof(int); i+=sizeof(int)) {
int ret = fread(&key, sizeof(int), 1, mmap->swap);
if( ferror(mmap->swap) ) {
return NULL;
}
if (key == page->key) {
fseek(mmap->swap, 100*sizeof(int) + (i/sizeof(int))*4096, SEEK_SET);
if( ferror(mmap->swap) ) {
return NULL;
}
fread(page->data, 4096, 1, mmap->swap);
if( ferror(mmap->swap) ) {
return NULL;
}
fseek(mmap->swap, i, SEEK_SET);
if( ferror(mmap->swap) ) {
return NULL;
}
int tmp = -1;
fwrite(&tmp, sizeof(int), 1, mmap->swap);
if( ferror(mmap->swap) ) {
return NULL;
}
return page;
} else {
return NULL;
}
CHECK_FERROR(mmap->swap);
if (key != page->key)
continue;
fseek(mmap->swap, 100*sizeof(int) + (i/sizeof(int))*4096, SEEK_SET);
CHECK_FERROR(mmap->swap);
fread(page->data, 4096, 1, mmap->swap);
CHECK_FERROR(mmap->swap);
fseek(mmap->swap, i, SEEK_SET);
CHECK_FERROR(mmap->swap);
int tmp = -1;
fwrite(&tmp, sizeof(int), 1, mmap->swap);
CHECK_FERROR(mmap->swap);
return page;
}
return NULL;
}