forked from rust-vmm/vm-memory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvolatile_memory.rs
More file actions
2271 lines (2023 loc) · 78.4 KB
/
volatile_memory.rs
File metadata and controls
2271 lines (2023 loc) · 78.4 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Portions Copyright 2019 Red Hat, Inc.
//
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRT-PARTY file.
//
// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
//! Types for volatile access to memory.
//!
//! Two of the core rules for safe rust is no data races and no aliased mutable references.
//! `VolatileRef` and `VolatileSlice`, along with types that produce those which implement
//! `VolatileMemory`, allow us to sidestep that rule by wrapping pointers that absolutely have to be
//! accessed volatile. Some systems really do need to operate on shared memory and can't have the
//! compiler reordering or eliding access because it has no visibility into what other systems are
//! doing with that hunk of memory.
//!
//! For the purposes of maintaining safety, volatile memory has some rules of its own:
//!
//! 1. No references or slices to volatile memory (`&` or `&mut`).
//!
//! 2. Access should always been done with a volatile read or write.
//!
//! The First rule is because having references of any kind to memory considered volatile would
//! violate pointer aliasing. The second is because unvolatile accesses are inherently undefined if
//! done concurrently without synchronization. With volatile access we know that the compiler has
//! not reordered or elided the access.
use std::cmp::min;
use std::io;
use std::marker::PhantomData;
use std::mem::{align_of, size_of};
use std::ptr::copy;
use std::ptr::{read_volatile, write_volatile};
use std::result;
use std::sync::atomic::Ordering;
use crate::atomic_integer::AtomicInteger;
use crate::bitmap::{Bitmap, BitmapSlice, BS};
use crate::{AtomicAccess, ByteValued, Bytes};
#[cfg(all(feature = "backend-mmap", feature = "xen", target_family = "unix"))]
use crate::mmap::xen::{MmapXen as MmapInfo, MmapXenSlice};
#[cfg(not(feature = "xen"))]
type MmapInfo = std::marker::PhantomData<()>;
use crate::io::{retry_eintr, ReadVolatile, WriteVolatile};
use copy_slice_impl::{copy_from_volatile_slice, copy_to_volatile_slice};
/// `VolatileMemory` related errors.
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// `addr` is out of bounds of the volatile memory slice.
#[error("address 0x{addr:x} is out of bounds")]
OutOfBounds { addr: usize },
/// Taking a slice at `base` with `offset` would overflow `usize`.
#[error("address 0x{base:x} offset by 0x{offset:x} would overflow")]
Overflow { base: usize, offset: usize },
/// Taking a slice whose size overflows `usize`.
#[error("{nelements:?} elements of size {size:?} would overflow a usize")]
TooBig { nelements: usize, size: usize },
/// Trying to obtain a misaligned reference.
#[error("address 0x{addr:x} is not aligned to {alignment:?}")]
Misaligned { addr: usize, alignment: usize },
/// Writing to memory failed
#[error("{0}")]
IOError(io::Error),
/// Incomplete read or write
#[error("only used {completed} bytes in {expected} long buffer")]
PartialBuffer { expected: usize, completed: usize },
}
/// Result of volatile memory operations.
pub type Result<T> = result::Result<T, Error>;
/// Convenience function for computing `base + offset`.
///
/// # Errors
///
/// Returns [`Err(Error::Overflow)`](enum.Error.html#variant.Overflow) in case `base + offset`
/// exceeds `usize::MAX`.
///
/// # Examples
///
/// ```
/// # use vm_memory::volatile_memory::compute_offset;
/// #
/// assert_eq!(108, compute_offset(100, 8).unwrap());
/// assert!(compute_offset(usize::MAX, 6).is_err());
/// ```
pub fn compute_offset(base: usize, offset: usize) -> Result<usize> {
match base.checked_add(offset) {
None => Err(Error::Overflow { base, offset }),
Some(m) => Ok(m),
}
}
/// Types that support raw volatile access to their data.
pub trait VolatileMemory {
/// Type used for dirty memory tracking.
type B: Bitmap;
/// Gets the size of this slice.
fn len(&self) -> usize;
/// Check whether the region is empty.
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns a [`VolatileSlice`](struct.VolatileSlice.html) of `count` bytes starting at
/// `offset`.
///
/// Note that the property `get_slice(offset, count).len() == count` MUST NOT be
/// relied on for the correctness of unsafe code. This is a safe function inside of a
/// safe trait, and implementors are under no obligation to follow its documentation.
fn get_slice(&self, offset: usize, count: usize) -> Result<VolatileSlice<BS<Self::B>>>;
/// Gets a slice of memory for the entire region that supports volatile access.
fn as_volatile_slice(&self) -> VolatileSlice<BS<Self::B>> {
self.get_slice(0, self.len()).unwrap()
}
/// Gets a `VolatileRef` at `offset`.
fn get_ref<T: ByteValued>(&self, offset: usize) -> Result<VolatileRef<T, BS<Self::B>>> {
let slice = self.get_slice(offset, size_of::<T>())?;
assert_eq!(
slice.len(),
size_of::<T>(),
"VolatileMemory::get_slice(offset, count) returned slice of length != count."
);
// SAFETY: This is safe because the invariants of the constructors of VolatileSlice ensure that
// slice.addr is valid memory of size slice.len(). The assert above ensures that
// the length of the slice is exactly enough to hold one `T`. Lastly, the lifetime of the
// returned VolatileRef match that of the VolatileSlice returned by get_slice and thus the
// lifetime one `self`.
unsafe {
Ok(VolatileRef::with_bitmap(
slice.addr,
slice.bitmap,
slice.mmap,
))
}
}
/// Returns a [`VolatileArrayRef`](struct.VolatileArrayRef.html) of `n` elements starting at
/// `offset`.
fn get_array_ref<T: ByteValued>(
&self,
offset: usize,
n: usize,
) -> Result<VolatileArrayRef<T, BS<Self::B>>> {
// Use isize to avoid problems with ptr::offset and ptr::add down the line.
let nbytes = isize::try_from(n)
.ok()
.and_then(|n| n.checked_mul(size_of::<T>() as isize))
.ok_or(Error::TooBig {
nelements: n,
size: size_of::<T>(),
})?;
let slice = self.get_slice(offset, nbytes as usize)?;
assert_eq!(
slice.len(),
nbytes as usize,
"VolatileMemory::get_slice(offset, count) returned slice of length != count."
);
// SAFETY: This is safe because the invariants of the constructors of VolatileSlice ensure that
// slice.addr is valid memory of size slice.len(). The assert above ensures that
// the length of the slice is exactly enough to hold `n` instances of `T`. Lastly, the lifetime of the
// returned VolatileArrayRef match that of the VolatileSlice returned by get_slice and thus the
// lifetime one `self`.
unsafe {
Ok(VolatileArrayRef::with_bitmap(
slice.addr,
n,
slice.bitmap,
slice.mmap,
))
}
}
/// Returns a reference to an instance of `T` at `offset`.
///
/// # Safety
/// To use this safely, the caller must guarantee that there are no other
/// users of the given chunk of memory for the lifetime of the result.
///
/// # Errors
///
/// If the resulting pointer is not aligned, this method will return an
/// [`Error`](enum.Error.html).
unsafe fn aligned_as_ref<T: ByteValued>(&self, offset: usize) -> Result<&T> {
let slice = self.get_slice(offset, size_of::<T>())?;
slice.check_alignment(align_of::<T>())?;
assert_eq!(
slice.len(),
size_of::<T>(),
"VolatileMemory::get_slice(offset, count) returned slice of length != count."
);
// SAFETY: This is safe because the invariants of the constructors of VolatileSlice ensure that
// slice.addr is valid memory of size slice.len(). The assert above ensures that
// the length of the slice is exactly enough to hold one `T`.
// Dereferencing the pointer is safe because we check the alignment above, and the invariants
// of this function ensure that no aliasing pointers exist. Lastly, the lifetime of the
// returned VolatileArrayRef match that of the VolatileSlice returned by get_slice and thus the
// lifetime one `self`.
unsafe { Ok(&*(slice.addr as *const T)) }
}
/// Returns a mutable reference to an instance of `T` at `offset`. Mutable accesses performed
/// using the resulting reference are not automatically accounted for by the dirty bitmap
/// tracking functionality.
///
/// # Safety
///
/// To use this safely, the caller must guarantee that there are no other
/// users of the given chunk of memory for the lifetime of the result.
///
/// # Errors
///
/// If the resulting pointer is not aligned, this method will return an
/// [`Error`](enum.Error.html).
unsafe fn aligned_as_mut<T: ByteValued>(&self, offset: usize) -> Result<&mut T> {
let slice = self.get_slice(offset, size_of::<T>())?;
slice.check_alignment(align_of::<T>())?;
assert_eq!(
slice.len(),
size_of::<T>(),
"VolatileMemory::get_slice(offset, count) returned slice of length != count."
);
// SAFETY: This is safe because the invariants of the constructors of VolatileSlice ensure that
// slice.addr is valid memory of size slice.len(). The assert above ensures that
// the length of the slice is exactly enough to hold one `T`.
// Dereferencing the pointer is safe because we check the alignment above, and the invariants
// of this function ensure that no aliasing pointers exist. Lastly, the lifetime of the
// returned VolatileArrayRef match that of the VolatileSlice returned by get_slice and thus the
// lifetime one `self`.
unsafe { Ok(&mut *(slice.addr as *mut T)) }
}
/// Returns a reference to an instance of `T` at `offset`. Mutable accesses performed
/// using the resulting reference are not automatically accounted for by the dirty bitmap
/// tracking functionality.
///
/// # Errors
///
/// If the resulting pointer is not aligned, this method will return an
/// [`Error`](enum.Error.html).
fn get_atomic_ref<T: AtomicInteger>(&self, offset: usize) -> Result<&T> {
let slice = self.get_slice(offset, size_of::<T>())?;
slice.check_alignment(align_of::<T>())?;
assert_eq!(
slice.len(),
size_of::<T>(),
"VolatileMemory::get_slice(offset, count) returned slice of length != count."
);
// SAFETY: This is safe because the invariants of the constructors of VolatileSlice ensure that
// slice.addr is valid memory of size slice.len(). The assert above ensures that
// the length of the slice is exactly enough to hold one `T`.
// Dereferencing the pointer is safe because we check the alignment above. Lastly, the lifetime of the
// returned VolatileArrayRef match that of the VolatileSlice returned by get_slice and thus the
// lifetime one `self`.
unsafe { Ok(&*(slice.addr as *const T)) }
}
/// Returns the sum of `base` and `offset` if it is valid to access a range of `offset`
/// bytes starting at `base`.
///
/// Specifically, allows accesses of length 0 at the end of a slice:
///
/// ```rust
/// # use vm_memory::{VolatileMemory, VolatileSlice};
/// let mut arr = [1, 2, 3];
/// let slice = VolatileSlice::from(arr.as_mut_slice());
///
/// assert_eq!(slice.compute_end_offset(3, 0).unwrap(), 3);
/// ```
fn compute_end_offset(&self, base: usize, offset: usize) -> Result<usize> {
let mem_end = compute_offset(base, offset)?;
if mem_end > self.len() {
return Err(Error::OutOfBounds { addr: mem_end });
}
Ok(mem_end)
}
}
impl<'a> From<&'a mut [u8]> for VolatileSlice<'a, ()> {
fn from(value: &'a mut [u8]) -> Self {
// SAFETY: Since we construct the VolatileSlice from a rust slice, we know that
// the memory at addr `value as *mut u8` is valid for reads and writes (because mutable
// reference) of len `value.len()`. Since the `VolatileSlice` inherits the lifetime `'a`,
// it is not possible to access/mutate `value` while the VolatileSlice is alive.
//
// Note that it is possible for multiple aliasing sub slices of this `VolatileSlice`s to
// be created through `VolatileSlice::subslice`. This is OK, as pointers are allowed to
// alias, and it is impossible to get rust-style references from a `VolatileSlice`.
unsafe { VolatileSlice::new(value.as_mut_ptr(), value.len()) }
}
}
#[repr(C, packed)]
struct Packed<T>(T);
/// A guard to perform mapping and protect unmapping of the memory.
#[derive(Debug)]
pub struct PtrGuard {
addr: *mut u8,
len: usize,
// This isn't used anymore, but it protects the slice from getting unmapped while in use.
// Once this goes out of scope, the memory is unmapped automatically.
#[cfg(all(feature = "xen", target_family = "unix"))]
_slice: MmapXenSlice,
}
#[allow(clippy::len_without_is_empty)]
impl PtrGuard {
#[allow(unused_variables)]
fn new(mmap: Option<&MmapInfo>, addr: *mut u8, write: bool, len: usize) -> Self {
#[cfg(all(feature = "xen", target_family = "unix"))]
let (addr, _slice) = {
let prot = if write {
libc::PROT_WRITE
} else {
libc::PROT_READ
};
let slice = MmapInfo::mmap(mmap, addr, prot, len);
(slice.addr(), slice)
};
Self {
addr,
len,
#[cfg(all(feature = "xen", target_family = "unix"))]
_slice,
}
}
fn read(mmap: Option<&MmapInfo>, addr: *mut u8, len: usize) -> Self {
Self::new(mmap, addr, false, len)
}
/// Returns a non-mutable pointer to the beginning of the slice.
pub fn as_ptr(&self) -> *const u8 {
self.addr
}
/// Gets the length of the mapped region.
pub fn len(&self) -> usize {
self.len
}
}
/// A mutable guard to perform mapping and protect unmapping of the memory.
#[derive(Debug)]
pub struct PtrGuardMut(PtrGuard);
#[allow(clippy::len_without_is_empty)]
impl PtrGuardMut {
fn write(mmap: Option<&MmapInfo>, addr: *mut u8, len: usize) -> Self {
Self(PtrGuard::new(mmap, addr, true, len))
}
/// Returns a mutable pointer to the beginning of the slice. Mutable accesses performed
/// using the resulting pointer are not automatically accounted for by the dirty bitmap
/// tracking functionality.
pub fn as_ptr(&self) -> *mut u8 {
self.0.addr
}
/// Gets the length of the mapped region.
pub fn len(&self) -> usize {
self.0.len
}
}
/// A slice of raw memory that supports volatile access.
#[derive(Clone, Copy, Debug)]
pub struct VolatileSlice<'a, B = ()> {
addr: *mut u8,
size: usize,
bitmap: B,
mmap: Option<&'a MmapInfo>,
}
impl<'a> VolatileSlice<'a, ()> {
/// Creates a slice of raw memory that must support volatile access.
///
/// # Safety
///
/// To use this safely, the caller must guarantee that the memory at `addr` is `size` bytes long
/// and is available for the duration of the lifetime of the new `VolatileSlice`. The caller
/// must also guarantee that all other users of the given chunk of memory are using volatile
/// accesses.
pub unsafe fn new(addr: *mut u8, size: usize) -> VolatileSlice<'a> {
Self::with_bitmap(addr, size, (), None)
}
}
impl<'a, B: BitmapSlice> VolatileSlice<'a, B> {
/// Creates a slice of raw memory that must support volatile access, and uses the provided
/// `bitmap` object for dirty page tracking.
///
/// # Safety
///
/// To use this safely, the caller must guarantee that the memory at `addr` is `size` bytes long
/// and is available for the duration of the lifetime of the new `VolatileSlice`. The caller
/// must also guarantee that all other users of the given chunk of memory are using volatile
/// accesses.
pub unsafe fn with_bitmap(
addr: *mut u8,
size: usize,
bitmap: B,
mmap: Option<&'a MmapInfo>,
) -> VolatileSlice<'a, B> {
VolatileSlice {
addr,
size,
bitmap,
mmap,
}
}
/// Returns a guard for the pointer to the underlying memory.
pub fn ptr_guard(&self) -> PtrGuard {
PtrGuard::read(self.mmap, self.addr, self.len())
}
/// Returns a mutable guard for the pointer to the underlying memory.
pub fn ptr_guard_mut(&self) -> PtrGuardMut {
PtrGuardMut::write(self.mmap, self.addr, self.len())
}
/// Gets the size of this slice.
pub fn len(&self) -> usize {
self.size
}
/// Checks if the slice is empty.
pub fn is_empty(&self) -> bool {
self.size == 0
}
/// Borrows the inner `BitmapSlice`.
pub fn bitmap(&self) -> &B {
&self.bitmap
}
/// Divides one slice into two at an index.
///
/// # Example
///
/// ```
/// # use vm_memory::{VolatileMemory, VolatileSlice};
/// #
/// # // Create a buffer
/// # let mut mem = [0u8; 32];
/// #
/// # // Get a `VolatileSlice` from the buffer
/// let vslice = VolatileSlice::from(&mut mem[..]);
///
/// let (start, end) = vslice.split_at(8).expect("Could not split VolatileSlice");
/// assert_eq!(8, start.len());
/// assert_eq!(24, end.len());
/// ```
pub fn split_at(&self, mid: usize) -> Result<(Self, Self)> {
let end = self.offset(mid)?;
let start =
// SAFETY: safe because self.offset() already checked the bounds
unsafe { VolatileSlice::with_bitmap(self.addr, mid, self.bitmap.clone(), self.mmap) };
Ok((start, end))
}
/// Returns a subslice of this [`VolatileSlice`](struct.VolatileSlice.html) starting at
/// `offset` with `count` length.
///
/// The returned subslice is a copy of this slice with the address increased by `offset` bytes
/// and the size set to `count` bytes.
pub fn subslice(&self, offset: usize, count: usize) -> Result<Self> {
let _ = self.compute_end_offset(offset, count)?;
// SAFETY: This is safe because the pointer is range-checked by compute_end_offset, and
// the lifetime is the same as the original slice.
unsafe {
Ok(VolatileSlice::with_bitmap(
self.addr.add(offset),
count,
self.bitmap.slice_at(offset),
self.mmap,
))
}
}
/// Returns a subslice of this [`VolatileSlice`](struct.VolatileSlice.html) starting at
/// `offset`.
///
/// The returned subslice is a copy of this slice with the address increased by `count` bytes
/// and the size reduced by `count` bytes.
pub fn offset(&self, count: usize) -> Result<VolatileSlice<'a, B>> {
let new_addr = (self.addr as usize)
.checked_add(count)
.ok_or(Error::Overflow {
base: self.addr as usize,
offset: count,
})?;
let new_size = self
.size
.checked_sub(count)
.ok_or(Error::OutOfBounds { addr: new_addr })?;
// SAFETY: Safe because the memory has the same lifetime and points to a subset of the
// memory of the original slice.
unsafe {
Ok(VolatileSlice::with_bitmap(
self.addr.add(count),
new_size,
self.bitmap.slice_at(count),
self.mmap,
))
}
}
/// Copies as many elements of type `T` as possible from this slice to `buf`.
///
/// Copies `self.len()` or `buf.len()` times the size of `T` bytes, whichever is smaller,
/// to `buf`. The copy happens from smallest to largest address in `T` sized chunks
/// using volatile reads.
///
/// # Examples
///
/// ```
/// # use vm_memory::{VolatileMemory, VolatileSlice};
/// #
/// let mut mem = [0u8; 32];
/// let vslice = VolatileSlice::from(&mut mem[..]);
/// let mut buf = [5u8; 16];
/// let res = vslice.copy_to(&mut buf[..]);
///
/// assert_eq!(16, res);
/// for &v in &buf[..] {
/// assert_eq!(v, 0);
/// }
/// ```
pub fn copy_to<T>(&self, buf: &mut [T]) -> usize
where
T: ByteValued,
{
// A fast path for u8/i8
if size_of::<T>() == 1 {
let total = buf.len().min(self.len());
// SAFETY:
// - dst is valid for writes of at least `total`, since total <= buf.len()
// - src is valid for reads of at least `total` as total <= self.len()
// - The regions are non-overlapping as `src` points to guest memory and `buf` is
// a slice and thus has to live outside of guest memory (there can be more slices to
// guest memory without violating rust's aliasing rules)
// - size is always a multiple of alignment, so treating *mut T as *mut u8 is fine
unsafe { copy_from_volatile_slice(buf.as_mut_ptr() as *mut u8, self, total) }
} else {
let count = self.size / size_of::<T>();
let source = self.get_array_ref::<T>(0, count).unwrap();
source.copy_to(buf)
}
}
/// Copies as many bytes as possible from this slice to the provided `slice`.
///
/// The copies happen in an undefined order.
///
/// # Examples
///
/// ```
/// # use vm_memory::{VolatileMemory, VolatileSlice};
/// #
/// # // Create a buffer
/// # let mut mem = [0u8; 32];
/// #
/// # // Get a `VolatileSlice` from the buffer
/// # let vslice = VolatileSlice::from(&mut mem[..]);
/// #
/// vslice.copy_to_volatile_slice(
/// vslice
/// .get_slice(16, 16)
/// .expect("Could not get VolatileSlice"),
/// );
/// ```
pub fn copy_to_volatile_slice<S: BitmapSlice>(&self, slice: VolatileSlice<S>) {
// SAFETY: Safe because the pointers are range-checked when the slices
// are created, and they never escape the VolatileSlices.
// FIXME: ... however, is it really okay to mix non-volatile
// operations such as copy with read_volatile and write_volatile?
unsafe {
let count = min(self.size, slice.size);
copy(self.addr, slice.addr, count);
slice.bitmap.mark_dirty(0, count);
}
}
/// Copies as many elements of type `T` as possible from `buf` to this slice.
///
/// The copy happens from smallest to largest address in `T` sized chunks using volatile writes.
///
/// # Examples
///
/// ```
/// # use vm_memory::{VolatileMemory, VolatileSlice};
/// #
/// let mut mem = [0u8; 32];
/// let vslice = VolatileSlice::from(&mut mem[..]);
///
/// let buf = [5u8; 64];
/// vslice.copy_from(&buf[..]);
///
/// for i in 0..4 {
/// let val = vslice
/// .get_ref::<u32>(i * 4)
/// .expect("Could not get value")
/// .load();
/// assert_eq!(val, 0x05050505);
/// }
/// ```
pub fn copy_from<T>(&self, buf: &[T])
where
T: ByteValued,
{
// A fast path for u8/i8
if size_of::<T>() == 1 {
let total = buf.len().min(self.len());
// SAFETY:
// - dst is valid for writes of at least `total`, since total <= self.len()
// - src is valid for reads of at least `total` as total <= buf.len()
// - The regions are non-overlapping as `dst` points to guest memory and `buf` is
// a slice and thus has to live outside of guest memory (there can be more slices to
// guest memory without violating rust's aliasing rules)
// - size is always a multiple of alignment, so treating *mut T as *mut u8 is fine
unsafe { copy_to_volatile_slice(self, buf.as_ptr() as *const u8, total) };
} else {
let count = self.size / size_of::<T>();
// It's ok to use unwrap here because `count` was computed based on the current
// length of `self`.
let dest = self.get_array_ref::<T>(0, count).unwrap();
// No need to explicitly call `mark_dirty` after this call because
// `VolatileArrayRef::copy_from` already takes care of that.
dest.copy_from(buf);
};
}
/// Checks if the current slice is aligned at `alignment` bytes.
fn check_alignment(&self, alignment: usize) -> Result<()> {
// Check that the desired alignment is a power of two.
debug_assert!((alignment & (alignment - 1)) == 0);
if ((self.addr as usize) & (alignment - 1)) != 0 {
return Err(Error::Misaligned {
addr: self.addr as usize,
alignment,
});
}
Ok(())
}
}
impl<B: BitmapSlice> Bytes<usize> for VolatileSlice<'_, B> {
type E = Error;
/// # Examples
/// * Write a slice of size 5 at offset 1020 of a 1024-byte `VolatileSlice`.
///
/// ```
/// # use vm_memory::{Bytes, VolatileMemory, VolatileSlice};
/// #
/// let mut mem = [0u8; 1024];
/// let vslice = VolatileSlice::from(&mut mem[..]);
/// let res = vslice.write(&[1, 2, 3, 4, 5], 1020);
///
/// assert!(res.is_ok());
/// assert_eq!(res.unwrap(), 4);
/// ```
fn write(&self, mut buf: &[u8], addr: usize) -> Result<usize> {
if buf.is_empty() {
return Ok(0);
}
if addr >= self.size {
return Err(Error::OutOfBounds { addr });
}
// NOTE: the duality of read <-> write here is correct. This is because we translate a call
// "volatile_slice.write(buf)" (e.g. "write to volatile_slice from buf") into
// "buf.read_volatile(volatile_slice)" (e.g. read from buf into volatile_slice)
buf.read_volatile(&mut self.offset(addr)?)
}
/// # Examples
/// * Read a slice of size 16 at offset 1010 of a 1024-byte `VolatileSlice`.
///
/// ```
/// # use vm_memory::{Bytes, VolatileMemory, VolatileSlice};
/// #
/// let mut mem = [0u8; 1024];
/// let vslice = VolatileSlice::from(&mut mem[..]);
/// let buf = &mut [0u8; 16];
/// let res = vslice.read(buf, 1010);
///
/// assert!(res.is_ok());
/// assert_eq!(res.unwrap(), 14);
/// ```
fn read(&self, mut buf: &mut [u8], addr: usize) -> Result<usize> {
if buf.is_empty() {
return Ok(0);
}
if addr >= self.size {
return Err(Error::OutOfBounds { addr });
}
// NOTE: The duality of read <-> write here is correct. This is because we translate a call
// volatile_slice.read(buf) (e.g. read from volatile_slice into buf) into
// "buf.write_volatile(volatile_slice)" (e.g. write into buf from volatile_slice)
// Both express data transfer from volatile_slice to buf.
buf.write_volatile(&self.offset(addr)?)
}
/// # Examples
/// * Write a slice at offset 256.
///
/// ```
/// # use vm_memory::{Bytes, VolatileMemory, VolatileSlice};
/// #
/// # // Create a buffer
/// # let mut mem = [0u8; 1024];
/// #
/// # // Get a `VolatileSlice` from the buffer
/// # let vslice = VolatileSlice::from(&mut mem[..]);
/// #
/// let res = vslice.write_slice(&[1, 2, 3, 4, 5], 256);
///
/// assert!(res.is_ok());
/// assert_eq!(res.unwrap(), ());
/// ```
fn write_slice(&self, buf: &[u8], addr: usize) -> Result<()> {
// `mark_dirty` called within `self.write`.
let len = self.write(buf, addr)?;
if len != buf.len() {
return Err(Error::PartialBuffer {
expected: buf.len(),
completed: len,
});
}
Ok(())
}
/// # Examples
/// * Read a slice of size 16 at offset 256.
///
/// ```
/// # use vm_memory::{Bytes, VolatileMemory, VolatileSlice};
/// #
/// # // Create a buffer
/// # let mut mem = [0u8; 1024];
/// #
/// # // Get a `VolatileSlice` from the buffer
/// # let vslice = VolatileSlice::from(&mut mem[..]);
/// #
/// let buf = &mut [0u8; 16];
/// let res = vslice.read_slice(buf, 256);
///
/// assert!(res.is_ok());
/// ```
fn read_slice(&self, buf: &mut [u8], addr: usize) -> Result<()> {
let len = self.read(buf, addr)?;
if len != buf.len() {
return Err(Error::PartialBuffer {
expected: buf.len(),
completed: len,
});
}
Ok(())
}
fn read_volatile_from<F>(&self, addr: usize, src: &mut F, count: usize) -> Result<usize>
where
F: ReadVolatile,
{
let slice = self.offset(addr)?;
/* Unwrap safe here because (0, min(len, count)) is definitely a valid subslice */
let mut slice = slice.subslice(0, slice.len().min(count)).unwrap();
retry_eintr!(src.read_volatile(&mut slice))
}
fn read_exact_volatile_from<F>(&self, addr: usize, src: &mut F, count: usize) -> Result<()>
where
F: ReadVolatile,
{
src.read_exact_volatile(&mut self.get_slice(addr, count)?)
}
fn write_volatile_to<F>(&self, addr: usize, dst: &mut F, count: usize) -> Result<usize>
where
F: WriteVolatile,
{
let slice = self.offset(addr)?;
/* Unwrap safe here because (0, min(len, count)) is definitely a valid subslice */
let slice = slice.subslice(0, slice.len().min(count)).unwrap();
retry_eintr!(dst.write_volatile(&slice))
}
fn write_all_volatile_to<F>(&self, addr: usize, dst: &mut F, count: usize) -> Result<()>
where
F: WriteVolatile,
{
dst.write_all_volatile(&self.get_slice(addr, count)?)
}
fn store<T: AtomicAccess>(&self, val: T, addr: usize, order: Ordering) -> Result<()> {
self.get_atomic_ref::<T::A>(addr).map(|r| {
r.store(val.into(), order);
self.bitmap.mark_dirty(addr, size_of::<T>())
})
}
fn load<T: AtomicAccess>(&self, addr: usize, order: Ordering) -> Result<T> {
self.get_atomic_ref::<T::A>(addr)
.map(|r| r.load(order).into())
}
}
impl<B: BitmapSlice> VolatileMemory for VolatileSlice<'_, B> {
type B = B;
fn len(&self) -> usize {
self.size
}
fn get_slice(&self, offset: usize, count: usize) -> Result<VolatileSlice<B>> {
self.subslice(offset, count)
}
}
/// A memory location that supports volatile access to an instance of `T`.
///
/// # Examples
///
/// ```
/// # use vm_memory::VolatileRef;
/// #
/// let mut v = 5u32;
/// let v_ref = unsafe { VolatileRef::new(&mut v as *mut u32 as *mut u8) };
///
/// assert_eq!(v, 5);
/// assert_eq!(v_ref.load(), 5);
/// v_ref.store(500);
/// assert_eq!(v, 500);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct VolatileRef<'a, T, B = ()> {
addr: *mut Packed<T>,
bitmap: B,
mmap: Option<&'a MmapInfo>,
}
impl<T> VolatileRef<'_, T, ()>
where
T: ByteValued,
{
/// Creates a [`VolatileRef`](struct.VolatileRef.html) to an instance of `T`.
///
/// # Safety
///
/// To use this safely, the caller must guarantee that the memory at `addr` is big enough for a
/// `T` and is available for the duration of the lifetime of the new `VolatileRef`. The caller
/// must also guarantee that all other users of the given chunk of memory are using volatile
/// accesses.
pub unsafe fn new(addr: *mut u8) -> Self {
Self::with_bitmap(addr, (), None)
}
}
#[allow(clippy::len_without_is_empty)]
impl<'a, T, B> VolatileRef<'a, T, B>
where
T: ByteValued,
B: BitmapSlice,
{
/// Creates a [`VolatileRef`](struct.VolatileRef.html) to an instance of `T`, using the
/// provided `bitmap` object for dirty page tracking.
///
/// # Safety
///
/// To use this safely, the caller must guarantee that the memory at `addr` is big enough for a
/// `T` and is available for the duration of the lifetime of the new `VolatileRef`. The caller
/// must also guarantee that all other users of the given chunk of memory are using volatile
/// accesses.
pub unsafe fn with_bitmap(addr: *mut u8, bitmap: B, mmap: Option<&'a MmapInfo>) -> Self {
VolatileRef {
addr: addr as *mut Packed<T>,
bitmap,
mmap,
}
}
/// Returns a guard for the pointer to the underlying memory.
pub fn ptr_guard(&self) -> PtrGuard {
PtrGuard::read(self.mmap, self.addr as *mut u8, self.len())
}
/// Returns a mutable guard for the pointer to the underlying memory.
pub fn ptr_guard_mut(&self) -> PtrGuardMut {
PtrGuardMut::write(self.mmap, self.addr as *mut u8, self.len())
}
/// Gets the size of the referenced type `T`.
///
/// # Examples
///
/// ```
/// # use std::mem::size_of;
/// # use vm_memory::VolatileRef;
/// #
/// let v_ref = unsafe { VolatileRef::<u32>::new(0 as *mut _) };
/// assert_eq!(v_ref.len(), size_of::<u32>() as usize);
/// ```
pub fn len(&self) -> usize {
size_of::<T>()
}
/// Borrows the inner `BitmapSlice`.
pub fn bitmap(&self) -> &B {
&self.bitmap
}
/// Does a volatile write of the value `v` to the address of this ref.
#[inline(always)]
pub fn store(&self, v: T) {
let guard = self.ptr_guard_mut();
// SAFETY: Safe because we checked the address and size when creating this VolatileRef.
unsafe { write_volatile(guard.as_ptr() as *mut Packed<T>, Packed::<T>(v)) };
self.bitmap.mark_dirty(0, self.len())
}
/// Does a volatile read of the value at the address of this ref.
#[inline(always)]
pub fn load(&self) -> T {
let guard = self.ptr_guard();
// SAFETY: Safe because we checked the address and size when creating this VolatileRef.
// For the purposes of demonstrating why read_volatile is necessary, try replacing the code
// in this function with the commented code below and running `cargo test --release`.
// unsafe { *(self.addr as *const T) }
unsafe { read_volatile(guard.as_ptr() as *const Packed<T>).0 }
}
/// Converts this to a [`VolatileSlice`](struct.VolatileSlice.html) with the same size and
/// address.
pub fn to_slice(&self) -> VolatileSlice<'a, B> {
// SAFETY: Safe because we checked the address and size when creating this VolatileRef.
unsafe {
VolatileSlice::with_bitmap(
self.addr as *mut u8,
size_of::<T>(),
self.bitmap.clone(),
self.mmap,
)
}
}
}
/// A memory location that supports volatile access to an array of elements of type `T`.
///
/// # Examples
///
/// ```
/// # use vm_memory::VolatileArrayRef;
/// #
/// let mut v = [5u32; 1];
/// let v_ref = unsafe { VolatileArrayRef::new(&mut v[0] as *mut u32 as *mut u8, v.len()) };
///
/// assert_eq!(v[0], 5);
/// assert_eq!(v_ref.load(0), 5);
/// v_ref.store(0, 500);
/// assert_eq!(v[0], 500);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct VolatileArrayRef<'a, T, B = ()> {