hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/boot/vmm.zig
blob: c84b624aa32faa01342fad3d30d0095dfbd8beda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// our own 4 level (x86_64) page tables so we can build
// per process address spaces and mark pages user accessible
//
// physical frames come from the pmm so we reach any frame through the hhdm
// to read/write table entries. the privileged bits (reading cr3, invlpg) are the
// only thing written in asm here
//
// see: https://wiki.osdev.org/Paging

const pmm = @import("pmm.zig");

// page table entry flag bits
pub const PRESENT: u64 = 1 << 0;
pub const WRITE: u64 = 1 << 1;
pub const USER: u64 = 1 << 2; // 1 = ring 3 accessible
pub const NX: u64 = 1 << 63; // WARNING: NEEDS EFER.NXE DO NOT SET UNLESS ENABLED

// a free software bit (the cpu ignores bits 9..11). we flag a page copy on write
// here: the page is mapped read only, and a write fault copies it, see handleCow
pub const COW: u64 = 1 << 9;

// bits 12..51 of an entry hold the physical frame address
const ADDR_MASK: u64 = 0x000F_FFFF_FFFF_F000;

// physical base of the currently active pml4 (top of cr3)
pub fn activePml4() u64 {
    const cr3 = asm volatile ("mov %%cr3, %[out]"
        : [out] "=r" (-> u64),
    );
    return cr3 & ADDR_MASK;
}

// switch the active address space
pub fn loadPml4(pml4_phys: u64) void {
    asm volatile ("mov %[v], %%cr3"
        :
        : [v] "r" (pml4_phys),
        : .{ .memory = true });
}

pub fn invlpg(virt: u64) void {
    asm volatile ("invlpg (%[v])"
        :
        : [v] "r" (virt),
        : .{ .memory = true });
}

fn table(phys: u64) [*]volatile u64 {
    return @ptrFromInt(pmm.physToVirt(phys));
}

fn zeroFrame(phys: u64) void {
    const p: [*]u8 = @ptrFromInt(pmm.physToVirt(phys));
    @memset(p[0..pmm.PAGE_SIZE], 0);
}

// which 9 bit slice of the virtual address indexes level (3=pml4 .. 0=pt)
fn index(virt: u64, level: u6) usize {
    const page_shift = 12; // low 12 bits are the page offset
    const index_bits = 9; // each level consumes 9 bits of the address
    return @intCast((virt >> (page_shift + index_bits * level)) & 0x1FF);
}

// return the physical base of the next level table under entry i
// if missing -> create one
fn nextTable(parent_phys: u64, i: usize, create: bool) ?u64 {
    const entries = table(parent_phys);
    const entry = entries[i];
    if (entry & PRESENT != 0) return entry & ADDR_MASK;
    if (!create) return null;
    const frame = pmm.alloc() orelse return null;
    zeroFrame(frame);
    entries[i] = frame | PRESENT | WRITE | USER;
    return frame;
}

// map one 4 kib page: virt -> phys with the given leaf flags (present is added
// returns false only if we ran out of frames for intermediate tables
pub fn map(pml4_phys: u64, virt: u64, phys: u64, flags: u64) bool {
    const pdpt = nextTable(pml4_phys, index(virt, 3), true) orelse return false;
    const pd = nextTable(pdpt, index(virt, 2), true) orelse return false;
    const pt = nextTable(pd, index(virt, 1), true) orelse return false;
    table(pt)[index(virt, 0)] = (phys & ADDR_MASK) | flags | PRESENT;
    invlpg(virt);
    return true;
}

// create a fresh address space
// a new pml4 that shares the kernels higher half, so indices 256..511
// (kernel image, hhdm, stack, vm heap) but has an empty lower half for a
// processs own user memory. returns the new pml4 phys
//
// sharing is by copying the top level entries, so every address space points at
// the same kernel page tables, the kernel stays mapped no matter which process
// is active, which is what lets us keep running after a cr3 switch
pub fn createAddressSpace() ?u64 {
    const pml4 = pmm.alloc() orelse return null;
    zeroFrame(pml4);
    const src = table(activePml4());
    const dst = table(pml4);
    // entries 256..511 are the shared kernel higher half
    var i: usize = 256;
    while (i < 512) : (i += 1) dst[i] = src[i];
    return pml4;
}

// deeop copy one lower level table (level 0=pt, level 1=pd, level 2=pdpt)
// subtables get fresh frames but leaf data pages are shared with the parent and
// flipped to copy on write on both sides.
fn copyTable(src_phys: u64, level: u6) ?u64 {
    const new = pmm.alloc() orelse return null;
    zeroFrame(new);
    const src = table(src_phys);
    const dst = table(new);

    var i: usize = 0;
    while (i < 512) : (i += 1) {
        if (src[i] & PRESENT == 0) continue;
        if (level == 0) {
            var entry = src[i];
            if (entry & WRITE != 0) {
                entry = (entry & ~WRITE) | COW; // demote: writable -> copy on write
                src[i] = entry; // the parent shares the same arr
            }
            dst[i] = entry;
            pmm.incref(entry & ADDR_MASK);
        } else {
            const sub = copyTable(src[i] & ADDR_MASK, level - 1) orelse {
                freeTable(new, level);
                return null;
            };
            dst[i] = sub | (src[i] & ~ADDR_MASK);
        }
    }
    return new;
}

fn freeTable(phys: u64, level: u6) void {
    const t = table(phys);
    var i: usize = 0;
    while (i < 512) : (i += 1) {
        if (t[i] & PRESENT == 0) continue;
        if (level == 0) {
            pmm.free(t[i] & ADDR_MASK); // decref the leaf data page
        } else {
            freeTable(t[i] & ADDR_MASK, level - 1);
        }
    }
    pmm.free(phys); // the table frame itself is never shared
}

pub fn forkAddressSpace(parent_pml4: u64) ?u64 {
    const child = pmm.alloc() orelse return null;
    zeroFrame(child);
    const src = table(parent_pml4);
    const dst = table(child);

    // kernel higher half
    var i: usize = 256;
    while (i < 512) : (i += 1) dst[i] = src[i];

    // user half
    i = 0;
    while (i < 256) : (i += 1) {
        if (src[i] & PRESENT == 0) continue;
        const sub = copyTable(src[i] & ADDR_MASK, 2) orelse {
            freeAddressSpace(child);
            return null;
        };
        dst[i] = sub | (src[i] & ~ADDR_MASK);
    }

    loadPml4(activePml4());
    return child;
}

pub fn freeAddressSpace(pml4: u64) void {
    const t = table(pml4);
    var i: usize = 0;
    while (i < 256) : (i += 1) {
        if (t[i] & PRESENT != 0) freeTable(t[i] & ADDR_MASK, 2);
    }
    pmm.free(pml4);
}

pub fn handleCow(virt: u64) bool {
    const pml4 = activePml4();
    const pdpt = nextTable(pml4, index(virt, 3), false) orelse return false;
    const pd = nextTable(pdpt, index(virt, 2), false) orelse return false;
    const pt = nextTable(pd, index(virt, 1), false) orelse return false;
    const pte = &table(pt)[index(virt, 0)];
    const entry = pte.*;
    if (entry & PRESENT == 0 or entry & COW == 0) return false;

    const old_phys = entry & ADDR_MASK;
    if (pmm.refcount(old_phys) > 1) {
        const new_phys = pmm.alloc() orelse return false;
        const from: [*]const u8 = @ptrFromInt(pmm.physToVirt(old_phys));
        const to: [*]u8 = @ptrFromInt(pmm.physToVirt(new_phys));
        @memcpy(to[0..pmm.PAGE_SIZE], from[0..pmm.PAGE_SIZE]);
        pte.* = (new_phys & ADDR_MASK) | (entry & ~ADDR_MASK & ~COW) | WRITE;
        pmm.free(old_phys); // drop our share of the old frame
    } else {
        pte.* = (entry & ~COW) | WRITE; // js take write back
    }
    invlpg(virt);
    return true;
}

// walk the tables and return the physical address a virtual address maps to
// (page base | offset), or null if unmapped
// note: mostly for debugging
pub fn translate(pml4_phys: u64, virt: u64) ?u64 {
    const pdpt = nextTable(pml4_phys, index(virt, 3), false) orelse return null;
    const pd = nextTable(pdpt, index(virt, 2), false) orelse return null;
    const pt = nextTable(pd, index(virt, 1), false) orelse return null;
    const entry = table(pt)[index(virt, 0)];
    if (entry & PRESENT == 0) return null;
    return (entry & ADDR_MASK) | (virt & 0xFFF); // frame base | page offset
}