1 // Copyright 2023 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 use std::fs::OpenOptions; 7 8 use anyhow::Context; 9 use base::flock; 10 use base::open_file_or_duplicate; 11 use base::FlockOperation; 12 use disk::DiskFile; 13 14 use crate::virtio::scsi::ScsiOption; 15 16 impl ScsiOption { open(&self) -> anyhow::Result<Box<dyn DiskFile>>17 pub fn open(&self) -> anyhow::Result<Box<dyn DiskFile>> { 18 let mut options = OpenOptions::new(); 19 options.read(true).write(!self.read_only); 20 21 let raw_image: File = open_file_or_duplicate(&self.path, &options) 22 .with_context(|| format!("failed to load disk image {}", self.path.display()))?; 23 // Lock the disk image to prevent other crosvm instances from using it. 24 let lock_op = if self.read_only { 25 FlockOperation::LockShared 26 } else { 27 FlockOperation::LockExclusive 28 }; 29 flock(&raw_image, lock_op, true) 30 .with_context(|| format!("failed to lock disk image {}", self.path.display()))?; 31 32 // We only support sparse disks for now. 33 disk::create_disk_file(raw_image, true, disk::MAX_NESTING_DEPTH, &self.path) 34 .context("create_disk_file failed") 35 } 36 } 37