-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathmod.rs
More file actions
336 lines (271 loc) · 11.9 KB
/
mod.rs
File metadata and controls
336 lines (271 loc) · 11.9 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
//! This module holds abstractions that enable tracking the areas dirtied by writes of a specified
//! length to a given offset. In particular, this is used to track write accesses within a
//! `GuestMemoryRegion` object, and the resulting bitmaps can then be aggregated to build the
//! global view for an entire `GuestMemory` object.
#[cfg(feature = "backend-bitmap")]
mod backend;
use std::fmt::Debug;
use crate::{GuestMemory, GuestMemoryRegion};
#[cfg(feature = "backend-bitmap")]
pub use backend::{ArcSlice, AtomicBitmap, RefSlice};
/// Trait implemented by types that support creating `BitmapSlice` objects.
pub trait WithBitmapSlice<'a> {
/// Type of the bitmap slice.
type S: BitmapSlice;
}
/// Trait used to represent that a `BitmapSlice` is a `Bitmap` itself, but also satisfies the
/// restriction that slices created from it have the same type as `Self`.
pub trait BitmapSlice: Bitmap + Clone + Debug + for<'a> WithBitmapSlice<'a, S = Self> {}
/// Common bitmap operations. Using Higher-Rank Trait Bounds (HRTBs) to effectively define
/// an associated type that has a lifetime parameter, without tagging the `Bitmap` trait with
/// a lifetime as well.
///
/// Using an associated type allows implementing the `Bitmap` and `BitmapSlice` functionality
/// as a zero-cost abstraction when providing trivial implementations such as the one
/// defined for `()`.
// These methods represent the core functionality that's required by `vm-memory` abstractions
// to implement generic tracking logic, as well as tests that can be reused by different backends.
pub trait Bitmap: for<'a> WithBitmapSlice<'a> {
/// Mark the memory range specified by the given `offset` and `len` as dirtied.
fn mark_dirty(&self, offset: usize, len: usize);
/// Check whether the specified `offset` is marked as dirty.
fn dirty_at(&self, offset: usize) -> bool;
/// Return a `<Self as WithBitmapSlice>::S` slice of the current bitmap, starting at
/// the specified `offset`.
fn slice_at(&self, offset: usize) -> <Self as WithBitmapSlice>::S;
}
/// A `Bitmap` that can be created starting from an initial size.
// Cannot be a part of the Bitmap trait itself because it cannot be implemented for BaseSlice
pub trait NewBitmap: Bitmap + Default {
/// Create a new object based on the specified length in bytes.
fn with_len(len: usize) -> Self;
}
/// A no-op `Bitmap` implementation that can be provided for backends that do not actually
/// require the tracking functionality.
impl WithBitmapSlice<'_> for () {
type S = Self;
}
impl BitmapSlice for () {}
impl Bitmap for () {
fn mark_dirty(&self, _offset: usize, _len: usize) {}
fn dirty_at(&self, _offset: usize) -> bool {
false
}
fn slice_at(&self, _offset: usize) -> Self {}
}
impl NewBitmap for () {
fn with_len(_len: usize) -> Self {}
}
/// A `Bitmap` and `BitmapSlice` implementation for `Option<B>`.
impl<'a, B> WithBitmapSlice<'a> for Option<B>
where
B: WithBitmapSlice<'a>,
{
type S = Option<B::S>;
}
impl<B: BitmapSlice> BitmapSlice for Option<B> {}
impl<B: Bitmap> Bitmap for Option<B> {
fn mark_dirty(&self, offset: usize, len: usize) {
if let Some(inner) = self {
inner.mark_dirty(offset, len)
}
}
fn dirty_at(&self, offset: usize) -> bool {
if let Some(inner) = self {
return inner.dirty_at(offset);
}
false
}
fn slice_at(&self, offset: usize) -> Option<<B as WithBitmapSlice>::S> {
if let Some(inner) = self {
return Some(inner.slice_at(offset));
}
None
}
}
/// Helper type alias for referring to the `BitmapSlice` concrete type associated with
/// an object `B: WithBitmapSlice<'a>`.
pub type BS<'a, B> = <B as WithBitmapSlice<'a>>::S;
/// Helper type alias for referring to the `BitmapSlice` concrete type associated with
/// the memory regions of an object `M: GuestMemory`.
pub type MS<'a, M> = BS<'a, <<M as GuestMemory>::R as GuestMemoryRegion>::B>;
#[cfg(test)]
#[cfg(feature = "backend-bitmap")]
pub(crate) mod tests {
use super::*;
use std::mem::size_of_val;
use std::sync::atomic::Ordering;
use crate::{Bytes, VolatileMemory};
#[cfg(all(feature = "backend-mmap", target_family = "unix"))]
use crate::{GuestAddress, MemoryRegionAddress};
// Helper method to check whether a specified range is clean.
pub fn range_is_clean<B: Bitmap>(b: &B, start: usize, len: usize) -> bool {
(start..start + len).all(|offset| !b.dirty_at(offset))
}
// Helper method to check whether a specified range is dirty.
pub fn range_is_dirty<B: Bitmap>(b: &B, start: usize, len: usize) -> bool {
(start..start + len).all(|offset| b.dirty_at(offset))
}
pub fn check_range<B: Bitmap>(b: &B, start: usize, len: usize, clean: bool) -> bool {
if clean {
range_is_clean(b, start, len)
} else {
range_is_dirty(b, start, len)
}
}
// Helper method that tests a generic `B: Bitmap` implementation. It assumes `b` covers
// an area of length at least 0x800.
pub fn test_bitmap<B: Bitmap>(b: &B) {
let len = 0x800;
let dirty_offset = 0x400;
let dirty_len = 0x100;
// Some basic checks.
let s = b.slice_at(dirty_offset);
assert!(range_is_clean(b, 0, len));
assert!(range_is_clean(&s, 0, dirty_len));
b.mark_dirty(dirty_offset, dirty_len);
assert!(range_is_dirty(b, dirty_offset, dirty_len));
assert!(range_is_dirty(&s, 0, dirty_len));
}
// `F` and `G` stand for the same closure types as described in the `BytesHelper` comment.
// The `step` parameter represents the offset that's added the the current address after
// performing each access. It provides finer grained control when testing tracking
// implementations that aggregate entire ranges for accounting purposes (for example, doing
// tracking at the page level).
pub fn test_bytes<F, G, M, A>(bytes: &M, check_range_fn: F, address_fn: G, step: usize)
where
F: Fn(&M, usize, usize, bool) -> bool,
G: Fn(usize) -> A,
M: Bytes<A>,
<M as Bytes<A>>::E: Debug,
{
const BUF_SIZE: usize = 1024;
let buf = vec![1u8; 1024];
let mut dirty_offset = 0x1000;
let val = 1u64;
// Test `write`.
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, true));
assert_eq!(
bytes
.write(buf.as_slice(), address_fn(dirty_offset))
.unwrap(),
BUF_SIZE
);
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, false));
// Test `write_slice`.
dirty_offset += step;
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, true));
bytes
.write_slice(buf.as_slice(), address_fn(dirty_offset))
.unwrap();
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, false));
// Test `write_obj`.
dirty_offset += step;
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, true));
bytes.write_obj(val, address_fn(dirty_offset)).unwrap();
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, false));
// Test `store`.
dirty_offset += step;
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, true));
bytes
.store(val, address_fn(dirty_offset), Ordering::Relaxed)
.unwrap();
assert!(check_range_fn(bytes, dirty_offset, BUF_SIZE, false));
}
// This function and the next are currently conditionally compiled because we only use
// them to test the mmap-based backend implementations for now. Going forward, the generic
// test functions defined here can be placed in a separate module (i.e. `test_utilities`)
// which is gated by a feature and can be used for testing purposes by other crates as well.
#[cfg(all(feature = "backend-mmap", target_family = "unix"))]
fn test_guest_memory_region<R: GuestMemoryRegion>(region: &R) {
let dirty_addr = MemoryRegionAddress(0x0);
let val = 123u64;
let dirty_len = size_of_val(&val);
let slice = region.get_slice(dirty_addr, dirty_len).unwrap();
assert!(range_is_clean(®ion.bitmap(), 0, region.len() as usize));
assert!(range_is_clean(slice.bitmap(), 0, dirty_len));
region.write_obj(val, dirty_addr).unwrap();
assert!(range_is_dirty(
®ion.bitmap(),
dirty_addr.0 as usize,
dirty_len
));
assert!(range_is_dirty(slice.bitmap(), 0, dirty_len));
// Finally, let's invoke the generic tests for `R: Bytes`. It's ok to pass the same
// `region` handle because `test_bytes` starts performing writes after the range that's
// been already dirtied in the first part of this test.
test_bytes(
region,
|r: &R, start: usize, len: usize, clean: bool| {
check_range(&r.bitmap(), start, len, clean)
},
|offset| MemoryRegionAddress(offset as u64),
0x1000,
);
}
#[cfg(all(feature = "backend-mmap", target_family = "unix"))]
// Assumptions about M generated by f ...
pub fn test_guest_memory_and_region<M, F>(f: F)
where
M: GuestMemory,
F: Fn() -> M,
{
let m = f();
let dirty_addr = GuestAddress(0x1000);
let val = 123u64;
let dirty_len = size_of_val(&val);
let (region, region_addr) = m.to_region_addr(dirty_addr).unwrap();
let mut slices = m.get_slices(dirty_addr, dirty_len);
let slice = slices.next().unwrap().unwrap();
assert!(slices.next().is_none());
assert!(range_is_clean(®ion.bitmap(), 0, region.len() as usize));
assert!(range_is_clean(slice.bitmap(), 0, dirty_len));
m.write_obj(val, dirty_addr).unwrap();
assert!(range_is_dirty(
®ion.bitmap(),
region_addr.0 as usize,
dirty_len
));
assert!(range_is_dirty(slice.bitmap(), 0, dirty_len));
// Now let's invoke the tests for the inner `GuestMemoryRegion` type.
test_guest_memory_region(f().find_region(GuestAddress(0)).unwrap());
// Finally, let's invoke the generic tests for `Bytes`.
let check_range_closure = |m: &M, start: usize, len: usize, clean: bool| -> bool {
m.get_slices(GuestAddress(start as u64), len).all(|r| {
let slice = r.unwrap();
check_range(slice.bitmap(), 0, slice.len(), clean)
})
};
test_bytes(
&f(),
check_range_closure,
|offset| GuestAddress(offset as u64),
0x1000,
);
}
pub fn test_volatile_memory<M: VolatileMemory>(m: &M) {
assert!(m.len() >= 0x8000);
let dirty_offset = 0x1000;
let val = 123u64;
let dirty_len = size_of_val(&val);
let get_ref_offset = 0x2000;
let array_ref_offset = 0x3000;
let s1 = m.as_volatile_slice();
let s2 = m.get_slice(dirty_offset, dirty_len).unwrap();
assert!(range_is_clean(s1.bitmap(), 0, s1.len()));
assert!(range_is_clean(s2.bitmap(), 0, s2.len()));
s1.write_obj(val, dirty_offset).unwrap();
assert!(range_is_dirty(s1.bitmap(), dirty_offset, dirty_len));
assert!(range_is_dirty(s2.bitmap(), 0, dirty_len));
let v_ref = m.get_ref::<u64>(get_ref_offset).unwrap();
assert!(range_is_clean(s1.bitmap(), get_ref_offset, dirty_len));
v_ref.store(val);
assert!(range_is_dirty(s1.bitmap(), get_ref_offset, dirty_len));
let arr_ref = m.get_array_ref::<u64>(array_ref_offset, 1).unwrap();
assert!(range_is_clean(s1.bitmap(), array_ref_offset, dirty_len));
arr_ref.store(0, val);
assert!(range_is_dirty(s1.bitmap(), array_ref_offset, dirty_len));
}
}