2018-08-06 18:41:45 +02:00
|
|
|
#include "mem.h"
|
2018-08-09 22:19:34 +02:00
|
|
|
#include "list.h"
|
2018-08-06 18:41:45 +02:00
|
|
|
#include "vga.h"
|
|
|
|
|
2018-08-09 22:19:34 +02:00
|
|
|
static struct mem_desc *page_desc = (struct mem_desc *)&__ld_kernel_end;
|
|
|
|
static struct mem_desc *free_page;
|
|
|
|
static struct mem_desc *used_page;
|
|
|
|
static unsigned long bottom_mem;
|
|
|
|
static unsigned long top_mem;
|
|
|
|
|
2018-08-06 18:41:45 +02:00
|
|
|
|
|
|
|
int memInit(unsigned long upper_mem)
|
|
|
|
{
|
2018-08-09 22:19:34 +02:00
|
|
|
printf("Free Mem going from %d to %d\n", &__ld_kernel_end, upper_mem * 1024);
|
2018-08-06 18:41:45 +02:00
|
|
|
unsigned long memdesc_end =
|
|
|
|
(unsigned long)page_desc +
|
|
|
|
((upper_mem) / (PAGE_SIZE / 1024)) * sizeof(struct mem_desc);
|
|
|
|
uint lastUsed = (memdesc_end >> PAGE_SHIFT) + 1;
|
2018-08-09 22:19:34 +02:00
|
|
|
list_init(free_page);
|
|
|
|
list_init(used_page);
|
|
|
|
bottom_mem = lastUsed;
|
|
|
|
top_mem = upper_mem;
|
2018-08-06 18:41:45 +02:00
|
|
|
for (uint i = 0; i < (upper_mem / (PAGE_SIZE / 1024)); i++) {
|
|
|
|
struct mem_desc *mem = &page_desc[i];
|
2018-08-09 22:19:34 +02:00
|
|
|
if (i < lastUsed) {
|
2018-08-06 18:41:45 +02:00
|
|
|
mem->ref = 1;
|
2018-08-09 22:19:34 +02:00
|
|
|
list_add_tail(used_page, mem);
|
|
|
|
} else {
|
2018-08-06 18:41:45 +02:00
|
|
|
mem->ref = 0;
|
2018-08-09 22:19:34 +02:00
|
|
|
list_add_tail(free_page, mem);
|
|
|
|
}
|
2018-08-06 18:41:45 +02:00
|
|
|
mem->phy_addr = i * PAGE_SIZE;
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
2018-08-09 22:19:34 +02:00
|
|
|
|
|
|
|
struct mem_desc *addr2memDesc(unsigned long addr)
|
|
|
|
{
|
|
|
|
if (addr > top_mem || addr < bottom_mem)
|
|
|
|
return NULL;
|
|
|
|
int idx = addr >> PAGE_SHIFT;
|
|
|
|
return page_desc + idx;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
unsigned long allocPage(void)
|
|
|
|
{
|
|
|
|
if (list_is_empty(free_page))
|
|
|
|
return (unsigned long)NULL;
|
|
|
|
struct mem_desc *mem = list_pop_head(free_page);
|
|
|
|
mem->ref = 1;
|
|
|
|
list_add_tail(used_page, mem);
|
|
|
|
return mem->phy_addr;
|
|
|
|
}
|
|
|
|
|
|
|
|
int unrefPage(unsigned long addr)
|
|
|
|
{
|
|
|
|
struct mem_desc *mem = addr2memDesc(addr);
|
|
|
|
if (!mem) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
mem->ref--;
|
|
|
|
if (mem->ref == 0) {
|
|
|
|
list_add_tail(free_page, mem);
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|