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 5 use std::fs::File; 6 7 use base::ioctl_with_ref; 8 use base::AsRawDescriptor; 9 use base::RawDescriptor; 10 use virtio_sys::VHOST_VSOCK_SET_GUEST_CID; 11 use virtio_sys::VHOST_VSOCK_SET_RUNNING; 12 13 use super::ioctl_result; 14 use super::Result; 15 use super::Vhost; 16 17 /// Handle for running VHOST_VSOCK ioctls. 18 pub struct Vsock { 19 descriptor: File, 20 } 21 22 impl Vsock { 23 /// Open a handle to a new VHOST_VSOCK instance. new(vhost_vsock_file: File) -> Vsock24 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 set_cid(&self, cid: u64) -> Result<()>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. start(&self) -> Result<()>46 pub fn start(&self) -> Result<()> { 47 self.set_running(true) 48 } 49 50 /// Tell the VHOST driver to stop performing data transfer. stop(&self) -> Result<()>51 pub fn stop(&self) -> Result<()> { 52 self.set_running(false) 53 } 54 set_running(&self, running: bool) -> Result<()>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 67 impl Vhost for Vsock {} 68 69 impl AsRawDescriptor for Vsock { as_raw_descriptor(&self) -> RawDescriptor70 fn as_raw_descriptor(&self) -> RawDescriptor { 71 self.descriptor.as_raw_descriptor() 72 } 73 } 74