blob: ee3ed717531cb2f344980883605d9c1d4892a51a [file] [log] [blame]
Balint Dobszay5bf492f2024-07-29 17:21:32 +02001// SPDX-FileCopyrightText: Copyright 2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4#![cfg_attr(not(test), no_std)]
Balint Dobszaya5846852025-02-26 15:38:53 +01005#![deny(clippy::undocumented_unsafe_blocks)]
6#![deny(unsafe_op_in_unsafe_fn)]
7#![doc = include_str!("../README.md")]
Balint Dobszay5bf492f2024-07-29 17:21:32 +02008
Andrew Walbran19970ba2024-11-25 15:35:00 +00009use core::fmt::{self, Debug, Display, Formatter};
Andrew Walbran44029a02024-11-25 15:34:31 +000010use num_enum::{IntoPrimitive, TryFromPrimitive};
11use thiserror::Error;
Imre Kisc0b062c2025-05-26 19:31:00 +020012pub use uuid::Uuid;
Imre Kis189f18c2025-05-26 19:33:05 +020013use zerocopy::{transmute, FromBytes, Immutable, IntoBytes};
Balint Dobszay5bf492f2024-07-29 17:21:32 +020014
15pub mod boot_info;
Balint Dobszayb2ff2bc2024-12-19 18:59:38 +010016mod ffa_v1_1;
Balint Dobszayde0dc802025-02-28 14:16:52 +010017mod ffa_v1_2;
Balint Dobszay5bf492f2024-07-29 17:21:32 +020018pub mod memory_management;
19pub mod partition_info;
20
Balint Dobszaya5846852025-02-26 15:38:53 +010021/// Constant for 4K page size. On many occasions the FF-A spec defines memory size as count of 4K
22/// pages, regardless of the current translation granule.
Balint Dobszay3aad9572025-01-17 16:54:11 +010023pub const FFA_PAGE_SIZE_4K: usize = 4096;
24
Balint Dobszaya5846852025-02-26 15:38:53 +010025/// Rich error types returned by this module. Should be converted to [`crate::FfaError`] when used
26/// with the `FFA_ERROR` interface.
Tomás González0a058bc2025-03-11 11:20:55 +000027#[derive(Debug, Error, PartialEq)]
Balint Dobszay3aad9572025-01-17 16:54:11 +010028pub enum Error {
29 #[error("Unrecognised FF-A function ID {0}")]
30 UnrecognisedFunctionId(u32),
31 #[error("Unrecognised FF-A feature ID {0}")]
32 UnrecognisedFeatureId(u8),
33 #[error("Unrecognised FF-A error code {0}")]
34 UnrecognisedErrorCode(i32),
Tomás González4d5b0ba2025-03-03 17:15:55 +000035 #[error("Unrecognised FF-A Framework Message {0}")]
36 UnrecognisedFwkMsg(u32),
Tomás González092202a2025-03-05 11:56:45 +000037 #[error("Invalid FF-A Msg Wait Flag {0}")]
38 InvalidMsgWaitFlag(u32),
Imre Kisa2fd69b2025-06-13 13:39:47 +020039 #[error("Invalid FF-A Msg Send2 Flag {0}")]
40 InvalidMsgSend2Flag(u32),
Tomás González4d5b0ba2025-03-03 17:15:55 +000041 #[error("Unrecognised VM availability status {0}")]
42 UnrecognisedVmAvailabilityStatus(i32),
43 #[error("Unrecognised FF-A Warm Boot Type {0}")]
44 UnrecognisedWarmBootType(u32),
45 #[error("Invalid version {0}")]
46 InvalidVersion(u32),
Tomás González0a058bc2025-03-11 11:20:55 +000047 #[error("Invalid Information Tag {0}")]
48 InvalidInformationTag(u16),
Tomás González7ffb6132025-04-03 12:28:58 +010049 #[error("Invalid Flag for Notification Set")]
50 InvalidNotificationSetFlag(u32),
51 #[error("Invalid Vm ID")]
52 InvalidVmId(u32),
Imre Kise295adb2025-04-10 13:26:28 +020053 #[error("Invalid FF-A Partition Info Get Flag {0}")]
54 InvalidPartitionInfoGetFlag(u32),
Imre Kis839eaef2025-04-11 17:38:36 +020055 #[error("Invalid success argument variant")]
56 InvalidSuccessArgsVariant,
Imre Kis787c5002025-04-10 14:25:51 +020057 #[error("Invalid notification count")]
58 InvalidNotificationCount,
Imre Kis92b663e2025-04-10 14:15:05 +020059 #[error("Invalid Partition Info Get Regs response")]
60 InvalidPartitionInfoGetRegsResponse,
Balint Dobszay82c71dd2025-04-15 10:16:44 +020061 #[error("Invalid FF-A version {0} for function ID {1:?}")]
62 InvalidVersionForFunctionId(Version, FuncId),
Imre Kis189f18c2025-05-26 19:33:05 +020063 #[error("Invalid character count {0}")]
64 InvalidCharacterCount(u8),
Imre Kis356395d2025-06-13 13:49:06 +020065 #[error("Invalid memory reclaim flags {0}")]
66 InvalidMemReclaimFlags(u32),
Imre Kisdcb7df22025-06-06 15:24:40 +020067 #[error("Memory management error")]
68 MemoryManagementError(#[from] memory_management::Error),
Balint Dobszay3aad9572025-01-17 16:54:11 +010069}
70
71impl From<Error> for FfaError {
72 fn from(value: Error) -> Self {
73 match value {
Balint Dobszay82c71dd2025-04-15 10:16:44 +020074 Error::UnrecognisedFunctionId(_)
75 | Error::UnrecognisedFeatureId(_)
76 | Error::InvalidVersionForFunctionId(..) => Self::NotSupported,
Tomás González0a058bc2025-03-11 11:20:55 +000077 Error::InvalidInformationTag(_) => Self::Retry,
Tomás González4d5b0ba2025-03-03 17:15:55 +000078 Error::UnrecognisedErrorCode(_)
79 | Error::UnrecognisedFwkMsg(_)
80 | Error::InvalidVersion(_)
Tomás González092202a2025-03-05 11:56:45 +000081 | Error::InvalidMsgWaitFlag(_)
Imre Kisa2fd69b2025-06-13 13:39:47 +020082 | Error::InvalidMsgSend2Flag(_)
Tomás González4d5b0ba2025-03-03 17:15:55 +000083 | Error::UnrecognisedVmAvailabilityStatus(_)
Tomás González7ffb6132025-04-03 12:28:58 +010084 | Error::InvalidNotificationSetFlag(_)
85 | Error::InvalidVmId(_)
Imre Kise295adb2025-04-10 13:26:28 +020086 | Error::UnrecognisedWarmBootType(_)
Imre Kis839eaef2025-04-11 17:38:36 +020087 | Error::InvalidPartitionInfoGetFlag(_)
Imre Kis787c5002025-04-10 14:25:51 +020088 | Error::InvalidSuccessArgsVariant
Imre Kis92b663e2025-04-10 14:15:05 +020089 | Error::InvalidNotificationCount
Imre Kis189f18c2025-05-26 19:33:05 +020090 | Error::InvalidPartitionInfoGetRegsResponse
Imre Kisdcb7df22025-06-06 15:24:40 +020091 | Error::InvalidCharacterCount(_)
Imre Kis356395d2025-06-13 13:49:06 +020092 | Error::InvalidMemReclaimFlags(_)
Imre Kisdcb7df22025-06-06 15:24:40 +020093 | Error::MemoryManagementError(_) => Self::InvalidParameters,
Balint Dobszay3aad9572025-01-17 16:54:11 +010094 }
95 }
96}
Balint Dobszay5bf492f2024-07-29 17:21:32 +020097
Balint Dobszaya5846852025-02-26 15:38:53 +010098/// An FF-A instance is a valid combination of two FF-A components at an exception level boundary.
Balint Dobszay5bf492f2024-07-29 17:21:32 +020099#[derive(PartialEq, Clone, Copy)]
100pub enum Instance {
Balint Dobszaya5846852025-02-26 15:38:53 +0100101 /// The instance between the SPMC and SPMD.
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200102 SecurePhysical,
Balint Dobszaya5846852025-02-26 15:38:53 +0100103 /// The instance between the SPMC and a physical SP (contains the SP's endpoint ID).
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200104 SecureVirtual(u16),
105}
106
Balint Dobszaya5846852025-02-26 15:38:53 +0100107/// Function IDs of the various FF-A interfaces.
Andrew Walbran969b9252024-11-25 15:35:42 +0000108#[derive(Clone, Copy, Debug, Eq, IntoPrimitive, PartialEq, TryFromPrimitive)]
Balint Dobszay3aad9572025-01-17 16:54:11 +0100109#[num_enum(error_type(name = Error, constructor = Error::UnrecognisedFunctionId))]
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200110#[repr(u32)]
111pub enum FuncId {
112 Error = 0x84000060,
113 Success32 = 0x84000061,
114 Success64 = 0xc4000061,
115 Interrupt = 0x84000062,
116 Version = 0x84000063,
117 Features = 0x84000064,
118 RxAcquire = 0x84000084,
119 RxRelease = 0x84000065,
120 RxTxMap32 = 0x84000066,
121 RxTxMap64 = 0xc4000066,
122 RxTxUnmap = 0x84000067,
123 PartitionInfoGet = 0x84000068,
Balint Dobszaye6aa4862025-02-28 16:37:56 +0100124 PartitionInfoGetRegs = 0xc400008b,
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200125 IdGet = 0x84000069,
126 SpmIdGet = 0x84000085,
Balint Dobszaye6aa4862025-02-28 16:37:56 +0100127 ConsoleLog32 = 0x8400008a,
128 ConsoleLog64 = 0xc400008a,
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200129 MsgWait = 0x8400006b,
130 Yield = 0x8400006c,
131 Run = 0x8400006d,
132 NormalWorldResume = 0x8400007c,
133 MsgSend2 = 0x84000086,
134 MsgSendDirectReq32 = 0x8400006f,
135 MsgSendDirectReq64 = 0xc400006f,
Balint Dobszayde0dc802025-02-28 14:16:52 +0100136 MsgSendDirectReq64_2 = 0xc400008d,
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200137 MsgSendDirectResp32 = 0x84000070,
138 MsgSendDirectResp64 = 0xc4000070,
Balint Dobszayde0dc802025-02-28 14:16:52 +0100139 MsgSendDirectResp64_2 = 0xc400008e,
Balint Dobszaye6aa4862025-02-28 16:37:56 +0100140 NotificationBitmapCreate = 0x8400007d,
141 NotificationBitmapDestroy = 0x8400007e,
142 NotificationBind = 0x8400007f,
143 NotificationUnbind = 0x84000080,
144 NotificationSet = 0x84000081,
145 NotificationGet = 0x84000082,
146 NotificationInfoGet32 = 0x84000083,
147 NotificationInfoGet64 = 0xc4000083,
148 El3IntrHandle = 0x8400008c,
Tomás González17b92442025-03-10 16:45:04 +0000149 SecondaryEpRegister32 = 0x84000087,
150 SecondaryEpRegister64 = 0xc4000087,
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200151 MemDonate32 = 0x84000071,
152 MemDonate64 = 0xc4000071,
153 MemLend32 = 0x84000072,
154 MemLend64 = 0xc4000072,
155 MemShare32 = 0x84000073,
156 MemShare64 = 0xc4000073,
157 MemRetrieveReq32 = 0x84000074,
158 MemRetrieveReq64 = 0xc4000074,
159 MemRetrieveResp = 0x84000075,
160 MemRelinquish = 0x84000076,
161 MemReclaim = 0x84000077,
162 MemPermGet32 = 0x84000088,
163 MemPermGet64 = 0xc4000088,
164 MemPermSet32 = 0x84000089,
165 MemPermSet64 = 0xc4000089,
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200166}
167
Balint Dobszayde0dc802025-02-28 14:16:52 +0100168impl FuncId {
169 /// Returns true if this is a 32-bit call, or false if it is a 64-bit call.
170 pub fn is_32bit(&self) -> bool {
Tomás González6ccba0a2025-04-09 13:31:29 +0100171 u32::from(*self) & (1 << 30) == 0
Balint Dobszayde0dc802025-02-28 14:16:52 +0100172 }
Balint Dobszay82c71dd2025-04-15 10:16:44 +0200173
174 /// Returns the FF-A version that has introduced the function ID.
175 pub fn minimum_ffa_version(&self) -> Version {
176 match self {
177 FuncId::Error
178 | FuncId::Success32
179 | FuncId::Success64
180 | FuncId::Interrupt
181 | FuncId::Version
182 | FuncId::Features
183 | FuncId::RxRelease
184 | FuncId::RxTxMap32
185 | FuncId::RxTxMap64
186 | FuncId::RxTxUnmap
187 | FuncId::PartitionInfoGet
188 | FuncId::IdGet
189 | FuncId::MsgWait
190 | FuncId::Yield
191 | FuncId::Run
192 | FuncId::NormalWorldResume
193 | FuncId::MsgSendDirectReq32
194 | FuncId::MsgSendDirectReq64
195 | FuncId::MsgSendDirectResp32
196 | FuncId::MsgSendDirectResp64
197 | FuncId::MemDonate32
198 | FuncId::MemDonate64
199 | FuncId::MemLend32
200 | FuncId::MemLend64
201 | FuncId::MemShare32
202 | FuncId::MemShare64
203 | FuncId::MemRetrieveReq32
204 | FuncId::MemRetrieveReq64
205 | FuncId::MemRetrieveResp
206 | FuncId::MemRelinquish
207 | FuncId::MemReclaim => Version(1, 0),
208
209 FuncId::RxAcquire
210 | FuncId::SpmIdGet
211 | FuncId::MsgSend2
212 | FuncId::MemPermGet32
213 | FuncId::MemPermGet64
214 | FuncId::MemPermSet32
215 | FuncId::MemPermSet64
216 | FuncId::NotificationBitmapCreate
217 | FuncId::NotificationBitmapDestroy
218 | FuncId::NotificationBind
219 | FuncId::NotificationUnbind
220 | FuncId::NotificationSet
221 | FuncId::NotificationGet
222 | FuncId::NotificationInfoGet32
223 | FuncId::NotificationInfoGet64
224 | FuncId::SecondaryEpRegister32
225 | FuncId::SecondaryEpRegister64 => Version(1, 1),
226
227 FuncId::PartitionInfoGetRegs
228 | FuncId::ConsoleLog32
229 | FuncId::ConsoleLog64
230 | FuncId::MsgSendDirectReq64_2
231 | FuncId::MsgSendDirectResp64_2
232 | FuncId::El3IntrHandle => Version(1, 2),
233 }
234 }
Balint Dobszayde0dc802025-02-28 14:16:52 +0100235}
236
Balint Dobszaya5846852025-02-26 15:38:53 +0100237/// Error status codes used by the `FFA_ERROR` interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100238#[derive(Clone, Copy, Debug, Eq, Error, IntoPrimitive, PartialEq, TryFromPrimitive)]
239#[num_enum(error_type(name = Error, constructor = Error::UnrecognisedErrorCode))]
240#[repr(i32)]
241pub enum FfaError {
242 #[error("Not supported")]
243 NotSupported = -1,
244 #[error("Invalid parameters")]
245 InvalidParameters = -2,
246 #[error("No memory")]
247 NoMemory = -3,
248 #[error("Busy")]
249 Busy = -4,
250 #[error("Interrupted")]
251 Interrupted = -5,
252 #[error("Denied")]
253 Denied = -6,
254 #[error("Retry")]
255 Retry = -7,
256 #[error("Aborted")]
257 Aborted = -8,
258 #[error("No data")]
259 NoData = -9,
260}
261
Balint Dobszaya5846852025-02-26 15:38:53 +0100262/// Endpoint ID and vCPU ID pair, used by `FFA_ERROR`, `FFA_INTERRUPT` and `FFA_RUN` interfaces.
Imre Kise521a282025-06-13 13:29:24 +0200263#[derive(Debug, Default, Eq, PartialEq, Clone, Copy)]
Balint Dobszay3aad9572025-01-17 16:54:11 +0100264pub struct TargetInfo {
265 pub endpoint_id: u16,
266 pub vcpu_id: u16,
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200267}
268
Balint Dobszay3aad9572025-01-17 16:54:11 +0100269impl From<u32> for TargetInfo {
270 fn from(value: u32) -> Self {
271 Self {
272 endpoint_id: (value >> 16) as u16,
273 vcpu_id: value as u16,
274 }
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200275 }
276}
277
Balint Dobszay3aad9572025-01-17 16:54:11 +0100278impl From<TargetInfo> for u32 {
279 fn from(value: TargetInfo) -> Self {
Balint Dobszaye9a3e762025-02-26 17:29:57 +0100280 ((value.endpoint_id as u32) << 16) | value.vcpu_id as u32
Andrew Walbran0d315812024-11-25 15:36:36 +0000281 }
Balint Dobszay3aad9572025-01-17 16:54:11 +0100282}
Andrew Walbran0d315812024-11-25 15:36:36 +0000283
Imre Kis839eaef2025-04-11 17:38:36 +0200284/// Generic arguments of the `FFA_SUCCESS` interface. The interpretation of the arguments depends on
285/// the interface that initiated the request. The application code has knowledge of the request, so
286/// it has to convert `SuccessArgs` into/from a specific success args structure that matches the
287/// request.
Imre Kis4e9d8bc2025-04-10 13:48:26 +0200288///
289/// The current specialized success arguments types are:
290/// * `FFA_FEATURES` - [`SuccessArgsFeatures`]
Imre Kisbbef2872025-04-10 14:11:29 +0200291/// * `FFA_ID_GET` - [`SuccessArgsIdGet`]
292/// * `FFA_SPM_ID_GET` - [`SuccessArgsSpmIdGet`]
Imre Kis61c34092025-04-10 14:14:38 +0200293/// * `FFA_PARTITION_INFO_GET` - [`partition_info::SuccessArgsPartitionInfoGet`]
Imre Kis92b663e2025-04-10 14:15:05 +0200294/// * `FFA_PARTITION_INFO_GET_REGS` - [`partition_info::SuccessArgsPartitionInfoGetRegs`]
Imre Kis9959e062025-04-10 14:16:10 +0200295/// * `FFA_NOTIFICATION_GET` - [`SuccessArgsNotificationGet`]
Imre Kis787c5002025-04-10 14:25:51 +0200296/// * `FFA_NOTIFICATION_INFO_GET_32` - [`SuccessArgsNotificationInfoGet32`]
297/// * `FFA_NOTIFICATION_INFO_GET_64` - [`SuccessArgsNotificationInfoGet64`]
Balint Dobszay3aad9572025-01-17 16:54:11 +0100298#[derive(Debug, Eq, PartialEq, Clone, Copy)]
299pub enum SuccessArgs {
Imre Kis54773b62025-04-10 13:47:39 +0200300 Args32([u32; 6]),
301 Args64([u64; 6]),
302 Args64_2([u64; 16]),
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200303}
304
Imre Kis839eaef2025-04-11 17:38:36 +0200305impl SuccessArgs {
306 fn try_get_args32(self) -> Result<[u32; 6], Error> {
307 match self {
308 SuccessArgs::Args32(args) => Ok(args),
309 SuccessArgs::Args64(_) | SuccessArgs::Args64_2(_) => {
310 Err(Error::InvalidSuccessArgsVariant)
311 }
312 }
313 }
314
315 fn try_get_args64(self) -> Result<[u64; 6], Error> {
316 match self {
317 SuccessArgs::Args64(args) => Ok(args),
318 SuccessArgs::Args32(_) | SuccessArgs::Args64_2(_) => {
319 Err(Error::InvalidSuccessArgsVariant)
320 }
321 }
322 }
323
324 fn try_get_args64_2(self) -> Result<[u64; 16], Error> {
325 match self {
326 SuccessArgs::Args64_2(args) => Ok(args),
327 SuccessArgs::Args32(_) | SuccessArgs::Args64(_) => {
328 Err(Error::InvalidSuccessArgsVariant)
329 }
330 }
331 }
332}
333
Tomás González17b92442025-03-10 16:45:04 +0000334/// Entrypoint address argument for `FFA_SECONDARY_EP_REGISTER` interface.
335#[derive(Debug, Eq, PartialEq, Clone, Copy)]
336pub enum SecondaryEpRegisterAddr {
337 Addr32(u32),
338 Addr64(u64),
339}
340
Balint Dobszaya5846852025-02-26 15:38:53 +0100341/// Version number of the FF-A implementation, `.0` is the major, `.1` is minor the version.
Balint Dobszayde0dc802025-02-28 14:16:52 +0100342#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200343pub struct Version(pub u16, pub u16);
344
Tomás González1f794352025-03-03 16:47:06 +0000345impl Version {
Tomás González83146af2025-03-04 11:32:41 +0000346 // The FF-A spec mandates that bit[31] of a version number must be 0
347 const MBZ_BITS: u32 = 1 << 31;
348
Tomás González1f794352025-03-03 16:47:06 +0000349 /// Returns whether the caller's version (self) is compatible with the callee's version (input
350 /// parameter)
351 pub fn is_compatible_to(&self, callee_version: &Version) -> bool {
352 self.0 == callee_version.0 && self.1 <= callee_version.1
353 }
Balint Dobszay5ded5922025-06-13 12:06:53 +0200354
355 /// Returns true if the specified FF-A version uses 18 registers for calls, false if it uses 8.
356 pub fn needs_18_regs(&self) -> bool {
357 *self >= Version(1, 2)
358 }
Tomás González1f794352025-03-03 16:47:06 +0000359}
360
Tomás González83146af2025-03-04 11:32:41 +0000361impl TryFrom<u32> for Version {
362 type Error = Error;
363
364 fn try_from(val: u32) -> Result<Self, Self::Error> {
365 if (val & Self::MBZ_BITS) != 0 {
366 Err(Error::InvalidVersion(val))
367 } else {
368 Ok(Self((val >> 16) as u16, val as u16))
369 }
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200370 }
371}
372
373impl From<Version> for u32 {
374 fn from(v: Version) -> Self {
Tomás González83146af2025-03-04 11:32:41 +0000375 let v_u32 = ((v.0 as u32) << 16) | v.1 as u32;
376 assert!(v_u32 & Version::MBZ_BITS == 0);
377 v_u32
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200378 }
379}
380
Andrew Walbran19970ba2024-11-25 15:35:00 +0000381impl Display for Version {
382 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
383 write!(f, "{}.{}", self.0, self.1)
384 }
385}
386
387impl Debug for Version {
388 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
389 Display::fmt(self, f)
390 }
391}
392
Balint Dobszaya5846852025-02-26 15:38:53 +0100393/// Feature IDs used by the `FFA_FEATURES` interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100394#[derive(Clone, Copy, Debug, Eq, IntoPrimitive, PartialEq, TryFromPrimitive)]
395#[num_enum(error_type(name = Error, constructor = Error::UnrecognisedFeatureId))]
396#[repr(u8)]
397pub enum FeatureId {
398 NotificationPendingInterrupt = 0x1,
399 ScheduleReceiverInterrupt = 0x2,
400 ManagedExitInterrupt = 0x3,
401}
Balint Dobszayc8802492025-01-15 18:11:39 +0100402
Balint Dobszaya5846852025-02-26 15:38:53 +0100403/// Arguments for the `FFA_FEATURES` interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100404#[derive(Debug, Eq, PartialEq, Clone, Copy)]
405pub enum Feature {
406 FuncId(FuncId),
407 FeatureId(FeatureId),
Balint Dobszayc31e0b92025-03-03 20:16:56 +0100408 Unknown(u32),
Balint Dobszay3aad9572025-01-17 16:54:11 +0100409}
Balint Dobszay5bf492f2024-07-29 17:21:32 +0200410
Balint Dobszayc31e0b92025-03-03 20:16:56 +0100411impl From<u32> for Feature {
412 fn from(value: u32) -> Self {
413 // Bit[31] is set for all valid FF-A function IDs so we don't have to check it separately
414 if let Ok(func_id) = value.try_into() {
415 Self::FuncId(func_id)
416 } else if let Ok(feat_id) = (value as u8).try_into() {
417 Self::FeatureId(feat_id)
Balint Dobszay3aad9572025-01-17 16:54:11 +0100418 } else {
Balint Dobszayc31e0b92025-03-03 20:16:56 +0100419 Self::Unknown(value)
420 }
Balint Dobszay3aad9572025-01-17 16:54:11 +0100421 }
422}
423
424impl From<Feature> for u32 {
425 fn from(value: Feature) -> Self {
426 match value {
427 Feature::FuncId(func_id) => (1 << 31) | func_id as u32,
428 Feature::FeatureId(feature_id) => feature_id as u32,
Imre Kis29c8ace2025-04-11 13:49:58 +0200429 Feature::Unknown(id) => id,
Balint Dobszay3aad9572025-01-17 16:54:11 +0100430 }
431 }
432}
433
Imre Kis4e9d8bc2025-04-10 13:48:26 +0200434/// `FFA_FEATURES` specific success argument structure. This type needs further specialization based
435/// on 'FF-A function ID or Feature ID' field of the preceeding `FFA_FEATURES` request.
Imre Kisa9e544c2025-06-13 15:57:54 +0200436#[derive(Debug, Eq, Default, PartialEq, Clone, Copy)]
Imre Kis4e9d8bc2025-04-10 13:48:26 +0200437pub struct SuccessArgsFeatures {
438 pub properties: [u32; 2],
439}
440
441impl From<SuccessArgsFeatures> for SuccessArgs {
442 fn from(value: SuccessArgsFeatures) -> Self {
443 Self::Args32([value.properties[0], value.properties[1], 0, 0, 0, 0])
444 }
445}
446
447impl TryFrom<SuccessArgs> for SuccessArgsFeatures {
448 type Error = Error;
449
450 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
451 let args = value.try_get_args32()?;
452
453 Ok(Self {
454 properties: [args[0], args[1]],
455 })
456 }
457}
458
Balint Dobszaya5846852025-02-26 15:38:53 +0100459/// RXTX buffer descriptor, used by `FFA_RXTX_MAP`.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100460#[derive(Debug, Eq, PartialEq, Clone, Copy)]
461pub enum RxTxAddr {
462 Addr32 { rx: u32, tx: u32 },
463 Addr64 { rx: u64, tx: u64 },
464}
465
Imre Kisbbef2872025-04-10 14:11:29 +0200466/// `FFA_ID_GET` specific success argument structure.
467#[derive(Debug, Eq, PartialEq, Clone, Copy)]
468pub struct SuccessArgsIdGet {
469 pub id: u16,
470}
471
472impl From<SuccessArgsIdGet> for SuccessArgs {
473 fn from(value: SuccessArgsIdGet) -> Self {
474 SuccessArgs::Args32([value.id as u32, 0, 0, 0, 0, 0])
475 }
476}
477
478impl TryFrom<SuccessArgs> for SuccessArgsIdGet {
479 type Error = Error;
480
481 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
482 let args = value.try_get_args32()?;
483 Ok(Self { id: args[0] as u16 })
484 }
485}
486
487/// `FFA_SPM_ID_GET` specific success argument structure.
488#[derive(Debug, Eq, PartialEq, Clone, Copy)]
489pub struct SuccessArgsSpmIdGet {
490 pub id: u16,
491}
492
493impl From<SuccessArgsSpmIdGet> for SuccessArgs {
494 fn from(value: SuccessArgsSpmIdGet) -> Self {
495 SuccessArgs::Args32([value.id as u32, 0, 0, 0, 0, 0])
496 }
497}
498
499impl TryFrom<SuccessArgs> for SuccessArgsSpmIdGet {
500 type Error = Error;
501
502 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
503 let args = value.try_get_args32()?;
504 Ok(Self { id: args[0] as u16 })
505 }
506}
507
Imre Kise295adb2025-04-10 13:26:28 +0200508/// Flags of the `FFA_PARTITION_INFO_GET` interface.
509#[derive(Debug, Eq, PartialEq, Clone, Copy)]
510pub struct PartitionInfoGetFlags {
511 pub count_only: bool,
512}
513
514impl PartitionInfoGetFlags {
515 const RETURN_INFORMATION_TYPE_FLAG: u32 = 1 << 0;
516 const MBZ_BITS: u32 = 0xffff_fffe;
517}
518
519impl TryFrom<u32> for PartitionInfoGetFlags {
520 type Error = Error;
521
522 fn try_from(val: u32) -> Result<Self, Self::Error> {
523 if (val & Self::MBZ_BITS) != 0 {
524 Err(Error::InvalidPartitionInfoGetFlag(val))
525 } else {
526 Ok(Self {
527 count_only: val & Self::RETURN_INFORMATION_TYPE_FLAG != 0,
528 })
529 }
530 }
531}
532
533impl From<PartitionInfoGetFlags> for u32 {
534 fn from(flags: PartitionInfoGetFlags) -> Self {
535 let mut bits: u32 = 0;
536 if flags.count_only {
537 bits |= PartitionInfoGetFlags::RETURN_INFORMATION_TYPE_FLAG;
538 }
539 bits
540 }
541}
542
Imre Kis68389c72025-06-16 12:42:49 +0200543/// Flags field of the `FFA_MSG_SEND2` interface.
Imre Kisa9e544c2025-06-13 15:57:54 +0200544#[derive(Debug, Eq, Default, PartialEq, Clone, Copy)]
Imre Kisa2fd69b2025-06-13 13:39:47 +0200545pub struct MsgSend2Flags {
546 pub delay_schedule_receiver: bool,
547}
548
549impl MsgSend2Flags {
550 const DELAY_SCHEDULE_RECEIVER: u32 = 1 << 1;
551 const MBZ_BITS: u32 = 0xffff_fffd;
552}
553
554impl TryFrom<u32> for MsgSend2Flags {
555 type Error = Error;
556
557 fn try_from(val: u32) -> Result<Self, Self::Error> {
558 if (val & Self::MBZ_BITS) != 0 {
559 Err(Error::InvalidMsgSend2Flag(val))
560 } else {
561 Ok(MsgSend2Flags {
562 delay_schedule_receiver: val & Self::DELAY_SCHEDULE_RECEIVER != 0,
563 })
564 }
565 }
566}
567
568impl From<MsgSend2Flags> for u32 {
569 fn from(flags: MsgSend2Flags) -> Self {
570 let mut bits: u32 = 0;
571 if flags.delay_schedule_receiver {
572 bits |= MsgSend2Flags::DELAY_SCHEDULE_RECEIVER;
573 }
574 bits
575 }
576}
577
Tomás González4d5b0ba2025-03-03 17:15:55 +0000578/// Composite type for capturing success and error return codes for the VM availability messages.
579///
580/// Error codes are handled by the `FfaError` type. Having a separate type for errors helps using
581/// `Result<(), FfaError>`. If a single type would include both success and error values,
582/// then `Err(FfaError::Success)` would be incomprehensible.
583#[derive(Debug, Eq, PartialEq, Clone, Copy)]
584pub enum VmAvailabilityStatus {
585 Success,
586 Error(FfaError),
587}
588
589impl TryFrom<i32> for VmAvailabilityStatus {
590 type Error = Error;
591 fn try_from(value: i32) -> Result<Self, <Self as TryFrom<i32>>::Error> {
592 Ok(match value {
593 0 => Self::Success,
594 error_code => Self::Error(FfaError::try_from(error_code)?),
595 })
596 }
597}
598
599impl From<VmAvailabilityStatus> for i32 {
600 fn from(value: VmAvailabilityStatus) -> Self {
601 match value {
602 VmAvailabilityStatus::Success => 0,
603 VmAvailabilityStatus::Error(error_code) => error_code.into(),
604 }
605 }
606}
607
608/// Arguments for the Power Warm Boot `FFA_MSG_SEND_DIRECT_REQ` interface.
609#[derive(Clone, Copy, Debug, Eq, IntoPrimitive, PartialEq, TryFromPrimitive)]
610#[num_enum(error_type(name = Error, constructor = Error::UnrecognisedWarmBootType))]
611#[repr(u32)]
612pub enum WarmBootType {
613 ExitFromSuspend = 0,
614 ExitFromLowPower = 1,
615}
616
Balint Dobszaya5846852025-02-26 15:38:53 +0100617/// Arguments for the `FFA_MSG_SEND_DIRECT_{REQ,RESP}` interfaces.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100618#[derive(Debug, Eq, PartialEq, Clone, Copy)]
619pub enum DirectMsgArgs {
620 Args32([u32; 5]),
621 Args64([u64; 5]),
Tomás González4d5b0ba2025-03-03 17:15:55 +0000622 /// Message for forwarding FFA_VERSION call from Normal world to the SPMC
623 VersionReq {
624 version: Version,
625 },
626 /// Response message to forwarded FFA_VERSION call from the Normal world
627 /// Contains the version returned by the SPMC or None
628 VersionResp {
629 version: Option<Version>,
630 },
631 /// Message for a power management operation initiated by a PSCI function
632 PowerPsciReq32 {
Tomás González4d5b0ba2025-03-03 17:15:55 +0000633 // params[i]: Input parameter in w[i] in PSCI function invocation at EL3.
Tomás González67f92c72025-03-20 16:50:42 +0000634 // params[0]: Function ID.
635 params: [u32; 4],
Tomás González4d5b0ba2025-03-03 17:15:55 +0000636 },
637 /// Message for a power management operation initiated by a PSCI function
638 PowerPsciReq64 {
Tomás González4d5b0ba2025-03-03 17:15:55 +0000639 // params[i]: Input parameter in x[i] in PSCI function invocation at EL3.
Tomás González67f92c72025-03-20 16:50:42 +0000640 // params[0]: Function ID.
641 params: [u64; 4],
Tomás González4d5b0ba2025-03-03 17:15:55 +0000642 },
643 /// Message for a warm boot
644 PowerWarmBootReq {
645 boot_type: WarmBootType,
646 },
647 /// Response message to indicate return status of the last power management request message
648 /// Return error code SUCCESS or DENIED as defined in PSCI spec. Caller is left to do the
649 /// parsing of the return status.
650 PowerPsciResp {
Tomás González4d5b0ba2025-03-03 17:15:55 +0000651 psci_status: i32,
652 },
653 /// Message to signal creation of a VM
654 VmCreated {
655 // Globally unique Handle to identify a memory region that contains IMPLEMENTATION DEFINED
656 // information associated with the created VM.
657 // The invalid memory region handle must be specified by the Hypervisor if this field is not
658 // used.
659 handle: memory_management::Handle,
660 vm_id: u16,
661 },
662 /// Message to acknowledge creation of a VM
663 VmCreatedAck {
664 sp_status: VmAvailabilityStatus,
665 },
666 /// Message to signal destruction of a VM
667 VmDestructed {
668 // Globally unique Handle to identify a memory region that contains IMPLEMENTATION DEFINED
669 // information associated with the created VM.
670 // The invalid memory region handle must be specified by the Hypervisor if this field is not
671 // used.
672 handle: memory_management::Handle,
673 vm_id: u16,
674 },
675 /// Message to acknowledge destruction of a VM
676 VmDestructedAck {
677 sp_status: VmAvailabilityStatus,
678 },
679}
680
681impl DirectMsgArgs {
682 // Flags for the `FFA_MSG_SEND_DIRECT_{REQ,RESP}` interfaces.
683
684 const FWK_MSG_BITS: u32 = 1 << 31;
685 const VERSION_REQ: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b1000;
686 const VERSION_RESP: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b1001;
687 const POWER_PSCI_REQ: u32 = DirectMsgArgs::FWK_MSG_BITS;
688 const POWER_WARM_BOOT_REQ: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b0001;
689 const POWER_PSCI_RESP: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b0010;
690 const VM_CREATED: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b0100;
691 const VM_CREATED_ACK: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b0101;
692 const VM_DESTRUCTED: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b0110;
693 const VM_DESTRUCTED_ACK: u32 = DirectMsgArgs::FWK_MSG_BITS | 0b0111;
Balint Dobszay3aad9572025-01-17 16:54:11 +0100694}
695
Balint Dobszayde0dc802025-02-28 14:16:52 +0100696/// Arguments for the `FFA_MSG_SEND_DIRECT_{REQ,RESP}2` interfaces.
697#[derive(Debug, Eq, PartialEq, Clone, Copy)]
Imre Kisc739e0e2025-05-30 11:49:25 +0200698pub struct DirectMsg2Args(pub [u64; 14]);
Balint Dobszayde0dc802025-02-28 14:16:52 +0100699
Imre Kis68389c72025-06-16 12:42:49 +0200700/// Flags field of the `FFA_MSG_WAIT` interface.
Imre Kisa9e544c2025-06-13 15:57:54 +0200701#[derive(Debug, Default, Eq, PartialEq, Clone, Copy)]
Tomás González092202a2025-03-05 11:56:45 +0000702pub struct MsgWaitFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200703 pub retain_rx_buffer: bool,
Tomás González092202a2025-03-05 11:56:45 +0000704}
705
706impl MsgWaitFlags {
707 const RETAIN_RX_BUFFER: u32 = 0x01;
708 const MBZ_BITS: u32 = 0xfffe;
709}
710
711impl TryFrom<u32> for MsgWaitFlags {
712 type Error = Error;
713
714 fn try_from(val: u32) -> Result<Self, Self::Error> {
715 if (val & Self::MBZ_BITS) != 0 {
716 Err(Error::InvalidMsgWaitFlag(val))
717 } else {
718 Ok(MsgWaitFlags {
719 retain_rx_buffer: val & Self::RETAIN_RX_BUFFER != 0,
720 })
721 }
722 }
723}
724
725impl From<MsgWaitFlags> for u32 {
726 fn from(flags: MsgWaitFlags) -> Self {
727 let mut bits: u32 = 0;
728 if flags.retain_rx_buffer {
729 bits |= MsgWaitFlags::RETAIN_RX_BUFFER;
730 }
731 bits
732 }
733}
734
Balint Dobszaya5846852025-02-26 15:38:53 +0100735/// Descriptor for a dynamically allocated memory buffer that contains the memory transaction
Tomás Gonzálezf268e322025-03-05 11:18:11 +0000736/// descriptor.
737///
738/// Used by `FFA_MEM_{DONATE,LEND,SHARE,RETRIEVE_REQ}` interfaces, only when the TX buffer is not
739/// used to transmit the transaction descriptor.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100740#[derive(Debug, Eq, PartialEq, Clone, Copy)]
741pub enum MemOpBuf {
742 Buf32 { addr: u32, page_cnt: u32 },
743 Buf64 { addr: u64, page_cnt: u32 },
744}
745
Balint Dobszaya5846852025-02-26 15:38:53 +0100746/// Memory address argument for `FFA_MEM_PERM_{GET,SET}` interfaces.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100747#[derive(Debug, Eq, PartialEq, Clone, Copy)]
748pub enum MemAddr {
749 Addr32(u32),
750 Addr64(u64),
751}
752
Balint Dobszay5cc04d62025-06-16 13:22:15 +0200753impl MemAddr {
754 /// Returns the contained address.
755 pub fn address(&self) -> u64 {
756 match self {
757 MemAddr::Addr32(a) => (*a).into(),
758 MemAddr::Addr64(a) => *a,
759 }
760 }
761}
762
Balint Dobszayde0dc802025-02-28 14:16:52 +0100763/// Argument for the `FFA_CONSOLE_LOG` interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100764#[derive(Debug, Eq, PartialEq, Clone, Copy)]
765pub enum ConsoleLogChars {
Imre Kis189f18c2025-05-26 19:33:05 +0200766 Chars32(ConsoleLogChars32),
767 Chars64(ConsoleLogChars64),
Balint Dobszay3aad9572025-01-17 16:54:11 +0100768}
769
Imre Kis189f18c2025-05-26 19:33:05 +0200770/// Generic type for storing `FFA_CONSOLE_LOG` character payload and its length in bytes.
771#[derive(Debug, Default, Eq, PartialEq, Clone, Copy)]
772pub struct LogChars<T>
773where
774 T: IntoBytes + FromBytes + Immutable,
775{
776 char_cnt: u8,
777 char_lists: T,
778}
779
780impl<T> LogChars<T>
781where
782 T: IntoBytes + FromBytes + Immutable,
783{
784 const MAX_LENGTH: u8 = core::mem::size_of::<T>() as u8;
785
786 /// Returns true if there are no characters in the structure.
787 pub fn empty(&self) -> bool {
788 self.char_cnt == 0
789 }
790
791 /// Returns true if the structure is full.
792 pub fn full(&self) -> bool {
793 self.char_cnt as usize >= core::mem::size_of::<T>()
794 }
795
796 /// Returns the payload bytes.
797 pub fn bytes(&self) -> &[u8] {
798 &self.char_lists.as_bytes()[..self.char_cnt as usize]
799 }
800
801 /// Append byte slice to the end of the characters.
802 pub fn push(&mut self, source: &[u8]) -> usize {
803 let empty_area = &mut self.char_lists.as_mut_bytes()[self.char_cnt.into()..];
804 let len = empty_area.len().min(source.len());
805
806 empty_area[..len].copy_from_slice(&source[..len]);
807 self.char_cnt += len as u8;
808
809 len
810 }
811}
812
813/// Specialized type for 32-bit `FFA_CONSOLE_LOG` payload.
814pub type ConsoleLogChars32 = LogChars<[u32; 6]>;
815
816/// Specialized type for 64-bit `FFA_CONSOLE_LOG` payload.
817pub type ConsoleLogChars64 = LogChars<[u64; 16]>;
818
Imre Kis68389c72025-06-16 12:42:49 +0200819/// Flags field of the `FFA_NOTIFICATION_BIND` interface.
Tomás González7ffb6132025-04-03 12:28:58 +0100820#[derive(Debug, Eq, PartialEq, Clone, Copy)]
821pub struct NotificationBindFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200822 pub per_vcpu_notification: bool,
Tomás González7ffb6132025-04-03 12:28:58 +0100823}
824
825impl NotificationBindFlags {
826 const PER_VCPU_NOTIFICATION: u32 = 1;
827}
828
829impl From<NotificationBindFlags> for u32 {
830 fn from(flags: NotificationBindFlags) -> Self {
831 let mut bits: u32 = 0;
832 if flags.per_vcpu_notification {
833 bits |= NotificationBindFlags::PER_VCPU_NOTIFICATION;
834 }
835 bits
836 }
837}
838
839impl From<u32> for NotificationBindFlags {
840 fn from(flags: u32) -> Self {
841 Self {
842 per_vcpu_notification: flags & Self::PER_VCPU_NOTIFICATION != 0,
843 }
844 }
845}
846
Imre Kis68389c72025-06-16 12:42:49 +0200847/// Flags field of the `FFA_NOTIFICATION_SET` interface.
Tomás González7ffb6132025-04-03 12:28:58 +0100848#[derive(Debug, Eq, PartialEq, Clone, Copy)]
849pub struct NotificationSetFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200850 pub delay_schedule_receiver: bool,
851 pub vcpu_id: Option<u16>,
Tomás González7ffb6132025-04-03 12:28:58 +0100852}
853
854impl NotificationSetFlags {
855 const PER_VCP_NOTIFICATION: u32 = 1 << 0;
856 const DELAY_SCHEDULE_RECEIVER: u32 = 1 << 1;
857 const VCPU_ID_SHIFT: u32 = 16;
858
859 const MBZ_BITS: u32 = 0xfffc;
860}
861
862impl From<NotificationSetFlags> for u32 {
863 fn from(flags: NotificationSetFlags) -> Self {
864 let mut bits: u32 = 0;
865
866 if flags.delay_schedule_receiver {
867 bits |= NotificationSetFlags::DELAY_SCHEDULE_RECEIVER;
868 }
869 if let Some(vcpu_id) = flags.vcpu_id {
870 bits |= NotificationSetFlags::PER_VCP_NOTIFICATION;
871 bits |= u32::from(vcpu_id) << NotificationSetFlags::VCPU_ID_SHIFT;
872 }
873
874 bits
875 }
876}
877
878impl TryFrom<u32> for NotificationSetFlags {
879 type Error = Error;
880
881 fn try_from(flags: u32) -> Result<Self, Self::Error> {
882 if (flags & Self::MBZ_BITS) != 0 {
883 return Err(Error::InvalidNotificationSetFlag(flags));
884 }
885
886 let tentative_vcpu_id = (flags >> Self::VCPU_ID_SHIFT) as u16;
887
888 let vcpu_id = if (flags & Self::PER_VCP_NOTIFICATION) != 0 {
889 Some(tentative_vcpu_id)
890 } else {
891 if tentative_vcpu_id != 0 {
892 return Err(Error::InvalidNotificationSetFlag(flags));
893 }
894 None
895 };
896
897 Ok(Self {
898 delay_schedule_receiver: (flags & Self::DELAY_SCHEDULE_RECEIVER) != 0,
899 vcpu_id,
900 })
901 }
902}
903
Imre Kis68389c72025-06-16 12:42:49 +0200904/// Flags field of the `FFA_NOTIFICATION_GET` interface.
Tomás González7ffb6132025-04-03 12:28:58 +0100905#[derive(Debug, Eq, PartialEq, Clone, Copy)]
906pub struct NotificationGetFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200907 pub sp_bitmap_id: bool,
908 pub vm_bitmap_id: bool,
909 pub spm_bitmap_id: bool,
910 pub hyp_bitmap_id: bool,
Tomás González7ffb6132025-04-03 12:28:58 +0100911}
912
913impl NotificationGetFlags {
914 const SP_BITMAP_ID: u32 = 1;
915 const VM_BITMAP_ID: u32 = 1 << 1;
916 const SPM_BITMAP_ID: u32 = 1 << 2;
917 const HYP_BITMAP_ID: u32 = 1 << 3;
918}
919
920impl From<NotificationGetFlags> for u32 {
921 fn from(flags: NotificationGetFlags) -> Self {
922 let mut bits: u32 = 0;
923 if flags.sp_bitmap_id {
924 bits |= NotificationGetFlags::SP_BITMAP_ID;
925 }
926 if flags.vm_bitmap_id {
927 bits |= NotificationGetFlags::VM_BITMAP_ID;
928 }
929 if flags.spm_bitmap_id {
930 bits |= NotificationGetFlags::SPM_BITMAP_ID;
931 }
932 if flags.hyp_bitmap_id {
933 bits |= NotificationGetFlags::HYP_BITMAP_ID;
934 }
935 bits
936 }
937}
938
939impl From<u32> for NotificationGetFlags {
940 // This is a "from" instead of a "try_from" because Reserved Bits are SBZ, *not* MBZ.
941 fn from(flags: u32) -> Self {
942 Self {
943 sp_bitmap_id: (flags & Self::SP_BITMAP_ID) != 0,
944 vm_bitmap_id: (flags & Self::VM_BITMAP_ID) != 0,
945 spm_bitmap_id: (flags & Self::SPM_BITMAP_ID) != 0,
946 hyp_bitmap_id: (flags & Self::HYP_BITMAP_ID) != 0,
947 }
948 }
949}
950
Imre Kis9959e062025-04-10 14:16:10 +0200951/// `FFA_NOTIFICATION_GET` specific success argument structure.
952#[derive(Debug, Eq, PartialEq, Clone, Copy)]
953pub struct SuccessArgsNotificationGet {
954 pub sp_notifications: Option<u64>,
955 pub vm_notifications: Option<u64>,
956 pub spm_notifications: Option<u32>,
957 pub hypervisor_notifications: Option<u32>,
958}
959
960impl From<SuccessArgsNotificationGet> for SuccessArgs {
961 fn from(value: SuccessArgsNotificationGet) -> Self {
962 let mut args = [0; 6];
963
964 if let Some(bitmap) = value.sp_notifications {
965 args[0] = bitmap as u32;
966 args[1] = (bitmap >> 32) as u32;
967 }
968
969 if let Some(bitmap) = value.vm_notifications {
970 args[2] = bitmap as u32;
971 args[3] = (bitmap >> 32) as u32;
972 }
973
974 if let Some(bitmap) = value.spm_notifications {
975 args[4] = bitmap;
976 }
977
978 if let Some(bitmap) = value.hypervisor_notifications {
979 args[5] = bitmap;
980 }
981
982 Self::Args32(args)
983 }
984}
985
986impl TryFrom<(NotificationGetFlags, SuccessArgs)> for SuccessArgsNotificationGet {
987 type Error = Error;
988
989 fn try_from(value: (NotificationGetFlags, SuccessArgs)) -> Result<Self, Self::Error> {
990 let (flags, value) = value;
991 let args = value.try_get_args32()?;
992
993 let sp_notifications = if flags.sp_bitmap_id {
994 Some(u64::from(args[0]) | (u64::from(args[1]) << 32))
995 } else {
996 None
997 };
998
999 let vm_notifications = if flags.vm_bitmap_id {
1000 Some(u64::from(args[2]) | (u64::from(args[3]) << 32))
1001 } else {
1002 None
1003 };
1004
1005 let spm_notifications = if flags.spm_bitmap_id {
1006 Some(args[4])
1007 } else {
1008 None
1009 };
1010
1011 let hypervisor_notifications = if flags.hyp_bitmap_id {
1012 Some(args[5])
1013 } else {
1014 None
1015 };
1016
1017 Ok(Self {
1018 sp_notifications,
1019 vm_notifications,
1020 spm_notifications,
1021 hypervisor_notifications,
1022 })
1023 }
1024}
Imre Kis787c5002025-04-10 14:25:51 +02001025
1026/// `FFA_NOTIFICATION_INFO_GET` specific success argument structure. The `MAX_COUNT` parameter
1027/// depends on the 32-bit or 64-bit packing.
1028#[derive(Debug, Eq, PartialEq, Clone, Copy)]
1029pub struct SuccessArgsNotificationInfoGet<const MAX_COUNT: usize> {
1030 pub more_pending_notifications: bool,
1031 list_count: usize,
1032 id_counts: [u8; MAX_COUNT],
1033 ids: [u16; MAX_COUNT],
1034}
1035
1036impl<const MAX_COUNT: usize> Default for SuccessArgsNotificationInfoGet<MAX_COUNT> {
1037 fn default() -> Self {
1038 Self {
1039 more_pending_notifications: false,
1040 list_count: 0,
1041 id_counts: [0; MAX_COUNT],
1042 ids: [0; MAX_COUNT],
1043 }
1044 }
1045}
1046
1047impl<const MAX_COUNT: usize> SuccessArgsNotificationInfoGet<MAX_COUNT> {
1048 const MORE_PENDING_NOTIFICATIONS_FLAG: u64 = 1 << 0;
1049 const LIST_COUNT_SHIFT: usize = 7;
1050 const LIST_COUNT_MASK: u64 = 0x1f;
1051 const ID_COUNT_SHIFT: usize = 12;
1052 const ID_COUNT_MASK: u64 = 0x03;
1053 const ID_COUNT_BITS: usize = 2;
1054
1055 pub fn add_list(&mut self, endpoint: u16, vcpu_ids: &[u16]) -> Result<(), Error> {
1056 if self.list_count >= MAX_COUNT || vcpu_ids.len() > Self::ID_COUNT_MASK as usize {
1057 return Err(Error::InvalidNotificationCount);
1058 }
1059
1060 // Each list contains at least one ID: the partition ID, followed by vCPU IDs. The number
1061 // of vCPU IDs is recorded in `id_counts`.
1062 let mut current_id_index = self.list_count + self.id_counts.iter().sum::<u8>() as usize;
1063 if current_id_index + 1 + vcpu_ids.len() > MAX_COUNT {
1064 // The new list does not fit into the available space for IDs.
1065 return Err(Error::InvalidNotificationCount);
1066 }
1067
1068 self.id_counts[self.list_count] = vcpu_ids.len() as u8;
1069 self.list_count += 1;
1070
1071 // The first ID is the endpoint ID.
1072 self.ids[current_id_index] = endpoint;
1073 current_id_index += 1;
1074
1075 // Insert the vCPU IDs.
1076 self.ids[current_id_index..current_id_index + vcpu_ids.len()].copy_from_slice(vcpu_ids);
1077
1078 Ok(())
1079 }
1080
1081 pub fn iter(&self) -> NotificationInfoGetIterator<'_> {
1082 NotificationInfoGetIterator {
1083 list_index: 0,
1084 id_index: 0,
1085 id_count: &self.id_counts[0..self.list_count],
1086 ids: &self.ids,
1087 }
1088 }
1089
1090 /// Pack flags field and IDs.
1091 fn pack(self) -> (u64, [u16; MAX_COUNT]) {
1092 let mut flags = if self.more_pending_notifications {
1093 Self::MORE_PENDING_NOTIFICATIONS_FLAG
1094 } else {
1095 0
1096 };
1097
1098 flags |= (self.list_count as u64) << Self::LIST_COUNT_SHIFT;
1099 for (count, shift) in self.id_counts.iter().take(self.list_count).zip(
1100 (Self::ID_COUNT_SHIFT..Self::ID_COUNT_SHIFT + Self::ID_COUNT_BITS * MAX_COUNT)
1101 .step_by(Self::ID_COUNT_BITS),
1102 ) {
1103 flags |= u64::from(*count) << shift;
1104 }
1105
1106 (flags, self.ids)
1107 }
1108
1109 /// Unpack flags field and IDs.
1110 fn unpack(flags: u64, ids: [u16; MAX_COUNT]) -> Result<Self, Error> {
1111 let count_of_lists = ((flags >> Self::LIST_COUNT_SHIFT) & Self::LIST_COUNT_MASK) as usize;
1112
1113 if count_of_lists > MAX_COUNT {
1114 return Err(Error::InvalidNotificationCount);
1115 }
1116
1117 let mut count_of_ids = [0; MAX_COUNT];
1118 let mut count_of_ids_bits = flags >> Self::ID_COUNT_SHIFT;
1119
1120 for id in count_of_ids.iter_mut().take(count_of_lists) {
1121 *id = (count_of_ids_bits & Self::ID_COUNT_MASK) as u8;
1122 count_of_ids_bits >>= Self::ID_COUNT_BITS;
1123 }
1124
Imre Kis7846c9f2025-04-15 09:45:00 +02001125 let id_field_count = count_of_lists + count_of_ids.iter().sum::<u8>() as usize;
1126 if id_field_count > MAX_COUNT {
1127 return Err(Error::InvalidNotificationCount);
1128 }
1129
Imre Kis787c5002025-04-10 14:25:51 +02001130 Ok(Self {
1131 more_pending_notifications: (flags & Self::MORE_PENDING_NOTIFICATIONS_FLAG) != 0,
1132 list_count: count_of_lists,
1133 id_counts: count_of_ids,
1134 ids,
1135 })
1136 }
1137}
1138
1139/// `FFA_NOTIFICATION_INFO_GET_32` specific success argument structure.
1140pub type SuccessArgsNotificationInfoGet32 = SuccessArgsNotificationInfoGet<10>;
1141
1142impl From<SuccessArgsNotificationInfoGet32> for SuccessArgs {
1143 fn from(value: SuccessArgsNotificationInfoGet32) -> Self {
1144 let (flags, ids) = value.pack();
1145 let id_regs: [u32; 5] = transmute!(ids);
1146
1147 let mut args = [0; 6];
1148 args[0] = flags as u32;
1149 args[1..6].copy_from_slice(&id_regs);
1150
1151 SuccessArgs::Args32(args)
1152 }
1153}
1154
1155impl TryFrom<SuccessArgs> for SuccessArgsNotificationInfoGet32 {
1156 type Error = Error;
1157
1158 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
1159 let args = value.try_get_args32()?;
1160 let flags = args[0].into();
1161 let id_regs: [u32; 5] = args[1..6].try_into().unwrap();
1162 Self::unpack(flags, transmute!(id_regs))
1163 }
1164}
1165
1166/// `FFA_NOTIFICATION_INFO_GET_64` specific success argument structure.
1167pub type SuccessArgsNotificationInfoGet64 = SuccessArgsNotificationInfoGet<20>;
1168
1169impl From<SuccessArgsNotificationInfoGet64> for SuccessArgs {
1170 fn from(value: SuccessArgsNotificationInfoGet64) -> Self {
1171 let (flags, ids) = value.pack();
1172 let id_regs: [u64; 5] = transmute!(ids);
1173
1174 let mut args = [0; 6];
1175 args[0] = flags;
1176 args[1..6].copy_from_slice(&id_regs);
1177
1178 SuccessArgs::Args64(args)
1179 }
1180}
1181
1182impl TryFrom<SuccessArgs> for SuccessArgsNotificationInfoGet64 {
1183 type Error = Error;
1184
1185 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
1186 let args = value.try_get_args64()?;
1187 let flags = args[0];
1188 let id_regs: [u64; 5] = args[1..6].try_into().unwrap();
1189 Self::unpack(flags, transmute!(id_regs))
1190 }
1191}
1192
Imre Kis68389c72025-06-16 12:42:49 +02001193/// Iterator implementation for parsing the (partition ID, vCPU ID list) pairs of the `FFA_SUCCESS`
1194/// of an `FFA_NOTIFICATION_INFO_GET` call.
Imre Kis787c5002025-04-10 14:25:51 +02001195pub struct NotificationInfoGetIterator<'a> {
1196 list_index: usize,
1197 id_index: usize,
1198 id_count: &'a [u8],
1199 ids: &'a [u16],
1200}
1201
1202impl<'a> Iterator for NotificationInfoGetIterator<'a> {
1203 type Item = (u16, &'a [u16]);
1204
1205 fn next(&mut self) -> Option<Self::Item> {
1206 if self.list_index < self.id_count.len() {
1207 let partition_id = self.ids[self.id_index];
1208 let id_range =
1209 (self.id_index + 1)..=(self.id_index + self.id_count[self.list_index] as usize);
1210
1211 self.id_index += 1 + self.id_count[self.list_index] as usize;
1212 self.list_index += 1;
1213
1214 Some((partition_id, &self.ids[id_range]))
1215 } else {
1216 None
1217 }
1218 }
1219}
1220
Tomás Gonzálezf268e322025-03-05 11:18:11 +00001221/// FF-A "message types", the terminology used by the spec is "interfaces".
1222///
1223/// The interfaces are used by FF-A components for communication at an FF-A instance. The spec also
1224/// describes the valid FF-A instances and conduits for each interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +01001225#[derive(Debug, Eq, PartialEq, Clone, Copy)]
1226pub enum Interface {
1227 Error {
1228 target_info: TargetInfo,
1229 error_code: FfaError,
Balint Dobszayb727aab2025-04-07 10:24:59 +02001230 error_arg: u32,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001231 },
1232 Success {
Imre Kise521a282025-06-13 13:29:24 +02001233 target_info: TargetInfo,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001234 args: SuccessArgs,
1235 },
1236 Interrupt {
1237 target_info: TargetInfo,
1238 interrupt_id: u32,
1239 },
1240 Version {
1241 input_version: Version,
1242 },
1243 VersionOut {
1244 output_version: Version,
1245 },
1246 Features {
1247 feat_id: Feature,
1248 input_properties: u32,
1249 },
1250 RxAcquire {
1251 vm_id: u16,
1252 },
1253 RxRelease {
1254 vm_id: u16,
1255 },
1256 RxTxMap {
1257 addr: RxTxAddr,
1258 page_cnt: u32,
1259 },
1260 RxTxUnmap {
1261 id: u16,
1262 },
1263 PartitionInfoGet {
1264 uuid: Uuid,
Imre Kise295adb2025-04-10 13:26:28 +02001265 flags: PartitionInfoGetFlags,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001266 },
Tomás González0a058bc2025-03-11 11:20:55 +00001267 PartitionInfoGetRegs {
1268 uuid: Uuid,
1269 start_index: u16,
1270 info_tag: u16,
1271 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001272 IdGet,
1273 SpmIdGet,
Tomás González092202a2025-03-05 11:56:45 +00001274 MsgWait {
1275 flags: Option<MsgWaitFlags>,
1276 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001277 Yield,
1278 Run {
1279 target_info: TargetInfo,
1280 },
1281 NormalWorldResume,
Tomás González17b92442025-03-10 16:45:04 +00001282 SecondaryEpRegister {
1283 entrypoint: SecondaryEpRegisterAddr,
1284 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001285 MsgSend2 {
1286 sender_vm_id: u16,
Imre Kisa2fd69b2025-06-13 13:39:47 +02001287 flags: MsgSend2Flags,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001288 },
1289 MsgSendDirectReq {
1290 src_id: u16,
1291 dst_id: u16,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001292 args: DirectMsgArgs,
1293 },
1294 MsgSendDirectResp {
1295 src_id: u16,
1296 dst_id: u16,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001297 args: DirectMsgArgs,
1298 },
Balint Dobszayde0dc802025-02-28 14:16:52 +01001299 MsgSendDirectReq2 {
1300 src_id: u16,
1301 dst_id: u16,
1302 uuid: Uuid,
1303 args: DirectMsg2Args,
1304 },
1305 MsgSendDirectResp2 {
1306 src_id: u16,
1307 dst_id: u16,
1308 args: DirectMsg2Args,
1309 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001310 MemDonate {
1311 total_len: u32,
1312 frag_len: u32,
1313 buf: Option<MemOpBuf>,
1314 },
1315 MemLend {
1316 total_len: u32,
1317 frag_len: u32,
1318 buf: Option<MemOpBuf>,
1319 },
1320 MemShare {
1321 total_len: u32,
1322 frag_len: u32,
1323 buf: Option<MemOpBuf>,
1324 },
1325 MemRetrieveReq {
1326 total_len: u32,
1327 frag_len: u32,
1328 buf: Option<MemOpBuf>,
1329 },
1330 MemRetrieveResp {
1331 total_len: u32,
1332 frag_len: u32,
1333 },
1334 MemRelinquish,
1335 MemReclaim {
1336 handle: memory_management::Handle,
Imre Kis356395d2025-06-13 13:49:06 +02001337 flags: memory_management::MemReclaimFlags,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001338 },
1339 MemPermGet {
1340 addr: MemAddr,
Balint Dobszayde0dc802025-02-28 14:16:52 +01001341 page_cnt: Option<u32>,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001342 },
1343 MemPermSet {
1344 addr: MemAddr,
1345 page_cnt: u32,
Imre Kisdcb7df22025-06-06 15:24:40 +02001346 mem_perm: memory_management::MemPermissionsGetSet,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001347 },
1348 ConsoleLog {
Imre Kis189f18c2025-05-26 19:33:05 +02001349 chars: ConsoleLogChars,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001350 },
Tomás González7ffb6132025-04-03 12:28:58 +01001351 NotificationBitmapCreate {
1352 vm_id: u16,
1353 vcpu_cnt: u32,
1354 },
1355 NotificationBitmapDestroy {
1356 vm_id: u16,
1357 },
1358 NotificationBind {
1359 sender_id: u16,
1360 receiver_id: u16,
1361 flags: NotificationBindFlags,
1362 bitmap: u64,
1363 },
Imre Kis3571f2c2025-05-26 19:29:23 +02001364 NotificationUnbind {
Tomás González7ffb6132025-04-03 12:28:58 +01001365 sender_id: u16,
1366 receiver_id: u16,
1367 bitmap: u64,
1368 },
1369 NotificationSet {
1370 sender_id: u16,
1371 receiver_id: u16,
1372 flags: NotificationSetFlags,
1373 bitmap: u64,
1374 },
1375 NotificationGet {
1376 vcpu_id: u16,
1377 endpoint_id: u16,
1378 flags: NotificationGetFlags,
1379 },
1380 NotificationInfoGet {
1381 is_32bit: bool,
1382 },
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01001383 El3IntrHandle,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001384}
1385
Balint Dobszayde0dc802025-02-28 14:16:52 +01001386impl Interface {
1387 /// Returns the function ID for the call, if it has one.
1388 pub fn function_id(&self) -> Option<FuncId> {
1389 match self {
1390 Interface::Error { .. } => Some(FuncId::Error),
1391 Interface::Success { args, .. } => match args {
Imre Kis54773b62025-04-10 13:47:39 +02001392 SuccessArgs::Args32(..) => Some(FuncId::Success32),
1393 SuccessArgs::Args64(..) | SuccessArgs::Args64_2(..) => Some(FuncId::Success64),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001394 },
1395 Interface::Interrupt { .. } => Some(FuncId::Interrupt),
1396 Interface::Version { .. } => Some(FuncId::Version),
1397 Interface::VersionOut { .. } => None,
1398 Interface::Features { .. } => Some(FuncId::Features),
1399 Interface::RxAcquire { .. } => Some(FuncId::RxAcquire),
1400 Interface::RxRelease { .. } => Some(FuncId::RxRelease),
1401 Interface::RxTxMap { addr, .. } => match addr {
1402 RxTxAddr::Addr32 { .. } => Some(FuncId::RxTxMap32),
1403 RxTxAddr::Addr64 { .. } => Some(FuncId::RxTxMap64),
1404 },
1405 Interface::RxTxUnmap { .. } => Some(FuncId::RxTxUnmap),
1406 Interface::PartitionInfoGet { .. } => Some(FuncId::PartitionInfoGet),
Tomás González0a058bc2025-03-11 11:20:55 +00001407 Interface::PartitionInfoGetRegs { .. } => Some(FuncId::PartitionInfoGetRegs),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001408 Interface::IdGet => Some(FuncId::IdGet),
1409 Interface::SpmIdGet => Some(FuncId::SpmIdGet),
Tomás González092202a2025-03-05 11:56:45 +00001410 Interface::MsgWait { .. } => Some(FuncId::MsgWait),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001411 Interface::Yield => Some(FuncId::Yield),
1412 Interface::Run { .. } => Some(FuncId::Run),
1413 Interface::NormalWorldResume => Some(FuncId::NormalWorldResume),
Tomás González17b92442025-03-10 16:45:04 +00001414 Interface::SecondaryEpRegister { entrypoint } => match entrypoint {
1415 SecondaryEpRegisterAddr::Addr32 { .. } => Some(FuncId::SecondaryEpRegister32),
1416 SecondaryEpRegisterAddr::Addr64 { .. } => Some(FuncId::SecondaryEpRegister64),
1417 },
Balint Dobszayde0dc802025-02-28 14:16:52 +01001418 Interface::MsgSend2 { .. } => Some(FuncId::MsgSend2),
1419 Interface::MsgSendDirectReq { args, .. } => match args {
1420 DirectMsgArgs::Args32(_) => Some(FuncId::MsgSendDirectReq32),
1421 DirectMsgArgs::Args64(_) => Some(FuncId::MsgSendDirectReq64),
Tomás González4d5b0ba2025-03-03 17:15:55 +00001422 DirectMsgArgs::VersionReq { .. } => Some(FuncId::MsgSendDirectReq32),
1423 DirectMsgArgs::PowerPsciReq32 { .. } => Some(FuncId::MsgSendDirectReq32),
1424 DirectMsgArgs::PowerPsciReq64 { .. } => Some(FuncId::MsgSendDirectReq64),
1425 DirectMsgArgs::PowerWarmBootReq { .. } => Some(FuncId::MsgSendDirectReq32),
1426 DirectMsgArgs::VmCreated { .. } => Some(FuncId::MsgSendDirectReq32),
1427 DirectMsgArgs::VmDestructed { .. } => Some(FuncId::MsgSendDirectReq32),
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001428 _ => panic!("Invalid direct request arguments: {:#?}", args),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001429 },
1430 Interface::MsgSendDirectResp { args, .. } => match args {
1431 DirectMsgArgs::Args32(_) => Some(FuncId::MsgSendDirectResp32),
1432 DirectMsgArgs::Args64(_) => Some(FuncId::MsgSendDirectResp64),
Tomás González4d5b0ba2025-03-03 17:15:55 +00001433 DirectMsgArgs::VersionResp { .. } => Some(FuncId::MsgSendDirectResp32),
1434 DirectMsgArgs::PowerPsciResp { .. } => Some(FuncId::MsgSendDirectResp32),
1435 DirectMsgArgs::VmCreatedAck { .. } => Some(FuncId::MsgSendDirectResp32),
1436 DirectMsgArgs::VmDestructedAck { .. } => Some(FuncId::MsgSendDirectResp32),
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001437 _ => panic!("Invalid direct response arguments: {:#?}", args),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001438 },
1439 Interface::MsgSendDirectReq2 { .. } => Some(FuncId::MsgSendDirectReq64_2),
1440 Interface::MsgSendDirectResp2 { .. } => Some(FuncId::MsgSendDirectResp64_2),
1441 Interface::MemDonate { buf, .. } => match buf {
1442 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemDonate64),
1443 _ => Some(FuncId::MemDonate32),
1444 },
1445 Interface::MemLend { buf, .. } => match buf {
1446 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemLend64),
1447 _ => Some(FuncId::MemLend32),
1448 },
1449 Interface::MemShare { buf, .. } => match buf {
1450 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemShare64),
1451 _ => Some(FuncId::MemShare32),
1452 },
1453 Interface::MemRetrieveReq { buf, .. } => match buf {
1454 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemRetrieveReq64),
1455 _ => Some(FuncId::MemRetrieveReq32),
1456 },
1457 Interface::MemRetrieveResp { .. } => Some(FuncId::MemRetrieveResp),
1458 Interface::MemRelinquish => Some(FuncId::MemRelinquish),
1459 Interface::MemReclaim { .. } => Some(FuncId::MemReclaim),
1460 Interface::MemPermGet { addr, .. } => match addr {
1461 MemAddr::Addr32(_) => Some(FuncId::MemPermGet32),
1462 MemAddr::Addr64(_) => Some(FuncId::MemPermGet64),
1463 },
1464 Interface::MemPermSet { addr, .. } => match addr {
1465 MemAddr::Addr32(_) => Some(FuncId::MemPermSet32),
1466 MemAddr::Addr64(_) => Some(FuncId::MemPermSet64),
1467 },
Imre Kis189f18c2025-05-26 19:33:05 +02001468 Interface::ConsoleLog { chars, .. } => match chars {
1469 ConsoleLogChars::Chars32(_) => Some(FuncId::ConsoleLog32),
1470 ConsoleLogChars::Chars64(_) => Some(FuncId::ConsoleLog64),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001471 },
Tomás González7ffb6132025-04-03 12:28:58 +01001472 Interface::NotificationBitmapCreate { .. } => Some(FuncId::NotificationBitmapCreate),
1473 Interface::NotificationBitmapDestroy { .. } => Some(FuncId::NotificationBitmapDestroy),
1474 Interface::NotificationBind { .. } => Some(FuncId::NotificationBind),
Imre Kis3571f2c2025-05-26 19:29:23 +02001475 Interface::NotificationUnbind { .. } => Some(FuncId::NotificationUnbind),
Tomás González7ffb6132025-04-03 12:28:58 +01001476 Interface::NotificationSet { .. } => Some(FuncId::NotificationSet),
1477 Interface::NotificationGet { .. } => Some(FuncId::NotificationGet),
1478 Interface::NotificationInfoGet { is_32bit } => match is_32bit {
1479 true => Some(FuncId::NotificationInfoGet32),
1480 false => Some(FuncId::NotificationInfoGet64),
1481 },
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01001482 Interface::El3IntrHandle => Some(FuncId::El3IntrHandle),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001483 }
1484 }
Balint Dobszay3aad9572025-01-17 16:54:11 +01001485
Balint Dobszayde0dc802025-02-28 14:16:52 +01001486 /// Returns true if this is a 32-bit call, or false if it is a 64-bit call.
1487 pub fn is_32bit(&self) -> bool {
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001488 if matches!(self, Self::VersionOut { .. }) {
1489 return true;
1490 }
1491
Balint Dobszayde0dc802025-02-28 14:16:52 +01001492 self.function_id().unwrap().is_32bit()
1493 }
1494
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001495 /// Returns the FF-A version that has introduced the function ID.
1496 pub fn minimum_ffa_version(&self) -> Version {
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001497 if matches!(self, Self::VersionOut { .. }) {
1498 return Version(1, 0);
1499 }
1500
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001501 self.function_id().unwrap().minimum_ffa_version()
1502 }
1503
Balint Dobszayde0dc802025-02-28 14:16:52 +01001504 /// Parse interface from register contents. The caller must ensure that the `regs` argument has
1505 /// the correct length: 8 registers for FF-A v1.1 and lower, 18 registers for v1.2 and higher.
1506 pub fn from_regs(version: Version, regs: &[u64]) -> Result<Self, Error> {
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001507 let func_id = FuncId::try_from(regs[0] as u32)?;
1508 if version < func_id.minimum_ffa_version() {
1509 return Err(Error::InvalidVersionForFunctionId(version, func_id));
1510 }
1511
Balint Dobszayde0dc802025-02-28 14:16:52 +01001512 let reg_cnt = regs.len();
1513
1514 let msg = match reg_cnt {
1515 8 => {
1516 assert!(version <= Version(1, 1));
1517 Interface::unpack_regs8(version, regs.try_into().unwrap())?
1518 }
1519 18 => {
1520 assert!(version >= Version(1, 2));
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001521 match func_id {
Balint Dobszayde0dc802025-02-28 14:16:52 +01001522 FuncId::ConsoleLog64
1523 | FuncId::Success64
1524 | FuncId::MsgSendDirectReq64_2
Tomás González0a058bc2025-03-11 11:20:55 +00001525 | FuncId::MsgSendDirectResp64_2
1526 | FuncId::PartitionInfoGetRegs => {
Balint Dobszayde0dc802025-02-28 14:16:52 +01001527 Interface::unpack_regs18(version, regs.try_into().unwrap())?
1528 }
1529 _ => Interface::unpack_regs8(version, regs[..8].try_into().unwrap())?,
1530 }
1531 }
1532 _ => panic!(
1533 "Invalid number of registers ({}) for FF-A version {}",
1534 reg_cnt, version
1535 ),
1536 };
1537
1538 Ok(msg)
1539 }
1540
1541 fn unpack_regs8(version: Version, regs: &[u64; 8]) -> Result<Self, Error> {
Balint Dobszay3aad9572025-01-17 16:54:11 +01001542 let fid = FuncId::try_from(regs[0] as u32)?;
1543
1544 let msg = match fid {
1545 FuncId::Error => Self::Error {
1546 target_info: (regs[1] as u32).into(),
1547 error_code: FfaError::try_from(regs[2] as i32)?,
Balint Dobszayb727aab2025-04-07 10:24:59 +02001548 error_arg: regs[3] as u32,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001549 },
1550 FuncId::Success32 => Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02001551 target_info: (regs[1] as u32).into(),
Imre Kis54773b62025-04-10 13:47:39 +02001552 args: SuccessArgs::Args32([
Balint Dobszay3aad9572025-01-17 16:54:11 +01001553 regs[2] as u32,
1554 regs[3] as u32,
1555 regs[4] as u32,
1556 regs[5] as u32,
1557 regs[6] as u32,
1558 regs[7] as u32,
1559 ]),
1560 },
1561 FuncId::Success64 => Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02001562 target_info: (regs[1] as u32).into(),
Imre Kis54773b62025-04-10 13:47:39 +02001563 args: SuccessArgs::Args64([regs[2], regs[3], regs[4], regs[5], regs[6], regs[7]]),
Balint Dobszay3aad9572025-01-17 16:54:11 +01001564 },
1565 FuncId::Interrupt => Self::Interrupt {
1566 target_info: (regs[1] as u32).into(),
1567 interrupt_id: regs[2] as u32,
1568 },
1569 FuncId::Version => Self::Version {
Tomás González83146af2025-03-04 11:32:41 +00001570 input_version: (regs[1] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001571 },
1572 FuncId::Features => Self::Features {
Balint Dobszayc31e0b92025-03-03 20:16:56 +01001573 feat_id: (regs[1] as u32).into(),
Balint Dobszay3aad9572025-01-17 16:54:11 +01001574 input_properties: regs[2] as u32,
1575 },
1576 FuncId::RxAcquire => Self::RxAcquire {
1577 vm_id: regs[1] as u16,
1578 },
1579 FuncId::RxRelease => Self::RxRelease {
1580 vm_id: regs[1] as u16,
1581 },
1582 FuncId::RxTxMap32 => {
1583 let addr = RxTxAddr::Addr32 {
1584 rx: regs[2] as u32,
1585 tx: regs[1] as u32,
1586 };
1587 let page_cnt = regs[3] as u32;
1588
1589 Self::RxTxMap { addr, page_cnt }
1590 }
1591 FuncId::RxTxMap64 => {
1592 let addr = RxTxAddr::Addr64 {
1593 rx: regs[2],
1594 tx: regs[1],
1595 };
1596 let page_cnt = regs[3] as u32;
1597
1598 Self::RxTxMap { addr, page_cnt }
1599 }
1600 FuncId::RxTxUnmap => Self::RxTxUnmap { id: regs[1] as u16 },
1601 FuncId::PartitionInfoGet => {
1602 let uuid_words = [
1603 regs[1] as u32,
1604 regs[2] as u32,
1605 regs[3] as u32,
1606 regs[4] as u32,
1607 ];
1608 let mut bytes: [u8; 16] = [0; 16];
1609 for (i, b) in uuid_words.iter().flat_map(|w| w.to_le_bytes()).enumerate() {
1610 bytes[i] = b;
1611 }
1612 Self::PartitionInfoGet {
1613 uuid: Uuid::from_bytes(bytes),
Imre Kise295adb2025-04-10 13:26:28 +02001614 flags: PartitionInfoGetFlags::try_from(regs[5] as u32)?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001615 }
1616 }
1617 FuncId::IdGet => Self::IdGet,
1618 FuncId::SpmIdGet => Self::SpmIdGet,
Tomás González092202a2025-03-05 11:56:45 +00001619 FuncId::MsgWait => Self::MsgWait {
1620 flags: if version >= Version(1, 2) {
1621 Some(MsgWaitFlags::try_from(regs[2] as u32)?)
1622 } else {
1623 None
1624 },
1625 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001626 FuncId::Yield => Self::Yield,
1627 FuncId::Run => Self::Run {
1628 target_info: (regs[1] as u32).into(),
1629 },
1630 FuncId::NormalWorldResume => Self::NormalWorldResume,
Tomás González17b92442025-03-10 16:45:04 +00001631 FuncId::SecondaryEpRegister32 => Self::SecondaryEpRegister {
1632 entrypoint: SecondaryEpRegisterAddr::Addr32(regs[1] as u32),
1633 },
1634 FuncId::SecondaryEpRegister64 => Self::SecondaryEpRegister {
1635 entrypoint: SecondaryEpRegisterAddr::Addr64(regs[1]),
1636 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001637 FuncId::MsgSend2 => Self::MsgSend2 {
1638 sender_vm_id: regs[1] as u16,
Imre Kisa2fd69b2025-06-13 13:39:47 +02001639 flags: (regs[2] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001640 },
1641 FuncId::MsgSendDirectReq32 => Self::MsgSendDirectReq {
1642 src_id: (regs[1] >> 16) as u16,
1643 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001644 args: if (regs[2] as u32 & DirectMsgArgs::FWK_MSG_BITS) != 0 {
1645 match regs[2] as u32 {
1646 DirectMsgArgs::VERSION_REQ => DirectMsgArgs::VersionReq {
1647 version: Version::try_from(regs[3] as u32)?,
1648 },
1649 DirectMsgArgs::POWER_PSCI_REQ => DirectMsgArgs::PowerPsciReq32 {
Tomás González67f92c72025-03-20 16:50:42 +00001650 params: [
1651 regs[3] as u32,
1652 regs[4] as u32,
1653 regs[5] as u32,
1654 regs[6] as u32,
1655 ],
Tomás González4d5b0ba2025-03-03 17:15:55 +00001656 },
1657 DirectMsgArgs::POWER_WARM_BOOT_REQ => DirectMsgArgs::PowerWarmBootReq {
1658 boot_type: WarmBootType::try_from(regs[3] as u32)?,
1659 },
1660 DirectMsgArgs::VM_CREATED => DirectMsgArgs::VmCreated {
1661 handle: memory_management::Handle::from([
1662 regs[3] as u32,
1663 regs[4] as u32,
1664 ]),
1665 vm_id: regs[5] as u16,
1666 },
1667 DirectMsgArgs::VM_DESTRUCTED => DirectMsgArgs::VmDestructed {
1668 handle: memory_management::Handle::from([
1669 regs[3] as u32,
1670 regs[4] as u32,
1671 ]),
1672 vm_id: regs[5] as u16,
1673 },
1674 _ => return Err(Error::UnrecognisedFwkMsg(regs[2] as u32)),
1675 }
1676 } else {
1677 DirectMsgArgs::Args32([
1678 regs[3] as u32,
1679 regs[4] as u32,
1680 regs[5] as u32,
1681 regs[6] as u32,
1682 regs[7] as u32,
1683 ])
1684 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001685 },
1686 FuncId::MsgSendDirectReq64 => Self::MsgSendDirectReq {
1687 src_id: (regs[1] >> 16) as u16,
1688 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001689 args: if (regs[2] & DirectMsgArgs::FWK_MSG_BITS as u64) != 0 {
1690 match regs[2] as u32 {
1691 DirectMsgArgs::POWER_PSCI_REQ => DirectMsgArgs::PowerPsciReq64 {
Tomás González67f92c72025-03-20 16:50:42 +00001692 params: [regs[3], regs[4], regs[5], regs[6]],
Tomás González4d5b0ba2025-03-03 17:15:55 +00001693 },
1694 _ => return Err(Error::UnrecognisedFwkMsg(regs[2] as u32)),
1695 }
1696 } else {
1697 DirectMsgArgs::Args64([regs[3], regs[4], regs[5], regs[6], regs[7]])
1698 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001699 },
1700 FuncId::MsgSendDirectResp32 => Self::MsgSendDirectResp {
1701 src_id: (regs[1] >> 16) as u16,
1702 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001703 args: if (regs[2] as u32 & DirectMsgArgs::FWK_MSG_BITS) != 0 {
1704 match regs[2] as u32 {
1705 DirectMsgArgs::VERSION_RESP => {
1706 if regs[3] as i32 == FfaError::NotSupported.into() {
1707 DirectMsgArgs::VersionResp { version: None }
1708 } else {
1709 DirectMsgArgs::VersionResp {
1710 version: Some(Version::try_from(regs[3] as u32)?),
1711 }
1712 }
1713 }
1714 DirectMsgArgs::POWER_PSCI_RESP => DirectMsgArgs::PowerPsciResp {
1715 psci_status: regs[3] as i32,
1716 },
1717 DirectMsgArgs::VM_CREATED_ACK => DirectMsgArgs::VmCreatedAck {
1718 sp_status: (regs[3] as i32).try_into()?,
1719 },
1720 DirectMsgArgs::VM_DESTRUCTED_ACK => DirectMsgArgs::VmDestructedAck {
1721 sp_status: (regs[3] as i32).try_into()?,
1722 },
1723 _ => return Err(Error::UnrecognisedFwkMsg(regs[2] as u32)),
1724 }
1725 } else {
1726 DirectMsgArgs::Args32([
1727 regs[3] as u32,
1728 regs[4] as u32,
1729 regs[5] as u32,
1730 regs[6] as u32,
1731 regs[7] as u32,
1732 ])
1733 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001734 },
1735 FuncId::MsgSendDirectResp64 => Self::MsgSendDirectResp {
1736 src_id: (regs[1] >> 16) as u16,
1737 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001738 args: if (regs[2] & DirectMsgArgs::FWK_MSG_BITS as u64) != 0 {
1739 return Err(Error::UnrecognisedFwkMsg(regs[2] as u32));
1740 } else {
1741 DirectMsgArgs::Args64([regs[3], regs[4], regs[5], regs[6], regs[7]])
1742 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001743 },
1744 FuncId::MemDonate32 => Self::MemDonate {
1745 total_len: regs[1] as u32,
1746 frag_len: regs[2] as u32,
1747 buf: if regs[3] != 0 && regs[4] != 0 {
1748 Some(MemOpBuf::Buf32 {
1749 addr: regs[3] as u32,
1750 page_cnt: regs[4] as u32,
1751 })
1752 } else {
1753 None
1754 },
1755 },
1756 FuncId::MemDonate64 => Self::MemDonate {
1757 total_len: regs[1] as u32,
1758 frag_len: regs[2] as u32,
1759 buf: if regs[3] != 0 && regs[4] != 0 {
1760 Some(MemOpBuf::Buf64 {
1761 addr: regs[3],
1762 page_cnt: regs[4] as u32,
1763 })
1764 } else {
1765 None
1766 },
1767 },
1768 FuncId::MemLend32 => Self::MemLend {
1769 total_len: regs[1] as u32,
1770 frag_len: regs[2] as u32,
1771 buf: if regs[3] != 0 && regs[4] != 0 {
1772 Some(MemOpBuf::Buf32 {
1773 addr: regs[3] as u32,
1774 page_cnt: regs[4] as u32,
1775 })
1776 } else {
1777 None
1778 },
1779 },
1780 FuncId::MemLend64 => Self::MemLend {
1781 total_len: regs[1] as u32,
1782 frag_len: regs[2] as u32,
1783 buf: if regs[3] != 0 && regs[4] != 0 {
1784 Some(MemOpBuf::Buf64 {
1785 addr: regs[3],
1786 page_cnt: regs[4] as u32,
1787 })
1788 } else {
1789 None
1790 },
1791 },
1792 FuncId::MemShare32 => Self::MemShare {
1793 total_len: regs[1] as u32,
1794 frag_len: regs[2] as u32,
1795 buf: if regs[3] != 0 && regs[4] != 0 {
1796 Some(MemOpBuf::Buf32 {
1797 addr: regs[3] as u32,
1798 page_cnt: regs[4] as u32,
1799 })
1800 } else {
1801 None
1802 },
1803 },
1804 FuncId::MemShare64 => Self::MemShare {
1805 total_len: regs[1] as u32,
1806 frag_len: regs[2] as u32,
1807 buf: if regs[3] != 0 && regs[4] != 0 {
1808 Some(MemOpBuf::Buf64 {
1809 addr: regs[3],
1810 page_cnt: regs[4] as u32,
1811 })
1812 } else {
1813 None
1814 },
1815 },
1816 FuncId::MemRetrieveReq32 => Self::MemRetrieveReq {
1817 total_len: regs[1] as u32,
1818 frag_len: regs[2] as u32,
1819 buf: if regs[3] != 0 && regs[4] != 0 {
1820 Some(MemOpBuf::Buf32 {
1821 addr: regs[3] as u32,
1822 page_cnt: regs[4] as u32,
1823 })
1824 } else {
1825 None
1826 },
1827 },
1828 FuncId::MemRetrieveReq64 => Self::MemRetrieveReq {
1829 total_len: regs[1] as u32,
1830 frag_len: regs[2] as u32,
1831 buf: if regs[3] != 0 && regs[4] != 0 {
1832 Some(MemOpBuf::Buf64 {
1833 addr: regs[3],
1834 page_cnt: regs[4] as u32,
1835 })
1836 } else {
1837 None
1838 },
1839 },
1840 FuncId::MemRetrieveResp => Self::MemRetrieveResp {
1841 total_len: regs[1] as u32,
1842 frag_len: regs[2] as u32,
1843 },
1844 FuncId::MemRelinquish => Self::MemRelinquish,
1845 FuncId::MemReclaim => Self::MemReclaim {
1846 handle: memory_management::Handle::from([regs[1] as u32, regs[2] as u32]),
Imre Kis356395d2025-06-13 13:49:06 +02001847 flags: (regs[3] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001848 },
1849 FuncId::MemPermGet32 => Self::MemPermGet {
1850 addr: MemAddr::Addr32(regs[1] as u32),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001851 page_cnt: if version >= Version(1, 3) {
1852 Some(regs[2] as u32)
1853 } else {
1854 None
1855 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001856 },
1857 FuncId::MemPermGet64 => Self::MemPermGet {
1858 addr: MemAddr::Addr64(regs[1]),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001859 page_cnt: if version >= Version(1, 3) {
1860 Some(regs[2] as u32)
1861 } else {
1862 None
1863 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001864 },
1865 FuncId::MemPermSet32 => Self::MemPermSet {
1866 addr: MemAddr::Addr32(regs[1] as u32),
1867 page_cnt: regs[2] as u32,
Imre Kisdcb7df22025-06-06 15:24:40 +02001868 mem_perm: (regs[3] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001869 },
1870 FuncId::MemPermSet64 => Self::MemPermSet {
1871 addr: MemAddr::Addr64(regs[1]),
1872 page_cnt: regs[2] as u32,
Imre Kisdcb7df22025-06-06 15:24:40 +02001873 mem_perm: (regs[3] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001874 },
Imre Kis189f18c2025-05-26 19:33:05 +02001875 FuncId::ConsoleLog32 => {
1876 let char_cnt = regs[1] as u8;
1877 if char_cnt > ConsoleLogChars32::MAX_LENGTH {
1878 return Err(Error::InvalidCharacterCount(char_cnt));
1879 }
1880
1881 Self::ConsoleLog {
1882 chars: ConsoleLogChars::Chars32(ConsoleLogChars32 {
1883 char_cnt,
1884 char_lists: [
1885 regs[2] as u32,
1886 regs[3] as u32,
1887 regs[4] as u32,
1888 regs[5] as u32,
1889 regs[6] as u32,
1890 regs[7] as u32,
1891 ],
1892 }),
1893 }
1894 }
Tomás González7ffb6132025-04-03 12:28:58 +01001895 FuncId::NotificationBitmapCreate => {
1896 let tentative_vm_id = regs[1] as u32;
1897 if (tentative_vm_id >> 16) != 0 {
1898 return Err(Error::InvalidVmId(tentative_vm_id));
1899 }
1900 Self::NotificationBitmapCreate {
1901 vm_id: tentative_vm_id as u16,
1902 vcpu_cnt: regs[2] as u32,
1903 }
1904 }
1905 FuncId::NotificationBitmapDestroy => {
1906 let tentative_vm_id = regs[1] as u32;
1907 if (tentative_vm_id >> 16) != 0 {
1908 return Err(Error::InvalidVmId(tentative_vm_id));
1909 }
1910 Self::NotificationBitmapDestroy {
1911 vm_id: tentative_vm_id as u16,
1912 }
1913 }
1914 FuncId::NotificationBind => Self::NotificationBind {
1915 sender_id: (regs[1] >> 16) as u16,
1916 receiver_id: regs[1] as u16,
1917 flags: (regs[2] as u32).into(),
1918 bitmap: (regs[4] << 32) | (regs[3] & 0xffff_ffff),
1919 },
Imre Kis3571f2c2025-05-26 19:29:23 +02001920 FuncId::NotificationUnbind => Self::NotificationUnbind {
Tomás González7ffb6132025-04-03 12:28:58 +01001921 sender_id: (regs[1] >> 16) as u16,
1922 receiver_id: regs[1] as u16,
1923 bitmap: (regs[4] << 32) | (regs[3] & 0xffff_ffff),
1924 },
1925 FuncId::NotificationSet => Self::NotificationSet {
1926 sender_id: (regs[1] >> 16) as u16,
1927 receiver_id: regs[1] as u16,
1928 flags: (regs[2] as u32).try_into()?,
1929 bitmap: (regs[4] << 32) | (regs[3] & 0xffff_ffff),
1930 },
1931 FuncId::NotificationGet => Self::NotificationGet {
1932 vcpu_id: (regs[1] >> 16) as u16,
1933 endpoint_id: regs[1] as u16,
1934 flags: (regs[2] as u32).into(),
1935 },
1936 FuncId::NotificationInfoGet32 => Self::NotificationInfoGet { is_32bit: true },
1937 FuncId::NotificationInfoGet64 => Self::NotificationInfoGet { is_32bit: false },
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01001938 FuncId::El3IntrHandle => Self::El3IntrHandle,
Balint Dobszayde0dc802025-02-28 14:16:52 +01001939 _ => panic!("Invalid number of registers (8) for function {:#x?}", fid),
Balint Dobszay3aad9572025-01-17 16:54:11 +01001940 };
1941
1942 Ok(msg)
1943 }
Balint Dobszay3aad9572025-01-17 16:54:11 +01001944
Balint Dobszayde0dc802025-02-28 14:16:52 +01001945 fn unpack_regs18(version: Version, regs: &[u64; 18]) -> Result<Self, Error> {
1946 assert!(version >= Version(1, 2));
Balint Dobszay5bf492f2024-07-29 17:21:32 +02001947
Balint Dobszayde0dc802025-02-28 14:16:52 +01001948 let fid = FuncId::try_from(regs[0] as u32)?;
1949
1950 let msg = match fid {
1951 FuncId::Success64 => Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02001952 target_info: (regs[1] as u32).into(),
Imre Kis54773b62025-04-10 13:47:39 +02001953 args: SuccessArgs::Args64_2(regs[2..18].try_into().unwrap()),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001954 },
1955 FuncId::MsgSendDirectReq64_2 => Self::MsgSendDirectReq2 {
1956 src_id: (regs[1] >> 16) as u16,
1957 dst_id: regs[1] as u16,
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00001958 uuid: Uuid::from_u64_pair(regs[2].swap_bytes(), regs[3].swap_bytes()),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001959 args: DirectMsg2Args(regs[4..18].try_into().unwrap()),
1960 },
1961 FuncId::MsgSendDirectResp64_2 => Self::MsgSendDirectResp2 {
1962 src_id: (regs[1] >> 16) as u16,
1963 dst_id: regs[1] as u16,
1964 args: DirectMsg2Args(regs[4..18].try_into().unwrap()),
1965 },
Imre Kis189f18c2025-05-26 19:33:05 +02001966 FuncId::ConsoleLog64 => {
1967 let char_cnt = regs[1] as u8;
1968 if char_cnt > ConsoleLogChars64::MAX_LENGTH {
1969 return Err(Error::InvalidCharacterCount(char_cnt));
1970 }
1971
1972 Self::ConsoleLog {
1973 chars: ConsoleLogChars::Chars64(ConsoleLogChars64 {
1974 char_cnt,
1975 char_lists: regs[2..18].try_into().unwrap(),
1976 }),
1977 }
1978 }
Tomás González0a058bc2025-03-11 11:20:55 +00001979 FuncId::PartitionInfoGetRegs => {
1980 // Bits[15:0]: Start index
1981 let start_index = (regs[3] & 0xffff) as u16;
1982 let info_tag = ((regs[3] >> 16) & 0xffff) as u16;
1983 Self::PartitionInfoGetRegs {
1984 uuid: Uuid::from_u64_pair(regs[1].swap_bytes(), regs[2].swap_bytes()),
1985 start_index,
1986 info_tag: if start_index == 0 && info_tag != 0 {
1987 return Err(Error::InvalidInformationTag(info_tag));
1988 } else {
1989 info_tag
1990 },
1991 }
1992 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01001993 _ => panic!("Invalid number of registers (18) for function {:#x?}", fid),
1994 };
1995
1996 Ok(msg)
Balint Dobszay3aad9572025-01-17 16:54:11 +01001997 }
1998
Balint Dobszaya5846852025-02-26 15:38:53 +01001999 /// Create register contents for an interface.
Balint Dobszayde0dc802025-02-28 14:16:52 +01002000 pub fn to_regs(&self, version: Version, regs: &mut [u64]) {
Balint Dobszay82c71dd2025-04-15 10:16:44 +02002001 assert!(self.minimum_ffa_version() <= version);
2002
Balint Dobszayde0dc802025-02-28 14:16:52 +01002003 let reg_cnt = regs.len();
2004
2005 match reg_cnt {
2006 8 => {
2007 assert!(version <= Version(1, 1));
Balint Dobszay91bea9b2025-04-09 13:16:06 +02002008 regs.fill(0);
2009
Balint Dobszayde0dc802025-02-28 14:16:52 +01002010 self.pack_regs8(version, (&mut regs[..8]).try_into().unwrap());
2011 }
2012 18 => {
2013 assert!(version >= Version(1, 2));
Balint Dobszay91bea9b2025-04-09 13:16:06 +02002014 regs.fill(0);
Balint Dobszayde0dc802025-02-28 14:16:52 +01002015
2016 match self {
2017 Interface::ConsoleLog {
Imre Kis189f18c2025-05-26 19:33:05 +02002018 chars: ConsoleLogChars::Chars64(_),
Balint Dobszayde0dc802025-02-28 14:16:52 +01002019 ..
2020 }
2021 | Interface::Success {
Imre Kis54773b62025-04-10 13:47:39 +02002022 args: SuccessArgs::Args64_2(_),
Balint Dobszayde0dc802025-02-28 14:16:52 +01002023 ..
2024 }
2025 | Interface::MsgSendDirectReq2 { .. }
Tomás González0a058bc2025-03-11 11:20:55 +00002026 | Interface::MsgSendDirectResp2 { .. }
2027 | Interface::PartitionInfoGetRegs { .. } => {
Balint Dobszayde0dc802025-02-28 14:16:52 +01002028 self.pack_regs18(version, regs.try_into().unwrap());
2029 }
2030 _ => {
2031 self.pack_regs8(version, (&mut regs[..8]).try_into().unwrap());
2032 }
2033 }
2034 }
2035 _ => panic!("Invalid number of registers {}", reg_cnt),
2036 }
2037 }
2038
2039 fn pack_regs8(&self, version: Version, a: &mut [u64; 8]) {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002040 if let Some(function_id) = self.function_id() {
2041 a[0] = function_id as u64;
2042 }
2043
2044 match *self {
2045 Interface::Error {
2046 target_info,
2047 error_code,
Balint Dobszayb727aab2025-04-07 10:24:59 +02002048 error_arg,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002049 } => {
2050 a[1] = u32::from(target_info).into();
2051 a[2] = (error_code as u32).into();
Balint Dobszayb727aab2025-04-07 10:24:59 +02002052 a[3] = error_arg.into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002053 }
2054 Interface::Success { target_info, args } => {
Imre Kise521a282025-06-13 13:29:24 +02002055 a[1] = u32::from(target_info).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002056 match args {
Imre Kis54773b62025-04-10 13:47:39 +02002057 SuccessArgs::Args32(regs) => {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002058 a[2] = regs[0].into();
2059 a[3] = regs[1].into();
2060 a[4] = regs[2].into();
2061 a[5] = regs[3].into();
2062 a[6] = regs[4].into();
2063 a[7] = regs[5].into();
2064 }
Imre Kis54773b62025-04-10 13:47:39 +02002065 SuccessArgs::Args64(regs) => {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002066 a[2] = regs[0];
2067 a[3] = regs[1];
2068 a[4] = regs[2];
2069 a[5] = regs[3];
2070 a[6] = regs[4];
2071 a[7] = regs[5];
2072 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01002073 _ => panic!("{:#x?} requires 18 registers", args),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002074 }
2075 }
2076 Interface::Interrupt {
2077 target_info,
2078 interrupt_id,
2079 } => {
2080 a[1] = u32::from(target_info).into();
2081 a[2] = interrupt_id.into();
2082 }
2083 Interface::Version { input_version } => {
2084 a[1] = u32::from(input_version).into();
2085 }
2086 Interface::VersionOut { output_version } => {
2087 a[0] = u32::from(output_version).into();
2088 }
2089 Interface::Features {
2090 feat_id,
2091 input_properties,
2092 } => {
2093 a[1] = u32::from(feat_id).into();
2094 a[2] = input_properties.into();
2095 }
2096 Interface::RxAcquire { vm_id } => {
2097 a[1] = vm_id.into();
2098 }
2099 Interface::RxRelease { vm_id } => {
2100 a[1] = vm_id.into();
2101 }
2102 Interface::RxTxMap { addr, page_cnt } => {
2103 match addr {
2104 RxTxAddr::Addr32 { rx, tx } => {
2105 a[1] = tx.into();
2106 a[2] = rx.into();
2107 }
2108 RxTxAddr::Addr64 { rx, tx } => {
2109 a[1] = tx;
2110 a[2] = rx;
2111 }
2112 }
2113 a[3] = page_cnt.into();
2114 }
2115 Interface::RxTxUnmap { id } => {
2116 a[1] = id.into();
2117 }
2118 Interface::PartitionInfoGet { uuid, flags } => {
2119 let bytes = uuid.into_bytes();
2120 a[1] = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]).into();
2121 a[2] = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]).into();
2122 a[3] = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]).into();
2123 a[4] = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]).into();
Imre Kise295adb2025-04-10 13:26:28 +02002124 a[5] = u32::from(flags).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002125 }
Tomás González092202a2025-03-05 11:56:45 +00002126 Interface::MsgWait { flags } => {
2127 if version >= Version(1, 2) {
2128 if let Some(flags) = flags {
2129 a[2] = u32::from(flags).into();
2130 }
2131 }
2132 }
2133 Interface::IdGet | Interface::SpmIdGet | Interface::Yield => {}
Balint Dobszay3aad9572025-01-17 16:54:11 +01002134 Interface::Run { target_info } => {
2135 a[1] = u32::from(target_info).into();
2136 }
2137 Interface::NormalWorldResume => {}
Tomás González17b92442025-03-10 16:45:04 +00002138 Interface::SecondaryEpRegister { entrypoint } => match entrypoint {
2139 SecondaryEpRegisterAddr::Addr32(addr) => a[1] = addr as u64,
2140 SecondaryEpRegisterAddr::Addr64(addr) => a[1] = addr,
2141 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01002142 Interface::MsgSend2 {
2143 sender_vm_id,
2144 flags,
2145 } => {
2146 a[1] = sender_vm_id.into();
Imre Kisa2fd69b2025-06-13 13:39:47 +02002147 a[2] = u32::from(flags).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002148 }
2149 Interface::MsgSendDirectReq {
2150 src_id,
2151 dst_id,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002152 args,
2153 } => {
Balint Dobszaye9a3e762025-02-26 17:29:57 +01002154 a[1] = ((src_id as u64) << 16) | dst_id as u64;
Balint Dobszay3aad9572025-01-17 16:54:11 +01002155 match args {
2156 DirectMsgArgs::Args32(args) => {
2157 a[3] = args[0].into();
2158 a[4] = args[1].into();
2159 a[5] = args[2].into();
2160 a[6] = args[3].into();
2161 a[7] = args[4].into();
2162 }
2163 DirectMsgArgs::Args64(args) => {
2164 a[3] = args[0];
2165 a[4] = args[1];
2166 a[5] = args[2];
2167 a[6] = args[3];
2168 a[7] = args[4];
2169 }
Tomás González4d5b0ba2025-03-03 17:15:55 +00002170 DirectMsgArgs::VersionReq { version } => {
2171 a[2] = DirectMsgArgs::VERSION_REQ.into();
2172 a[3] = u32::from(version).into();
2173 }
Tomás González67f92c72025-03-20 16:50:42 +00002174 DirectMsgArgs::PowerPsciReq32 { params } => {
Tomás González4d5b0ba2025-03-03 17:15:55 +00002175 a[2] = DirectMsgArgs::POWER_PSCI_REQ.into();
Tomás González67f92c72025-03-20 16:50:42 +00002176 a[3] = params[0].into();
2177 a[4] = params[1].into();
2178 a[5] = params[2].into();
2179 a[6] = params[3].into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002180 }
Tomás González67f92c72025-03-20 16:50:42 +00002181 DirectMsgArgs::PowerPsciReq64 { params } => {
Tomás González4d5b0ba2025-03-03 17:15:55 +00002182 a[2] = DirectMsgArgs::POWER_PSCI_REQ.into();
Tomás González67f92c72025-03-20 16:50:42 +00002183 a[3] = params[0];
2184 a[4] = params[1];
2185 a[5] = params[2];
2186 a[6] = params[3];
Tomás González4d5b0ba2025-03-03 17:15:55 +00002187 }
2188 DirectMsgArgs::PowerWarmBootReq { boot_type } => {
2189 a[2] = DirectMsgArgs::POWER_WARM_BOOT_REQ.into();
2190 a[3] = u32::from(boot_type).into();
2191 }
2192 DirectMsgArgs::VmCreated { handle, vm_id } => {
2193 a[2] = DirectMsgArgs::VM_CREATED.into();
2194 let handle_regs: [u32; 2] = handle.into();
2195 a[3] = handle_regs[0].into();
2196 a[4] = handle_regs[1].into();
2197 a[5] = vm_id.into();
2198 }
2199 DirectMsgArgs::VmDestructed { handle, vm_id } => {
2200 a[2] = DirectMsgArgs::VM_DESTRUCTED.into();
2201 let handle_regs: [u32; 2] = handle.into();
2202 a[3] = handle_regs[0].into();
2203 a[4] = handle_regs[1].into();
2204 a[5] = vm_id.into();
2205 }
2206 _ => panic!("Malformed MsgSendDirectReq interface"),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002207 }
2208 }
2209 Interface::MsgSendDirectResp {
2210 src_id,
2211 dst_id,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002212 args,
2213 } => {
Balint Dobszaye9a3e762025-02-26 17:29:57 +01002214 a[1] = ((src_id as u64) << 16) | dst_id as u64;
Balint Dobszay3aad9572025-01-17 16:54:11 +01002215 match args {
2216 DirectMsgArgs::Args32(args) => {
2217 a[3] = args[0].into();
2218 a[4] = args[1].into();
2219 a[5] = args[2].into();
2220 a[6] = args[3].into();
2221 a[7] = args[4].into();
2222 }
2223 DirectMsgArgs::Args64(args) => {
2224 a[3] = args[0];
2225 a[4] = args[1];
2226 a[5] = args[2];
2227 a[6] = args[3];
2228 a[7] = args[4];
2229 }
Tomás González4d5b0ba2025-03-03 17:15:55 +00002230 DirectMsgArgs::VersionResp { version } => {
2231 a[2] = DirectMsgArgs::VERSION_RESP.into();
2232 match version {
Tomás González67f92c72025-03-20 16:50:42 +00002233 None => a[3] = (i32::from(FfaError::NotSupported) as u32).into(),
Tomás González4d5b0ba2025-03-03 17:15:55 +00002234 Some(ver) => a[3] = u32::from(ver).into(),
2235 }
2236 }
2237 DirectMsgArgs::PowerPsciResp { psci_status } => {
2238 a[2] = DirectMsgArgs::POWER_PSCI_RESP.into();
Imre Kisb2d3c882025-04-11 14:19:35 +02002239 a[3] = (psci_status as u32).into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002240 }
2241 DirectMsgArgs::VmCreatedAck { sp_status } => {
2242 a[2] = DirectMsgArgs::VM_CREATED_ACK.into();
Tomás González67f92c72025-03-20 16:50:42 +00002243 a[3] = (i32::from(sp_status) as u32).into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002244 }
2245 DirectMsgArgs::VmDestructedAck { sp_status } => {
2246 a[2] = DirectMsgArgs::VM_DESTRUCTED_ACK.into();
Tomás González67f92c72025-03-20 16:50:42 +00002247 a[3] = (i32::from(sp_status) as u32).into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002248 }
2249 _ => panic!("Malformed MsgSendDirectResp interface"),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002250 }
2251 }
2252 Interface::MemDonate {
2253 total_len,
2254 frag_len,
2255 buf,
2256 } => {
2257 a[1] = total_len.into();
2258 a[2] = frag_len.into();
2259 (a[3], a[4]) = match buf {
2260 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2261 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2262 None => (0, 0),
2263 };
2264 }
2265 Interface::MemLend {
2266 total_len,
2267 frag_len,
2268 buf,
2269 } => {
2270 a[1] = total_len.into();
2271 a[2] = frag_len.into();
2272 (a[3], a[4]) = match buf {
2273 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2274 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2275 None => (0, 0),
2276 };
2277 }
2278 Interface::MemShare {
2279 total_len,
2280 frag_len,
2281 buf,
2282 } => {
2283 a[1] = total_len.into();
2284 a[2] = frag_len.into();
2285 (a[3], a[4]) = match buf {
2286 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2287 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2288 None => (0, 0),
2289 };
2290 }
2291 Interface::MemRetrieveReq {
2292 total_len,
2293 frag_len,
2294 buf,
2295 } => {
2296 a[1] = total_len.into();
2297 a[2] = frag_len.into();
2298 (a[3], a[4]) = match buf {
2299 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2300 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2301 None => (0, 0),
2302 };
2303 }
2304 Interface::MemRetrieveResp {
2305 total_len,
2306 frag_len,
2307 } => {
2308 a[1] = total_len.into();
2309 a[2] = frag_len.into();
2310 }
2311 Interface::MemRelinquish => {}
2312 Interface::MemReclaim { handle, flags } => {
2313 let handle_regs: [u32; 2] = handle.into();
2314 a[1] = handle_regs[0].into();
2315 a[2] = handle_regs[1].into();
Imre Kis356395d2025-06-13 13:49:06 +02002316 a[3] = u32::from(flags).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002317 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01002318 Interface::MemPermGet { addr, page_cnt } => {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002319 a[1] = match addr {
2320 MemAddr::Addr32(addr) => addr.into(),
2321 MemAddr::Addr64(addr) => addr,
2322 };
Balint Dobszayde0dc802025-02-28 14:16:52 +01002323 a[2] = if version >= Version(1, 3) {
2324 page_cnt.unwrap().into()
2325 } else {
2326 assert!(page_cnt.is_none());
2327 0
2328 }
Balint Dobszay3aad9572025-01-17 16:54:11 +01002329 }
2330 Interface::MemPermSet {
2331 addr,
2332 page_cnt,
2333 mem_perm,
2334 } => {
2335 a[1] = match addr {
2336 MemAddr::Addr32(addr) => addr.into(),
2337 MemAddr::Addr64(addr) => addr,
2338 };
2339 a[2] = page_cnt.into();
Imre Kisdcb7df22025-06-06 15:24:40 +02002340 a[3] = u32::from(mem_perm).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002341 }
Imre Kis189f18c2025-05-26 19:33:05 +02002342 Interface::ConsoleLog { chars } => match chars {
2343 ConsoleLogChars::Chars32(ConsoleLogChars32 {
2344 char_cnt,
2345 char_lists,
2346 }) => {
2347 a[1] = char_cnt.into();
2348 a[2] = char_lists[0].into();
2349 a[3] = char_lists[1].into();
2350 a[4] = char_lists[2].into();
2351 a[5] = char_lists[3].into();
2352 a[6] = char_lists[4].into();
2353 a[7] = char_lists[5].into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002354 }
Imre Kis189f18c2025-05-26 19:33:05 +02002355 _ => panic!("{:#x?} requires 18 registers", chars),
2356 },
Tomás González7ffb6132025-04-03 12:28:58 +01002357 Interface::NotificationBitmapCreate { vm_id, vcpu_cnt } => {
2358 a[1] = vm_id.into();
2359 a[2] = vcpu_cnt.into();
2360 }
2361 Interface::NotificationBitmapDestroy { vm_id } => {
2362 a[1] = vm_id.into();
2363 }
2364 Interface::NotificationBind {
2365 sender_id,
2366 receiver_id,
2367 flags,
2368 bitmap,
2369 } => {
2370 a[1] = (u64::from(sender_id) << 16) | u64::from(receiver_id);
2371 a[2] = u32::from(flags).into();
2372 a[3] = bitmap & 0xffff_ffff;
2373 a[4] = bitmap >> 32;
2374 }
Imre Kis3571f2c2025-05-26 19:29:23 +02002375 Interface::NotificationUnbind {
Tomás González7ffb6132025-04-03 12:28:58 +01002376 sender_id,
2377 receiver_id,
2378 bitmap,
2379 } => {
2380 a[1] = (u64::from(sender_id) << 16) | u64::from(receiver_id);
2381 a[3] = bitmap & 0xffff_ffff;
2382 a[4] = bitmap >> 32;
2383 }
2384 Interface::NotificationSet {
2385 sender_id,
2386 receiver_id,
2387 flags,
2388 bitmap,
2389 } => {
2390 a[1] = (u64::from(sender_id) << 16) | u64::from(receiver_id);
2391 a[2] = u32::from(flags).into();
2392 a[3] = bitmap & 0xffff_ffff;
2393 a[4] = bitmap >> 32;
2394 }
2395 Interface::NotificationGet {
2396 vcpu_id,
2397 endpoint_id,
2398 flags,
2399 } => {
2400 a[1] = (u64::from(vcpu_id) << 16) | u64::from(endpoint_id);
2401 a[2] = u32::from(flags).into();
2402 }
2403 Interface::NotificationInfoGet { .. } => {}
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01002404 Interface::El3IntrHandle => {}
Balint Dobszayde0dc802025-02-28 14:16:52 +01002405 _ => panic!("{:#x?} requires 18 registers", self),
2406 }
2407 }
2408
2409 fn pack_regs18(&self, version: Version, a: &mut [u64; 18]) {
2410 assert!(version >= Version(1, 2));
2411
Balint Dobszayde0dc802025-02-28 14:16:52 +01002412 if let Some(function_id) = self.function_id() {
2413 a[0] = function_id as u64;
2414 }
2415
2416 match *self {
2417 Interface::Success { target_info, args } => {
Imre Kise521a282025-06-13 13:29:24 +02002418 a[1] = u32::from(target_info).into();
Balint Dobszayde0dc802025-02-28 14:16:52 +01002419 match args {
Imre Kis54773b62025-04-10 13:47:39 +02002420 SuccessArgs::Args64_2(regs) => a[2..18].copy_from_slice(&regs[..16]),
Balint Dobszayde0dc802025-02-28 14:16:52 +01002421 _ => panic!("{:#x?} requires 8 registers", args),
2422 }
2423 }
2424 Interface::MsgSendDirectReq2 {
2425 src_id,
2426 dst_id,
2427 uuid,
2428 args,
2429 } => {
2430 a[1] = ((src_id as u64) << 16) | dst_id as u64;
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002431 let (uuid_msb, uuid_lsb) = uuid.as_u64_pair();
2432 (a[2], a[3]) = (uuid_msb.swap_bytes(), uuid_lsb.swap_bytes());
Balint Dobszayde0dc802025-02-28 14:16:52 +01002433 a[4..18].copy_from_slice(&args.0[..14]);
2434 }
2435 Interface::MsgSendDirectResp2 {
2436 src_id,
2437 dst_id,
2438 args,
2439 } => {
2440 a[1] = ((src_id as u64) << 16) | dst_id as u64;
2441 a[2] = 0;
2442 a[3] = 0;
2443 a[4..18].copy_from_slice(&args.0[..14]);
2444 }
Imre Kis189f18c2025-05-26 19:33:05 +02002445 Interface::ConsoleLog { chars: char_lists } => match char_lists {
2446 ConsoleLogChars::Chars64(ConsoleLogChars64 {
2447 char_cnt,
2448 char_lists,
2449 }) => {
2450 a[1] = char_cnt.into();
2451 a[2..18].copy_from_slice(&char_lists[..16])
Balint Dobszayde0dc802025-02-28 14:16:52 +01002452 }
Imre Kis189f18c2025-05-26 19:33:05 +02002453 _ => panic!("{:#x?} requires 8 registers", char_lists),
2454 },
Tomás González0a058bc2025-03-11 11:20:55 +00002455 Interface::PartitionInfoGetRegs {
2456 uuid,
2457 start_index,
2458 info_tag,
2459 } => {
2460 if start_index == 0 && info_tag != 0 {
2461 panic!("Information Tag MBZ if start index is 0: {:#x?}", self);
2462 }
2463 let (uuid_msb, uuid_lsb) = uuid.as_u64_pair();
2464 (a[1], a[2]) = (uuid_msb.swap_bytes(), uuid_lsb.swap_bytes());
2465 a[3] = (u64::from(info_tag) << 16) | u64::from(start_index);
2466 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01002467 _ => panic!("{:#x?} requires 8 registers", self),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002468 }
2469 }
2470
Balint Dobszaya5846852025-02-26 15:38:53 +01002471 /// Helper function to create an `FFA_SUCCESS` interface without any arguments.
Balint Dobszay3aad9572025-01-17 16:54:11 +01002472 pub fn success32_noargs() -> Self {
2473 Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02002474 target_info: TargetInfo::default(),
Imre Kis54773b62025-04-10 13:47:39 +02002475 args: SuccessArgs::Args32([0; 6]),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002476 }
2477 }
2478
Balint Dobszaya5846852025-02-26 15:38:53 +01002479 /// Helper function to create an `FFA_ERROR` interface with an error code.
Balint Dobszay3aad9572025-01-17 16:54:11 +01002480 pub fn error(error_code: FfaError) -> Self {
2481 Self::Error {
Imre Kise521a282025-06-13 13:29:24 +02002482 target_info: TargetInfo::default(),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002483 error_code,
Balint Dobszayb727aab2025-04-07 10:24:59 +02002484 error_arg: 0,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002485 }
2486 }
2487}
2488
Tomás González0a058bc2025-03-11 11:20:55 +00002489#[cfg(test)]
2490mod tests {
2491 use super::*;
2492
2493 #[test]
Balint Dobszay5ded5922025-06-13 12:06:53 +02002494 fn version_reg_count() {
2495 assert!(!Version(1, 1).needs_18_regs());
2496 assert!(Version(1, 2).needs_18_regs())
2497 }
2498
2499 #[test]
Tomás González0a058bc2025-03-11 11:20:55 +00002500 fn part_info_get_regs() {
2501 let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
2502 let uuid_bytes = uuid.as_bytes();
2503 let test_info_tag = 0b1101_1101;
2504 let test_start_index = 0b1101;
2505 let start_index_and_tag = (test_info_tag << 16) | test_start_index;
2506 let version = Version(1, 2);
2507
2508 // From spec:
2509 // Bytes[0...7] of UUID with byte 0 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002510 let reg_x1 = ((uuid_bytes[7] as u64) << 56)
2511 | ((uuid_bytes[6] as u64) << 48)
2512 | ((uuid_bytes[5] as u64) << 40)
2513 | ((uuid_bytes[4] as u64) << 32)
2514 | ((uuid_bytes[3] as u64) << 24)
2515 | ((uuid_bytes[2] as u64) << 16)
2516 | ((uuid_bytes[1] as u64) << 8)
Tomás González0a058bc2025-03-11 11:20:55 +00002517 | (uuid_bytes[0] as u64);
2518
2519 // From spec:
2520 // Bytes[8...15] of UUID with byte 8 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002521 let reg_x2 = ((uuid_bytes[15] as u64) << 56)
2522 | ((uuid_bytes[14] as u64) << 48)
2523 | ((uuid_bytes[13] as u64) << 40)
2524 | ((uuid_bytes[12] as u64) << 32)
2525 | ((uuid_bytes[11] as u64) << 24)
2526 | ((uuid_bytes[10] as u64) << 16)
2527 | ((uuid_bytes[9] as u64) << 8)
Tomás González0a058bc2025-03-11 11:20:55 +00002528 | (uuid_bytes[8] as u64);
2529
2530 // First, test for wrong tag:
2531 {
2532 let mut regs = [0u64; 18];
2533 regs[0] = FuncId::PartitionInfoGetRegs as u64;
2534 regs[1] = reg_x1;
2535 regs[2] = reg_x2;
2536 regs[3] = test_info_tag << 16;
2537
2538 assert!(Interface::from_regs(version, &regs).is_err_and(
2539 |e| e == Error::InvalidInformationTag(test_info_tag.try_into().unwrap())
2540 ));
2541 }
2542
2543 // Test for regs -> Interface -> regs
2544 {
2545 let mut orig_regs = [0u64; 18];
2546 orig_regs[0] = FuncId::PartitionInfoGetRegs as u64;
2547 orig_regs[1] = reg_x1;
2548 orig_regs[2] = reg_x2;
2549 orig_regs[3] = start_index_and_tag;
2550
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002551 let mut test_regs = orig_regs;
2552 let interface = Interface::from_regs(version, &test_regs).unwrap();
Tomás González0a058bc2025-03-11 11:20:55 +00002553 match &interface {
2554 Interface::PartitionInfoGetRegs {
2555 info_tag,
2556 start_index,
2557 uuid: int_uuid,
2558 } => {
2559 assert_eq!(u64::from(*info_tag), test_info_tag);
2560 assert_eq!(u64::from(*start_index), test_start_index);
2561 assert_eq!(*int_uuid, uuid);
2562 }
2563 _ => panic!("Expecting Interface::PartitionInfoGetRegs!"),
2564 }
2565 test_regs.fill(0);
2566 interface.to_regs(version, &mut test_regs);
2567 assert_eq!(orig_regs, test_regs);
2568 }
2569
2570 // Test for Interface -> regs -> Interface
2571 {
2572 let interface = Interface::PartitionInfoGetRegs {
2573 info_tag: test_info_tag.try_into().unwrap(),
2574 start_index: test_start_index.try_into().unwrap(),
2575 uuid,
2576 };
2577
2578 let mut regs: [u64; 18] = [0; 18];
2579 interface.to_regs(version, &mut regs);
2580
2581 assert_eq!(Some(FuncId::PartitionInfoGetRegs), interface.function_id());
2582 assert_eq!(regs[0], interface.function_id().unwrap() as u64);
2583 assert_eq!(regs[1], reg_x1);
2584 assert_eq!(regs[2], reg_x2);
2585 assert_eq!(regs[3], (test_info_tag << 16) | test_start_index);
2586
2587 assert_eq!(Interface::from_regs(version, &regs).unwrap(), interface);
2588 }
2589 }
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002590
2591 #[test]
2592 fn msg_send_direct_req2() {
2593 let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
2594 let uuid_bytes = uuid.as_bytes();
2595
2596 // From spec:
2597 // Bytes[0...7] of UUID with byte 0 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002598 let reg_x2 = ((uuid_bytes[7] as u64) << 56)
2599 | ((uuid_bytes[6] as u64) << 48)
2600 | ((uuid_bytes[5] as u64) << 40)
2601 | ((uuid_bytes[4] as u64) << 32)
2602 | ((uuid_bytes[3] as u64) << 24)
2603 | ((uuid_bytes[2] as u64) << 16)
2604 | ((uuid_bytes[1] as u64) << 8)
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002605 | (uuid_bytes[0] as u64);
2606
2607 // From spec:
2608 // Bytes[8...15] of UUID with byte 8 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002609 let reg_x3 = ((uuid_bytes[15] as u64) << 56)
2610 | ((uuid_bytes[14] as u64) << 48)
2611 | ((uuid_bytes[13] as u64) << 40)
2612 | ((uuid_bytes[12] as u64) << 32)
2613 | ((uuid_bytes[11] as u64) << 24)
2614 | ((uuid_bytes[10] as u64) << 16)
2615 | ((uuid_bytes[9] as u64) << 8)
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002616 | (uuid_bytes[8] as u64);
2617
2618 let test_sender = 0b1101_1101;
2619 let test_receiver = 0b1101;
2620 let test_sender_receiver = (test_sender << 16) | test_receiver;
2621 let version = Version(1, 2);
2622
2623 // Test for regs -> Interface -> regs
2624 {
2625 let mut orig_regs = [0u64; 18];
2626 orig_regs[0] = FuncId::MsgSendDirectReq64_2 as u64;
2627 orig_regs[1] = test_sender_receiver;
2628 orig_regs[2] = reg_x2;
2629 orig_regs[3] = reg_x3;
2630
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002631 let mut test_regs = orig_regs;
2632 let interface = Interface::from_regs(version, &test_regs).unwrap();
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002633 match &interface {
2634 Interface::MsgSendDirectReq2 {
2635 dst_id,
2636 src_id,
2637 args: _,
2638 uuid: int_uuid,
2639 } => {
2640 assert_eq!(u64::from(*src_id), test_sender);
2641 assert_eq!(u64::from(*dst_id), test_receiver);
2642 assert_eq!(*int_uuid, uuid);
2643 }
2644 _ => panic!("Expecting Interface::MsgSendDirectReq2!"),
2645 }
2646 test_regs.fill(0);
2647 interface.to_regs(version, &mut test_regs);
2648 assert_eq!(orig_regs, test_regs);
2649 }
2650
2651 // Test for Interface -> regs -> Interface
2652 {
2653 let rest_of_regs: [u64; 14] = [0; 14];
2654
2655 let interface = Interface::MsgSendDirectReq2 {
2656 src_id: test_sender.try_into().unwrap(),
2657 dst_id: test_receiver.try_into().unwrap(),
2658 uuid,
2659 args: DirectMsg2Args(rest_of_regs),
2660 };
2661
2662 let mut regs: [u64; 18] = [0; 18];
2663 interface.to_regs(version, &mut regs);
2664
2665 assert_eq!(Some(FuncId::MsgSendDirectReq64_2), interface.function_id());
2666 assert_eq!(regs[0], interface.function_id().unwrap() as u64);
2667 assert_eq!(regs[1], test_sender_receiver);
2668 assert_eq!(regs[2], reg_x2);
2669 assert_eq!(regs[3], reg_x3);
2670 assert_eq!(regs[4], 0);
2671
2672 assert_eq!(Interface::from_regs(version, &regs).unwrap(), interface);
2673 }
2674 }
Tomás González6ccba0a2025-04-09 13:31:29 +01002675
2676 #[test]
2677 fn is_32bit() {
2678 let interface_64 = Interface::MsgSendDirectReq {
2679 src_id: 0,
2680 dst_id: 1,
2681 args: DirectMsgArgs::Args64([0, 0, 0, 0, 0]),
2682 };
2683 assert!(!interface_64.is_32bit());
2684
2685 let interface_32 = Interface::MsgSendDirectReq {
2686 src_id: 0,
2687 dst_id: 1,
2688 args: DirectMsgArgs::Args32([0, 0, 0, 0, 0]),
2689 };
2690 assert!(interface_32.is_32bit());
2691 }
Imre Kis787c5002025-04-10 14:25:51 +02002692
2693 #[test]
2694 fn success_args_notification_info_get32() {
2695 let mut notifications = SuccessArgsNotificationInfoGet32::default();
2696
2697 // 16.7.1.1 Example usage
2698 notifications.add_list(0x0000, &[0, 2, 3]).unwrap();
2699 notifications.add_list(0x0000, &[4, 6]).unwrap();
2700 notifications.add_list(0x0002, &[]).unwrap();
2701 notifications.add_list(0x0003, &[1]).unwrap();
2702
2703 let args: SuccessArgs = notifications.into();
2704 assert_eq!(
2705 SuccessArgs::Args32([
2706 0x0004_b200,
2707 0x0000_0000,
2708 0x0003_0002,
2709 0x0004_0000,
2710 0x0002_0006,
2711 0x0001_0003
2712 ]),
2713 args
2714 );
2715
2716 let notifications = SuccessArgsNotificationInfoGet32::try_from(args).unwrap();
2717 let mut iter = notifications.iter();
2718 assert_eq!(Some((0x0000, &[0, 2, 3][..])), iter.next());
2719 assert_eq!(Some((0x0000, &[4, 6][..])), iter.next());
2720 assert_eq!(Some((0x0002, &[][..])), iter.next());
2721 assert_eq!(Some((0x0003, &[1][..])), iter.next());
2722 }
2723
2724 #[test]
2725 fn success_args_notification_info_get64() {
2726 let mut notifications = SuccessArgsNotificationInfoGet64::default();
2727
2728 // 16.7.1.1 Example usage
2729 notifications.add_list(0x0000, &[0, 2, 3]).unwrap();
2730 notifications.add_list(0x0000, &[4, 6]).unwrap();
2731 notifications.add_list(0x0002, &[]).unwrap();
2732 notifications.add_list(0x0003, &[1]).unwrap();
2733
2734 let args: SuccessArgs = notifications.into();
2735 assert_eq!(
2736 SuccessArgs::Args64([
2737 0x0004_b200,
2738 0x0003_0002_0000_0000,
2739 0x0002_0006_0004_0000,
2740 0x0000_0000_0001_0003,
2741 0x0000_0000_0000_0000,
2742 0x0000_0000_0000_0000,
2743 ]),
2744 args
2745 );
2746
2747 let notifications = SuccessArgsNotificationInfoGet64::try_from(args).unwrap();
2748 let mut iter = notifications.iter();
2749 assert_eq!(Some((0x0000, &[0, 2, 3][..])), iter.next());
2750 assert_eq!(Some((0x0000, &[4, 6][..])), iter.next());
2751 assert_eq!(Some((0x0002, &[][..])), iter.next());
2752 assert_eq!(Some((0x0003, &[1][..])), iter.next());
2753 }
Tomás González0a058bc2025-03-11 11:20:55 +00002754}