ckb_vm/
snapshot.rs

1use crate::instructions::Register;
2use crate::memory::Memory;
3use crate::memory::FLAG_DIRTY;
4use crate::{CoreMachine, Error, RISCV_GENERAL_REGISTER_NUMBER, RISCV_PAGESIZE, RISCV_PAGE_SHIFTS};
5use serde::{Deserialize, Serialize};
6
7// Snapshot provides a mechanism for suspending and resuming a virtual machine.
8//
9// When cycle limit is too low, our work won't be finished when we hit it and
10// a "max cycles exceeded" error will be returned. At this time, a snapshot could
11// be created, we can create a new virtual machine from this snapshot, provide
12// more cycles and then continue to run it.
13//
14// For the following data, we simply save them, and then restore them.
15//   - machine.version
16//   - machine.pc
17//   - machine.registers
18//
19// For memory, the situation becomes more complicated. Every memory page has
20// page flag where each page flag stores a optional FLAG_DIRTY. When this page
21// is wrote, the memory instance will set this bit to 1, this helps us keep
22// track of those pages that have been modified. After `machine.load_elf`, We
23// clean up all dirty flags, so after the program terminates, all pages marked
24// as dirty are the pages that have been modified by the program. We only store
25// these pages in the snapshot.
26
27#[derive(Default, Deserialize, Serialize)]
28pub struct Snapshot {
29    pub version: u32,
30    pub registers: [u64; RISCV_GENERAL_REGISTER_NUMBER],
31    pub pc: u64,
32    pub page_indices: Vec<u64>,
33    pub page_flags: Vec<u8>,
34    pub pages: Vec<Vec<u8>>,
35    pub load_reservation_address: u64,
36}
37
38pub fn make_snapshot<T: CoreMachine>(machine: &mut T) -> Result<Snapshot, Error> {
39    let mut snap = Snapshot {
40        version: machine.version(),
41        pc: machine.pc().to_u64(),
42        load_reservation_address: machine.memory().lr().to_u64(),
43        ..Default::default()
44    };
45    for (i, v) in machine.registers().iter().enumerate() {
46        snap.registers[i] = v.to_u64();
47    }
48
49    for i in 0..machine.memory().memory_pages() {
50        let flag = machine.memory_mut().fetch_flag(i as u64)?;
51        if flag & FLAG_DIRTY != 0 {
52            let addr_from = i << RISCV_PAGE_SHIFTS;
53            let addr_to = (i + 1) << RISCV_PAGE_SHIFTS;
54
55            let mut page = vec![0; RISCV_PAGESIZE];
56            for i in (addr_from..addr_to).step_by(8) {
57                let v64 = machine
58                    .memory_mut()
59                    .load64(&T::REG::from_u64(i as u64))?
60                    .to_u64();
61                let j = i - addr_from;
62                page[j] = v64 as u8;
63                page[j + 1] = (v64 >> 8) as u8;
64                page[j + 2] = (v64 >> 16) as u8;
65                page[j + 3] = (v64 >> 24) as u8;
66                page[j + 4] = (v64 >> 32) as u8;
67                page[j + 5] = (v64 >> 40) as u8;
68                page[j + 6] = (v64 >> 48) as u8;
69                page[j + 7] = (v64 >> 56) as u8;
70            }
71
72            snap.page_indices.push(i as u64);
73            snap.page_flags.push(flag);
74            snap.pages.push(page);
75        }
76    }
77    Ok(snap)
78}
79
80pub fn resume<T: CoreMachine>(machine: &mut T, snapshot: &Snapshot) -> Result<(), Error> {
81    if machine.version() != snapshot.version {
82        return Err(Error::InvalidVersion);
83    }
84    for (i, v) in snapshot.registers.iter().enumerate() {
85        machine.set_register(i, T::REG::from_u64(*v));
86    }
87    machine.update_pc(T::REG::from_u64(snapshot.pc));
88    machine.commit_pc();
89    for i in 0..snapshot.page_indices.len() {
90        let page_index = snapshot.page_indices[i];
91        let page_flag = snapshot.page_flags[i];
92        let page = &snapshot.pages[i];
93        let addr_from = page_index << RISCV_PAGE_SHIFTS;
94        machine.memory_mut().store_bytes(addr_from, &page[..])?;
95        machine.memory_mut().set_flag(page_index, page_flag)?;
96    }
97    machine
98        .memory_mut()
99        .set_lr(&T::REG::from_u64(snapshot.load_reservation_address));
100    Ok(())
101}