xref: /aosp_15_r20/external/crosvm/hypervisor/src/haxm/linux.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 // Copyright 2020 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::cell::RefCell;
6 use std::os::raw::c_char;
7 use std::os::raw::c_int;
8 
9 use base::errno_result;
10 use base::Error;
11 use base::FromRawDescriptor;
12 use base::MappedRegion;
13 use base::Result;
14 use base::SafeDescriptor;
15 use libc::open64;
16 use libc::EBUSY;
17 use libc::O_CLOEXEC;
18 use libc::O_RDWR;
19 
20 use super::haxm_sys::hax_tunnel;
21 use super::HaxmVcpu;
22 use super::HAX_EXIT_PAUSED;
23 
open_haxm_device(_use_ghaxm: bool) -> Result<SafeDescriptor>24 pub(super) fn open_haxm_device(_use_ghaxm: bool) -> Result<SafeDescriptor> {
25     // Open calls are safe because we give a constant nul-terminated string and verify the
26     // result.
27     let ret = unsafe { open64("/dev/HAX\0".as_ptr() as *const c_char, O_RDWR | O_CLOEXEC) };
28     if ret < 0 {
29         return errno_result();
30     }
31     // Safe because we verify that ret is valid and we own the fd.
32     Ok(unsafe { SafeDescriptor::from_raw_descriptor(ret) })
33 }
34 
open_haxm_vm_device(_use_ghaxm: bool, vm_id: u32) -> Result<SafeDescriptor>35 pub(super) fn open_haxm_vm_device(_use_ghaxm: bool, vm_id: u32) -> Result<SafeDescriptor> {
36     // Haxm creates additional device paths when VMs are created
37     let path = format!("/dev/hax_vm/vm{:02}\0", vm_id);
38 
39     let ret = unsafe { open64(path.as_ptr() as *const c_char, O_RDWR | O_CLOEXEC) };
40     if ret < 0 {
41         return errno_result();
42     }
43 
44     // Safe because we verify that ret is valid and we own the fd.
45     Ok(unsafe { SafeDescriptor::from_raw_descriptor(ret) })
46 }
47 
open_haxm_vcpu_device( _use_ghaxm: bool, vm_id: u32, vcpu_id: u32, ) -> Result<SafeDescriptor>48 pub(super) fn open_haxm_vcpu_device(
49     _use_ghaxm: bool,
50     vm_id: u32,
51     vcpu_id: u32,
52 ) -> Result<SafeDescriptor> {
53     // Haxm creates additional device paths when VMs are created
54     let path = format!("/dev/hax_vm{:02}/vcpu{:02}\0", vm_id, vcpu_id);
55 
56     let ret = unsafe { open64(path.as_ptr() as *const c_char, O_RDWR | O_CLOEXEC) };
57     if ret < 0 {
58         return errno_result();
59     }
60 
61     // Safe because we verify that ret is valid and we own the fd.
62     unsafe { SafeDescriptor::from_raw_descriptor(ret) };
63 }
64