Skip to main content

hv1_emulator/
synic.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Synthetic interrupt controller emulation.
5
6use crate::RequestInterrupt;
7use crate::VtlProtectAccess;
8use crate::pages::OverlayPage;
9use hvdef::HV_MESSAGE_SIZE;
10use hvdef::HV_PAGE_SIZE_USIZE;
11use hvdef::HvAllArchRegisterName;
12use hvdef::HvError;
13use hvdef::HvMessage;
14use hvdef::HvMessageHeader;
15use hvdef::HvMessageType;
16use hvdef::HvRegisterName;
17use hvdef::HvRegisterValue;
18use hvdef::HvRegisterVsmVina;
19use hvdef::HvResult;
20use hvdef::HvSynicSimpSiefp;
21use hvdef::HvSynicStimerConfig;
22use hvdef::NUM_SINTS;
23use hvdef::TimerMessagePayload;
24use inspect::Inspect;
25use parking_lot::RwLock;
26use safeatomic::AtomicSliceOps;
27use std::array;
28use std::sync::Arc;
29use std::sync::atomic::Ordering;
30use virt::x86::MsrError;
31use vm_topology::processor::VpIndex;
32use zerocopy::IntoBytes;
33
34/// The virtual processor synthetic interrupt controller state.
35#[derive(Inspect)]
36pub struct ProcessorSynic {
37    #[inspect(flatten)]
38    sints: SintState,
39    #[inspect(iter_by_index)]
40    timers: [Timer; hvdef::NUM_TIMERS],
41    #[inspect(skip)]
42    shared: Arc<RwLock<SharedProcessorState>>,
43    #[inspect(debug)]
44    vina: HvRegisterVsmVina,
45}
46
47#[derive(Inspect)]
48struct SintState {
49    #[inspect(hex, with = "|&x| u64::from(x)")]
50    siefp: HvSynicSimpSiefp,
51    #[inspect(hex, with = "|&x| u64::from(x)")]
52    simp: HvSynicSimpSiefp,
53    simp_page: OverlayPage,
54    #[inspect(hex, with = "|&x| u64::from(x)")]
55    scontrol: hvdef::HvSynicScontrol,
56    #[inspect(
57        hex,
58        with = "|x| inspect::iter_by_index(x).map_value(|x| u64::from(*x))"
59    )]
60    sint: [hvdef::HvSynicSint; NUM_SINTS],
61    pending_sints: u16,
62    ready_sints: u16,
63}
64
65impl Default for SintState {
66    fn default() -> Self {
67        Self {
68            siefp: HvSynicSimpSiefp::new(),
69            simp: HvSynicSimpSiefp::new(),
70            simp_page: OverlayPage::default(),
71            scontrol: hvdef::HvSynicScontrol::new().with_enabled(true),
72            sint: [hvdef::HvSynicSint::new().with_masked(true); NUM_SINTS],
73            pending_sints: 0,
74            ready_sints: 0,
75        }
76    }
77}
78
79#[derive(Default, Inspect)]
80struct Timer {
81    #[inspect(hex, with = "|&x| u64::from(x)")]
82    config: HvSynicStimerConfig,
83    count: u64,
84    reevaluate: bool,
85    due_time: Option<u64>,
86}
87
88#[derive(Inspect)]
89struct SharedProcessorState {
90    online: bool,
91    enabled: bool,
92    siefp_page: OverlayPage,
93    #[inspect(
94        hex,
95        with = "|x| inspect::iter_by_index(x).map_value(|x| u64::from(*x))"
96    )]
97    sint: [hvdef::HvSynicSint; NUM_SINTS],
98}
99
100impl SharedProcessorState {
101    fn new() -> Self {
102        Self {
103            online: false,
104            enabled: false,
105            siefp_page: OverlayPage::default(),
106            sint: [hvdef::HvSynicSint::new(); NUM_SINTS],
107        }
108    }
109
110    fn at_reset() -> Self {
111        Self {
112            online: true,
113            enabled: true,
114            siefp_page: OverlayPage::default(),
115            sint: [hvdef::HvSynicSint::new().with_masked(true); NUM_SINTS],
116        }
117    }
118
119    fn reset(&mut self, prot_access: &mut dyn VtlProtectAccess) {
120        self.siefp_page.reset(prot_access);
121        *self = Self::at_reset();
122    }
123}
124
125/// A partition-wide synthetic interrupt controller.
126#[derive(Inspect)]
127pub struct GlobalSynic {
128    #[inspect(iter_by_index)]
129    vps: Vec<Arc<RwLock<SharedProcessorState>>>,
130}
131
132fn sint_interrupt(request: &mut dyn RequestInterrupt, sint: hvdef::HvSynicSint) {
133    assert!(
134        !sint.masked() && !sint.proxy(),
135        "caller should have verified sint was ready"
136    );
137    if !sint.polling() {
138        request.request_interrupt(sint.vector().into(), sint.auto_eoi());
139    }
140}
141
142impl Timer {
143    fn set_count(&mut self, v: u64) {
144        self.count = v;
145        if self.config.auto_enable() && self.count != 0 {
146            self.config.set_enabled(true);
147        }
148        self.reevaluate = true;
149    }
150
151    fn set_count_at(&mut self, v: u64, ref_time: u64) {
152        self.count = v;
153        if self.config.auto_enable() && self.count != 0 {
154            self.config.set_enabled(true);
155        }
156        self.reevaluate = false;
157        self.due_time = if self.config.enabled() && self.count != 0 {
158            Some(if self.config.periodic() {
159                ref_time.wrapping_add(self.count)
160            } else {
161                self.count
162            })
163        } else {
164            None
165        };
166    }
167
168    fn evaluate(
169        &mut self,
170        timer_index: u32,
171        sints: &mut SintState,
172        ref_time_now: u64,
173        interrupt: &mut dyn RequestInterrupt,
174    ) -> Option<u64> {
175        if self.reevaluate {
176            self.reevaluate = false;
177            self.due_time = if self.config.enabled() && self.count != 0 {
178                Some(if self.config.periodic() {
179                    ref_time_now.wrapping_add(self.count)
180                } else {
181                    self.count
182                })
183            } else {
184                None
185            };
186        }
187
188        let due_time = self.due_time?;
189        let delta = due_time.wrapping_sub(ref_time_now);
190        if delta.cast_signed() > 0 {
191            return Some(due_time);
192        }
193
194        if self.config.direct_mode() {
195            interrupt.request_interrupt(self.config.apic_vector().into(), false);
196        } else {
197            let sint_index = self.config.sint();
198            let sint = sints.sint[sint_index as usize];
199            if sint.proxy()
200                || sint.masked()
201                || sints.pending_sints & (1 << sint_index) != 0
202                || !sints.check_sint_ready(sint_index)
203            {
204                return None;
205            }
206
207            let payload = TimerMessagePayload {
208                timer_index,
209                reserved: 0,
210                expiration_time: due_time,
211                delivery_time: ref_time_now,
212            };
213
214            let message = HvMessage::new(
215                HvMessageType::HvMessageTypeTimerExpired,
216                0,
217                payload.as_bytes(),
218            );
219
220            sints.post_message(sint_index, &message, &mut *interrupt);
221        }
222
223        // One-shot timers must be disabled upon expiration.
224        if !self.config.periodic() {
225            self.config.set_enabled(false);
226        }
227
228        self.due_time = if self.config.periodic() {
229            Some(ref_time_now.wrapping_add(self.count))
230        } else {
231            None
232        };
233
234        self.due_time
235    }
236}
237
238/// Error returned when trying to wait for readiness or signal events to a
239/// proxied SINT.
240pub struct SintProxied;
241
242impl GlobalSynic {
243    /// Returns a new instance of the synthetic interrupt controller.
244    pub fn new(max_vp_count: u32) -> Self {
245        Self {
246            vps: (0..max_vp_count)
247                .map(|_| Arc::new(RwLock::new(SharedProcessorState::new())))
248                .collect(),
249        }
250    }
251
252    /// Signals an event to the specified virtual processor.
253    ///
254    /// `interrupt` is called with the target APIC vector while holding a lock
255    /// preventing the synic state from changing.
256    ///
257    /// Returns `true` if the event flag is newly signaled.
258    pub fn signal_event(
259        &self,
260        vp: VpIndex,
261        sint_index: u8,
262        flag: u16,
263        interrupt: &mut dyn RequestInterrupt,
264    ) -> Result<bool, SintProxied> {
265        let Some(vp) = self.vps.get(vp.index() as usize) else {
266            return Ok(false);
267        };
268        let vp = vp.read();
269        let sint_index = sint_index as usize;
270        if sint_index >= NUM_SINTS {
271            return Ok(false);
272        }
273        let sint = vp.sint[sint_index];
274        let flag = flag as usize;
275        // Each SINT owns this many event flags in the SIEFP page
276        if flag >= (HV_PAGE_SIZE_USIZE / NUM_SINTS) * 8 {
277            return Ok(false);
278        }
279        if sint.proxy() {
280            return Err(SintProxied);
281        }
282        if !vp.enabled || sint.masked() {
283            return Ok(false);
284        }
285        let byte_offset = sint_index * (HV_PAGE_SIZE_USIZE / NUM_SINTS) + flag / 8;
286        let mask = 1 << (flag % 8);
287        if vp.siefp_page[byte_offset].fetch_or(mask, Ordering::SeqCst) & mask != 0 {
288            return Ok(false);
289        }
290        sint_interrupt(interrupt, sint);
291        Ok(true)
292    }
293
294    /// Adds a virtual processor to the synthetic interrupt controller state.
295    pub fn add_vp(&self, vp_index: VpIndex) -> ProcessorSynic {
296        let shared = self.vps[vp_index.index() as usize].clone();
297        let old_shared = std::mem::replace(&mut *shared.write(), SharedProcessorState::at_reset());
298        assert!(!old_shared.online);
299
300        ProcessorSynic {
301            sints: SintState::default(),
302            timers: array::from_fn(|_| Timer::default()),
303            shared,
304            vina: HvRegisterVsmVina::new(),
305        }
306    }
307}
308
309impl ProcessorSynic {
310    /// Resets the synic state back to its initial state.
311    pub fn reset(&mut self, prot_access: &mut dyn VtlProtectAccess) {
312        let Self {
313            sints,
314            timers,
315            shared,
316            vina,
317        } = self;
318
319        sints.reset(prot_access);
320        *timers = array::from_fn(|_| Timer::default());
321        shared.write().reset(prot_access);
322        *vina = HvRegisterVsmVina::new();
323    }
324
325    /// Returns the event flags page register.
326    pub fn siefp(&self) -> u64 {
327        self.sints.siefp.into()
328    }
329
330    /// Returns the message page register.
331    pub fn simp(&self) -> u64 {
332        self.sints.simp.into()
333    }
334
335    /// Returns the `SCONTROL` register.
336    pub fn scontrol(&self) -> u64 {
337        self.sints.scontrol.into()
338    }
339
340    /// Returns the `SVERSION` register.
341    pub fn sversion(&self) -> u64 {
342        1
343    }
344
345    /// Returns the end-of-message register.
346    pub fn eom(&self) -> u64 {
347        0
348    }
349
350    /// Returns the specified `SINT` register.
351    pub fn sint(&self, n: u8) -> u64 {
352        self.sints.sint[n as usize].into()
353    }
354
355    /// Returns the set of SINTs that are proxied to the host.
356    pub fn proxied_sints(&self) -> u16 {
357        self.sints
358            .sint
359            .iter()
360            .enumerate()
361            .fold(0, |v, (i, s)| v | ((s.proxy() as u16) << i))
362    }
363
364    /// Returns the specified synthetic timer configuration register.
365    pub fn stimer_config(&self, n: usize) -> u64 {
366        self.timers[n].config.into()
367    }
368
369    /// Returns the specified synthetic timer count register.
370    pub fn stimer_count(&self, n: usize) -> u64 {
371        self.timers[n].count
372    }
373
374    /// Returns the value of the VINA register.
375    pub fn vina(&self) -> HvRegisterVsmVina {
376        self.vina
377    }
378
379    /// Sets the event flags page register.
380    pub fn set_siefp(
381        &mut self,
382        v: u64,
383        prot_access: &mut dyn VtlProtectAccess,
384    ) -> Result<(), MsrError> {
385        let siefp = HvSynicSimpSiefp::from(v);
386        tracing::debug!(?siefp, "setting siefp");
387        let mut shared = self.shared.write();
388        shared
389            .siefp_page
390            .sync(siefp.enabled(), siefp.base_gpn(), prot_access)
391            .map_err(|_| MsrError::InvalidAccess)?;
392        self.sints.siefp = siefp;
393        Ok(())
394    }
395
396    /// Sets the message page register.
397    pub fn set_simp(
398        &mut self,
399        v: u64,
400        prot_access: &mut dyn VtlProtectAccess,
401    ) -> Result<(), MsrError> {
402        let simp = HvSynicSimpSiefp::from(v);
403        tracing::debug!(?simp, "setting simp");
404        self.sints
405            .simp_page
406            .sync(simp.enabled(), simp.base_gpn(), prot_access)
407            .map_err(|_| MsrError::InvalidAccess)?;
408        self.sints.simp = simp;
409        Ok(())
410    }
411
412    /// Sets the `SCONTROL` register.
413    pub fn set_scontrol(&mut self, v: u64) {
414        self.sints.scontrol = v.into();
415        self.shared.write().enabled = self.sints.scontrol.enabled();
416    }
417
418    /// Performs an end-of-message operation.
419    pub fn set_eom(&mut self, _v: u64) {
420        // FUTURE: mark that the processor should scan message queues.
421    }
422
423    /// Sets the specified `SINT` register.
424    pub fn set_sint(&mut self, n: usize, v: u64) {
425        let sint = v.into();
426        self.sints.sint[n] = sint;
427        self.shared.write().sint[n] = sint;
428    }
429
430    /// Sets the specified synthetic timer configuration register.
431    pub fn set_stimer_config(&mut self, n: usize, v: u64) {
432        let config = v.into();
433        self.timers[n].config = config;
434        self.timers[n].reevaluate = true;
435    }
436
437    /// Sets the specified synthetic timer count register.
438    pub fn set_stimer_count(&mut self, n: usize, v: u64) {
439        self.timers[n].set_count(v);
440    }
441
442    /// Sets a synthetic timer count written at the given reference time.
443    pub fn set_stimer_count_at(&mut self, n: usize, v: u64, ref_time: u64) {
444        self.timers[n].set_count_at(v, ref_time);
445    }
446
447    /// Requests a notification when any of the requested sints has a free
448    /// message slot.
449    ///
450    /// The free sints will be returned by [`Self::scan`].
451    pub fn request_sint_readiness(&mut self, sints: u16) {
452        self.sints.pending_sints = sints;
453    }
454
455    /// Writes a message to the message page.
456    ///
457    /// Returns `Err(HvError::ObjectInUse)` if the message slot is full.
458    pub fn post_message(
459        &mut self,
460        sint_index: u8,
461        message: &HvMessage,
462        interrupt: &mut dyn RequestInterrupt,
463    ) -> Result<(), HvError> {
464        if sint_index as usize >= NUM_SINTS {
465            return Err(HvError::InvalidSynicState);
466        }
467        let sint = &self.sints.sint[sint_index as usize];
468        if sint.masked() || sint.proxy() {
469            return Err(HvError::InvalidSynicState);
470        }
471        if self.sints.ready_sints & (1 << sint_index) == 0 {
472            return Err(HvError::ObjectInUse);
473        }
474
475        self.sints.post_message(sint_index, message, interrupt);
476
477        Ok(())
478    }
479
480    /// Writes an intercept message to the message page. Meant to be used on
481    /// paths where the message can be written directly without using the
482    /// message queues, as it marks the intercept sint as ready.
483    ///
484    /// Returns `Err(HvError::ObjectInUse)` if the message slot is full.
485    pub fn post_intercept_message(
486        &mut self,
487        message: &HvMessage,
488        interrupt: &mut dyn RequestInterrupt,
489    ) -> Result<(), HvError> {
490        if self
491            .sints
492            .check_sint_ready(hvdef::HV_SYNIC_INTERCEPTION_SINT_INDEX)
493        {
494            self.post_message(hvdef::HV_SYNIC_INTERCEPTION_SINT_INDEX, message, interrupt)
495        } else {
496            Err(HvError::ObjectInUse)
497        }
498    }
499
500    fn reg_to_msr(reg: HvRegisterName) -> HvResult<u32> {
501        Ok(match HvAllArchRegisterName(reg.0) {
502            HvAllArchRegisterName::Sint0
503            | HvAllArchRegisterName::Sint1
504            | HvAllArchRegisterName::Sint2
505            | HvAllArchRegisterName::Sint3
506            | HvAllArchRegisterName::Sint4
507            | HvAllArchRegisterName::Sint5
508            | HvAllArchRegisterName::Sint6
509            | HvAllArchRegisterName::Sint7
510            | HvAllArchRegisterName::Sint8
511            | HvAllArchRegisterName::Sint9
512            | HvAllArchRegisterName::Sint10
513            | HvAllArchRegisterName::Sint11
514            | HvAllArchRegisterName::Sint12
515            | HvAllArchRegisterName::Sint13
516            | HvAllArchRegisterName::Sint14
517            | HvAllArchRegisterName::Sint15 => {
518                hvdef::HV_X64_MSR_SINT0 + (reg.0 - HvAllArchRegisterName::Sint0.0)
519            }
520            HvAllArchRegisterName::Scontrol => hvdef::HV_X64_MSR_SCONTROL,
521            HvAllArchRegisterName::Sversion => hvdef::HV_X64_MSR_SVERSION,
522            HvAllArchRegisterName::Sifp => hvdef::HV_X64_MSR_SIEFP,
523            HvAllArchRegisterName::Sipp => hvdef::HV_X64_MSR_SIMP,
524            HvAllArchRegisterName::Eom => hvdef::HV_X64_MSR_EOM,
525            HvAllArchRegisterName::Stimer0Config
526            | HvAllArchRegisterName::Stimer0Count
527            | HvAllArchRegisterName::Stimer1Config
528            | HvAllArchRegisterName::Stimer1Count
529            | HvAllArchRegisterName::Stimer2Config
530            | HvAllArchRegisterName::Stimer2Count
531            | HvAllArchRegisterName::Stimer3Config
532            | HvAllArchRegisterName::Stimer3Count => {
533                hvdef::HV_X64_MSR_STIMER0_CONFIG + (reg.0 - HvAllArchRegisterName::Stimer0Config.0)
534            }
535            _ => {
536                tracelimit::error_ratelimited!(?reg, "unknown synic register");
537                return Err(HvError::UnknownRegisterName);
538            }
539        })
540    }
541
542    fn msrerr_to_hverr(err: MsrError) -> HvError {
543        match err {
544            MsrError::Unknown => HvError::UnknownRegisterName,
545            MsrError::InvalidAccess => HvError::InvalidParameter,
546        }
547    }
548
549    /// Writes a synthetic interrupt controller register.
550    pub fn write_reg(
551        &mut self,
552        reg: HvRegisterName,
553        v: HvRegisterValue,
554        prot_access: &mut dyn VtlProtectAccess,
555    ) -> HvResult<()> {
556        match HvAllArchRegisterName(reg.0) {
557            HvAllArchRegisterName::VsmVina => {
558                let v = HvRegisterVsmVina::from(v.as_u64());
559                if v.reserved() != 0 {
560                    return Err(HvError::InvalidParameter);
561                }
562                self.vina = v;
563            }
564            _ => self
565                .write_msr(Self::reg_to_msr(reg)?, v.as_u64(), prot_access)
566                .map_err(Self::msrerr_to_hverr)?,
567        }
568        Ok(())
569    }
570
571    /// Writes an x64 MSR.
572    pub fn write_msr(
573        &mut self,
574        msr: u32,
575        v: u64,
576        prot_access: &mut dyn VtlProtectAccess,
577    ) -> Result<(), MsrError> {
578        match msr {
579            msr @ hvdef::HV_X64_MSR_STIMER0_CONFIG..=hvdef::HV_X64_MSR_STIMER3_COUNT => {
580                let offset = msr - hvdef::HV_X64_MSR_STIMER0_CONFIG;
581                let timer = (offset >> 1) as _;
582                let is_count = offset & 1 != 0;
583                if is_count {
584                    self.set_stimer_count(timer, v);
585                } else {
586                    self.set_stimer_config(timer, v);
587                }
588            }
589            _ => self.write_nontimer_msr(msr, v, prot_access)?,
590        }
591        Ok(())
592    }
593
594    /// Writes a non-synthetic-timer x64 MSR.
595    pub fn write_nontimer_msr(
596        &mut self,
597        msr: u32,
598        v: u64,
599        prot_access: &mut dyn VtlProtectAccess,
600    ) -> Result<(), MsrError> {
601        match msr {
602            hvdef::HV_X64_MSR_SCONTROL => self.set_scontrol(v),
603            hvdef::HV_X64_MSR_SVERSION => return Err(MsrError::InvalidAccess),
604            hvdef::HV_X64_MSR_SIEFP => self
605                .set_siefp(v, prot_access)
606                .map_err(|_| MsrError::InvalidAccess)?,
607            hvdef::HV_X64_MSR_SIMP => self
608                .set_simp(v, prot_access)
609                .map_err(|_| MsrError::InvalidAccess)?,
610            hvdef::HV_X64_MSR_EOM => self.set_eom(v),
611            msr @ hvdef::HV_X64_MSR_SINT0..=hvdef::HV_X64_MSR_SINT15 => {
612                self.set_sint((msr - hvdef::HV_X64_MSR_SINT0) as usize, v)
613            }
614            _ => return Err(MsrError::Unknown),
615        }
616        Ok(())
617    }
618
619    /// Reads a synthetic interrupt controller register.
620    pub fn read_reg(&self, reg: HvRegisterName) -> HvResult<HvRegisterValue> {
621        let v = match HvAllArchRegisterName(reg.0) {
622            HvAllArchRegisterName::VsmVina => self.vina.into_bits(),
623            _ => self
624                .read_msr(Self::reg_to_msr(reg)?)
625                .map_err(Self::msrerr_to_hverr)?,
626        };
627        Ok(v.into())
628    }
629
630    /// Reads an x64 MSR.
631    pub fn read_msr(&self, msr: u32) -> Result<u64, MsrError> {
632        let value = match msr {
633            msr @ hvdef::HV_X64_MSR_STIMER0_CONFIG..=hvdef::HV_X64_MSR_STIMER3_COUNT => {
634                let offset = msr - hvdef::HV_X64_MSR_STIMER0_CONFIG;
635                let timer = (offset >> 1) as _;
636                let is_count = offset & 1 != 0;
637                if is_count {
638                    self.stimer_count(timer)
639                } else {
640                    self.stimer_config(timer)
641                }
642            }
643            _ => self.read_nontimer_msr(msr)?,
644        };
645        Ok(value)
646    }
647
648    /// Reads a non-synthetic-timer x64 MSR.
649    pub fn read_nontimer_msr(&self, msr: u32) -> Result<u64, MsrError> {
650        let value = match msr {
651            hvdef::HV_X64_MSR_SCONTROL => self.scontrol(),
652            hvdef::HV_X64_MSR_SVERSION => self.sversion(),
653            hvdef::HV_X64_MSR_SIEFP => self.siefp(),
654            hvdef::HV_X64_MSR_SIMP => self.simp(),
655            hvdef::HV_X64_MSR_EOM => self.eom(),
656            msr @ hvdef::HV_X64_MSR_SINT0..=hvdef::HV_X64_MSR_SINT15 => {
657                self.sint((msr - hvdef::HV_X64_MSR_SINT0) as u8)
658            }
659            _ => return Err(MsrError::Unknown),
660        };
661        Ok(value)
662    }
663
664    /// Scans for pending messages and timers.
665    ///
666    /// Calls `interrupt` with the APIC vector to signal, possibly multiple
667    /// times for different SINTs.
668    ///
669    /// Returns SINTs that are now deliverable after calls to
670    /// [`Self::request_sint_readiness`].
671    #[must_use]
672    pub fn scan(
673        &mut self,
674        ref_time_now: u64,
675        interrupt: &mut dyn RequestInterrupt,
676    ) -> (u16, Option<u64>) {
677        // Evaluate `ready_sints` for each pending SINT.
678        if self.sints.pending_sints != 0 {
679            for sint in 0..NUM_SINTS as u8 {
680                if self.sints.pending_sints & (1 << sint) != 0 {
681                    self.sints.check_sint_ready(sint);
682                }
683            }
684        }
685
686        // Scan for due timers.
687        let mut next_ref_time: Option<u64> = None;
688        if self
689            .timers
690            .iter()
691            .any(|t| t.reevaluate || t.due_time.is_some())
692        {
693            for (timer_index, timer) in self.timers.iter_mut().enumerate() {
694                if let Some(next) =
695                    timer.evaluate(timer_index as u32, &mut self.sints, ref_time_now, interrupt)
696                {
697                    match next_ref_time.as_mut() {
698                        Some(v) => *v = (*v).min(next),
699                        None => next_ref_time = Some(next),
700                    }
701                }
702            }
703        }
704
705        let ready_pending_sints = self.sints.ready_sints & self.sints.pending_sints;
706        self.sints.pending_sints &= !ready_pending_sints;
707        (ready_pending_sints, next_ref_time)
708    }
709}
710
711impl SintState {
712    fn post_message(
713        &mut self,
714        sint_index: u8,
715        message: &HvMessage,
716        interrupt: &mut dyn RequestInterrupt,
717    ) {
718        let sint = self.sint[sint_index as usize];
719
720        assert!(
721            !sint.masked() && !sint.proxy() && self.ready_sints & (1 << sint_index) != 0,
722            "caller should have verified sint was ready"
723        );
724
725        let offset = sint_index as usize * HV_MESSAGE_SIZE;
726        let data = message.as_bytes();
727        self.simp_page[offset..offset + data.len()].atomic_write(data);
728        self.ready_sints &= !(1 << sint_index);
729        sint_interrupt(interrupt, sint);
730    }
731
732    fn check_sint_ready(&mut self, sint: u8) -> bool {
733        if self.ready_sints & (1 << sint) != 0 {
734            return true;
735        }
736        let offset = sint as usize * HV_MESSAGE_SIZE;
737        let mut header: HvMessageHeader =
738            self.simp_page[offset..offset + size_of::<HvMessageHeader>()].atomic_read_obj();
739
740        if header.typ != HvMessageType::HvMessageTypeNone {
741            // The slot is full. Mark the message pending so that the guest forces an EOM.
742            if !header.flags.message_pending() {
743                header.flags.set_message_pending(true);
744                let data = header.as_bytes();
745                self.simp_page[offset..offset + data.len()].atomic_write(data);
746            }
747            return false;
748        }
749        self.ready_sints |= 1 << sint;
750        true
751    }
752
753    fn reset(&mut self, prot_access: &mut dyn VtlProtectAccess) {
754        self.simp_page.reset(prot_access);
755        *self = Self::default();
756    }
757}
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762
763    #[test]
764    fn restored_periodic_timer_preserves_program_time() {
765        let mut timer = Timer {
766            config: HvSynicStimerConfig::new()
767                .with_periodic(true)
768                .with_auto_enable(true),
769            ..Default::default()
770        };
771
772        timer.set_count_at(100, 1000);
773
774        assert!(timer.config.enabled());
775        assert_eq!(timer.due_time, Some(1100));
776        assert!(!timer.reevaluate);
777    }
778
779    #[test]
780    fn restored_oneshot_timer_preserves_absolute_deadline() {
781        let mut timer = Timer {
782            config: HvSynicStimerConfig::new().with_auto_enable(true),
783            ..Default::default()
784        };
785
786        timer.set_count_at(2000, 1000);
787
788        assert!(timer.config.enabled());
789        assert_eq!(timer.due_time, Some(2000));
790        assert!(!timer.reevaluate);
791    }
792
793    #[test]
794    fn restored_expired_timer_is_evaluated() {
795        let mut timer = Timer {
796            config: HvSynicStimerConfig::new()
797                .with_auto_enable(true)
798                .with_direct_mode(true)
799                .with_apic_vector(0x40),
800            ..Default::default()
801        };
802        let mut sints = SintState::default();
803        let mut requested = None;
804        let mut interrupt = |vector, auto_eoi| requested = Some((vector, auto_eoi));
805
806        timer.set_count_at(1000, 900);
807        timer.evaluate(0, &mut sints, 1001, &mut interrupt);
808
809        assert_eq!(requested, Some((0x40, false)));
810        assert!(!timer.config.enabled());
811        assert_eq!(timer.due_time, None);
812    }
813}