summaryrefslogtreecommitdiff
path: root/Source/Kernel/MemoryManager/PhysMem.ns.cpp
blob: a9bfd35f88d0348eeebd1aabf88155660cc6b2e6 (plain) (blame)
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
#include "PhysMem.ns.h"
#include <Library/Bitset.class.h>
#include <VTManager/VirtualTerminal.class.h>

PageDirectory* kernelPageDirectory;

namespace PhysMem {

u32int nframes;
Bitset *frames;

void initPaging(u32int mem_size) {
	nframes = mem_size / 0x1000;
	
	frames = new Bitset(nframes);

	kernelPageDirectory = new (Mem::kalloc(sizeof(PageDirectory), true)) PageDirectory();

	u32int i = 0xC0000000;
	while (i < Mem::placementAddress) {
		page_t *p2 = kernelPageDirectory->getPage(i, true);
		allocFrame(p2, true, false);
		/* /DEBUG_HEX(i); DEBUG(" =>");
		DEBUG_HEX(p2->frame); DEBUG("."); */
		i += 0x1000;
	}
	//Also map thoses pages at begning of virtual memory
	for (u32int i = 0; i < (Mem::placementAddress - 0xC0000000) / 0x100000; i++) {
		kernelPageDirectory->tablesPhysical[i] = kernelPageDirectory->tablesPhysical[768 + i];
		kernelPageDirectory->tables[i] = kernelPageDirectory->tables[768 + i];
	}
	DEBUG_HEX((u32int)kernelPageDirectory->physicalAddr); DEBUG(" is page dir phys addr.");
	//asm volatile("hlt");

	kernelPageDirectory->switchTo();
	DEBUG("Paging enabled !");

	Mem::pagingEnabled = true;
}

void removeTemporaryPages() {
	for (u32int i = 0; i < (Mem::placementAddress - 0xC0000000) / 0x100000; i++) {
		kernelPageDirectory->tablesPhysical[i] = 0;
		kernelPageDirectory->tables[i] = 0;
	}
}

void allocFrame(page_t *page, bool is_user, bool is_writable) {
	if (page->frame != 0) {
		return;
	} else {
		u32int idx = frames->firstFreeBit();
		if (idx == (u32int) - 1) PANIC("No more free frames !");
		frames->setBit(idx);
		page->present = 1;
		page->user = (is_user ? 1 : 0);
		page->rw = (is_writable ? 1 : 0);
		page->frame = idx;
	}
}

void freeFrame(page_t *page) {
	if (page->frame == 0) {
		return;
	} else {
		frames->clearBit(page->frame / 0x1000);
		page->frame = 0;
	}
}

u32int free() {
	return nframes - frames->usedBits();
}

u32int total() {
	return nframes;
}

}