device_virtio_block/sys/
linux.rs

1// Copyright 2022 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::cmp::max;
6use std::cmp::min;
7use std::os::fd::BorrowedFd;
8
9use anyhow::Context;
10use base::linux::preadv2;
11use base::linux::pwritev2;
12use base::unix::iov_max;
13use base::IoBufMut;
14use base::RawDescriptor;
15use cros_async::Executor;
16use disk::DiskFile;
17
18use crate::asynchronous::BlockAsync;
19use crate::DiskFormat;
20use crate::DiskOption;
21
22pub fn get_seg_max(queue_size: u16) -> u32 {
23    let seg_max = min(max(iov_max(), 1), u32::MAX as usize) as u32;
24
25    // Since we do not currently support indirect descriptors, the maximum
26    // number of segments must be smaller than the queue size.
27    // In addition, the request header and status each consume a descriptor.
28    min(seg_max, u32::from(queue_size) - 2)
29}
30
31pub fn check_dontcache_support(fd: RawDescriptor, write: bool) -> bool {
32    let mut buf = [0u8; 1];
33    let mut iovs = [IoBufMut::new(&mut buf)];
34    // SAFETY: fd is an open file descriptor.
35    let borrowed_fd = unsafe { BorrowedFd::borrow_raw(fd) };
36    let res = if write {
37        // To probe write support without clobbering existing disk data, read the byte
38        // at offset 0 first and write it back.
39        if preadv2(borrowed_fd, &mut iovs, 0, 0) != 1 {
40            return false;
41        }
42        pwritev2(
43            borrowed_fd,
44            IoBufMut::as_iobufs(&iovs),
45            0,
46            libc::RWF_DONTCACHE,
47        )
48    } else {
49        preadv2(borrowed_fd, &mut iovs, 0, libc::RWF_DONTCACHE)
50    };
51    if res < 0 {
52        let err = base::Error::last();
53        match err.errno() {
54            libc::EOPNOTSUPP | libc::EINVAL | libc::ENOSYS => false,
55            _ => {
56                base::warn!("Unexpected error checking for DONTCACHE support: {err}");
57                false
58            }
59        }
60    } else {
61        true
62    }
63}
64
65impl DiskOption {
66    /// Open the specified disk file.
67    pub fn open(&self) -> anyhow::Result<Box<dyn DiskFile>> {
68        let params = disk::DiskFileParams {
69            path: self.path.clone(),
70            is_read_only: self.read_only,
71            is_sparse_file: self.sparse,
72            is_direct: self.direct,
73            lock: self.lock,
74            ..Default::default()
75        };
76        match self.format {
77            DiskFormat::Auto => disk::open_disk_file(params),
78            DiskFormat::Raw => disk::open_disk_file_as(params, disk::ImageType::Raw),
79        }
80        .context("open_disk_file failed")
81    }
82}
83
84impl BlockAsync {
85    pub fn create_executor(&self) -> Executor {
86        Executor::with_executor_kind(self.executor_kind).expect("Failed to create an executor")
87    }
88}