Serenity Operating System
1/*
2 * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#pragma once
8
9#include <AK/Error.h>
10#include <AK/IntrusiveRedBlackTree.h>
11#include <Kernel/Locking/Spinlock.h>
12#include <Kernel/Memory/Region.h>
13#include <Kernel/Memory/VirtualRange.h>
14#include <Kernel/VirtualAddress.h>
15
16namespace Kernel::Memory {
17
18enum class RandomizeVirtualAddress {
19 No,
20 Yes,
21};
22
23// RegionTree represents a virtual address space.
24// It is used by MemoryManager for kernel VM and by AddressSpace for user VM.
25// Regions are stored in an intrusive data structure and there are no allocations when interacting with it.
26class RegionTree {
27 AK_MAKE_NONCOPYABLE(RegionTree);
28 AK_MAKE_NONMOVABLE(RegionTree);
29
30public:
31 explicit RegionTree(VirtualRange total_range)
32 : m_total_range(total_range)
33 {
34 }
35
36 ~RegionTree();
37
38 auto& regions() { return m_regions; }
39 auto const& regions() const { return m_regions; }
40
41 VirtualRange total_range() const { return m_total_range; }
42
43 ErrorOr<void> place_anywhere(Region&, RandomizeVirtualAddress, size_t size, size_t alignment = PAGE_SIZE);
44 ErrorOr<void> place_specifically(Region&, VirtualRange const&);
45
46 void delete_all_regions_assuming_they_are_unmapped();
47
48 bool remove(Region&);
49
50 Region* find_region_containing(VirtualAddress);
51 Region* find_region_containing(VirtualRange);
52
53private:
54 ErrorOr<VirtualRange> allocate_range_anywhere(size_t size, size_t alignment = PAGE_SIZE);
55 ErrorOr<VirtualRange> allocate_range_specific(VirtualAddress base, size_t size);
56 ErrorOr<VirtualRange> allocate_range_randomized(size_t size, size_t alignment = PAGE_SIZE);
57
58 IntrusiveRedBlackTree<&Region::m_tree_node> m_regions;
59 VirtualRange const m_total_range;
60};
61
62}