# Memory Management

***

### Memory Layout

```
Virtual Address Space (x86_64)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
0xFFFFFFFF_FFFFFFFF ┐
                    │ Kernel Space
0xFFFFFFFF_80000000 ┤ (Higher Half)
                    │
                    ├─ .text    (RX)  Code
                    ├─ .rodata  (RO)  Constants
                    ├─ .data    (RW)  Initialized data
                    ├─ .bss     (RW)  Zero-initialized
                    ├─ Heap     (RW)  Dynamic
                    └─ Stacks   (RW)  Per-task

0x00007FFF_FFFFFFFF ┐
                    │ User Space
0x00000000_00000000 ┘ (Reserved for future)
```

***

### Physical Memory

#### Frame Allocator

* Manages 4KB physical frames
* Bitmap tracks allocation state
* Initialized from UEFI memory map

#### Memory Regions

Types from UEFI memory map:

| Type         | Usage                    |
| ------------ | ------------------------ |
| Conventional | Available for allocation |
| Reserved     | Hardware reserved        |
| ACPI         | ACPI tables              |
| Framebuffer  | GPU memory               |

***

### Virtual Memory

#### Paging Structure

x86\_64 4-level paging:

```
CR3 → PML4 → PDPT → PD → PT → Physical Frame
       │       │     │    │
      512    512   512  512 entries each
```

#### Page Sizes

| Size | Use Case       |
| ---- | -------------- |
| 4KB  | Default        |
| 2MB  | Large mappings |
| 1GB  | Huge mappings  |

***

#### Page Flags

| Flag       | Meaning                  |
| ---------- | ------------------------ |
| Present    | Page is mapped           |
| Writable   | Write access allowed     |
| User       | User-mode accessible     |
| No-Execute | Code execution forbidden |

***

### Heap Allocator

#### Implementation

* Linked-list allocator
* `#[global_allocator]` attribute
* Thread-safe with spinlock

#### Allocation Sizes

| Request | Strategy                |
| ------- | ----------------------- |
| < 4KB   | Heap allocator          |
| ≥ 4KB   | Direct frame allocation |

***

### Stack Management

#### Kernel Stacks

* 64KB per task
* Guard pages for overflow detection
* Grows downward

#### Stack Layout

```
┌─────────────────┐ High address
│   Guard Page    │ (Unmapped)
├─────────────────┤
│                 │
│   Stack Space   │
│                 │
├─────────────────┤
│   Guard Page    │ (Unmapped)
└─────────────────┘ Low address
```

***

### Security Features

#### W^X Enforcement

No page is both writable and executable:

* Code pages: RX (read + execute)
* Data pages: RW (read + write)
* Rodata: RO (read only)

#### KASLR

Kernel Address Space Layout Randomization:

* Randomized kernel base address
* Randomized stack locations
* Uses hardware entropy (RDRAND)

#### Guard Pages

Unmapped pages to catch:

* Stack overflow
* Buffer overflows

***

### Memory APIs

#### Kernel Allocation

```rust
// Allocate memory
let ptr = alloc::alloc::alloc(layout);

// Deallocate
alloc::alloc::dealloc(ptr, layout);
```

#### Page Mapping

```rust
// Map a virtual address to physical
memory::map_page(virt_addr, phys_addr, flags);

// Unmap
memory::unmap_page(virt_addr);
```

***

### Performance

| Operation          | Time        |
| ------------------ | ----------- |
| Page fault         | \~1μs       |
| Allocation (small) | \~100ns     |
| TLB flush          | \~50 cycles |
