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

//! A generic, read-only PCI Capability (backed by an [`AsBytes`] type).

use super::PciCapability;
use inspect::Inspect;
use std::fmt::Debug;
use zerocopy::AsBytes;

/// Helper to define a read-only [`PciCapability`] from an [`AsBytes`] type.
#[derive(Debug)]
pub struct ReadOnlyCapability<T> {
    label: String,
    data: T,
}

impl<T: AsBytes> ReadOnlyCapability<T> {
    /// Create a new [`ReadOnlyCapability`]
    pub fn new(label: impl Into<String>, data: T) -> Self {
        Self {
            label: label.into(),
            data,
        }
    }
}

impl<T: Debug> Inspect for ReadOnlyCapability<T> {
    fn inspect(&self, req: inspect::Request<'_>) {
        req.respond()
            .field("label", &self.label)
            .display_debug("data", &self.data);
    }
}

impl<T> PciCapability for ReadOnlyCapability<T>
where
    T: AsBytes + Send + Sync + Debug,
{
    fn label(&self) -> &str {
        &self.label
    }

    fn len(&self) -> usize {
        size_of::<T>()
    }

    fn read_u32(&self, offset: u16) -> u32 {
        if offset as usize + 4 <= self.len() {
            let offset = offset.into();
            u32::from_ne_bytes(self.data.as_bytes()[offset..offset + 4].try_into().unwrap())
        } else {
            !0
        }
    }

    fn write_u32(&mut self, offset: u16, val: u32) {
        tracelimit::warn_ratelimited!(
            label = ?self.label,
            ?offset,
            ?val,
            "write to read-only capability"
        );
    }

    fn reset(&mut self) {}
}

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

    // This is a noop impl, as the capability is (by definition) read only.
    impl<T> SaveRestore for ReadOnlyCapability<T> {
        type SavedState = NoSavedState;

        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
            Ok(NoSavedState)
        }

        fn restore(&mut self, NoSavedState: Self::SavedState) -> Result<(), RestoreError> {
            Ok(())
        }
    }
}