aboutsummaryrefslogtreecommitdiff
path: root/arch/x86_64/src/kernel/cpu/control_register.cpp
blob: 41b8cd732104dc20311cff219c03de1684608dcd (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
#include "arch/kernel/cpu/control_register.hpp"

#include "arch/exception_handling/panic.hpp"

#include <type_traits>

namespace teachos::arch::kernel::cpu
{
  auto read_control_register(control_register cr) -> uint64_t
  {
    uint64_t current_value;
    switch (cr)
    {
      case control_register::CR0:
        asm volatile("mov %%cr0, %[output]" : [output] "=r"(current_value));
        break;
      case control_register::CR2:
        asm volatile("mov %%cr2, %[output]" : [output] "=r"(current_value));
        break;
      case control_register::CR3:
        asm volatile("mov %%cr3, %[output]" : [output] "=r"(current_value));
        break;
      case control_register::CR4:
        asm volatile("mov %%cr4, %[output]" : [output] "=r"(current_value));
        break;
    }
    return current_value;
  }

  auto write_control_register(control_register cr, uint64_t new_value) -> void
  {
    switch (cr)
    {
      case control_register::CR0:
        asm volatile("mov %[input], %%cr0"
                     : /* no output from call */
                     : [input] "r"(new_value)
                     : "memory");
        break;
      case control_register::CR2:
        asm volatile("mov %[input], %%cr2"
                     : /* no output from call */
                     : [input] "r"(new_value)
                     : "memory");
        break;
      case control_register::CR3:
        asm volatile("mov %[input], %%cr3"
                     : /* no output from call */
                     : [input] "r"(new_value)
                     : "memory");
        break;
      case control_register::CR4:
        asm volatile("mov %[input], %%cr4"
                     : /* no output from call */
                     : [input] "r"(new_value)
                     : "memory");
        break;
    }
  }

  auto set_cr0_bit(cr0_flags flag) -> void
  {
    auto const cr0 = read_control_register(control_register::CR0);
    write_control_register(control_register::CR0, static_cast<std::underlying_type<cr0_flags>::type>(flag) | cr0);
  }
}  // namespace teachos::arch::kernel::cpu