blob: 235c0e000ef7fffffb2ffe8b655ec0efe8d69f8e [file] [log] [blame]
Alice Wang4dd20932023-05-26 13:47:16 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Hardware management of the access flag and dirty state.
16
Alice Wang3fa9b802023-06-06 07:52:31 +000017use super::page_table::is_leaf_pte;
18use super::util::flush_region;
Alice Wang4dd20932023-05-26 13:47:16 +000019use crate::{isb, read_sysreg, write_sysreg};
Alice Wang3fa9b802023-06-06 07:52:31 +000020use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion};
Alice Wang4dd20932023-05-26 13:47:16 +000021
22/// Sets whether the hardware management of access and dirty state is enabled with
23/// the given boolean.
24pub fn set_dbm_enabled(enabled: bool) {
25 if !dbm_available() {
26 return;
27 }
28 // TCR_EL1.{HA,HD} bits controlling hardware management of access and dirty state
29 const TCR_EL1_HA_HD_BITS: usize = 3 << 39;
30
31 let mut tcr = read_sysreg!("tcr_el1");
32 if enabled {
33 tcr |= TCR_EL1_HA_HD_BITS
34 } else {
35 tcr &= !TCR_EL1_HA_HD_BITS
36 };
37 // Safe because it writes to a system register and does not affect Rust.
38 unsafe { write_sysreg!("tcr_el1", tcr) }
39 isb!();
40}
41
42/// Returns `true` if hardware dirty state management is available.
43fn dbm_available() -> bool {
44 if !cfg!(feature = "cpu_feat_hafdbs") {
45 return false;
46 }
47 // Hardware dirty bit management available flag (ID_AA64MMFR1_EL1.HAFDBS[1])
48 const DBM_AVAILABLE: usize = 1 << 1;
49 read_sysreg!("id_aa64mmfr1_el1") & DBM_AVAILABLE != 0
50}
Alice Wang3fa9b802023-06-06 07:52:31 +000051
52/// Flushes a memory range the descriptor refers to, if the descriptor is in writable-dirty state.
53/// As the return type is required by the crate `aarch64_paging`, we cannot address the lint
54/// issue `clippy::result_unit_err`.
55#[allow(clippy::result_unit_err)]
56pub fn flush_dirty_range(
57 va_range: &MemoryRegion,
58 desc: &mut Descriptor,
59 level: usize,
60) -> Result<(), ()> {
61 // Only flush ranges corresponding to dirty leaf PTEs.
62 let flags = desc.flags().ok_or(())?;
63 if !is_leaf_pte(&flags, level) {
64 return Ok(());
65 }
66 if !flags.contains(Attributes::READ_ONLY) {
67 flush_region(va_range.start().0, va_range.len());
68 }
69 Ok(())
70}