German
German

Reputation: 345

How do I implement memory management in the kernel?

I can't fully understand how to implement virtual memory and how to allocate it for the kernel and processes. Now I'm interested in how to implement memory management at the core level.

How do I imagine it: 1. Divide the available RAM into equal blocks (frame) of 4 KB. 2. Then, if we want to allocate a certain amount of memory for a variable in the kernel, we look for a certain number of blocks(frames) in memory whose total size is not less than the requested amount of memory. Then we enter the address of the first block, the number of blocks in a certain table and give the address of the first block for data to this process.

And will it be optimal to go through all the pages of memory every time in search of free memory? Is it correct to give an entire page at once if the required volume is small?

How to implement all this? What am I wrong about?

Upvotes: 1

Views: 514

Answers (1)

NotNik.
NotNik.

Reputation: 418

Not quite. To allocate a certain amount of pages that are directly behind each other in (virtual) memory, we first ask our physical memory manager (pmm) to allocate some "random" pages (i.e. not behind each other). Then each individual page is passed to our virtual memory manager (vmm). The vmm has the pointer to the current page directory which itself contains several page tables. A page table holds a physical address (4k aligned) to every virtual address it covers. If we now want to map a physical address to a virtual address, we can do so by calculating the index in the page directory and in the resulting page table and set the right bits. If we now map our "randomly" allocated pages right behind each other we have our wonderful block of memory just for ourselves. Now if you want to switch betweenn processes you can simply swap out the current page directory.

To summarize the vmm: Top level is an array of arrays of physical addresses. The index of each address tells the CPU which virtual address to map to. Additionally each array holds some access meta-data.

If you want to know more feel free to read this if you haven't done so already.

Upvotes: 1

Related Questions