vhost/
vsock.rs

1// Copyright 2017 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::fs::File;
6
7use base::ioctl_with_ref;
8use base::AsRawDescriptor;
9use base::RawDescriptor;
10use virtio_sys::VHOST_VSOCK_SET_GUEST_CID;
11use virtio_sys::VHOST_VSOCK_SET_RUNNING;
12
13use super::ioctl_result;
14use super::Result;
15use super::Vhost;
16
17/// Handle for running VHOST_VSOCK ioctls.
18pub struct Vsock {
19    descriptor: File,
20}
21
22impl Vsock {
23    /// Open a handle to a new VHOST_VSOCK instance.
24    pub fn new(vhost_vsock_file: File) -> Vsock {
25        Vsock {
26            descriptor: vhost_vsock_file,
27        }
28    }
29
30    /// Set the CID for the guest.  This number is used for routing all data destined for
31    /// programs
32    /// running in the guest.
33    ///
34    /// # Arguments
35    /// * `cid` - CID to assign to the guest
36    pub fn set_cid(&self, cid: u64) -> Result<()> {
37        // SAFETY: Safe because descriptor is valid and the return value is checked.
38        let ret = unsafe { ioctl_with_ref(&self.descriptor, VHOST_VSOCK_SET_GUEST_CID, &cid) };
39        if ret < 0 {
40            return ioctl_result();
41        }
42        Ok(())
43    }
44
45    /// Tell the VHOST driver to start performing data transfer.
46    pub fn start(&self) -> Result<()> {
47        self.set_running(true)
48    }
49
50    /// Tell the VHOST driver to stop performing data transfer.
51    pub fn stop(&self) -> Result<()> {
52        self.set_running(false)
53    }
54
55    fn set_running(&self, running: bool) -> Result<()> {
56        let on = ::std::os::raw::c_int::from(running);
57        // SAFETY: Safe because descriptor is valid and the return value is checked.
58        let ret = unsafe { ioctl_with_ref(&self.descriptor, VHOST_VSOCK_SET_RUNNING, &on) };
59
60        if ret < 0 {
61            return ioctl_result();
62        }
63        Ok(())
64    }
65}
66
67impl Vhost for Vsock {}
68
69impl AsRawDescriptor for Vsock {
70    fn as_raw_descriptor(&self) -> RawDescriptor {
71        self.descriptor.as_raw_descriptor()
72    }
73}