aboutsummaryrefslogtreecommitdiff
path: root/arch/riscv64/kernel/vmem.c
blob: 835f53d5415488037fc80768cc4e40aadcd026d1 (plain) (blame)
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
/* SPDX-License-Identifier: copyleft-next-0.3.1 */
/* Copyright 2021 - 2022, Kim Kuparinen < kimi.h.kuparinen@gmail.com > */

/**
 * @file vmem.c
 * riscv64 implementation of arch-specific virtual memory handling.
 */

#include <kmi/assert.h>
#include <kmi/string.h>
#include <kmi/pmem.h>
#include <kmi/vmem.h>
#include <kmi/mem.h>
#include <kmi/debug.h>
#include <arch/cpu.h>
#include "pages.h"
#include "arch.h"
#include "csr.h"

/**
 * Get page table entry physical page number.
 *
 * @param pte Page table entry.
 * @return Corresponding physical page number.
 */
#define pte_ppn(pte) (((pm_t)(pte)) >> 10)

/**
 * Get page table entry flags.
 *
 * @param pte Page table entry.
 * @return Corresponding flags.
 */
#define pte_flags(pte) (((pm_t)(pte)) & 0xff)

/**
 * Convert physical memory address to page table entry.
 *
 * @param p Physical memory address.
 * @param f Flags to use.
 * @return Corresponding page table entry.
 */
#define to_pte(p, f) ((((p) >> page_shift()) << 10) | (f))

/**
 * Get physical address in page table entry.
 *
 * @param pte Page table entry.
 * @return Corresponding physical address.
 */
#define pte_paddr(pte) (pte_ppn(pte) << page_shift())

/**
 * Get virtual address in page table entry.
 *
 * @param pte Page table entry.
 * @return Corresponding virtual address.
 */
#define pte_addr(pte) __va(pte_paddr(pte))

/**
 * Virtual memory address to page order index.
 *
 * @param a Virtual address.
 * @param o Order of page.
 * @return Corresponding page index.
 */
#define vm_to_index(a, o) (pm_to_index(a, o))

/**
 * Check if page table entry is active.
 *
 * @param pte Page table entry.
 * @return \c 0 if entry is not active, non-zero otherwise.
 */
#define is_active(pte) (pte_flags(pte) &VM_V)

/**
 * Check if page table entry is a leaf.
 *
 * @param pte Page table entry.
 * @return \c 0 if entry is not leaf, non-zero otherwise.
 */
#define is_leaf(pte) (is_active(pte) && (pte_flags(pte) & ~VM_V))

/**
 * Check if page table entry is a branch.
 *
 * @param pte Page table entry.
 * @return \c 0 if entry is not branch, non-zero otherwise.
 */
#define is_branch(pte) (is_active(pte) && !(pte_flags(pte) & ~VM_V))

/**
 * Gravestone marker.
 *
 * Riscv allows us to have arbitrary data in page entries, as long as they're
 * not marked active (VM_V) the content is ignored. Here we use this to our
 * advantage by differentiating between empty entries (NULL) and filler entries
 * (GRAVESTONE).
 *
 * A gravestone tells us that somewhere above it (= higher index) there is an
 * active entry. This is useful mainly in \ref clone_uvmem(), where we can stop
 * copying data as soon as we hit an empty entry. I expect typical programs to
 * generally have most active entries in relatively low addresses, and allowing
 * us to skip copying 'obvious' entries is way quicker than copying the whole
 * 2048 byte user virtual memory.
 *
 * Current optimisations also include setting the uvmem to stop on an 8-page
 * boundary, allowing \ref clone_uvmem() to work in eight page increments for a
 * bit of extra speed. Gravestones are only applied to userspace virtual memory,
 * that is kernel and rpc memory regions are ignored.
 *
 * Example of how stuff should look like:
 *
 * Startin with page entries:
 * 1 2 3 4 0 0 0 ...
 *
 * Mapping a page:
 * 1 2 3 4 0 5 0 ...
 *
 * Adding gravestones:
 * 1 2 3 4 G 5 0 ...
 *
 * More testing is probably necessary, as the init tests program doesn't really
 * excercise the mapping utilities.
 */
#define GRAVESTONE VM_G

/**
 * Check if pte is unused, i.e. either a gravestone or empty.
 *
 * @param b pte to check.
 * @return \ref true if \p b is unused.
 */
static bool __unused(pm_t b)
{
	return b == GRAVESTONE || b == NULL;
}

/**
 * Find page table entry corresponding to virtual address.
 *
 * @param b Virtual memory to work in.
 * @param v Virtual address to look for.
 * @param o Address where to return page order to.
 * @return Physical address of page.
 */
static pm_t *__find_vmem(struct vmem *b, vm_t v, enum mm_order *o)
{
	enum mm_order top = __mm_max_order;
	if (o)
		*o = MM_O0;
	do {
		size_t idx = vm_to_index(v, top);
		pm_t pte = (pm_t)b->leaf[idx];

		if (__unused(pte))
			return 0;

		if (is_leaf(pte)) {
			if (o)
				*o = top;

			return (pm_t *)&b->leaf[idx];
		}

		b = (struct vmem *)pte_addr(pte);
	} while (top--);

	return 0;
}

stat_t set_vpage_flags(struct vmem *branch, vm_t vaddr, vmflags_t flags)
{
	enum mm_order order;
	pm_t *pte = __find_vmem(branch, vaddr, &order);
	if (pte) {
		set_bits(*pte, vp_flags(flags));
		return OK;
	}

	return ERR_NF;
}

stat_t clear_vpage_flags(struct vmem *branch, vm_t vaddr, vmflags_t flags)
{
	enum mm_order order;
	pm_t *pte = __find_vmem(branch, vaddr, &order);
	if (pte) {
		clear_bits(*pte, vp_flags(flags));
		return OK;
	}

	return ERR_NF;
}

stat_t mod_vpage(struct vmem *branch, vm_t vaddr, pm_t paddr, vmflags_t flags)
{
	flags |= VM_A | VM_D;

	enum mm_order order;
	pm_t *pte = __find_vmem(branch, vaddr, &order);
	if (pte) {
		*pte = to_pte((pm_t)__pa(paddr), vp_flags(flags));
		return OK;
	}

	return ERR_NF;
}

/* huh, should probably add status flags etc. to all my API functions. Damn, I'm
 * lazy. */
stat_t stat_vpage(struct vmem *branch, vm_t vaddr, pm_t *paddr,
                  enum mm_order *order, vmflags_t *flags)
{
	pm_t *pte = __find_vmem(branch, vaddr, order);
	if (pte) {
		if (paddr)
			*paddr = (pm_t)pte_addr(*pte);

		if (flags)
			*flags = pte_flags(*pte);

		return OK;
	}

	return ERR_NF;
}

/**
 * Create virtual memory leaf page table.
 *
 * @return New virtual memory leaf page table.
 */
static struct vmem *__create_leaf()
{
	pm_t new_leaf = alloc_page(MM_KPAGE);
	memset((void *)new_leaf, 0, sizeof(struct vmem));
	return (struct vmem *)to_pte((pm_t)__pa(new_leaf), VM_V);
}

/**
 * Destroy virtual memory page table branch.
 *
 * @param b Virtual memory to work in.
 */
static void __destroy_branch(struct vmem *b)
{
	if (!b)
		return;

	for (size_t i = 0; i < RISCV_NUM_LEAVES; ++i) {
		if (is_branch(b->leaf[i]))
			__destroy_branch((struct vmem *)pte_addr(b->leaf[i]));
	}

	free_page(MM_KPAGE, (pm_t)__pa(b));
}

/**
 * Add graves if necessary.
 *
 * Checks that the index is within user virtual memory. If it is, change all
 * NULL-entries to gravestones at lower addresses than \p idx.
 *
 * @param branch Top level branch to add graves to.
 * @param idx Index of new entry just added.
 */
static void __add_graves(struct vmem *branch, size_t idx)
{
	if (idx >= CSTACK_PAGE)
		return;

	for (ssize_t i = idx - 1; i >= 0; --i) {
		if (!__unused((pm_t)branch->leaf[i]))
			return;

		branch->leaf[i] = (struct vmem *)GRAVESTONE;
	}
}

stat_t map_vpage(struct vmem *branch, pm_t paddr, vm_t vaddr, vmflags_t flags,
                 enum mm_order order)
{
	struct vmem *root = branch;
	enum mm_order top = __mm_max_order;

	/* eventually we may want to keep track of page accesses,
	 * but for now they're mainly a nuisance. */
	flags |= VM_A | VM_D;

	while (top != order) {
		size_t idx = vm_to_index(vaddr, top);

		if (__unused((pm_t)branch->leaf[idx]))
			branch->leaf[idx] = __create_leaf();

		branch = (struct vmem *)pte_addr(branch->leaf[idx]);
		top--;
	}

	size_t idx = vm_to_index(vaddr, top);
	if (is_branch(
		    branch->leaf[idx])) /* something has gone terribly wrong? */
		__destroy_branch(branch->leaf[idx]);

	branch->leaf[idx] =
		(struct vmem *)to_pte((pm_t)__pa(paddr), vp_flags(flags));

	__add_graves(root, vm_to_index(vaddr, __mm_max_order));
	return OK;
}

/**
 * Remove graves if possible.
 *
 * Checks if \p idx is in user virtual memory. If it is, check if the entry at
 * \p idx was the top page and was turned into a gravestone. If it was, start
 * removing gravestoned until we hit the next top.
 *
 * @param branch Top level branch to remove gravestones in.
 * @param idx Index of just unmapped page at the top level.
 */
static void __remove_graves(struct vmem *branch, size_t idx)
{
	if (idx >= CSTACK_PAGE)
		return;

	if ((pm_t)branch->leaf[idx + 1] != NULL)
		return;

	for (ssize_t i = idx; i >= 0; --i) {
		if ((pm_t)branch->leaf[i] != GRAVESTONE)
			return;

		branch->leaf[i] = NULL;
	}
}

stat_t unmap_vpage(struct vmem *branch, vm_t vaddr)
{
	pm_t *pte = __find_vmem(branch, vaddr, 0);
	if (pte) {
		*pte = GRAVESTONE;
		__remove_graves(branch, vm_to_index(vaddr, __mm_max_order));
		return OK;
	}

	return ERR_NF;
}

void flush_tlb(uintptr_t addr)
{
	__asm__ volatile ("sfence.vma %0, x0\n" : : "r" (addr) : "memory");
}

void flush_tlb_full()
{
	__asm__ volatile ("sfence.vma %0\n" : : "r" (0) : "memory");
}

void flush_tlb_all()
{
	/** @todo this only works on a single core atm. needs to do an IPI */
	__asm__ volatile ("sfence.vma\n" ::: "memory");
}

/**
 * Jump into virtual memory.
 *
 * @param branch Virtual memory address space to jump into.
 * @param m Riscv memory mode to use.
 */
static void __use_vmem(struct vmem *branch, enum mm_mode m)
{
	pm_t satp = branch_to_satp(branch, m);
	csr_write(CSR_SATP, satp);
	flush_tlb_full();
	/** @todo ASID table for maybe faster context switches? */
}

/**
 * Populate \p branch with direct mapping.
 * Mainly intended for bringup and init stuff.
 * Arguably works only for riscv64 and is sort of shared with init.c, so could
 * still be improved.
 *
 * @param branch Branch to populate.
 */
static void __populate_dmap(struct vmem *branch)
{
	size_t flags = VM_V | VM_R | VM_W | VM_X | VM_G | VM_D | VM_A;
	for (size_t i = 0; i < CSTACK_PAGE; ++i)
		branch->leaf[i] =
			(struct vmem *)to_pte(TOP_PAGE_SIZE * i, flags);
}

/** How many base pages we use for the rpc stack. Used fairly often so calculate
 * it at the start and then reference it. */
static size_t rpc_pages;
long riscv_init_stack[4096 / sizeof(long)];
__attribute__((aligned(4096))) struct vmem bootvmem;

struct vmem *direct_mapping()
{
	rpc_pages = order_size(MM_O1) / BASE_PAGE_SIZE;

	__populate_dmap(&bootvmem);
	populate_kvmem(&bootvmem);
	__use_vmem(&bootvmem, DEFAULT_Sv_MODE);

	return &bootvmem;
}


struct vmem *init_vmem(void *fdt)
{
	UNUSED(fdt);
	struct vmem *b = create_vmem();
	__populate_dmap(b);
	/* update which memory branch to use */
	use_vmem(b);
	return b;
}

struct vmem *create_vmem()
{
	struct vmem *b = (struct vmem *)alloc_page(MM_KPAGE);
	memset(b, 0, MM_KPAGE_SIZE);
	populate_kvmem(b);
	return b;
}

stat_t use_vmem(struct vmem *b)
{
	__use_vmem(__pa(b), DEFAULT_Sv_MODE);
	return OK;
}

stat_t destroy_vmem(struct vmem *b)
{
	__destroy_branch(b);
	return OK;
}

stat_t populate_kvmem(struct vmem *b)
{
	size_t flags = VM_V | VM_R | VM_W | VM_X | VM_G | VM_D | VM_A;
	for (size_t i = KSTART_PAGE; i < IO_PAGE; ++i)
		b->leaf[i] = (struct vmem *)to_pte(
			get_ram_base() + TOP_PAGE_SIZE * (i - KSTART_PAGE),
			flags);

	/* map in IO region */
	map_io_dbg(b);
	return OK;
}

#if defined(DEBUG)
vm_t setup_kernel_io(struct vmem *b, vm_t paddr)
{
	pm_t top_page = paddr / TOP_PAGE_SIZE;
	pm_t addr = top_page * TOP_PAGE_SIZE;
	b->leaf[IO_PAGE] = (struct vmem *)to_pte(addr,
	                                         VM_V | VM_R | VM_W | VM_A |
	                                         VM_D);
	/* flush might be necessary when we're in the actual vmem we're
	 * modifying, or during the startup stage where we don't have a tcb yet.
	 * I don't think checking the rpc context is necessary? */
	if (!cur_tcb() || cur_tcb()->proc.vmem == b)
		flush_tlb_full();

	return -TOP_PAGE_SIZE + paddr - addr;
}
#endif

void clone_uvmem(struct vmem * restrict r, struct vmem * restrict b)
{
	size_t i = 0;
	for (; i < CSTACK_PAGE; ++i) {
		struct vmem *t = r->leaf[i + 0];
		if (t == 0)
			break;

		b->leaf[i] = t;
	}

	for (; i < CSTACK_PAGE; ++i) {
		struct vmem *t = b->leaf[i + 0];
		if (t == 0)
			break;

		b->leaf[i] = 0;
	}
}

size_t max_rpc_size()
{
	return SZ_512K;
}

void setup_rpc_stack(struct tcb *t)
{
	/* by default rpc stack is marked inaccessible to generate segfaults on
	 * access so as to ease stack usage tracking */
	vmflags_t flags = VM_V | VM_R | VM_W | VM_U;

	for (size_t i = 0; i < rpc_pages; ++i) {
		pm_t page = alloc_page(BASE_PAGE);
		map_vpage(t->rpc.vmem, page,
		          RPC_STACK_BASE + BASE_PAGE_SIZE * i,
		          flags, BASE_PAGE);

		map_vpage(t->proc.vmem, page,
		          RPC_STACK_BASE + BASE_PAGE_SIZE * i,
		          flags, BASE_PAGE);
	}

	/* we allocated a second order page for rpc stack usage */
	t->rpc_stack = RPC_STACK_BASE + order_size(MM_O1);

	/* slightly hacky maybe but we know the first pte is at RPC_STACK_BASE,
	 * which means that it must also be the leaf */
	t->arch.rpc_leaf = (struct vmem *)__find_vmem(t->rpc.vmem,
	                                              RPC_STACK_BASE,
	                                              BASE_PAGE);
	/* we count downward in base pages */
	t->arch.rpc_idx = rpc_pages;
}

void destroy_rpc_stack(struct tcb *t)
{
	for (size_t i = 0; i < rpc_pages; ++i) {
		pm_t page = 0; enum mm_order order = BASE_PAGE;
		stat_vpage(t->rpc.vmem, RPC_STACK_BASE + BASE_PAGE_SIZE * i,
		           &page, &order, NULL);
		free_page(page, order);
	}
}

bool rpc_stack_empty(pm_t addr)
{
	return addr == RPC_STACK_BASE + (BASE_PAGE_SIZE * rpc_pages);
}

vm_t rpc_position(struct tcb *t)
{
	/** @todo we assume rpc_idx is updated on every segfault of the rpc stack */
	/** @todo hmm, technically speaking we always know that on riscv the base
	 * page size if 4096, would it be a good idea to replace BASE_PAGE_SIZE in
	 * riscv-specific code with a RISCV_BASE_PAGE_SIZE or something? */
	return RPC_STACK_BASE + (BASE_PAGE_SIZE * t->arch.rpc_idx);
}

void mark_rpc_invalid(struct tcb *t, vm_t top)
{
	struct vmem *b = t->arch.rpc_leaf;
	int top_idx = t->arch.rpc_idx;
	int bottom_idx = (top - RPC_STACK_BASE) / BASE_PAGE_SIZE;
	catastrophic_assert(bottom_idx < top_idx);

	while (top_idx != bottom_idx) {
		pm_t *pte = (pm_t *)&b->leaf[top_idx];
		/* make page not accessible from userspace */
		clear_bits(*pte, vp_flags(VM_U));
		top_idx--;
	}

	t->arch.rpc_idx = top_idx;
}

void mark_rpc_valid(struct tcb *t, vm_t bottom)
{
	struct vmem *b = t->arch.rpc_leaf;
	int bottom_idx = t->arch.rpc_idx;
	int top_idx = (bottom - RPC_STACK_BASE) / BASE_PAGE_SIZE;
	catastrophic_assert(bottom_idx < top_idx);

	while (top_idx != bottom_idx) {
		pm_t *pte = (pm_t *)&b->leaf[bottom_idx];
		/* make page accessible from userspace */
		set_bits(*pte, vp_flags(VM_U));
		/* clear used bits */
		clear_bits(*pte, vp_flags(VM_A | VM_D));
		bottom_idx++;
	}

	t->arch.rpc_idx = bottom_idx;
}