In the previous chapter, the base and bounds registers enabled the OS to map the virtual address space to the physical address space easily. But there’s a big chunk of “free space” in the middle that’s getting wasted due to this. This space cannot be used by any other process.
Also, this will become difficult when allocating address spaces that are larger than the memory. Even though the entire virtual space might not get used up, the OS still has to allocate the requested amount of memory.
This can be solved by a simple strategy: instead of just having one MMU for our entire address space, we can have a base and bounds pair for each logical segment i.e. code, stack and heap. This will enable the OS to allocate memory in different places for each segment instead of allocating a big chunk like before.
Below is an illustration of how this works
From the above diagram, the physical address space has the following base and bound pairs for each segment:
Sgement | Base | Size |
---|---|---|
Code | 32KB | 2KB |
Heap | 34KB | 3KB |
Stack | 28KB | 2KB |
Let’s do an address translation from the virtual space to the physical space in this setup.
Assume we need to access the address 100 in virtual space, which belongs to the code segment. Now, to get the physical address we need to add it to the base 32KB which gives us 32868 (100 + 32768).
Let’s look at the address in the heap. Say we want to access virtual address 4200. We need to first get the offset of this wrt heap area in virtual space, which is 4200 - 4096 = 104. We need to now add this to the base of heap i.e 34KB. This gives us 34KB + 104 = 34920.
The book then explains how these segments and offsets can be stored. This information can be stored (named “explicit” approach) like:
4200 in binary.
The first two bits will be used to store the segment. These two bits allow us to store up to 4 segments. If the top two bits are 00, then the segment will be code, etc. The remaining 12 bits will store the offset. Let’s take the translation of the address space of 4200 as an example. The first two bits (01) represent the segment is the heap. The remaining bits, 000 0110 1000, or 104 in decimal directly give us the offset in physical space.