starry-kernel 0.9.0

A Linux-compatible OS kernel built on ArceOS unikernel
Documentation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
//! Memory mapping backends.
use alloc::{
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};
use core::sync::atomic::{AtomicUsize, Ordering};

use ax_alloc::{UsageKind, global_allocator};
use ax_fs_ng::{file::CachedFileIdentity, vfs::CachedFile};
use ax_memory_addr::{DynPageIter, MemoryAddr, PAGE_SIZE_4K, PhysAddr, VirtAddr, VirtAddrRange};
use ax_memory_set::MappingBackend;
use ax_runtime::hal::{
    mem::{phys_to_virt, virt_to_phys},
    paging::{MappingFlags, PageTable},
};
use scope_local::scope_local;

use crate::{StarryError, StarryResult};

mod cow;
mod file;
mod linear;
mod shared;

pub use self::shared::SharedMemoryObject;
pub use super::accounting::RssKind;
use super::{
    AddressSpaceId,
    vma::{MappingId, VmaDescriptor},
};

fn mincore_file_visible(location: &axfs_ng_vfs::Location, cred: &crate::task::Cred) -> bool {
    use axfs_ng_vfs::NodePermission;

    let Ok(metadata) = location.metadata() else {
        return false;
    };
    cred.fsuid == metadata.uid
        || cred.has_cap_fowner()
        || cred.has_cap_dac_override()
        || metadata.mode.contains(if cred.in_group(metadata.gid) {
            NodePermission::GROUP_WRITE
        } else {
            NodePermission::OTHER_WRITE
        })
}

scope_local! {
    static DEFER_TLB_RETIRE: AtomicUsize = AtomicUsize::new(0);
}

/// Marks one backend-unmap scope as owned by an outer address-space receipt.
///
/// The guard is scope-local rather than global: another CPU or a nested
/// rollback must never inherit a decision to skip its immediate invalidation.
/// The outer caller has already reserved and retained every affected mapping
/// owner before entering this scope.
pub(crate) struct DeferredTlbRetireGuard {
    previous: usize,
    _not_send: core::marker::PhantomData<*mut ()>,
}

impl DeferredTlbRetireGuard {
    pub(crate) fn enter() -> Self {
        let previous = DEFER_TLB_RETIRE.with(|state| state.swap(1, Ordering::AcqRel));
        Self {
            previous,
            _not_send: core::marker::PhantomData,
        }
    }
}

impl Drop for DeferredTlbRetireGuard {
    fn drop(&mut self) {
        DEFER_TLB_RETIRE.with(|state| state.store(self.previous, Ordering::Release));
    }
}

pub(super) fn tlb_retire_is_deferred() -> bool {
    DEFER_TLB_RETIRE.with(|state| state.load(Ordering::Acquire) != 0)
}

fn divide_page(size: usize, page_size: usize) -> usize {
    assert!(size.is_multiple_of(page_size), "unaligned");
    size >> page_size.trailing_zeros()
}

pub(crate) fn alloc_frame(zeroed: bool, size: usize) -> StarryResult<PhysAddr> {
    let num_pages = size / PAGE_SIZE_4K;
    let vaddr = VirtAddr::from(
        global_allocator()
            .alloc_pages(num_pages, size, UsageKind::VirtMem)
            .map_err(|_| StarryError::NoMemory)?,
    );
    if zeroed {
        unsafe { core::ptr::write_bytes(vaddr.as_mut_ptr(), 0, size) };
    }
    let paddr = virt_to_phys(vaddr);

    Ok(paddr)
}

pub(crate) fn dealloc_frame(frame: PhysAddr, align: usize) {
    let vaddr = phys_to_virt(frame);
    let num_pages = align / PAGE_SIZE_4K;
    global_allocator().dealloc_pages(vaddr.as_usize(), num_pages, UsageKind::VirtMem);
}

fn pages_in(range: VirtAddrRange, align: usize) -> StarryResult<DynPageIter<VirtAddr>> {
    DynPageIter::new(range.start, range.end, align).ok_or(StarryError::InvalidInput)
}

/// Returns only materialized page-table leaves wholly contained in `range`.
///
/// Lazy VMAs may span terabytes while owning only a handful of leaves.  Linux
/// walks page-table directories for these operations instead of probing every
/// base-page address.  Keeping the same rule here makes `mmap`, `mprotect`,
/// `munmap`, and sparse `fork` proportional to materialized state.
fn occupied_leaf_ranges(
    range: VirtAddrRange,
    pt: &PageTable,
) -> StarryResult<Vec<(VirtAddr, usize)>> {
    if range.is_empty() || !range.start.is_aligned_4k() || !range.end.is_aligned_4k() {
        return Err(StarryError::InvalidInput);
    }
    let occupied = pt.walk_occupied_range(range.start, range.end);
    let (lower, upper) = occupied.size_hint();
    let mut leaves = Vec::new();
    leaves
        .try_reserve(upper.unwrap_or(lower))
        .map_err(|_| StarryError::NoMemory)?;
    for entry in occupied {
        let leaf_size = pt
            .mapping_size_for_level(entry.level)
            .ok_or(StarryError::BadState)?;
        let leaf_end = entry
            .vaddr
            .checked_add(leaf_size)
            .ok_or(StarryError::BadState)?;
        if leaf_size < PAGE_SIZE_4K
            || !leaf_size.is_power_of_two()
            || entry.vaddr < range.start
            || leaf_end > range.end
        {
            return Err(StarryError::OperationNotSupported);
        }
        leaves.try_reserve(1).map_err(|_| StarryError::NoMemory)?;
        leaves.push((entry.vaddr, leaf_size));
    }
    Ok(leaves)
}

fn validate_occupied_leaf_range(
    range: VirtAddrRange,
    expected_leaf_size: Option<usize>,
    pt: &PageTable,
) -> bool {
    occupied_leaf_ranges(range, pt).is_ok_and(|leaves| {
        expected_leaf_size
            .is_none_or(|expected| leaves.iter().all(|(_, leaf_size)| *leaf_size == expected))
    })
}

/// How one backend PTE operation changed the software owner expected at a
/// virtual address.
///
/// The backend already owns the exact [`PageObject`] when it installs or
/// replaces a PTE.  Returning that object keeps `AddrSpace` from reconstructing
/// ownership later from a raw PFN.  `Updated` means the PTE still names the
/// same object but permissions or resident classification changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PteOwnerTransition {
    Installed,
    Replaced,
    Updated,
}

/// Provider-side state that must be consumed only after the MappingSlot/rmap
/// has been published.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ProviderPublication {
    Complete,
    Pending,
}

/// Exact software owner prepared by one materialized PTE operation.
///
/// This is the Rust equivalent of carrying a referenced folio through Linux's
/// fault path: the PTE address is still rechecked under the address-space
/// mutation gate, but the owner is never rediscovered from the PTE PFN.
pub(super) struct PreparedPteOwner {
    pub va: VirtAddr,
    /// Materialized physical address for this leaf.  This is identity data,
    /// not an owning token; `page: Arc<PageObject>` remains the sole frame
    /// owner and bounds-checks this address during publication.
    pub paddr: PhysAddr,
    pub page_size: usize,
    pub page: Arc<super::objects::PageObject>,
    pub resident_kind: Option<RssKind>,
    pub transition: PteOwnerTransition,
    pub provider_publication: ProviderPublication,
}

impl PreparedPteOwner {
    pub(super) fn installed(
        va: VirtAddr,
        paddr: PhysAddr,
        page_size: usize,
        page: Arc<super::objects::PageObject>,
        resident_kind: Option<RssKind>,
        provider_publication: ProviderPublication,
    ) -> Self {
        Self {
            va,
            paddr,
            page_size,
            page,
            resident_kind,
            transition: PteOwnerTransition::Installed,
            provider_publication,
        }
    }

    pub(super) fn replaced(
        va: VirtAddr,
        paddr: PhysAddr,
        page_size: usize,
        page: Arc<super::objects::PageObject>,
        resident_kind: Option<RssKind>,
        provider_publication: ProviderPublication,
    ) -> Self {
        Self {
            va,
            paddr,
            page_size,
            page,
            resident_kind,
            transition: PteOwnerTransition::Replaced,
            provider_publication,
        }
    }

    pub(super) fn updated(
        va: VirtAddr,
        paddr: PhysAddr,
        page_size: usize,
        page: Arc<super::objects::PageObject>,
        resident_kind: Option<RssKind>,
    ) -> Self {
        Self {
            va,
            paddr,
            page_size,
            page,
            resident_kind,
            transition: PteOwnerTransition::Updated,
            provider_publication: ProviderPublication::Complete,
        }
    }
}

/// Materialized-PTE result returned by every backend operation.
///
/// `satisfied_pages` preserves Linux fault/populate return semantics, while
/// `owners` contains only PTEs whose owner or resident classification changed
/// in this operation.  The vector is fully reserved by the producer before
/// returning, so publication does not need to rediscover any page identity.
#[derive(Default)]
pub(super) struct PteMaterialization {
    satisfied_pages: usize,
    owners: Vec<PreparedPteOwner>,
}

/// Typed request for materializing one VMA range.
///
/// Bulk population retains the backend's native granule. A fault request also
/// carries the exact faulting address so an anonymous transparent-huge
/// allocation can fall back to the correct 4 KiB page without smuggling that
/// address through an aligned range endpoint.
#[derive(Clone, Copy, Debug)]
pub(super) struct PopulateRequest {
    range: VirtAddrRange,
    preferred_leaf_size: usize,
    fault_address: Option<VirtAddr>,
    fallback: FaultFallback,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum FaultFallback {
    Forbidden,
    BasePage,
}

/// Stable PTE state captured before a fault drops the address-space mutex.
///
/// Backends use this copyable value to prepare a page, cache pin, or COW copy
/// without constructing a speculative page table. The live PTE is rechecked
/// under its stripe immediately before the prepared descriptor is installed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum FaultPteSnapshot {
    NotMapped,
    Mapped {
        paddr: PhysAddr,
        flags: MappingFlags,
        page_size: usize,
    },
}

impl FaultPteSnapshot {
    pub(super) fn capture(pt: &PageTable, va: VirtAddr) -> StarryResult<Self> {
        match pt.query(va) {
            Ok((paddr, flags, page_size)) => Ok(Self::Mapped {
                paddr,
                flags,
                page_size,
            }),
            Err(ax_runtime::hal::paging::PagingError::NotMapped) => Ok(Self::NotMapped),
            Err(error) => Err(error.into()),
        }
    }

    pub(super) fn matches(self, va: VirtAddr, pt: &PageTable) -> bool {
        match (self, pt.query(va)) {
            (Self::NotMapped, Err(ax_runtime::hal::paging::PagingError::NotMapped)) => true,
            (
                Self::Mapped {
                    paddr,
                    flags,
                    page_size,
                },
                Ok((current_paddr, current_flags, current_size)),
            ) => paddr == current_paddr && flags == current_flags && page_size == current_size,
            _ => false,
        }
    }
}

/// Allocation-free, single-leaf result of backend fault preparation.
///
/// Bulk population keeps using [`PteMaterialization`], but a hardware fault
/// carries at most one owner inline, like Linux's `vm_fault` folio reference.
/// The page-table flags are bound to the owner before the live PTE lock is
/// acquired, so apply consists only of a stale-state check and one descriptor
/// update.
pub(super) struct FaultMaterialization {
    satisfied_pages: usize,
    owner: Option<PreparedPteOwner>,
    pte_flags: Option<MappingFlags>,
}

impl FaultMaterialization {
    pub(super) const fn empty() -> Self {
        Self {
            satisfied_pages: 0,
            owner: None,
            pte_flags: None,
        }
    }

    pub(super) const fn satisfied(satisfied_pages: usize) -> Self {
        Self {
            satisfied_pages,
            owner: None,
            pte_flags: None,
        }
    }

    pub(super) const fn with_owner(
        satisfied_pages: usize,
        owner: PreparedPteOwner,
        pte_flags: MappingFlags,
    ) -> Self {
        Self {
            satisfied_pages,
            owner: Some(owner),
            pte_flags: Some(pte_flags),
        }
    }

    pub(super) const fn satisfied_pages(&self) -> usize {
        self.satisfied_pages
    }

    pub(super) const fn owner(&self) -> Option<&PreparedPteOwner> {
        self.owner.as_ref()
    }

    pub(super) const fn pte_flags(&self) -> Option<MappingFlags> {
        self.pte_flags
    }

    fn into_owner(self) -> Option<PreparedPteOwner> {
        self.owner
    }
}

impl PopulateRequest {
    pub(super) fn area(range: VirtAddrRange, preferred_leaf_size: usize) -> StarryResult<Self> {
        Self::new(range, preferred_leaf_size, None, FaultFallback::Forbidden)
    }

    pub(super) fn fault(
        range: VirtAddrRange,
        preferred_leaf_size: usize,
        fault_address: VirtAddr,
        fallback: FaultFallback,
    ) -> StarryResult<Self> {
        Self::new(range, preferred_leaf_size, Some(fault_address), fallback)
    }

    fn new(
        range: VirtAddrRange,
        preferred_leaf_size: usize,
        fault_address: Option<VirtAddr>,
        fallback: FaultFallback,
    ) -> StarryResult<Self> {
        if range.is_empty()
            || preferred_leaf_size < PAGE_SIZE_4K
            || !preferred_leaf_size.is_power_of_two()
            || !preferred_leaf_size.is_multiple_of(PAGE_SIZE_4K)
            || fault_address.is_some_and(|address| !range.contains(address))
        {
            return Err(StarryError::InvalidInput);
        }
        Ok(Self {
            range,
            preferred_leaf_size,
            fault_address,
            fallback,
        })
    }

    pub(super) const fn range(self) -> VirtAddrRange {
        self.range
    }

    pub(super) const fn preferred_leaf_size(self) -> usize {
        self.preferred_leaf_size
    }

    pub(super) const fn fault_address(self) -> Option<VirtAddr> {
        self.fault_address
    }

    pub(super) const fn fallback(self) -> FaultFallback {
        self.fallback
    }

    /// Narrows a transparent-huge fault to its faulting base page.
    ///
    /// Linux may abandon a prepared huge folio when a later page-table
    /// allocation fails, release that reservation, and retry the base-page
    /// fault. Keeping this transition on the typed request prevents callers
    /// from accidentally retaining the original 2 MiB publication range.
    pub(super) fn into_base_page_fallback(self) -> Option<Self> {
        if self.fallback != FaultFallback::BasePage || self.preferred_leaf_size <= PAGE_SIZE_4K {
            return None;
        }
        let fault_address = self.fault_address?;
        let range =
            VirtAddrRange::try_from_start_size(fault_address.align_down_4k(), PAGE_SIZE_4K)?;
        Self::fault(range, PAGE_SIZE_4K, fault_address, FaultFallback::Forbidden).ok()
    }
}

impl PteMaterialization {
    pub(super) const fn empty() -> Self {
        Self {
            satisfied_pages: 0,
            owners: Vec::new(),
        }
    }

    pub(super) fn with_capacity(capacity: usize) -> StarryResult<Self> {
        let mut owners = Vec::new();
        owners
            .try_reserve(capacity)
            .map_err(|_| StarryError::NoMemory)?;
        Ok(Self {
            satisfied_pages: 0,
            owners,
        })
    }

    pub(super) const fn satisfied_pages(&self) -> usize {
        self.satisfied_pages
    }

    pub(super) fn owners(&self) -> &[PreparedPteOwner] {
        &self.owners
    }

    pub(super) fn set_satisfied_pages(&mut self, pages: usize) {
        self.satisfied_pages = pages;
    }

    pub(super) fn increment_satisfied(&mut self, pages: usize) -> StarryResult {
        self.satisfied_pages = self
            .satisfied_pages
            .checked_add(pages)
            .ok_or(StarryError::NoMemory)?;
        Ok(())
    }

    pub(super) fn push(&mut self, owner: PreparedPteOwner) {
        self.owners.push(owner);
    }

    pub(super) fn append(&mut self, mut other: Self) -> StarryResult {
        self.satisfied_pages = self
            .satisfied_pages
            .checked_add(other.satisfied_pages)
            .ok_or(StarryError::NoMemory)?;
        self.owners
            .try_reserve(other.owners.len())
            .map_err(|_| StarryError::NoMemory)?;
        self.owners.append(&mut other.owners);
        Ok(())
    }
}

pub(super) trait MappingExecution {
    /// Returns the page size of the backend.
    fn page_size(&self) -> usize;

    /// Describe the logical mapping represented by this backend.  The
    /// descriptor is pure metadata and must not perform file I/O; it is used
    /// while publishing an immutable VMA snapshot.
    fn vma_descriptor(&self, area_start: VirtAddr) -> VmaDescriptor;

    /// Map a memory region.
    fn map(
        &self,
        range: VirtAddrRange,
        flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult<PteMaterialization>;

    /// Read-only map preflight.  Lazy backends may accept an empty page table;
    /// resident/device backends should reject malformed or conflicting leaves
    /// before an overlapping replacement removes the old VMA.
    fn validate_map(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        if range.is_empty()
            || !range.start.is_aligned(self.page_size())
            || !range.end.is_aligned(self.page_size())
        {
            return false;
        }
        pt.walk_occupied_range(range.start, range.end)
            .next()
            .is_none()
    }

    /// Unmap a memory region.
    fn unmap(&self, range: VirtAddrRange, pt: &mut PageTable) -> StarryResult;

    /// Read-only unmap preflight. `NotMapped` is valid for lazy mappings;
    /// malformed page-table walks are rejected before any leaf is detached.
    fn validate_unmap(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        validate_occupied_leaf_range(range, Some(self.page_size()), pt)
    }

    /// Read-only protection preflight. A non-resident lazy page is legal, but
    /// every resident leaf must be structurally queryable and use one backend
    /// page size.
    fn validate_protect(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        validate_occupied_leaf_range(range, Some(self.page_size()), pt)
    }

    /// Called before a memory region is protected.
    fn on_protect(
        &self,
        _range: VirtAddrRange,
        _new_flags: MappingFlags,
        _pt: &mut PageTable,
    ) -> StarryResult {
        Ok(())
    }

    /// Populate a memory region and return how many pages now satisfy
    /// `access_flags`.
    ///
    /// If another thread has already mapped the page with sufficient permissions,
    /// treat it as populated.
    fn populate(
        &self,
        _space_id: AddressSpaceId,
        _request: PopulateRequest,
        _flags: MappingFlags,
        _access_flags: MappingFlags,
        _pt: &mut PageTable,
    ) -> StarryResult<PteMaterialization> {
        Ok(PteMaterialization::empty())
    }

    /// Prepares exactly one hardware-fault leaf without mutating a page table.
    ///
    /// Implementations may allocate frames or perform file I/O here. They may
    /// not publish a PTE or rmap; those steps happen after the caller reacquires
    /// the address-space mutex and rechecks `preimage` under the PTE stripe.
    fn prepare_fault(
        &self,
        _space_id: AddressSpaceId,
        _request: PopulateRequest,
        _flags: MappingFlags,
        _access_flags: MappingFlags,
        _preimage: FaultPteSnapshot,
    ) -> StarryResult<FaultMaterialization> {
        Ok(FaultMaterialization::empty())
    }

    /// Duplicates this mapping for use in a different page table.
    ///
    /// This differs from `clone`, which is designed for splitting a mapping
    /// within the same table. Eager backends must install every resident child
    /// leaf before returning; lazy backends may return metadata that can
    /// reconstruct a missing leaf from [`MappingExecution::populate`].
    fn clone_map(
        &self,
        range: VirtAddrRange,
        flags: MappingFlags,
        old_pt: &mut PageTable,
        new_pt: &mut PageTable,
    ) -> StarryResult<(MappingOperation, PteMaterialization)>;

    /// Splits the backend into two at the given position, and returns the backend for the upper part.
    ///
    /// The original backend is shrunk to the lower part.
    ///
    /// Returns `None` if the given position is not in the memory area, or one
    /// of the parts is empty after splitting.
    fn split(&mut self, align_diff: usize) -> Option<MappingOperation>;

    /// Shrinks the backend from the left by the given size.
    fn shrink_left(&mut self, _shrink_size: usize) -> bool;

    /// Shrinks the backend from the right by the given size.
    fn shrink_right(&mut self, _shrink_size: usize) -> bool;
}

/// Executable mapping policy retained privately by one immutable VMA node.
///
/// The closed dispatch enum is deliberately private.  Callers observe logical
/// mapping metadata through `VmaDescriptor`/`MappingSource` and invoke named
/// capabilities on this value; they cannot recover a second public source-kind
/// enum and make ownership decisions from it.  This mirrors Linux's split
/// between immutable VMA metadata and the mapping operations used to
/// materialize or retire PTEs.
#[derive(Clone)]
pub struct MappingOperation {
    kind: MappingOperationKind,
}

#[derive(Clone)]
enum MappingOperationKind {
    Linear(linear::LinearBackend),
    Cow(cow::CowBackend),
    Shared(shared::SharedBackend),
    File(file::FileBackend),
}

/// Stable ownership domain used by a process-shared futex key.
///
/// Linux keys shared futexes by the backing shmem object or inode rather than
/// by a VMA fragment.  These typed identities provide the same stability
/// across VMA splits, relocation and independently opened cached-file handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SharedFutexRegion {
    SharedMemory(MappingId),
    File(CachedFileIdentity),
}

/// Logical location of a futex within one shared backing object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SharedFutexIdentity {
    region: SharedFutexRegion,
    offset: usize,
}

impl SharedFutexIdentity {
    const fn shared_memory(mapping: MappingId, offset: usize) -> Self {
        Self {
            region: SharedFutexRegion::SharedMemory(mapping),
            offset,
        }
    }

    const fn file(cache: CachedFileIdentity, offset: usize) -> Self {
        Self {
            region: SharedFutexRegion::File(cache),
            offset,
        }
    }

    pub const fn region(self) -> SharedFutexRegion {
        self.region
    }

    pub const fn offset(self) -> usize {
        self.offset
    }
}

#[derive(Debug, Clone)]
pub struct MappingFileInfo {
    pub path: String,
    pub offset: Option<u64>,
    pub inode: Option<u64>,
    pub dev: Option<u64>,
    pub shared: bool,
}

/// Owned shared-file capability that may outlive the VMA publication lock.
/// It retains the file/cache executor but exposes only operations valid for a
/// shared file mapping; callers cannot recover the closed mapping-operation
/// dispatch type from it.
#[derive(Clone)]
pub(crate) struct SharedFileMappingLease {
    backend: file::FileBackend,
}

impl SharedFileMappingLease {
    pub(crate) fn check_flags(&self, flags: MappingFlags) -> StarryResult {
        self.backend.check_flags(flags)
    }

    pub(crate) fn cache(&self) -> &CachedFile {
        self.backend.cache()
    }

    pub(crate) fn cache_location(&self) -> &axfs_ng_vfs::Location {
        self.backend.cache_location()
    }

    pub(crate) fn file_offset_at(&self, address: VirtAddr) -> u64 {
        self.backend.file_offset_at(address)
    }

    pub(crate) fn writeback_range(&self, start: VirtAddr, end: VirtAddr) -> StarryResult {
        self.backend.writeback_range(start, end)
    }

    pub(crate) fn pageout_range(
        &self,
        start: VirtAddr,
        end: VirtAddr,
    ) -> StarryResult<ax_fs_ng::file::CachePageoutResult> {
        self.backend.pageout_range(start, end)
    }
}

/// Exact materialized leaf retained by a mapping preimage.
///
/// Grouping identity, PTE shape and accounting ownership prevents rollback
/// callers from accidentally restoring only a subset of one resident fact.
pub(crate) struct ResidentLeafRestore<'a> {
    pub va: VirtAddr,
    pub paddr: PhysAddr,
    pub page_size: usize,
    pub flags: MappingFlags,
    pub page: Option<&'a Arc<super::objects::PageObject>>,
}

impl MappingOperation {
    fn from_linear(backend: linear::LinearBackend) -> Self {
        Self {
            kind: MappingOperationKind::Linear(backend),
        }
    }

    fn from_cow(backend: cow::CowBackend) -> Self {
        Self {
            kind: MappingOperationKind::Cow(backend),
        }
    }

    fn from_shared(backend: shared::SharedBackend) -> Self {
        Self {
            kind: MappingOperationKind::Shared(backend),
        }
    }

    fn from_file(backend: file::FileBackend) -> Self {
        Self {
            kind: MappingOperationKind::File(backend),
        }
    }

    /// Page granularity required by the execution policy.
    pub fn page_size(&self) -> usize {
        MappingExecution::page_size(self)
    }

    pub(crate) fn validate_map_range(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        MappingExecution::validate_map(self, range, pt)
    }

    pub(super) fn map_range(
        &self,
        range: VirtAddrRange,
        flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult<PteMaterialization> {
        MappingExecution::map(self, range, flags, pt)
    }

    pub(crate) fn validate_protect_range(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        MappingExecution::validate_protect(self, range, pt)
    }

    pub(crate) fn protect_range(
        &self,
        range: VirtAddrRange,
        new_flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult {
        MappingExecution::on_protect(self, range, new_flags, pt)?;
        let pte_flags = match &self.kind {
            MappingOperationKind::Cow(cow) => cow.pte_flags_for_protect(new_flags),
            _ => new_flags,
        };
        // VMA metadata may cover an enormous sparse range.  Protect only the
        // materialized leaves collected before the first PTE write; probing
        // every 4 KiB address would turn an otherwise metadata-only mprotect
        // into an unbounded syscall.
        let leaves = occupied_leaf_ranges(range, pt)?;
        for (va, expected_size) in leaves {
            if pt.protect_page(va, pte_flags)? != expected_size {
                return Err(StarryError::BadState);
            }
        }
        Ok(())
    }

    /// Returns the execution policy for one contained VMA fragment.
    ///
    /// Backend split/shrink operations update source coordinates but do not
    /// touch PTEs. The original value remains a complete rollback preimage.
    pub(crate) fn fragment(
        &self,
        source: VirtAddrRange,
        fragment: VirtAddrRange,
    ) -> StarryResult<Self> {
        if fragment.is_empty() || fragment.start < source.start || fragment.end > source.end {
            return Err(StarryError::InvalidInput);
        }
        let mut operation = self.clone();
        if fragment.start > source.start {
            let offset = fragment
                .start
                .checked_sub_addr(source.start)
                .ok_or(StarryError::InvalidInput)?;
            operation =
                MappingExecution::split(&mut operation, offset).ok_or(StarryError::BadState)?;
        }
        if fragment.end < source.end {
            let shrink = source
                .end
                .checked_sub_addr(fragment.end)
                .ok_or(StarryError::InvalidInput)?;
            if !MappingExecution::shrink_right(&mut operation, shrink) {
                return Err(StarryError::BadState);
            }
        }
        Ok(operation)
    }

    /// Returns a capability only when this operation represents a shared file
    /// VMA. Private file mappings execute through COW and intentionally do not
    /// expose shared writeback or hole-punch operations.
    pub(crate) fn shared_file_lease(&self) -> Option<SharedFileMappingLease> {
        match &self.kind {
            MappingOperationKind::File(backend) if backend.is_shared_file_map() => {
                Some(SharedFileMappingLease {
                    backend: backend.clone(),
                })
            }
            _ => None,
        }
    }

    pub(crate) fn shared_memory_object(&self) -> Option<Arc<SharedMemoryObject>> {
        match &self.kind {
            MappingOperationKind::Shared(backend) => Some(backend.object().clone()),
            _ => None,
        }
    }

    pub(crate) fn mremap_alignment(&self) -> usize {
        match &self.kind {
            MappingOperationKind::Shared(shared) => shared.mapping_alignment(),
            MappingOperationKind::Linear(_)
            | MappingOperationKind::Cow(_)
            | MappingOperationKind::File(_) => PAGE_SIZE_4K,
        }
    }

    pub(crate) fn supports_mremap_dontunmap(&self) -> bool {
        matches!(&self.kind, MappingOperationKind::Cow(cow) if cow.is_anonymous())
    }

    pub(crate) fn is_linear(&self) -> bool {
        matches!(&self.kind, MappingOperationKind::Linear(_))
    }

    pub(crate) fn is_private_anonymous(&self) -> bool {
        self.supports_mremap_dontunmap()
    }

    /// Derive the Linux `VM_MAY*`-equivalent permission envelope from the
    /// executable mapping capability rather than exposing its concrete kind.
    pub(crate) fn maximum_mapping_flags(&self, current: MappingFlags) -> MappingFlags {
        let permission_bits =
            MappingFlags::READ | MappingFlags::WRITE | MappingFlags::EXECUTE | MappingFlags::USER;
        let attributes = current - permission_bits;
        match &self.kind {
            MappingOperationKind::Cow(_) | MappingOperationKind::Shared(_) => {
                attributes | permission_bits
            }
            MappingOperationKind::File(file) => {
                let mut maximum =
                    attributes | MappingFlags::READ | MappingFlags::EXECUTE | MappingFlags::USER;
                if file.check_flags(MappingFlags::WRITE).is_ok() {
                    maximum |= MappingFlags::WRITE;
                }
                maximum
            }
            MappingOperationKind::Linear(_) => current,
        }
    }

    pub(crate) fn check_mprotect_flags(&self, flags: MappingFlags) -> StarryResult {
        match &self.kind {
            MappingOperationKind::File(file) => file.check_flags(flags),
            _ => Ok(()),
        }
    }

    pub(crate) fn validate_discard_fragment(&self, range: VirtAddrRange) -> StarryResult {
        match &self.kind {
            MappingOperationKind::Linear(_) => Err(StarryError::InvalidInput),
            MappingOperationKind::Shared(_)
                if !range.start.is_aligned(self.page_size())
                    || !range.end.is_aligned(self.page_size()) =>
            {
                Err(StarryError::OperationNotSupported)
            }
            MappingOperationKind::Cow(_)
            | MappingOperationKind::Shared(_)
            | MappingOperationKind::File(_) => Ok(()),
        }
    }

    pub(crate) fn pin_file_cache_owner_for_mapping(
        &self,
        address: VirtAddr,
        paddr: PhysAddr,
    ) -> StarryResult<Option<ax_fs_ng::file::CachedPagePin>> {
        match &self.kind {
            MappingOperationKind::File(file) => {
                file.pin_cache_owner_for_mapping(address, paddr).map(Some)
            }
            _ => Ok(None),
        }
    }

    pub(super) fn populate(
        &self,
        space_id: AddressSpaceId,
        request: PopulateRequest,
        flags: MappingFlags,
        access_flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult<PteMaterialization> {
        MappingExecution::populate(self, space_id, request, flags, access_flags, pt)
    }

    pub(super) fn prepare_fault(
        &self,
        space_id: AddressSpaceId,
        request: PopulateRequest,
        flags: MappingFlags,
        access_flags: MappingFlags,
        preimage: FaultPteSnapshot,
    ) -> StarryResult<FaultMaterialization> {
        MappingExecution::prepare_fault(self, space_id, request, flags, access_flags, preimage)
    }

    pub(super) fn clone_map(
        &self,
        range: VirtAddrRange,
        flags: MappingFlags,
        old_pt: &mut PageTable,
        new_pt: &mut PageTable,
    ) -> StarryResult<(Self, PteMaterialization)> {
        MappingExecution::clone_map(self, range, flags, old_pt, new_pt)
    }

    pub(crate) fn validate_unmap_range(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        MappingExecution::validate_unmap(self, range, pt)
    }

    pub(crate) fn unmap_range(&self, range: VirtAddrRange, pt: &mut PageTable) -> StarryResult {
        MappingExecution::unmap(self, range, pt)
    }

    /// Resolve a process-shared futex against its backing object rather than
    /// against the current VMA fragment.
    pub(crate) fn shared_futex_identity(&self, address: VirtAddr) -> Option<SharedFutexIdentity> {
        match &self.kind {
            MappingOperationKind::Shared(shared) => shared.shared_futex_identity(address),
            MappingOperationKind::File(file) => file.shared_futex_identity(address),
            MappingOperationKind::Linear(_) | MappingOperationKind::Cow(_) => None,
        }
    }

    /// Returns whether fork must remove write permission from resident parent
    /// PTEs before the child address space can be published.
    pub(crate) const fn requires_fork_write_protect(&self) -> bool {
        matches!(&self.kind, MappingOperationKind::Cow(_))
    }

    pub(crate) fn mapping_id(&self) -> super::vma::MappingId {
        match &self.kind {
            MappingOperationKind::Linear(backend) => backend.mapping_id(),
            MappingOperationKind::Cow(backend) => backend.mapping_id(),
            MappingOperationKind::Shared(backend) => backend.object().mapping_id(),
            MappingOperationKind::File(backend) => backend.mapping_id(),
        }
    }

    /// Completes a provider's temporary PTE-to-PageObject identity
    /// reservation after the MappingSlot and rmap are published.
    pub(crate) fn finish_page_publication(
        &self,
        va: VirtAddr,
        page: &Arc<super::objects::PageObject>,
    ) -> StarryResult {
        match &self.kind {
            MappingOperationKind::Cow(cow) => cow.publish_page_object(page),
            MappingOperationKind::File(file) => file.finish_page_publication(va, page),
            MappingOperationKind::Linear(_) | MappingOperationKind::Shared(_) => Ok(()),
        }
    }

    /// Cancels the one provider reservation carried inline by a fault token.
    /// This runs after the address-space mutex is released.
    pub(super) fn cancel_prepared_fault_publication(
        &self,
        materialization: FaultMaterialization,
    ) -> StarryResult {
        let Some(owner) = materialization.into_owner() else {
            return Ok(());
        };
        if owner.provider_publication != ProviderPublication::Pending {
            return Ok(());
        }
        match &self.kind {
            MappingOperationKind::Cow(cow) => cow.cancel_page_publication(&owner.page),
            MappingOperationKind::File(file) => file.cancel_page_publication(owner.va, &owner.page),
            MappingOperationKind::Linear(_) | MappingOperationKind::Shared(_) => Ok(()),
        }
    }

    /// Restores one exact resident leaf retained by a mutation preimage.
    /// MappingOperation reference accounting is re-established before the PTE becomes
    /// visible; failures undo that reservation rather than publishing a leaf
    /// whose frame owner has already retired.
    pub(crate) fn restore_resident_preimage(
        &self,
        leaf: ResidentLeafRestore<'_>,
        pt: &mut PageTable,
    ) -> StarryResult {
        let ResidentLeafRestore {
            va,
            paddr,
            page_size,
            flags,
            page,
        } = leaf;
        match &self.kind {
            MappingOperationKind::Cow(cow) => {
                let page = page.ok_or(StarryError::BadState)?;
                cow.restore_page_identity(page)?;
            }
            MappingOperationKind::File(file) => {
                let page = page.ok_or(StarryError::BadState)?;
                file.ensure_page_identity(va, page)?;
            }
            MappingOperationKind::Linear(_) | MappingOperationKind::Shared(_) => {}
        }

        if let Err(error) = pt.map_page(va, paddr, page_size, flags) {
            return Err(error.into());
        }
        Ok(())
    }

    /// Returns whether a fault may report an object/address SIGBUS when no
    /// page can be supplied (for example a file mapping beyond EOF).
    pub fn is_file_backed(&self) -> bool {
        match &self.kind {
            MappingOperationKind::Cow(backend) => !backend.is_anonymous(),
            MappingOperationKind::File(_) => true,
            MappingOperationKind::Linear(_) | MappingOperationKind::Shared(_) => false,
        }
    }

    /// Reports the mincore bit after releasing the MM metadata lock. File
    /// queries use the caller's ordinary inode ownership/write-access policy;
    /// unavailable precise information is represented as resident, as Linux
    /// can_do_mincore specifies.
    pub(crate) fn mincore_resident(&self, va: VirtAddr, cred: &crate::task::Cred) -> bool {
        match &self.kind {
            MappingOperationKind::Cow(cow) => {
                cow.mincore_location()
                    .is_some_and(|location| !mincore_file_visible(location, cred))
                    || cow.page_cache_resident(va)
            }
            MappingOperationKind::File(file) => {
                !mincore_file_visible(file.mincore_location(), cred) || file.page_cache_resident(va)
            }
            MappingOperationKind::Shared(shared) => shared.page_cache_resident(va),
            MappingOperationKind::Linear(_) => true,
        }
    }

    /// Return the immutable VMA descriptor for this backend.
    pub(crate) fn vma_descriptor(&self, area_start: VirtAddr) -> VmaDescriptor {
        MappingExecution::vma_descriptor(self, area_start)
    }

    /// Returns the file information if this is a file-backed mapping, or `None` otherwise.
    ///
    /// The returned tuple contains the file name, offset, inode and whether the mapping is shared.
    pub fn file_info(&self) -> StarryResult<MappingFileInfo> {
        match &self.kind {
            MappingOperationKind::Cow(b) => b.file_info(),
            MappingOperationKind::Linear(b) => Ok(MappingFileInfo {
                path: "".to_string(),
                offset: None,
                inode: None,
                dev: None,
                shared: b.is_shared(),
            }),
            MappingOperationKind::Shared(_) => Ok(MappingFileInfo {
                path: "".to_string(),
                offset: None,
                inode: None,
                dev: None,
                shared: true,
            }),
            MappingOperationKind::File(b) => b.file_info(),
        }
    }

    /// Clone with a different base address (for mremap moves).
    /// `src_offset` is the distance from the original VMA start to the
    /// mremap source address, used to adjust file/page offsets.
    pub fn relocated(&self, new_start: VirtAddr, src_offset: usize) -> StarryResult<Self> {
        let adjusted = new_start
            .as_usize()
            .checked_sub(src_offset)
            .map(VirtAddr::from)
            .ok_or(StarryError::InvalidInput)?;
        Ok(match &self.kind {
            MappingOperationKind::Cow(cb) => Self::from_cow(cb.with_start(adjusted)),
            MappingOperationKind::Shared(sb) => Self::from_shared(sb.with_start(adjusted)),
            MappingOperationKind::Linear(_) => return Err(StarryError::OperationNotSupported),
            MappingOperationKind::File(fb) => Self::from_file(fb.with_start(adjusted)?),
        })
    }

    /// Adjusts the logical extent for an `mremap` destination.  The operation
    /// is checked before any VMA/PTE publication; backends that cannot grow
    /// (for example an externally supplied shared buffer) return a typed
    /// unsupported error instead of silently exposing a shorter mapping.
    pub fn resized(&self, size: usize) -> StarryResult<Self> {
        if size == 0 {
            return Err(StarryError::InvalidInput);
        }
        Ok(match &self.kind {
            MappingOperationKind::Cow(cow) => Self::from_cow(cow.for_extent(size)?),
            MappingOperationKind::Shared(shared) => Self::from_shared(shared.with_size(size)?),
            MappingOperationKind::Linear(_) => return Err(StarryError::OperationNotSupported),
            MappingOperationKind::File(file) => Self::from_file(file.clone()),
        })
    }
}

impl MappingExecution for MappingOperation {
    fn page_size(&self) -> usize {
        match &self.kind {
            MappingOperationKind::Linear(backend) => MappingExecution::page_size(backend),
            MappingOperationKind::Cow(backend) => MappingExecution::page_size(backend),
            MappingOperationKind::Shared(backend) => MappingExecution::page_size(backend),
            MappingOperationKind::File(backend) => MappingExecution::page_size(backend),
        }
    }

    fn vma_descriptor(&self, area_start: VirtAddr) -> VmaDescriptor {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::vma_descriptor(backend, area_start)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::vma_descriptor(backend, area_start)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::vma_descriptor(backend, area_start)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::vma_descriptor(backend, area_start)
            }
        }
    }

    fn map(
        &self,
        range: VirtAddrRange,
        flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult<PteMaterialization> {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::map(backend, range, flags, pt)
            }
            MappingOperationKind::Cow(backend) => MappingExecution::map(backend, range, flags, pt),
            MappingOperationKind::Shared(backend) => {
                MappingExecution::map(backend, range, flags, pt)
            }
            MappingOperationKind::File(backend) => MappingExecution::map(backend, range, flags, pt),
        }
    }

    fn validate_map(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::validate_map(backend, range, pt)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::validate_map(backend, range, pt)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::validate_map(backend, range, pt)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::validate_map(backend, range, pt)
            }
        }
    }

    fn unmap(&self, range: VirtAddrRange, pt: &mut PageTable) -> StarryResult {
        match &self.kind {
            MappingOperationKind::Linear(backend) => MappingExecution::unmap(backend, range, pt),
            MappingOperationKind::Cow(backend) => MappingExecution::unmap(backend, range, pt),
            MappingOperationKind::Shared(backend) => MappingExecution::unmap(backend, range, pt),
            MappingOperationKind::File(backend) => MappingExecution::unmap(backend, range, pt),
        }
    }

    fn validate_unmap(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::validate_unmap(backend, range, pt)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::validate_unmap(backend, range, pt)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::validate_unmap(backend, range, pt)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::validate_unmap(backend, range, pt)
            }
        }
    }

    fn validate_protect(&self, range: VirtAddrRange, pt: &PageTable) -> bool {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::validate_protect(backend, range, pt)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::validate_protect(backend, range, pt)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::validate_protect(backend, range, pt)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::validate_protect(backend, range, pt)
            }
        }
    }

    fn on_protect(
        &self,
        range: VirtAddrRange,
        new_flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::on_protect(backend, range, new_flags, pt)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::on_protect(backend, range, new_flags, pt)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::on_protect(backend, range, new_flags, pt)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::on_protect(backend, range, new_flags, pt)
            }
        }
    }

    fn populate(
        &self,
        space_id: AddressSpaceId,
        request: PopulateRequest,
        flags: MappingFlags,
        access_flags: MappingFlags,
        pt: &mut PageTable,
    ) -> StarryResult<PteMaterialization> {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::populate(backend, space_id, request, flags, access_flags, pt)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::populate(backend, space_id, request, flags, access_flags, pt)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::populate(backend, space_id, request, flags, access_flags, pt)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::populate(backend, space_id, request, flags, access_flags, pt)
            }
        }
    }

    fn prepare_fault(
        &self,
        space_id: AddressSpaceId,
        request: PopulateRequest,
        flags: MappingFlags,
        access_flags: MappingFlags,
        preimage: FaultPteSnapshot,
    ) -> StarryResult<FaultMaterialization> {
        match &self.kind {
            MappingOperationKind::Linear(backend) => MappingExecution::prepare_fault(
                backend,
                space_id,
                request,
                flags,
                access_flags,
                preimage,
            ),
            MappingOperationKind::Cow(backend) => MappingExecution::prepare_fault(
                backend,
                space_id,
                request,
                flags,
                access_flags,
                preimage,
            ),
            MappingOperationKind::Shared(backend) => MappingExecution::prepare_fault(
                backend,
                space_id,
                request,
                flags,
                access_flags,
                preimage,
            ),
            MappingOperationKind::File(backend) => MappingExecution::prepare_fault(
                backend,
                space_id,
                request,
                flags,
                access_flags,
                preimage,
            ),
        }
    }

    fn clone_map(
        &self,
        range: VirtAddrRange,
        flags: MappingFlags,
        old_pt: &mut PageTable,
        new_pt: &mut PageTable,
    ) -> StarryResult<(MappingOperation, PteMaterialization)> {
        match &self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::clone_map(backend, range, flags, old_pt, new_pt)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::clone_map(backend, range, flags, old_pt, new_pt)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::clone_map(backend, range, flags, old_pt, new_pt)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::clone_map(backend, range, flags, old_pt, new_pt)
            }
        }
    }

    fn split(&mut self, align_diff: usize) -> Option<MappingOperation> {
        match &mut self.kind {
            MappingOperationKind::Linear(backend) => MappingExecution::split(backend, align_diff),
            MappingOperationKind::Cow(backend) => MappingExecution::split(backend, align_diff),
            MappingOperationKind::Shared(backend) => MappingExecution::split(backend, align_diff),
            MappingOperationKind::File(backend) => MappingExecution::split(backend, align_diff),
        }
    }

    fn shrink_left(&mut self, shrink_size: usize) -> bool {
        match &mut self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::shrink_left(backend, shrink_size)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::shrink_left(backend, shrink_size)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::shrink_left(backend, shrink_size)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::shrink_left(backend, shrink_size)
            }
        }
    }

    fn shrink_right(&mut self, shrink_size: usize) -> bool {
        match &mut self.kind {
            MappingOperationKind::Linear(backend) => {
                MappingExecution::shrink_right(backend, shrink_size)
            }
            MappingOperationKind::Cow(backend) => {
                MappingExecution::shrink_right(backend, shrink_size)
            }
            MappingOperationKind::Shared(backend) => {
                MappingExecution::shrink_right(backend, shrink_size)
            }
            MappingOperationKind::File(backend) => {
                MappingExecution::shrink_right(backend, shrink_size)
            }
        }
    }
}

impl MappingBackend for MappingOperation {
    type Addr = VirtAddr;
    type Flags = MappingFlags;
    type MutationContext = ();
    type PageTable = PageTable;

    fn map(
        &self,
        start: VirtAddr,
        size: usize,
        flags: MappingFlags,
        _context: &mut (),
        pt: &mut PageTable,
    ) -> bool {
        let range = VirtAddrRange::from_start_size(start, size);
        if let Err(err) = MappingExecution::map(self, range, flags, pt) {
            warn!("Failed to map area: {:?}", err);
            false
        } else {
            true
        }
    }

    fn validate_map(
        &self,
        start: VirtAddr,
        size: usize,
        _flags: MappingFlags,
        pt: &PageTable,
    ) -> bool {
        let Some(range) = VirtAddrRange::try_from_start_size(start, size) else {
            return false;
        };
        MappingExecution::validate_map(self, range, pt)
    }

    fn unmap(&self, start: VirtAddr, size: usize, _context: &mut (), pt: &mut PageTable) -> bool {
        let range = VirtAddrRange::from_start_size(start, size);
        if let Err(err) = MappingExecution::unmap(self, range, pt) {
            warn!("Failed to unmap area: {:?}", err);
            false
        } else {
            true
        }
    }

    fn validate_unmap(&self, start: VirtAddr, size: usize, pt: &PageTable) -> bool {
        let Some(range) = VirtAddrRange::try_from_start_size(start, size) else {
            return false;
        };
        MappingExecution::validate_unmap(self, range, pt)
    }

    fn protect(
        &self,
        start: Self::Addr,
        size: usize,
        new_flags: Self::Flags,
        _context: &mut (),
        pt: &mut Self::PageTable,
    ) -> bool {
        let range = VirtAddrRange::from_start_size(start, size);
        if let Err(err) = MappingExecution::on_protect(self, range, new_flags, pt) {
            warn!("Failed to protect area: {:?}", err);
            return false;
        }
        let pte_flags = match &self.kind {
            MappingOperationKind::Cow(c) => c.pte_flags_for_protect(new_flags),
            _ => new_flags,
        };
        pt.protect_region(start, size, pte_flags).is_ok()
    }

    fn validate_protect(
        &self,
        start: VirtAddr,
        size: usize,
        _new_flags: MappingFlags,
        pt: &PageTable,
    ) -> bool {
        let Some(range) = VirtAddrRange::try_from_start_size(start, size) else {
            return false;
        };
        MappingExecution::validate_protect(self, range, pt)
    }

    fn split(&mut self, align_diff: usize) -> Option<Self> {
        MappingExecution::split(self, align_diff)
    }

    fn shrink_left(&mut self, shrink_size: usize) -> bool {
        MappingExecution::shrink_left(self, shrink_size)
    }

    fn shrink_right(&mut self, shrink_size: usize) -> bool {
        MappingExecution::shrink_right(self, shrink_size)
    }
}