# Virtual memory implementation
## Original mechanisms
Since originally Phantom worked on 32-bit architecture it has 32-bit address space.
## Memory layout
It is lower 2GB of the address space that is mapped 1 to 1 to the physical memory
> based on sources and https://github.com/dzavalishin/phantomuserland/wiki/KernelMemoryMap
- `0x0 - 0x500` = BIOS data area, preserved
- `0x500 - 0x100000` = low memory. Allocable except for I/O and ROM area (1mb-640k)
- Allocation via:
- `phantom_phys_alloc_page(), phantom_phys_alloc_region()` using `low_map` arena in `hal_physmem.c`
- What stores:
- Structures specific to certain devices
- ???
- Who uses:
- Device drivers
- ???
- `0x100000 - 0x???????` = Kernel (size: 1mb - ?mb)
- `<kernel end> - 0x40000000` = kernel heap, mapped as is (will be mapped not as is later)
- Allocation via:
- `malloc()`
- What stores:
- all dynamically allocated kernel structures
- Who uses:
- kernel
- `0x40000000 - 0x80000000` = unmapped, used to allocate unbacked address space (mem mapped devices, etc)
- Allocation via:
- `hal_alloc_phys_page()`
- `phantom_phys_alloc_page(), phantom_phys_alloc_region()` using `pm_map` arena in `hal_physmem.c`
- What stores:
- Any allocated physical page that is not backed by disk and mapped onto object space
- Who uses:
- Pager (when handling page faults)
- Device drivers
- `0x80000000 - 0xC0000000` = foreground, objects space
- Allocation via:
- `hal_alloc_vaddress()`, `hal_pv_alloc()`
- `phantom_phys_alloc_page(), phantom_phys_alloc_region()` using `vm_map` arena in `hal_physmem.c`
- Who uses:
- Virtual machine
- Drivers (to store some state)
## Implementation
Several mechanisms to allocate physical/virtual memory are available inside Phantom:
- Main physical memory allocator
- Address space allocator
- P+V allocator
- Kernel heap
- Pools
They are described in the corresponding section of the book:
- https://github.com/dzavalishin/phantomuserland/wiki/KernelMemoryMap
## Proposed implementation
### Layout
Ideally, first 32 GBs of virtual address space can be used as a kernel heap and the rest can be used for persistent memory. However, while internal Phantom memory structures are not adapted to 64 bits, only first 3 GBs will be used in the following way:
- 0 - 2GB = kernel heap
- 2 - 3GB = persistent memory
- 3GB - 2^64B = unmapped
### Implementation
TODO : What to describe?
- Access to API to map virtual pages
- Pseudo-physical space and rationale behind it
- Object space with dedicated page fault handler
- Why malloc from Genode's libc and why not own implementation?
- Why malloc and Phantom's physical page allocation will not intersect?