Skip to content

Commit 9854224

Browse files
committed
Address review feedback on vector state preservation
1 parent dbc8b67 commit 9854224

10 files changed

Lines changed: 178 additions & 152 deletions

File tree

Lines changed: 65 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
// SPDX-FileCopyrightText: 2023 IBM Corporation
22
// SPDX-FileContributor: Wojciech Ozga <woz@zurich.ibm.com>, IBM Research - Zurich
33
// SPDX-License-Identifier: Apache-2.0
4-
use crate::core::architecture::riscv::specification::{CSR_VCSR, CSR_VL, CSR_VLENB, CSR_VSTART, CSR_VTYPE, SR_VS_DIRTY};
5-
use crate::core::architecture::{CSR, HardwareExtension};
4+
5+
use crate::core::architecture::riscv::control_status_registers::ReadWriteRiscvCsr;
6+
use crate::core::architecture::riscv::specification::{CSR_VCSR, CSR_VL, CSR_VSTART, CSR_VTYPE};
67
use crate::core::hardware_setup::HardwareSetup;
7-
use alloc::vec;
8+
use crate::error::Error;
89
use alloc::vec::Vec;
910
use core::arch::asm;
1011

@@ -14,164 +15,117 @@ const NUMBER_OF_VECTOR_REGISTERS: usize = 32;
1415
pub struct VectorUnit {
1516
registers: Vec<u8>,
1617
vlenb: usize,
17-
vl: usize,
18-
vtype: usize,
19-
vstart: usize,
20-
vcsr: usize,
18+
vl: ReadWriteRiscvCsr<CSR_VL>,
19+
vtype: ReadWriteRiscvCsr<CSR_VTYPE>,
20+
vstart: ReadWriteRiscvCsr<CSR_VSTART>,
21+
vcsr: ReadWriteRiscvCsr<CSR_VCSR>,
2122
}
2223

2324
impl VectorUnit {
24-
pub fn empty() -> Self {
25-
if !HardwareSetup::is_extension_supported(HardwareExtension::VectorExtension) {
26-
return Self { registers: Vec::new(), vlenb: 0, vl: 0, vtype: 0, vstart: 0, vcsr: 0 };
27-
}
28-
29-
let old_mstatus = CSR.mstatus.read_and_set_bits(SR_VS_DIRTY);
30-
31-
let vlenb: usize;
32-
unsafe {
33-
asm!(
34-
"csrr {value}, {csr}",
35-
value = out(reg) vlenb,
36-
csr = const CSR_VLENB
37-
);
38-
}
39-
40-
CSR.mstatus.write(old_mstatus);
41-
42-
assert!(vlenb > 0);
43-
44-
let length = NUMBER_OF_VECTOR_REGISTERS.checked_mul(vlenb).expect("Invalid vector register size");
45-
46-
Self { registers: vec![0; length], vlenb, vl: 0, vtype: 0, vstart: 0, vcsr: 0 }
47-
}
48-
49-
unsafe fn validate_vlenb(&self) {
50-
let mut vlenb: usize;
51-
unsafe { asm!("csrr {value}, {csr}", value = out(reg) vlenb, csr = const CSR_VLENB) };
52-
assert_eq!(self.vlenb, vlenb);
53-
assert_eq!(self.registers.len(), NUMBER_OF_VECTOR_REGISTERS * vlenb);
25+
pub fn empty() -> Result<Self, Error> {
26+
let vlenb = HardwareSetup::vector_vlenb()?;
27+
28+
let length = NUMBER_OF_VECTOR_REGISTERS.checked_mul(vlenb).ok_or(Error::InvalidVectorRegisterSize())?;
29+
30+
let mut registers = Vec::new();
31+
registers.try_reserve_exact(length).map_err(|_| Error::NotEnoughMemory())?;
32+
registers.resize(length, 0);
33+
34+
Ok(Self {
35+
registers,
36+
vlenb,
37+
vl: ReadWriteRiscvCsr::new(),
38+
vtype: ReadWriteRiscvCsr::new(),
39+
vstart: ReadWriteRiscvCsr::new(),
40+
vcsr: ReadWriteRiscvCsr::new(),
41+
})
5442
}
5543

44+
/// Saves vector state in main memory.
45+
///
46+
/// # Safety
47+
///
48+
/// The vector extension must be supported and enabled.
5649
pub unsafe fn save_in_main_memory(&mut self) {
57-
unsafe { self.validate_vlenb() };
58-
unsafe {
59-
asm!("csrr {value}, {csr}", value = out(reg) self.vl, csr = const CSR_VL);
60-
asm!("csrr {value}, {csr}", value = out(reg) self.vtype, csr = const CSR_VTYPE);
61-
asm!("csrr {value}, {csr}", value = out(reg) self.vstart, csr = const CSR_VSTART);
62-
asm!("csrr {value}, {csr}", value = out(reg) self.vcsr, csr = const CSR_VCSR);
63-
asm!("csrw {csr}, zero", csr = const CSR_VSTART);
64-
}
50+
self.vl.save_in_main_memory();
51+
self.vtype.save_in_main_memory();
52+
self.vstart.save_in_main_memory();
53+
self.vcsr.save_in_main_memory();
54+
55+
self.vstart.write(0);
6556

6657
macro_rules! store {
6758
($index:literal) => {
6859
unsafe {
6960
asm!(
7061
".option push",
7162
".option arch, +v",
72-
concat!("vs1r.v v", stringify!($index), ", ({address})"),
63+
concat!(
64+
"vs8r.v v",
65+
stringify!($index),
66+
", ({address})"
67+
),
7368
".option pop",
74-
address = in(reg) self.registers.as_mut_ptr().add($index * self.vlenb)
69+
address = in(reg) self.registers
70+
.as_mut_ptr()
71+
.add($index * self.vlenb),
7572
);
7673
}
7774
};
7875
}
7976

8077
store!(0);
81-
store!(1);
82-
store!(2);
83-
store!(3);
84-
store!(4);
85-
store!(5);
86-
store!(6);
87-
store!(7);
8878
store!(8);
89-
store!(9);
90-
store!(10);
91-
store!(11);
92-
store!(12);
93-
store!(13);
94-
store!(14);
95-
store!(15);
9679
store!(16);
97-
store!(17);
98-
store!(18);
99-
store!(19);
100-
store!(20);
101-
store!(21);
102-
store!(22);
103-
store!(23);
10480
store!(24);
105-
store!(25);
106-
store!(26);
107-
store!(27);
108-
store!(28);
109-
store!(29);
110-
store!(30);
111-
store!(31);
11281
}
11382

83+
/// Restores vector state from main memory.
84+
///
85+
/// # Safety
86+
///
87+
/// The vector extension must be supported and enabled.
88+
/// The current hart must have a compatible vector configuration.
11489
pub unsafe fn restore_from_main_memory(&self) {
115-
unsafe { self.validate_vlenb() };
116-
unsafe { asm!("csrw {csr}, zero", csr = const CSR_VSTART) };
90+
self.vstart.write(0);
11791

11892
macro_rules! load {
11993
($index:literal) => {
12094
unsafe {
12195
asm!(
12296
".option push",
12397
".option arch, +v",
124-
concat!("vl1re8.v v", stringify!($index), ", ({address})"),
98+
concat!(
99+
"vl8re8.v v",
100+
stringify!($index),
101+
", ({address})"
102+
),
125103
".option pop",
126-
address = in(reg) self.registers.as_ptr().add($index * self.vlenb)
104+
address = in(reg) self.registers
105+
.as_ptr()
106+
.add($index * self.vlenb),
127107
);
128108
}
129109
};
130110
}
131111

132112
load!(0);
133-
load!(1);
134-
load!(2);
135-
load!(3);
136-
load!(4);
137-
load!(5);
138-
load!(6);
139-
load!(7);
140113
load!(8);
141-
load!(9);
142-
load!(10);
143-
load!(11);
144-
load!(12);
145-
load!(13);
146-
load!(14);
147-
load!(15);
148114
load!(16);
149-
load!(17);
150-
load!(18);
151-
load!(19);
152-
load!(20);
153-
load!(21);
154-
load!(22);
155-
load!(23);
156115
load!(24);
157-
load!(25);
158-
load!(26);
159-
load!(27);
160-
load!(28);
161-
load!(29);
162-
load!(30);
163-
load!(31);
116+
164117
unsafe {
165118
asm!(
166119
".option push",
167120
".option arch, +v",
168121
"vsetvl zero, {saved_vl}, {saved_vtype}",
169122
".option pop",
170-
saved_vl = in(reg) self.vl,
171-
saved_vtype = in(reg) self.vtype
123+
saved_vl = in(reg) self.vl.read_from_main_memory(),
124+
saved_vtype = in(reg) self.vtype.read_from_main_memory(),
172125
);
173-
asm!("csrw {csr}, {value}", csr = const CSR_VCSR, value = in(reg) self.vcsr);
174-
asm!("csrw {csr}, {value}", csr = const CSR_VSTART, value = in(reg) self.vstart);
175126
}
127+
128+
self.vcsr.restore_from_main_memory();
129+
self.vstart.restore_from_main_memory();
176130
}
177131
}

‎security-monitor/src/core/architecture/riscv/hart_architectural_state.rs‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::core::architecture::riscv::specification::*;
66
use crate::core::architecture::riscv::{
77
ControlStatusRegisters, FloatingPointUnit, GeneralPurposeRegister, GeneralPurposeRegisters, VectorUnit,
88
};
9+
use crate::error::Error;
910

1011
/// Defines the state of a processor's core (hart) when stored in main memory.
1112
#[repr(C)]
@@ -14,26 +15,26 @@ pub struct HartArchitecturalState {
1415
csrs: ControlStatusRegisters,
1516
fprs: FloatingPointUnit,
1617
sstc: SupervisorTimerExtension,
17-
vector: VectorUnit,
18+
vrs: VectorUnit,
1819
}
1920

2021
impl HartArchitecturalState {
21-
pub fn empty() -> Self {
22-
Self {
22+
pub fn empty() -> Result<Self, Error> {
23+
Ok(Self {
2324
gprs: GeneralPurposeRegisters::empty(),
2425
csrs: ControlStatusRegisters::empty(),
2526
fprs: FloatingPointUnit::empty(),
2627
sstc: SupervisorTimerExtension::empty(),
27-
vector: VectorUnit::empty(),
28-
}
28+
vrs: VectorUnit::empty()?,
29+
})
2930
}
3031

31-
pub fn vector(&self) -> &VectorUnit {
32-
&self.vector
32+
pub fn vrs(&self) -> &VectorUnit {
33+
&self.vrs
3334
}
3435

35-
pub fn vector_mut(&mut self) -> &mut VectorUnit {
36-
&mut self.vector
36+
pub fn vrs_mut(&mut self) -> &mut VectorUnit {
37+
&mut self.vrs
3738
}
3839

3940
pub fn set_gprs(&mut self, gprs: GeneralPurposeRegisters) {

‎security-monitor/src/core/architecture/riscv/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// SPDX-FileContributor: Wojciech Ozga <woz@zurich.ibm.com>, IBM Research - Zurich
33
// SPDX-License-Identifier: Apache-2.0
44
#![allow(unused)]
5+
pub(crate) use control_status_registers::ReadWriteRiscvCsr;
56
pub use control_status_registers::{CSR, ControlStatusRegister, ControlStatusRegisters};
67
pub use extensions::HardwareExtension;
78
pub use extensions::compressed_instructions::decode_result_register;

‎security-monitor/src/core/control_data/confidential_hart.rs‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -67,23 +67,23 @@ impl ConfidentialHart {
6767
/// confidential hart has been assigned to a hardware hart for execution. A dummy confidential hart has the id of the hardware hart it
6868
/// represents. This is required to track information on which hardware hart a stolen confidential hart executes (for example to
6969
/// interrupt it with IPI).
70-
pub fn dummy(hardware_hart_id: usize) -> Self {
70+
pub fn dummy(hardware_hart_id: usize) -> Result<Self, Error> {
7171
// We set the lifecycle state of the dummy hart to `Started` because this state will be used as the state of the confidential hart
7272
// that has been assigned to physical hart. Specifically, after a confidential hart gets assigned to hardware hart, the confidential
7373
// VM will be left with a dummy hart. Any other code or request that will inspect the state of the (stolen) confidential hart, will
7474
// in reality look into the state of the dummy hart which will correctly say that the confidential hart is in the `Started` state.
75-
Self {
75+
Ok(Self {
7676
confidential_vm_id: None,
77-
confidential_hart_state: HartArchitecturalState::empty(),
77+
confidential_hart_state: HartArchitecturalState::empty()?,
7878
lifecycle_state: HartLifecycleState::Started,
7979
resumable_operation: None,
8080
id: hardware_hart_id,
81-
}
81+
})
8282
}
8383

8484
/// Constructs a confidential hart with the state after a reset.
85-
pub fn from_vm_hart_reset(id: usize, htimedelta: usize, shared_memory: &NaclSharedMemory) -> Self {
86-
let mut confidential_hart_state = HartArchitecturalState::empty();
85+
pub fn from_vm_hart_reset(id: usize, htimedelta: usize, shared_memory: &NaclSharedMemory) -> Result<Self, Error> {
86+
let mut confidential_hart_state = HartArchitecturalState::empty()?;
8787
confidential_hart_state.csrs_mut().mstatus.save_value_in_main_memory(Self::INITIAL_MSTATUS);
8888
confidential_hart_state.csrs_mut().sstatus.save_value_in_main_memory(Self::INITIAL_SSTATUS);
8989
confidential_hart_state.csrs_mut().hstatus.save_value_in_main_memory(Self::INITIAL_HSTATUS);
@@ -121,22 +121,22 @@ impl ConfidentialHart {
121121
confidential_hart_state.csrs_mut().vsstatus.enable_bits_on_saved_value(SR_VS_INITIAL);
122122
}
123123

124-
Self {
124+
Ok(Self {
125125
confidential_vm_id: None,
126126
confidential_hart_state,
127127
lifecycle_state: HartLifecycleState::Stopped,
128128
resumable_operation: None,
129129
id,
130-
}
130+
})
131131
}
132132

133133
/// Constructs a confidential hart with the state of the non-confidential hart that made a call to promote the VM to confidential VM
134134
pub fn from_vm_hart(
135135
id: usize, program_counter: usize, fdt_address: &ConfidentialVmPhysicalAddress, htimedelta: usize, shared_memory: &NaclSharedMemory,
136-
) -> Self {
136+
) -> Result<Self, Error> {
137137
// We first create a confidential hart in the reset state and then fill this state with the runtime state of the hart that made a
138138
// call to promote to confidential VM. This state consists of GPRs and VS-level CSRs.
139-
let mut confidential_hart = Self::from_vm_hart_reset(id, htimedelta, shared_memory);
139+
let mut confidential_hart = Self::from_vm_hart_reset(id, htimedelta, shared_memory)?;
140140
let confidential_hart_state = &mut confidential_hart.confidential_hart_state;
141141
confidential_hart_state.set_gprs(shared_memory.gprs());
142142
confidential_hart_state.gprs_mut().write(GeneralPurposeRegister::a0, id);
@@ -152,7 +152,7 @@ impl ConfidentialHart {
152152
// Store the program counter of the VM, so that we can resume confidential VM at the point it became promoted.
153153
confidential_hart_state.csrs_mut().mepc.save_value_in_main_memory(program_counter);
154154
confidential_hart.lifecycle_state = HartLifecycleState::Started;
155-
confidential_hart
155+
Ok(confidential_hart)
156156
}
157157

158158
/// Saves the state of the confidential hart in the main memory. This is part of the heavy context switch.
@@ -178,8 +178,11 @@ impl ConfidentialHart {
178178
}
179179

180180
if HardwareSetup::is_extension_supported(HardwareExtension::VectorExtension) {
181+
// Enable the vector unit in mstatus to access vector
182+
// registers and execute vector instructions.
181183
self.csrs().mstatus.read_and_set_bits(SR_VS_DIRTY);
182-
unsafe { self.confidential_hart_state.vector_mut().save_in_main_memory() };
184+
185+
unsafe { self.confidential_hart_state.vrs_mut().save_in_main_memory() };
183186
}
184187
}
185188

@@ -198,8 +201,11 @@ impl ConfidentialHart {
198201
}
199202

200203
if HardwareSetup::is_extension_supported(HardwareExtension::VectorExtension) {
204+
// Enable the vector unit in mstatus to access vector
205+
// registers and execute vector instructions.
201206
self.csrs().mstatus.read_and_set_bits(SR_VS_DIRTY);
202-
unsafe { self.confidential_hart_state.vector().restore_from_main_memory() };
207+
208+
unsafe { self.confidential_hart_state.vrs().restore_from_main_memory() };
203209
}
204210
}
205211

0 commit comments

Comments
 (0)