Skip to content

Commit 0173112

Browse files
roypatJonathanWoollett-Light
authored andcommitted
feat: Introduce Read/WriteVolatile traits
With #217, various `read_from` and `write_to` methods across vm-memory incurred a performance penalty due to an unneccesary copy of all data read and written. This is due to these functions operating on arbitrary Read/Write implementations, which cannot generally be assumed to respect the volatile semantics of guest memory. Additionally, they required taking slices to guest memory, which was undefined behavior. This patch series fixes those short-comings by introducing a pair of new traits, `ReadVolatile` and `WriteVolatile` which are identical to the standard library's `Read` and `Write` traits, with the difference being that they operate on `VolatileSlice`s instead of `&mut [u8]`. Using these traits will therefore not incur the performance penalty of #217. Additionally, this will make using the vm-memory library easier for users familiar with std::io, as the APIs will be more familiar (in particular, the unintuitive "swapping" of reader/writer src and dst of the old read_from/write_to APIs is resolved). Please note that `impl<T: AsRawFd> ReadVolatile for T` is not be possible, as the orphan rules will note that "upstream crates may add a new impl of trait std::os::fd::AsRawFd for type &[u8] in future versions". Signed-off-by: Patrick Roy <roypat@amazon.co.uk>
1 parent aff1dd4 commit 0173112

File tree

5 files changed

+304
-29
lines changed

5 files changed

+304
-29
lines changed

src/bytes.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,9 @@ pub trait Bytes<A> {
280280
/// * `addr` - Begin writing at this address.
281281
/// * `src` - Copy from `src` into the container.
282282
/// * `count` - Copy `count` bytes from `src` into the container.
283+
#[deprecated(
284+
note = "Use `.read_from_volatile` or the functions of the `ReadVolatile` trait instead"
285+
)]
283286
fn read_from<F>(&self, addr: A, src: &mut F, count: usize) -> Result<usize, Self::E>
284287
where
285288
F: Read;
@@ -295,6 +298,9 @@ pub trait Bytes<A> {
295298
/// * `addr` - Begin writing at this address.
296299
/// * `src` - Copy from `src` into the container.
297300
/// * `count` - Copy exactly `count` bytes from `src` into the container.
301+
#[deprecated(
302+
note = "Use `.read_exact_from_volatile` or the functions of the `ReadVolatile` trait instead"
303+
)]
298304
fn read_exact_from<F>(&self, addr: A, src: &mut F, count: usize) -> Result<(), Self::E>
299305
where
300306
F: Read;
@@ -307,6 +313,9 @@ pub trait Bytes<A> {
307313
/// * `addr` - Begin reading from this address.
308314
/// * `dst` - Copy from the container to `dst`.
309315
/// * `count` - Copy `count` bytes from the container to `dst`.
316+
#[deprecated(
317+
note = "Use `.write_to_volatile` or the functions of the `WriteVolatile` trait instead"
318+
)]
310319
fn write_to<F>(&self, addr: A, dst: &mut F, count: usize) -> Result<usize, Self::E>
311320
where
312321
F: Write;
@@ -322,6 +331,9 @@ pub trait Bytes<A> {
322331
/// * `addr` - Begin reading from this address.
323332
/// * `dst` - Copy from the container to `dst`.
324333
/// * `count` - Copy exactly `count` bytes from the container to `dst`.
334+
#[deprecated(
335+
note = "Use `.write_all_to_volatile` or the functions of the `WriteVolatile` trait instead"
336+
)]
325337
fn write_all_to<F>(&self, addr: A, dst: &mut F, count: usize) -> Result<(), Self::E>
326338
where
327339
F: Write;

src/guest_memory.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,7 @@ impl<T: GuestMemory + ?Sized> Bytes<GuestAddress> for T {
856856
where
857857
F: Read,
858858
{
859+
#[allow(deprecated)] // this function itself is deprecated
859860
let res = self.read_from(addr, src, count)?;
860861
if res != count {
861862
return Err(Error::PartialBuffer {
@@ -949,6 +950,7 @@ impl<T: GuestMemory + ?Sized> Bytes<GuestAddress> for T {
949950
where
950951
F: Write,
951952
{
953+
#[allow(deprecated)] // this function itself is deprecated
952954
let res = self.write_to(addr, dst, count)?;
953955
if res != count {
954956
return Err(Error::PartialBuffer {

src/io.rs

Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
//! Module containing versions of the standard library's [`Read`] and [`Write`] traits compatible
4+
//! with volatile memory accesses.
5+
6+
use crate::bitmap::BitmapSlice;
7+
use crate::volatile_memory::copy_slice_impl::{copy_from_volatile_slice, copy_to_volatile_slice};
8+
use crate::{VolatileMemoryError, VolatileSlice};
9+
use std::io::ErrorKind;
10+
use std::os::fd::AsRawFd;
11+
12+
/// A version of the standard library's [`Read`] trait that operates on volatile memory instead of
13+
/// slices
14+
///
15+
/// This trait is needed as rust slices (`&[u8]` and `&mut [u8]`) cannot be used when operating on
16+
/// guest memory [1].
17+
///
18+
/// [1]: https://github.com/rust-vmm/vm-memory/pull/217
19+
pub trait ReadVolatile {
20+
/// Tries to read some bytes into the given [`VolatileSlice`] buffer, returning how many bytes
21+
/// were read.
22+
///
23+
/// The behavior of implementations should be identical to [`Read::read`]
24+
fn read_volatile<B: BitmapSlice>(
25+
&mut self,
26+
buf: &mut VolatileSlice<B>,
27+
) -> Result<usize, VolatileMemoryError>;
28+
29+
/// Tries to fill the given [`VolatileSlice`] buffer by reading from `self` returning an error
30+
/// if insufficient bytes could be read.
31+
///
32+
/// The default implementation is identical to that of [`Read::read_exact`]
33+
fn read_exact_volatile<B: BitmapSlice>(
34+
&mut self,
35+
buf: &mut VolatileSlice<B>,
36+
) -> Result<(), VolatileMemoryError> {
37+
// Implementation based on https://github.com/rust-lang/rust/blob/7e7483d26e3cec7a44ef00cf7ae6c9c8c918bec6/library/std/src/io/mod.rs#L465
38+
39+
let mut partial_buf = buf.offset(0)?;
40+
41+
while !partial_buf.is_empty() {
42+
match self.read_volatile(&mut partial_buf) {
43+
Err(VolatileMemoryError::IOError(err)) if err.kind() == ErrorKind::Interrupted => {
44+
continue
45+
}
46+
Ok(0) => {
47+
return Err(VolatileMemoryError::IOError(std::io::Error::new(
48+
ErrorKind::UnexpectedEof,
49+
"failed to fill whole buffer",
50+
)))
51+
}
52+
Ok(bytes_read) => partial_buf = partial_buf.offset(bytes_read)?,
53+
Err(err) => return Err(err),
54+
}
55+
}
56+
57+
Ok(())
58+
}
59+
}
60+
61+
/// A version of the standard library's [`Write`] trait that operates on volatile memory instead of
62+
/// slices
63+
///
64+
/// This trait is needed as rust slices (`&[u8]` and `&mut [u8]`) cannot be used when operating on
65+
/// guest memory [1].
66+
///
67+
/// [1]: https://github.com/rust-vmm/vm-memory/pull/217
68+
pub trait WriteVolatile {
69+
/// Tries to write some bytes from the given [`VolatileSlice`] buffer, returning how many bytes
70+
/// were written.
71+
///
72+
/// The behavior of implementations should be identical to [`Write::write`]
73+
fn write_volatile<B: BitmapSlice>(
74+
&mut self,
75+
buf: &VolatileSlice<B>,
76+
) -> Result<usize, VolatileMemoryError>;
77+
78+
/// Tries write the entire content of the given [`VolatileSlice`] buffer to `self` returning an
79+
/// error if not all bytes could be written.
80+
///
81+
/// The default implementation is identical to that of [`Write::write_all`]
82+
fn write_all_volatile<B: BitmapSlice>(
83+
&mut self,
84+
buf: &VolatileSlice<B>,
85+
) -> Result<(), VolatileMemoryError> {
86+
// Based on https://github.com/rust-lang/rust/blob/7e7483d26e3cec7a44ef00cf7ae6c9c8c918bec6/library/std/src/io/mod.rs#L1570
87+
88+
let mut partial_buf = buf.offset(0)?;
89+
90+
while !partial_buf.is_empty() {
91+
match self.write_volatile(&partial_buf) {
92+
Err(VolatileMemoryError::IOError(err)) if err.kind() == ErrorKind::Interrupted => {
93+
continue
94+
}
95+
Ok(0) => {
96+
return Err(VolatileMemoryError::IOError(std::io::Error::new(
97+
ErrorKind::WriteZero,
98+
"failed to write whole buffer",
99+
)))
100+
}
101+
Ok(bytes_written) => partial_buf = partial_buf.offset(bytes_written)?,
102+
Err(err) => return Err(err),
103+
}
104+
}
105+
106+
Ok(())
107+
}
108+
}
109+
110+
// We explicitly implement our traits for [`std::fs::File`] and [`std::os::unix::net::UnixStream`]
111+
// instead of providing blanket implementation for [`AsRawFd`] due to trait coherence limitations: A
112+
// blanket implementation would prevent us from providing implementations for `&mut [u8]` below, as
113+
// "an upstream crate could implement AsRawFd for &mut [u8]`.
114+
115+
macro_rules! impl_read_write_volatile_for_raw_fd {
116+
($raw_fd_ty:ty) => {
117+
impl ReadVolatile for $raw_fd_ty {
118+
fn read_volatile<B: BitmapSlice>(
119+
&mut self,
120+
buf: &mut VolatileSlice<B>,
121+
) -> Result<usize, VolatileMemoryError> {
122+
read_volatile_raw_fd(self, buf)
123+
}
124+
}
125+
126+
impl WriteVolatile for $raw_fd_ty {
127+
fn write_volatile<B: BitmapSlice>(
128+
&mut self,
129+
buf: &VolatileSlice<B>,
130+
) -> Result<usize, VolatileMemoryError> {
131+
write_volatile_raw_fd(self, buf)
132+
}
133+
}
134+
};
135+
}
136+
137+
impl_read_write_volatile_for_raw_fd!(std::fs::File);
138+
impl_read_write_volatile_for_raw_fd!(std::os::unix::net::UnixStream);
139+
impl_read_write_volatile_for_raw_fd!(std::os::fd::OwnedFd);
140+
impl_read_write_volatile_for_raw_fd!(std::os::fd::BorrowedFd<'_>);
141+
142+
/// Tries to do a single `read` syscall on the provided file descriptor, storing the data raed in
143+
/// the given [`VolatileSlice`].
144+
///
145+
/// Returns the numbers of bytes read.
146+
fn read_volatile_raw_fd<Fd: AsRawFd>(
147+
raw_fd: &mut Fd,
148+
buf: &mut VolatileSlice<impl BitmapSlice>,
149+
) -> Result<usize, VolatileMemoryError> {
150+
let fd = raw_fd.as_raw_fd();
151+
let guard = buf.ptr_guard_mut();
152+
153+
let dst = guard.as_ptr().cast::<libc::c_void>();
154+
155+
// SAFETY: We got a valid file descriptor from `AsRawFd`. The memory pointed to by `dst` is
156+
// valid for writes of length `buf.len() by the invariants upheld by the constructor
157+
// of `VolatileSlice`.
158+
let bytes_read = unsafe { libc::read(fd, dst, buf.len()) };
159+
160+
if bytes_read < 0 {
161+
// We don't know if a partial read might have happened, so mark everything as dirty
162+
buf.bitmap().mark_dirty(0, buf.len());
163+
164+
Err(VolatileMemoryError::IOError(std::io::Error::last_os_error()))
165+
} else {
166+
let bytes_read = bytes_read.try_into().unwrap();
167+
buf.bitmap().mark_dirty(0, bytes_read);
168+
Ok(bytes_read)
169+
}
170+
}
171+
172+
/// Tries to do a single `write` syscall on the provided file descriptor, attempting to write the
173+
/// data stored in the given [`VolatileSlice`].
174+
///
175+
/// Returns the numbers of bytes written.
176+
fn write_volatile_raw_fd<Fd: AsRawFd>(
177+
raw_fd: &mut Fd,
178+
buf: &VolatileSlice<impl BitmapSlice>,
179+
) -> Result<usize, VolatileMemoryError> {
180+
let fd = raw_fd.as_raw_fd();
181+
let guard = buf.ptr_guard();
182+
183+
let src = guard.as_ptr().cast::<libc::c_void>();
184+
185+
// SAFETY: We got a valid file descriptor from `AsRawFd`. The memory pointed to by `src` is
186+
// valid for reads of length `buf.len() by the invariants upheld by the constructor
187+
// of `VolatileSlice`.
188+
let bytes_written = unsafe { libc::write(fd, src, buf.len()) };
189+
190+
if bytes_written < 0 {
191+
Err(VolatileMemoryError::IOError(std::io::Error::last_os_error()))
192+
} else {
193+
Ok(bytes_written.try_into().unwrap())
194+
}
195+
}
196+
197+
impl WriteVolatile for &mut [u8] {
198+
fn write_volatile<B: BitmapSlice>(
199+
&mut self,
200+
buf: &VolatileSlice<B>,
201+
) -> Result<usize, VolatileMemoryError> {
202+
let total = buf.len().min(self.len());
203+
let src = buf.subslice(0, total)?;
204+
205+
// SAFETY:
206+
// We check above that `src` is contiguously allocated memory of length `total <= self.len())`.
207+
// Furthermore, both src and dst of the call to
208+
// copy_from_volatile_slice are valid for reads and writes respectively of length `total`
209+
// since total is the minimum of lengths of the memory areas pointed to. The areas do not
210+
// overlap, since `dst` is inside guest memory, and buf is a slice (no slices to guest
211+
// memory are possible without violating rust's aliasing rules).
212+
let written = unsafe { copy_from_volatile_slice(self.as_mut_ptr(), &src, total) };
213+
214+
// Advance the slice, just like the stdlib: https://doc.rust-lang.org/src/std/io/impls.rs.html#335
215+
*self = std::mem::take(self).split_at_mut(written).1;
216+
217+
Ok(written)
218+
}
219+
220+
fn write_all_volatile<B: BitmapSlice>(
221+
&mut self,
222+
buf: &VolatileSlice<B>,
223+
) -> Result<(), VolatileMemoryError> {
224+
// Based on https://github.com/rust-lang/rust/blob/f7b831ac8a897273f78b9f47165cf8e54066ce4b/library/std/src/io/impls.rs#L376-L382
225+
if self.write_volatile(buf)? == buf.len() {
226+
Ok(())
227+
} else {
228+
Err(VolatileMemoryError::IOError(std::io::Error::new(
229+
ErrorKind::WriteZero,
230+
"failed to write whole buffer",
231+
)))
232+
}
233+
}
234+
}
235+
236+
impl ReadVolatile for &[u8] {
237+
fn read_volatile<B: BitmapSlice>(
238+
&mut self,
239+
buf: &mut VolatileSlice<B>,
240+
) -> Result<usize, VolatileMemoryError> {
241+
let total = buf.len().min(self.len());
242+
let dst = buf.subslice(0, total)?;
243+
244+
// SAFETY:
245+
// We check above that `dst` is contiguously allocated memory of length `total <= self.len())`.
246+
// Furthermore, both src and dst of the call to copy_to_volatile_slice are valid for reads
247+
// and writes respectively of length `total` since total is the minimum of lengths of the
248+
// memory areas pointed to. The areas do not overlap, since `dst` is inside guest memory,
249+
// and buf is a slice (no slices to guest memory are possible without violating rust's aliasing rules).
250+
let read = unsafe { copy_to_volatile_slice(&dst, self.as_ptr(), total) };
251+
252+
// Advance the slice, just like the stdlib: https://doc.rust-lang.org/src/std/io/impls.rs.html#232-310
253+
*self = self.split_at(read).1;
254+
255+
Ok(read)
256+
}
257+
258+
fn read_exact_volatile<B: BitmapSlice>(
259+
&mut self,
260+
buf: &mut VolatileSlice<B>,
261+
) -> Result<(), VolatileMemoryError> {
262+
// Based on https://github.com/rust-lang/rust/blob/f7b831ac8a897273f78b9f47165cf8e54066ce4b/library/std/src/io/impls.rs#L282-L302
263+
if buf.len() > self.len() {
264+
return Err(VolatileMemoryError::IOError(std::io::Error::new(
265+
ErrorKind::UnexpectedEof,
266+
"failed to fill whole buffer",
267+
)));
268+
}
269+
270+
self.read_volatile(buf).map(|_| ())
271+
}
272+
}

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ pub use guest_memory::{
4545
GuestMemoryRegion, GuestUsize, MemoryRegionAddress, Result as GuestMemoryResult,
4646
};
4747

48+
pub mod io;
49+
pub use io::{ReadVolatile, WriteVolatile};
50+
4851
#[cfg(all(feature = "backend-mmap", not(feature = "xen"), unix))]
4952
mod mmap_unix;
5053

0 commit comments

Comments
 (0)