Skip to content

Commit 702731c

Browse files
committed
refactor: assert on TLS reset
The reset must be called only once on vcpu drop. Replace errors with asserts in this case. Signed-off-by: Egor Lazarchuk <[email protected]>
1 parent c3f6891 commit 702731c

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/vmm/src/vstate/vcpu.rs

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -126,21 +126,14 @@ impl Vcpu {
126126

127127
/// Deassociates `self` from the current thread.
128128
///
129-
/// Should be called if the current `self` had called `init_thread_local_data()` and
130-
/// now needs to move to a different thread.
131-
///
132-
/// Fails if `self` was not previously associated with the current thread.
133-
fn reset_thread_local_data(&mut self) -> Result<(), VcpuError> {
129+
/// Must be called after `init_thread_local_data`.
130+
fn reset_thread_local_data(&mut self) {
134131
// Best-effort to clean up TLS. If the `Vcpu` was moved to another thread
135132
// _before_ running this, then there is nothing we can do.
136133
Self::TLS_VCPU_PTR.with(|cell: &VcpuCell| {
137-
if let Some(vcpu_ptr) = cell.get() {
138-
if std::ptr::eq(vcpu_ptr, self) {
139-
Self::TLS_VCPU_PTR.with(|cell: &VcpuCell| cell.take());
140-
return Ok(());
141-
}
142-
}
143-
Err(VcpuError::VcpuTlsNotPresent)
134+
let vcpu_ptr = cell.get().unwrap();
135+
assert!(std::ptr::eq(vcpu_ptr, self));
136+
cell.update(|_| None );
144137
})
145138
}
146139

@@ -615,7 +608,7 @@ fn handle_kvm_exit(
615608

616609
impl Drop for Vcpu {
617610
fn drop(&mut self) {
618-
let _ = self.reset_thread_local_data();
611+
self.reset_thread_local_data();
619612
}
620613
}
621614

@@ -1039,7 +1032,7 @@ pub(crate) mod tests {
10391032
}
10401033

10411034
// Reset vcpu TLS.
1042-
vcpu.reset_thread_local_data().unwrap();
1035+
vcpu.reset_thread_local_data();
10431036

10441037
// Running on the TLS vcpu after TLS reset should fail.
10451038
unsafe {
@@ -1050,6 +1043,15 @@ pub(crate) mod tests {
10501043
vcpu.reset_thread_local_data().unwrap_err();
10511044
}
10521045

1046+
#[test]
1047+
#[should_panic]
1048+
fn test_vcpu_tls_double_reset() {
1049+
let (_, _, mut vcpu) = setup_vcpu(0x1000);
1050+
vcpu.init_thread_local_data();
1051+
vcpu.reset_thread_local_data();
1052+
vcpu.reset_thread_local_data();
1053+
}
1054+
10531055
#[test]
10541056
#[should_panic]
10551057
fn test_invalid_tls() {

0 commit comments

Comments
 (0)