device_virtio_pmem/
lib.rs

1// Copyright 2019 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#![cfg(any(target_os = "android", target_os = "linux"))]
6
7use std::collections::BTreeMap;
8use std::fs::File;
9use std::fs::OpenOptions;
10use std::io;
11use std::mem::size_of;
12use std::path::Path;
13use std::path::PathBuf;
14use std::time::Duration;
15
16use anyhow::anyhow;
17use anyhow::Context;
18use base::error;
19use base::round_up_to_page_size;
20use base::sys::MemfdSeals;
21use base::sys::SharedMemoryLinux;
22use base::AsRawDescriptor;
23use base::Error as SysError;
24use base::Event;
25use base::MemoryMappingArena;
26use base::Protection;
27use base::RawDescriptor;
28use base::Result as SysResult;
29use base::SharedMemory;
30use base::Timer;
31use base::Tube;
32use base::TubeError;
33use base::WorkerThread;
34use cros_async::select2;
35use cros_async::select3;
36use cros_async::AsyncError;
37use cros_async::EventAsync;
38use cros_async::Executor;
39use cros_async::TimerAsync;
40use data_model::Le32;
41use data_model::Le64;
42use devices::virtio::async_utils;
43use devices::virtio::copy_config;
44use devices::virtio::DescriptorChain;
45use devices::virtio::DeviceType;
46use devices::virtio::Interrupt;
47use devices::virtio::Queue;
48use devices::virtio::VirtioDevice;
49use devices::VirtioDeviceArgs;
50use devices::VirtioDeviceModule;
51use futures::pin_mut;
52use hypervisor::MemCacheType;
53use hypervisor::ProtectionType;
54use hypervisor::Vm;
55use remain::sorted;
56use resources::Alloc;
57use resources::AllocOptions;
58use resources::SystemAllocator;
59use serde::Deserialize;
60use serde::Deserializer;
61use serde::Serialize;
62use serde_keyvalue::FromKeyValues;
63use snapshot::AnySnapshot;
64use thiserror::Error;
65use vm_control::AnyControlTube;
66use vm_control::MemSlot;
67use vm_control::VmMemoryMappingRequest;
68use vm_control::VmMemoryMappingResponse;
69use vm_memory::GuestAddress;
70use vm_memory::GuestMemory;
71use zerocopy::FromBytes;
72use zerocopy::Immutable;
73use zerocopy::IntoBytes;
74use zerocopy::KnownLayout;
75
76const QUEUE_SIZE: u16 = 256;
77const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE];
78
79/* Feature bits */
80const VIRTIO_PMEM_F_DISCARD: u32 = 63;
81
82const VIRTIO_PMEM_REQ_TYPE_FLUSH: u32 = 0;
83const VIRTIO_PMEM_REQ_TYPE_DISCARD: u32 = u32::MAX;
84const VIRTIO_PMEM_RESP_TYPE_OK: u32 = 0;
85const VIRTIO_PMEM_RESP_TYPE_EIO: u32 = 1;
86
87#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)]
88#[repr(C)]
89struct virtio_pmem_config {
90    start_address: Le64,
91    size: Le64,
92}
93
94#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)]
95#[repr(C)]
96struct virtio_pmem_resp {
97    status_code: Le32,
98}
99
100#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)]
101#[repr(C)]
102struct virtio_pmem_req {
103    type_: Le32,
104}
105
106#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)]
107#[repr(C)]
108struct virtio_pmem_range_req {
109    type_: Le32,
110    padding_: Le32,
111    start_address: Le64,
112    size: Le64,
113}
114
115#[sorted]
116#[derive(Error, Debug)]
117enum Error {
118    /// Failed to get value from pageout timer.
119    #[error("failed to get value from pageout timer: {0}")]
120    PageoutTimer(AsyncError),
121    /// Failed to read from virtqueue.
122    #[error("failed to read from virtqueue: {0}")]
123    ReadQueue(io::Error),
124    /// Failed to receive tube response.
125    #[error("failed to receive tube response: {0}")]
126    ReceiveResponse(TubeError),
127    /// Failed to send tube request.
128    #[error("failed to send tube request: {0}")]
129    SendingRequest(TubeError),
130    /// Failed to write to virtqueue.
131    #[error("failed to write to virtqueue: {0}")]
132    WriteQueue(io::Error),
133}
134
135type Result<T> = ::std::result::Result<T, Error>;
136
137async fn pageout(
138    ex: &Executor,
139    swap_interval: Duration,
140    pmem_device_tube: &Tube,
141    mapping_arena_slot: u32,
142    mapping_size: usize,
143) -> Result<()> {
144    let timer = Timer::new().expect("Failed to create a timer");
145    let mut pageout_timer =
146        TimerAsync::new(timer, ex).expect("Failed to create an async pageout timer");
147    pageout_timer
148        .reset_repeating(swap_interval)
149        .expect("Failed to reset pageout timer");
150
151    loop {
152        pageout_timer.wait().await.map_err(Error::PageoutTimer)?;
153        let request = VmMemoryMappingRequest::MadvisePageout {
154            slot: mapping_arena_slot,
155            offset: 0,
156            size: mapping_size,
157        };
158
159        pmem_device_tube
160            .send(&request)
161            .map_err(Error::SendingRequest)?;
162        match pmem_device_tube
163            .recv::<VmMemoryMappingResponse>()
164            .map_err(Error::ReceiveResponse)?
165        {
166            VmMemoryMappingResponse::Ok => {}
167            VmMemoryMappingResponse::Err(e) => {
168                error!("failed to page out the memory mapping: {}", e);
169            }
170        };
171    }
172}
173
174fn execute_request(
175    request_type: u32,
176    start_address: u64,
177    size: u64,
178    pmem_device_tube: &Tube,
179    mapping_arena_slot: u32,
180    mapping_size: usize,
181) -> u32 {
182    match request_type {
183        VIRTIO_PMEM_REQ_TYPE_FLUSH => {
184            let request = VmMemoryMappingRequest::MsyncArena {
185                slot: mapping_arena_slot,
186                offset: 0, // The pmem backing file is always at offset 0 in the arena.
187                size: mapping_size,
188            };
189
190            if let Err(e) = pmem_device_tube.send(&request) {
191                error!("failed to send request: {}", e);
192                return VIRTIO_PMEM_RESP_TYPE_EIO;
193            }
194
195            match pmem_device_tube.recv() {
196                Ok(response) => match response {
197                    VmMemoryMappingResponse::Ok => VIRTIO_PMEM_RESP_TYPE_OK,
198                    VmMemoryMappingResponse::Err(e) => {
199                        error!("failed flushing disk image: {}", e);
200                        VIRTIO_PMEM_RESP_TYPE_EIO
201                    }
202                },
203                Err(e) => {
204                    error!("failed to receive data: {}", e);
205                    VIRTIO_PMEM_RESP_TYPE_EIO
206                }
207            }
208        }
209
210        VIRTIO_PMEM_REQ_TYPE_DISCARD => {
211            let request = VmMemoryMappingRequest::MadviseRemove {
212                slot: mapping_arena_slot,
213                offset: usize::try_from(start_address).unwrap(),
214                size: usize::try_from(size).unwrap(),
215            };
216
217            if let Err(e) = pmem_device_tube.send(&request) {
218                error!("failed to send request: {}", e);
219                return VIRTIO_PMEM_RESP_TYPE_EIO;
220            }
221
222            match pmem_device_tube.recv() {
223                Ok(response) => match response {
224                    VmMemoryMappingResponse::Ok => VIRTIO_PMEM_RESP_TYPE_OK,
225                    VmMemoryMappingResponse::Err(e) => {
226                        error!("failed to discard memory range: {}", e);
227                        VIRTIO_PMEM_RESP_TYPE_EIO
228                    }
229                },
230                Err(e) => {
231                    error!("failed to receive data: {}", e);
232                    VIRTIO_PMEM_RESP_TYPE_EIO
233                }
234            }
235        }
236
237        _ => {
238            error!("unknown request type: {}", request_type);
239            VIRTIO_PMEM_RESP_TYPE_EIO
240        }
241    }
242}
243
244fn handle_request(
245    avail_desc: &mut DescriptorChain,
246    pmem_device_tube: &Tube,
247    mapping_arena_slot: u32,
248    mapping_size: usize,
249) -> Result<usize> {
250    let (request_type, start_address, size) =
251        if avail_desc.reader.available_bytes() == size_of::<virtio_pmem_req>() {
252            let request = avail_desc
253                .reader
254                .read_obj::<virtio_pmem_req>()
255                .map_err(Error::ReadQueue)?;
256            (request.type_.to_native(), 0, 0)
257        } else {
258            let request = avail_desc
259                .reader
260                .read_obj::<virtio_pmem_range_req>()
261                .map_err(Error::ReadQueue)?;
262            (
263                request.type_.to_native(),
264                request.start_address.to_native(),
265                request.size.to_native(),
266            )
267        };
268    let status_code = execute_request(
269        request_type,
270        start_address,
271        size,
272        pmem_device_tube,
273        mapping_arena_slot,
274        mapping_size,
275    );
276
277    let response = virtio_pmem_resp {
278        status_code: status_code.into(),
279    };
280
281    avail_desc
282        .writer
283        .write_obj(response)
284        .map_err(Error::WriteQueue)?;
285
286    Ok(avail_desc.writer.bytes_written())
287}
288
289async fn handle_queue(
290    queue: &mut Queue,
291    mut queue_event: EventAsync,
292    pmem_device_tube: &Tube,
293    mapping_arena_slot: u32,
294    mapping_size: usize,
295) {
296    loop {
297        let mut avail_desc = match queue.next_async(&mut queue_event).await {
298            Err(e) => {
299                error!("Failed to read descriptor {}", e);
300                return;
301            }
302            Ok(d) => d,
303        };
304
305        let written = match handle_request(
306            &mut avail_desc,
307            pmem_device_tube,
308            mapping_arena_slot,
309            mapping_size,
310        ) {
311            Ok(n) => n,
312            Err(e) => {
313                error!("pmem: failed to handle request: {}", e);
314                0
315            }
316        };
317        queue.add_used_with_bytes_written(avail_desc, written as u32);
318        queue.trigger_interrupt();
319    }
320}
321
322fn run_worker(
323    queue: &mut Queue,
324    pmem_device_tube: &Tube,
325    kill_evt: Event,
326    mapping_arena_slot: u32,
327    mapping_size: usize,
328    swap_interval: Option<Duration>,
329) {
330    let ex = Executor::new().unwrap();
331
332    let queue_evt = queue
333        .event()
334        .try_clone()
335        .expect("failed to clone queue event");
336    let queue_evt = EventAsync::new(queue_evt, &ex).expect("failed to set up the queue event");
337
338    // Process requests from the virtio queue.
339    let queue_fut = handle_queue(
340        queue,
341        queue_evt,
342        pmem_device_tube,
343        mapping_arena_slot,
344        mapping_size,
345    );
346    pin_mut!(queue_fut);
347
348    // Exit if the kill event is triggered.
349    let kill = async_utils::await_and_exit(&ex, kill_evt);
350    pin_mut!(kill);
351
352    let interval = swap_interval.unwrap_or(Duration::ZERO);
353    if interval.is_zero() {
354        if let Err(e) = ex.run_until(select2(queue_fut, kill)) {
355            error!("error happened in executor: {}", e);
356        }
357    } else {
358        let pageout_fut = pageout(
359            &ex,
360            interval,
361            pmem_device_tube,
362            mapping_arena_slot,
363            mapping_size,
364        );
365        pin_mut!(pageout_fut);
366        if let Err(e) = ex.run_until(select3(queue_fut, kill, pageout_fut)) {
367            error!("error happened in executor: {}", e);
368        }
369    }
370}
371
372/// Specifies how memory slot is initialized.
373pub enum MemSlotConfig {
374    /// The memory region has already been mapped to the guest.
375    MemSlot {
376        /// index of the guest-mapped memory regions.
377        idx: MemSlot,
378    },
379    /// The memory region that is not initialized yet and whose slot index will be provided via
380    /// `Tube` later. e.g. pmem-ext2 device, where fs construction will be done in the main
381    /// process.
382    LazyInit { tube: Tube },
383}
384
385pub struct Pmem {
386    worker_thread: Option<WorkerThread<(Queue, Tube)>>,
387    features: u64,
388    disk_image: Option<File>,
389    mapping_address: GuestAddress,
390    mem_slot: MemSlotConfig,
391    mapping_size: u64,
392    pmem_device_tube: Option<Tube>,
393    swap_interval: Option<Duration>,
394}
395
396#[derive(serde::Serialize, serde::Deserialize)]
397struct PmemSnapshot {
398    mapping_address: GuestAddress,
399    mapping_size: u64,
400}
401
402/// Configuration of a virtio-pmem device.
403pub struct PmemConfig {
404    /// Disk image exposed to the guest.
405    /// If the memory region is not backed by a file, this should be `None`.
406    pub disk_image: Option<File>,
407    /// Guest physical address where the memory will be mapped.
408    pub mapping_address: GuestAddress,
409    pub mem_slot: MemSlotConfig,
410    /// The size of the mapped region.
411    pub mapping_size: u64,
412    /// A communication channel to the main process to send memory requests.
413    pub pmem_device_tube: Tube,
414    /// Interval for periodic swap out of memory mapping
415    pub swap_interval: Option<Duration>,
416    /// Whether the region is writeble or not.
417    pub mapping_writable: bool,
418}
419
420impl Pmem {
421    pub fn new(base_features: u64, cfg: PmemConfig) -> SysResult<Pmem> {
422        if cfg.mapping_size > usize::MAX as u64 {
423            return Err(SysError::new(libc::EOVERFLOW));
424        }
425
426        let mut avail_features = base_features;
427        if cfg.mapping_writable {
428            if let MemSlotConfig::LazyInit { .. } = cfg.mem_slot {
429                error!("pmem-ext2 must be a read-only device");
430                return Err(SysError::new(libc::EINVAL));
431            }
432
433            avail_features |= 1 << VIRTIO_PMEM_F_DISCARD;
434        }
435
436        Ok(Pmem {
437            worker_thread: None,
438            features: avail_features,
439            disk_image: cfg.disk_image,
440            mapping_address: cfg.mapping_address,
441            mem_slot: cfg.mem_slot,
442            mapping_size: cfg.mapping_size,
443            pmem_device_tube: Some(cfg.pmem_device_tube),
444            swap_interval: cfg.swap_interval,
445        })
446    }
447}
448
449impl VirtioDevice for Pmem {
450    fn keep_rds(&self) -> Vec<RawDescriptor> {
451        let mut keep_rds = Vec::new();
452        if let Some(disk_image) = &self.disk_image {
453            keep_rds.push(disk_image.as_raw_descriptor());
454        }
455
456        if let Some(ref pmem_device_tube) = self.pmem_device_tube {
457            keep_rds.push(pmem_device_tube.as_raw_descriptor());
458        }
459
460        if let MemSlotConfig::LazyInit { tube } = &self.mem_slot {
461            keep_rds.push(tube.as_raw_descriptor());
462        }
463
464        keep_rds
465    }
466
467    fn device_type(&self) -> DeviceType {
468        DeviceType::Pmem
469    }
470
471    fn queue_max_sizes(&self) -> &[u16] {
472        QUEUE_SIZES
473    }
474
475    fn features(&self) -> u64 {
476        self.features
477    }
478
479    fn read_config(&self, offset: u64, data: &mut [u8]) {
480        let config = virtio_pmem_config {
481            start_address: Le64::from(self.mapping_address.offset()),
482            size: Le64::from(self.mapping_size),
483        };
484        copy_config(data, 0, config.as_bytes(), offset);
485    }
486
487    fn activate(
488        &mut self,
489        _memory: GuestMemory,
490        _interrupt: Interrupt,
491        mut queues: BTreeMap<usize, Queue>,
492    ) -> anyhow::Result<()> {
493        if queues.len() != 1 {
494            return Err(anyhow!("expected 1 queue, got {}", queues.len()));
495        }
496
497        let mut queue = queues.remove(&0).unwrap();
498
499        // We checked that this fits in a usize in `Pmem::new`.
500        let mapping_size = self.mapping_size as usize;
501
502        let pmem_device_tube = self
503            .pmem_device_tube
504            .take()
505            .context("missing pmem device tube")?;
506
507        let swap_interval = self.swap_interval;
508
509        let mapping_arena_slot = match &self.mem_slot {
510            MemSlotConfig::MemSlot { idx } => *idx,
511            MemSlotConfig::LazyInit { tube } => tube
512                .recv::<u32>()
513                .context("failed to receive memory slot for ext2 pmem device")?,
514        };
515
516        self.worker_thread = Some(WorkerThread::start("v_pmem", move |kill_event| {
517            run_worker(
518                &mut queue,
519                &pmem_device_tube,
520                kill_event,
521                mapping_arena_slot,
522                mapping_size,
523                swap_interval,
524            );
525            (queue, pmem_device_tube)
526        }));
527
528        Ok(())
529    }
530
531    fn reset(&mut self) -> anyhow::Result<()> {
532        if let Some(worker_thread) = self.worker_thread.take() {
533            let (_queue, pmem_device_tube) = worker_thread.stop();
534            self.pmem_device_tube = Some(pmem_device_tube);
535        }
536        Ok(())
537    }
538
539    fn virtio_sleep(&mut self) -> anyhow::Result<Option<BTreeMap<usize, Queue>>> {
540        if let Some(worker_thread) = self.worker_thread.take() {
541            let (queue, pmem_device_tube) = worker_thread.stop();
542            self.pmem_device_tube = Some(pmem_device_tube);
543            return Ok(Some(BTreeMap::from([(0, queue)])));
544        }
545        Ok(None)
546    }
547
548    fn virtio_wake(
549        &mut self,
550        queues_state: Option<(GuestMemory, Interrupt, BTreeMap<usize, Queue>)>,
551    ) -> anyhow::Result<()> {
552        if let Some((mem, interrupt, queues)) = queues_state {
553            self.activate(mem, interrupt, queues)?;
554        }
555        Ok(())
556    }
557
558    fn virtio_snapshot(&mut self) -> anyhow::Result<AnySnapshot> {
559        AnySnapshot::to_any(PmemSnapshot {
560            mapping_address: self.mapping_address,
561            mapping_size: self.mapping_size,
562        })
563        .context("failed to serialize pmem snapshot")
564    }
565
566    fn virtio_restore(&mut self, data: AnySnapshot) -> anyhow::Result<()> {
567        let snapshot: PmemSnapshot =
568            AnySnapshot::from_any(data).context("failed to deserialize pmem snapshot")?;
569        anyhow::ensure!(
570            snapshot.mapping_address == self.mapping_address
571                && snapshot.mapping_size == self.mapping_size,
572            "pmem snapshot doesn't match config: expected {:?}, got {:?}",
573            (self.mapping_address, self.mapping_size),
574            (snapshot.mapping_address, snapshot.mapping_size),
575        );
576        Ok(())
577    }
578}
579
580fn create_anonymous_file<P: AsRef<Path>>(path: P, size: u64) -> anyhow::Result<File> {
581    let file_name = path
582        .as_ref()
583        .to_str()
584        .ok_or_else(|| base::Error::new(libc::EINVAL))?;
585    let mut shm = SharedMemory::new(file_name, size)?;
586    let mut seals = MemfdSeals::new();
587
588    seals.set_shrink_seal();
589    seals.set_grow_seal();
590    seals.set_seal_seal();
591    shm.add_seals(seals)?;
592
593    Ok(shm.descriptor.into())
594}
595
596fn create_pmem_device(
597    protection_type: ProtectionType,
598    vm: &dyn Vm,
599    resources: &mut SystemAllocator,
600    pmem: &PmemOption,
601    index: usize,
602    pmem_device_tube: Tube,
603) -> anyhow::Result<Box<dyn VirtioDevice>> {
604    let (fd, disk_size) = match pmem.vma_size {
605        None => {
606            let disk_image = base::open_file_or_duplicate(
607                &pmem.path,
608                OpenOptions::new().read(true).write(!pmem.ro),
609            )
610            .with_context(|| format!("failed to load disk image {}", pmem.path.display()))?;
611            let metadata = std::fs::metadata(&pmem.path).with_context(|| {
612                format!("failed to get disk image {} metadata", pmem.path.display())
613            })?;
614            (disk_image, metadata.len())
615        }
616        Some(size) => {
617            let anon_file =
618                create_anonymous_file(&pmem.path, size).context("failed to create anon file")?;
619            (anon_file, size)
620        }
621    };
622
623    // Linux requires pmem region sizes to be 2 MiB aligned. Linux will fill any partial page
624    // at the end of an mmap'd file and won't write back beyond the actual file length, but if
625    // we just align the size of the file to 2 MiB then access beyond the last page of the
626    // mapped file will generate SIGBUS. So use a memory mapping arena that will provide
627    // padding up to 2 MiB.
628    let alignment = 2 * 1024 * 1024;
629    let arena_size = disk_size
630        .checked_next_multiple_of(alignment)
631        .ok_or_else(|| anyhow!("pmem device image too big"))?;
632
633    let protection = {
634        if pmem.ro {
635            Protection::read()
636        } else {
637            Protection::read_write()
638        }
639    };
640
641    let arena = {
642        // Conversion from u64 to usize may fail on 32bit system.
643        let arena_size = usize::try_from(arena_size).context("pmem device image too big")?;
644        let disk_size = usize::try_from(disk_size).context("pmem device image too big")?;
645
646        let mut arena =
647            MemoryMappingArena::new(arena_size).context("failed to reserve pmem memory")?;
648        arena
649            .add_fd_offset_protection(0, disk_size, &fd, 0, protection)
650            .context("failed to reserve pmem memory")?;
651
652        // If the disk is not a multiple of the page size, the OS will fill the remaining part
653        // of the page with zeroes. However, the anonymous mapping added below must start on a
654        // page boundary, so round up the size before calculating the offset of the anon region.
655        let disk_size = round_up_to_page_size(disk_size);
656
657        if arena_size > disk_size {
658            // Add an anonymous region with the same protection as the disk mapping if the arena
659            // size was aligned.
660            arena
661                .add_anon_protection(disk_size, arena_size - disk_size, protection)
662                .context("failed to reserve pmem padding")?;
663        }
664        arena
665    };
666
667    let mapping_address = GuestAddress(
668        resources
669            .allocate_mmio(
670                arena_size,
671                Alloc::PmemDevice(index),
672                format!("pmem_disk_image_{index}"),
673                AllocOptions::new()
674                    // Allocate from the bottom up rather than top down to avoid exceeding
675                    // PHYSMEM_END with kaslr.
676                    // TODO: b/375506171: Find a proper fix.
677                    .top_down(false)
678                    .prefetchable(true)
679                    // Linux kernel requires pmem namespaces to be 128 MiB aligned.
680                    // cf. https://github.com/pmem/ndctl/issues/76
681                    .align(128 * 1024 * 1024), /* 128 MiB */
682            )
683            .context("failed to allocate memory for pmem device")?,
684    );
685
686    let mem_slot = MemSlotConfig::MemSlot {
687        idx: vm
688            .add_memory_region(
689                mapping_address,
690                Box::new(arena),
691                /* read_only = */ pmem.ro,
692                /* log_dirty_pages = */ false,
693                MemCacheType::CacheCoherent,
694            )
695            .context("failed to add pmem device memory")?,
696    };
697
698    let dev = Pmem::new(
699        devices::virtio::base_features(protection_type),
700        PmemConfig {
701            disk_image: Some(fd),
702            mapping_address,
703            mem_slot,
704            mapping_size: arena_size,
705            pmem_device_tube,
706            swap_interval: pmem.swap_interval,
707            mapping_writable: !pmem.ro,
708        },
709    )
710    .context("failed to create pmem device")?;
711
712    Ok(Box::new(dev))
713}
714
715fn deserialize_swap_interval<'de, D: Deserializer<'de>>(
716    deserializer: D,
717) -> std::result::Result<Option<Duration>, D::Error> {
718    let ms = Option::<u64>::deserialize(deserializer)?;
719    match ms {
720        None => Ok(None),
721        Some(ms) => Ok(Some(Duration::from_millis(ms))),
722    }
723}
724
725#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, FromKeyValues)]
726#[serde(deny_unknown_fields, rename_all = "kebab-case")]
727pub struct PmemOption {
728    /// Path to the disk image.
729    pub path: PathBuf,
730    /// Whether the disk is read-only.
731    #[serde(default)]
732    pub ro: bool,
733    /// If set, add a kernel command line option making this the root device. Can only be set once.
734    #[serde(default)]
735    pub root: bool,
736    /// Experimental option to specify the size in bytes of an anonymous virtual memory area that
737    /// will be created to back this device.
738    #[serde(default)]
739    pub vma_size: Option<u64>,
740    /// Experimental option to specify interval for periodic swap out of memory mapping
741    #[serde(
742        default,
743        deserialize_with = "deserialize_swap_interval",
744        rename = "swap-interval-ms"
745    )]
746    pub swap_interval: Option<Duration>,
747}
748
749pub fn validate_pmem(pmem: &PmemOption) -> std::result::Result<(), String> {
750    if (pmem.swap_interval.is_some() && pmem.vma_size.is_none())
751        || (pmem.swap_interval.is_none() && pmem.vma_size.is_some())
752    {
753        return Err(
754            "--pmem vma-size and swap-interval parameters must be specified together".to_string(),
755        );
756    }
757
758    if pmem.ro && pmem.swap_interval.is_some() {
759        return Err(
760            "--pmem swap-interval parameter can only be set for writable pmem device".to_string(),
761        );
762    }
763
764    Ok(())
765}
766
767#[derive(Clone, Debug, Serialize, Deserialize)]
768pub struct VirtioPmemModule {
769    pub pmem_option: PmemOption,
770    pub index: usize,
771}
772
773impl VirtioDeviceModule for VirtioPmemModule {
774    fn sort_name(&self) -> &'static str {
775        "pmem"
776    }
777
778    fn create(&self, cx: &mut VirtioDeviceArgs<'_>) -> anyhow::Result<Box<dyn VirtioDevice>> {
779        let (pmem_host_tube, pmem_device_tube) =
780            base::Tube::pair().context("failed to create tube")?;
781        (cx.add_control_tube)(AnyControlTube::VmMsync(pmem_host_tube));
782        create_pmem_device(
783            cx.protection_type,
784            cx.vm,
785            cx.resources,
786            &self.pmem_option,
787            self.index,
788            pmem_device_tube,
789        )
790    }
791
792    fn create_jail(
793        &self,
794        jail_config: Option<&jail::JailConfig>,
795    ) -> anyhow::Result<Option<minijail::Minijail>> {
796        jail::simple_jail(jail_config, "pmem_device")
797    }
798}
799
800pub mod ext2;
801pub use ext2::PmemExt2Option;
802pub use ext2::VirtioPmemExt2Module;
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807
808    #[test]
809    fn parse_pmem_options_missing_path() {
810        assert!(serde_keyvalue::from_key_values::<PmemOption>("")
811            .unwrap_err()
812            .to_string()
813            .contains("missing field `path`"));
814    }
815
816    #[test]
817    fn parse_pmem_options_default_values() {
818        let pmem = serde_keyvalue::from_key_values::<PmemOption>("/path/to/disk.img").unwrap();
819        assert_eq!(
820            pmem,
821            PmemOption {
822                path: "/path/to/disk.img".into(),
823                ro: false,
824                root: false,
825                vma_size: None,
826                swap_interval: None,
827            }
828        );
829    }
830
831    #[test]
832    fn parse_pmem_options_virtual_swap() {
833        let pmem = serde_keyvalue::from_key_values::<PmemOption>(
834            "virtual_path,vma-size=12345,swap-interval-ms=1000",
835        )
836        .unwrap();
837        assert_eq!(
838            pmem,
839            PmemOption {
840                path: "virtual_path".into(),
841                ro: false,
842                root: false,
843                vma_size: Some(12345),
844                swap_interval: Some(Duration::new(1, 0)),
845            }
846        );
847    }
848
849    #[test]
850    fn validate_pmem_missing_virtual_swap_param() {
851        let pmem =
852            serde_keyvalue::from_key_values::<PmemOption>("virtual_path,swap-interval-ms=1000")
853                .unwrap();
854        assert!(validate_pmem(&pmem)
855            .unwrap_err()
856            .contains("vma-size and swap-interval parameters must be specified together"));
857    }
858
859    #[test]
860    fn validate_pmem_read_only_virtual_swap() {
861        let pmem = serde_keyvalue::from_key_values::<PmemOption>(
862            "virtual_path,ro=true,vma-size=12345,swap-interval-ms=1000",
863        )
864        .unwrap();
865        assert!(validate_pmem(&pmem)
866            .unwrap_err()
867            .contains("swap-interval parameter can only be set for writable pmem device"));
868    }
869}