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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
|
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Copyright (C) 2026 Richard Qin */
/*
* vma.cc — Virtual Memory Area management (MI layer)
*
* Manages user address spaces using a red-black tree of VMA regions.
* Implements demand paging: vmm_map_user records intent only;
* physical pages are allocated on page fault via vmm_handle_page_fault.
*
* MI/MD separation: this file NEVER references pmap::PTE_* constants.
* Permission translation is delegated to pmap::vm_perm_to_pte().
*
* Reference: docs/specs/vmm.md
*/
#include <lume/vmm.h>
#include <lume/addr.h>
#include <lume/config.h>
#include <lume/errno.h>
#include <lume/pmm.h>
#include <lume/new.h>
#include <lume/klog.h>
#include <arch/pmap.h>
#include <lume/tlb.h>
#include <lume/mm_layout.h>
/* ------------------------------------------------------------------ */
/* Rbtree callbacks for VMA interval tree */
/* ------------------------------------------------------------------ */
static bool vma_less(struct rb_node* node, const struct rb_node* parent) {
VmAreaStruct* n = reinterpret_cast<VmAreaStruct*>(
reinterpret_cast<char*>(node) - __builtin_offsetof(VmAreaStruct, rb));
const VmAreaStruct* p = reinterpret_cast<const VmAreaStruct*>(
reinterpret_cast<const char*>(parent) - __builtin_offsetof(VmAreaStruct, rb));
return n->start < p->start;
}
static int vma_cmp(const void* key, const struct rb_node* node) {
uint64 addr = *static_cast<const uint64*>(key);
const VmAreaStruct* n = reinterpret_cast<const VmAreaStruct*>(
reinterpret_cast<const char*>(node) - __builtin_offsetof(VmAreaStruct, rb));
if (addr < n->start) return -1;
if (addr >= n->end) return 1;
return 0;
}
static VmAreaStruct* node_to_vma(struct rb_node* node)
{
return reinterpret_cast<VmAreaStruct*>(
reinterpret_cast<char*>(node) - __builtin_offsetof(VmAreaStruct, rb));
}
static uint64 align_up_any(uint64 value, uint64 align)
{
if (align == 0) {
return value;
}
return ((value + align - 1) / align) * align;
}
static bool range_overlaps(uint64 a_start, uint64 a_end,
uint64 b_start, uint64 b_end)
{
return a_start < b_end && b_start < a_end;
}
static bool vma_overlaps_locked(VmSpace* space, uint64 start, uint64 end)
{
struct rb_node* node = rb_first(&space->vma_tree);
while (node) {
VmAreaStruct* vma = node_to_vma(node);
if (range_overlaps(start, end, vma->start, vma->end)) {
return true;
}
node = rb_next(node);
}
return false;
}
static bool vma_range_covered_locked(VmSpace* space, uint64 start, uint64 end)
{
uint64 cursor = start;
struct rb_node* node = rb_first(&space->vma_tree);
while (node && cursor < end) {
VmAreaStruct* vma = node_to_vma(node);
if (vma->end <= cursor) {
node = rb_next(node);
continue;
}
if (vma->start > cursor) {
return false;
}
if (vma->end > cursor) {
cursor = vma->end;
}
node = rb_next(node);
}
return cursor >= end;
}
static void vma_try_merge_neighbors_locked(VmSpace* space, VmAreaStruct* vma)
{
struct rb_node* prev_node = rb_prev(&vma->rb);
if (prev_node) {
VmAreaStruct* prev = node_to_vma(prev_node);
if (prev->end == vma->start && prev->perm == vma->perm) {
prev->end = vma->end;
rb_erase(&vma->rb, &space->vma_tree);
delete vma;
vma = prev;
}
}
struct rb_node* next_node = rb_next(&vma->rb);
if (next_node) {
VmAreaStruct* next = node_to_vma(next_node);
if (vma->end == next->start && vma->perm == next->perm) {
vma->end = next->end;
rb_erase(&next->rb, &space->vma_tree);
delete next;
}
}
}
static int vma_split_locked(VmSpace* space, VmAreaStruct* vma, uint64 split)
{
if (split <= vma->start || split >= vma->end) {
return 0;
}
VmAreaStruct* right = new VmAreaStruct;
if (!right) {
return -ENOMEM;
}
right->start = split;
right->end = vma->end;
right->perm = vma->perm;
right->mm = space;
vma->end = split;
rb_add(&right->rb, &space->vma_tree, vma_less);
return 0;
}
static int vma_split_range_locked(VmSpace* space, uint64 start, uint64 end)
{
if (end <= start) {
return 0;
}
struct rb_node* start_node = rb_find(&start, &space->vma_tree, vma_cmp);
if (!start_node) {
return -ENOMEM;
}
VmAreaStruct* start_vma = node_to_vma(start_node);
int ret = vma_split_locked(space, start_vma, start);
if (ret < 0) {
return ret;
}
uint64 end_key = end - 1;
struct rb_node* end_node = rb_find(&end_key, &space->vma_tree, vma_cmp);
if (!end_node) {
return -ENOMEM;
}
VmAreaStruct* end_vma = node_to_vma(end_node);
return vma_split_locked(space, end_vma, end);
}
/* ------------------------------------------------------------------ */
/* VmSpace lifecycle */
/* ------------------------------------------------------------------ */
VmSpace* VmSpace::create() {
VmSpace* space = new VmSpace;
if (!space) return nullptr;
space->root_pa = pmap::create();
if (!space->root_pa) {
delete space;
return nullptr;
}
space->vma_tree = RB_ROOT;
space->lock.init("VmSpace");
space->refcount.store(1, __ATOMIC_RELAXED);
space->brk_start = 0;
space->brk_end = 0;
return space;
}
void VmSpace::incref() {
refcount.fetch_add(1, __ATOMIC_RELAXED);
}
void VmSpace::put() {
if (refcount.fetch_sub(1, __ATOMIC_ACQ_REL) == 1) {
destroy();
}
}
void VmSpace::destroy() {
/* Drain VMA tree under lock, then release BEFORE delete this */
lock.acquire();
uint64 root = root_pa;
struct rb_node* node = rb_first(&vma_tree);
while (node) {
VmAreaStruct* vma = reinterpret_cast<VmAreaStruct*>(
reinterpret_cast<char*>(node) - __builtin_offsetof(VmAreaStruct, rb));
/* Decref and dec mapcount for all mapped physical pages */
for (uint64 addr = vma->start; addr < vma->end; addr += kPageSize) {
uint64 pa;
if (pmap::lookup(root, addr, &pa)) {
Page* pg = pa_to_page(phys_addr(pa));
page_dec_mapcount(pg);
page_decref(pg);
}
}
node = rb_next(node);
rb_erase(&vma->rb, &vma_tree);
delete vma;
}
lock.release();
/* Destroy hardware page tables outside the lock */
pmap::destroy(root);
/* Finally free VmSpace itself */
delete this;
}
/* ------------------------------------------------------------------ */
/* Public API: VMA manipulation */
/* ------------------------------------------------------------------ */
int vmm_map_user(VmSpace* space, uint64 va, uint64 len, uint64 perm) {
if (!space) return -EINVAL;
va = page_align_down(va);
len = page_align_up(len);
if (len == 0) return 0;
if (va < kUserVaBase) return -EINVAL;
if (va >= kUserVaLimit) return -EINVAL;
if (va + len < va || va + len > kUserVaLimit) return -EINVAL;
VmAreaStruct* vma = new VmAreaStruct;
if (!vma) return -ENOMEM;
vma->start = va;
vma->end = va + len;
vma->perm = perm | VM_USER; // Enforce user-mode access (MI flag)
vma->mm = space;
LockGuard guard(space->lock);
if (vma_overlaps_locked(space, vma->start, vma->end)) {
delete vma;
return -EINVAL;
}
rb_add(&vma->rb, &space->vma_tree, vma_less);
vma_try_merge_neighbors_locked(space, vma);
return 0;
}
int vmm_unmap_user(VmSpace* space, uint64 va, uint64 len) {
if (!space) return -EINVAL;
va = page_align_down(va);
len = page_align_up(len);
if (len == 0) return 0;
if (va < kUserVaBase) return -EINVAL;
if (va >= kUserVaLimit) return -EINVAL;
if (va + len < va || va + len > kUserVaLimit) return -EINVAL;
uint64 end = va + len;
LockGuard guard(space->lock);
struct rb_node* node = rb_first(&space->vma_tree);
while (node) {
VmAreaStruct* vma = node_to_vma(node);
struct rb_node* next = rb_next(node);
if (vma->end <= va) {
node = next;
continue;
}
if (vma->start >= end) {
break;
}
uint64 unmap_start = (vma->start > va) ? vma->start : va;
uint64 unmap_end = (vma->end < end) ? vma->end : end;
if (unmap_start < unmap_end) {
for (uint64 addr = unmap_start; addr < unmap_end; addr += kPageSize) {
uint64 pa;
if (pmap::lookup(space->root_pa, addr, &pa)) {
pmap::unmap(space->root_pa, addr);
Page* pg = pa_to_page(phys_addr(pa));
page_dec_mapcount(pg);
page_decref(pg);
}
}
}
if (unmap_start == vma->start && unmap_end == vma->end) {
rb_erase(&vma->rb, &space->vma_tree);
delete vma;
} else if (unmap_start == vma->start) {
rb_erase(&vma->rb, &space->vma_tree);
vma->start = unmap_end;
rb_add(&vma->rb, &space->vma_tree, vma_less);
} else if (unmap_end == vma->end) {
vma->end = unmap_start;
} else {
VmAreaStruct* right = new VmAreaStruct;
if (!right) {
return -ENOMEM;
}
right->start = unmap_end;
right->end = vma->end;
right->perm = vma->perm;
right->mm = space;
vma->end = unmap_start;
rb_add(&right->rb, &space->vma_tree, vma_less);
break;
}
node = next;
}
return 0;
}
int vmm_protect_user(VmSpace* space, uint64 va, uint64 len, uint64 perm)
{
if (!space) return -EINVAL;
va = page_align_down(va);
len = page_align_up(len);
if (len == 0) return -EINVAL;
if (va < kUserVaBase) return -EINVAL;
if (va >= kUserVaLimit) return -EINVAL;
if (va + len < va || va + len > kUserVaLimit) return -EINVAL;
uint64 end = va + len;
LockGuard guard(space->lock);
if (!vma_range_covered_locked(space, va, end)) {
return -ENOMEM;
}
int ret = vma_split_range_locked(space, va, end);
if (ret < 0) {
return ret;
}
bool tlb_flush_needed = false;
struct rb_node* node = rb_find(&va, &space->vma_tree, vma_cmp);
while (node) {
VmAreaStruct* vma = node_to_vma(node);
if (vma->start >= end) {
break;
}
if (vma->end <= va) {
node = rb_next(node);
continue;
}
vma->perm = (perm | VM_USER);
for (uint64 addr = vma->start; addr < vma->end; addr += kPageSize) {
uint64 pa;
if (!pmap::lookup(space->root_pa, addr, &pa)) {
continue;
}
if (perm == 0) {
Page* pg = pa_to_page(phys_addr(pa));
page_dec_mapcount(pg);
page_decref(pg);
pmap::unmap(space->root_pa, addr);
tlb_flush_needed = true;
continue;
}
uint64 pte_perm = pmap::vm_perm_to_pte(vma->perm);
if ((vma->perm & VM_WRITE) && pmap::is_cow(space->root_pa, addr)) {
pte_perm &= ~pmap::PTE_W;
pte_perm |= pmap::PTE_COW;
}
int ret = pmap::protect(space->root_pa, addr, pte_perm);
if (ret < 0) {
return ret;
}
tlb_flush_needed = true;
}
node = rb_next(node);
}
if (tlb_flush_needed) {
tlb_shootdown_range(space, va, end);
}
return 0;
}
uint64 mm_find_free_va(VmSpace* space, uint64 length, uint64 align)
{
if (!space) return 0;
length = page_align_up(length);
if (length == 0) return 0;
if (align < kPageSize) align = kPageSize;
LockGuard guard(space->lock);
/* Linux: arch_get_unmapped_area() starts from mm->mmap_base.
* RISC-V: TASK_UNMAPPED_BASE = PAGE_ALIGN(TASK_SIZE / 3).
* Fall back to kUserVaBase if mmap_base not set (kernel VmSpaces). */
uint64 base = space->mmap_base ? space->mmap_base : kUserVaBase;
uint64 cursor = align_up_any(base, align);
struct rb_node* node = rb_first(&space->vma_tree);
while (node) {
VmAreaStruct* vma = node_to_vma(node);
if (cursor <= vma->start) {
if (cursor > kUserVaLimit - length) {
return 0;
}
if (cursor + length <= vma->start) {
return cursor;
}
}
if (cursor < vma->end) {
cursor = vma->end;
}
cursor = align_up_any(cursor, align);
node = rb_next(node);
}
if (cursor > kUserVaLimit - length) {
return 0;
}
return cursor;
}
bool vma_range_covered(VmSpace* space, uint64 start, uint64 end)
{
if (!space) return false;
start = page_align_down(start);
end = page_align_up(end);
if (end <= start) return true;
LockGuard guard(space->lock);
return vma_range_covered_locked(space, start, end);
}
/* ------------------------------------------------------------------ */
/* Page fault handler (demand paging) */
/* ------------------------------------------------------------------ */
static bool vma_allows(const VmAreaStruct* vma, VmFaultCause cause)
{
switch (cause) {
case VmFaultCause::Read:
return (vma->perm & VM_READ) != 0;
case VmFaultCause::Write:
return (vma->perm & VM_WRITE) != 0;
case VmFaultCause::Exec:
return (vma->perm & VM_EXEC) != 0;
default:
return false;
}
}
int vmm_handle_page_fault(VmSpace* space, uint64 fault_addr, VmFaultCause cause) {
if (!space) return -EINVAL;
uint64 aligned_addr = page_align_down(fault_addr);
LockGuard guard(space->lock);
struct rb_node* node = rb_find(&fault_addr, &space->vma_tree, vma_cmp);
if (!node) {
return -EFAULT; // No VMA covers this address → segfault
}
VmAreaStruct* vma = reinterpret_cast<VmAreaStruct*>(
reinterpret_cast<char*>(node) - __builtin_offsetof(VmAreaStruct, rb));
if (!vma_allows(vma, cause)) {
return -EFAULT;
}
/* Check if page is already mapped */
uint64 paddr;
if (pmap::lookup(space->root_pa, aligned_addr, &paddr)) {
if (cause == VmFaultCause::Write && pmap::is_cow(space->root_pa, aligned_addr)) {
/* Store Page Fault on a COW page */
Page* page = pmm_alloc_page();
if (!page) return -ENOMEM;
uint64 new_pa = page_to_pa(page).raw;
/* Copy page contents */
uint8* dst = reinterpret_cast<uint8*>(pa_to_va(phys_addr(new_pa)).raw);
const uint8* src = reinterpret_cast<const uint8*>(pa_to_va(phys_addr(paddr)).raw);
for (uint64 i = 0; i < kPageSize; i++) {
dst[i] = src[i];
}
/* Remap with write permission, clearing COW */
uint64 pte_perm = pmap::vm_perm_to_pte(vma->perm);
if (pmap::map(space->root_pa, aligned_addr, new_pa, pte_perm) != 0) {
pmm_free_page(page);
return -ENOMEM;
}
/* New page gets mapcount = 1 (we just mapped it) */
page_inc_mapcount(page);
/* Decrement mapcount and refcount of old page */
Page* old_page = pa_to_page(phys_addr(paddr));
page_dec_mapcount(old_page);
page_decref(old_page);
/* Flush TLB to remove old read-only cached translation */
tlb_shootdown_page(space, aligned_addr);
return 0;
}
/* DEBUG: page already mapped but still faulting — dump PTE */
{
uint64 cur_satp;
asm volatile("csrr %0, satp" : "=r"(cur_satp));
printk(KERN_ERR "fault: va=%llx pa=%llx cause=%d pte=%llx satp=%llx root=%llx\n",
aligned_addr, paddr, static_cast<int>(cause),
pmap::lookup_pte(space->root_pa, aligned_addr),
cur_satp, space->root_pa);
}
return 0; // Already mapped, maybe read fault on existing page
}
/* Allocate physical page and zero it.
* Linux: do_anonymous_page() uses alloc_zeroed_user_highpage_movable().
* Anonymous pages MUST be zeroed — userspace expects MAP_ANONYMOUS
* pages to contain all zeros (POSIX requirement). */
Page* page = pmm_alloc_page();
if (!page) return -ENOMEM;
uint64 pa = page_to_pa(page).raw;
/* Zero the page before mapping it to userspace */
/* Zero the page before mapping it to userspace */
uint8* kva = reinterpret_cast<uint8*>(pa_to_va(PhysAddr{pa}).raw);
for (uint64 i = 0; i < kPageSize; i++) kva[i] = 0;
/* Translate MI permission flags to hardware PTE bits (MD layer) */
uint64 pte_perm = pmap::vm_perm_to_pte(vma->perm);
if (pmap::map(space->root_pa, aligned_addr, pa, pte_perm) != 0) {
pmm_free_page(page);
return -ENOMEM;
}
/* Initial mapping: refcount is already 1 from pmm_alloc_page.
* Set mapcount = 1 to track this PTE mapping. */
page_inc_mapcount(page);
return 0;
}
/* ------------------------------------------------------------------ */
/* Fork / Clone (COW infrastructure) */
/* ------------------------------------------------------------------ */
VmSpace* vmm_clone(VmSpace* parent) {
if (!parent) return nullptr;
VmSpace* child = VmSpace::create();
if (!child) return nullptr;
child->brk_start = parent->brk_start;
child->brk_end = parent->brk_end;
LockGuard parent_guard(parent->lock);
struct rb_node* node = rb_first(&parent->vma_tree);
while (node) {
VmAreaStruct* parent_vma = reinterpret_cast<VmAreaStruct*>(
reinterpret_cast<char*>(node) - __builtin_offsetof(VmAreaStruct, rb));
VmAreaStruct* child_vma = new VmAreaStruct;
if (!child_vma) {
child->destroy();
return nullptr;
}
child_vma->start = parent_vma->start;
child_vma->end = parent_vma->end;
child_vma->perm = parent_vma->perm;
child_vma->mm = child;
/* Copy pages and mark COW if writable */
for (uint64 va = child_vma->start; va < child_vma->end; va += kPageSize) {
uint64 pa;
if (pmap::lookup(parent->root_pa, va, &pa)) {
/* Make parent COW if it was writable */
if (child_vma->perm & VM_WRITE) {
pmap::make_cow(parent->root_pa, va);
/* Flush TLB for parent since we reduced permissions */
tlb_shootdown_page(parent, va);
}
/* Map in child as COW or read-only */
uint64 pte_perm = pmap::vm_perm_to_pte(child_vma->perm);
if (child_vma->perm & VM_WRITE) {
pte_perm &= ~pmap::PTE_W;
pte_perm |= pmap::PTE_COW;
}
if (pmap::map(child->root_pa, va, pa, pte_perm) != 0) {
/* If map fails, we leak what we did in this loop for now,
* but child->destroy() will clean it up safely since
* we increment refcounts as we go. */
delete child_vma;
child->destroy();
return nullptr;
}
/* Increment physical page refcount and mapcount */
Page* shared_page = pa_to_page(phys_addr(pa));
page_incref(shared_page);
page_inc_mapcount(shared_page);
}
}
rb_add(&child_vma->rb, &child->vma_tree, vma_less);
node = rb_next(node);
}
return child;
}
|