Skip to main content

vmbus_core/
protocol.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use crate::VersionInfo;
5use bitfield_struct::bitfield;
6use hvdef::Vtl;
7use inspect::Inspect;
8use mesh::payload::Protobuf;
9use open_enum::open_enum;
10use std::mem::size_of;
11use std::ops::BitAnd;
12use std::ops::BitAndAssign;
13use std::ops::BitOr;
14use std::ops::Deref;
15use std::ops::DerefMut;
16use thiserror::Error;
17use zerocopy::FromBytes;
18use zerocopy::FromZeros;
19use zerocopy::Immutable;
20use zerocopy::IntoBytes;
21use zerocopy::KnownLayout;
22use zerocopy::Unalign;
23
24#[macro_use]
25mod macros;
26
27type Guid = guid::Guid;
28
29pub const VMBUS_MESSAGE_REDIRECT_CONNECTION_ID: u32 = 0x800074;
30
31pub const STATUS_SUCCESS: i32 = 0;
32pub const STATUS_UNSUCCESSFUL: i32 = 0x8000ffff_u32 as i32;
33pub const STATUS_CONNECTION_REFUSED: i32 = 0xc0000236_u32 as i32;
34
35pub const HEADER_SIZE: usize = size_of::<MessageHeader>();
36pub const MAX_MESSAGE_SIZE: usize = hvdef::HV_MESSAGE_PAYLOAD_SIZE;
37
38// This macro is used to define a MessageType open enum, a Message enum, a parse method for the
39// Message enum, and VmbusMessage trait implementations for each protocol message struct.
40//
41// The syntax here is as follows:
42// number name { struct min_version [options],* },*
43//
44// If a message has different variants depending on the version or feature flags, you can express
45// this by having multiple comma-separated items inside the curly braces for that message. List the
46// variants in the order you want them to be matched (so, newer first).
47//
48// A message that can be received when disconnected should have the min_version set to 0.
49//
50// The following additional options can be set:
51// - features: specifies one or more feature flags, at least one of which must be supported for the
52//             message to be allowed.
53// - check_size: set to true to only match the message if its size is at least the size of the
54//               struct; if it's not, allow another message to match. Without this option, the size
55//               is still checked but a message that is too small is considered a parsing failure,
56//               and won't allow another match. Use this for a message whose variants can only be
57//               distinguished by size.
58vmbus_messages! {
59    pub enum Message, MessageType {
60        1 OFFER_CHANNEL { OfferChannel V1 },
61        2 RESCIND_CHANNEL_OFFER { RescindChannelOffer V1 },
62        3 REQUEST_OFFERS { RequestOffers V1 },
63        4 ALL_OFFERS_DELIVERED { AllOffersDelivered V1 },
64        5 OPEN_CHANNEL {
65            OpenChannel2 Copper features:(guest_specified_signal_parameters | channel_interrupt_redirection),
66            OpenChannel V1
67        },
68        6 OPEN_CHANNEL_RESULT { OpenResult V1 },
69        7 CLOSE_CHANNEL { CloseChannel V1 },
70        8 GPADL_HEADER { GpadlHeader V1 },
71        9 GPADL_BODY { GpadlBody V1 },
72        10 GPADL_CREATED { GpadlCreated V1 },
73        11 GPADL_TEARDOWN { GpadlTeardown V1 },
74        12 GPADL_TORNDOWN { GpadlTorndown V1 },
75        13 REL_ID_RELEASED { RelIdReleased V1 },
76        14 INITIATE_CONTACT {
77            // Although the InitiateContact2 message is only used in Copper and above, it
78            // must be set as minimum version 0 because the version is not known when the message
79            // is received. For this same reason, we can't check the feature flags here.
80            InitiateContact2 0 check_size:true,
81            InitiateContact 0
82        },
83        15 VERSION_RESPONSE {
84            VersionResponse3 0 check_size:true,
85            VersionResponse2 0 check_size:true,
86            VersionResponse 0
87        },
88        16 UNLOAD { Unload V1 },
89        17 UNLOAD_COMPLETE { UnloadComplete Win7 },
90        18 OPEN_RESERVED_CHANNEL { OpenReservedChannel Win10 },
91        19 CLOSE_RESERVED_CHANNEL { CloseReservedChannel 0 },
92        20 CLOSE_RESERVED_RESPONSE { CloseReservedChannelResponse Win10 },
93        21 TL_CONNECT_REQUEST {
94            // Some clients send the old message even for newer protocols, so check the size to allow
95            // the old version to match if it's smaller.
96            TlConnectRequest2 Win10Rs5 check_size:true,
97            TlConnectRequest Win10
98        },
99        22 MODIFY_CHANNEL { ModifyChannel Win10Rs3_0 },
100        23 TL_CONNECT_REQUEST_RESULT { TlConnectResult Win10Rs3_0 },
101        24 MODIFY_CHANNEL_RESPONSE { ModifyChannelResponse Iron },
102        25 MODIFY_CONNECTION { ModifyConnection Copper features:modify_connection },
103        26 MODIFY_CONNECTION_RESPONSE { ModifyConnectionResponse Copper features:modify_connection },
104        27 PAUSE { Pause Copper features:pause_resume },
105        28 PAUSE_RESPONSE { PauseResponse Copper features:pause_resume },
106        29 RESUME { Resume Copper features:pause_resume },
107    }
108}
109
110/// An error that occurred while parsing a vmbus protocol message.
111#[derive(Debug, Error)]
112pub enum ParseError {
113    /// The message was smaller than required for the message type.
114    #[error("message too small: {0:?}")]
115    MessageTooSmall(Option<MessageType>),
116    /// The message type is not a valid vmbus protocol message, or a message that is not supported
117    /// with the current protocol version.
118    #[error("unexpected or unsupported message type: {0:?}")]
119    InvalidMessageType(MessageType),
120}
121
122/// Trait implemented on all protocol message structs by the vmbus_message! macro.
123pub trait VmbusMessage: Sized {
124    /// The corresponding message type for the struct.
125    const MESSAGE_TYPE: MessageType;
126
127    /// The size of the message, including the vmbus message header.
128    const MESSAGE_SIZE: usize = HEADER_SIZE + size_of::<Self>();
129}
130
131/// The header of a vmbus message.
132#[repr(C)]
133#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
134pub struct MessageHeader {
135    message_type: MessageType,
136    padding: u32,
137}
138
139impl MessageHeader {
140    /// Creates a new `MessageHeader` for the specified message type.
141    pub fn new(message_type: MessageType) -> Self {
142        Self {
143            message_type,
144            padding: 0,
145        }
146    }
147
148    pub fn message_type(&self) -> MessageType {
149        self.message_type
150    }
151}
152
153#[derive(Inspect)]
154#[bitfield(u32)]
155#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)]
156pub struct FeatureFlags {
157    /// Feature which allows the guest to specify an event flag and connection ID when opening
158    /// a channel. If not used, the event flag defaults to the channel ID and the connection ID
159    /// is specified by the host in the offer channel message.
160    pub guest_specified_signal_parameters: bool, // 0x1
161
162    /// Indicates the `REDIRECT_INTERRUPT` flag is supported in the OpenChannel flags.
163    pub channel_interrupt_redirection: bool, // 0x2
164
165    /// Indicates the `MODIFY_CONNECTION` and `MODIFY_CONNECTION_RESPONSE` messages are supported.
166    pub modify_connection: bool, // 0x4
167
168    /// Feature which allows a client (Windows, Linux, MiniVMBus, etc)
169    /// to specify a well-known GUID to identify itself when initiating contact.
170    /// If not used, the client ID is zero.
171    pub client_id: bool, // 0x8
172
173    /// Indicates the `confidential_ring_buffer` and `confidential_external_memory` offer flags are
174    /// supported.
175    pub confidential_channels: bool, // 0x10
176
177    /// The server supports messages to pause and resume additional control messages.
178    pub pause_resume: bool, // 0x20
179
180    /// The guest supports having the server (host or paravisor) provide monitor page GPAs.
181    ///
182    /// If this flag is present in the `InitiateContact` message, the guest may still provide its
183    /// own monitor pages, which the server may ignore if it supports the flag. The server will
184    /// only set this flag in the `VersionResponse` message if it is actually providing monitor
185    /// pages, which the guest must then use instead of its own.
186    ///
187    /// If the server sets the flag in the `VersionResponse` message, it must provide a non-zero
188    /// value for the [`VersionResponse3::child_to_parent_monitor_page_gpa`]; the
189    /// [`VersionResponse3::parent_to_child_monitor_page_gpa`] is optional and may be zero, in which
190    /// case the guest cannot cancel MNF interrupts from the host.
191    pub server_specified_monitor_pages: bool, // 0x40
192
193    /// The guest supports channels that require the use of pinned memory. This indicates that the
194    /// `require_pinned_external_memory` flag in the channel offer message is supported.
195    pub gpa_pinning: bool, // 0x80
196
197    #[bits(24)]
198    _reserved: u32,
199}
200
201impl FeatureFlags {
202    /// Returns true if `other` contains only flags that are also set in `self`.
203    pub fn contains(&self, other: FeatureFlags) -> bool {
204        self.into_bits() & other.into_bits() == other.into_bits()
205    }
206}
207
208impl BitAnd for FeatureFlags {
209    type Output = Self;
210
211    fn bitand(self, rhs: Self) -> Self::Output {
212        (self.into_bits() & rhs.into_bits()).into()
213    }
214}
215
216impl BitAndAssign for FeatureFlags {
217    fn bitand_assign(&mut self, rhs: Self) {
218        *self = (self.into_bits() & rhs.into_bits()).into()
219    }
220}
221
222impl BitOr for FeatureFlags {
223    type Output = Self;
224
225    fn bitor(self, rhs: Self) -> Self::Output {
226        (self.into_bits() | rhs.into_bits()).into()
227    }
228}
229
230#[repr(transparent)]
231#[derive(
232    Copy,
233    Clone,
234    Debug,
235    Eq,
236    PartialEq,
237    Ord,
238    PartialOrd,
239    Hash,
240    IntoBytes,
241    FromBytes,
242    Immutable,
243    KnownLayout,
244    Protobuf,
245)]
246#[mesh(package = "vmbus")]
247pub struct GpadlId(pub u32);
248
249#[repr(transparent)]
250#[derive(
251    Copy,
252    Clone,
253    Debug,
254    Eq,
255    Inspect,
256    PartialEq,
257    Ord,
258    PartialOrd,
259    Hash,
260    IntoBytes,
261    FromBytes,
262    Immutable,
263    KnownLayout,
264    Protobuf,
265)]
266#[inspect(transparent)]
267pub struct ChannelId(pub u32);
268
269pub struct ConnectionId(pub u32);
270
271impl ConnectionId {
272    /// Format a connection ID for a given channel.
273    pub fn new(channel_id: u32, vtl: Vtl, sint: u8) -> Self {
274        Self(channel_id | (sint as u32) << 12 | (vtl as u32) << 16)
275    }
276}
277
278#[repr(C)]
279#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
280pub struct InitiateContact {
281    pub version_requested: u32,
282    pub target_message_vp: u32,
283    pub interrupt_page_or_target_info: u64, // sint, vtl, _
284    pub parent_to_child_monitor_page_gpa: u64,
285    pub child_to_parent_monitor_page_gpa: u64,
286}
287
288/// Initiate contact message used with `FeatureFlags::CLIENT_ID` when the feature is supported
289/// (Copper and above).
290#[repr(C)]
291#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
292pub struct InitiateContact2 {
293    pub initiate_contact: InitiateContact,
294    pub client_id: Guid,
295}
296
297impl From<InitiateContact> for InitiateContact2 {
298    fn from(value: InitiateContact) -> Self {
299        Self {
300            initiate_contact: value,
301            ..FromZeros::new_zeroed()
302        }
303    }
304}
305
306/// Helper struct to interpret the `InitiateContact::interrupt_page_or_target_info` field.
307#[bitfield(u64)]
308pub struct TargetInfo {
309    pub sint: u8,
310    pub vtl: u8,
311    pub _padding: u16,
312    pub feature_flags: u32,
313}
314
315pub const fn make_version(major: u16, minor: u16) -> u32 {
316    ((major as u32) << 16) | (minor as u32)
317}
318
319#[repr(u32)]
320#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Inspect)]
321pub enum Version {
322    V1 = make_version(0, 13),
323    Win7 = make_version(1, 1),
324    Win8 = make_version(2, 4),
325    Win8_1 = make_version(3, 0),
326    Win10 = make_version(4, 0),
327    Win10Rs3_0 = make_version(4, 1),
328    Win10Rs3_1 = make_version(5, 0),
329    Win10Rs4 = make_version(5, 1),
330    Win10Rs5 = make_version(5, 2),
331    Iron = make_version(5, 3),
332    Copper = make_version(6, 0),
333}
334
335open_enum! {
336    /// Possible values for the `VersionResponse::connection_state` field.
337    #[derive(IntoBytes, FromBytes, Immutable, KnownLayout)]
338    pub enum ConnectionState: u8 {
339        SUCCESSFUL = 0,
340        FAILED_LOW_RESOURCES = 1,
341        FAILED_UNKNOWN_FAILURE = 2,
342    }
343}
344
345#[repr(C)]
346#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
347pub struct VersionResponse {
348    pub version_supported: u8,
349    pub connection_state: ConnectionState,
350    pub padding: u16,
351    pub selected_version_or_connection_id: u32,
352}
353
354/// Version response message used by `Version::Copper` and above.
355/// N.B. The server will only send this version if the requested version is `Version::Copper` or
356///      above and the version is supported. For unsupported versions, the original `VersionResponse`
357///      is always sent.
358#[repr(C)]
359#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
360pub struct VersionResponse2 {
361    pub version_response: VersionResponse,
362    pub supported_features: u32,
363}
364
365/// Version response message used by [`Version::Copper`] and above if
366/// [`FeatureFlags::server_specified_monitor_pages`] is set.
367#[repr(C)]
368#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
369pub struct VersionResponse3 {
370    pub version_response2: VersionResponse2,
371    pub _padding: u32,
372    // Only valid with `FeatureFlags::server_specified_monitor_pages`.
373    pub parent_to_child_monitor_page_gpa: u64,
374    pub child_to_parent_monitor_page_gpa: u64,
375}
376
377impl From<VersionResponse> for VersionResponse2 {
378    fn from(value: VersionResponse) -> Self {
379        Self {
380            version_response: value,
381            ..FromZeros::new_zeroed()
382        }
383    }
384}
385
386impl From<VersionResponse2> for VersionResponse3 {
387    fn from(value: VersionResponse2) -> Self {
388        Self {
389            version_response2: value,
390            ..FromZeros::new_zeroed()
391        }
392    }
393}
394
395impl From<VersionResponse> for VersionResponse3 {
396    fn from(value: VersionResponse) -> Self {
397        let version_response: VersionResponse2 = value.into();
398        version_response.into()
399    }
400}
401
402/// User-defined data provided by a device as part of an offer or open request.
403#[derive(
404    Copy, Clone, PartialEq, Eq, IntoBytes, FromBytes, Immutable, KnownLayout, Protobuf, Inspect,
405)]
406#[repr(C, align(4))]
407#[mesh(transparent)]
408#[inspect(transparent)]
409pub struct UserDefinedData([u8; 120]);
410
411impl UserDefinedData {
412    pub fn as_pipe_params(&self) -> &PipeUserDefinedParameters {
413        PipeUserDefinedParameters::ref_from_bytes(
414            &self.0[0..size_of::<PipeUserDefinedParameters>()],
415        )
416        .expect("from bytes should not fail")
417    }
418
419    pub fn as_pipe_params_mut(&mut self) -> &mut PipeUserDefinedParameters {
420        PipeUserDefinedParameters::mut_from_bytes(
421            &mut self.0[0..size_of::<PipeUserDefinedParameters>()],
422        )
423        .expect("from bytes should not fail")
424    }
425
426    pub fn as_hvsock_params(&self) -> &HvsockUserDefinedParameters {
427        HvsockUserDefinedParameters::ref_from_bytes(
428            &self.0[0..size_of::<HvsockUserDefinedParameters>()],
429        )
430        .expect("from bytes should not fail")
431    }
432
433    pub fn as_hvsock_params_mut(&mut self) -> &mut HvsockUserDefinedParameters {
434        HvsockUserDefinedParameters::mut_from_bytes(
435            &mut self.0[0..size_of::<HvsockUserDefinedParameters>()],
436        )
437        .expect("from bytes should not fail")
438    }
439}
440
441impl Deref for UserDefinedData {
442    type Target = [u8; 120];
443
444    fn deref(&self) -> &Self::Target {
445        &self.0
446    }
447}
448
449impl DerefMut for UserDefinedData {
450    fn deref_mut(&mut self) -> &mut Self::Target {
451        &mut self.0
452    }
453}
454
455impl From<[u8; 120]> for UserDefinedData {
456    fn from(value: [u8; 120]) -> Self {
457        Self(value)
458    }
459}
460
461impl From<UserDefinedData> for [u8; 120] {
462    fn from(value: UserDefinedData) -> Self {
463        value.0
464    }
465}
466
467impl Default for UserDefinedData {
468    fn default() -> Self {
469        Self::new_zeroed()
470    }
471}
472
473impl std::fmt::Debug for UserDefinedData {
474    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
475        if self.0.iter().all(|&b| b == 0) {
476            // Compact output for all-zeroes
477            write!(f, "UserDefinedData([<all-zeroes>])")
478        } else {
479            // Compact output as uppercase hex
480            write!(f, "UserDefinedData([")?;
481            for byte in &self.0 {
482                write!(f, "{:02X}", byte)?;
483            }
484            write!(f, "])")
485        }
486    }
487}
488
489#[repr(C)]
490#[derive(
491    Copy, Clone, Debug, Inspect, PartialEq, Eq, IntoBytes, FromBytes, Immutable, KnownLayout,
492)]
493#[inspect(extra = "Self::inspect_extra")]
494pub struct OfferChannel {
495    pub interface_id: Guid,
496    pub instance_id: Guid,
497    #[inspect(skip)]
498    pub rsvd: [u32; 4],
499    pub flags: OfferFlags,
500    pub mmio_megabytes: u16,
501    pub user_defined: UserDefinedData,
502    pub subchannel_index: u16,
503    pub mmio_megabytes_optional: u16,
504    pub channel_id: ChannelId,
505    pub monitor_id: u8,
506    pub monitor_allocated: u8,
507    pub is_dedicated: u16,
508    pub connection_id: u32,
509}
510
511impl OfferChannel {
512    fn inspect_extra(&self, resp: &mut inspect::Response<'_>) {
513        // TODO: There doesn't exist a single crate that has all these interface
514        // IDs. Today they're defined in each individual crate, but we don't
515        // want to include all those crates as dependencies here.
516        //
517        // In the future, it might make sense to have a common protocol crate
518        // that has all of these defined, but for now just redefine the most
519        // common ones here. Add more as needed.
520        const SHUTDOWN_IC: Guid = guid::guid!("0e0b6031-5213-4934-818b-38d90ced39db");
521        const KVP_IC: Guid = guid::guid!("a9a0f4e7-5a45-4d96-b827-8a841e8c03e6");
522        const VSS_IC: Guid = guid::guid!("35fa2e29-ea23-4236-96ae-3a6ebacba440");
523        const TIMESYNC_IC: Guid = guid::guid!("9527e630-d0ae-497b-adce-e80ab0175caf");
524        const HEARTBEAT_IC: Guid = guid::guid!("57164f39-9115-4e78-ab55-382f3bd5422d");
525        const RDV_IC: Guid = guid::guid!("276aacf4-ac15-426c-98dd-7521ad3f01fe");
526
527        const INHERITED_ACTIVATION: Guid = guid::guid!("3375baf4-9e15-4b30-b765-67acb10d607b");
528
529        const NET: Guid = guid::guid!("f8615163-df3e-46c5-913f-f2d2f965ed0e");
530        const SCSI: Guid = guid::guid!("ba6163d9-04a1-4d29-b605-72e2ffb1dc7f");
531        const VPCI: Guid = guid::guid!("44c4f61d-4444-4400-9d52-802e27ede19f");
532
533        resp.field_with("interface_name", || match self.interface_id {
534            SHUTDOWN_IC => "shutdown_ic",
535            KVP_IC => "kvp_ic",
536            VSS_IC => "vss_ic",
537            TIMESYNC_IC => "timesync_ic",
538            HEARTBEAT_IC => "heartbeat_ic",
539            RDV_IC => "rdv_ic",
540            INHERITED_ACTIVATION => "inherited_activation",
541            NET => "net",
542            SCSI => "scsi",
543            VPCI => "vpci",
544            _ => "unknown",
545        });
546    }
547}
548
549#[derive(Inspect)]
550#[bitfield(u16)]
551#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq, Protobuf)]
552#[mesh(transparent)]
553pub struct OfferFlags {
554    pub enumerate_device_interface: bool, // 0x1
555    /// Indicates the channel must use an encrypted ring buffer on a hardware-isolated VM.
556    pub confidential_ring_buffer: bool, // 0x2
557    /// Indicates the channel must use encrypted additional GPADLs and GPA direct ranges on a
558    /// hardware-isolated VM.
559    pub confidential_external_memory: bool, // 0x4
560    /// Indicates that additional GPADLs and GPA direct packets must use pinned GPA ranges.
561    pub require_pinned_external_memory: bool, // 0x8
562    pub named_pipe_mode: bool,            // 0x10
563    #[bits(8)]
564    _reserved2: u16,
565    pub tlnpi_provider: bool, // 0x2000
566    #[bits(2)]
567    _reserved3: u16,
568}
569
570open_enum! {
571    /// Possible values for the `PipeUserDefinedParameters::pipe_type` field.
572    #[derive(IntoBytes, FromBytes, Immutable, KnownLayout)]
573    pub enum PipeType: u32 {
574        BYTE = 0,
575        MESSAGE = 4,
576    }
577}
578
579/// Provider-defined portion of the user-defined data for named pipe offers.
580#[derive(
581    Copy,
582    Clone,
583    Debug,
584    PartialEq,
585    Eq,
586    IntoBytes,
587    FromBytes,
588    Immutable,
589    KnownLayout,
590    Protobuf,
591    Inspect,
592)]
593#[repr(transparent)]
594#[mesh(transparent)]
595#[inspect(transparent)]
596pub struct PipeUserDefinedData([u8; 112]);
597
598impl From<[u8; 112]> for PipeUserDefinedData {
599    fn from(value: [u8; 112]) -> Self {
600        Self(value)
601    }
602}
603
604impl From<PipeUserDefinedData> for [u8; 112] {
605    fn from(value: PipeUserDefinedData) -> Self {
606        value.0
607    }
608}
609
610impl Default for PipeUserDefinedData {
611    fn default() -> Self {
612        Self::new_zeroed()
613    }
614}
615
616/// User-defined data layout for named pipe offers.
617#[repr(C)]
618#[derive(Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
619pub struct PipeUserDefinedParameters {
620    pub pipe_type: PipeType,
621    pub user_defined: PipeUserDefinedData,
622    pub flags: PipeFlags,
623}
624
625static_assertions::const_assert_eq!(
626    size_of::<PipeUserDefinedParameters>(),
627    size_of::<UserDefinedData>()
628);
629
630/// Flags stored in the final 4 bytes of the named pipe user-defined data.
631#[derive(Inspect)]
632#[bitfield(u32)]
633#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq, Protobuf)]
634#[mesh(transparent)]
635pub struct PipeFlags {
636    /// Indicates that the pipe supports GPA-direct transfers.
637    pub gpa_direct: bool,
638    #[bits(31)]
639    _reserved: u32,
640}
641
642#[repr(C)]
643#[derive(Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
644pub struct HvsockUserDefinedParameters {
645    pub pipe_type: PipeType,
646    pub is_for_guest_accept: u8,
647    pub is_for_guest_container: u8,
648    pub version: Unalign<HvsockParametersVersion>, // unaligned u32
649    pub silo_id: Unalign<Guid>,                    // unaligned Guid
650    pub _padding: [u8; 2],
651}
652
653impl HvsockUserDefinedParameters {
654    pub fn new(is_for_guest_accept: bool, is_for_guest_container: bool, silo_id: Guid) -> Self {
655        Self {
656            pipe_type: PipeType::BYTE,
657            is_for_guest_accept: is_for_guest_accept.into(),
658            is_for_guest_container: is_for_guest_container.into(),
659            version: Unalign::new(HvsockParametersVersion::RS5),
660            silo_id: Unalign::new(silo_id),
661            _padding: [0; 2],
662        }
663    }
664}
665
666open_enum! {
667    /// Possible values for the `PipeUserDefinedParameters::pipe_type` field.
668    #[derive(IntoBytes, FromBytes, Immutable, KnownLayout)]
669    pub enum HvsockParametersVersion: u32 {
670        PRE_RS5 = 0,
671        RS5 = 1,
672    }
673}
674
675#[repr(C)]
676#[derive(Copy, Clone, Debug, PartialEq, Eq, IntoBytes, FromBytes, Immutable, KnownLayout)]
677pub struct RescindChannelOffer {
678    pub channel_id: ChannelId,
679}
680
681#[repr(C)]
682#[derive(Copy, Clone, Debug, IntoBytes, FromBytes, Immutable, KnownLayout)]
683pub struct GpadlHeader {
684    pub channel_id: ChannelId,
685    pub gpadl_id: GpadlId,
686    pub len: u16,
687    pub count: u16,
688}
689
690impl GpadlHeader {
691    /// The maximum number of 64 bit values that fit after the message data.
692    pub const MAX_DATA_VALUES: usize = (MAX_MESSAGE_SIZE - Self::MESSAGE_SIZE) / size_of::<u64>();
693}
694
695#[repr(C)]
696#[derive(Copy, Clone, Debug, IntoBytes, FromBytes, Immutable, KnownLayout)]
697pub struct GpadlBody {
698    pub rsvd: u32,
699    pub gpadl_id: GpadlId,
700}
701
702impl GpadlBody {
703    /// The maximum number of 64 bit values that fit after the message data.
704    pub const MAX_DATA_VALUES: usize = (MAX_MESSAGE_SIZE - Self::MESSAGE_SIZE) / size_of::<u64>();
705}
706
707#[repr(C)]
708#[derive(Copy, Clone, Eq, PartialEq, Debug, IntoBytes, FromBytes, Immutable, KnownLayout)]
709pub struct GpadlCreated {
710    pub channel_id: ChannelId,
711    pub gpadl_id: GpadlId,
712    pub status: i32,
713}
714
715/// Target VP index value that indicates that interrupts should be disabled for the channel.
716pub const VP_INDEX_DISABLE_INTERRUPT: u32 = u32::MAX;
717
718/// Helper that returns `None` if the VP index indicates interrupts should be disabled.
719pub fn vp_index_if_enabled(vp_index: u32) -> Option<u32> {
720    (vp_index != VP_INDEX_DISABLE_INTERRUPT).then_some(vp_index)
721}
722
723#[repr(C)]
724#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
725pub struct OpenChannel {
726    pub channel_id: ChannelId,
727    pub open_id: u32,
728    pub ring_buffer_gpadl_id: GpadlId,
729    pub target_vp: u32,
730    pub downstream_ring_buffer_page_offset: u32,
731    pub user_data: UserDefinedData,
732}
733
734#[bitfield(u16)]
735#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)]
736pub struct OpenChannelFlags {
737    /// Indicates the host-to-guest interrupt for this channel should be sent to the redirected
738    /// VTL and SINT. This has no effect if the server is not using redirection.
739    pub redirect_interrupt: bool,
740
741    #[bits(15)]
742    pub unused: u16,
743}
744
745/// Open channel message used if `FeatureFlags::GUEST_SPECIFIED_SIGNAL_PARAMETERS` or
746/// `FeatureFlags::CHANNEL_INTERRUPT_REDIRECTION` is supported.
747#[repr(C)]
748#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
749pub struct OpenChannel2 {
750    pub open_channel: OpenChannel,
751
752    // Only valid with FeatureFlags::GUEST_SPECIFIED_SIGNAL_PARAMETERS
753    pub connection_id: u32,
754    pub event_flag: u16,
755
756    // Only valid with FeatureFlags::CHANNEL_INTERRUPT_REDIRECTION
757    pub flags: OpenChannelFlags,
758}
759
760impl From<OpenChannel> for OpenChannel2 {
761    fn from(value: OpenChannel) -> Self {
762        Self {
763            open_channel: value,
764            ..FromZeros::new_zeroed()
765        }
766    }
767}
768
769#[repr(C)]
770#[derive(PartialEq, Eq, Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
771pub struct OpenResult {
772    pub channel_id: ChannelId,
773    pub open_id: u32,
774    pub status: u32,
775}
776
777#[repr(C)]
778#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
779pub struct CloseChannel {
780    pub channel_id: ChannelId,
781}
782
783#[repr(C)]
784#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
785pub struct RelIdReleased {
786    pub channel_id: ChannelId,
787}
788
789#[repr(C)]
790#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
791pub struct GpadlTeardown {
792    pub channel_id: ChannelId,
793    pub gpadl_id: GpadlId,
794}
795
796#[repr(C)]
797#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
798pub struct GpadlTorndown {
799    pub gpadl_id: GpadlId,
800}
801
802#[repr(C)]
803#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
804pub struct OpenReservedChannel {
805    pub channel_id: ChannelId,
806    pub target_vp: u32,
807    pub target_sint: u32,
808    pub ring_buffer_gpadl: GpadlId,
809    pub downstream_page_offset: u32,
810}
811
812#[repr(C)]
813#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
814pub struct CloseReservedChannel {
815    pub channel_id: ChannelId,
816    pub target_vp: u32,
817    pub target_sint: u32,
818}
819
820#[repr(C)]
821#[derive(PartialEq, Eq, Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
822pub struct CloseReservedChannelResponse {
823    pub channel_id: ChannelId,
824}
825
826#[repr(C)]
827#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
828pub struct TlConnectRequest {
829    pub endpoint_id: Guid,
830    pub service_id: Guid,
831}
832
833#[repr(C)]
834#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
835pub struct TlConnectRequest2 {
836    pub base: TlConnectRequest,
837    pub silo_id: Guid,
838}
839
840impl From<TlConnectRequest> for TlConnectRequest2 {
841    fn from(value: TlConnectRequest) -> Self {
842        Self {
843            base: value,
844            ..FromZeros::new_zeroed()
845        }
846    }
847}
848
849#[repr(C)]
850#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
851pub struct TlConnectResult {
852    pub endpoint_id: Guid,
853    pub service_id: Guid,
854    pub status: i32,
855}
856
857#[repr(C)]
858#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
859pub struct ModifyChannel {
860    pub channel_id: ChannelId,
861    pub target_vp: u32,
862}
863
864#[repr(C)]
865#[derive(PartialEq, Eq, Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
866pub struct ModifyChannelResponse {
867    pub channel_id: ChannelId,
868    pub status: i32,
869}
870
871#[repr(C)]
872#[derive(PartialEq, Eq, Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
873pub struct ModifyConnection {
874    pub parent_to_child_monitor_page_gpa: u64,
875    pub child_to_parent_monitor_page_gpa: u64,
876}
877
878#[repr(C)]
879#[derive(PartialEq, Eq, Debug, Copy, Clone, IntoBytes, FromBytes, Immutable, KnownLayout)]
880pub struct ModifyConnectionResponse {
881    pub connection_state: ConnectionState,
882}
883
884// The remaining structs are for empty messages, provided to simplify the vmbus_messages! macro and
885// to allow for consistent use of the VmbusMessage trait for all messages.
886
887#[repr(C)]
888#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
889pub struct RequestOffers {}
890
891#[repr(C)]
892#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
893pub struct Unload {}
894
895#[repr(C)]
896#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
897pub struct UnloadComplete {}
898
899#[repr(C)]
900#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
901pub struct AllOffersDelivered {}
902
903#[repr(C)]
904#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
905pub struct Pause;
906
907#[repr(C)]
908#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
909pub struct PauseResponse;
910
911#[repr(C)]
912#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoBytes, FromBytes, Immutable, KnownLayout)]
913pub struct Resume;