blob: 4086af7035c50a22e14a45fbe12deaa1523a8a9e [file] [log] [blame]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +01001// Copyright 2022, 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
15//! Support for the pvmfw configuration data format.
16
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010017use core::fmt;
18use core::mem;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +000019use core::ops::Range;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010020use core::result;
Alice Wangeacb7382023-06-05 12:53:54 +000021use vmbase::util::unchecked_align_up;
Alan Stokesa0e42962023-04-14 17:59:50 +010022use zerocopy::{FromBytes, LayoutVerified};
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010023
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000024/// Configuration data header.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010025#[repr(C, packed)]
Alan Stokesa0e42962023-04-14 17:59:50 +010026#[derive(Clone, Copy, Debug, FromBytes)]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010027struct Header {
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000028 /// Magic number; must be `Header::MAGIC`.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010029 magic: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000030 /// Version of the header format.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010031 version: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000032 /// Total size of the configuration data.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010033 total_size: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000034 /// Feature flags; currently reserved and must be zero.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010035 flags: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000036 /// (offset, size) pairs used to locate individual entries appended to the header.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010037 entries: [HeaderEntry; Entry::COUNT],
38}
39
40#[derive(Debug)]
41pub enum Error {
42 /// Reserved region can't fit configuration header.
43 BufferTooSmall,
Alan Stokesa0e42962023-04-14 17:59:50 +010044 /// Header has the wrong alignment
45 HeaderMisaligned,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010046 /// Header doesn't contain the expect magic value.
47 InvalidMagic,
48 /// Version of the header isn't supported.
49 UnsupportedVersion(u16, u16),
50 /// Header sets flags incorrectly or uses reserved flags.
51 InvalidFlags(u32),
52 /// Header describes configuration data that doesn't fit in the expected buffer.
53 InvalidSize(usize),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000054 /// Header entry is missing.
55 MissingEntry(Entry),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010056 /// Header entry is invalid.
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000057 InvalidEntry(Entry, EntryError),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010058}
59
60impl fmt::Display for Error {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 match self {
63 Self::BufferTooSmall => write!(f, "Reserved region is smaller than config header"),
Alan Stokesa0e42962023-04-14 17:59:50 +010064 Self::HeaderMisaligned => write!(f, "Reserved region is misaligned"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010065 Self::InvalidMagic => write!(f, "Wrong magic number"),
66 Self::UnsupportedVersion(x, y) => write!(f, "Version {x}.{y} not supported"),
67 Self::InvalidFlags(v) => write!(f, "Flags value {v:#x} is incorrect or reserved"),
68 Self::InvalidSize(sz) => write!(f, "Total size ({sz:#x}) overflows reserved region"),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000069 Self::MissingEntry(entry) => write!(f, "Mandatory {entry:?} entry is missing"),
70 Self::InvalidEntry(entry, e) => write!(f, "Invalid {entry:?} entry: {e}"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010071 }
72 }
73}
74
75pub type Result<T> = result::Result<T, Error>;
76
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000077#[derive(Debug)]
78pub enum EntryError {
79 /// Offset isn't between the fixed minimum value and size of configuration data.
80 InvalidOffset(usize),
81 /// Size must be zero when offset is and not be when it isn't.
82 InvalidSize(usize),
83 /// Entry isn't fully within the configuration data structure.
84 OutOfBounds { offset: usize, size: usize, limit: usize },
85}
86
87impl fmt::Display for EntryError {
88 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89 match self {
90 Self::InvalidOffset(offset) => write!(f, "Invalid offset: {offset:#x?}"),
91 Self::InvalidSize(sz) => write!(f, "Invalid size: {sz:#x?}"),
92 Self::OutOfBounds { offset, size, limit } => {
93 let range = Header::PADDED_SIZE..*limit;
94 let entry = *offset..(*offset + *size);
95 write!(f, "Out of bounds: {entry:#x?} must be within range {range:#x?}")
96 }
97 }
98 }
99}
100
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100101impl Header {
102 const MAGIC: u32 = u32::from_ne_bytes(*b"pvmf");
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +0000103 const VERSION_1_0: u32 = Self::version(1, 0);
Alice Wangeacb7382023-06-05 12:53:54 +0000104 const PADDED_SIZE: usize = unchecked_align_up(mem::size_of::<Self>(), mem::size_of::<u64>());
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100105
106 pub const fn version(major: u16, minor: u16) -> u32 {
107 ((major as u32) << 16) | (minor as u32)
108 }
109
110 pub const fn version_tuple(&self) -> (u16, u16) {
111 ((self.version >> 16) as u16, self.version as u16)
112 }
113
114 pub fn total_size(&self) -> usize {
115 self.total_size as usize
116 }
117
118 pub fn body_size(&self) -> usize {
119 self.total_size() - Self::PADDED_SIZE
120 }
121
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000122 fn get_body_range(&self, entry: Entry) -> Result<Option<Range<usize>>> {
123 let e = self.entries[entry as usize];
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000124 let offset = e.offset as usize;
125 let size = e.size as usize;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000126
Pierre-Clément Tosi706a10c2022-12-14 10:33:24 +0000127 match self._get_body_range(offset, size) {
128 Ok(r) => Ok(r),
129 Err(EntryError::InvalidSize(0)) => {
130 // As our bootloader currently uses this (non-compliant) case, permit it for now.
131 log::warn!("Config entry {entry:?} uses non-zero offset with zero size");
132 // TODO(b/262181812): Either make this case valid or fix the bootloader.
133 Ok(None)
134 }
135 Err(e) => Err(Error::InvalidEntry(entry, e)),
136 }
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000137 }
138
139 fn _get_body_range(
140 &self,
141 offset: usize,
142 size: usize,
143 ) -> result::Result<Option<Range<usize>>, EntryError> {
144 match (offset, size) {
145 (0, 0) => Ok(None),
146 (0, size) | (_, size @ 0) => Err(EntryError::InvalidSize(size)),
147 _ => {
148 let start = offset
149 .checked_sub(Header::PADDED_SIZE)
150 .ok_or(EntryError::InvalidOffset(offset))?;
151 let end = start
152 .checked_add(size)
153 .filter(|x| *x <= self.body_size())
154 .ok_or(EntryError::OutOfBounds { offset, size, limit: self.total_size() })?;
155
156 Ok(Some(start..end))
157 }
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000158 }
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100159 }
160}
161
162#[derive(Clone, Copy, Debug)]
163pub enum Entry {
164 Bcc = 0,
165 DebugPolicy = 1,
166}
167
168impl Entry {
169 const COUNT: usize = 2;
170}
171
172#[repr(packed)]
Alan Stokesa0e42962023-04-14 17:59:50 +0100173#[derive(Clone, Copy, Debug, FromBytes)]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100174struct HeaderEntry {
175 offset: u32,
176 size: u32,
177}
178
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100179#[derive(Debug)]
180pub struct Config<'a> {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100181 body: &'a mut [u8],
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000182 bcc_range: Range<usize>,
183 dp_range: Option<Range<usize>>,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100184}
185
186impl<'a> Config<'a> {
187 /// Take ownership of a pvmfw configuration consisting of its header and following entries.
Alan Stokesc3829f12023-06-02 15:02:23 +0100188 pub fn new(data: &'a mut [u8]) -> Result<Self> {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100189 let header = data.get(..Header::PADDED_SIZE).ok_or(Error::BufferTooSmall)?;
190
Alan Stokesa0e42962023-04-14 17:59:50 +0100191 let (header, _) =
192 LayoutVerified::<_, Header>::new_from_prefix(header).ok_or(Error::HeaderMisaligned)?;
193 let header = header.into_ref();
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100194
195 if header.magic != Header::MAGIC {
196 return Err(Error::InvalidMagic);
197 }
198
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +0000199 if header.version != Header::VERSION_1_0 {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100200 let (major, minor) = header.version_tuple();
201 return Err(Error::UnsupportedVersion(major, minor));
202 }
203
204 if header.flags != 0 {
205 return Err(Error::InvalidFlags(header.flags));
206 }
207
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000208 let bcc_range =
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000209 header.get_body_range(Entry::Bcc)?.ok_or(Error::MissingEntry(Entry::Bcc))?;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000210 let dp_range = header.get_body_range(Entry::DebugPolicy)?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100211
Alan Stokesa0e42962023-04-14 17:59:50 +0100212 let body_size = header.body_size();
213 let total_size = header.total_size();
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100214 let body = data
215 .get_mut(Header::PADDED_SIZE..)
216 .ok_or(Error::BufferTooSmall)?
Alan Stokesa0e42962023-04-14 17:59:50 +0100217 .get_mut(..body_size)
218 .ok_or(Error::InvalidSize(total_size))?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100219
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000220 Ok(Self { body, bcc_range, dp_range })
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100221 }
222
223 /// Get slice containing the platform BCC.
Pierre-Clément Tosiefe780c2023-02-21 21:36:30 +0000224 pub fn get_entries(&mut self) -> (&mut [u8], Option<&mut [u8]>) {
225 let bcc_start = self.bcc_range.start;
226 let bcc_end = self.bcc_range.len();
227 let (_, rest) = self.body.split_at_mut(bcc_start);
228 let (bcc, rest) = rest.split_at_mut(bcc_end);
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100229
Pierre-Clément Tosiefe780c2023-02-21 21:36:30 +0000230 let dp = if let Some(dp_range) = &self.dp_range {
231 let dp_start = dp_range.start.checked_sub(self.bcc_range.end).unwrap();
232 let dp_end = dp_range.len();
233 let (_, rest) = rest.split_at_mut(dp_start);
234 let (dp, _) = rest.split_at_mut(dp_end);
235 Some(dp)
236 } else {
237 None
238 };
239
240 (bcc, dp)
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100241 }
242}