1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use core::fmt;
use ax_memory_addr::{AddrRange, MemoryAddr};
use crate::{MappingBackend, MappingError, MappingResult};
/// A memory area represents a continuous range of virtual memory with the same
/// flags.
///
/// The target physical memory frames are determined by [`MappingBackend`] and
/// may not be contiguous.
#[derive(Clone)]
pub struct MemoryArea<B: MappingBackend> {
va_range: AddrRange<B::Addr>,
flags: B::Flags,
reported_flags: B::Flags,
max_flags: B::Flags,
backend: B,
}
impl<B: MappingBackend> MemoryArea<B> {
/// Fallible counterpart of [`Self::new`]. New code that receives
/// untrusted address/length pairs should use this constructor so an
/// overflow is represented as a mapping error instead of a panic.
pub fn try_new(
start: B::Addr,
size: usize,
flags: B::Flags,
backend: B,
) -> MappingResult<Self> {
Self::try_new_with_reported_flags(start, size, flags, flags, backend)
}
/// Fallible constructor with separate operational and reported flags.
pub fn try_new_with_reported_flags(
start: B::Addr,
size: usize,
flags: B::Flags,
reported_flags: B::Flags,
backend: B,
) -> MappingResult<Self> {
let va_range = ax_memory_addr::AddrRange::try_from_start_size(start, size)
.ok_or(MappingError::InvalidParam)?;
if va_range.is_empty() {
return Err(MappingError::InvalidParam);
}
Ok(Self {
va_range,
flags,
reported_flags,
max_flags: flags,
backend,
})
}
/// Creates a new memory area.
///
/// # Panics
///
/// Panics if `start + size` overflows.
pub fn new(start: B::Addr, size: usize, flags: B::Flags, backend: B) -> Self {
Self::new_with_reported_flags(start, size, flags, flags, backend)
}
/// Creates a new memory area with separate backend and reported flags.
///
/// `flags` are used for page-table/backend operations. `reported_flags`
/// are metadata exposed through introspection interfaces such as procfs.
///
/// # Panics
///
/// Panics if `start + size` overflows.
pub fn new_with_reported_flags(
start: B::Addr,
size: usize,
flags: B::Flags,
reported_flags: B::Flags,
backend: B,
) -> Self {
Self {
va_range: AddrRange::from_start_size(start, size),
flags,
reported_flags,
max_flags: flags,
backend,
}
}
/// Creates an area with an explicit maximum permission envelope.
pub fn new_with_permissions(
start: B::Addr,
size: usize,
flags: B::Flags,
reported_flags: B::Flags,
max_flags: B::Flags,
backend: B,
) -> Self {
Self {
va_range: AddrRange::from_start_size(start, size),
flags,
reported_flags,
max_flags,
backend,
}
}
/// Fallible constructor with an explicit maximum permission envelope.
///
/// This is the constructor used at syscall boundaries. The older
/// infallible constructors remain available for trusted boot-time
/// mappings, but user supplied `start + size` pairs must not be allowed to
/// wrap through `AddrRange::from_start_size`.
pub fn try_new_with_permissions(
start: B::Addr,
size: usize,
flags: B::Flags,
reported_flags: B::Flags,
max_flags: B::Flags,
backend: B,
) -> MappingResult<Self> {
let va_range =
AddrRange::try_from_start_size(start, size).ok_or(MappingError::InvalidParam)?;
if va_range.is_empty() {
return Err(MappingError::InvalidParam);
}
Ok(Self {
va_range,
flags,
reported_flags,
max_flags,
backend,
})
}
/// Returns the virtual address range.
pub const fn va_range(&self) -> AddrRange<B::Addr> {
self.va_range
}
/// Returns the memory flags, e.g., the permission bits.
pub const fn flags(&self) -> B::Flags {
self.flags
}
/// Returns the permission flags reported to user-visible introspection.
pub const fn reported_flags(&self) -> B::Flags {
self.reported_flags
}
/// Returns the maximum permissions retained for this mapping.
pub const fn max_flags(&self) -> B::Flags {
self.max_flags
}
/// Returns the start address of the memory area.
pub const fn start(&self) -> B::Addr {
self.va_range.start
}
/// Returns the end address of the memory area.
pub const fn end(&self) -> B::Addr {
self.va_range.end
}
/// Returns the size of the memory area.
pub fn size(&self) -> usize {
self.va_range.size()
}
/// Returns the mapping backend of the memory area.
pub const fn backend(&self) -> &B {
&self.backend
}
}
impl<B: MappingBackend> MemoryArea<B> {
pub(crate) fn replace_backend(&mut self, backend: B) -> B {
core::mem::replace(&mut self.backend, backend)
}
/// Changes backend/page-table flags and reported flags together.
pub(crate) fn set_flags_with_reported_flags(
&mut self,
new_flags: B::Flags,
new_reported_flags: B::Flags,
) {
self.flags = new_flags;
self.reported_flags = new_reported_flags;
}
/// Maps the whole memory area in the page table.
pub(crate) fn map_area(
&self,
context: &mut B::MutationContext,
page_table: &mut B::PageTable,
) -> MappingResult {
self.backend
.map(self.start(), self.size(), self.flags, context, page_table)
.then_some(())
.ok_or(MappingError::BadState)
}
pub(crate) fn validate_map(&self, page_table: &B::PageTable) -> MappingResult {
self.backend
.validate_map(self.start(), self.size(), self.flags, page_table)
.then_some(())
.ok_or(MappingError::BadState)
}
/// Unmaps the whole memory area in the page table.
pub(crate) fn unmap_area(
&self,
context: &mut B::MutationContext,
page_table: &mut B::PageTable,
) -> MappingResult {
self.unmap_range(self.start(), self.size(), context, page_table)
}
/// Unmaps a sub-range without changing this area's metadata.
///
/// Callers use this to complete the fallible backend transition before
/// committing a split or key change in the containing memory set.
pub(crate) fn unmap_range(
&self,
start: B::Addr,
size: usize,
context: &mut B::MutationContext,
page_table: &mut B::PageTable,
) -> MappingResult {
debug_assert!(
self.va_range
.contains_range(AddrRange::from_start_size(start, size))
);
self.backend
.unmap(start, size, context, page_table)
.then_some(())
.ok_or(MappingError::BadState)
}
/// Preflights an unmap sub-range without changing page-table or metadata.
pub(crate) fn validate_unmap_range(
&self,
start: B::Addr,
size: usize,
page_table: &B::PageTable,
) -> MappingResult {
debug_assert!(
self.va_range
.contains_range(AddrRange::from_start_size(start, size))
);
self.backend
.validate_unmap(start, size, page_table)
.then_some(())
.ok_or(MappingError::BadState)
}
/// Changes page-table flags for a sub-range without changing metadata.
pub(crate) fn protect_range(
&self,
start: B::Addr,
size: usize,
new_flags: B::Flags,
context: &mut B::MutationContext,
page_table: &mut B::PageTable,
) -> MappingResult {
debug_assert!(
self.va_range
.contains_range(AddrRange::from_start_size(start, size))
);
self.backend
.protect(start, size, new_flags, context, page_table)
.then_some(())
.ok_or(MappingError::BadState)
}
/// Shrinks the memory area at the left side without touching the page
/// table.
pub(crate) fn shrink_left_metadata(&mut self, new_size: usize) -> MappingResult {
if new_size == 0 || new_size >= self.size() {
return Err(MappingError::InvalidParam);
}
let old_size = self.size();
let unmap_size = old_size - new_size;
let new_start = self
.va_range
.start
.checked_add(unmap_size)
.ok_or(MappingError::InvalidParam)?;
if !self.backend.shrink_left(unmap_size) {
return Err(MappingError::BadState);
}
self.va_range.start = new_start;
Ok(())
}
/// Shrinks the memory area at the right side without touching the page
/// table.
pub(crate) fn shrink_right_metadata(&mut self, new_size: usize) -> MappingResult {
if new_size == 0 || new_size >= self.size() {
return Err(MappingError::InvalidParam);
}
let old_size = self.size();
let unmap_size = old_size - new_size;
let new_end = self
.va_range
.end
.checked_sub(unmap_size)
.ok_or(MappingError::InvalidParam)?;
if !self.backend.shrink_right(unmap_size) {
return Err(MappingError::BadState);
}
self.va_range.end = new_end;
Ok(())
}
/// Inverse of [`shrink_right`]: extends the end by `additional_size`
/// and maps the new region via the backend.
pub(crate) fn grow_right(
&mut self,
additional_size: usize,
context: &mut B::MutationContext,
page_table: &mut B::PageTable,
) -> MappingResult {
if additional_size == 0
|| !self.end().is_aligned_4k()
|| !additional_size.is_multiple_of(ax_memory_addr::PAGE_SIZE_4K)
{
return Err(MappingError::InvalidParam);
}
let map_start = self.end();
let new_end = self
.va_range
.end
.checked_add(additional_size)
.ok_or(MappingError::InvalidParam)?;
if !self
.backend
.validate_map(map_start, additional_size, self.flags, page_table)
{
return Err(MappingError::BadState);
}
if !self
.backend
.map(map_start, additional_size, self.flags, context, page_table)
{
// A backend is allowed to materialize a prefix before reporting
// failure. Use its inverse while the original metadata is still
// intact; if that inverse cannot prove a full cleanup, expose the
// indeterminate state instead of returning a recoverable error.
return Err(
if self
.backend
.unmap(map_start, additional_size, context, page_table)
{
MappingError::BadState
} else {
MappingError::NeedsRepair
},
);
}
self.va_range.end = new_end;
Ok(())
}
/// Splits the memory area at the given position.
///
/// The original memory area is shrunk to the left part, and the right part
/// is returned.
///
/// Returns `None` if the given position is not in the memory area, or one
/// of the parts is empty after splitting.
pub(crate) fn split(&mut self, pos: B::Addr) -> MappingResult<Option<Self>> {
if self.start() < pos && pos < self.end() {
let align_diff = pos.sub_addr(self.start());
let right = self
.backend
.split(align_diff)
.ok_or(MappingError::BadState)?;
let mut new_area = Self::new_with_reported_flags(
pos,
self.end()
.checked_sub_addr(pos)
.ok_or(MappingError::InvalidParam)?,
self.flags,
self.reported_flags,
right,
);
new_area.max_flags = self.max_flags;
self.va_range.end = pos;
Ok(Some(new_area))
} else {
Ok(None)
}
}
}
impl<B: MappingBackend> fmt::Debug for MemoryArea<B>
where
B::Addr: fmt::Debug,
B::Flags: fmt::Debug + Copy,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("MemoryArea")
.field("va_range", &self.va_range)
.field("flags", &self.flags)
.field("reported_flags", &self.reported_flags)
.field("max_flags", &self.max_flags)
.finish()
}
}