guest_watchdog/
lib.rs

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

#![expect(missing_docs)]

use chipset_device::ChipsetDevice;
use chipset_device::io::IoError;
use chipset_device::io::IoResult;
use chipset_device::pio::ControlPortIoIntercept;
use chipset_device::pio::PortIoIntercept;
use chipset_device::pio::RegisterPortIoIntercept;
use chipset_device::poll_device::PollDevice;
use inspect::Inspect;
use inspect::InspectMut;
use std::task::Context;
use vmcore::device_state::ChangeDeviceState;
use vmcore::vmtime::VmTimeAccess;
use watchdog_core::WatchdogServices;
use watchdog_core::platform::WatchdogPlatform;

open_enum::open_enum! {
    enum WatchdogPort: u16 {
        ADDRESS          = 0x0,
        DATA             = 0x4,
    }
}

pub struct GuestwatchdogRt {
    pio_static_wdat_port: Box<dyn ControlPortIoIntercept>,
}

#[derive(Debug, Inspect)]
pub struct GuestWatchdogState {
    watchdog_reg: u32,
}

#[derive(InspectMut)]
pub struct GuestWatchdogServices {
    // Runtime glue
    #[inspect(skip)]
    rt: GuestwatchdogRt,

    // Sub-emulators
    watchdog: WatchdogServices,

    // Volatile state
    state: GuestWatchdogState,
}

impl GuestWatchdogServices {
    pub async fn new(
        vmtime: VmTimeAccess,
        watchdog_platform: Box<dyn WatchdogPlatform>,
        register_pio: &mut dyn RegisterPortIoIntercept,
        pio_wdat_port: u16,
        is_restoring: bool,
    ) -> GuestWatchdogServices {
        let mut pio_static_wdat_port = register_pio.new_io_region("wdat_port", 8);

        pio_static_wdat_port.map(pio_wdat_port);

        GuestWatchdogServices {
            watchdog: WatchdogServices::new(
                "guest-watchdog",
                vmtime,
                watchdog_platform,
                is_restoring,
            )
            .await,
            state: GuestWatchdogState { watchdog_reg: 0 },
            rt: GuestwatchdogRt {
                pio_static_wdat_port,
            },
        }
    }

    fn read_data(&mut self, addr: u32) -> u32 {
        match WatchdogRegister(addr) {
            WatchdogRegister::WATCHDOG_RESOLUTION
            | WatchdogRegister::WATCHDOG_CONFIG
            | WatchdogRegister::WATCHDOG_COUNT => {
                let reg = bios_cmd_to_watchdog_register(WatchdogRegister(addr)).unwrap();
                match self.watchdog.read(reg) {
                    Ok(val) => val,
                    Err(err) => {
                        tracelimit::warn_ratelimited!(
                            error = &err as &dyn std::error::Error,
                            "Error while reading from watchdog device"
                        );
                        !0
                    }
                }
            }
            _ => {
                tracelimit::warn_ratelimited!(?addr, "unknown bios read");
                !0
            }
        }
    }

    fn write_data(&mut self, addr: u32, data: u32) {
        match WatchdogRegister(addr) {
            WatchdogRegister::WATCHDOG_RESOLUTION
            | WatchdogRegister::WATCHDOG_CONFIG
            | WatchdogRegister::WATCHDOG_COUNT => {
                let reg = bios_cmd_to_watchdog_register(WatchdogRegister(addr)).unwrap();
                match self.watchdog.write(reg, data) {
                    Ok(()) => (),
                    Err(err) => {
                        tracelimit::warn_ratelimited!(
                            error = &err as &dyn std::error::Error,
                            "Error while writing to watchdog device"
                        );
                    }
                }
            }
            _ => tracelimit::warn_ratelimited!(addr, data, "unknown bios write"),
        }
    }
}

fn bios_cmd_to_watchdog_register(cmd: WatchdogRegister) -> Option<watchdog_core::Register> {
    let res = match cmd {
        WatchdogRegister::WATCHDOG_RESOLUTION => watchdog_core::Register::Resolution,
        WatchdogRegister::WATCHDOG_CONFIG => watchdog_core::Register::Config,
        WatchdogRegister::WATCHDOG_COUNT => watchdog_core::Register::Count,
        _ => return None,
    };
    Some(res)
}

impl PollDevice for GuestWatchdogServices {
    fn poll_device(&mut self, cx: &mut Context<'_>) {
        self.watchdog.poll(cx);
    }
}

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

    async fn stop(&mut self) {}

    async fn reset(&mut self) {
        self.watchdog.reset();
        self.state.watchdog_reg = 0;
    }
}

impl ChipsetDevice for GuestWatchdogServices {
    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 GuestWatchdogServices {
    fn io_read(&mut self, io_port: u16, data: &mut [u8]) -> IoResult {
        if data.len() != 4 {
            return IoResult::Err(IoError::InvalidAccessSize);
        }

        if let Some(offset) = self.rt.pio_static_wdat_port.offset_of(io_port) {
            let v = match WatchdogPort(offset) {
                WatchdogPort::ADDRESS => self.state.watchdog_reg,
                WatchdogPort::DATA => self.read_data(self.state.watchdog_reg),
                _ => return IoResult::Err(IoError::InvalidRegister),
            };

            data.copy_from_slice(&v.to_ne_bytes());
            return IoResult::Ok;
        }
        IoResult::Err(IoError::InvalidRegister)
    }

    fn io_write(&mut self, io_port: u16, data: &[u8]) -> IoResult {
        if data.len() != 4 {
            return IoResult::Err(IoError::InvalidAccessSize);
        }

        if let Some(offset) = self.rt.pio_static_wdat_port.offset_of(io_port) {
            let v = u32::from_ne_bytes(data.try_into().unwrap());
            match WatchdogPort(offset) {
                WatchdogPort::ADDRESS => self.state.watchdog_reg = v,
                WatchdogPort::DATA => self.write_data(self.state.watchdog_reg, v),
                _ => return IoResult::Err(IoError::InvalidRegister),
            };
            return IoResult::Ok;
        }
        IoResult::Err(IoError::InvalidRegister)
    }
}

open_enum::open_enum! {
    pub enum WatchdogRegister: u32 {
        WATCHDOG_CONFIG              = 0x27,
        WATCHDOG_RESOLUTION          = 0x28,
        WATCHDOG_COUNT               = 0x29,
    }
}

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.watchdog.guest")]
        pub struct SavedState {
            #[mesh(1)]
            pub watchdog_reg: u32,
            #[mesh(2)]
            pub inner: <watchdog_core::WatchdogServices as SaveRestore>::SavedState,
        }
    }

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

        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
            let GuestWatchdogState { watchdog_reg } = self.state;
            let saved_state = state::SavedState {
                watchdog_reg,
                inner: self.watchdog.save()?,
            };

            Ok(saved_state)
        }

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