1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::collections::BTreeMap;
use std::fs::File;
use std::io;
use std::mem::size_of;
use std::time::Duration;

use anyhow::anyhow;
use anyhow::Context;
use base::error;
use base::AsRawDescriptor;
use base::Error as SysError;
use base::Event;
use base::RawDescriptor;
use base::Result as SysResult;
use base::Timer;
use base::Tube;
use base::TubeError;
use base::WorkerThread;
use cros_async::select3;
use cros_async::select4;
use cros_async::AsyncError;
use cros_async::EventAsync;
use cros_async::Executor;
use cros_async::TimerAsync;
use data_model::Le32;
use data_model::Le64;
use futures::pin_mut;
use remain::sorted;
use thiserror::Error;
use vm_control::MemSlot;
use vm_control::VmMemoryMappingRequest;
use vm_control::VmMemoryMappingResponse;
use vm_memory::GuestAddress;
use vm_memory::GuestMemory;
use zerocopy::AsBytes;
use zerocopy::FromBytes;
use zerocopy::FromZeroes;

use super::async_utils;
use super::copy_config;
use super::DescriptorChain;
use super::DeviceType;
use super::Interrupt;
use super::Queue;
use super::VirtioDevice;

const QUEUE_SIZE: u16 = 256;
const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE];

/* Feature bits */
const VIRTIO_PMEM_F_DISCARD: u32 = 63;

const VIRTIO_PMEM_REQ_TYPE_FLUSH: u32 = 0;
const VIRTIO_PMEM_REQ_TYPE_DISCARD: u32 = u32::MAX;
const VIRTIO_PMEM_RESP_TYPE_OK: u32 = 0;
const VIRTIO_PMEM_RESP_TYPE_EIO: u32 = 1;

#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)]
#[repr(C)]
struct virtio_pmem_config {
    start_address: Le64,
    size: Le64,
}

#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)]
#[repr(C)]
struct virtio_pmem_resp {
    status_code: Le32,
}

#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)]
#[repr(C)]
struct virtio_pmem_req {
    type_: Le32,
}

#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)]
#[repr(C)]
struct virtio_pmem_range_req {
    type_: Le32,
    padding_: Le32,
    start_address: Le64,
    size: Le64,
}

#[sorted]
#[derive(Error, Debug)]
enum Error {
    /// Failed to get value from pageout timer.
    #[error("failed to get value from pageout timer: {0}")]
    PageoutTimer(AsyncError),
    /// Failed to read from virtqueue.
    #[error("failed to read from virtqueue: {0}")]
    ReadQueue(io::Error),
    /// Failed to receive tube response.
    #[error("failed to receive tube response: {0}")]
    ReceiveResponse(TubeError),
    /// Failed to send tube request.
    #[error("failed to send tube request: {0}")]
    SendingRequest(TubeError),
    /// Failed to write to virtqueue.
    #[error("failed to write to virtqueue: {0}")]
    WriteQueue(io::Error),
}

type Result<T> = ::std::result::Result<T, Error>;

async fn pageout(
    ex: &Executor,
    swap_interval: Duration,
    pmem_device_tube: &Tube,
    mapping_arena_slot: u32,
    mapping_size: usize,
) -> Result<()> {
    let timer = Timer::new().expect("Failed to create a timer");
    let mut pageout_timer =
        TimerAsync::new(timer, ex).expect("Failed to create an async pageout timer");
    pageout_timer
        .reset_repeating(swap_interval)
        .expect("Failed to reset pageout timer");

    loop {
        pageout_timer.wait().await.map_err(Error::PageoutTimer)?;
        let request = VmMemoryMappingRequest::MadvisePageout {
            slot: mapping_arena_slot,
            offset: 0,
            size: mapping_size,
        };

        pmem_device_tube
            .send(&request)
            .map_err(Error::SendingRequest)?;
        match pmem_device_tube
            .recv::<VmMemoryMappingResponse>()
            .map_err(Error::ReceiveResponse)?
        {
            VmMemoryMappingResponse::Ok => {}
            VmMemoryMappingResponse::Err(e) => {
                error!("failed to page out the memory mapping: {}", e);
            }
        };
    }
}

fn execute_request(
    request_type: u32,
    start_address: u64,
    size: u64,
    pmem_device_tube: &Tube,
    mapping_arena_slot: u32,
    mapping_size: usize,
) -> u32 {
    match request_type {
        VIRTIO_PMEM_REQ_TYPE_FLUSH => {
            let request = VmMemoryMappingRequest::MsyncArena {
                slot: mapping_arena_slot,
                offset: 0, // The pmem backing file is always at offset 0 in the arena.
                size: mapping_size,
            };

            if let Err(e) = pmem_device_tube.send(&request) {
                error!("failed to send request: {}", e);
                return VIRTIO_PMEM_RESP_TYPE_EIO;
            }

            match pmem_device_tube.recv() {
                Ok(response) => match response {
                    VmMemoryMappingResponse::Ok => VIRTIO_PMEM_RESP_TYPE_OK,
                    VmMemoryMappingResponse::Err(e) => {
                        error!("failed flushing disk image: {}", e);
                        VIRTIO_PMEM_RESP_TYPE_EIO
                    }
                },
                Err(e) => {
                    error!("failed to receive data: {}", e);
                    VIRTIO_PMEM_RESP_TYPE_EIO
                }
            }
        }

        VIRTIO_PMEM_REQ_TYPE_DISCARD => {
            let request = VmMemoryMappingRequest::MadviseRemove {
                slot: mapping_arena_slot,
                offset: usize::try_from(start_address).unwrap(),
                size: usize::try_from(size).unwrap(),
            };

            if let Err(e) = pmem_device_tube.send(&request) {
                error!("failed to send request: {}", e);
                return VIRTIO_PMEM_RESP_TYPE_EIO;
            }

            match pmem_device_tube.recv() {
                Ok(response) => match response {
                    VmMemoryMappingResponse::Ok => VIRTIO_PMEM_RESP_TYPE_OK,
                    VmMemoryMappingResponse::Err(e) => {
                        error!("failed to discard memory range: {}", e);
                        VIRTIO_PMEM_RESP_TYPE_EIO
                    }
                },
                Err(e) => {
                    error!("failed to receive data: {}", e);
                    VIRTIO_PMEM_RESP_TYPE_EIO
                }
            }
        }

        _ => {
            error!("unknown request type: {}", request_type);
            VIRTIO_PMEM_RESP_TYPE_EIO
        }
    }
}

fn handle_request(
    avail_desc: &mut DescriptorChain,
    pmem_device_tube: &Tube,
    mapping_arena_slot: u32,
    mapping_size: usize,
) -> Result<usize> {
    let (request_type, start_address, size) =
        if avail_desc.reader.available_bytes() == size_of::<virtio_pmem_req>() {
            let request = avail_desc
                .reader
                .read_obj::<virtio_pmem_req>()
                .map_err(Error::ReadQueue)?;
            (request.type_.to_native(), 0, 0)
        } else {
            let request = avail_desc
                .reader
                .read_obj::<virtio_pmem_range_req>()
                .map_err(Error::ReadQueue)?;
            (
                request.type_.to_native(),
                request.start_address.to_native(),
                request.size.to_native(),
            )
        };
    let status_code = execute_request(
        request_type,
        start_address,
        size,
        pmem_device_tube,
        mapping_arena_slot,
        mapping_size,
    );

    let response = virtio_pmem_resp {
        status_code: status_code.into(),
    };

    avail_desc
        .writer
        .write_obj(response)
        .map_err(Error::WriteQueue)?;

    Ok(avail_desc.writer.bytes_written())
}

async fn handle_queue(
    queue: &mut Queue,
    mut queue_event: EventAsync,
    pmem_device_tube: &Tube,
    mapping_arena_slot: u32,
    mapping_size: usize,
) {
    loop {
        let mut avail_desc = match queue.next_async(&mut queue_event).await {
            Err(e) => {
                error!("Failed to read descriptor {}", e);
                return;
            }
            Ok(d) => d,
        };

        let written = match handle_request(
            &mut avail_desc,
            pmem_device_tube,
            mapping_arena_slot,
            mapping_size,
        ) {
            Ok(n) => n,
            Err(e) => {
                error!("pmem: failed to handle request: {}", e);
                0
            }
        };
        queue.add_used(avail_desc, written as u32);
        queue.trigger_interrupt();
    }
}

fn run_worker(
    queue: &mut Queue,
    pmem_device_tube: &Tube,
    interrupt: Interrupt,
    kill_evt: Event,
    mapping_arena_slot: u32,
    mapping_size: usize,
    swap_interval: Option<Duration>,
) {
    let ex = Executor::new().unwrap();

    let queue_evt = queue
        .event()
        .try_clone()
        .expect("failed to clone queue event");
    let queue_evt = EventAsync::new(queue_evt, &ex).expect("failed to set up the queue event");

    // Process requests from the virtio queue.
    let queue_fut = handle_queue(
        queue,
        queue_evt,
        pmem_device_tube,
        mapping_arena_slot,
        mapping_size,
    );
    pin_mut!(queue_fut);

    // Process any requests to resample the irq value.
    let resample = async_utils::handle_irq_resample(&ex, interrupt);
    pin_mut!(resample);

    // Exit if the kill event is triggered.
    let kill = async_utils::await_and_exit(&ex, kill_evt);
    pin_mut!(kill);

    let interval = swap_interval.unwrap_or(Duration::ZERO);
    if interval.is_zero() {
        if let Err(e) = ex.run_until(select3(queue_fut, resample, kill)) {
            error!("error happened in executor: {}", e);
        }
    } else {
        let pageout_fut = pageout(
            &ex,
            interval,
            pmem_device_tube,
            mapping_arena_slot,
            mapping_size,
        );
        pin_mut!(pageout_fut);
        if let Err(e) = ex.run_until(select4(queue_fut, resample, kill, pageout_fut)) {
            error!("error happened in executor: {}", e);
        }
    }
}

/// Specifies how memory slot is initialized.
pub enum MemSlotConfig {
    /// The memory region has already been mapped to the guest.
    MemSlot {
        /// index of the guest-mapped memory regions.
        idx: MemSlot,
    },
    /// The memory region that is not initialized yet and whose slot index will be provided via
    /// `Tube` later. e.g. pmem-ext2 device, where fs construction will be done in the main
    /// process.
    LazyInit { tube: Tube },
}

pub struct Pmem {
    worker_thread: Option<WorkerThread<(Queue, Tube)>>,
    features: u64,
    disk_image: Option<File>,
    mapping_address: GuestAddress,
    mem_slot: MemSlotConfig,
    mapping_size: u64,
    pmem_device_tube: Option<Tube>,
    swap_interval: Option<Duration>,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct PmemSnapshot {
    mapping_address: GuestAddress,
    mapping_size: u64,
}

/// Configuration of a virtio-pmem device.
pub struct PmemConfig {
    /// Disk image exposed to the guest.
    /// If the memory region is not backed by a file, this should be `None`.
    pub disk_image: Option<File>,
    /// Guest physical address where the memory will be mapped.
    pub mapping_address: GuestAddress,
    pub mem_slot: MemSlotConfig,
    /// The size of the mapped region.
    pub mapping_size: u64,
    /// A communication channel to the main process to send memory requests.
    pub pmem_device_tube: Tube,
    /// Interval for periodic swap out of memory mapping
    pub swap_interval: Option<Duration>,
    /// Whether the region is writeble or not.
    pub mapping_writable: bool,
}

impl Pmem {
    pub fn new(base_features: u64, cfg: PmemConfig) -> SysResult<Pmem> {
        if cfg.mapping_size > usize::MAX as u64 {
            return Err(SysError::new(libc::EOVERFLOW));
        }

        let mut avail_features = base_features;
        if cfg.mapping_writable {
            if let MemSlotConfig::LazyInit { .. } = cfg.mem_slot {
                error!("pmem-ext2 must be a read-only device");
                return Err(SysError::new(libc::EINVAL));
            }

            avail_features |= 1 << VIRTIO_PMEM_F_DISCARD;
        }

        Ok(Pmem {
            worker_thread: None,
            features: avail_features,
            disk_image: cfg.disk_image,
            mapping_address: cfg.mapping_address,
            mem_slot: cfg.mem_slot,
            mapping_size: cfg.mapping_size,
            pmem_device_tube: Some(cfg.pmem_device_tube),
            swap_interval: cfg.swap_interval,
        })
    }
}

impl VirtioDevice for Pmem {
    fn keep_rds(&self) -> Vec<RawDescriptor> {
        let mut keep_rds = Vec::new();
        if let Some(disk_image) = &self.disk_image {
            keep_rds.push(disk_image.as_raw_descriptor());
        }

        if let Some(ref pmem_device_tube) = self.pmem_device_tube {
            keep_rds.push(pmem_device_tube.as_raw_descriptor());
        }

        if let MemSlotConfig::LazyInit { tube } = &self.mem_slot {
            keep_rds.push(tube.as_raw_descriptor());
        }

        keep_rds
    }

    fn device_type(&self) -> DeviceType {
        DeviceType::Pmem
    }

    fn queue_max_sizes(&self) -> &[u16] {
        QUEUE_SIZES
    }

    fn features(&self) -> u64 {
        self.features
    }

    fn read_config(&self, offset: u64, data: &mut [u8]) {
        let config = virtio_pmem_config {
            start_address: Le64::from(self.mapping_address.offset()),
            size: Le64::from(self.mapping_size),
        };
        copy_config(data, 0, config.as_bytes(), offset);
    }

    fn activate(
        &mut self,
        _memory: GuestMemory,
        interrupt: Interrupt,
        mut queues: BTreeMap<usize, Queue>,
    ) -> anyhow::Result<()> {
        if queues.len() != 1 {
            return Err(anyhow!("expected 1 queue, got {}", queues.len()));
        }

        let mut queue = queues.remove(&0).unwrap();

        // We checked that this fits in a usize in `Pmem::new`.
        let mapping_size = self.mapping_size as usize;

        let pmem_device_tube = self
            .pmem_device_tube
            .take()
            .context("missing pmem device tube")?;

        let swap_interval = self.swap_interval;

        let mapping_arena_slot = match &self.mem_slot {
            MemSlotConfig::MemSlot { idx } => *idx,
            MemSlotConfig::LazyInit { tube } => tube
                .recv::<u32>()
                .context("failed to receive memory slot for ext2 pmem device")?,
        };

        self.worker_thread = Some(WorkerThread::start("v_pmem", move |kill_event| {
            run_worker(
                &mut queue,
                &pmem_device_tube,
                interrupt,
                kill_event,
                mapping_arena_slot,
                mapping_size,
                swap_interval,
            );
            (queue, pmem_device_tube)
        }));

        Ok(())
    }

    fn reset(&mut self) -> anyhow::Result<()> {
        if let Some(worker_thread) = self.worker_thread.take() {
            let (_queue, pmem_device_tube) = worker_thread.stop();
            self.pmem_device_tube = Some(pmem_device_tube);
        }
        Ok(())
    }

    fn virtio_sleep(&mut self) -> anyhow::Result<Option<BTreeMap<usize, Queue>>> {
        if let Some(worker_thread) = self.worker_thread.take() {
            let (queue, pmem_device_tube) = worker_thread.stop();
            self.pmem_device_tube = Some(pmem_device_tube);
            return Ok(Some(BTreeMap::from([(0, queue)])));
        }
        Ok(None)
    }

    fn virtio_wake(
        &mut self,
        queues_state: Option<(GuestMemory, Interrupt, BTreeMap<usize, Queue>)>,
    ) -> anyhow::Result<()> {
        if let Some((mem, interrupt, queues)) = queues_state {
            self.activate(mem, interrupt, queues)?;
        }
        Ok(())
    }

    fn virtio_snapshot(&mut self) -> anyhow::Result<serde_json::Value> {
        serde_json::to_value(PmemSnapshot {
            mapping_address: self.mapping_address,
            mapping_size: self.mapping_size,
        })
        .context("failed to serialize pmem snapshot")
    }

    fn virtio_restore(&mut self, data: serde_json::Value) -> anyhow::Result<()> {
        let snapshot: PmemSnapshot =
            serde_json::from_value(data).context("failed to deserialize pmem snapshot")?;
        anyhow::ensure!(
            snapshot.mapping_address == self.mapping_address
                && snapshot.mapping_size == self.mapping_size,
            "pmem snapshot doesn't match config: expected {:?}, got {:?}",
            (self.mapping_address, self.mapping_size),
            (snapshot.mapping_address, snapshot.mapping_size),
        );
        Ok(())
    }
}