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
5 use std::cmp::max;
6 use std::cmp::min;
7 use std::fs::File;
8 use std::fs::OpenOptions;
9 use std::os::unix::prelude::OpenOptionsExt;
10
11 use anyhow::Context;
12 use base::flock;
13 use base::iov_max;
14 use base::open_file;
15 use base::FlockOperation;
16 use disk::DiskFile;
17
18 use crate::virtio::block::block::DiskOption;
19
get_seg_max(queue_size: u16) -> u3220 pub fn get_seg_max(queue_size: u16) -> u32 {
21 let seg_max = min(max(iov_max(), 1), u32::max_value() as usize) as u32;
22
23 // Since we do not currently support indirect descriptors, the maximum
24 // number of segments must be smaller than the queue size.
25 // In addition, the request header and status each consume a descriptor.
26 min(seg_max, u32::from(queue_size) - 2)
27 }
28
29 impl DiskOption {
30 /// Open the specified disk file.
open(&self) -> anyhow::Result<Box<dyn DiskFile>>31 pub fn open(&self) -> anyhow::Result<Box<dyn DiskFile>> {
32 let mut options = OpenOptions::new();
33 options.read(true).write(!self.read_only);
34
35 if self.direct {
36 options.custom_flags(libc::O_DIRECT);
37 }
38
39 let raw_image: File = open_file(&self.path, &options)
40 .with_context(|| format!("failed to load disk image {}", self.path.display()))?;
41 // Lock the disk image to prevent other crosvm instances from using it.
42 let lock_op = if self.read_only {
43 FlockOperation::LockShared
44 } else {
45 FlockOperation::LockExclusive
46 };
47 flock(&raw_image, lock_op, true)
48 .with_context(|| format!("failed to lock disk image {}", self.path.display()))?;
49
50 disk::create_disk_file(raw_image, self.sparse, disk::MAX_NESTING_DEPTH, &self.path)
51 .context("create_disk_file failed")
52 }
53 }
54