ic_memory/runtime/backing.rs
1use ic_platform::stable_structures::{Memory, memory_manager::VirtualMemory};
2use std::{
3 cell::{Cell, RefCell},
4 rc::Rc,
5};
6
7// Physical custody, immutable geometry and exact manager metadata authority are
8// shared by the runtime and every handle, including detached ledger handles.
9pub(super) struct GrowthState<M: Memory> {
10 pub backing: Rc<M>,
11 pub bucket_size_pages: u16,
12 pub authority: RefCell<super::layout::ManagerAuthority>,
13 pub _claim: super::custody::BackingClaim,
14 pub open_slots: [Cell<u64>; 4],
15}
16
17impl<M: Memory> GrowthState<M> {
18 pub fn verify(&self) -> Result<(), super::MemoryManagerLayoutError> {
19 self.authority.borrow().verify(self.backing.as_ref())
20 }
21}
22
23///
24/// RuntimeMemory
25///
26/// Exclusive virtual memory leased through a runtime's committed authority.
27/// Implements [`Memory`] for stable structures without exposing the backing
28/// memory or an alternate manager. The lease cannot be cloned; dropping it
29/// permits another open of the same allocation. Moving it into a collection
30/// transfers the lease until that collection releases the memory.
31/// The handle can outlive its runtime and retains the backing claim. A replacement
32/// runtime is refused until every handle releases it. Custom backing identities
33/// must follow [`super::MemoryBacking`]; raw aliased access remains prohibited.
34/// IO checks the virtual extent before upstream bucket translation. Empty IO
35/// is valid at the end of memory, but not beyond it. Reads preserve the upstream
36/// optimized support for uninitialized destinations through `Memory::read_unsafe`.
37/// Growth reserves physical capacity before assigning manager buckets. Ordinary
38/// backing refusal, arithmetic overflow and bucket exhaustion return typed errors
39/// without changing virtual extents or manager metadata. Backing implementations
40/// must obey the `Memory` contract; traps and partial writes are not transactions
41/// on native memory. Typed collections retain their own failure behavior.
42/// Size, valid IO, and growth check the complete bounded manager metadata before
43/// using cached translations. Detected divergence permanently poisons this owner.
44/// Invalid IO bounds still refuse before backing access. These checks add bounded
45/// metadata reads, not ledger/payload decoding or synchronization with raw aliases.
46///
47
48pub struct RuntimeMemory<M: Memory> {
49 pub(super) memory: VirtualMemory<Rc<M>>,
50 pub(super) growth: Rc<GrowthState<M>>,
51 pub(super) id: u8,
52}
53
54impl<M: Memory> Drop for RuntimeMemory<M> {
55 fn drop(&mut self) {
56 let word = &self.growth.open_slots[usize::from(self.id / 64)];
57 word.set(word.get() & !(1_u64 << (self.id % 64)));
58 }
59}
60
61impl<M: Memory> RuntimeMemory<M> {
62 // The manager bounds page counts by 32768 buckets of at most u16::MAX
63 // pages, so converting its virtual extent to bytes cannot overflow u64.
64 // Check before the upstream cache: its buckets can include virtual slack,
65 // and its span/translation arithmetic is unchecked in release builds.
66 #[expect(
67 clippy::inline_always,
68 reason = "matched PocketIC measurements reduce IO instructions with bounded Wasm growth"
69 )]
70 #[inline(always)]
71 fn check_io_bounds(&self, offset: u64, count: usize) {
72 let extent = self.memory.size() * crate::constants::WASM_PAGE_SIZE_BYTES;
73 assert!(
74 offset <= extent && count as u64 <= extent - offset,
75 "virtual memory access out of bounds",
76 );
77 self.growth
78 .verify()
79 .expect("persisted manager metadata differs from runtime authority");
80 }
81
82 /// Grow by the requested pages, returning the previous virtual page count.
83 ///
84 /// Capacity is reserved before assigning manager buckets. Ordinary refusal
85 /// preserves virtual extents and manager metadata and permits retry. The
86 /// upstream [`Memory::grow`] adapter translates errors into its required
87 /// `-1` sentinel; direct runtime callers receive [`super::RuntimeGrowError`].
88 /// A zero-page request verifies metadata and returns the current extent
89 /// without growth or writes, after checking for reentrant growth.
90 ///
91 /// # Panics
92 ///
93 /// Panics if a private growth-accounting invariant is broken or backing
94 /// memory panics.
95 pub fn grow(&self, pages: u64) -> Result<u64, super::RuntimeGrowError> {
96 use super::RuntimeGrowError;
97 let mut authority = self
98 .growth
99 .authority
100 .try_borrow_mut()
101 .map_err(|_| RuntimeGrowError::ReentrantAccess)?;
102 authority.verify(self.growth.backing.as_ref())?;
103 let old_pages = self.memory.size();
104 if pages == 0 {
105 return Ok(old_pages);
106 }
107 let new_pages = old_pages
108 .checked_add(pages)
109 .ok_or(RuntimeGrowError::ArithmeticOverflow)?;
110 let bucket_pages = u64::from(self.growth.bucket_size_pages);
111 let extra = new_pages.div_ceil(bucket_pages) - old_pages.div_ceil(bucket_pages);
112 let total = u64::from(authority.allocated_buckets())
113 .checked_add(extra)
114 .ok_or(RuntimeGrowError::ArithmeticOverflow)?;
115 if total > u64::from(super::layout::BUCKET_CAPACITY) {
116 return Err(RuntimeGrowError::BucketExhausted {
117 required_buckets: total,
118 capacity: super::layout::BUCKET_CAPACITY,
119 });
120 }
121 #[expect(
122 clippy::cast_possible_truncation,
123 reason = "admission bounds total by the u16 bucket capacity"
124 )]
125 let total_buckets = total as u16;
126 let required_pages = 1 + total * bucket_pages;
127 let physical_pages = self.growth.backing.size();
128 if required_pages > physical_pages
129 && self.growth.backing.grow(required_pages - physical_pages) < 0
130 {
131 return Err(RuntimeGrowError::BackingRefused {
132 additional_pages: required_pages - physical_pages,
133 });
134 }
135 // The pinned manager's only refusal is bucket exhaustion, already
136 // checked above while all handles share this exclusive reservation.
137 // Physical capacity is reserved before it assigns any buckets.
138 assert_eq!(
139 self.memory.grow(pages),
140 old_pages.cast_signed(),
141 "preflighted manager growth returns the previous virtual extent"
142 );
143 authority.record_growth(self.id, new_pages, total_buckets);
144 authority.verify(self.growth.backing.as_ref())?;
145 Ok(old_pages)
146 }
147}
148
149impl<M: Memory> Memory for RuntimeMemory<M> {
150 fn size(&self) -> u64 {
151 self.growth
152 .verify()
153 .expect("persisted manager metadata differs from runtime authority");
154 self.memory.size()
155 }
156 fn grow(&self, pages: u64) -> i64 {
157 // The upstream trait fixes the sentinel contract. Direct calls use the
158 // inherent typed method; virtual extents fit in i64 by bucket capacity.
159 Self::grow(self, pages).map_or(-1, u64::cast_signed)
160 }
161 fn read(&self, offset: u64, dst: &mut [u8]) {
162 self.check_io_bounds(offset, dst.len());
163 self.memory.read(offset, dst);
164 }
165 #[expect(
166 unsafe_code,
167 reason = "delegate the upstream raw-read contract unchanged"
168 )]
169 unsafe fn read_unsafe(&self, offset: u64, dst: *mut u8, count: usize) {
170 self.check_io_bounds(offset, count);
171 // SAFETY: The caller supplies a valid destination disjoint from this
172 // memory and its backing. Forwarding preserves the pointer and count;
173 // VirtualMemory owns bucket translation and initializes the destination
174 // on success. After a panic, initialization must not be assumed.
175 unsafe { self.memory.read_unsafe(offset, dst, count) }
176 }
177 fn write(&self, offset: u64, src: &[u8]) {
178 self.check_io_bounds(offset, src.len());
179 self.memory.write(offset, src);
180 }
181}