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
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//
// Portions 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 LICENSE-BSD-Google file.
//! Traits and structs to control Linux in-kernel vhost drivers.
//!
//! The initial vhost implementation is a part of the Linux kernel and uses ioctl interface to
//! communicate with userspace applications. This sub module provides ioctl based interfaces to
//! control the in-kernel net, scsi, vsock vhost drivers.
use std::mem;
use std::os::unix::io::{AsRawFd, RawFd};
use libc::{c_void, ssize_t, write};
use vm_memory::{Address, GuestAddress, GuestAddressSpace, GuestMemory, GuestUsize};
use vmm_sys_util::eventfd::EventFd;
use vmm_sys_util::ioctl::{ioctl, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref};
use super::{
Error, Result, VhostAccess, VhostBackend, VhostIotlbBackend, VhostIotlbMsg,
VhostIotlbMsgParser, VhostIotlbType, VhostUserDirtyLogRegion, VhostUserMemoryRegionInfo,
VringConfigData, VHOST_MAX_MEMORY_REGIONS,
};
pub mod vhost_binding;
use self::vhost_binding::*;
#[cfg(feature = "vhost-net")]
pub mod net;
#[cfg(feature = "vhost-vdpa")]
pub mod vdpa;
#[cfg(feature = "vhost-vsock")]
pub mod vsock;
#[inline]
fn ioctl_result<T>(rc: i32, res: T) -> Result<T> {
if rc < 0 {
Err(Error::IoctlError(std::io::Error::last_os_error()))
} else {
Ok(res)
}
}
#[inline]
fn io_result<T>(rc: isize, res: T) -> Result<T> {
if rc < 0 {
Err(Error::IOError(std::io::Error::last_os_error()))
} else {
Ok(res)
}
}
/// Represent an in-kernel vhost device backend.
pub trait VhostKernBackend: AsRawFd {
/// Associated type to access guest memory.
type AS: GuestAddressSpace;
/// Get the object to access the guest's memory.
fn mem(&self) -> &Self::AS;
/// Check whether the ring configuration is valid.
fn is_valid(&self, config_data: &VringConfigData) -> bool {
let queue_size = config_data.queue_size;
if queue_size > config_data.queue_max_size
|| queue_size == 0
|| (queue_size & (queue_size - 1)) != 0
{
return false;
}
let m = self.mem().memory();
let desc_table_size = 16 * u64::from(queue_size) as GuestUsize;
let avail_ring_size = 6 + 2 * u64::from(queue_size) as GuestUsize;
let used_ring_size = 6 + 8 * u64::from(queue_size) as GuestUsize;
if GuestAddress(config_data.desc_table_addr)
.checked_add(desc_table_size)
.is_none_or(|v| !m.address_in_range(v))
{
return false;
}
if GuestAddress(config_data.avail_ring_addr)
.checked_add(avail_ring_size)
.is_none_or(|v| !m.address_in_range(v))
{
return false;
}
if GuestAddress(config_data.used_ring_addr)
.checked_add(used_ring_size)
.is_none_or(|v| !m.address_in_range(v))
{
return false;
}
config_data.is_log_addr_valid()
}
}
impl<T: VhostKernBackend> VhostBackend for T {
/// Get a bitmask of supported virtio/vhost features.
fn get_features(&self) -> Result<u64> {
let mut avail_features: u64 = 0;
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_mut_ref(self, VHOST_GET_FEATURES(), &mut avail_features) };
ioctl_result(ret, avail_features)
}
/// Inform the vhost subsystem which features to enable. This should be a subset of
/// supported features from VHOST_GET_FEATURES.
///
/// # Arguments
/// * `features` - Bitmask of features to set.
fn set_features(&self, features: u64) -> Result<()> {
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_FEATURES(), &features) };
ioctl_result(ret, ())
}
/// Set the current process as the owner of this file descriptor.
/// This must be run before any other vhost ioctls.
fn set_owner(&self) -> Result<()> {
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl(self, VHOST_SET_OWNER()) };
ioctl_result(ret, ())
}
fn reset_owner(&self) -> Result<()> {
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl(self, VHOST_RESET_OWNER()) };
ioctl_result(ret, ())
}
/// Set the guest memory mappings for vhost to use.
fn set_mem_table(&self, regions: &[VhostUserMemoryRegionInfo]) -> Result<()> {
if regions.is_empty() || regions.len() > VHOST_MAX_MEMORY_REGIONS {
return Err(Error::InvalidGuestMemory);
}
let mut vhost_memory = VhostMemory::new(regions.len() as u16);
for (index, region) in regions.iter().enumerate() {
vhost_memory.set_region(
index as u32,
&vhost_memory_region {
guest_phys_addr: region.guest_phys_addr,
memory_size: region.memory_size,
userspace_addr: region.userspace_addr,
flags_padding: 0u64,
},
)?;
}
// SAFETY: This ioctl is called with a pointer that is valid for the lifetime
// of this function. The kernel will make its own copy of the memory
// tables. As always, check the return value.
let ret = unsafe { ioctl_with_ptr(self, VHOST_SET_MEM_TABLE(), vhost_memory.as_ptr()) };
ioctl_result(ret, ())
}
/// Set base address for page modification logging.
///
/// # Arguments
/// * `base` - Base address for page modification logging.
fn set_log_base(&self, base: u64, region: Option<VhostUserDirtyLogRegion>) -> Result<()> {
if region.is_some() {
return Err(Error::LogAddress);
}
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_LOG_BASE(), &base) };
ioctl_result(ret, ())
}
/// Specify an eventfd file descriptor to signal on log write.
fn set_log_fd(&self, fd: RawFd) -> Result<()> {
let val: i32 = fd;
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_LOG_FD(), &val) };
ioctl_result(ret, ())
}
/// Set the number of descriptors in the vring.
///
/// # Arguments
/// * `queue_index` - Index of the queue to set descriptor count for.
/// * `num` - Number of descriptors in the queue.
fn set_vring_num(&self, queue_index: usize, num: u16) -> Result<()> {
let vring_state = vhost_vring_state {
index: queue_index as u32,
num: u32::from(num),
};
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_NUM(), &vring_state) };
ioctl_result(ret, ())
}
/// Set the addresses for a given vring.
///
/// # Arguments
/// * `queue_index` - Index of the queue to set addresses for.
/// * `config_data` - Vring config data, addresses of desc_table, avail_ring
/// and used_ring are in the guest address space.
fn set_vring_addr(&self, queue_index: usize, config_data: &VringConfigData) -> Result<()> {
if !self.is_valid(config_data) {
return Err(Error::InvalidQueue);
}
// The addresses are converted into the host address space.
let vring_addr = config_data.to_vhost_vring_addr(queue_index, self.mem())?;
// SAFETY: This ioctl is called on a valid vhost fd and has its
// return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_ADDR(), &vring_addr) };
ioctl_result(ret, ())
}
/// Set the first index to look for available descriptors.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `num` - Index where available descriptors start.
fn set_vring_base(&self, queue_index: usize, base: u16) -> Result<()> {
let vring_state = vhost_vring_state {
index: queue_index as u32,
num: u32::from(base),
};
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_BASE(), &vring_state) };
ioctl_result(ret, ())
}
/// Get a bitmask of supported virtio/vhost features.
fn get_vring_base(&self, queue_index: usize) -> Result<u32> {
let mut vring_state = vhost_vring_state {
index: queue_index as u32,
num: 0,
};
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_mut_ref(self, VHOST_GET_VRING_BASE(), &mut vring_state) };
ioctl_result(ret, vring_state.num)
}
/// Set the eventfd to trigger when buffers have been used by the host.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd to trigger.
fn set_vring_call(&self, queue_index: usize, fd: &EventFd) -> Result<()> {
let vring_file = vhost_vring_file {
index: queue_index as u32,
fd: fd.as_raw_fd(),
};
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_CALL(), &vring_file) };
ioctl_result(ret, ())
}
/// Set the eventfd that will be signaled by the guest when buffers are
/// available for the host to process.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd that will be signaled from guest.
fn set_vring_kick(&self, queue_index: usize, fd: &EventFd) -> Result<()> {
let vring_file = vhost_vring_file {
index: queue_index as u32,
fd: fd.as_raw_fd(),
};
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_KICK(), &vring_file) };
ioctl_result(ret, ())
}
/// Set the eventfd to signal an error from the vhost backend.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd that will be signaled from the backend.
fn set_vring_err(&self, queue_index: usize, fd: &EventFd) -> Result<()> {
let vring_file = vhost_vring_file {
index: queue_index as u32,
fd: fd.as_raw_fd(),
};
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_ERR(), &vring_file) };
ioctl_result(ret, ())
}
}
/// Interface to handle in-kernel backend features.
pub trait VhostKernFeatures: Sized + AsRawFd {
/// Get features acked with the vhost backend.
fn get_backend_features_acked(&self) -> u64;
/// Set features acked with the vhost backend.
fn set_backend_features_acked(&mut self, features: u64);
/// Get a bitmask of supported vhost backend features.
fn get_backend_features(&self) -> Result<u64> {
let mut avail_features: u64 = 0;
let ret =
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
unsafe { ioctl_with_mut_ref(self, VHOST_GET_BACKEND_FEATURES(), &mut avail_features) };
ioctl_result(ret, avail_features)
}
/// Inform the vhost subsystem which backend features to enable. This should
/// be a subset of supported features from VHOST_GET_BACKEND_FEATURES.
///
/// # Arguments
/// * `features` - Bitmask of features to set.
fn set_backend_features(&mut self, features: u64) -> Result<()> {
// SAFETY: This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_BACKEND_FEATURES(), &features) };
if ret >= 0 {
self.set_backend_features_acked(features);
}
ioctl_result(ret, ())
}
}
/// Handle IOTLB messeges for in-kernel vhost device backend.
impl<I: VhostKernBackend + VhostKernFeatures> VhostIotlbBackend for I {
/// Send an IOTLB message to the in-kernel vhost backend.
///
/// # Arguments
/// * `msg` - IOTLB message to send.
fn send_iotlb_msg(&self, msg: &VhostIotlbMsg) -> Result<()> {
let ret: ssize_t;
if self.get_backend_features_acked() & (1 << VHOST_BACKEND_F_IOTLB_MSG_V2) != 0 {
let mut msg_v2 = vhost_msg_v2 {
type_: VHOST_IOTLB_MSG_V2,
..Default::default()
};
msg_v2.__bindgen_anon_1.iotlb.iova = msg.iova;
msg_v2.__bindgen_anon_1.iotlb.size = msg.size;
msg_v2.__bindgen_anon_1.iotlb.uaddr = msg.userspace_addr;
msg_v2.__bindgen_anon_1.iotlb.perm = msg.perm as u8;
msg_v2.__bindgen_anon_1.iotlb.type_ = msg.msg_type as u8;
// SAFETY: This is safe because we are using a valid vhost fd, and
// a valid pointer and size to the vhost_msg_v2 structure.
ret = unsafe {
write(
self.as_raw_fd(),
&msg_v2 as *const vhost_msg_v2 as *const c_void,
mem::size_of::<vhost_msg_v2>(),
)
};
} else {
let mut msg_v1 = vhost_msg {
type_: VHOST_IOTLB_MSG,
..Default::default()
};
msg_v1.__bindgen_anon_1.iotlb.iova = msg.iova;
msg_v1.__bindgen_anon_1.iotlb.size = msg.size;
msg_v1.__bindgen_anon_1.iotlb.uaddr = msg.userspace_addr;
msg_v1.__bindgen_anon_1.iotlb.perm = msg.perm as u8;
msg_v1.__bindgen_anon_1.iotlb.type_ = msg.msg_type as u8;
// SAFETY: This is safe because we are using a valid vhost fd, and
// a valid pointer and size to the vhost_msg structure.
ret = unsafe {
write(
self.as_raw_fd(),
&msg_v1 as *const vhost_msg as *const c_void,
mem::size_of::<vhost_msg>(),
)
};
}
io_result(ret, ())
}
}
impl VhostIotlbMsgParser for vhost_msg {
fn parse(&self, msg: &mut VhostIotlbMsg) -> Result<()> {
if self.type_ != VHOST_IOTLB_MSG {
return Err(Error::InvalidIotlbMsg);
}
// SAFETY: We trust the kernel to return a structure with the union
// fields properly initialized. We are sure it is a vhost_msg, because
// we checked that `self.type_` is VHOST_IOTLB_MSG.
unsafe {
if self.__bindgen_anon_1.iotlb.type_ == 0 {
return Err(Error::InvalidIotlbMsg);
}
msg.iova = self.__bindgen_anon_1.iotlb.iova;
msg.size = self.__bindgen_anon_1.iotlb.size;
msg.userspace_addr = self.__bindgen_anon_1.iotlb.uaddr;
msg.perm = mem::transmute::<u8, VhostAccess>(self.__bindgen_anon_1.iotlb.perm);
msg.msg_type = mem::transmute::<u8, VhostIotlbType>(self.__bindgen_anon_1.iotlb.type_);
}
Ok(())
}
}
impl VhostIotlbMsgParser for vhost_msg_v2 {
fn parse(&self, msg: &mut VhostIotlbMsg) -> Result<()> {
if self.type_ != VHOST_IOTLB_MSG_V2 {
return Err(Error::InvalidIotlbMsg);
}
// SAFETY: We trust the kernel to return a structure with the union
// fields properly initialized. We are sure it is a vhost_msg_v2, because
// we checked that `self.type_` is VHOST_IOTLB_MSG_V2.
unsafe {
if self.__bindgen_anon_1.iotlb.type_ == 0 {
return Err(Error::InvalidIotlbMsg);
}
msg.iova = self.__bindgen_anon_1.iotlb.iova;
msg.size = self.__bindgen_anon_1.iotlb.size;
msg.userspace_addr = self.__bindgen_anon_1.iotlb.uaddr;
msg.perm = mem::transmute::<u8, VhostAccess>(self.__bindgen_anon_1.iotlb.perm);
msg.msg_type = mem::transmute::<u8, VhostIotlbType>(self.__bindgen_anon_1.iotlb.type_);
}
Ok(())
}
}
impl VringConfigData {
/// Convert the config (guest address space) into vhost_vring_addr
/// (host address space).
pub fn to_vhost_vring_addr<AS: GuestAddressSpace>(
&self,
queue_index: usize,
mem: &AS,
) -> Result<vhost_vring_addr> {
let desc_addr = mem
.memory()
.get_host_address(GuestAddress(self.desc_table_addr))
.map_err(|_| Error::DescriptorTableAddress)?;
let avail_addr = mem
.memory()
.get_host_address(GuestAddress(self.avail_ring_addr))
.map_err(|_| Error::AvailAddress)?;
let used_addr = mem
.memory()
.get_host_address(GuestAddress(self.used_ring_addr))
.map_err(|_| Error::UsedAddress)?;
Ok(vhost_vring_addr {
index: queue_index as u32,
flags: self.flags,
desc_user_addr: desc_addr as u64,
used_user_addr: used_addr as u64,
avail_user_addr: avail_addr as u64,
log_guest_addr: self.get_log_addr(),
})
}
}