Skip to main content

ostd/boot/
memory_region.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Information of memory regions in the boot phase.
3use core::cmp::Ordering;
4use vstd::{
5    array::group_array_axioms,
6    laws_cmp::{
7        obeys_cmp, obeys_cmp_ord, obeys_cmp_partial_ord, obeys_partial_cmp_spec_properties,
8    },
9    laws_eq::obeys_eq_spec_properties,
10    prelude::*,
11    std_specs::cmp::{OrdSpec, OrdSpecImpl, PartialEqSpecImpl, PartialOrdSpec, PartialOrdSpecImpl},
12    std_specs::iter::{IteratorSpec, filter_keep},
13};
14use vstd_extra::prelude::*;
15
16use crate::specs::arch::*;
17
18use core::ops::Deref;
19
20use align_ext::AlignExt;
21
22// use crate::mm::kspace::kernel_loaded_offset;
23use crate::mm::{
24    PAGE_SIZE, Paddr, Vaddr,
25    kspace::{LINEAR_MAPPING_BASE_VADDR, VMALLOC_BASE_VADDR},
26};
27
28/// The type of initial memory regions that are needed for the kernel.
29#[verus_verify]
30#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
31pub enum MemoryRegionType {
32    /// Maybe points to an unplugged DIMM module. It's bad anyway.
33    BadMemory = 0,
34    /// Some holes not specified by the bootloader/firmware. It may be used for
35    /// I/O memory but we don't know for sure.
36    Unknown = 1,
37    /// In ACPI spec, this area needs to be preserved when sleeping.
38    NonVolatileSleep = 2,
39    /// Reserved by BIOS or bootloader, do not use.
40    Reserved = 3,
41    /// The place where kernel sections are loaded.
42    Kernel = 4,
43    /// The place where kernel modules (e.g. initrd) are loaded, could be reused.
44    Module = 5,
45    /// The memory region provided as the framebuffer.
46    Framebuffer = 6,
47    /// Once used in the boot phase. Kernel can reclaim it after initialization.
48    Reclaimable = 7,
49    /// Directly usable by the frame allocator.
50    Usable = 8,
51}
52
53#[verus_verify]
54impl MemoryRegionType {
55    /// Returns whether the memory region corresponds to physical memory.
56    ///
57    /// The linear mapping will cover memory addresses up to the top of the physical memory.
58    /// Therefore, if this method returns `false`, the memory region may not be included in the
59    /// linear mapping.
60    #[verus_verify(dual_spec, open)]
61    #[verus_spec(returns self.is_physical())]
62    pub fn is_physical(self) -> bool {
63        // Bad memory or I/O memory is not physical. All other memory should be physical.
64        !matches!(
65            self,
66            Self::BadMemory | Self::Unknown | Self::Reserved | Self::Framebuffer
67        )
68    }
69}
70
71/// The information of initial memory regions that are needed by the kernel.
72/// The sections are **not** guaranteed to not overlap. The region must be page aligned.
73#[verus_verify]
74#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
75pub struct MemoryRegion {
76    base: usize,
77    len: usize,
78    typ: MemoryRegionType,
79}
80
81verus! {
82
83impl PartialEqSpecImpl for MemoryRegionType {
84    open spec fn obeys_eq_spec() -> bool {
85        true
86    }
87
88    open spec fn eq_spec(&self, other: &Self) -> bool {
89        self == other
90    }
91}
92
93impl PartialOrdSpecImpl for MemoryRegionType {
94    open spec fn obeys_partial_cmp_spec() -> bool {
95        true
96    }
97
98    open spec fn partial_cmp_spec(&self, other: &Self) -> Option<Ordering> {
99        <u8 as PartialOrdSpec>::partial_cmp_spec(&(*self as u8), &(*other as u8))
100    }
101}
102
103impl OrdSpecImpl for MemoryRegionType {
104    open spec fn obeys_cmp_spec() -> bool {
105        true
106    }
107
108    open spec fn cmp_spec(&self, other: &Self) -> Ordering {
109        <u8 as OrdSpec>::cmp_spec(&(*self as u8), &(*other as u8))
110    }
111}
112
113impl MemoryRegion {
114    /// The region aligned inward for `Usable`, outward otherwise.
115    pub open spec fn aligned_region(self) -> Self {
116        let base = if self.typ() == MemoryRegionType::Usable {
117            nat_align_up(self.base() as nat, PAGE_SIZE as nat)
118        } else {
119            nat_align_down(self.base() as nat, PAGE_SIZE as nat)
120        };
121        let end = if self.typ() == MemoryRegionType::Usable {
122            nat_align_down((self.base() + self.len()) as nat, PAGE_SIZE as nat)
123        } else {
124            nat_align_up((self.base() + self.len()) as nat, PAGE_SIZE as nat)
125        };
126        let len = if end >= base {
127            (end - base) as usize
128        } else {
129            0
130        };
131        Self::new(base as usize, len, self.typ())
132    }
133
134    #[verifier::type_invariant]
135    closed spec fn type_inv(self) -> bool {
136        self.base + self.len <= usize::MAX
137    }
138
139    /// Whether `self` is contained in `old_region`, with the same type.
140    pub closed spec fn is_sub_region(self, old_region: Self) -> bool {
141        self.typ == old_region.typ && old_region.base <= self.base && self.base + self.len
142            <= old_region.base + old_region.len
143    }
144
145    /// Whether the region shares no address with `region`.
146    pub closed spec fn is_separate(self, region: Self) -> bool {
147        self.base + self.len <= region.base || region.base + region.len <= self.base
148    }
149
150    /// Whether both boundaries of the region are multiples of `align`.
151    pub closed spec fn aligned(self, align: int) -> bool {
152        self.base as int % align == 0 && (self.base + self.len) % align == 0
153    }
154}
155
156} // verus!
157#[verus_verify]
158impl MemoryRegion {
159    /// Constructs a valid memory region.
160    ///
161    /// # Verified Properties
162    ///
163    /// ## Safety
164    /// - The function does not panic.
165    ///
166    /// ## Preconditions
167    /// - `base + len <= usize::MAX` establishes the region's type invariant.
168    #[verus_verify(dual_spec)]
169    #[verus_spec(
170        requires
171            base + len <= usize::MAX,
172        returns
173            Self::new(base, len, typ),
174    )]
175    pub const fn new(base: Paddr, len: usize, typ: MemoryRegionType) -> Self {
176        MemoryRegion { base, len, typ }
177    }
178
179    /// Constructs a bad memory region.
180    ///
181    /// # Verified Properties
182    ///
183    /// ## Safety
184    /// - The function does not panic.
185    #[verus_verify(dual_spec)]
186    #[verus_spec(
187        returns Self::bad(),
188    )]
189    pub const fn bad() -> Self {
190        MemoryRegion {
191            base: 0,
192            len: 0,
193            typ: MemoryRegionType::BadMemory,
194        }
195    }
196
197    /*
198    /// Constructs a memory region where kernel sections are loaded.
199    ///
200    /// Most boot protocols do not mark the place where the kernel loads as unusable. In this case,
201    /// we need to explicitly construct and append this memory region.
202    pub fn kernel() -> Self {
203        // These are physical addresses provided by the linker script.
204        unsafe extern "C" {
205            fn __kernel_start();
206            fn __kernel_end();
207        }
208        MemoryRegion {
209            base: __kernel_start as *const () as usize - kernel_loaded_offset(),
210            len: __kernel_end as *const () as usize - __kernel_start as *const () as usize,
211            typ: MemoryRegionType::Kernel,
212        }
213    }
214
215    */
216    /// Constructs a framebuffer memory region.
217    ///
218    /// # Verified Properties
219    ///
220    /// ## Safety
221    /// - The function does not panic when its preconditions hold.
222    ///
223    /// ## Preconditions
224    /// - `fb.width * fb.height` fits in `usize`.
225    /// - `fb.width * fb.height * fb.bpp` fits in `usize`.
226    /// - The framebuffer's physical end is at most `usize::MAX`.
227    ///
228    /// ## Postconditions
229    /// - The framebuffer's bit size is rounded up to whole bytes.
230    #[verus_spec(
231        requires
232            fb.width * fb.height <= usize::MAX,
233            fb.width * fb.height * fb.bpp <= usize::MAX,
234            fb.address + (fb.width * fb.height * fb.bpp + 7) / 8 <= usize::MAX,
235        returns
236            Self::new(fb.address, ((fb.width * fb.height * fb.bpp + 7) / 8) as usize,
237                MemoryRegionType::Framebuffer),
238    )]
239    pub fn framebuffer(fb: &crate::boot::BootloaderFramebufferArg) -> Self {
240        Self {
241            base: fb.address,
242            len: (fb.width * fb.height * fb.bpp).div_ceil(8), // round up when divide with 8 (bits/Byte)
243            typ: MemoryRegionType::Framebuffer,
244        }
245    }
246
247    /// Constructs a module memory region from a byte slice that lives in the linear mapping.
248    ///
249    /// # Panics
250    ///
251    /// This method will panic if the byte slice does not live in the linear mapping.
252    ///
253    /// # Verified Properties
254    ///
255    /// ## Safety
256    /// - The function does not panic when its preconditions hold.
257    ///
258    /// ## Preconditions
259    /// - The slice's base lies in the linear mapping, below `VMALLOC_BASE_VADDR`.
260    /// - The translated physical end is at most `usize::MAX`.
261    #[verus_spec(
262        requires
263            LINEAR_MAPPING_BASE_VADDR <= (bytes.as_ptr() as usize) < VMALLOC_BASE_VADDR,
264            (bytes.as_ptr() as usize) - LINEAR_MAPPING_BASE_VADDR + bytes.len() <= usize::MAX,
265        returns
266            Self::new((bytes.as_ptr() as usize - LINEAR_MAPPING_BASE_VADDR) as usize,
267                bytes.len(), MemoryRegionType::Reclaimable),
268    )]
269    pub fn module(bytes: &[u8]) -> Self {
270        let vaddr = bytes.as_ptr() as Vaddr;
271        assert!(crate::mm::kspace::LINEAR_MAPPING_VADDR_RANGE.contains(&vaddr));
272
273        Self {
274            base: vaddr - crate::mm::kspace::LINEAR_MAPPING_BASE_VADDR,
275            len: bytes.len(),
276            typ: MemoryRegionType::Reclaimable,
277        }
278    }
279
280    /// Returns the physical address of the base of the region.
281    #[verus_verify(dual_spec)]
282    #[verus_spec(returns self.base())]
283    pub fn base(&self) -> Paddr {
284        self.base
285    }
286
287    /// Returns the length in bytes of the region.
288    #[verus_verify(dual_spec)]
289    #[verus_spec(returns self.len())]
290    pub fn len(&self) -> usize {
291        self.len
292    }
293
294    /// Returns the physical address of the end of the region.
295    #[verus_verify(dual_spec)]
296    #[verus_spec(returns self.end())]
297    pub fn end(&self) -> Paddr {
298        proof! {
299            use_type_invariant(self);
300        }
301        self.base + self.len
302    }
303
304    /// Checks whether the region is empty
305    #[verus_verify(dual_spec)]
306    #[verus_spec(returns self.is_empty())]
307    pub fn is_empty(&self) -> bool {
308        self.len == 0
309    }
310
311    /// Returns the type of the region.
312    #[verus_verify(dual_spec)]
313    #[verus_spec(returns self.typ())]
314    pub fn typ(&self) -> MemoryRegionType {
315        self.typ
316    }
317
318    /// Returns the region with boundaries rounded to `PAGE_SIZE` boundaries:
319    /// inward for `Usable` regions, outward for the others.
320    #[verus_spec(ret =>
321        requires
322            self.typ == MemoryRegionType::Usable ==> self.base <= usize::MAX - (PAGE_SIZE - 1),
323            self.typ != MemoryRegionType::Usable ==> self.base + self.len <= usize::MAX - (PAGE_SIZE - 1),
324        ensures
325            ret.aligned(PAGE_SIZE as int),
326            self.typ == MemoryRegionType::Usable && ret.len() > 0 ==> ret.is_sub_region(*self),
327            self.typ != MemoryRegionType::Usable ==> self.is_sub_region(ret),
328        returns self.aligned_region(),
329    )]
330    fn as_aligned(&self) -> Self {
331        proof! {
332            lemma_pow2_is_pow2_to64();
333            use_type_invariant(self);
334        }
335        let (base, len) = match self.typ() {
336            MemoryRegionType::Usable => {
337                let aligned_base = self.base().align_up(PAGE_SIZE);
338                let aligned_end = self.end().align_down(PAGE_SIZE);
339                (aligned_base, aligned_end.saturating_sub(aligned_base))
340            }
341            _ => {
342                let aligned_base = self.base().align_down(PAGE_SIZE);
343                let aligned_end = self.end().align_up(PAGE_SIZE);
344                (aligned_base, aligned_end - aligned_base)
345            }
346        };
347        MemoryRegion {
348            base,
349            len,
350            typ: self.typ,
351        }
352    }
353}
354
355/// The maximum number of regions that can be handled.
356///
357/// The choice of 512 is probably fine since old Linux boot protocol only
358/// allows 128 regions.
359//
360// TODO: confirm the number or make it configurable.
361#[verus_verify]
362const MAX_REGIONS: usize = 512;
363
364/// A heapless set of memory regions.
365///
366/// The set cannot contain more than `LEN` regions.
367#[verus_verify]
368pub(crate) struct MemoryRegionArray<const LEN: usize = MAX_REGIONS> {
369    regions: [MemoryRegion; LEN],
370    count: usize,
371}
372
373verus! {
374
375impl<const LEN: usize> MemoryRegionArray<LEN> {
376    #[verifier::type_invariant]
377    closed spec fn type_inv(self) -> bool {
378        self.count <= LEN
379    }
380
381    /// The active regions after page alignment and removal of empty regions.
382    pub open spec fn aligned_regions(self) -> Seq<MemoryRegion> {
383        self@.map_values(|r: MemoryRegion| r.aligned_region()).filter(|r: MemoryRegion| r.len() > 0)
384    }
385}
386
387/// The distinct positive region boundaries.
388pub open spec fn region_boundaries(rs: Seq<MemoryRegion>) -> Set<int> {
389    rs.map_values(|r: MemoryRegion| r.base() as int).to_set().union(
390        rs.map_values(|r: MemoryRegion| r.base() + r.len()).to_set(),
391    ).remove(0)
392}
393
394/// Whether the regions form a contiguous, page-aligned partition starting at zero.
395pub open spec fn is_partition(rs: Seq<MemoryRegion>) -> bool {
396    &&& (rs.len() > 0 ==> rs[0].base() == 0)
397    &&& (forall|i: int|
398        0 <= i < rs.len() ==> {
399            &&& #[trigger] rs[i].aligned(PAGE_SIZE as int)
400            &&& rs[i].len() > 0
401            &&& rs[i].base() + rs[i].len() <= usize::MAX
402            &&& (i > 0 ==> rs[i - 1].base() + rs[i - 1].len() == rs[i].base())
403        })
404}
405
406/// The type selected by the lowest-usability covering input region.
407#[verifier::opaque]
408pub open spec fn selected_type(rs: Seq<MemoryRegion>, addr: int, typ: MemoryRegionType) -> bool {
409    &&& (rs.any(|r: MemoryRegion| r.base() <= addr < r.base() + r.len()) ==> rs.any(
410        |r: MemoryRegion| r.base() <= addr < r.base() + r.len() && r.typ() == typ,
411    ))
412    &&& rs.all(
413        |r: MemoryRegion| r.base() <= addr < r.base() + r.len() ==> typ as int <= r.typ() as int,
414    )
415    &&& (!rs.any(|r: MemoryRegion| r.base() <= addr < r.base() + r.len()) ==> typ
416        == MemoryRegionType::Unknown)
417}
418
419/// Every output byte carries the most restrictive covering input type.
420pub open spec fn preserves_types(output: Seq<MemoryRegion>, input: Seq<MemoryRegion>) -> bool {
421    output.all(
422        |r: MemoryRegion|
423            forall|addr: int|
424                r.base() <= addr < r.base() + r.len() ==> #[trigger] selected_type(
425                    input,
426                    addr,
427                    r.typ(),
428                ),
429    )
430}
431
432/// Adjacent regions have different types, so no further merge is possible.
433#[verifier::opaque]
434pub open spec fn coalesced(rs: Seq<MemoryRegion>) -> bool {
435    forall|j: int|
436        #![trigger rs[j].typ(), rs[j - 1].typ()]
437        0 < j < rs.len() ==> rs[j].typ() != rs[j - 1].typ()
438}
439
440impl<const LEN: usize> View for MemoryRegionArray<LEN> {
441    type V = Seq<MemoryRegion>;
442
443    closed spec fn view(&self) -> Seq<MemoryRegion> {
444        Seq::new(self.count as nat, |i: int| self.regions[i])
445    }
446}
447
448} // verus!
449#[verus_verify]
450impl<const LEN: usize> Default for MemoryRegionArray<LEN> {
451    #[verus_spec(ret =>
452        ensures
453            ret@ == Seq::<MemoryRegion>::empty(),
454    )]
455    fn default() -> Self {
456        Self::new()
457    }
458}
459
460#[verus_verify]
461impl<const LEN: usize> Deref for MemoryRegionArray<LEN> {
462    type Target = [MemoryRegion];
463
464    #[verus_spec(ret =>
465        ensures
466            ret@ == self@,
467    )]
468    fn deref(&self) -> &Self::Target {
469        proof! {
470            use_type_invariant(self);
471        }
472        &self.regions[..self.count]
473    }
474}
475/// An error returned by [`MemoryRegionArray::push`] when the array is full.
476#[verus_verify]
477#[derive(Debug)]
478pub(crate) struct ArrayFullError;
479
480#[verus_verify]
481impl<const LEN: usize> MemoryRegionArray<LEN> {
482    /// Constructs an empty set.
483    ///
484    /// # Verified Properties
485    ///
486    /// ## Safety
487    /// - The function does not panic.
488    #[verus_verify(dual_spec)]
489    #[verus_spec(ret =>
490        ensures
491            ret@ == Seq::<MemoryRegion>::empty(),
492        returns Self::new(),
493    )]
494    pub(crate) const fn new() -> Self {
495        let ret = Self {
496            regions: [MemoryRegion::bad(); LEN],
497            count: 0,
498        };
499
500        ret
501    }
502
503    /// Appends a region to the set.
504    ///
505    /// If the set is full, an error is returned.
506    ///
507    /// # Verified Properties
508    ///
509    /// ## Safety
510    /// - The function does not panic.
511    ///
512    /// ## Postconditions
513    /// - On error, the region set is unchanged.
514    #[verus_spec(ret =>
515        ensures
516            old(self)@.len() < LEN ==> {
517                &&& final(self)@ == old(self)@.push(region)
518                &&& ret is Ok
519            },
520            old(self)@.len() == LEN ==> {
521                &&& final(self)@ == old(self)@
522                &&& ret is Err
523            },
524    )]
525    pub(crate) fn push(&mut self, region: MemoryRegion) -> Result<(), ArrayFullError> {
526        if self.count >= self.regions.len() {
527            return Err(ArrayFullError);
528        }
529
530        self.regions[self.count] = region;
531        self.count += 1;
532
533        Ok(())
534    }
535
536    /// Sorts the regions and returns a full set of non-overlapping regions.
537    ///
538    /// If an address is in multiple regions, the region with the lowest
539    /// usability will be its type.
540    ///
541    /// All the addresses between 0 and the end of the last region will be in
542    /// the resulting set. If an address is not in any region, it will be marked
543    /// as [`MemoryRegionType::Unknown`].
544    ///
545    /// If any of the region boundaries are not page-aligned, they will be aligned
546    /// according to the type of the region.
547    ///
548    /// # Panics
549    ///
550    /// This method will panic if the number of output regions is greater than `LEN`.
551    ///
552    /// # Verified Properties
553    ///
554    /// ## Safety
555    /// - The function does not panic when its precondition holds.
556    ///
557    /// ## Preconditions
558    /// - Nonempty aligned inputs have at most `LEN` distinct positive boundaries.
559    ///   Each boundary produces one region before merging.
560    /// - Rounding up `Usable` bases and other input ends does not overflow.
561    ///
562    /// ## Postconditions
563    /// - The output ends at the largest nonempty aligned input end, or is empty
564    ///   if no such input remains.
565    /// - Adjacent output regions have different types.
566    #[verus_verify(spinoff_prover)]
567    #[verus_spec(ret =>
568        requires
569            region_boundaries(self.aligned_regions()).len() <= LEN,
570            self@.all(|r: MemoryRegion| if r.typ() == MemoryRegionType::Usable {
571                r.base() <= usize::MAX - (PAGE_SIZE - 1)
572            } else {
573                r.base() + r.len() <= usize::MAX - (PAGE_SIZE - 1)
574            }),
575        ensures
576            is_partition(ret@),
577            preserves_types(ret@, self.aligned_regions()),
578            ret@.len() == 0 <==> self.aligned_regions().len() == 0,
579            ret@.len() > 0 ==> self.aligned_regions().all(|r: MemoryRegion| r.end() <= ret@.last().end()),
580            ret@.len() > 0 ==> self.aligned_regions().any(|r: MemoryRegion| r.end() == ret@.last().end()),
581            coalesced(ret@),
582    )]
583    pub(crate) fn into_non_overlapping(mut self) -> Self {
584        proof! {
585            broadcast use group_array_axioms;
586            use_type_invariant(&self);
587        }
588        proof_decl! { let ghost original = self; }
589        // Align the regions and drop those that become empty after alignment.
590        let mut count = 0;
591        #[verus_spec(
592            invariant
593                count <= i <= self.count == original.count <= LEN,
594                region_boundaries(original.aligned_regions()).len() <= LEN,
595                original@.all(|r: MemoryRegion| if r.typ() == MemoryRegionType::Usable {
596                    r.base() <= usize::MAX - (PAGE_SIZE - 1)
597                } else {
598                    r.base() + r.len() <= usize::MAX - (PAGE_SIZE - 1)
599                }),
600                self.regions@[..count] == original@[..i]
601                    .map_values(|r: MemoryRegion| r.aligned_region())
602                    .filter(|r: MemoryRegion| r.len() > 0),
603                forall|j: int| i <= j < original.count ==> #[trigger] self.regions[j] == original@[j],
604                forall|j: int| #![trigger self.regions[j]] 0 <= j < count ==> {
605                    &&& self.regions[j].aligned(PAGE_SIZE as int)
606                    &&& self.regions[j].len > 0
607                    &&& self.regions[j].base + self.regions[j].len <= usize::MAX
608                },
609        )]
610        for i in 0..self.count {
611            let region = self.regions[i].as_aligned();
612            proof! {
613                use_type_invariant(&region);
614                let mapped = original@[..i].map_values(|r: MemoryRegion| r.aligned_region());
615                assert(original@[..i + 1].map_values(|r: MemoryRegion| r.aligned_region())
616                    == mapped.push(region));
617                mapped.lemma_filter_push(region, |r: MemoryRegion| r.len() > 0);
618            }
619            if !region.is_empty() {
620                self.regions[count] = region;
621                count += 1;
622            }
623        }
624        self.count = count;
625        proof_decl! { let ghost source = self@; }
626        proof! {
627            assert(original@[..original.count] == original@);
628            assert(source == original.aligned_regions());
629        }
630        /* Keep iterator proofs local to the maximum-end computation.
631         * Origin Rust: let max_addr = self.iter().map(|r| r.end()).max().unwrap_or(0);
632         */
633        let max_addr = max_region_end(&self).unwrap_or(0);
634        proof_decl! {
635            let ghost bounds = region_boundaries(source);
636            let ghost mut visited = Set::<int>::empty();
637        }
638
639        let mut result = MemoryRegionArray::<LEN>::new();
640
641        let mut cur_right = 0;
642
643        #[verus_spec(
644            invariant
645                self@ == source,
646                source == original.aligned_regions(),
647                max_addr == 0 <==> source.len() == 0,
648                source.len() == self.count <= LEN,
649                bounds == region_boundaries(source),
650                bounds.len() <= LEN,
651                visited.subset_of(bounds),
652                visited.len() == result.count,
653                forall|p: int| #[trigger] visited.contains(p) ==> p <= cur_right,
654                cur_right <= max_addr <= usize::MAX,
655                cur_right % PAGE_SIZE == 0,
656                is_partition(result@),
657                cur_right == if result@.len() == 0 { 0 } else { result@.last().end() },
658                preserves_types(result@, source),
659                result.count == result@.len() <= LEN,
660                max_addr == 0 || exists|j: int| 0 <= j < source.len() && #[trigger] source[j].end() == max_addr,
661                forall|j: int| #![trigger source[j]] 0 <= j < source.len() ==> {
662                    &&& source[j].aligned(PAGE_SIZE as int)
663                    &&& source[j].len > 0
664                    &&& source[j].base + source[j].len <= max_addr
665                },
666            decreases usize::MAX - cur_right,
667        )]
668        while cur_right < max_addr {
669            /* Verus needs non-generic helpers for these iterator closures.
670             * `FilterMap` lacks a model; use filter + map, relying on base <= end.
671             * TODO: Restore filter_map when vstd includes the model from
672             * https://github.com/verus-lang/verus/pull/2728.
673             * Origin Rust: let typ = self.iter()
674             *     .filter(|region| (region.base()..region.end()).contains(&cur_right))
675             *     .map(|region| region.typ()).min().unwrap_or(MemoryRegionType::Unknown);
676             * let right = self.iter().filter_map(|region| {
677             *     if region.base() > cur_right { Some(region.base()) }
678             *     else if region.end() > cur_right { Some(region.end()) }
679             *     else { None }
680             * }).min().unwrap();
681             */
682            let typ = most_restrictive_type(&self, cur_right).unwrap_or(MemoryRegionType::Unknown);
683            let right = next_region_boundary(&self, cur_right).unwrap();
684            proof! {
685                assert forall|addr: int| cur_right <= addr < right implies
686                    #[trigger] selected_type(source, addr, typ) by {
687                    reveal(selected_type);
688                    let covers_cur_right = |r: MemoryRegion| r.base() <= cur_right < r.end();
689                    if source.any(covers_cur_right) {
690                        let j = choose|j: int| #![trigger source[j]] 0 <= j < source.len()
691                            && source[j].base <= cur_right < source[j].end() && source[j].typ == typ;
692                        let covers_with_type = |r: MemoryRegion|
693                            r.base() <= addr < r.base() + r.len() && r.typ() == typ;
694                        let covers = |r: MemoryRegion| r.base() <= addr < r.base() + r.len();
695                        assert(covers_with_type(source[j]));
696                        assert(covers(source[j]));
697                    } else {
698                        assert forall|j: int| #![trigger source[j]] 0 <= j < source.len()
699                            implies !(source[j].base() <= cur_right < source[j].end()) by {
700                            assert(!covers_cur_right(source[j]));
701                        }
702                        assert(typ == MemoryRegionType::Unknown);
703                    }
704                }
705            }
706            proof_decl! { let ghost before = result@; }
707            proof! {
708                let j = choose|j: int| #![trigger source[j]] 0 <= j < source.len()
709                    && (source[j].base == right || source[j].end() == right);
710                assert(source[j].aligned(PAGE_SIZE as int));
711                assert(right % PAGE_SIZE == 0);
712                if source[j].base == right {
713                    assert(source.map_values(|r: MemoryRegion| r.base() as int)[j] == right);
714                } else {
715                    assert(source.map_values(|r: MemoryRegion| r.base() + r.len())[j] == right);
716                }
717                visited.lemma_subset_not_in_lt(bounds, right as int);
718                visited = visited.insert(right as int);
719            }
720
721            result
722                .push(MemoryRegion::new(cur_right, right - cur_right, typ))
723                .unwrap();
724
725            proof! {
726                assert forall|j: int| 0 <= j < result@.len() implies
727                    #[trigger] result@[j].aligned(PAGE_SIZE as int) by {
728                    if j < before.len() { assert(before[j].aligned(PAGE_SIZE as int)); }
729                }
730                assert forall|j: int| 0 <= j < result@.len() implies #[trigger] result@[j].len > 0 by {
731                    if j < before.len() { assert(before[j].aligned(PAGE_SIZE as int)); }
732                }
733                assert forall|j: int| 0 <= j < result@.len() implies #[trigger] result@[j].base + result@[j].len <= usize::MAX by {
734                    if j < before.len() { assert(before[j].aligned(PAGE_SIZE as int)); }
735                }
736                assert forall|j: int| 0 < j < result@.len() implies result@[j - 1].base + result@[j - 1].len == #[trigger] result@[j].base by {
737                    if j < before.len() { assert(before[j].aligned(PAGE_SIZE as int)); }
738                }
739            }
740
741            cur_right = right;
742        }
743
744        if result.is_empty() {
745            proof! { reveal(coalesced); }
746            return result;
747        }
748        // Merge the adjacent regions with the same type.
749        let mut merged_count = 1;
750        proof_decl! { let ghost split = result@; }
751        proof! {
752            assert(coalesced(result.regions@[..1])) by { reveal(coalesced); }
753            assert(is_partition(result.regions@[..1])) by {
754                assert(split[0].aligned(PAGE_SIZE as int));
755            }
756            assert(split.last().aligned(PAGE_SIZE as int));
757        }
758        #[verus_spec(
759            invariant
760                result.count == split.len() <= LEN,
761                1 <= merged_count <= i <= split.len(),
762                is_partition(split),
763                split.last().end() == cur_right,
764                cur_right == max_addr,
765                source == original.aligned_regions(),
766                source.len() > 0,
767                exists|j: int| 0 <= j < source.len() && #[trigger] source[j].end() == max_addr,
768                forall|j: int| 0 <= j < source.len() ==> #[trigger] source[j].end() <= max_addr,
769                coalesced(result.regions@[..merged_count]),
770                preserves_types(split, source),
771                preserves_types(result.regions@[..merged_count], source),
772                is_partition(result.regions@[..merged_count]),
773                result.regions@[..merged_count].last().end() == split[i - 1].end(),
774                forall|j: int| i <= j < split.len() ==> #[trigger] result.regions[j] == split[j],
775        )]
776        for i in 1..result.count {
777            proof_decl! { let ghost previous = result.regions@; let ghost old_count = merged_count; }
778            proof! {
779                let prefix = result.regions@[..merged_count];
780                assert(prefix.last().aligned(PAGE_SIZE as int));
781                assert(split[i as int].aligned(PAGE_SIZE as int));
782            }
783            if result[i].typ() == result.regions[merged_count - 1].typ() {
784                result.regions[merged_count - 1] = MemoryRegion::new(
785                    result.regions[merged_count - 1].base(),
786                    result.regions[merged_count - 1].len() + result[i].len(),
787                    result.regions[merged_count - 1].typ(),
788                );
789            } else {
790                result.regions[merged_count] = result[i];
791                merged_count += 1;
792            }
793            proof! {
794                let prefix = result.regions@[..merged_count];
795                assert(coalesced(prefix)) by {
796                    assert forall|j: int| #![trigger prefix[j].typ(), prefix[j - 1].typ()]
797                        0 < j < prefix.len() implies prefix[j].typ() != prefix[j - 1].typ() by {
798                        if j < old_count {
799                            reveal(coalesced);
800                            assert(previous[..old_count][j].typ()
801                                != previous[..old_count][j - 1].typ());
802                        }
803                    }
804                    reveal(coalesced);
805                }
806                assert(is_partition(prefix)) by {
807                    assert forall|j: int| 0 <= j < prefix.len() implies
808                        #[trigger] prefix[j].aligned(PAGE_SIZE as int) by {
809                        if j < old_count { assert(previous[..old_count][j].aligned(PAGE_SIZE as int)); }
810                    }
811                    assert forall|j: int| 0 <= j < prefix.len() implies #[trigger] prefix[j].len > 0 by {
812                        if j < old_count { assert(previous[..old_count][j].aligned(PAGE_SIZE as int)); }
813                    }
814                    assert forall|j: int| 0 <= j < prefix.len() implies #[trigger] prefix[j].base + prefix[j].len <= usize::MAX by {
815                        if j < old_count { assert(previous[..old_count][j].aligned(PAGE_SIZE as int)); }
816                    }
817                    assert forall|j: int| 0 < j < prefix.len() implies prefix[j - 1].base + prefix[j - 1].len == #[trigger] prefix[j].base by {
818                        if j < old_count { assert(previous[..old_count][j].aligned(PAGE_SIZE as int)); }
819                    }
820                }
821                assert(preserves_types(prefix, source)) by {
822                    let preserves_region = |r: MemoryRegion|
823                        forall|addr: int|
824                            r.base() <= addr < r.base() + r.len()
825                                ==> #[trigger] selected_type(source, addr, r.typ());
826                    assert forall|j: int, addr: int| #![trigger prefix[j], selected_type(source, addr, prefix[j].typ())]
827                        0 <= j < prefix.len() && prefix[j].base <= addr < prefix[j].base + prefix[j].len
828                        implies selected_type(source, addr, prefix[j].typ()) by {
829                        if j < old_count && addr < previous[j].base + previous[j].len {
830                            assert(preserves_region(previous[..old_count][j]));
831                        }
832                    }
833                }
834            }
835        }
836        result.count = merged_count;
837
838        proof! {
839            assert(result@ == result.regions@[..merged_count]);
840        }
841
842        result
843    }
844}
845
846/// Finds the largest end address among the active regions.
847#[verus_verify]
848#[verus_spec(ret =>
849    ensures
850        ret is None <==> regions@.len() == 0,
851        ret matches Some(end) ==> {
852            &&& regions@.any(|r: MemoryRegion| r.end() == end)
853            &&& regions@.all(|r: MemoryRegion| r.end() <= end)
854        },
855)]
856fn max_region_end(regions: &[MemoryRegion]) -> Option<usize> {
857    proof_decl! { let ghost source = regions@; }
858    let regions = regions.iter();
859    let region_end = #[verus_spec(end: usize => ensures end == r.end())]
860    |r: &MemoryRegion| r.end();
861    let ends = regions.map(region_end);
862    proof_decl! { let ghost ends_model = ends; }
863    let end = ends.max();
864    proof! {
865        axiom_iterator_max_postcondition(ends_model, end);
866        if let Some(greatest) = end {
867            let j = choose|j: int| 0 <= j < ends_model.remaining().len()
868                && ends_model.remaining()[j] == greatest;
869            let reaches_end = |r: MemoryRegion| r.end() == greatest;
870            assert(reaches_end(source[j]));
871            assert forall|j: int| 0 <= j < source.len() implies
872                #[trigger] source[j].end() <= greatest by {
873                assert(ends_model.remaining()[j] == source[j].end());
874            }
875        }
876    }
877    end
878}
879
880/// Finds the lowest usability of the regions covering `cur_right`.
881#[verus_verify]
882#[verus_spec(ret =>
883    ensures
884        ret matches Some(t) ==> exists|j: int| 0 <= j < regions@.len()
885            && #[trigger] regions@[j].base() <= cur_right < regions@[j].end()
886            && regions@[j].typ() == t,
887        forall|j: int| #![trigger regions@[j]] 0 <= j < regions@.len()
888            && regions@[j].base() <= cur_right < regions@[j].end()
889            ==> (ret matches Some(least) && least as int <= regions@[j].typ() as int),
890)]
891fn most_restrictive_type(regions: &[MemoryRegion], cur_right: usize) -> Option<MemoryRegionType> {
892    proof_decl! { let ghost source = regions@; }
893    let regions = regions.iter();
894    let keep_covering =
895        #[verus_spec(keep: bool =>
896        ensures keep == (region.base() <= cur_right < region.end()),
897    )]
898        move |region: &&MemoryRegion| (region.base()..region.end()).contains(&cur_right);
899    let covering = regions.filter(keep_covering);
900    proof_decl! { let ghost covering_model = covering; }
901    let region_type = #[verus_spec(typ: MemoryRegionType =>
902        ensures typ == region.typ(),
903    )]
904    |region: &MemoryRegion| region.typ();
905    let types = covering.map(region_type);
906    proof_decl! { let ghost types_model = types; }
907    proof! {
908        proof fn lemma_memory_region_type_order()
909            ensures
910                obeys_cmp::<MemoryRegionType>(),
911        {
912            reveal(obeys_cmp_ord);
913            reveal(obeys_cmp_partial_ord);
914            reveal(obeys_partial_cmp_spec_properties);
915            reveal(obeys_eq_spec_properties);
916        }
917        lemma_memory_region_type_order();
918    }
919    let typ = types.min();
920    proof! {
921        axiom_iterator_min_postcondition(types_model, typ);
922        assert forall|j: int| #![trigger source[j]] 0 <= j < source.len()
923            && source[j].base <= cur_right < source[j].end() implies
924            typ matches Some(least) && least as int <= source[j].typ as int by {
925            assert(covering_model.remaining().contains(source.as_ref()[j]));
926            let k = choose|k: int| 0 <= k < covering_model.remaining().len()
927                && covering_model.remaining()[k] == source.as_ref()[j];
928            assert(types_model.remaining()[k] == source[j].typ);
929        }
930    }
931    typ
932}
933
934/// Finds the first region boundary strictly beyond `cur_right`.
935#[verus_verify(spinoff_prover, rlimit(50))]
936#[verus_spec(ret =>
937    ensures
938        ret matches Some(bound) ==> {
939            &&& cur_right < bound
940            &&& exists|j: int| 0 <= j < regions@.len()
941                && (#[trigger] regions@[j].base() == bound || regions@[j].end() == bound)
942        },
943        forall|j: int| #![trigger regions@[j]] 0 <= j < regions@.len() ==> {
944            &&& (regions@[j].base() > cur_right ==> (ret matches Some(bound) && bound <= regions@[j].base()))
945            &&& (regions@[j].end() > cur_right ==> (ret matches Some(bound) && bound <= regions@[j].end()))
946        },
947)]
948fn next_region_boundary(regions: &[MemoryRegion], cur_right: usize) -> Option<usize> {
949    proof_decl! { let ghost source = regions@; }
950    let regions = regions.iter();
951    proof_decl! { let ghost regions_model = regions; }
952    let keep_future = #[verus_spec(keep: bool =>
953        ensures
954            keep == (region.end() > cur_right),
955            region.base() <= region.end(),
956    )]
957    move |region: &&MemoryRegion| {
958        proof! { use_type_invariant(*region); }
959        region.end() > cur_right
960    };
961    let future = regions.filter(keep_future);
962    proof_decl! { let ghost future_model = future; }
963    let next_boundary = #[verus_spec(bound: usize =>
964        ensures bound == if region.base() > cur_right { region.base() } else { region.end() },
965    )]
966    move |region: &MemoryRegion| {
967        if region.base() > cur_right {
968            region.base()
969        } else {
970            region.end()
971        }
972    };
973    let boundaries = future.map(next_boundary);
974    proof_decl! { let ghost boundaries_model = boundaries; }
975    let right = boundaries.min();
976    proof! {
977        axiom_iterator_min_postcondition(boundaries_model, right);
978        assert forall|k: int| 0 <= k < future_model.remaining().len()
979            implies #[trigger] IteratorSpec::produces(&future_model)[k] by {
980            assert(boundaries_model.produces()[k]);
981        }
982        assert forall|j: int| #![trigger source[j]] 0 <= j < source.len() implies {
983            &&& (source[j].base > cur_right ==> (right matches Some(bound) && bound <= source[j].base))
984            &&& (source[j].end() > cur_right ==> (right matches Some(bound) && bound <= source[j].end()))
985        } by {
986            if filter_keep(future_model)[j] {
987                let keep = |idx: int| filter_keep(future_model)[idx];
988                let k = regions_model.remaining()[..j].filter_index(keep).len() as int;
989                lemma_filter_index_take_len_lt(regions_model.remaining(), keep, j);
990            }
991            if source[j].end() > cur_right {
992                assert(future_model.remaining().contains(source.as_ref()[j]));
993                let k = choose|k: int| 0 <= k < future_model.remaining().len()
994                    && future_model.remaining()[k] == source.as_ref()[j];
995                assert(boundaries_model.remaining()[k] == if source[j].base > cur_right {
996                    source[j].base
997                } else {
998                    source[j].end()
999                });
1000            }
1001        }
1002    }
1003    right
1004}
1005
1006#[cfg(ktest)]
1007mod test {
1008    use super::*;
1009    use crate::prelude::ktest;
1010
1011    #[ktest]
1012    fn sort_full_non_overlapping() {
1013        let mut regions = MemoryRegionArray::<64>::new();
1014        // Regions that can be combined.
1015        regions
1016            .push(MemoryRegion::new(
1017                0,
1018                PAGE_SIZE + 1,
1019                MemoryRegionType::Usable,
1020            ))
1021            .unwrap();
1022        regions
1023            .push(MemoryRegion::new(
1024                PAGE_SIZE - 1,
1025                PAGE_SIZE + 2,
1026                MemoryRegionType::Usable,
1027            ))
1028            .unwrap();
1029        regions
1030            .push(MemoryRegion::new(
1031                PAGE_SIZE * 2,
1032                PAGE_SIZE * 5,
1033                MemoryRegionType::Usable,
1034            ))
1035            .unwrap();
1036        // A punctured region.
1037        regions
1038            .push(MemoryRegion::new(
1039                PAGE_SIZE * 3 + 1,
1040                PAGE_SIZE - 2,
1041                MemoryRegionType::BadMemory,
1042            ))
1043            .unwrap();
1044        // A far region that left a hole in the middle.
1045        regions
1046            .push(MemoryRegion::new(
1047                PAGE_SIZE * 9,
1048                PAGE_SIZE * 2,
1049                MemoryRegionType::Usable,
1050            ))
1051            .unwrap();
1052
1053        let regions = regions.into_non_overlapping();
1054
1055        assert_eq!(regions.count, 5);
1056        assert_eq!(regions[0].base(), 0);
1057        assert_eq!(regions[0].len(), PAGE_SIZE * 3);
1058        assert_eq!(regions[0].typ(), MemoryRegionType::Usable);
1059
1060        assert_eq!(regions[1].base(), PAGE_SIZE * 3);
1061        assert_eq!(regions[1].len(), PAGE_SIZE);
1062        assert_eq!(regions[1].typ(), MemoryRegionType::BadMemory);
1063
1064        assert_eq!(regions[2].base(), PAGE_SIZE * 4);
1065        assert_eq!(regions[2].len(), PAGE_SIZE * 3);
1066        assert_eq!(regions[2].typ(), MemoryRegionType::Usable);
1067
1068        assert_eq!(regions[3].base(), PAGE_SIZE * 7);
1069        assert_eq!(regions[3].len(), PAGE_SIZE * 2);
1070        assert_eq!(regions[3].typ(), MemoryRegionType::Unknown);
1071
1072        assert_eq!(regions[4].base(), PAGE_SIZE * 9);
1073        assert_eq!(regions[4].len(), PAGE_SIZE * 2);
1074        assert_eq!(regions[4].typ(), MemoryRegionType::Usable);
1075    }
1076
1077    #[ktest]
1078    fn into_non_overlapping_drops_usable_subpage_regions() {
1079        let mut regions = MemoryRegionArray::<64>::new();
1080        let bases = [
1081            100 * PAGE_SIZE,       // page-aligned
1082            100 * PAGE_SIZE + 123, // unaligned
1083        ];
1084        let subpage_lens = [0, PAGE_SIZE / 2, PAGE_SIZE - 1];
1085        for base in bases {
1086            for len in subpage_lens {
1087                regions
1088                    .push(MemoryRegion::new(base, len, MemoryRegionType::Usable))
1089                    .unwrap();
1090            }
1091        }
1092        // `into_non_overlapping` drops usable regions whose lengths are smaller than a page.
1093        let regions = regions.into_non_overlapping();
1094        assert!(regions.is_empty());
1095    }
1096}