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

//! Real Time Clock Interface used by the UEFI Time Service
//!
//! Provides an interface to persist the time set by the guest (with UEFI
//! SetTime) so that the time retrieved by the guest (with UEFI GetTime)
//! reflects the time that has elapsed. Currently only used on ARM64.

use crate::UefiDevice;
use guestmem::GuestMemoryError;
use inspect::InspectMut;
use local_clock::InspectableLocalClock;
use thiserror::Error;
use time::OffsetDateTime;
use uefi_specs::hyperv::time::VmEfiTime;
use uefi_specs::uefi::common::EfiStatus;
use uefi_specs::uefi::time::EfiDaylight;
use uefi_specs::uefi::time::EfiTimezone;
use uefi_specs::uefi::time::EFI_TIME;

#[derive(Debug, Error)]
pub enum TimeServiceError {
    #[error("Invalid Argument")]
    InvalidArg,
    #[error("Time")]
    Time(#[from] time::Error),
    #[error("Overflow")]
    Overflow,
}

/// The same information as [`EFI_TIME`] but backed by [`OffsetDateTime`]
/// instead of raw numbers to make the values easier to manipulate.
struct EfiOffsetDateTime {
    datetime: OffsetDateTime,
    timezone: EfiTimezone,
    daylight: EfiDaylight,
}

impl TryFrom<EFI_TIME> for EfiOffsetDateTime {
    type Error = time::Error;

    fn try_from(v: EFI_TIME) -> Result<Self, Self::Error> {
        Ok(Self {
            datetime: OffsetDateTime::from_unix_timestamp(0)?
                .replace_year(v.year as i32)?
                .replace_month(v.month.try_into()?)?
                .replace_day(v.day)?
                .replace_hour(v.hour)?
                .replace_minute(v.minute)?
                .replace_second(v.second)?
                .replace_nanosecond(v.nanosecond)?,
            timezone: v.timezone,
            daylight: v.daylight,
        })
    }
}

impl From<EfiOffsetDateTime> for EFI_TIME {
    fn from(v: EfiOffsetDateTime) -> Self {
        Self {
            year: v.datetime.year() as u16,
            month: v.datetime.month().into(),
            day: v.datetime.day(),
            hour: v.datetime.hour(),
            minute: v.datetime.minute(),
            second: v.datetime.second(),
            pad1: 0,
            nanosecond: v.datetime.nanosecond(),
            timezone: v.timezone,
            daylight: v.daylight,
            pad2: 0,
        }
    }
}

#[derive(InspectMut)]
pub struct TimeServices {
    clock: Box<dyn InspectableLocalClock>,
    timezone: EfiTimezone,
    daylight: EfiDaylight,
}

impl TimeServices {
    /// Create a new time service using the provided clock source.
    /// SaveRestore for the clock should be handled externally.
    pub fn new(clock: Box<dyn InspectableLocalClock>) -> Self {
        Self {
            clock,
            timezone: EfiTimezone(0),
            daylight: EfiDaylight::new(),
        }
    }

    /// Get the [`LocalClock`](local_clock::LocalClock) time as [`EFI_TIME`].
    ///
    /// The clock implementation should handle any time delta between the host
    /// and guest, including timezone and daylight.
    pub fn get_time(&mut self) -> Result<EFI_TIME, TimeServiceError> {
        if !self.daylight.valid() || !self.timezone.valid() {
            return Err(TimeServiceError::InvalidArg);
        }

        let datetime: OffsetDateTime = self
            .clock
            .get_time()
            .try_into()
            .map_err(|_| TimeServiceError::Overflow)?;

        Ok(EfiOffsetDateTime {
            datetime,
            timezone: self.timezone,
            daylight: self.daylight,
        }
        .into())
    }

    /// Set the [`LocalClock`](local_clock::LocalClock) time from [`EFI_TIME`].
    ///
    /// The timezone and daylight information are saved so they can be retrieved
    /// by the guest, but not processed.
    pub fn set_time(&mut self, new_time: EFI_TIME) -> Result<(), TimeServiceError> {
        let EfiOffsetDateTime {
            datetime,
            timezone,
            daylight,
        } = new_time.try_into()?;

        if !daylight.valid() || !timezone.valid() {
            return Err(TimeServiceError::InvalidArg);
        }

        self.timezone = timezone;
        self.daylight = daylight;
        self.clock.set_time(datetime.into());

        Ok(())
    }
}

impl UefiDevice {
    /// Writes the time and status to the address specified.
    pub(crate) fn get_time(&mut self, gpa: u64) -> Result<(), GuestMemoryError> {
        let vm_time = match self.service.time.get_time() {
            Ok(time) => VmEfiTime {
                status: EfiStatus::SUCCESS.into(),
                time,
            },
            Err(e) => {
                tracing::error!("get_time: {}", e);
                VmEfiTime {
                    status: EfiStatus::DEVICE_ERROR.into(),
                    time: Default::default(),
                }
            }
        };

        tracing::debug!("get_time: {:?}", vm_time);
        self.gm.write_plain(gpa, &vm_time)
    }

    /// Reads the time from address specified, updates internal state,
    /// and writes back the status.
    pub(crate) fn set_time(&mut self, gpa: u64) -> Result<(), GuestMemoryError> {
        let vm_time = self.gm.read_plain::<VmEfiTime>(gpa)?;
        let status = match self.service.time.set_time(vm_time.time) {
            Ok(_) => EfiStatus::SUCCESS,
            Err(e) => {
                tracing::error!("set_time: {}", e);
                match e {
                    TimeServiceError::InvalidArg => EfiStatus::INVALID_PARAMETER,
                    _ => EfiStatus::DEVICE_ERROR,
                }
            }
        };

        let vm_time = VmEfiTime {
            time: vm_time.time,
            status: status.into(),
        };
        tracing::debug!("set_time: {:?}", vm_time);
        self.gm.write_plain(gpa, &vm_time)
    }
}

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::SavedStateRoot;

        #[derive(Protobuf, SavedStateRoot)]
        #[mesh(package = "firmware.uefi.time")]
        pub struct SavedState {
            #[mesh(1)]
            pub timezone: i16,
            #[mesh(2)]
            pub daylight: u8,
        }
    }

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

        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
            Ok(state::SavedState {
                timezone: self.timezone.0,
                daylight: self.daylight.into(),
            })
        }

        fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
            let state::SavedState { timezone, daylight } = state;
            self.timezone = EfiTimezone(timezone);
            self.daylight = EfiDaylight::from(daylight);
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use local_clock::MockLocalClock;
    use local_clock::MockLocalClockAccessor;
    use std::time::Duration;
    use test_with_tracing::test;

    fn new_test_time_service() -> (MockLocalClockAccessor, TimeServices) {
        let time = MockLocalClock::new();
        let time_access = time.accessor();
        let service = TimeServices::new(Box::new(time));
        (time_access, service)
    }

    #[test]
    fn test_basic_get_time_set_time() {
        let (time_access, mut service) = new_test_time_service();
        let mut init_time = EFI_TIME {
            year: 2023,
            month: 11,
            day: 9,
            hour: 10,
            minute: 42,
            second: 27,
            pad1: 0,
            nanosecond: 0,
            timezone: EfiTimezone(-480),
            daylight: EfiDaylight::new().with_adjust_daylight(true),
            pad2: 0,
        };
        service.set_time(init_time).unwrap();
        time_access.tick(Duration::from_secs(2));
        init_time.second += 2;
        let new_time = service.get_time().unwrap();
        assert_eq!(init_time, new_time);
    }

    #[test]
    #[should_panic]
    fn test_validate_timezone() {
        let (_, mut service) = new_test_time_service();
        let init_time = EFI_TIME {
            year: 2023,
            month: 11,
            day: 9,
            hour: 10,
            minute: 42,
            second: 27,
            pad1: 0,
            nanosecond: 0,
            timezone: EfiTimezone(1500),
            daylight: EfiDaylight::new().with_adjust_daylight(true),
            pad2: 0,
        };
        service.set_time(init_time).unwrap();
    }

    #[test]
    #[should_panic]
    fn test_validate_daylight() {
        let (_, mut service) = new_test_time_service();
        let init_time = EFI_TIME {
            year: 2023,
            month: 11,
            day: 9,
            hour: 10,
            minute: 42,
            second: 27,
            pad1: 0,
            nanosecond: 0,
            timezone: EfiTimezone(-480),
            daylight: EfiDaylight::from(4),
            pad2: 0,
        };
        service.set_time(init_time).unwrap();
    }
}