x86_64/registers/control.rs
1//! Functions to read and write control registers.
2
3pub use super::model_specific::{Efer, EferFlags};
4use bitflags::bitflags;
5
6/// Various control flags modifying the basic operation of the CPU.
7#[derive(Debug)]
8pub struct Cr0;
9
10bitflags! {
11 /// Configuration flags of the [`Cr0`] register.
12 #[repr(transparent)]
13 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
14 pub struct Cr0Flags: u64 {
15 /// Enables protected mode.
16 const PROTECTED_MODE_ENABLE = 1;
17 /// Enables monitoring of the coprocessor, typical for x87 instructions.
18 ///
19 /// Controls (together with the [`TASK_SWITCHED`](Cr0Flags::TASK_SWITCHED)
20 /// flag) whether a `wait` or `fwait` instruction should cause an `#NE` exception.
21 const MONITOR_COPROCESSOR = 1 << 1;
22 /// Force all x87 and MMX instructions to cause an `#NE` exception.
23 const EMULATE_COPROCESSOR = 1 << 2;
24 /// Automatically set to 1 on _hardware_ task switch.
25 ///
26 /// This flags allows lazily saving x87/MMX/SSE instructions on hardware context switches.
27 const TASK_SWITCHED = 1 << 3;
28 /// Indicates support of 387DX math coprocessor instructions.
29 ///
30 /// Always set on all recent x86 processors, cannot be cleared.
31 const EXTENSION_TYPE = 1 << 4;
32 /// Enables the native (internal) error reporting mechanism for x87 FPU errors.
33 const NUMERIC_ERROR = 1 << 5;
34 /// Controls whether supervisor-level writes to read-only pages are inhibited.
35 ///
36 /// When set, it is not possible to write to read-only pages from ring 0.
37 const WRITE_PROTECT = 1 << 16;
38 /// Enables automatic usermode alignment checking if [`RFlags::ALIGNMENT_CHECK`] is also set.
39 const ALIGNMENT_MASK = 1 << 18;
40 /// Ignored, should always be unset.
41 ///
42 /// Must be unset if [`CACHE_DISABLE`](Cr0Flags::CACHE_DISABLE) is unset.
43 /// Older CPUs used this to control write-back/write-through cache strategy.
44 const NOT_WRITE_THROUGH = 1 << 29;
45 /// Disables some processor caches, specifics are model-dependent.
46 const CACHE_DISABLE = 1 << 30;
47 /// Enables paging.
48 ///
49 /// If this bit is set, [`PROTECTED_MODE_ENABLE`](Cr0Flags::PROTECTED_MODE_ENABLE) must be set.
50 const PAGING = 1 << 31;
51 }
52}
53
54/// Contains the Page Fault Linear Address (PFLA).
55///
56/// When a page fault occurs, the CPU sets this register to the faulting virtual address.
57#[derive(Debug)]
58pub struct Cr2;
59
60/// Contains the physical address of the highest-level page table.
61#[derive(Debug)]
62pub struct Cr3;
63
64bitflags! {
65 /// Controls cache settings for the highest-level page table.
66 ///
67 /// Unused if paging is disabled or if [`PCID`](Cr4Flags::PCID) is enabled.
68 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
69 pub struct Cr3Flags: u64 {
70 /// Use a writethrough cache policy for the table (otherwise a writeback policy is used).
71 const PAGE_LEVEL_WRITETHROUGH = 1 << 3;
72 /// Disable caching for the table.
73 const PAGE_LEVEL_CACHE_DISABLE = 1 << 4;
74 }
75}
76
77/// Contains various control flags that enable architectural extensions, and
78/// indicate support for specific processor capabilities.
79#[derive(Debug)]
80pub struct Cr4;
81
82bitflags! {
83 /// Configuration flags of the [`Cr4`] register.
84 #[repr(transparent)]
85 #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
86 pub struct Cr4Flags: u64 {
87 /// Enables hardware-supported performance enhancements for software running in
88 /// virtual-8086 mode.
89 const VIRTUAL_8086_MODE_EXTENSIONS = 1;
90 /// Enables support for protected-mode virtual interrupts.
91 const PROTECTED_MODE_VIRTUAL_INTERRUPTS = 1 << 1;
92 /// When set, only privilege-level 0 can execute the `RDTSC` or `RDTSCP` instructions.
93 const TIMESTAMP_DISABLE = 1 << 2;
94 /// Enables I/O breakpoint capability and enforces treatment of `DR4` and `DR5` registers
95 /// as reserved.
96 const DEBUGGING_EXTENSIONS = 1 << 3;
97 /// Enables the use of 4MB physical frames; ignored if
98 /// [`PHYSICAL_ADDRESS_EXTENSION`](Cr4Flags::PHYSICAL_ADDRESS_EXTENSION)
99 /// is set (so always ignored in long mode).
100 const PAGE_SIZE_EXTENSION = 1 << 4;
101 /// Enables physical address extensions and 2MB physical frames. Required in long mode.
102 const PHYSICAL_ADDRESS_EXTENSION = 1 << 5;
103 /// Enables the machine-check exception mechanism.
104 const MACHINE_CHECK_EXCEPTION = 1 << 6;
105 /// Enables the global page feature, allowing some page translations to
106 /// be marked as global (see [`PageTableFlags::GLOBAL`]).
107 const PAGE_GLOBAL = 1 << 7;
108 /// Allows software running at any privilege level to use the `RDPMC` instruction.
109 const PERFORMANCE_MONITOR_COUNTER = 1 << 8;
110 /// Enables the use of legacy SSE instructions; allows using `FXSAVE`/`FXRSTOR` for saving
111 /// processor state of 128-bit media instructions.
112 const OSFXSR = 1 << 9;
113 /// Enables the SIMD floating-point exception (`#XF`) for handling unmasked 256-bit and
114 /// 128-bit media floating-point errors.
115 const OSXMMEXCPT_ENABLE = 1 << 10;
116 /// Prevents the execution of the `SGDT`, `SIDT`, `SLDT`, `SMSW`, and `STR` instructions by
117 /// user-mode software.
118 const USER_MODE_INSTRUCTION_PREVENTION = 1 << 11;
119 /// Enables 5-level paging on supported CPUs (Intel Only).
120 const L5_PAGING = 1 << 12;
121 /// Enables VMX instructions (Intel Only).
122 const VIRTUAL_MACHINE_EXTENSIONS = 1 << 13;
123 /// Enables SMX instructions (Intel Only).
124 const SAFER_MODE_EXTENSIONS = 1 << 14;
125 /// Enables software running in 64-bit mode at any privilege level to read and write
126 /// the FS.base and GS.base hidden segment register state.
127 const FSGSBASE = 1 << 16;
128 /// Enables process-context identifiers (PCIDs).
129 const PCID = 1 << 17;
130 /// Enables extended processor state management instructions, including `XGETBV` and `XSAVE`.
131 const OSXSAVE = 1 << 18;
132 /// Enables the Key Locker feature (Intel Only).
133 ///
134 /// This enables creation and use of opaque AES key handles; see the
135 /// [Intel Key Locker Specification](https://software.intel.com/content/www/us/en/develop/download/intel-key-locker-specification.html)
136 /// for more information.
137 const KEY_LOCKER = 1 << 19;
138 /// Prevents the execution of instructions that reside in pages accessible by user-mode
139 /// software when the processor is in supervisor-mode.
140 const SUPERVISOR_MODE_EXECUTION_PROTECTION = 1 << 20;
141 /// Enables restrictions for supervisor-mode software when reading data from user-mode
142 /// pages.
143 const SUPERVISOR_MODE_ACCESS_PREVENTION = 1 << 21;
144 /// Enables protection keys for user-mode pages.
145 ///
146 /// Also enables access to the PKRU register (via the `RDPKRU`/`WRPKRU`
147 /// instructions) to set user-mode protection key access controls.
148 const PROTECTION_KEY_USER = 1 << 22;
149 /// Enables Control-flow Enforcement Technology (CET)
150 ///
151 /// This enables the shadow stack feature, ensuring return addresses read
152 /// via `RET` and `IRET` have not been corrupted.
153 const CONTROL_FLOW_ENFORCEMENT = 1 << 23;
154 /// Enables protection keys for supervisor-mode pages (Intel Only).
155 ///
156 /// Also enables the `IA32_PKRS` MSR to set supervisor-mode protection
157 /// key access controls.
158 const PROTECTION_KEY_SUPERVISOR = 1 << 24;
159 }
160}
161
162#[cfg(all(feature = "instructions", target_arch = "x86_64"))]
163mod x86_64 {
164 use super::*;
165 use crate::{
166 addr::VirtAddrNotValid, instructions::tlb::Pcid, structures::paging::PhysFrame, PhysAddr,
167 VirtAddr,
168 };
169 use core::arch::asm;
170
171 impl Cr0 {
172 /// Read the current set of CR0 flags.
173 #[inline]
174 pub fn read() -> Cr0Flags {
175 Cr0Flags::from_bits_truncate(Self::read_raw())
176 }
177
178 /// Read the current raw CR0 value.
179 #[inline]
180 pub fn read_raw() -> u64 {
181 let value: u64;
182
183 unsafe {
184 asm!("mov {}, cr0", out(reg) value, options(nomem, nostack, preserves_flags));
185 }
186
187 value
188 }
189
190 /// Write CR0 flags.
191 ///
192 /// Preserves the value of reserved fields.
193 ///
194 /// ## Safety
195 ///
196 /// This function is unsafe because it's possible to violate memory
197 /// safety through it, e.g. by disabling paging.
198 #[inline]
199 pub unsafe fn write(flags: Cr0Flags) {
200 let old_value = Self::read_raw();
201 let reserved = old_value & !(Cr0Flags::all().bits());
202 let new_value = reserved | flags.bits();
203
204 unsafe {
205 Self::write_raw(new_value);
206 }
207 }
208
209 /// Write raw CR0 flags.
210 ///
211 /// Does _not_ preserve any values, including reserved fields.
212 ///
213 /// ## Safety
214 ///
215 /// This function is unsafe because it's possible to violate memory
216 /// safety through it, e.g. by disabling paging.
217 #[inline]
218 pub unsafe fn write_raw(value: u64) {
219 unsafe {
220 asm!("mov cr0, {}", in(reg) value, options(nostack, preserves_flags));
221 }
222 }
223
224 /// Updates CR0 flags.
225 ///
226 /// Preserves the value of reserved fields.
227 ///
228 /// ## Safety
229 ///
230 /// This function is unsafe because it's possible to violate memory
231 /// safety through it, e.g. by disabling paging.
232 #[inline]
233 pub unsafe fn update<F>(f: F)
234 where
235 F: FnOnce(&mut Cr0Flags),
236 {
237 let mut flags = Self::read();
238 f(&mut flags);
239 unsafe {
240 Self::write(flags);
241 }
242 }
243 }
244
245 impl Cr2 {
246 /// Read the current page fault linear address from the CR2 register.
247 ///
248 /// # Errors
249 ///
250 /// This method returns a [`VirtAddrNotValid`] error if the CR2 register contains a
251 /// non-canonical address. Call [`Cr2::read_raw`] to handle such cases.
252 #[inline]
253 pub fn read() -> Result<VirtAddr, VirtAddrNotValid> {
254 VirtAddr::try_new(Self::read_raw())
255 }
256
257 /// Read the current page fault linear address from the CR2 register as a raw `u64`.
258 #[inline]
259 pub fn read_raw() -> u64 {
260 let value: u64;
261
262 unsafe {
263 asm!("mov {}, cr2", out(reg) value, options(nomem, nostack, preserves_flags));
264 }
265
266 value
267 }
268 }
269
270 impl Cr3 {
271 /// Read the current P4 table address from the CR3 register.
272 #[inline]
273 pub fn read() -> (PhysFrame, Cr3Flags) {
274 let (frame, value) = Cr3::read_raw();
275 let flags = Cr3Flags::from_bits_truncate(value.into());
276 (frame, flags)
277 }
278
279 /// Read the current P4 table address from the CR3 register
280 #[inline]
281 pub fn read_raw() -> (PhysFrame, u16) {
282 let value: u64;
283
284 unsafe {
285 asm!("mov {}, cr3", out(reg) value, options(nomem, nostack, preserves_flags));
286 }
287
288 let addr = PhysAddr::new(value & 0x_000f_ffff_ffff_f000);
289 let frame = PhysFrame::containing_address(addr);
290 (frame, (value & 0xFFF) as u16)
291 }
292
293 /// Read the current P4 table address from the CR3 register along with PCID.
294 /// The correct functioning of this requires CR4.PCIDE = 1.
295 /// See [`Cr4Flags::PCID`]
296 #[inline]
297 pub fn read_pcid() -> (PhysFrame, Pcid) {
298 let (frame, value) = Cr3::read_raw();
299 (frame, Pcid::new(value).unwrap())
300 }
301
302 /// Write a new P4 table address into the CR3 register.
303 ///
304 /// ## Safety
305 ///
306 /// Changing the level 4 page table is unsafe, because it's possible to violate memory safety by
307 /// changing the page mapping.
308 #[inline]
309 pub unsafe fn write(frame: PhysFrame, flags: Cr3Flags) {
310 unsafe {
311 Cr3::write_raw_impl(false, frame, flags.bits() as u16);
312 }
313 }
314
315 /// Write a new P4 table address into the CR3 register.
316 ///
317 /// ## Safety
318 ///
319 /// Changing the level 4 page table is unsafe, because it's possible to violate memory safety by
320 /// changing the page mapping.
321 /// [`Cr4Flags::PCID`] must be set before calling this method.
322 #[inline]
323 pub unsafe fn write_pcid(frame: PhysFrame, pcid: Pcid) {
324 unsafe {
325 Cr3::write_raw_impl(false, frame, pcid.value());
326 }
327 }
328
329 /// Write a new P4 table address into the CR3 register without flushing existing TLB entries for
330 /// the PCID.
331 ///
332 /// ## Safety
333 ///
334 /// Changing the level 4 page table is unsafe, because it's possible to violate memory safety by
335 /// changing the page mapping.
336 /// [`Cr4Flags::PCID`] must be set before calling this method.
337 #[inline]
338 pub unsafe fn write_pcid_no_flush(frame: PhysFrame, pcid: Pcid) {
339 unsafe {
340 Cr3::write_raw_impl(true, frame, pcid.value());
341 }
342 }
343
344 /// Write a new P4 table address into the CR3 register.
345 ///
346 /// ## Safety
347 ///
348 /// Changing the level 4 page table is unsafe, because it's possible to violate memory safety by
349 /// changing the page mapping.
350 #[inline]
351 pub unsafe fn write_raw(frame: PhysFrame, val: u16) {
352 unsafe { Self::write_raw_impl(false, frame, val) }
353 }
354
355 #[inline]
356 unsafe fn write_raw_impl(top_bit: bool, frame: PhysFrame, val: u16) {
357 let addr = frame.start_address();
358 let value = ((top_bit as u64) << 63) | addr.as_u64() | val as u64;
359
360 unsafe {
361 asm!("mov cr3, {}", in(reg) value, options(nostack, preserves_flags));
362 }
363 }
364 }
365
366 impl Cr4 {
367 /// Read the current set of CR4 flags.
368 #[inline]
369 pub fn read() -> Cr4Flags {
370 Cr4Flags::from_bits_truncate(Self::read_raw())
371 }
372
373 /// Read the current raw CR4 value.
374 #[inline]
375 pub fn read_raw() -> u64 {
376 let value: u64;
377
378 unsafe {
379 asm!("mov {}, cr4", out(reg) value, options(nomem, nostack, preserves_flags));
380 }
381
382 value
383 }
384
385 /// Write CR4 flags.
386 ///
387 /// Preserves the value of reserved fields.
388 ///
389 /// ## Safety
390 ///
391 /// This function is unsafe because it's possible to violate memory
392 /// safety through it, e.g. by overwriting the physical address extension
393 /// flag.
394 #[inline]
395 pub unsafe fn write(flags: Cr4Flags) {
396 let old_value = Self::read_raw();
397 let reserved = old_value & !(Cr4Flags::all().bits());
398 let new_value = reserved | flags.bits();
399
400 unsafe {
401 Self::write_raw(new_value);
402 }
403 }
404
405 /// Write raw CR4 flags.
406 ///
407 /// Does _not_ preserve any values, including reserved fields.
408 ///
409 /// ## Safety
410 ///
411 /// This function is unsafe because it's possible to violate memory
412 /// safety through it, e.g. by overwriting the physical address extension
413 /// flag.
414 #[inline]
415 pub unsafe fn write_raw(value: u64) {
416 unsafe {
417 asm!("mov cr4, {}", in(reg) value, options(nostack, preserves_flags));
418 }
419 }
420
421 /// Updates CR4 flags.
422 ///
423 /// Preserves the value of reserved fields.
424 ///
425 /// ## Safety
426 ///
427 /// This function is unsafe because it's possible to violate memory
428 /// safety through it, e.g. by overwriting the physical address extension
429 /// flag.
430 #[inline]
431 pub unsafe fn update<F>(f: F)
432 where
433 F: FnOnce(&mut Cr4Flags),
434 {
435 let mut flags = Self::read();
436 f(&mut flags);
437 unsafe {
438 Self::write(flags);
439 }
440 }
441 }
442}