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