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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! PIIX4 - CMOS RTC
//!
//! Extends basic x86 CMOS RTC with a few additional ports + more RAM.

use chipset_device::io::IoError;
use chipset_device::io::IoResult;
use chipset_device::pio::PortIoIntercept;
use chipset_device::poll_device::PollDevice;
use chipset_device::ChipsetDevice;
use inspect::Inspect;
use inspect::InspectMut;
use local_clock::InspectableLocalClock;
use std::ops::RangeInclusive;
use vmcore::device_state::ChangeDeviceState;
use vmcore::line_interrupt::LineInterrupt;
use vmcore::vmtime::VmTimeSource;

open_enum::open_enum! {
    enum Piix4CmosRtcIoPort: u16 {
        ADDRESS          = 0x70,
        DATA             = 0x71,
        EXTENDED_ADDRESS = 0x72,
        EXTENDED_DATA    = 0x73,
        ADDRESS_SHADOW_2 = 0x74,
        DATA_SHADOW_2    = 0x75,
        ADDRESS_SHADOW_3 = 0x76,
        DATA_SHADOW_3    = 0x77,
    }
}

#[derive(Debug, Inspect)]
struct Piix4CmosRtcState {
    ext_addr: u8,
}

#[derive(InspectMut)]
pub struct Piix4CmosRtc {
    // Sub-emulators
    #[inspect(mut)]
    inner: chipset::cmos_rtc::Rtc,

    // Volatile state
    state: Piix4CmosRtcState,
}

impl Piix4CmosRtc {
    pub fn new(
        real_time_source: Box<dyn InspectableLocalClock>,
        interrupt: LineInterrupt,
        vmtime_source: &VmTimeSource,
        initial_cmos: Option<[u8; 256]>,
        enlightened_interrupts: bool,
    ) -> Piix4CmosRtc {
        Piix4CmosRtc {
            state: Piix4CmosRtcState { ext_addr: 0 },
            inner: chipset::cmos_rtc::Rtc::new(
                real_time_source,
                interrupt,
                vmtime_source,
                0x32,
                initial_cmos,
                enlightened_interrupts,
            ),
        }
    }
}

impl ChangeDeviceState for Piix4CmosRtc {
    fn start(&mut self) {}

    async fn stop(&mut self) {}

    async fn reset(&mut self) {
        self.inner.reset().await;
    }
}

impl ChipsetDevice for Piix4CmosRtc {
    fn supports_pio(&mut self) -> Option<&mut dyn PortIoIntercept> {
        Some(self)
    }

    fn supports_poll_device(&mut self) -> Option<&mut dyn PollDevice> {
        Some(self)
    }
}

impl PortIoIntercept for Piix4CmosRtc {
    fn io_read(&mut self, io_port: u16, data: &mut [u8]) -> IoResult {
        // We assume all accesses are one byte in size. Attempts to
        // access larger sizes will return a single byte of information
        // (zero-extended to the size of the access).
        data[0] = match Piix4CmosRtcIoPort(io_port) {
            Piix4CmosRtcIoPort::ADDRESS | Piix4CmosRtcIoPort::DATA => {
                return self.inner.io_read(io_port, data)
            }
            Piix4CmosRtcIoPort::ADDRESS_SHADOW_2 | Piix4CmosRtcIoPort::DATA_SHADOW_2 => {
                return self.inner.io_read(io_port - 4, data)
            }
            Piix4CmosRtcIoPort::EXTENDED_ADDRESS | Piix4CmosRtcIoPort::ADDRESS_SHADOW_3 => {
                self.state.ext_addr
            }
            Piix4CmosRtcIoPort::EXTENDED_DATA | Piix4CmosRtcIoPort::DATA_SHADOW_3 => {
                self.inner.get_cmos_byte(self.state.ext_addr + 128)
            }
            _ => return IoResult::Err(IoError::InvalidRegister),
        };

        IoResult::Ok
    }

    fn io_write(&mut self, io_port: u16, data: &[u8]) -> IoResult {
        // We assume all accesses are one byte in size. Attempts to
        // access larger sizes will return a single byte of information
        // (zero-extended to the size of the access).
        match Piix4CmosRtcIoPort(io_port) {
            Piix4CmosRtcIoPort::ADDRESS | Piix4CmosRtcIoPort::DATA => {
                return self.inner.io_write(io_port, data)
            }
            Piix4CmosRtcIoPort::ADDRESS_SHADOW_2 | Piix4CmosRtcIoPort::DATA_SHADOW_2 => {
                return self.inner.io_write(io_port - 4, data)
            }
            Piix4CmosRtcIoPort::EXTENDED_ADDRESS | Piix4CmosRtcIoPort::ADDRESS_SHADOW_3 => {
                self.state.ext_addr = data[0] & 0x7F;
            }
            Piix4CmosRtcIoPort::EXTENDED_DATA | Piix4CmosRtcIoPort::DATA_SHADOW_3 => {
                self.inner.set_cmos_byte(self.state.ext_addr + 128, data[0]);
            }
            _ => return IoResult::Err(IoError::InvalidRegister),
        }

        IoResult::Ok
    }

    fn get_static_regions(&mut self) -> &[(&str, RangeInclusive<u16>)] {
        &[
            (
                "io",
                (Piix4CmosRtcIoPort::ADDRESS.0)..=(Piix4CmosRtcIoPort::DATA.0),
            ),
            (
                "io-ext",
                (Piix4CmosRtcIoPort::EXTENDED_ADDRESS.0)..=(Piix4CmosRtcIoPort::DATA_SHADOW_3.0),
            ),
        ]
    }
}

impl PollDevice for Piix4CmosRtc {
    fn poll_device(&mut self, cx: &mut std::task::Context<'_>) {
        self.inner.poll_device(cx)
    }
}

mod save_restore {
    use super::*;
    use vmcore::save_restore::RestoreError;
    use vmcore::save_restore::SaveError;
    use vmcore::save_restore::SaveRestore;

    mod state {
        use mesh::payload::Protobuf;
        use vmcore::save_restore::SaveRestore;
        use vmcore::save_restore::SavedStateRoot;

        #[derive(Protobuf, SavedStateRoot)]
        #[mesh(package = "chipset.piix4.cmos_rtc")]
        pub struct SavedState {
            #[mesh(1)]
            pub ext_addr: u8,
            #[mesh(2)]
            pub inner: <chipset::cmos_rtc::Rtc as SaveRestore>::SavedState,
        }
    }

    impl SaveRestore for Piix4CmosRtc {
        type SavedState = state::SavedState;

        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
            let Piix4CmosRtcState { ext_addr } = self.state;

            let saved_state = state::SavedState {
                ext_addr,
                inner: self.inner.save()?,
            };

            Ok(saved_state)
        }

        fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
            let state::SavedState { ext_addr, inner } = state;
            self.state = Piix4CmosRtcState { ext_addr };
            self.inner.restore(inner)?;
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use local_clock::MockLocalClock;

    fn new_test_rtc() -> (
        pal_async::DefaultPool,
        vmcore::vmtime::VmTimeKeeper,
        Piix4CmosRtc,
    ) {
        let mut pool = pal_async::DefaultPool::new();
        let driver = pool.driver();
        let vm_time_keeper =
            vmcore::vmtime::VmTimeKeeper::new(&driver, vmcore::vmtime::VmTime::from_100ns(0));
        let vm_time_source = pool
            .run_until(vm_time_keeper.builder().build(&driver))
            .unwrap();

        let rtc = Piix4CmosRtc::new(
            Box::new(MockLocalClock::new()),
            LineInterrupt::detached(),
            &vm_time_source,
            None,
            false,
        );

        (pool, vm_time_keeper, rtc)
    }

    fn get_cmos_data(rtc: &mut Piix4CmosRtc, addr: u8) -> u8 {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::ADDRESS.0, &temp).unwrap();
        rtc.io_read(Piix4CmosRtcIoPort::DATA.0, &mut temp).unwrap();
        temp[0]
    }

    fn set_cmos_data(rtc: &mut Piix4CmosRtc, addr: u8, data: u8) {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::ADDRESS.0, &temp).unwrap();
        temp[0] = data;
        rtc.io_write(Piix4CmosRtcIoPort::DATA.0, &temp).unwrap();
    }

    fn get_ext_cmos_data(rtc: &mut Piix4CmosRtc, addr: u8) -> u8 {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::EXTENDED_ADDRESS.0, &temp)
            .unwrap();
        rtc.io_read(Piix4CmosRtcIoPort::EXTENDED_DATA.0, &mut temp)
            .unwrap();
        temp[0]
    }

    fn set_ext_cmos_data(rtc: &mut Piix4CmosRtc, addr: u8, data: u8) {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::EXTENDED_ADDRESS.0, &temp)
            .unwrap();
        temp[0] = data;
        rtc.io_write(Piix4CmosRtcIoPort::EXTENDED_DATA.0, &temp)
            .unwrap();
    }

    fn get_cmos_data_shadow(rtc: &mut Piix4CmosRtc, addr: u8) -> u8 {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::ADDRESS_SHADOW_2.0, &temp)
            .unwrap();
        rtc.io_read(Piix4CmosRtcIoPort::DATA_SHADOW_2.0, &mut temp)
            .unwrap();
        temp[0]
    }

    fn set_cmos_data_shadow(rtc: &mut Piix4CmosRtc, addr: u8, data: u8) {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::ADDRESS_SHADOW_2.0, &temp)
            .unwrap();
        temp[0] = data;
        rtc.io_write(Piix4CmosRtcIoPort::DATA_SHADOW_2.0, &temp)
            .unwrap();
    }

    fn get_ext_cmos_data_shadow(rtc: &mut Piix4CmosRtc, addr: u8) -> u8 {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::ADDRESS_SHADOW_3.0, &temp)
            .unwrap();
        rtc.io_read(Piix4CmosRtcIoPort::DATA_SHADOW_3.0, &mut temp)
            .unwrap();
        temp[0]
    }

    fn set_ext_cmos_data_shadow(rtc: &mut Piix4CmosRtc, addr: u8, data: u8) {
        let mut temp = [addr];
        rtc.io_write(Piix4CmosRtcIoPort::ADDRESS_SHADOW_3.0, &temp)
            .unwrap();
        temp[0] = data;
        rtc.io_write(Piix4CmosRtcIoPort::DATA_SHADOW_3.0, &temp)
            .unwrap();
    }

    #[test]
    fn test_writeable() {
        let (_, _, mut rtc) = new_test_rtc();

        //Rigisters 0x0f..0x7f should be writable, skip 0x32 which is century field of RTC
        for i in 0x0F..=0x7F {
            if i == 0x32 {
                continue;
            }

            set_cmos_data(&mut rtc, i, 0xFF);
            assert_eq!(get_cmos_data(&mut rtc, i), 0xFF);
            assert_eq!(get_cmos_data_shadow(&mut rtc, i), 0xFF);
            set_cmos_data(&mut rtc, i, 0);
            assert_eq!(get_cmos_data(&mut rtc, i), 0);
            assert_eq!(get_cmos_data_shadow(&mut rtc, i), 0);
            set_cmos_data_shadow(&mut rtc, i, 0xFF);
            assert_eq!(get_cmos_data(&mut rtc, i), 0xFF);
            assert_eq!(get_cmos_data_shadow(&mut rtc, i), 0xFF);
            set_cmos_data_shadow(&mut rtc, i, 0);
            assert_eq!(get_cmos_data(&mut rtc, i), 0);
            assert_eq!(get_cmos_data_shadow(&mut rtc, i), 0);
        }
    }

    #[test]
    fn test_writeable_ext() {
        let (_, _, mut rtc) = new_test_rtc();

        //Rigisters 0x80..0xff should be writable through extended gate 0x72/0x73
        for i in 0..=0x7F {
            set_ext_cmos_data(&mut rtc, i, 0xFF);
            assert_eq!(get_ext_cmos_data(&mut rtc, i), 0xFF);
            assert_eq!(get_ext_cmos_data_shadow(&mut rtc, i), 0xFF);
            set_ext_cmos_data(&mut rtc, i, 0);
            assert_eq!(get_ext_cmos_data(&mut rtc, i), 0);
            assert_eq!(get_ext_cmos_data_shadow(&mut rtc, i), 0);
            set_ext_cmos_data_shadow(&mut rtc, i, 0xFF);
            assert_eq!(get_ext_cmos_data(&mut rtc, i), 0xFF);
            assert_eq!(get_ext_cmos_data_shadow(&mut rtc, i), 0xFF);
            set_ext_cmos_data_shadow(&mut rtc, i, 0);
            assert_eq!(get_ext_cmos_data(&mut rtc, i), 0);
            assert_eq!(get_ext_cmos_data_shadow(&mut rtc, i), 0);
        }
    }
}