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
use std::rc::Rc;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use femtos::{Instant, Duration};

use crate::{Bus, Error, InterruptController, Address, Device};


pub struct System {
    pub clock: Instant,
    pub devices: HashMap<String, Device>,
    pub event_queue: Vec<NextStep>,

    pub debuggables: Vec<Device>,

    pub bus: Rc<RefCell<Bus>>,
    pub buses: HashMap<String, Rc<RefCell<Bus>>>,
    pub interrupt_controller: RefCell<InterruptController>,
}

impl Default for System {
    fn default() -> Self {
        Self {
            clock: Instant::START,
            devices: HashMap::new(),
            event_queue: vec![],

            debuggables: Vec::new(),

            bus: Rc::new(RefCell::new(Bus::default())),
            buses: HashMap::new(),
            interrupt_controller: RefCell::new(InterruptController::default()),
        }
    }
}

impl System {
    pub fn get_bus(&self) -> RefMut<'_, Bus> {
        self.bus.borrow_mut()
    }

    pub fn get_interrupt_controller(&self) -> RefMut<'_, InterruptController> {
        self.interrupt_controller.borrow_mut()
    }

    pub fn get_device(&self, name: &str) -> Result<Device, Error> {
        self.devices
            .get(name)
            .cloned()
            .ok_or_else(|| Error::new(format!("system: no device named {}", name)))
    }

    pub fn add_device(&mut self, name: &str, device: Device) -> Result<(), Error> {
        self.try_add_debuggable(device.clone());
        self.try_queue_device(device.clone());
        self.devices.insert(name.to_string(), device);
        Ok(())
    }

    pub fn add_addressable_device(&mut self, addr: Address, device: Device) -> Result<(), Error> {
        self.add_peripheral(&format!("mem{:x}", addr), addr, device)
    }

    pub fn add_peripheral(&mut self, name: &str, addr: Address, device: Device) -> Result<(), Error> {
        self.bus.borrow_mut().insert(addr, device.clone());
        self.try_add_debuggable(device.clone());
        self.try_queue_device(device.clone());
        self.devices.insert(name.to_string(), device);
        Ok(())
    }

    pub fn add_interruptable_device(&mut self, name: &str, device: Device) -> Result<(), Error> {
        self.try_add_debuggable(device.clone());
        self.try_queue_device(device.clone());
        self.devices.insert(name.to_string(), device);
        Ok(())
    }

    fn process_one_event(&mut self) -> Result<(), Error> {
        let mut event_device = self.event_queue.pop().unwrap();
        self.clock = event_device.next_clock;
        let result = match event_device.device.borrow_mut().as_steppable().unwrap().step(self) {
            Ok(diff) => {
                event_device.next_clock = self.clock.checked_add(diff).unwrap();
                Ok(())
            },
            Err(err) => Err(err),
        };
        self.queue_device(event_device);
        result
    }

    /// Step the simulation one event exactly
    pub fn step(&mut self) -> Result<(), Error> {
        match self.process_one_event() {
            Ok(()) => {},
            Err(err @ Error::Breakpoint(_)) => {
                return Err(err);
            },
            Err(err) => {
                self.exit_error();
                log::error!("{:?}", err);
                return Err(err);
            },
        }
        Ok(())
    }

    /// Step through the simulation until the next event is for the given device
    pub fn step_until_device(&mut self, device: Device) -> Result<(), Error> {
        loop {
            self.step()?;

            if self.get_next_event_device().id() == device.id() {
                break;
            }
        }
        Ok(())
    }

    /// Step through the simulation until the next event scheduled is for a debuggable device
    pub fn step_until_debuggable(&mut self) -> Result<(), Error> {
        loop {
            self.step()?;

            if self.get_next_event_device().borrow_mut().as_debuggable().is_some() {
                break;
            }
        }
        Ok(())
    }

    /// Run the simulation until the given simulation clock time has been reached
    pub fn run_until_clock(&mut self, clock: Instant) -> Result<(), Error> {
        while self.clock < clock {
            self.step()?;
        }
        Ok(())
    }

    /// Run the simulation for `elapsed` amount of simulation time
    pub fn run_for_duration(&mut self, elapsed: Duration) -> Result<(), Error> {
        let target = self.clock + elapsed;

        while self.clock < target {
            self.step()?;
        }
        Ok(())
    }

    /// Run the simulation forever, or until there is an error
    pub fn run_forever(&mut self) -> Result<(), Error> {
        self.run_until_clock(Instant::FOREVER)
    }

    pub fn exit_error(&mut self) {
        for (_, dev) in self.devices.iter() {
            if let Some(dev) = dev.borrow_mut().as_steppable() {
                dev.on_error(self);
            }
        }
    }

    pub fn get_next_event_device(&self) -> Device {
        self.event_queue[self.event_queue.len() - 1].device.clone()
    }

    pub fn get_next_debuggable_device(&self) -> Option<Device> {
        for event in self.event_queue.iter().rev() {
            if event.device.borrow_mut().as_debuggable().is_some() {
                return Some(event.device.clone());
            }
        }
        None
    }

    fn try_add_debuggable(&mut self, device: Device) {
        if device.borrow_mut().as_debuggable().is_some() {
            self.debuggables.push(device);
        }
    }

    fn try_queue_device(&mut self, device: Device) {
        if device.borrow_mut().as_steppable().is_some() {
            self.queue_device(NextStep::new(device));
        }
    }

    fn queue_device(&mut self, device_step: NextStep) {
        for (i, event) in self.event_queue.iter().enumerate().rev() {
            if event.next_clock > device_step.next_clock {
                self.event_queue.insert(i + 1, device_step);
                return;
            }
        }
        self.event_queue.insert(0, device_step);
    }
}


pub struct NextStep {
    pub next_clock: Instant,
    pub device: Device,
}

impl NextStep {
    pub fn new(device: Device) -> Self {
        Self {
            next_clock: Instant::START,
            device,
        }
    }
}

/*
use emulator_hal::bus::{BusType, BusAccess};

impl BusType for System {
    type Address = u64;
    type Error = Error;
    type Instant = Instant;
}

impl BusAccess for System {
    fn read(&mut self, _now: Instant, addr: u64, data: &mut [u8]) -> Result<usize, Self::Error> {
        let addr = addr as usize;
        data.copy_from_slice(&self.0[addr..addr + data.len()]);
        Ok(data.len())
    }

    fn write(&mut self, _now: Instant, addr: u64, data: &[u8]) -> Result<usize, Self::Error> {
        let addr = addr as usize;
        self.0[addr..addr + data.len()].copy_from_slice(data);
        Ok(data.len())
    }
}
*/