rvsim-core 2.0.0

A cycle-level RISC-V 64-bit system simulator.
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
//! The virtio block device (MMIO).
//!
//! Implements a virtio block device over Memory-Mapped I/O (MMIO) for disk access.
//! Supports the legacy virtio interface required by the Linux kernel.

mod checkpoint;
mod queue;

use crate::common::{IrqId, LineAddr, PhysAddr};
use crate::sim::components::{ComponentId, ReqId};
use crate::sim::handle::{Handle, HandleCtx};
use crate::sim::memory::GlobalMemory;
use crate::sim::packet::{AccessSize, HitLevel, MemOp, MemRespData, MesiState, Packet, WriteData};
use crate::soc::devices::Device;
use std::collections::BTreeSet;
use std::collections::VecDeque;

use serde::{Deserialize, Serialize};

/// virtio MMIO magic value register offset.
const REG_MAGIC: u64 = 0x00;

/// virtio MMIO version register offset.
const REG_VERSION: u64 = 0x04;

/// virtio MMIO device ID register offset.
const REG_DEVICE_ID: u64 = 0x08;

/// virtio MMIO vendor ID register offset.
const REG_VENDOR_ID: u64 = 0x0c;

/// virtio MMIO device features register offset.
const REG_DEVICE_FEATURES: u64 = 0x10;

/// virtio MMIO device features select register offset.
const REG_DEVICE_FEATURES_SEL: u64 = 0x14;

/// virtio MMIO driver features register offset — writes ignored (no feature negotiation).
const _REG_DRIVER_FEATURES: u64 = 0x20;

/// virtio MMIO driver features select register offset.
const REG_DRIVER_FEATURES_SEL: u64 = 0x24;

/// virtio MMIO queue select register offset — writes ignored.
const _REG_QUEUE_SEL: u64 = 0x30;

/// virtio MMIO queue maximum size register offset.
const REG_QUEUE_NUM_MAX: u64 = 0x34;

/// virtio MMIO queue size register offset.
const REG_QUEUE_NUM: u64 = 0x38;

/// virtio MMIO queue ready register offset.
const REG_QUEUE_READY: u64 = 0x44;

/// virtio MMIO queue notify register offset.
const REG_QUEUE_NOTIFY: u64 = 0x50;

/// virtio MMIO interrupt status register offset.
const REG_INTERRUPT_STATUS: u64 = 0x60;

/// virtio MMIO interrupt acknowledge register offset.
const REG_INTERRUPT_ACK: u64 = 0x64;

/// virtio MMIO device status register offset.
const REG_STATUS: u64 = 0x70;

/// virtio MMIO queue descriptor table address (low 32 bits) register offset.
const REG_QUEUE_DESC_LOW: u64 = 0x80;

/// virtio MMIO queue descriptor table address (high 32 bits) register offset.
const REG_QUEUE_DESC_HIGH: u64 = 0x84;

/// virtio MMIO queue available ring address (low 32 bits) register offset.
const REG_QUEUE_AVAIL_LOW: u64 = 0x90;

/// virtio MMIO queue available ring address (high 32 bits) register offset.
const REG_QUEUE_AVAIL_HIGH: u64 = 0x94;

/// virtio MMIO queue used ring address (low 32 bits) register offset.
const REG_QUEUE_USED_LOW: u64 = 0xa0;

/// virtio MMIO queue used ring address (high 32 bits) register offset.
const REG_QUEUE_USED_HIGH: u64 = 0xa4;

/// virtio MMIO configuration space base offset.
const REG_CONFIG_BASE: u64 = 0x100;

/// virtio MMIO magic value ("virt" in ASCII: 0x74726976).
const VIRTIO_MMIO_MAGIC_VALUE: u32 = 0x74726976;

/// virtio MMIO vendor ID value (QEMU vendor: 0x554d4551).
const VIRTIO_MMIO_VENDOR_ID_VALUE: u32 = 0x554d4551;

/// virtio MMIO device ID for block device (2).
const VIRTIO_MMIO_DEVICE_ID_VALUE: u32 = 2;

/// virtio specification version (2).
const VIRTIO_VERSION_VALUE: u32 = 2;

/// Maximum queue size supported by this device (16 entries).
const QUEUE_NUM_MAX_VALUE: u32 = 16;

/// Size of a virtqueue descriptor in bytes (16 bytes).
const DESC_SIZE: u64 = 16;

/// Offset of address field within descriptor (bytes 0-7).
const DESC_OFFSET_ADDR: u64 = 0;

/// Offset of length field within descriptor (bytes 8-11).
const DESC_OFFSET_LEN: u64 = 8;

/// Offset of flags field within descriptor (bytes 12-13).
const DESC_OFFSET_FLAGS: u64 = 12;

/// Offset of next descriptor index field within descriptor (bytes 14-15).
const DESC_OFFSET_NEXT: u64 = 14;

/// Virtqueue descriptor flag: indicates chained descriptors (more descriptors follow).
const VRING_DESC_F_NEXT: u16 = 1;

/// Virtqueue descriptor flag: indicates write-only descriptor (device writes to memory).
const VRING_DESC_F_WRITE: u16 = 2;

/// Disk sector size in bytes (512 bytes per sector).
const SECTOR_SIZE: u64 = 512;

/// Bytes a DMA transfer moves at most: one cache line.
const LINE_BYTES: u64 = 64;

/// virtio Block device structure.
///
/// Implements a memory-mapped block device compliant with the virtio
/// specification. Its DMA reads and writes the system's memory image.
#[derive(Debug)]
pub struct VirtioBlock {
    /// Base physical address of the device MMIO region.
    base_addr: u64,
    /// Disk image data.
    disk_image: Vec<u8>,
    /// Digest of the image as loaded.
    image_digest: u64,
    /// Sectors the guest has written since the image was loaded.
    written: BTreeSet<u64>,

    /// Device status register.
    status: u32,
    /// Configured queue size.
    queue_num: u32,
    /// Queue ready bit.
    queue_ready: u32,
    /// Queue notify register (triggers processing).
    queue_notify: u32,

    /// Queue Descriptor Table address (Low 32 bits).
    queue_desc_low: u32,
    /// Queue Descriptor Table address (High 32 bits).
    queue_desc_high: u32,
    /// Queue Available Ring address (Low 32 bits).
    queue_avail_low: u32,
    /// Queue Available Ring address (High 32 bits).
    queue_avail_high: u32,
    /// Queue Used Ring address (Low 32 bits).
    queue_used_low: u32,
    /// Queue Used Ring address (High 32 bits).
    queue_used_high: u32,

    /// Interrupt status register.
    interrupt_status: u32,
    /// Last processed available index.
    last_avail_idx: u16,

    /// Device features selection.
    device_features_sel: u32,
    /// Driver features selection.
    driver_features_sel: u32,

    /// The request whose DMA is in flight.
    job: Option<DmaJob>,
    /// Sequence number of the next DMA request id.
    next_dma_seq: u64,
}

/// The device's registers, as a checkpoint carries them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VirtioBlockState {
    /// Device status register.
    pub status: u32,
    /// Configured queue size.
    pub queue_num: u32,
    /// Queue ready bit.
    pub queue_ready: u32,
    /// Queue notify register.
    pub queue_notify: u32,
    /// Descriptor table address, low half.
    pub queue_desc_low: u32,
    /// Descriptor table address, high half.
    pub queue_desc_high: u32,
    /// Available ring address, low half.
    pub queue_avail_low: u32,
    /// Available ring address, high half.
    pub queue_avail_high: u32,
    /// Used ring address, low half.
    pub queue_used_low: u32,
    /// Used ring address, high half.
    pub queue_used_high: u32,
    /// Interrupt status register.
    pub interrupt_status: u32,
    /// Next available ring index to process.
    pub last_avail_idx: u16,
    /// Device features selector.
    pub device_features_sel: u32,
    /// Driver features selector.
    pub driver_features_sel: u32,
    /// Sequence number of the next DMA request id.
    pub next_dma_seq: u64,
    /// Digest of the disk image as loaded, which a restore must match.
    pub image_digest: u64,
    /// Every sector the guest has written since the image was loaded.
    pub written: Vec<WrittenSector>,
}

/// A sector the guest wrote, as a checkpoint carries it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WrittenSector {
    /// The sector number.
    pub sector: u64,
    /// Its contents, as hex.
    pub data: String,
}

/// A 64-bit FNV-1a digest of `bytes`, taken 8 bytes at a time.
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

fn digest(bytes: &[u8]) -> u64 {
    let mut hash = FNV_OFFSET;
    let (words, rest) = bytes.as_chunks::<8>();
    for &word in words {
        hash = (hash ^ u64::from_le_bytes(word)).wrapping_mul(FNV_PRIME);
    }
    for &byte in rest {
        hash = (hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME);
    }
    hash ^ bytes.len() as u64
}

fn to_hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut text = String::with_capacity(bytes.len() * 2);
    for &byte in bytes {
        text.push(char::from(DIGITS[usize::from(byte >> 4)]));
        text.push(char::from(DIGITS[usize::from(byte & 0xf)]));
    }
    text
}

fn from_hex(text: &str) -> Option<Vec<u8>> {
    (0..text.len())
        .step_by(2)
        .map(|i| text.get(i..i + 2).and_then(|pair| u8::from_str_radix(pair, 16).ok()))
        .collect()
}

/// One DMA transfer of a request, as the bus sees it.
#[derive(Clone, Copy, Debug)]
struct DmaAccess {
    paddr: PhysAddr,
    size: AccessSize,
    write: bool,
}

impl DmaAccess {
    const fn read(paddr: u64, size: AccessSize) -> Self {
        Self { paddr: PhysAddr::new(paddr), size, write: false }
    }

    const fn write(paddr: u64, size: AccessSize) -> Self {
        Self { paddr: PhysAddr::new(paddr), size, write: true }
    }
}

/// A request in flight: the DMA phases still to issue and the transfers
/// of the current phase not yet answered.
#[derive(Debug)]
struct DmaJob {
    head_idx: u16,
    phases: VecDeque<Vec<DmaAccess>>,
    outstanding: Vec<ReqId>,
}

/// `[addr, addr + len)` as line-sized transfers, one per cache line touched.
fn line_chunks(addr: u64, len: u64, write: bool) -> Vec<DmaAccess> {
    let mut chunks = Vec::new();
    let mut start = addr;
    let end = addr.saturating_add(len);
    while start < end {
        chunks.push(DmaAccess { paddr: PhysAddr::new(start), size: AccessSize::Line, write });
        start = (start | (LINE_BYTES - 1)) + 1;
    }
    chunks
}

impl VirtioBlock {
    /// A device with no disk image, mapped at `base_addr`.
    pub const fn new(base_addr: u64) -> Self {
        Self {
            base_addr,
            disk_image: Vec::new(),
            image_digest: FNV_OFFSET,
            written: BTreeSet::new(),
            status: 0,
            queue_num: 0,
            queue_ready: 0,
            queue_notify: 0,
            queue_desc_low: 0,
            queue_desc_high: 0,
            queue_avail_low: 0,
            queue_avail_high: 0,
            queue_used_low: 0,
            queue_used_high: 0,
            interrupt_status: 0,
            last_avail_idx: 0,
            device_features_sel: 0,
            driver_features_sel: 0,
            job: None,
            next_dma_seq: 0,
        }
    }

    /// Loads a disk image into the device.
    pub fn load(&mut self, data: Vec<u8>) {
        self.image_digest = digest(&data);
        self.written.clear();
        self.disk_image = data;
    }
}

impl VirtioBlock {
    fn read_u32_reg(&self, offset: u64) -> u32 {
        match offset {
            REG_MAGIC => VIRTIO_MMIO_MAGIC_VALUE,
            REG_VERSION => VIRTIO_VERSION_VALUE,
            REG_DEVICE_ID => VIRTIO_MMIO_DEVICE_ID_VALUE,
            REG_VENDOR_ID => VIRTIO_MMIO_VENDOR_ID_VALUE,
            REG_DEVICE_FEATURES => {
                if self.device_features_sel == 1 {
                    1
                } else {
                    0
                }
            }
            REG_QUEUE_NUM_MAX => QUEUE_NUM_MAX_VALUE,
            REG_QUEUE_READY => self.queue_ready,
            REG_INTERRUPT_STATUS => self.interrupt_status,
            REG_STATUS => self.status,
            _ => {
                if (REG_CONFIG_BASE..REG_CONFIG_BASE + 0x100).contains(&offset) {
                    let config_offset = offset - REG_CONFIG_BASE;
                    match config_offset {
                        0 => (self.disk_image.len() as u64 / SECTOR_SIZE) as u32,
                        4 => ((self.disk_image.len() as u64 / SECTOR_SIZE) >> 32) as u32,
                        _ => 0,
                    }
                } else {
                    0
                }
            }
        }
    }

    const fn write_u32_reg(&mut self, offset: u64, val: u32) {
        match offset {
            REG_DEVICE_FEATURES_SEL => self.device_features_sel = val,
            REG_DRIVER_FEATURES_SEL => self.driver_features_sel = val,
            REG_QUEUE_NUM => self.queue_num = val,
            REG_QUEUE_READY => self.queue_ready = val,
            REG_QUEUE_NOTIFY => self.queue_notify = val,
            REG_INTERRUPT_ACK => self.interrupt_status &= !val,
            REG_STATUS => self.status = val,
            REG_QUEUE_DESC_LOW => self.queue_desc_low = val,
            REG_QUEUE_DESC_HIGH => self.queue_desc_high = val,
            REG_QUEUE_AVAIL_LOW => self.queue_avail_low = val,
            REG_QUEUE_AVAIL_HIGH => self.queue_avail_high = val,
            REG_QUEUE_USED_LOW => self.queue_used_low = val,
            REG_QUEUE_USED_HIGH => self.queue_used_high = val,
            _ => {}
        }
    }
}

impl Handle for VirtioBlock {
    fn handle(&mut self, packet: Packet, source: ComponentId, ctx: &mut HandleCtx<'_>) {
        if let Packet::MemResp { req_id, .. } = packet {
            self.on_dma_response(req_id, ctx);
            return;
        }
        if let Packet::MemReq { req_id, paddr, size, op, .. } = packet {
            let offset = paddr.val().saturating_sub(self.base_addr);
            let notified = matches!(op, MemOp::Write { .. }) && (offset & !3) == REG_QUEUE_NOTIFY;
            let value: u64 = match (size, op) {
                (
                    AccessSize::B4 | AccessSize::B8,
                    MemOp::Read | MemOp::ReadOwn | MemOp::Fetch | MemOp::Atomic { .. },
                ) => u64::from(self.read_u32_reg(offset)),
                (
                    AccessSize::B1,
                    MemOp::Read | MemOp::ReadOwn | MemOp::Fetch | MemOp::Atomic { .. },
                ) => {
                    let aligned = offset & !3;
                    let shift = (offset & 3) * 8;
                    u64::from((self.read_u32_reg(aligned) >> shift) as u8)
                }
                (
                    AccessSize::B2,
                    MemOp::Read | MemOp::ReadOwn | MemOp::Fetch | MemOp::Atomic { .. },
                ) => {
                    let aligned = offset & !3;
                    let shift = (offset & 3) * 8;
                    u64::from((self.read_u32_reg(aligned) >> shift) as u16)
                }
                (
                    AccessSize::B4 | AccessSize::B8,
                    MemOp::Write { data: WriteData::Small(val), .. },
                ) => {
                    self.write_u32_reg(offset, val as u32);
                    0
                }
                (
                    AccessSize::B1 | AccessSize::B2,
                    MemOp::Write { data: WriteData::Small(val), .. },
                ) => {
                    self.write_u32_reg(offset & !3, val as u32);
                    0
                }
                _ => 0,
            };
            ctx.scheduler.schedule(
                ctx.cycle + ctx.config.system.device_access_cycles(self.name()),
                source,
                ctx.self_id,
                Packet::MemResp {
                    req_id,
                    line_addr: LineAddr::from_phys(paddr, 64),
                    data: MemRespData::Small(value),
                    hit_level: HitLevel::Mmio,
                    state: MesiState::Exclusive,
                },
            );
            if notified {
                tracing::trace!(target: "rvsim::dma", cycle = ctx.cycle, busy = self.job.is_some(), "virtio: notified");
                self.start_next_request(ctx);
            }
        }
    }
}

impl Device for VirtioBlock {
    /// A request in flight moves on DMA responses; without one the device
    /// waits for the driver.
    fn quiet_ticks(&self) -> Option<u64> {
        if self.job.is_some() { Some(0) } else { None }
    }

    /// Completes the request in flight and every chain still available
    /// at once: after a restore nothing would notify the device again.
    fn drain(&mut self, memory: &mut GlobalMemory) {
        if let Some(job) = self.job.take() {
            self.complete_request(job.head_idx, memory);
        }
        while let Some((head_idx, _)) = self.next_available_chain(memory) {
            self.complete_request(head_idx, memory);
        }
    }

    fn checkpoint(&self) -> Option<serde_json::Value> {
        serde_json::to_value(self.state()).ok()
    }

    fn check_restore(&self, state: &serde_json::Value) -> Result<(), String> {
        let state = serde_json::from_value::<VirtioBlockState>(state.clone())
            .map_err(|error| format!("virtio disk state: {error}"))?;
        self.check_state(&state)
    }

    fn restore(&mut self, state: &serde_json::Value) -> Result<(), String> {
        let state = serde_json::from_value::<VirtioBlockState>(state.clone())
            .map_err(|error| format!("virtio disk state: {error}"))?;
        self.set_state(&state)
    }

    fn name(&self) -> &'static str {
        "VirtIO-Blk"
    }

    fn address_range(&self) -> (u64, u64) {
        (self.base_addr, 0x1000)
    }

    fn tick(&mut self) -> bool {
        (self.interrupt_status & 1) != 0
    }

    fn get_irq_id(&self) -> Option<IrqId> {
        Some(IrqId::new(1))
    }
}