WVB Operating System(Eighth Stage)
Welcome back all the readers to my eighth article on operating system implementation. In the last articles, we learned about Virtual memory and paging. This article will explain Page Frame Allocation, Managing Available Memory, and the Kernel Heap.
When we are going to do the page frame allocation first we need to know how much memory is available on the computer the OS is running on. Reading it from the multiboot structure supplied to us by GRUB is the simplest way to do it. GRUB gathers the memory information we require, such as what is reserved, I/O mapped, read-only, and so on. We must also make certain that the memory used by the kernel is not marked as free. Exporting labels at the beginning and end of the kernel binary from the linker script is one technique to figure out how much memory the kernel uses.
Then, Our “link” file would be like this.
These labels can directly be read from assembly code and pushed on the stack to make them available to C code.
Updated loader.s file would be like this.
What method do we use to determine which page frames are in use? The page frame allocator must keep track of which frames are available for use and which are not. There are several ways to do this. Bitmaps are quite simple to use. Each page frame uses one bit, and one page frame is allocated to storing the bitmap.
The page frame allocator delivers the page frame’s physical start address. There is no page table that points to this page frame since it is not mapped in. What is the best way to read and write data to the frame? We must map the page frame into virtual memory by modifying the kernel’s PDT. We won’t be able to map the page frame into memory if all available page tables are occupied. One option is to set aside a portion of the kernel’s first-page table for temporarily mapping page frames in order to make them accessible.
We may add the page frame we wish to use as a page table to the paging directory and remove the temporary mapping after we’ve temporarily mapped it and set it up to map in our initial page frame. We have only been able to operate with fixed-size data or raw memory up until now. We can implement malloc and free to use in the kernel now that we have a page frame allocator. We must additionally ensure that the page frame allocator returns virtual addresses for the page frames it returns. When sufficiently large blocks of memory are freed, a proper implementation should also return page frames to the page frame allocator.