1#include <math/align.h>
2#include <mem/alloc.h>
3#include <mem/buddy.h>
4#include <mem/page.h>
5#include <mem/pmm.h>
6#include <mem/vmm.h>
7#include <string.h>
8
9#include "internal.h"
10#include "mem/buddy/internal.h"
11
12bool domain_arena_push(struct domain_arena *arena, struct buddy_page *page) {
13 bool success = false;
14 enum irql irql = spin_lock(lock: &arena->lock);
15
16 /* A page entering the arena must currently be allocated (tag NONE). If it
17 * is already cached (ARENA) or in the buddy (BUDDY), this is a physical
18 * double-free, which would otherwise hand the same page to two owners. */
19 page_assert_tag(BUDDY_PAGE_TO_PAGE(page), expected: PAGE_TAG_NONE);
20
21 size_t next = (arena->tail + 1) % arena->capacity;
22 if (next != arena->head) {
23 arena->pages[arena->tail] = page;
24 arena->tail = next;
25 success = true;
26 }
27
28 if (success) {
29 page_set_tag(BUDDY_PAGE_TO_PAGE(page), tag: PAGE_TAG_ARENA);
30 atomic_fetch_add_explicit(&arena->num_pages, 1, memory_order_relaxed);
31 }
32
33 spin_unlock(lock: &arena->lock, old: irql);
34 return success;
35}
36
37struct buddy_page *domain_arena_pop(struct domain_arena *arena) {
38 struct buddy_page *page = NULL;
39 enum irql irql = spin_lock(lock: &arena->lock);
40
41 if (arena->head != arena->tail) {
42 page = arena->pages[arena->head];
43 arena->head = (arena->head + 1) % arena->capacity;
44 }
45
46 if (page) {
47 /* Must have been cached by a push; transition back to allocated. */
48 page_assert_tag(BUDDY_PAGE_TO_PAGE(page), expected: PAGE_TAG_ARENA);
49 page_set_tag(BUDDY_PAGE_TO_PAGE(page), tag: PAGE_TAG_NONE);
50 atomic_fetch_sub_explicit(&arena->num_pages, 1, memory_order_relaxed);
51 }
52
53 spin_unlock(lock: &arena->lock, old: irql);
54 return page;
55}
56