blob: b240f95caf0073a1bf5dff8c6329956fcf57bb09 [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 Kisa2fd69b2025-06-13 13:39:47 +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 Kisa9e544c2025-06-13 15:57:54 +0200700#[derive(Debug, Default, Eq, PartialEq, Clone, Copy)]
Tomás González092202a2025-03-05 11:56:45 +0000701pub struct MsgWaitFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200702 pub retain_rx_buffer: bool,
Tomás González092202a2025-03-05 11:56:45 +0000703}
704
705impl MsgWaitFlags {
706 const RETAIN_RX_BUFFER: u32 = 0x01;
707 const MBZ_BITS: u32 = 0xfffe;
708}
709
710impl TryFrom<u32> for MsgWaitFlags {
711 type Error = Error;
712
713 fn try_from(val: u32) -> Result<Self, Self::Error> {
714 if (val & Self::MBZ_BITS) != 0 {
715 Err(Error::InvalidMsgWaitFlag(val))
716 } else {
717 Ok(MsgWaitFlags {
718 retain_rx_buffer: val & Self::RETAIN_RX_BUFFER != 0,
719 })
720 }
721 }
722}
723
724impl From<MsgWaitFlags> for u32 {
725 fn from(flags: MsgWaitFlags) -> Self {
726 let mut bits: u32 = 0;
727 if flags.retain_rx_buffer {
728 bits |= MsgWaitFlags::RETAIN_RX_BUFFER;
729 }
730 bits
731 }
732}
733
Balint Dobszaya5846852025-02-26 15:38:53 +0100734/// Descriptor for a dynamically allocated memory buffer that contains the memory transaction
Tomás Gonzálezf268e322025-03-05 11:18:11 +0000735/// descriptor.
736///
737/// Used by `FFA_MEM_{DONATE,LEND,SHARE,RETRIEVE_REQ}` interfaces, only when the TX buffer is not
738/// used to transmit the transaction descriptor.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100739#[derive(Debug, Eq, PartialEq, Clone, Copy)]
740pub enum MemOpBuf {
741 Buf32 { addr: u32, page_cnt: u32 },
742 Buf64 { addr: u64, page_cnt: u32 },
743}
744
Balint Dobszaya5846852025-02-26 15:38:53 +0100745/// Memory address argument for `FFA_MEM_PERM_{GET,SET}` interfaces.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100746#[derive(Debug, Eq, PartialEq, Clone, Copy)]
747pub enum MemAddr {
748 Addr32(u32),
749 Addr64(u64),
750}
751
Balint Dobszayde0dc802025-02-28 14:16:52 +0100752/// Argument for the `FFA_CONSOLE_LOG` interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +0100753#[derive(Debug, Eq, PartialEq, Clone, Copy)]
754pub enum ConsoleLogChars {
Imre Kis189f18c2025-05-26 19:33:05 +0200755 Chars32(ConsoleLogChars32),
756 Chars64(ConsoleLogChars64),
Balint Dobszay3aad9572025-01-17 16:54:11 +0100757}
758
Imre Kis189f18c2025-05-26 19:33:05 +0200759/// Generic type for storing `FFA_CONSOLE_LOG` character payload and its length in bytes.
760#[derive(Debug, Default, Eq, PartialEq, Clone, Copy)]
761pub struct LogChars<T>
762where
763 T: IntoBytes + FromBytes + Immutable,
764{
765 char_cnt: u8,
766 char_lists: T,
767}
768
769impl<T> LogChars<T>
770where
771 T: IntoBytes + FromBytes + Immutable,
772{
773 const MAX_LENGTH: u8 = core::mem::size_of::<T>() as u8;
774
775 /// Returns true if there are no characters in the structure.
776 pub fn empty(&self) -> bool {
777 self.char_cnt == 0
778 }
779
780 /// Returns true if the structure is full.
781 pub fn full(&self) -> bool {
782 self.char_cnt as usize >= core::mem::size_of::<T>()
783 }
784
785 /// Returns the payload bytes.
786 pub fn bytes(&self) -> &[u8] {
787 &self.char_lists.as_bytes()[..self.char_cnt as usize]
788 }
789
790 /// Append byte slice to the end of the characters.
791 pub fn push(&mut self, source: &[u8]) -> usize {
792 let empty_area = &mut self.char_lists.as_mut_bytes()[self.char_cnt.into()..];
793 let len = empty_area.len().min(source.len());
794
795 empty_area[..len].copy_from_slice(&source[..len]);
796 self.char_cnt += len as u8;
797
798 len
799 }
800}
801
802/// Specialized type for 32-bit `FFA_CONSOLE_LOG` payload.
803pub type ConsoleLogChars32 = LogChars<[u32; 6]>;
804
805/// Specialized type for 64-bit `FFA_CONSOLE_LOG` payload.
806pub type ConsoleLogChars64 = LogChars<[u64; 16]>;
807
Tomás González7ffb6132025-04-03 12:28:58 +0100808#[derive(Debug, Eq, PartialEq, Clone, Copy)]
809pub struct NotificationBindFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200810 pub per_vcpu_notification: bool,
Tomás González7ffb6132025-04-03 12:28:58 +0100811}
812
813impl NotificationBindFlags {
814 const PER_VCPU_NOTIFICATION: u32 = 1;
815}
816
817impl From<NotificationBindFlags> for u32 {
818 fn from(flags: NotificationBindFlags) -> Self {
819 let mut bits: u32 = 0;
820 if flags.per_vcpu_notification {
821 bits |= NotificationBindFlags::PER_VCPU_NOTIFICATION;
822 }
823 bits
824 }
825}
826
827impl From<u32> for NotificationBindFlags {
828 fn from(flags: u32) -> Self {
829 Self {
830 per_vcpu_notification: flags & Self::PER_VCPU_NOTIFICATION != 0,
831 }
832 }
833}
834
835#[derive(Debug, Eq, PartialEq, Clone, Copy)]
836pub struct NotificationSetFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200837 pub delay_schedule_receiver: bool,
838 pub vcpu_id: Option<u16>,
Tomás González7ffb6132025-04-03 12:28:58 +0100839}
840
841impl NotificationSetFlags {
842 const PER_VCP_NOTIFICATION: u32 = 1 << 0;
843 const DELAY_SCHEDULE_RECEIVER: u32 = 1 << 1;
844 const VCPU_ID_SHIFT: u32 = 16;
845
846 const MBZ_BITS: u32 = 0xfffc;
847}
848
849impl From<NotificationSetFlags> for u32 {
850 fn from(flags: NotificationSetFlags) -> Self {
851 let mut bits: u32 = 0;
852
853 if flags.delay_schedule_receiver {
854 bits |= NotificationSetFlags::DELAY_SCHEDULE_RECEIVER;
855 }
856 if let Some(vcpu_id) = flags.vcpu_id {
857 bits |= NotificationSetFlags::PER_VCP_NOTIFICATION;
858 bits |= u32::from(vcpu_id) << NotificationSetFlags::VCPU_ID_SHIFT;
859 }
860
861 bits
862 }
863}
864
865impl TryFrom<u32> for NotificationSetFlags {
866 type Error = Error;
867
868 fn try_from(flags: u32) -> Result<Self, Self::Error> {
869 if (flags & Self::MBZ_BITS) != 0 {
870 return Err(Error::InvalidNotificationSetFlag(flags));
871 }
872
873 let tentative_vcpu_id = (flags >> Self::VCPU_ID_SHIFT) as u16;
874
875 let vcpu_id = if (flags & Self::PER_VCP_NOTIFICATION) != 0 {
876 Some(tentative_vcpu_id)
877 } else {
878 if tentative_vcpu_id != 0 {
879 return Err(Error::InvalidNotificationSetFlag(flags));
880 }
881 None
882 };
883
884 Ok(Self {
885 delay_schedule_receiver: (flags & Self::DELAY_SCHEDULE_RECEIVER) != 0,
886 vcpu_id,
887 })
888 }
889}
890
891#[derive(Debug, Eq, PartialEq, Clone, Copy)]
892pub struct NotificationGetFlags {
Imre Kisc739e0e2025-05-30 11:49:25 +0200893 pub sp_bitmap_id: bool,
894 pub vm_bitmap_id: bool,
895 pub spm_bitmap_id: bool,
896 pub hyp_bitmap_id: bool,
Tomás González7ffb6132025-04-03 12:28:58 +0100897}
898
899impl NotificationGetFlags {
900 const SP_BITMAP_ID: u32 = 1;
901 const VM_BITMAP_ID: u32 = 1 << 1;
902 const SPM_BITMAP_ID: u32 = 1 << 2;
903 const HYP_BITMAP_ID: u32 = 1 << 3;
904}
905
906impl From<NotificationGetFlags> for u32 {
907 fn from(flags: NotificationGetFlags) -> Self {
908 let mut bits: u32 = 0;
909 if flags.sp_bitmap_id {
910 bits |= NotificationGetFlags::SP_BITMAP_ID;
911 }
912 if flags.vm_bitmap_id {
913 bits |= NotificationGetFlags::VM_BITMAP_ID;
914 }
915 if flags.spm_bitmap_id {
916 bits |= NotificationGetFlags::SPM_BITMAP_ID;
917 }
918 if flags.hyp_bitmap_id {
919 bits |= NotificationGetFlags::HYP_BITMAP_ID;
920 }
921 bits
922 }
923}
924
925impl From<u32> for NotificationGetFlags {
926 // This is a "from" instead of a "try_from" because Reserved Bits are SBZ, *not* MBZ.
927 fn from(flags: u32) -> Self {
928 Self {
929 sp_bitmap_id: (flags & Self::SP_BITMAP_ID) != 0,
930 vm_bitmap_id: (flags & Self::VM_BITMAP_ID) != 0,
931 spm_bitmap_id: (flags & Self::SPM_BITMAP_ID) != 0,
932 hyp_bitmap_id: (flags & Self::HYP_BITMAP_ID) != 0,
933 }
934 }
935}
936
Imre Kis9959e062025-04-10 14:16:10 +0200937/// `FFA_NOTIFICATION_GET` specific success argument structure.
938#[derive(Debug, Eq, PartialEq, Clone, Copy)]
939pub struct SuccessArgsNotificationGet {
940 pub sp_notifications: Option<u64>,
941 pub vm_notifications: Option<u64>,
942 pub spm_notifications: Option<u32>,
943 pub hypervisor_notifications: Option<u32>,
944}
945
946impl From<SuccessArgsNotificationGet> for SuccessArgs {
947 fn from(value: SuccessArgsNotificationGet) -> Self {
948 let mut args = [0; 6];
949
950 if let Some(bitmap) = value.sp_notifications {
951 args[0] = bitmap as u32;
952 args[1] = (bitmap >> 32) as u32;
953 }
954
955 if let Some(bitmap) = value.vm_notifications {
956 args[2] = bitmap as u32;
957 args[3] = (bitmap >> 32) as u32;
958 }
959
960 if let Some(bitmap) = value.spm_notifications {
961 args[4] = bitmap;
962 }
963
964 if let Some(bitmap) = value.hypervisor_notifications {
965 args[5] = bitmap;
966 }
967
968 Self::Args32(args)
969 }
970}
971
972impl TryFrom<(NotificationGetFlags, SuccessArgs)> for SuccessArgsNotificationGet {
973 type Error = Error;
974
975 fn try_from(value: (NotificationGetFlags, SuccessArgs)) -> Result<Self, Self::Error> {
976 let (flags, value) = value;
977 let args = value.try_get_args32()?;
978
979 let sp_notifications = if flags.sp_bitmap_id {
980 Some(u64::from(args[0]) | (u64::from(args[1]) << 32))
981 } else {
982 None
983 };
984
985 let vm_notifications = if flags.vm_bitmap_id {
986 Some(u64::from(args[2]) | (u64::from(args[3]) << 32))
987 } else {
988 None
989 };
990
991 let spm_notifications = if flags.spm_bitmap_id {
992 Some(args[4])
993 } else {
994 None
995 };
996
997 let hypervisor_notifications = if flags.hyp_bitmap_id {
998 Some(args[5])
999 } else {
1000 None
1001 };
1002
1003 Ok(Self {
1004 sp_notifications,
1005 vm_notifications,
1006 spm_notifications,
1007 hypervisor_notifications,
1008 })
1009 }
1010}
Imre Kis787c5002025-04-10 14:25:51 +02001011
1012/// `FFA_NOTIFICATION_INFO_GET` specific success argument structure. The `MAX_COUNT` parameter
1013/// depends on the 32-bit or 64-bit packing.
1014#[derive(Debug, Eq, PartialEq, Clone, Copy)]
1015pub struct SuccessArgsNotificationInfoGet<const MAX_COUNT: usize> {
1016 pub more_pending_notifications: bool,
1017 list_count: usize,
1018 id_counts: [u8; MAX_COUNT],
1019 ids: [u16; MAX_COUNT],
1020}
1021
1022impl<const MAX_COUNT: usize> Default for SuccessArgsNotificationInfoGet<MAX_COUNT> {
1023 fn default() -> Self {
1024 Self {
1025 more_pending_notifications: false,
1026 list_count: 0,
1027 id_counts: [0; MAX_COUNT],
1028 ids: [0; MAX_COUNT],
1029 }
1030 }
1031}
1032
1033impl<const MAX_COUNT: usize> SuccessArgsNotificationInfoGet<MAX_COUNT> {
1034 const MORE_PENDING_NOTIFICATIONS_FLAG: u64 = 1 << 0;
1035 const LIST_COUNT_SHIFT: usize = 7;
1036 const LIST_COUNT_MASK: u64 = 0x1f;
1037 const ID_COUNT_SHIFT: usize = 12;
1038 const ID_COUNT_MASK: u64 = 0x03;
1039 const ID_COUNT_BITS: usize = 2;
1040
1041 pub fn add_list(&mut self, endpoint: u16, vcpu_ids: &[u16]) -> Result<(), Error> {
1042 if self.list_count >= MAX_COUNT || vcpu_ids.len() > Self::ID_COUNT_MASK as usize {
1043 return Err(Error::InvalidNotificationCount);
1044 }
1045
1046 // Each list contains at least one ID: the partition ID, followed by vCPU IDs. The number
1047 // of vCPU IDs is recorded in `id_counts`.
1048 let mut current_id_index = self.list_count + self.id_counts.iter().sum::<u8>() as usize;
1049 if current_id_index + 1 + vcpu_ids.len() > MAX_COUNT {
1050 // The new list does not fit into the available space for IDs.
1051 return Err(Error::InvalidNotificationCount);
1052 }
1053
1054 self.id_counts[self.list_count] = vcpu_ids.len() as u8;
1055 self.list_count += 1;
1056
1057 // The first ID is the endpoint ID.
1058 self.ids[current_id_index] = endpoint;
1059 current_id_index += 1;
1060
1061 // Insert the vCPU IDs.
1062 self.ids[current_id_index..current_id_index + vcpu_ids.len()].copy_from_slice(vcpu_ids);
1063
1064 Ok(())
1065 }
1066
1067 pub fn iter(&self) -> NotificationInfoGetIterator<'_> {
1068 NotificationInfoGetIterator {
1069 list_index: 0,
1070 id_index: 0,
1071 id_count: &self.id_counts[0..self.list_count],
1072 ids: &self.ids,
1073 }
1074 }
1075
1076 /// Pack flags field and IDs.
1077 fn pack(self) -> (u64, [u16; MAX_COUNT]) {
1078 let mut flags = if self.more_pending_notifications {
1079 Self::MORE_PENDING_NOTIFICATIONS_FLAG
1080 } else {
1081 0
1082 };
1083
1084 flags |= (self.list_count as u64) << Self::LIST_COUNT_SHIFT;
1085 for (count, shift) in self.id_counts.iter().take(self.list_count).zip(
1086 (Self::ID_COUNT_SHIFT..Self::ID_COUNT_SHIFT + Self::ID_COUNT_BITS * MAX_COUNT)
1087 .step_by(Self::ID_COUNT_BITS),
1088 ) {
1089 flags |= u64::from(*count) << shift;
1090 }
1091
1092 (flags, self.ids)
1093 }
1094
1095 /// Unpack flags field and IDs.
1096 fn unpack(flags: u64, ids: [u16; MAX_COUNT]) -> Result<Self, Error> {
1097 let count_of_lists = ((flags >> Self::LIST_COUNT_SHIFT) & Self::LIST_COUNT_MASK) as usize;
1098
1099 if count_of_lists > MAX_COUNT {
1100 return Err(Error::InvalidNotificationCount);
1101 }
1102
1103 let mut count_of_ids = [0; MAX_COUNT];
1104 let mut count_of_ids_bits = flags >> Self::ID_COUNT_SHIFT;
1105
1106 for id in count_of_ids.iter_mut().take(count_of_lists) {
1107 *id = (count_of_ids_bits & Self::ID_COUNT_MASK) as u8;
1108 count_of_ids_bits >>= Self::ID_COUNT_BITS;
1109 }
1110
Imre Kis7846c9f2025-04-15 09:45:00 +02001111 let id_field_count = count_of_lists + count_of_ids.iter().sum::<u8>() as usize;
1112 if id_field_count > MAX_COUNT {
1113 return Err(Error::InvalidNotificationCount);
1114 }
1115
Imre Kis787c5002025-04-10 14:25:51 +02001116 Ok(Self {
1117 more_pending_notifications: (flags & Self::MORE_PENDING_NOTIFICATIONS_FLAG) != 0,
1118 list_count: count_of_lists,
1119 id_counts: count_of_ids,
1120 ids,
1121 })
1122 }
1123}
1124
1125/// `FFA_NOTIFICATION_INFO_GET_32` specific success argument structure.
1126pub type SuccessArgsNotificationInfoGet32 = SuccessArgsNotificationInfoGet<10>;
1127
1128impl From<SuccessArgsNotificationInfoGet32> for SuccessArgs {
1129 fn from(value: SuccessArgsNotificationInfoGet32) -> Self {
1130 let (flags, ids) = value.pack();
1131 let id_regs: [u32; 5] = transmute!(ids);
1132
1133 let mut args = [0; 6];
1134 args[0] = flags as u32;
1135 args[1..6].copy_from_slice(&id_regs);
1136
1137 SuccessArgs::Args32(args)
1138 }
1139}
1140
1141impl TryFrom<SuccessArgs> for SuccessArgsNotificationInfoGet32 {
1142 type Error = Error;
1143
1144 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
1145 let args = value.try_get_args32()?;
1146 let flags = args[0].into();
1147 let id_regs: [u32; 5] = args[1..6].try_into().unwrap();
1148 Self::unpack(flags, transmute!(id_regs))
1149 }
1150}
1151
1152/// `FFA_NOTIFICATION_INFO_GET_64` specific success argument structure.
1153pub type SuccessArgsNotificationInfoGet64 = SuccessArgsNotificationInfoGet<20>;
1154
1155impl From<SuccessArgsNotificationInfoGet64> for SuccessArgs {
1156 fn from(value: SuccessArgsNotificationInfoGet64) -> Self {
1157 let (flags, ids) = value.pack();
1158 let id_regs: [u64; 5] = transmute!(ids);
1159
1160 let mut args = [0; 6];
1161 args[0] = flags;
1162 args[1..6].copy_from_slice(&id_regs);
1163
1164 SuccessArgs::Args64(args)
1165 }
1166}
1167
1168impl TryFrom<SuccessArgs> for SuccessArgsNotificationInfoGet64 {
1169 type Error = Error;
1170
1171 fn try_from(value: SuccessArgs) -> Result<Self, Self::Error> {
1172 let args = value.try_get_args64()?;
1173 let flags = args[0];
1174 let id_regs: [u64; 5] = args[1..6].try_into().unwrap();
1175 Self::unpack(flags, transmute!(id_regs))
1176 }
1177}
1178
1179pub struct NotificationInfoGetIterator<'a> {
1180 list_index: usize,
1181 id_index: usize,
1182 id_count: &'a [u8],
1183 ids: &'a [u16],
1184}
1185
1186impl<'a> Iterator for NotificationInfoGetIterator<'a> {
1187 type Item = (u16, &'a [u16]);
1188
1189 fn next(&mut self) -> Option<Self::Item> {
1190 if self.list_index < self.id_count.len() {
1191 let partition_id = self.ids[self.id_index];
1192 let id_range =
1193 (self.id_index + 1)..=(self.id_index + self.id_count[self.list_index] as usize);
1194
1195 self.id_index += 1 + self.id_count[self.list_index] as usize;
1196 self.list_index += 1;
1197
1198 Some((partition_id, &self.ids[id_range]))
1199 } else {
1200 None
1201 }
1202 }
1203}
1204
Tomás Gonzálezf268e322025-03-05 11:18:11 +00001205/// FF-A "message types", the terminology used by the spec is "interfaces".
1206///
1207/// The interfaces are used by FF-A components for communication at an FF-A instance. The spec also
1208/// describes the valid FF-A instances and conduits for each interface.
Balint Dobszay3aad9572025-01-17 16:54:11 +01001209#[derive(Debug, Eq, PartialEq, Clone, Copy)]
1210pub enum Interface {
1211 Error {
1212 target_info: TargetInfo,
1213 error_code: FfaError,
Balint Dobszayb727aab2025-04-07 10:24:59 +02001214 error_arg: u32,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001215 },
1216 Success {
Imre Kise521a282025-06-13 13:29:24 +02001217 target_info: TargetInfo,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001218 args: SuccessArgs,
1219 },
1220 Interrupt {
1221 target_info: TargetInfo,
1222 interrupt_id: u32,
1223 },
1224 Version {
1225 input_version: Version,
1226 },
1227 VersionOut {
1228 output_version: Version,
1229 },
1230 Features {
1231 feat_id: Feature,
1232 input_properties: u32,
1233 },
1234 RxAcquire {
1235 vm_id: u16,
1236 },
1237 RxRelease {
1238 vm_id: u16,
1239 },
1240 RxTxMap {
1241 addr: RxTxAddr,
1242 page_cnt: u32,
1243 },
1244 RxTxUnmap {
1245 id: u16,
1246 },
1247 PartitionInfoGet {
1248 uuid: Uuid,
Imre Kise295adb2025-04-10 13:26:28 +02001249 flags: PartitionInfoGetFlags,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001250 },
Tomás González0a058bc2025-03-11 11:20:55 +00001251 PartitionInfoGetRegs {
1252 uuid: Uuid,
1253 start_index: u16,
1254 info_tag: u16,
1255 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001256 IdGet,
1257 SpmIdGet,
Tomás González092202a2025-03-05 11:56:45 +00001258 MsgWait {
1259 flags: Option<MsgWaitFlags>,
1260 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001261 Yield,
1262 Run {
1263 target_info: TargetInfo,
1264 },
1265 NormalWorldResume,
Tomás González17b92442025-03-10 16:45:04 +00001266 SecondaryEpRegister {
1267 entrypoint: SecondaryEpRegisterAddr,
1268 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001269 MsgSend2 {
1270 sender_vm_id: u16,
Imre Kisa2fd69b2025-06-13 13:39:47 +02001271 flags: MsgSend2Flags,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001272 },
1273 MsgSendDirectReq {
1274 src_id: u16,
1275 dst_id: u16,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001276 args: DirectMsgArgs,
1277 },
1278 MsgSendDirectResp {
1279 src_id: u16,
1280 dst_id: u16,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001281 args: DirectMsgArgs,
1282 },
Balint Dobszayde0dc802025-02-28 14:16:52 +01001283 MsgSendDirectReq2 {
1284 src_id: u16,
1285 dst_id: u16,
1286 uuid: Uuid,
1287 args: DirectMsg2Args,
1288 },
1289 MsgSendDirectResp2 {
1290 src_id: u16,
1291 dst_id: u16,
1292 args: DirectMsg2Args,
1293 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001294 MemDonate {
1295 total_len: u32,
1296 frag_len: u32,
1297 buf: Option<MemOpBuf>,
1298 },
1299 MemLend {
1300 total_len: u32,
1301 frag_len: u32,
1302 buf: Option<MemOpBuf>,
1303 },
1304 MemShare {
1305 total_len: u32,
1306 frag_len: u32,
1307 buf: Option<MemOpBuf>,
1308 },
1309 MemRetrieveReq {
1310 total_len: u32,
1311 frag_len: u32,
1312 buf: Option<MemOpBuf>,
1313 },
1314 MemRetrieveResp {
1315 total_len: u32,
1316 frag_len: u32,
1317 },
1318 MemRelinquish,
1319 MemReclaim {
1320 handle: memory_management::Handle,
Imre Kis356395d2025-06-13 13:49:06 +02001321 flags: memory_management::MemReclaimFlags,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001322 },
1323 MemPermGet {
1324 addr: MemAddr,
Balint Dobszayde0dc802025-02-28 14:16:52 +01001325 page_cnt: Option<u32>,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001326 },
1327 MemPermSet {
1328 addr: MemAddr,
1329 page_cnt: u32,
Imre Kisdcb7df22025-06-06 15:24:40 +02001330 mem_perm: memory_management::MemPermissionsGetSet,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001331 },
1332 ConsoleLog {
Imre Kis189f18c2025-05-26 19:33:05 +02001333 chars: ConsoleLogChars,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001334 },
Tomás González7ffb6132025-04-03 12:28:58 +01001335 NotificationBitmapCreate {
1336 vm_id: u16,
1337 vcpu_cnt: u32,
1338 },
1339 NotificationBitmapDestroy {
1340 vm_id: u16,
1341 },
1342 NotificationBind {
1343 sender_id: u16,
1344 receiver_id: u16,
1345 flags: NotificationBindFlags,
1346 bitmap: u64,
1347 },
Imre Kis3571f2c2025-05-26 19:29:23 +02001348 NotificationUnbind {
Tomás González7ffb6132025-04-03 12:28:58 +01001349 sender_id: u16,
1350 receiver_id: u16,
1351 bitmap: u64,
1352 },
1353 NotificationSet {
1354 sender_id: u16,
1355 receiver_id: u16,
1356 flags: NotificationSetFlags,
1357 bitmap: u64,
1358 },
1359 NotificationGet {
1360 vcpu_id: u16,
1361 endpoint_id: u16,
1362 flags: NotificationGetFlags,
1363 },
1364 NotificationInfoGet {
1365 is_32bit: bool,
1366 },
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01001367 El3IntrHandle,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001368}
1369
Balint Dobszayde0dc802025-02-28 14:16:52 +01001370impl Interface {
1371 /// Returns the function ID for the call, if it has one.
1372 pub fn function_id(&self) -> Option<FuncId> {
1373 match self {
1374 Interface::Error { .. } => Some(FuncId::Error),
1375 Interface::Success { args, .. } => match args {
Imre Kis54773b62025-04-10 13:47:39 +02001376 SuccessArgs::Args32(..) => Some(FuncId::Success32),
1377 SuccessArgs::Args64(..) | SuccessArgs::Args64_2(..) => Some(FuncId::Success64),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001378 },
1379 Interface::Interrupt { .. } => Some(FuncId::Interrupt),
1380 Interface::Version { .. } => Some(FuncId::Version),
1381 Interface::VersionOut { .. } => None,
1382 Interface::Features { .. } => Some(FuncId::Features),
1383 Interface::RxAcquire { .. } => Some(FuncId::RxAcquire),
1384 Interface::RxRelease { .. } => Some(FuncId::RxRelease),
1385 Interface::RxTxMap { addr, .. } => match addr {
1386 RxTxAddr::Addr32 { .. } => Some(FuncId::RxTxMap32),
1387 RxTxAddr::Addr64 { .. } => Some(FuncId::RxTxMap64),
1388 },
1389 Interface::RxTxUnmap { .. } => Some(FuncId::RxTxUnmap),
1390 Interface::PartitionInfoGet { .. } => Some(FuncId::PartitionInfoGet),
Tomás González0a058bc2025-03-11 11:20:55 +00001391 Interface::PartitionInfoGetRegs { .. } => Some(FuncId::PartitionInfoGetRegs),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001392 Interface::IdGet => Some(FuncId::IdGet),
1393 Interface::SpmIdGet => Some(FuncId::SpmIdGet),
Tomás González092202a2025-03-05 11:56:45 +00001394 Interface::MsgWait { .. } => Some(FuncId::MsgWait),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001395 Interface::Yield => Some(FuncId::Yield),
1396 Interface::Run { .. } => Some(FuncId::Run),
1397 Interface::NormalWorldResume => Some(FuncId::NormalWorldResume),
Tomás González17b92442025-03-10 16:45:04 +00001398 Interface::SecondaryEpRegister { entrypoint } => match entrypoint {
1399 SecondaryEpRegisterAddr::Addr32 { .. } => Some(FuncId::SecondaryEpRegister32),
1400 SecondaryEpRegisterAddr::Addr64 { .. } => Some(FuncId::SecondaryEpRegister64),
1401 },
Balint Dobszayde0dc802025-02-28 14:16:52 +01001402 Interface::MsgSend2 { .. } => Some(FuncId::MsgSend2),
1403 Interface::MsgSendDirectReq { args, .. } => match args {
1404 DirectMsgArgs::Args32(_) => Some(FuncId::MsgSendDirectReq32),
1405 DirectMsgArgs::Args64(_) => Some(FuncId::MsgSendDirectReq64),
Tomás González4d5b0ba2025-03-03 17:15:55 +00001406 DirectMsgArgs::VersionReq { .. } => Some(FuncId::MsgSendDirectReq32),
1407 DirectMsgArgs::PowerPsciReq32 { .. } => Some(FuncId::MsgSendDirectReq32),
1408 DirectMsgArgs::PowerPsciReq64 { .. } => Some(FuncId::MsgSendDirectReq64),
1409 DirectMsgArgs::PowerWarmBootReq { .. } => Some(FuncId::MsgSendDirectReq32),
1410 DirectMsgArgs::VmCreated { .. } => Some(FuncId::MsgSendDirectReq32),
1411 DirectMsgArgs::VmDestructed { .. } => Some(FuncId::MsgSendDirectReq32),
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001412 _ => panic!("Invalid direct request arguments: {:#?}", args),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001413 },
1414 Interface::MsgSendDirectResp { args, .. } => match args {
1415 DirectMsgArgs::Args32(_) => Some(FuncId::MsgSendDirectResp32),
1416 DirectMsgArgs::Args64(_) => Some(FuncId::MsgSendDirectResp64),
Tomás González4d5b0ba2025-03-03 17:15:55 +00001417 DirectMsgArgs::VersionResp { .. } => Some(FuncId::MsgSendDirectResp32),
1418 DirectMsgArgs::PowerPsciResp { .. } => Some(FuncId::MsgSendDirectResp32),
1419 DirectMsgArgs::VmCreatedAck { .. } => Some(FuncId::MsgSendDirectResp32),
1420 DirectMsgArgs::VmDestructedAck { .. } => Some(FuncId::MsgSendDirectResp32),
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001421 _ => panic!("Invalid direct response arguments: {:#?}", args),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001422 },
1423 Interface::MsgSendDirectReq2 { .. } => Some(FuncId::MsgSendDirectReq64_2),
1424 Interface::MsgSendDirectResp2 { .. } => Some(FuncId::MsgSendDirectResp64_2),
1425 Interface::MemDonate { buf, .. } => match buf {
1426 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemDonate64),
1427 _ => Some(FuncId::MemDonate32),
1428 },
1429 Interface::MemLend { buf, .. } => match buf {
1430 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemLend64),
1431 _ => Some(FuncId::MemLend32),
1432 },
1433 Interface::MemShare { buf, .. } => match buf {
1434 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemShare64),
1435 _ => Some(FuncId::MemShare32),
1436 },
1437 Interface::MemRetrieveReq { buf, .. } => match buf {
1438 Some(MemOpBuf::Buf64 { .. }) => Some(FuncId::MemRetrieveReq64),
1439 _ => Some(FuncId::MemRetrieveReq32),
1440 },
1441 Interface::MemRetrieveResp { .. } => Some(FuncId::MemRetrieveResp),
1442 Interface::MemRelinquish => Some(FuncId::MemRelinquish),
1443 Interface::MemReclaim { .. } => Some(FuncId::MemReclaim),
1444 Interface::MemPermGet { addr, .. } => match addr {
1445 MemAddr::Addr32(_) => Some(FuncId::MemPermGet32),
1446 MemAddr::Addr64(_) => Some(FuncId::MemPermGet64),
1447 },
1448 Interface::MemPermSet { addr, .. } => match addr {
1449 MemAddr::Addr32(_) => Some(FuncId::MemPermSet32),
1450 MemAddr::Addr64(_) => Some(FuncId::MemPermSet64),
1451 },
Imre Kis189f18c2025-05-26 19:33:05 +02001452 Interface::ConsoleLog { chars, .. } => match chars {
1453 ConsoleLogChars::Chars32(_) => Some(FuncId::ConsoleLog32),
1454 ConsoleLogChars::Chars64(_) => Some(FuncId::ConsoleLog64),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001455 },
Tomás González7ffb6132025-04-03 12:28:58 +01001456 Interface::NotificationBitmapCreate { .. } => Some(FuncId::NotificationBitmapCreate),
1457 Interface::NotificationBitmapDestroy { .. } => Some(FuncId::NotificationBitmapDestroy),
1458 Interface::NotificationBind { .. } => Some(FuncId::NotificationBind),
Imre Kis3571f2c2025-05-26 19:29:23 +02001459 Interface::NotificationUnbind { .. } => Some(FuncId::NotificationUnbind),
Tomás González7ffb6132025-04-03 12:28:58 +01001460 Interface::NotificationSet { .. } => Some(FuncId::NotificationSet),
1461 Interface::NotificationGet { .. } => Some(FuncId::NotificationGet),
1462 Interface::NotificationInfoGet { is_32bit } => match is_32bit {
1463 true => Some(FuncId::NotificationInfoGet32),
1464 false => Some(FuncId::NotificationInfoGet64),
1465 },
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01001466 Interface::El3IntrHandle => Some(FuncId::El3IntrHandle),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001467 }
1468 }
Balint Dobszay3aad9572025-01-17 16:54:11 +01001469
Balint Dobszayde0dc802025-02-28 14:16:52 +01001470 /// Returns true if this is a 32-bit call, or false if it is a 64-bit call.
1471 pub fn is_32bit(&self) -> bool {
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001472 if matches!(self, Self::VersionOut { .. }) {
1473 return true;
1474 }
1475
Balint Dobszayde0dc802025-02-28 14:16:52 +01001476 self.function_id().unwrap().is_32bit()
1477 }
1478
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001479 /// Returns the FF-A version that has introduced the function ID.
1480 pub fn minimum_ffa_version(&self) -> Version {
Balint Dobszay3c1c89a2025-04-25 17:36:46 +02001481 if matches!(self, Self::VersionOut { .. }) {
1482 return Version(1, 0);
1483 }
1484
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001485 self.function_id().unwrap().minimum_ffa_version()
1486 }
1487
Balint Dobszayde0dc802025-02-28 14:16:52 +01001488 /// Parse interface from register contents. The caller must ensure that the `regs` argument has
1489 /// the correct length: 8 registers for FF-A v1.1 and lower, 18 registers for v1.2 and higher.
1490 pub fn from_regs(version: Version, regs: &[u64]) -> Result<Self, Error> {
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001491 let func_id = FuncId::try_from(regs[0] as u32)?;
1492 if version < func_id.minimum_ffa_version() {
1493 return Err(Error::InvalidVersionForFunctionId(version, func_id));
1494 }
1495
Balint Dobszayde0dc802025-02-28 14:16:52 +01001496 let reg_cnt = regs.len();
1497
1498 let msg = match reg_cnt {
1499 8 => {
1500 assert!(version <= Version(1, 1));
1501 Interface::unpack_regs8(version, regs.try_into().unwrap())?
1502 }
1503 18 => {
1504 assert!(version >= Version(1, 2));
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001505 match func_id {
Balint Dobszayde0dc802025-02-28 14:16:52 +01001506 FuncId::ConsoleLog64
1507 | FuncId::Success64
1508 | FuncId::MsgSendDirectReq64_2
Tomás González0a058bc2025-03-11 11:20:55 +00001509 | FuncId::MsgSendDirectResp64_2
1510 | FuncId::PartitionInfoGetRegs => {
Balint Dobszayde0dc802025-02-28 14:16:52 +01001511 Interface::unpack_regs18(version, regs.try_into().unwrap())?
1512 }
1513 _ => Interface::unpack_regs8(version, regs[..8].try_into().unwrap())?,
1514 }
1515 }
1516 _ => panic!(
1517 "Invalid number of registers ({}) for FF-A version {}",
1518 reg_cnt, version
1519 ),
1520 };
1521
1522 Ok(msg)
1523 }
1524
1525 fn unpack_regs8(version: Version, regs: &[u64; 8]) -> Result<Self, Error> {
Balint Dobszay3aad9572025-01-17 16:54:11 +01001526 let fid = FuncId::try_from(regs[0] as u32)?;
1527
1528 let msg = match fid {
1529 FuncId::Error => Self::Error {
1530 target_info: (regs[1] as u32).into(),
1531 error_code: FfaError::try_from(regs[2] as i32)?,
Balint Dobszayb727aab2025-04-07 10:24:59 +02001532 error_arg: regs[3] as u32,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001533 },
1534 FuncId::Success32 => Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02001535 target_info: (regs[1] as u32).into(),
Imre Kis54773b62025-04-10 13:47:39 +02001536 args: SuccessArgs::Args32([
Balint Dobszay3aad9572025-01-17 16:54:11 +01001537 regs[2] as u32,
1538 regs[3] as u32,
1539 regs[4] as u32,
1540 regs[5] as u32,
1541 regs[6] as u32,
1542 regs[7] as u32,
1543 ]),
1544 },
1545 FuncId::Success64 => Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02001546 target_info: (regs[1] as u32).into(),
Imre Kis54773b62025-04-10 13:47:39 +02001547 args: SuccessArgs::Args64([regs[2], regs[3], regs[4], regs[5], regs[6], regs[7]]),
Balint Dobszay3aad9572025-01-17 16:54:11 +01001548 },
1549 FuncId::Interrupt => Self::Interrupt {
1550 target_info: (regs[1] as u32).into(),
1551 interrupt_id: regs[2] as u32,
1552 },
1553 FuncId::Version => Self::Version {
Tomás González83146af2025-03-04 11:32:41 +00001554 input_version: (regs[1] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001555 },
1556 FuncId::Features => Self::Features {
Balint Dobszayc31e0b92025-03-03 20:16:56 +01001557 feat_id: (regs[1] as u32).into(),
Balint Dobszay3aad9572025-01-17 16:54:11 +01001558 input_properties: regs[2] as u32,
1559 },
1560 FuncId::RxAcquire => Self::RxAcquire {
1561 vm_id: regs[1] as u16,
1562 },
1563 FuncId::RxRelease => Self::RxRelease {
1564 vm_id: regs[1] as u16,
1565 },
1566 FuncId::RxTxMap32 => {
1567 let addr = RxTxAddr::Addr32 {
1568 rx: regs[2] as u32,
1569 tx: regs[1] as u32,
1570 };
1571 let page_cnt = regs[3] as u32;
1572
1573 Self::RxTxMap { addr, page_cnt }
1574 }
1575 FuncId::RxTxMap64 => {
1576 let addr = RxTxAddr::Addr64 {
1577 rx: regs[2],
1578 tx: regs[1],
1579 };
1580 let page_cnt = regs[3] as u32;
1581
1582 Self::RxTxMap { addr, page_cnt }
1583 }
1584 FuncId::RxTxUnmap => Self::RxTxUnmap { id: regs[1] as u16 },
1585 FuncId::PartitionInfoGet => {
1586 let uuid_words = [
1587 regs[1] as u32,
1588 regs[2] as u32,
1589 regs[3] as u32,
1590 regs[4] as u32,
1591 ];
1592 let mut bytes: [u8; 16] = [0; 16];
1593 for (i, b) in uuid_words.iter().flat_map(|w| w.to_le_bytes()).enumerate() {
1594 bytes[i] = b;
1595 }
1596 Self::PartitionInfoGet {
1597 uuid: Uuid::from_bytes(bytes),
Imre Kise295adb2025-04-10 13:26:28 +02001598 flags: PartitionInfoGetFlags::try_from(regs[5] as u32)?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001599 }
1600 }
1601 FuncId::IdGet => Self::IdGet,
1602 FuncId::SpmIdGet => Self::SpmIdGet,
Tomás González092202a2025-03-05 11:56:45 +00001603 FuncId::MsgWait => Self::MsgWait {
1604 flags: if version >= Version(1, 2) {
1605 Some(MsgWaitFlags::try_from(regs[2] as u32)?)
1606 } else {
1607 None
1608 },
1609 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001610 FuncId::Yield => Self::Yield,
1611 FuncId::Run => Self::Run {
1612 target_info: (regs[1] as u32).into(),
1613 },
1614 FuncId::NormalWorldResume => Self::NormalWorldResume,
Tomás González17b92442025-03-10 16:45:04 +00001615 FuncId::SecondaryEpRegister32 => Self::SecondaryEpRegister {
1616 entrypoint: SecondaryEpRegisterAddr::Addr32(regs[1] as u32),
1617 },
1618 FuncId::SecondaryEpRegister64 => Self::SecondaryEpRegister {
1619 entrypoint: SecondaryEpRegisterAddr::Addr64(regs[1]),
1620 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001621 FuncId::MsgSend2 => Self::MsgSend2 {
1622 sender_vm_id: regs[1] as u16,
Imre Kisa2fd69b2025-06-13 13:39:47 +02001623 flags: (regs[2] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001624 },
1625 FuncId::MsgSendDirectReq32 => Self::MsgSendDirectReq {
1626 src_id: (regs[1] >> 16) as u16,
1627 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001628 args: if (regs[2] as u32 & DirectMsgArgs::FWK_MSG_BITS) != 0 {
1629 match regs[2] as u32 {
1630 DirectMsgArgs::VERSION_REQ => DirectMsgArgs::VersionReq {
1631 version: Version::try_from(regs[3] as u32)?,
1632 },
1633 DirectMsgArgs::POWER_PSCI_REQ => DirectMsgArgs::PowerPsciReq32 {
Tomás González67f92c72025-03-20 16:50:42 +00001634 params: [
1635 regs[3] as u32,
1636 regs[4] as u32,
1637 regs[5] as u32,
1638 regs[6] as u32,
1639 ],
Tomás González4d5b0ba2025-03-03 17:15:55 +00001640 },
1641 DirectMsgArgs::POWER_WARM_BOOT_REQ => DirectMsgArgs::PowerWarmBootReq {
1642 boot_type: WarmBootType::try_from(regs[3] as u32)?,
1643 },
1644 DirectMsgArgs::VM_CREATED => DirectMsgArgs::VmCreated {
1645 handle: memory_management::Handle::from([
1646 regs[3] as u32,
1647 regs[4] as u32,
1648 ]),
1649 vm_id: regs[5] as u16,
1650 },
1651 DirectMsgArgs::VM_DESTRUCTED => DirectMsgArgs::VmDestructed {
1652 handle: memory_management::Handle::from([
1653 regs[3] as u32,
1654 regs[4] as u32,
1655 ]),
1656 vm_id: regs[5] as u16,
1657 },
1658 _ => return Err(Error::UnrecognisedFwkMsg(regs[2] as u32)),
1659 }
1660 } else {
1661 DirectMsgArgs::Args32([
1662 regs[3] as u32,
1663 regs[4] as u32,
1664 regs[5] as u32,
1665 regs[6] as u32,
1666 regs[7] as u32,
1667 ])
1668 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001669 },
1670 FuncId::MsgSendDirectReq64 => Self::MsgSendDirectReq {
1671 src_id: (regs[1] >> 16) as u16,
1672 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001673 args: if (regs[2] & DirectMsgArgs::FWK_MSG_BITS as u64) != 0 {
1674 match regs[2] as u32 {
1675 DirectMsgArgs::POWER_PSCI_REQ => DirectMsgArgs::PowerPsciReq64 {
Tomás González67f92c72025-03-20 16:50:42 +00001676 params: [regs[3], regs[4], regs[5], regs[6]],
Tomás González4d5b0ba2025-03-03 17:15:55 +00001677 },
1678 _ => return Err(Error::UnrecognisedFwkMsg(regs[2] as u32)),
1679 }
1680 } else {
1681 DirectMsgArgs::Args64([regs[3], regs[4], regs[5], regs[6], regs[7]])
1682 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001683 },
1684 FuncId::MsgSendDirectResp32 => Self::MsgSendDirectResp {
1685 src_id: (regs[1] >> 16) as u16,
1686 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001687 args: if (regs[2] as u32 & DirectMsgArgs::FWK_MSG_BITS) != 0 {
1688 match regs[2] as u32 {
1689 DirectMsgArgs::VERSION_RESP => {
1690 if regs[3] as i32 == FfaError::NotSupported.into() {
1691 DirectMsgArgs::VersionResp { version: None }
1692 } else {
1693 DirectMsgArgs::VersionResp {
1694 version: Some(Version::try_from(regs[3] as u32)?),
1695 }
1696 }
1697 }
1698 DirectMsgArgs::POWER_PSCI_RESP => DirectMsgArgs::PowerPsciResp {
1699 psci_status: regs[3] as i32,
1700 },
1701 DirectMsgArgs::VM_CREATED_ACK => DirectMsgArgs::VmCreatedAck {
1702 sp_status: (regs[3] as i32).try_into()?,
1703 },
1704 DirectMsgArgs::VM_DESTRUCTED_ACK => DirectMsgArgs::VmDestructedAck {
1705 sp_status: (regs[3] as i32).try_into()?,
1706 },
1707 _ => return Err(Error::UnrecognisedFwkMsg(regs[2] as u32)),
1708 }
1709 } else {
1710 DirectMsgArgs::Args32([
1711 regs[3] as u32,
1712 regs[4] as u32,
1713 regs[5] as u32,
1714 regs[6] as u32,
1715 regs[7] as u32,
1716 ])
1717 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001718 },
1719 FuncId::MsgSendDirectResp64 => Self::MsgSendDirectResp {
1720 src_id: (regs[1] >> 16) as u16,
1721 dst_id: regs[1] as u16,
Tomás González4d5b0ba2025-03-03 17:15:55 +00001722 args: if (regs[2] & DirectMsgArgs::FWK_MSG_BITS as u64) != 0 {
1723 return Err(Error::UnrecognisedFwkMsg(regs[2] as u32));
1724 } else {
1725 DirectMsgArgs::Args64([regs[3], regs[4], regs[5], regs[6], regs[7]])
1726 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001727 },
1728 FuncId::MemDonate32 => Self::MemDonate {
1729 total_len: regs[1] as u32,
1730 frag_len: regs[2] as u32,
1731 buf: if regs[3] != 0 && regs[4] != 0 {
1732 Some(MemOpBuf::Buf32 {
1733 addr: regs[3] as u32,
1734 page_cnt: regs[4] as u32,
1735 })
1736 } else {
1737 None
1738 },
1739 },
1740 FuncId::MemDonate64 => Self::MemDonate {
1741 total_len: regs[1] as u32,
1742 frag_len: regs[2] as u32,
1743 buf: if regs[3] != 0 && regs[4] != 0 {
1744 Some(MemOpBuf::Buf64 {
1745 addr: regs[3],
1746 page_cnt: regs[4] as u32,
1747 })
1748 } else {
1749 None
1750 },
1751 },
1752 FuncId::MemLend32 => Self::MemLend {
1753 total_len: regs[1] as u32,
1754 frag_len: regs[2] as u32,
1755 buf: if regs[3] != 0 && regs[4] != 0 {
1756 Some(MemOpBuf::Buf32 {
1757 addr: regs[3] as u32,
1758 page_cnt: regs[4] as u32,
1759 })
1760 } else {
1761 None
1762 },
1763 },
1764 FuncId::MemLend64 => Self::MemLend {
1765 total_len: regs[1] as u32,
1766 frag_len: regs[2] as u32,
1767 buf: if regs[3] != 0 && regs[4] != 0 {
1768 Some(MemOpBuf::Buf64 {
1769 addr: regs[3],
1770 page_cnt: regs[4] as u32,
1771 })
1772 } else {
1773 None
1774 },
1775 },
1776 FuncId::MemShare32 => Self::MemShare {
1777 total_len: regs[1] as u32,
1778 frag_len: regs[2] as u32,
1779 buf: if regs[3] != 0 && regs[4] != 0 {
1780 Some(MemOpBuf::Buf32 {
1781 addr: regs[3] as u32,
1782 page_cnt: regs[4] as u32,
1783 })
1784 } else {
1785 None
1786 },
1787 },
1788 FuncId::MemShare64 => Self::MemShare {
1789 total_len: regs[1] as u32,
1790 frag_len: regs[2] as u32,
1791 buf: if regs[3] != 0 && regs[4] != 0 {
1792 Some(MemOpBuf::Buf64 {
1793 addr: regs[3],
1794 page_cnt: regs[4] as u32,
1795 })
1796 } else {
1797 None
1798 },
1799 },
1800 FuncId::MemRetrieveReq32 => Self::MemRetrieveReq {
1801 total_len: regs[1] as u32,
1802 frag_len: regs[2] as u32,
1803 buf: if regs[3] != 0 && regs[4] != 0 {
1804 Some(MemOpBuf::Buf32 {
1805 addr: regs[3] as u32,
1806 page_cnt: regs[4] as u32,
1807 })
1808 } else {
1809 None
1810 },
1811 },
1812 FuncId::MemRetrieveReq64 => Self::MemRetrieveReq {
1813 total_len: regs[1] as u32,
1814 frag_len: regs[2] as u32,
1815 buf: if regs[3] != 0 && regs[4] != 0 {
1816 Some(MemOpBuf::Buf64 {
1817 addr: regs[3],
1818 page_cnt: regs[4] as u32,
1819 })
1820 } else {
1821 None
1822 },
1823 },
1824 FuncId::MemRetrieveResp => Self::MemRetrieveResp {
1825 total_len: regs[1] as u32,
1826 frag_len: regs[2] as u32,
1827 },
1828 FuncId::MemRelinquish => Self::MemRelinquish,
1829 FuncId::MemReclaim => Self::MemReclaim {
1830 handle: memory_management::Handle::from([regs[1] as u32, regs[2] as u32]),
Imre Kis356395d2025-06-13 13:49:06 +02001831 flags: (regs[3] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001832 },
1833 FuncId::MemPermGet32 => Self::MemPermGet {
1834 addr: MemAddr::Addr32(regs[1] as u32),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001835 page_cnt: if version >= Version(1, 3) {
1836 Some(regs[2] as u32)
1837 } else {
1838 None
1839 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001840 },
1841 FuncId::MemPermGet64 => Self::MemPermGet {
1842 addr: MemAddr::Addr64(regs[1]),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001843 page_cnt: if version >= Version(1, 3) {
1844 Some(regs[2] as u32)
1845 } else {
1846 None
1847 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01001848 },
1849 FuncId::MemPermSet32 => Self::MemPermSet {
1850 addr: MemAddr::Addr32(regs[1] as u32),
1851 page_cnt: regs[2] as u32,
Imre Kisdcb7df22025-06-06 15:24:40 +02001852 mem_perm: (regs[3] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001853 },
1854 FuncId::MemPermSet64 => Self::MemPermSet {
1855 addr: MemAddr::Addr64(regs[1]),
1856 page_cnt: regs[2] as u32,
Imre Kisdcb7df22025-06-06 15:24:40 +02001857 mem_perm: (regs[3] as u32).try_into()?,
Balint Dobszay3aad9572025-01-17 16:54:11 +01001858 },
Imre Kis189f18c2025-05-26 19:33:05 +02001859 FuncId::ConsoleLog32 => {
1860 let char_cnt = regs[1] as u8;
1861 if char_cnt > ConsoleLogChars32::MAX_LENGTH {
1862 return Err(Error::InvalidCharacterCount(char_cnt));
1863 }
1864
1865 Self::ConsoleLog {
1866 chars: ConsoleLogChars::Chars32(ConsoleLogChars32 {
1867 char_cnt,
1868 char_lists: [
1869 regs[2] as u32,
1870 regs[3] as u32,
1871 regs[4] as u32,
1872 regs[5] as u32,
1873 regs[6] as u32,
1874 regs[7] as u32,
1875 ],
1876 }),
1877 }
1878 }
Tomás González7ffb6132025-04-03 12:28:58 +01001879 FuncId::NotificationBitmapCreate => {
1880 let tentative_vm_id = regs[1] as u32;
1881 if (tentative_vm_id >> 16) != 0 {
1882 return Err(Error::InvalidVmId(tentative_vm_id));
1883 }
1884 Self::NotificationBitmapCreate {
1885 vm_id: tentative_vm_id as u16,
1886 vcpu_cnt: regs[2] as u32,
1887 }
1888 }
1889 FuncId::NotificationBitmapDestroy => {
1890 let tentative_vm_id = regs[1] as u32;
1891 if (tentative_vm_id >> 16) != 0 {
1892 return Err(Error::InvalidVmId(tentative_vm_id));
1893 }
1894 Self::NotificationBitmapDestroy {
1895 vm_id: tentative_vm_id as u16,
1896 }
1897 }
1898 FuncId::NotificationBind => Self::NotificationBind {
1899 sender_id: (regs[1] >> 16) as u16,
1900 receiver_id: regs[1] as u16,
1901 flags: (regs[2] as u32).into(),
1902 bitmap: (regs[4] << 32) | (regs[3] & 0xffff_ffff),
1903 },
Imre Kis3571f2c2025-05-26 19:29:23 +02001904 FuncId::NotificationUnbind => Self::NotificationUnbind {
Tomás González7ffb6132025-04-03 12:28:58 +01001905 sender_id: (regs[1] >> 16) as u16,
1906 receiver_id: regs[1] as u16,
1907 bitmap: (regs[4] << 32) | (regs[3] & 0xffff_ffff),
1908 },
1909 FuncId::NotificationSet => Self::NotificationSet {
1910 sender_id: (regs[1] >> 16) as u16,
1911 receiver_id: regs[1] as u16,
1912 flags: (regs[2] as u32).try_into()?,
1913 bitmap: (regs[4] << 32) | (regs[3] & 0xffff_ffff),
1914 },
1915 FuncId::NotificationGet => Self::NotificationGet {
1916 vcpu_id: (regs[1] >> 16) as u16,
1917 endpoint_id: regs[1] as u16,
1918 flags: (regs[2] as u32).into(),
1919 },
1920 FuncId::NotificationInfoGet32 => Self::NotificationInfoGet { is_32bit: true },
1921 FuncId::NotificationInfoGet64 => Self::NotificationInfoGet { is_32bit: false },
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01001922 FuncId::El3IntrHandle => Self::El3IntrHandle,
Balint Dobszayde0dc802025-02-28 14:16:52 +01001923 _ => panic!("Invalid number of registers (8) for function {:#x?}", fid),
Balint Dobszay3aad9572025-01-17 16:54:11 +01001924 };
1925
1926 Ok(msg)
1927 }
Balint Dobszay3aad9572025-01-17 16:54:11 +01001928
Balint Dobszayde0dc802025-02-28 14:16:52 +01001929 fn unpack_regs18(version: Version, regs: &[u64; 18]) -> Result<Self, Error> {
1930 assert!(version >= Version(1, 2));
Balint Dobszay5bf492f2024-07-29 17:21:32 +02001931
Balint Dobszayde0dc802025-02-28 14:16:52 +01001932 let fid = FuncId::try_from(regs[0] as u32)?;
1933
1934 let msg = match fid {
1935 FuncId::Success64 => Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02001936 target_info: (regs[1] as u32).into(),
Imre Kis54773b62025-04-10 13:47:39 +02001937 args: SuccessArgs::Args64_2(regs[2..18].try_into().unwrap()),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001938 },
1939 FuncId::MsgSendDirectReq64_2 => Self::MsgSendDirectReq2 {
1940 src_id: (regs[1] >> 16) as u16,
1941 dst_id: regs[1] as u16,
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00001942 uuid: Uuid::from_u64_pair(regs[2].swap_bytes(), regs[3].swap_bytes()),
Balint Dobszayde0dc802025-02-28 14:16:52 +01001943 args: DirectMsg2Args(regs[4..18].try_into().unwrap()),
1944 },
1945 FuncId::MsgSendDirectResp64_2 => Self::MsgSendDirectResp2 {
1946 src_id: (regs[1] >> 16) as u16,
1947 dst_id: regs[1] as u16,
1948 args: DirectMsg2Args(regs[4..18].try_into().unwrap()),
1949 },
Imre Kis189f18c2025-05-26 19:33:05 +02001950 FuncId::ConsoleLog64 => {
1951 let char_cnt = regs[1] as u8;
1952 if char_cnt > ConsoleLogChars64::MAX_LENGTH {
1953 return Err(Error::InvalidCharacterCount(char_cnt));
1954 }
1955
1956 Self::ConsoleLog {
1957 chars: ConsoleLogChars::Chars64(ConsoleLogChars64 {
1958 char_cnt,
1959 char_lists: regs[2..18].try_into().unwrap(),
1960 }),
1961 }
1962 }
Tomás González0a058bc2025-03-11 11:20:55 +00001963 FuncId::PartitionInfoGetRegs => {
1964 // Bits[15:0]: Start index
1965 let start_index = (regs[3] & 0xffff) as u16;
1966 let info_tag = ((regs[3] >> 16) & 0xffff) as u16;
1967 Self::PartitionInfoGetRegs {
1968 uuid: Uuid::from_u64_pair(regs[1].swap_bytes(), regs[2].swap_bytes()),
1969 start_index,
1970 info_tag: if start_index == 0 && info_tag != 0 {
1971 return Err(Error::InvalidInformationTag(info_tag));
1972 } else {
1973 info_tag
1974 },
1975 }
1976 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01001977 _ => panic!("Invalid number of registers (18) for function {:#x?}", fid),
1978 };
1979
1980 Ok(msg)
Balint Dobszay3aad9572025-01-17 16:54:11 +01001981 }
1982
Balint Dobszaya5846852025-02-26 15:38:53 +01001983 /// Create register contents for an interface.
Balint Dobszayde0dc802025-02-28 14:16:52 +01001984 pub fn to_regs(&self, version: Version, regs: &mut [u64]) {
Balint Dobszay82c71dd2025-04-15 10:16:44 +02001985 assert!(self.minimum_ffa_version() <= version);
1986
Balint Dobszayde0dc802025-02-28 14:16:52 +01001987 let reg_cnt = regs.len();
1988
1989 match reg_cnt {
1990 8 => {
1991 assert!(version <= Version(1, 1));
Balint Dobszay91bea9b2025-04-09 13:16:06 +02001992 regs.fill(0);
1993
Balint Dobszayde0dc802025-02-28 14:16:52 +01001994 self.pack_regs8(version, (&mut regs[..8]).try_into().unwrap());
1995 }
1996 18 => {
1997 assert!(version >= Version(1, 2));
Balint Dobszay91bea9b2025-04-09 13:16:06 +02001998 regs.fill(0);
Balint Dobszayde0dc802025-02-28 14:16:52 +01001999
2000 match self {
2001 Interface::ConsoleLog {
Imre Kis189f18c2025-05-26 19:33:05 +02002002 chars: ConsoleLogChars::Chars64(_),
Balint Dobszayde0dc802025-02-28 14:16:52 +01002003 ..
2004 }
2005 | Interface::Success {
Imre Kis54773b62025-04-10 13:47:39 +02002006 args: SuccessArgs::Args64_2(_),
Balint Dobszayde0dc802025-02-28 14:16:52 +01002007 ..
2008 }
2009 | Interface::MsgSendDirectReq2 { .. }
Tomás González0a058bc2025-03-11 11:20:55 +00002010 | Interface::MsgSendDirectResp2 { .. }
2011 | Interface::PartitionInfoGetRegs { .. } => {
Balint Dobszayde0dc802025-02-28 14:16:52 +01002012 self.pack_regs18(version, regs.try_into().unwrap());
2013 }
2014 _ => {
2015 self.pack_regs8(version, (&mut regs[..8]).try_into().unwrap());
2016 }
2017 }
2018 }
2019 _ => panic!("Invalid number of registers {}", reg_cnt),
2020 }
2021 }
2022
2023 fn pack_regs8(&self, version: Version, a: &mut [u64; 8]) {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002024 if let Some(function_id) = self.function_id() {
2025 a[0] = function_id as u64;
2026 }
2027
2028 match *self {
2029 Interface::Error {
2030 target_info,
2031 error_code,
Balint Dobszayb727aab2025-04-07 10:24:59 +02002032 error_arg,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002033 } => {
2034 a[1] = u32::from(target_info).into();
2035 a[2] = (error_code as u32).into();
Balint Dobszayb727aab2025-04-07 10:24:59 +02002036 a[3] = error_arg.into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002037 }
2038 Interface::Success { target_info, args } => {
Imre Kise521a282025-06-13 13:29:24 +02002039 a[1] = u32::from(target_info).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002040 match args {
Imre Kis54773b62025-04-10 13:47:39 +02002041 SuccessArgs::Args32(regs) => {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002042 a[2] = regs[0].into();
2043 a[3] = regs[1].into();
2044 a[4] = regs[2].into();
2045 a[5] = regs[3].into();
2046 a[6] = regs[4].into();
2047 a[7] = regs[5].into();
2048 }
Imre Kis54773b62025-04-10 13:47:39 +02002049 SuccessArgs::Args64(regs) => {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002050 a[2] = regs[0];
2051 a[3] = regs[1];
2052 a[4] = regs[2];
2053 a[5] = regs[3];
2054 a[6] = regs[4];
2055 a[7] = regs[5];
2056 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01002057 _ => panic!("{:#x?} requires 18 registers", args),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002058 }
2059 }
2060 Interface::Interrupt {
2061 target_info,
2062 interrupt_id,
2063 } => {
2064 a[1] = u32::from(target_info).into();
2065 a[2] = interrupt_id.into();
2066 }
2067 Interface::Version { input_version } => {
2068 a[1] = u32::from(input_version).into();
2069 }
2070 Interface::VersionOut { output_version } => {
2071 a[0] = u32::from(output_version).into();
2072 }
2073 Interface::Features {
2074 feat_id,
2075 input_properties,
2076 } => {
2077 a[1] = u32::from(feat_id).into();
2078 a[2] = input_properties.into();
2079 }
2080 Interface::RxAcquire { vm_id } => {
2081 a[1] = vm_id.into();
2082 }
2083 Interface::RxRelease { vm_id } => {
2084 a[1] = vm_id.into();
2085 }
2086 Interface::RxTxMap { addr, page_cnt } => {
2087 match addr {
2088 RxTxAddr::Addr32 { rx, tx } => {
2089 a[1] = tx.into();
2090 a[2] = rx.into();
2091 }
2092 RxTxAddr::Addr64 { rx, tx } => {
2093 a[1] = tx;
2094 a[2] = rx;
2095 }
2096 }
2097 a[3] = page_cnt.into();
2098 }
2099 Interface::RxTxUnmap { id } => {
2100 a[1] = id.into();
2101 }
2102 Interface::PartitionInfoGet { uuid, flags } => {
2103 let bytes = uuid.into_bytes();
2104 a[1] = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]).into();
2105 a[2] = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]).into();
2106 a[3] = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]).into();
2107 a[4] = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]).into();
Imre Kise295adb2025-04-10 13:26:28 +02002108 a[5] = u32::from(flags).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002109 }
Tomás González092202a2025-03-05 11:56:45 +00002110 Interface::MsgWait { flags } => {
2111 if version >= Version(1, 2) {
2112 if let Some(flags) = flags {
2113 a[2] = u32::from(flags).into();
2114 }
2115 }
2116 }
2117 Interface::IdGet | Interface::SpmIdGet | Interface::Yield => {}
Balint Dobszay3aad9572025-01-17 16:54:11 +01002118 Interface::Run { target_info } => {
2119 a[1] = u32::from(target_info).into();
2120 }
2121 Interface::NormalWorldResume => {}
Tomás González17b92442025-03-10 16:45:04 +00002122 Interface::SecondaryEpRegister { entrypoint } => match entrypoint {
2123 SecondaryEpRegisterAddr::Addr32(addr) => a[1] = addr as u64,
2124 SecondaryEpRegisterAddr::Addr64(addr) => a[1] = addr,
2125 },
Balint Dobszay3aad9572025-01-17 16:54:11 +01002126 Interface::MsgSend2 {
2127 sender_vm_id,
2128 flags,
2129 } => {
2130 a[1] = sender_vm_id.into();
Imre Kisa2fd69b2025-06-13 13:39:47 +02002131 a[2] = u32::from(flags).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002132 }
2133 Interface::MsgSendDirectReq {
2134 src_id,
2135 dst_id,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002136 args,
2137 } => {
Balint Dobszaye9a3e762025-02-26 17:29:57 +01002138 a[1] = ((src_id as u64) << 16) | dst_id as u64;
Balint Dobszay3aad9572025-01-17 16:54:11 +01002139 match args {
2140 DirectMsgArgs::Args32(args) => {
2141 a[3] = args[0].into();
2142 a[4] = args[1].into();
2143 a[5] = args[2].into();
2144 a[6] = args[3].into();
2145 a[7] = args[4].into();
2146 }
2147 DirectMsgArgs::Args64(args) => {
2148 a[3] = args[0];
2149 a[4] = args[1];
2150 a[5] = args[2];
2151 a[6] = args[3];
2152 a[7] = args[4];
2153 }
Tomás González4d5b0ba2025-03-03 17:15:55 +00002154 DirectMsgArgs::VersionReq { version } => {
2155 a[2] = DirectMsgArgs::VERSION_REQ.into();
2156 a[3] = u32::from(version).into();
2157 }
Tomás González67f92c72025-03-20 16:50:42 +00002158 DirectMsgArgs::PowerPsciReq32 { params } => {
Tomás González4d5b0ba2025-03-03 17:15:55 +00002159 a[2] = DirectMsgArgs::POWER_PSCI_REQ.into();
Tomás González67f92c72025-03-20 16:50:42 +00002160 a[3] = params[0].into();
2161 a[4] = params[1].into();
2162 a[5] = params[2].into();
2163 a[6] = params[3].into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002164 }
Tomás González67f92c72025-03-20 16:50:42 +00002165 DirectMsgArgs::PowerPsciReq64 { params } => {
Tomás González4d5b0ba2025-03-03 17:15:55 +00002166 a[2] = DirectMsgArgs::POWER_PSCI_REQ.into();
Tomás González67f92c72025-03-20 16:50:42 +00002167 a[3] = params[0];
2168 a[4] = params[1];
2169 a[5] = params[2];
2170 a[6] = params[3];
Tomás González4d5b0ba2025-03-03 17:15:55 +00002171 }
2172 DirectMsgArgs::PowerWarmBootReq { boot_type } => {
2173 a[2] = DirectMsgArgs::POWER_WARM_BOOT_REQ.into();
2174 a[3] = u32::from(boot_type).into();
2175 }
2176 DirectMsgArgs::VmCreated { handle, vm_id } => {
2177 a[2] = DirectMsgArgs::VM_CREATED.into();
2178 let handle_regs: [u32; 2] = handle.into();
2179 a[3] = handle_regs[0].into();
2180 a[4] = handle_regs[1].into();
2181 a[5] = vm_id.into();
2182 }
2183 DirectMsgArgs::VmDestructed { handle, vm_id } => {
2184 a[2] = DirectMsgArgs::VM_DESTRUCTED.into();
2185 let handle_regs: [u32; 2] = handle.into();
2186 a[3] = handle_regs[0].into();
2187 a[4] = handle_regs[1].into();
2188 a[5] = vm_id.into();
2189 }
2190 _ => panic!("Malformed MsgSendDirectReq interface"),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002191 }
2192 }
2193 Interface::MsgSendDirectResp {
2194 src_id,
2195 dst_id,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002196 args,
2197 } => {
Balint Dobszaye9a3e762025-02-26 17:29:57 +01002198 a[1] = ((src_id as u64) << 16) | dst_id as u64;
Balint Dobszay3aad9572025-01-17 16:54:11 +01002199 match args {
2200 DirectMsgArgs::Args32(args) => {
2201 a[3] = args[0].into();
2202 a[4] = args[1].into();
2203 a[5] = args[2].into();
2204 a[6] = args[3].into();
2205 a[7] = args[4].into();
2206 }
2207 DirectMsgArgs::Args64(args) => {
2208 a[3] = args[0];
2209 a[4] = args[1];
2210 a[5] = args[2];
2211 a[6] = args[3];
2212 a[7] = args[4];
2213 }
Tomás González4d5b0ba2025-03-03 17:15:55 +00002214 DirectMsgArgs::VersionResp { version } => {
2215 a[2] = DirectMsgArgs::VERSION_RESP.into();
2216 match version {
Tomás González67f92c72025-03-20 16:50:42 +00002217 None => a[3] = (i32::from(FfaError::NotSupported) as u32).into(),
Tomás González4d5b0ba2025-03-03 17:15:55 +00002218 Some(ver) => a[3] = u32::from(ver).into(),
2219 }
2220 }
2221 DirectMsgArgs::PowerPsciResp { psci_status } => {
2222 a[2] = DirectMsgArgs::POWER_PSCI_RESP.into();
Imre Kisb2d3c882025-04-11 14:19:35 +02002223 a[3] = (psci_status as u32).into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002224 }
2225 DirectMsgArgs::VmCreatedAck { sp_status } => {
2226 a[2] = DirectMsgArgs::VM_CREATED_ACK.into();
Tomás González67f92c72025-03-20 16:50:42 +00002227 a[3] = (i32::from(sp_status) as u32).into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002228 }
2229 DirectMsgArgs::VmDestructedAck { sp_status } => {
2230 a[2] = DirectMsgArgs::VM_DESTRUCTED_ACK.into();
Tomás González67f92c72025-03-20 16:50:42 +00002231 a[3] = (i32::from(sp_status) as u32).into();
Tomás González4d5b0ba2025-03-03 17:15:55 +00002232 }
2233 _ => panic!("Malformed MsgSendDirectResp interface"),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002234 }
2235 }
2236 Interface::MemDonate {
2237 total_len,
2238 frag_len,
2239 buf,
2240 } => {
2241 a[1] = total_len.into();
2242 a[2] = frag_len.into();
2243 (a[3], a[4]) = match buf {
2244 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2245 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2246 None => (0, 0),
2247 };
2248 }
2249 Interface::MemLend {
2250 total_len,
2251 frag_len,
2252 buf,
2253 } => {
2254 a[1] = total_len.into();
2255 a[2] = frag_len.into();
2256 (a[3], a[4]) = match buf {
2257 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2258 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2259 None => (0, 0),
2260 };
2261 }
2262 Interface::MemShare {
2263 total_len,
2264 frag_len,
2265 buf,
2266 } => {
2267 a[1] = total_len.into();
2268 a[2] = frag_len.into();
2269 (a[3], a[4]) = match buf {
2270 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2271 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2272 None => (0, 0),
2273 };
2274 }
2275 Interface::MemRetrieveReq {
2276 total_len,
2277 frag_len,
2278 buf,
2279 } => {
2280 a[1] = total_len.into();
2281 a[2] = frag_len.into();
2282 (a[3], a[4]) = match buf {
2283 Some(MemOpBuf::Buf32 { addr, page_cnt }) => (addr.into(), page_cnt.into()),
2284 Some(MemOpBuf::Buf64 { addr, page_cnt }) => (addr, page_cnt.into()),
2285 None => (0, 0),
2286 };
2287 }
2288 Interface::MemRetrieveResp {
2289 total_len,
2290 frag_len,
2291 } => {
2292 a[1] = total_len.into();
2293 a[2] = frag_len.into();
2294 }
2295 Interface::MemRelinquish => {}
2296 Interface::MemReclaim { handle, flags } => {
2297 let handle_regs: [u32; 2] = handle.into();
2298 a[1] = handle_regs[0].into();
2299 a[2] = handle_regs[1].into();
Imre Kis356395d2025-06-13 13:49:06 +02002300 a[3] = u32::from(flags).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002301 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01002302 Interface::MemPermGet { addr, page_cnt } => {
Balint Dobszay3aad9572025-01-17 16:54:11 +01002303 a[1] = match addr {
2304 MemAddr::Addr32(addr) => addr.into(),
2305 MemAddr::Addr64(addr) => addr,
2306 };
Balint Dobszayde0dc802025-02-28 14:16:52 +01002307 a[2] = if version >= Version(1, 3) {
2308 page_cnt.unwrap().into()
2309 } else {
2310 assert!(page_cnt.is_none());
2311 0
2312 }
Balint Dobszay3aad9572025-01-17 16:54:11 +01002313 }
2314 Interface::MemPermSet {
2315 addr,
2316 page_cnt,
2317 mem_perm,
2318 } => {
2319 a[1] = match addr {
2320 MemAddr::Addr32(addr) => addr.into(),
2321 MemAddr::Addr64(addr) => addr,
2322 };
2323 a[2] = page_cnt.into();
Imre Kisdcb7df22025-06-06 15:24:40 +02002324 a[3] = u32::from(mem_perm).into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002325 }
Imre Kis189f18c2025-05-26 19:33:05 +02002326 Interface::ConsoleLog { chars } => match chars {
2327 ConsoleLogChars::Chars32(ConsoleLogChars32 {
2328 char_cnt,
2329 char_lists,
2330 }) => {
2331 a[1] = char_cnt.into();
2332 a[2] = char_lists[0].into();
2333 a[3] = char_lists[1].into();
2334 a[4] = char_lists[2].into();
2335 a[5] = char_lists[3].into();
2336 a[6] = char_lists[4].into();
2337 a[7] = char_lists[5].into();
Balint Dobszay3aad9572025-01-17 16:54:11 +01002338 }
Imre Kis189f18c2025-05-26 19:33:05 +02002339 _ => panic!("{:#x?} requires 18 registers", chars),
2340 },
Tomás González7ffb6132025-04-03 12:28:58 +01002341 Interface::NotificationBitmapCreate { vm_id, vcpu_cnt } => {
2342 a[1] = vm_id.into();
2343 a[2] = vcpu_cnt.into();
2344 }
2345 Interface::NotificationBitmapDestroy { vm_id } => {
2346 a[1] = vm_id.into();
2347 }
2348 Interface::NotificationBind {
2349 sender_id,
2350 receiver_id,
2351 flags,
2352 bitmap,
2353 } => {
2354 a[1] = (u64::from(sender_id) << 16) | u64::from(receiver_id);
2355 a[2] = u32::from(flags).into();
2356 a[3] = bitmap & 0xffff_ffff;
2357 a[4] = bitmap >> 32;
2358 }
Imre Kis3571f2c2025-05-26 19:29:23 +02002359 Interface::NotificationUnbind {
Tomás González7ffb6132025-04-03 12:28:58 +01002360 sender_id,
2361 receiver_id,
2362 bitmap,
2363 } => {
2364 a[1] = (u64::from(sender_id) << 16) | u64::from(receiver_id);
2365 a[3] = bitmap & 0xffff_ffff;
2366 a[4] = bitmap >> 32;
2367 }
2368 Interface::NotificationSet {
2369 sender_id,
2370 receiver_id,
2371 flags,
2372 bitmap,
2373 } => {
2374 a[1] = (u64::from(sender_id) << 16) | u64::from(receiver_id);
2375 a[2] = u32::from(flags).into();
2376 a[3] = bitmap & 0xffff_ffff;
2377 a[4] = bitmap >> 32;
2378 }
2379 Interface::NotificationGet {
2380 vcpu_id,
2381 endpoint_id,
2382 flags,
2383 } => {
2384 a[1] = (u64::from(vcpu_id) << 16) | u64::from(endpoint_id);
2385 a[2] = u32::from(flags).into();
2386 }
2387 Interface::NotificationInfoGet { .. } => {}
Tomás Gonzáleze6fe75f2025-04-04 09:46:50 +01002388 Interface::El3IntrHandle => {}
Balint Dobszayde0dc802025-02-28 14:16:52 +01002389 _ => panic!("{:#x?} requires 18 registers", self),
2390 }
2391 }
2392
2393 fn pack_regs18(&self, version: Version, a: &mut [u64; 18]) {
2394 assert!(version >= Version(1, 2));
2395
Balint Dobszayde0dc802025-02-28 14:16:52 +01002396 if let Some(function_id) = self.function_id() {
2397 a[0] = function_id as u64;
2398 }
2399
2400 match *self {
2401 Interface::Success { target_info, args } => {
Imre Kise521a282025-06-13 13:29:24 +02002402 a[1] = u32::from(target_info).into();
Balint Dobszayde0dc802025-02-28 14:16:52 +01002403 match args {
Imre Kis54773b62025-04-10 13:47:39 +02002404 SuccessArgs::Args64_2(regs) => a[2..18].copy_from_slice(&regs[..16]),
Balint Dobszayde0dc802025-02-28 14:16:52 +01002405 _ => panic!("{:#x?} requires 8 registers", args),
2406 }
2407 }
2408 Interface::MsgSendDirectReq2 {
2409 src_id,
2410 dst_id,
2411 uuid,
2412 args,
2413 } => {
2414 a[1] = ((src_id as u64) << 16) | dst_id as u64;
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002415 let (uuid_msb, uuid_lsb) = uuid.as_u64_pair();
2416 (a[2], a[3]) = (uuid_msb.swap_bytes(), uuid_lsb.swap_bytes());
Balint Dobszayde0dc802025-02-28 14:16:52 +01002417 a[4..18].copy_from_slice(&args.0[..14]);
2418 }
2419 Interface::MsgSendDirectResp2 {
2420 src_id,
2421 dst_id,
2422 args,
2423 } => {
2424 a[1] = ((src_id as u64) << 16) | dst_id as u64;
2425 a[2] = 0;
2426 a[3] = 0;
2427 a[4..18].copy_from_slice(&args.0[..14]);
2428 }
Imre Kis189f18c2025-05-26 19:33:05 +02002429 Interface::ConsoleLog { chars: char_lists } => match char_lists {
2430 ConsoleLogChars::Chars64(ConsoleLogChars64 {
2431 char_cnt,
2432 char_lists,
2433 }) => {
2434 a[1] = char_cnt.into();
2435 a[2..18].copy_from_slice(&char_lists[..16])
Balint Dobszayde0dc802025-02-28 14:16:52 +01002436 }
Imre Kis189f18c2025-05-26 19:33:05 +02002437 _ => panic!("{:#x?} requires 8 registers", char_lists),
2438 },
Tomás González0a058bc2025-03-11 11:20:55 +00002439 Interface::PartitionInfoGetRegs {
2440 uuid,
2441 start_index,
2442 info_tag,
2443 } => {
2444 if start_index == 0 && info_tag != 0 {
2445 panic!("Information Tag MBZ if start index is 0: {:#x?}", self);
2446 }
2447 let (uuid_msb, uuid_lsb) = uuid.as_u64_pair();
2448 (a[1], a[2]) = (uuid_msb.swap_bytes(), uuid_lsb.swap_bytes());
2449 a[3] = (u64::from(info_tag) << 16) | u64::from(start_index);
2450 }
Balint Dobszayde0dc802025-02-28 14:16:52 +01002451 _ => panic!("{:#x?} requires 8 registers", self),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002452 }
2453 }
2454
Balint Dobszaya5846852025-02-26 15:38:53 +01002455 /// Helper function to create an `FFA_SUCCESS` interface without any arguments.
Balint Dobszay3aad9572025-01-17 16:54:11 +01002456 pub fn success32_noargs() -> Self {
2457 Self::Success {
Imre Kise521a282025-06-13 13:29:24 +02002458 target_info: TargetInfo::default(),
Imre Kis54773b62025-04-10 13:47:39 +02002459 args: SuccessArgs::Args32([0; 6]),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002460 }
2461 }
2462
Balint Dobszaya5846852025-02-26 15:38:53 +01002463 /// Helper function to create an `FFA_ERROR` interface with an error code.
Balint Dobszay3aad9572025-01-17 16:54:11 +01002464 pub fn error(error_code: FfaError) -> Self {
2465 Self::Error {
Imre Kise521a282025-06-13 13:29:24 +02002466 target_info: TargetInfo::default(),
Balint Dobszay3aad9572025-01-17 16:54:11 +01002467 error_code,
Balint Dobszayb727aab2025-04-07 10:24:59 +02002468 error_arg: 0,
Balint Dobszay3aad9572025-01-17 16:54:11 +01002469 }
2470 }
2471}
2472
Tomás González0a058bc2025-03-11 11:20:55 +00002473#[cfg(test)]
2474mod tests {
2475 use super::*;
2476
2477 #[test]
Balint Dobszay5ded5922025-06-13 12:06:53 +02002478 fn version_reg_count() {
2479 assert!(!Version(1, 1).needs_18_regs());
2480 assert!(Version(1, 2).needs_18_regs())
2481 }
2482
2483 #[test]
Tomás González0a058bc2025-03-11 11:20:55 +00002484 fn part_info_get_regs() {
2485 let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
2486 let uuid_bytes = uuid.as_bytes();
2487 let test_info_tag = 0b1101_1101;
2488 let test_start_index = 0b1101;
2489 let start_index_and_tag = (test_info_tag << 16) | test_start_index;
2490 let version = Version(1, 2);
2491
2492 // From spec:
2493 // Bytes[0...7] of UUID with byte 0 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002494 let reg_x1 = ((uuid_bytes[7] as u64) << 56)
2495 | ((uuid_bytes[6] as u64) << 48)
2496 | ((uuid_bytes[5] as u64) << 40)
2497 | ((uuid_bytes[4] as u64) << 32)
2498 | ((uuid_bytes[3] as u64) << 24)
2499 | ((uuid_bytes[2] as u64) << 16)
2500 | ((uuid_bytes[1] as u64) << 8)
Tomás González0a058bc2025-03-11 11:20:55 +00002501 | (uuid_bytes[0] as u64);
2502
2503 // From spec:
2504 // Bytes[8...15] of UUID with byte 8 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002505 let reg_x2 = ((uuid_bytes[15] as u64) << 56)
2506 | ((uuid_bytes[14] as u64) << 48)
2507 | ((uuid_bytes[13] as u64) << 40)
2508 | ((uuid_bytes[12] as u64) << 32)
2509 | ((uuid_bytes[11] as u64) << 24)
2510 | ((uuid_bytes[10] as u64) << 16)
2511 | ((uuid_bytes[9] as u64) << 8)
Tomás González0a058bc2025-03-11 11:20:55 +00002512 | (uuid_bytes[8] as u64);
2513
2514 // First, test for wrong tag:
2515 {
2516 let mut regs = [0u64; 18];
2517 regs[0] = FuncId::PartitionInfoGetRegs as u64;
2518 regs[1] = reg_x1;
2519 regs[2] = reg_x2;
2520 regs[3] = test_info_tag << 16;
2521
2522 assert!(Interface::from_regs(version, &regs).is_err_and(
2523 |e| e == Error::InvalidInformationTag(test_info_tag.try_into().unwrap())
2524 ));
2525 }
2526
2527 // Test for regs -> Interface -> regs
2528 {
2529 let mut orig_regs = [0u64; 18];
2530 orig_regs[0] = FuncId::PartitionInfoGetRegs as u64;
2531 orig_regs[1] = reg_x1;
2532 orig_regs[2] = reg_x2;
2533 orig_regs[3] = start_index_and_tag;
2534
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002535 let mut test_regs = orig_regs;
2536 let interface = Interface::from_regs(version, &test_regs).unwrap();
Tomás González0a058bc2025-03-11 11:20:55 +00002537 match &interface {
2538 Interface::PartitionInfoGetRegs {
2539 info_tag,
2540 start_index,
2541 uuid: int_uuid,
2542 } => {
2543 assert_eq!(u64::from(*info_tag), test_info_tag);
2544 assert_eq!(u64::from(*start_index), test_start_index);
2545 assert_eq!(*int_uuid, uuid);
2546 }
2547 _ => panic!("Expecting Interface::PartitionInfoGetRegs!"),
2548 }
2549 test_regs.fill(0);
2550 interface.to_regs(version, &mut test_regs);
2551 assert_eq!(orig_regs, test_regs);
2552 }
2553
2554 // Test for Interface -> regs -> Interface
2555 {
2556 let interface = Interface::PartitionInfoGetRegs {
2557 info_tag: test_info_tag.try_into().unwrap(),
2558 start_index: test_start_index.try_into().unwrap(),
2559 uuid,
2560 };
2561
2562 let mut regs: [u64; 18] = [0; 18];
2563 interface.to_regs(version, &mut regs);
2564
2565 assert_eq!(Some(FuncId::PartitionInfoGetRegs), interface.function_id());
2566 assert_eq!(regs[0], interface.function_id().unwrap() as u64);
2567 assert_eq!(regs[1], reg_x1);
2568 assert_eq!(regs[2], reg_x2);
2569 assert_eq!(regs[3], (test_info_tag << 16) | test_start_index);
2570
2571 assert_eq!(Interface::from_regs(version, &regs).unwrap(), interface);
2572 }
2573 }
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002574
2575 #[test]
2576 fn msg_send_direct_req2() {
2577 let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
2578 let uuid_bytes = uuid.as_bytes();
2579
2580 // From spec:
2581 // Bytes[0...7] of UUID with byte 0 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002582 let reg_x2 = ((uuid_bytes[7] as u64) << 56)
2583 | ((uuid_bytes[6] as u64) << 48)
2584 | ((uuid_bytes[5] as u64) << 40)
2585 | ((uuid_bytes[4] as u64) << 32)
2586 | ((uuid_bytes[3] as u64) << 24)
2587 | ((uuid_bytes[2] as u64) << 16)
2588 | ((uuid_bytes[1] as u64) << 8)
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002589 | (uuid_bytes[0] as u64);
2590
2591 // From spec:
2592 // Bytes[8...15] of UUID with byte 8 in the low-order bits.
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002593 let reg_x3 = ((uuid_bytes[15] as u64) << 56)
2594 | ((uuid_bytes[14] as u64) << 48)
2595 | ((uuid_bytes[13] as u64) << 40)
2596 | ((uuid_bytes[12] as u64) << 32)
2597 | ((uuid_bytes[11] as u64) << 24)
2598 | ((uuid_bytes[10] as u64) << 16)
2599 | ((uuid_bytes[9] as u64) << 8)
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002600 | (uuid_bytes[8] as u64);
2601
2602 let test_sender = 0b1101_1101;
2603 let test_receiver = 0b1101;
2604 let test_sender_receiver = (test_sender << 16) | test_receiver;
2605 let version = Version(1, 2);
2606
2607 // Test for regs -> Interface -> regs
2608 {
2609 let mut orig_regs = [0u64; 18];
2610 orig_regs[0] = FuncId::MsgSendDirectReq64_2 as u64;
2611 orig_regs[1] = test_sender_receiver;
2612 orig_regs[2] = reg_x2;
2613 orig_regs[3] = reg_x3;
2614
Balint Dobszayb2e9bed2025-04-15 12:57:36 +02002615 let mut test_regs = orig_regs;
2616 let interface = Interface::from_regs(version, &test_regs).unwrap();
Tomás Gonzálezce3bc222025-03-25 14:30:42 +00002617 match &interface {
2618 Interface::MsgSendDirectReq2 {
2619 dst_id,
2620 src_id,
2621 args: _,
2622 uuid: int_uuid,
2623 } => {
2624 assert_eq!(u64::from(*src_id), test_sender);
2625 assert_eq!(u64::from(*dst_id), test_receiver);
2626 assert_eq!(*int_uuid, uuid);
2627 }
2628 _ => panic!("Expecting Interface::MsgSendDirectReq2!"),
2629 }
2630 test_regs.fill(0);
2631 interface.to_regs(version, &mut test_regs);
2632 assert_eq!(orig_regs, test_regs);
2633 }
2634
2635 // Test for Interface -> regs -> Interface
2636 {
2637 let rest_of_regs: [u64; 14] = [0; 14];
2638
2639 let interface = Interface::MsgSendDirectReq2 {
2640 src_id: test_sender.try_into().unwrap(),
2641 dst_id: test_receiver.try_into().unwrap(),
2642 uuid,
2643 args: DirectMsg2Args(rest_of_regs),
2644 };
2645
2646 let mut regs: [u64; 18] = [0; 18];
2647 interface.to_regs(version, &mut regs);
2648
2649 assert_eq!(Some(FuncId::MsgSendDirectReq64_2), interface.function_id());
2650 assert_eq!(regs[0], interface.function_id().unwrap() as u64);
2651 assert_eq!(regs[1], test_sender_receiver);
2652 assert_eq!(regs[2], reg_x2);
2653 assert_eq!(regs[3], reg_x3);
2654 assert_eq!(regs[4], 0);
2655
2656 assert_eq!(Interface::from_regs(version, &regs).unwrap(), interface);
2657 }
2658 }
Tomás González6ccba0a2025-04-09 13:31:29 +01002659
2660 #[test]
2661 fn is_32bit() {
2662 let interface_64 = Interface::MsgSendDirectReq {
2663 src_id: 0,
2664 dst_id: 1,
2665 args: DirectMsgArgs::Args64([0, 0, 0, 0, 0]),
2666 };
2667 assert!(!interface_64.is_32bit());
2668
2669 let interface_32 = Interface::MsgSendDirectReq {
2670 src_id: 0,
2671 dst_id: 1,
2672 args: DirectMsgArgs::Args32([0, 0, 0, 0, 0]),
2673 };
2674 assert!(interface_32.is_32bit());
2675 }
Imre Kis787c5002025-04-10 14:25:51 +02002676
2677 #[test]
2678 fn success_args_notification_info_get32() {
2679 let mut notifications = SuccessArgsNotificationInfoGet32::default();
2680
2681 // 16.7.1.1 Example usage
2682 notifications.add_list(0x0000, &[0, 2, 3]).unwrap();
2683 notifications.add_list(0x0000, &[4, 6]).unwrap();
2684 notifications.add_list(0x0002, &[]).unwrap();
2685 notifications.add_list(0x0003, &[1]).unwrap();
2686
2687 let args: SuccessArgs = notifications.into();
2688 assert_eq!(
2689 SuccessArgs::Args32([
2690 0x0004_b200,
2691 0x0000_0000,
2692 0x0003_0002,
2693 0x0004_0000,
2694 0x0002_0006,
2695 0x0001_0003
2696 ]),
2697 args
2698 );
2699
2700 let notifications = SuccessArgsNotificationInfoGet32::try_from(args).unwrap();
2701 let mut iter = notifications.iter();
2702 assert_eq!(Some((0x0000, &[0, 2, 3][..])), iter.next());
2703 assert_eq!(Some((0x0000, &[4, 6][..])), iter.next());
2704 assert_eq!(Some((0x0002, &[][..])), iter.next());
2705 assert_eq!(Some((0x0003, &[1][..])), iter.next());
2706 }
2707
2708 #[test]
2709 fn success_args_notification_info_get64() {
2710 let mut notifications = SuccessArgsNotificationInfoGet64::default();
2711
2712 // 16.7.1.1 Example usage
2713 notifications.add_list(0x0000, &[0, 2, 3]).unwrap();
2714 notifications.add_list(0x0000, &[4, 6]).unwrap();
2715 notifications.add_list(0x0002, &[]).unwrap();
2716 notifications.add_list(0x0003, &[1]).unwrap();
2717
2718 let args: SuccessArgs = notifications.into();
2719 assert_eq!(
2720 SuccessArgs::Args64([
2721 0x0004_b200,
2722 0x0003_0002_0000_0000,
2723 0x0002_0006_0004_0000,
2724 0x0000_0000_0001_0003,
2725 0x0000_0000_0000_0000,
2726 0x0000_0000_0000_0000,
2727 ]),
2728 args
2729 );
2730
2731 let notifications = SuccessArgsNotificationInfoGet64::try_from(args).unwrap();
2732 let mut iter = notifications.iter();
2733 assert_eq!(Some((0x0000, &[0, 2, 3][..])), iter.next());
2734 assert_eq!(Some((0x0000, &[4, 6][..])), iter.next());
2735 assert_eq!(Some((0x0002, &[][..])), iter.next());
2736 assert_eq!(Some((0x0003, &[1][..])), iter.next());
2737 }
Tomás González0a058bc2025-03-11 11:20:55 +00002738}