summaryrefslogtreecommitdiff
path: root/Source/Kernel/MemoryManager/PageAlloc.ns.cpp
blob: 34d4f74bf55bda7eb4deaeeda04f1be76a0a2db9 (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
#include "PageAlloc.ns.h"
#include <MemoryManager/PhysMem.ns.h>

#define CACHED_PAGES 3

// This mechanism is supposed to make it impossible to run out of free pages to use as a page table

namespace PageAlloc {

void* freePage[CACHED_PAGES];
int freec = 0;
bool usable = false, locked = false;

void init() {
	freec = CACHED_PAGES;
	for (u32int i = 0; i < CACHED_PAGES; i++) {
		freePage[i] = Mem::kalloc(0x1000, true);
	}
	usable = true;
}

void* alloc(u32int* phys) {
	if (!usable) init();

	while (freec < CACHED_PAGES && (!locked)) {
		locked = true;
		void* next = 0;
		if (!Mem::pagingEnabled) {
			next = Mem::kalloc(0x1000, true);
		} else {
			u32int i = 0xFFFFF000;
			page_t *p;
			while (1) {
				p = kernelPageDirectory->getPage(i, true);
				if (p->frame == 0) break;
				i -= 0x1000;
			}
			PhysMem::allocFrame(p, true, false);
			next = (void*)i;
		}
		freePage[freec] = next;
		freec++;
		locked = false;
	}

	freec--;
	void* ret = freePage[freec];
	if (!Mem::pagingEnabled) {
		*phys = (u32int)ret - 0xC0000000;
	} else {
		page_t* p = kernelPageDirectory->getPage((u32int)ret, false);
		if (p == 0) {	//THIS SHOULD NEVER HAPPEN
			PANIC("Cached free page does not exist.");
		} else if (p->frame == 0) {
			PhysMem::allocFrame(p, true, false);
		} else {
			*phys = (p->frame * 0x1000);
		}
	}
	return ret;
}

void free(void *ptr) {
	kernelPageDirectory->freeFrame((u32int)ptr);
	return;
}

}