vmem.c file
Virtual memory implementation.
Functions
- auto vmem_page_size(void) -> size_t
- System page size in bytes.
- auto vmem_align_up(size_t bytes) -> size_t
- Round a byte count up to a multiple of the page size.
- auto vmem_reserve(VMemoryRegion* out, size_t bytes) -> int
- Reserve inaccessible virtual address space.
- auto vmem_commit(void* p, size_t bytes) -> int
- Make the pages covering
[p, p + bytes)readable and writable. - void vmem_release(VMemoryRegion* region)
- Release a whole reservation and zero the struct.
Defines
- #define _POSIX_C_SOURCE
- #define _DEFAULT_SOURCE
- #define MAP_ANONYMOUS
Function documentation
size_t vmem_page_size(void)
System page size in bytes.
| Returns | A power of two, or 4096 if the OS does not report a page size. |
|---|
size_t vmem_align_up(size_t bytes)
Round a byte count up to a multiple of the page size.
| Parameters | |
|---|---|
| bytes | Length to round. Zero stays zero. |
| Returns | Rounded length, or 0 if bytes is 0 or the rounded value would overflow. |
int vmem_reserve(VMemoryRegion* out, size_t bytes)
Reserve inaccessible virtual address space.
| Parameters | |
|---|---|
| out | Receives the reservation. Unchanged on failure. |
| bytes | Requested length. Rounded up to the page size. |
| Returns | 0 on success, or -1 if out is NULL, bytes is 0, or the OS refuses. |
On success the region is page-aligned and not yet readable or writable. Physical memory is charged only when the pages are committed.
int vmem_commit(void* p, size_t bytes)
Make the pages covering [p, p + bytes) readable and writable.
| Parameters | |
|---|---|
| p | Address inside a region from vmem_. |
| bytes | Number of bytes that must become accessible. |
| Returns | 0 on success, or -1 if p is NULL and bytes is non-zero, or the OS refuses. |
The range is expanded to whole pages. Committing the same pages again is success. bytes == 0 is success and does not touch memory.
void vmem_release(VMemoryRegion* region)
Release a whole reservation and zero the struct.
| Parameters | |
|---|---|
| region | Region returned by vmem_. |
NULL and already-released regions are ignored.