blob: 05ecc6b1029234d3381c26bb5660b5fa45d42f2e [file] [log] [blame]
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000015use core::fmt;
16use core::result;
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000017
18/// Standard SMCCC TRNG error values as described in DEN 0098 1.0 REL0.
19#[derive(Debug, Clone)]
20pub enum Error {
21 /// The call is not supported by the implementation.
22 NotSupported,
23 /// One of the call parameters has a non-supported value.
24 InvalidParameter,
25 /// Call returned without the requested entropy bits.
26 NoEntropy,
27 /// Negative values indicate error.
28 Unknown(i64),
29 /// The call returned a positive value when 0 was expected.
30 Unexpected(u64),
31}
32
33impl fmt::Display for Error {
34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35 match self {
36 Self::NotSupported => write!(f, "SMCCC TRNG call not supported"),
37 Self::InvalidParameter => write!(f, "SMCCC TRNG call received non-supported value"),
38 Self::NoEntropy => write!(f, "SMCCC TRNG call returned no entropy"),
39 Self::Unexpected(v) => write!(f, "Unexpected SMCCC TRNG return value {} ({0:#x})", v),
40 Self::Unknown(e) => write!(f, "Unknown SMCCC TRNG return value {} ({0:#x})", e),
41 }
42 }
43}
44
45pub type Result<T> = result::Result<T, Error>;
46
47pub fn hvc64(function: u32, args: [u64; 17]) -> Result<[u64; 18]> {
48 let res = smccc::hvc64(function, args);
49 match res[0] as i64 {
50 ret if ret >= 0 => Ok(res),
51 -1 => Err(Error::NotSupported),
52 -2 => Err(Error::InvalidParameter),
53 -3 => Err(Error::NoEntropy),
54 ret => Err(Error::Unknown(ret)),
55 }
56}
57
58pub fn hvc64_expect_zero(function: u32, args: [u64; 17]) -> Result<[u64; 18]> {
59 let res = hvc64(function, args)?;
60 match res[0] {
61 0 => Ok(res),
62 v => Err(Error::Unexpected(v)),
63 }
64}