kernel: Pin image load sources against private use

d3b089b946d9fc3198b141aa5fa9e9a6c9cb29e84119cbb4f5237dd8c515fd75
Only heap conversion checked whether an active image load still read a
Page through its source token, and it scanned every context record to
find the one load. A Page could still become a context stack while the
loader read it outside the lock.

An image load now pins its source extent in the page store until it
finishes or is cancelled, and `exclusiveExtent` rejects an overlapping
Page as busy. Stacks and heaps share the check, which takes constant
time and validates the handle once.

Page allocation and heap conversion now share one reserve, publish and
call path. A held heap is its own `PageHeld` variant, which selects how
the memory is initialized outside the lock and how it is published.

Use a typed operation for page reservations and one interval overlap
check across page pinning, platform ranges and device windows.

Assisted-by: Claude:opus-5.5
Assisted-by: Claude:sonnet-5.5
Assisted-by: Codex:gpt-6
Alexis Sellier committed ago 1 parent bf2423a6
kernel/kernel/calls.rad +75 -103
37 37
use std::arch::rv64;
38 38
use std::lang::il;
39 39
40 40
// Types //
41 41
42 +
/// Page reservation operation.
43 +
export union PageOperation: Copy {
44 +
    /// Allocate pages.
45 +
    Allocate,
46 +
    /// Initialize a page heap.
47 +
    Heap,
48 +
}
49 +
42 50
/// Query result for a context without a physical hart.
43 51
constant NO_HART: u64 = mem::U64_MAX;
44 52
45 53
/// Hart-local facts that safe call logic receives instead of reading.
46 54
export record Running: Copy {
1012 1020
        throw abi::Error::BadHandle;
1013 1021
    }
1014 1022
    return try domains::publish(&mut shared.domains, &mut shared.pages.backings, table, ready);
1015 1023
}
1016 1024
1017 -
/// Reserve zeroed pages and retain them under the calling context.
1025 +
/// Reserve zeroed pages, or an exclusive Page for heap initialization, and retain the
1026 +
/// reservation under the calling context.
1018 1027
export fn reservePage(
1019 1028
    shared: &mut state::Shared,
1020 1029
    domain: &domains::Domain,
1021 1030
    table: &mut capability::Table,
1031 +
    operation: PageOperation,
1022 1032
    arguments: &[u64],
1023 1033
    current: ?abi::CurrentContextInfo
1024 1034
) -> lifecycle::PageHeld throws (abi::Error) {
1025 1035
    let running = current else panic "reservePage: no current context";
1026 -
    try admit(&*shared, domain, &*table, abi::Operation::PageAllocate as u64, abi::Handle(
1027 -
        arguments[0]
1028 -
    ));
1029 -
    let pending = try pages::reserve(
1030 -
        &mut shared.pages, table, abi::Handle(arguments[0]), arguments[1]
1031 -
    );
1032 -
    return lifecycle::holdPage(
1033 -
        &mut shared.lifecycle, &mut shared.domains, abi::reference(running.context), pending
1034 -
    );
1035 -
}
1036 -
1037 -
/// Publish cleared pages unless their owner died while they were cleared.
1038 -
export fn publishPage(
1039 -
    shared: &mut state::Shared,
1040 -
    table: &mut capability::Table,
1041 -
    lease: lifecycle::Lease,
1042 -
    access: physical::Access
1043 -
) -> abi::Handle throws (abi::Error) {
1044 -
    let ready = lifecycle::takePage(&mut shared.lifecycle, &mut shared.domains, lease, access);
1045 -
    if not live(&shared.domains, table.owner) {
1046 -
        pages::cancel(&mut shared.pages, table, ready);
1047 -
        throw abi::Error::BadHandle;
1048 -
    }
1049 -
    return pages::publish(&mut shared.pages, table, ready);
1050 -
}
1051 -
1052 -
/// Reserve an exclusive Page for heap initialization.
1053 -
export fn reserveHeap(
1054 -
    shared: &mut state::Shared,
1055 -
    domain: &domains::Domain,
1056 -
    table: &mut capability::Table,
1057 -
    arguments: &[u64],
1058 -
    current: ?abi::CurrentContextInfo
1059 -
) -> lifecycle::PageHeld throws (abi::Error) {
1060 -
    let running = current else panic "reserveHeap: no current context";
1061 -
    try admit(&*shared, domain, &*table, abi::Operation::PageHeap as u64, abi::Handle(
1062 -
        arguments[0]
1063 -
    ));
1064 -
    if arguments[1] <> 0 or arguments[2] <> 0 or arguments[3] <> 0 {
1065 -
        throw abi::Error::InvalidArg;
1066 -
    }
1067 -
    let extent = try pages::exclusiveExtent(&shared.pages, &*table, abi::Handle(arguments[0]));
1068 -
    if lifecycle::sourceBusy(&shared.lifecycle, extent.start, extent.end) {
1069 -
        throw abi::Error::Busy;
1036 +
    let handle = abi::Handle(arguments[0]);
1037 +
    let context = abi::reference(running.context);
1038 +
    let op = abi::Operation::PageHeap as u64 if operation == PageOperation::Heap
1039 +
        else abi::Operation::PageAllocate as u64;
1040 +
    try admit(&*shared, domain, &*table, op, handle);
1041 +
    if operation == PageOperation::Heap {
1042 +
        if arguments[1] <> 0 or arguments[2] <> 0 or arguments[3] <> 0 {
1043 +
            throw abi::Error::InvalidArg;
1044 +
        }
1045 +
        let pending = try pages::reserveHeap(&shared.pages, table, handle);
1046 +
        return lifecycle::holdHeap(&mut shared.lifecycle, &mut shared.domains, context, pending);
1070 1047
    }
1071 -
    let pending = try pages::reserveHeap(&shared.pages, table, abi::Handle(arguments[0]));
1072 -
    return lifecycle::holdHeap(
1073 -
        &mut shared.lifecycle, &mut shared.domains, abi::reference(running.context), pending
1074 -
    );
1048 +
    let pending = try pages::reserve(&mut shared.pages, table, handle, arguments[1]);
1049 +
    return lifecycle::holdPage(&mut shared.lifecycle, &mut shared.domains, context, pending);
1075 1050
}
1076 1051
1077 -
/// Finish heap conversion and release the caller's reservation.
1078 -
export fn publishHeap(
1079 -
    shared: &mut state::Shared,
1080 -
    table: &mut capability::Table,
1081 -
    lease: lifecycle::Lease,
1082 -
    access: physical::Access
1052 +
/// Publish initialized pages or a heap unless their owner died during initialization.
1053 +
/// Returns the new handle for pages, and the address of the header for a heap.
1054 +
export fn publishPage(
1055 +
    shared: &mut state::Shared, table: &mut capability::Table, held: lifecycle::PageHeld
1083 1056
) -> u64 throws (abi::Error) {
1084 -
    let ready = lifecycle::takeHeap(&mut shared.lifecycle, &mut shared.domains, lease, access);
1085 -
    let alive = live(&shared.domains, table.owner);
1086 -
    let address = pages::finishHeap(&mut shared.pages, table, ready);
1087 -
    if not alive {
1088 -
        throw abi::Error::BadHandle;
1057 +
    match held {
1058 +
        case lifecycle::PageHeld::Held(lease, access) => {
1059 +
            let ready = lifecycle::takePage(
1060 +
                &mut shared.lifecycle, &mut shared.domains, lease, access
1061 +
            );
1062 +
            if not live(&shared.domains, table.owner) {
1063 +
                pages::cancel(&mut shared.pages, table, ready);
1064 +
                throw abi::Error::BadHandle;
1065 +
            }
1066 +
            return *pages::publish(&mut shared.pages, table, ready);
1067 +
        }
1068 +
        case lifecycle::PageHeld::Heap(lease, access) => {
1069 +
            let ready = lifecycle::takeHeap(
1070 +
                &mut shared.lifecycle, &mut shared.domains, lease, access
1071 +
            );
1072 +
            let alive = live(&shared.domains, table.owner);
1073 +
            let address = pages::finishHeap(&mut shared.pages, table, ready);
1074 +
            if not alive {
1075 +
                throw abi::Error::BadHandle;
1076 +
            }
1077 +
            return address;
1078 +
        }
1089 1079
    }
1090 -
    return address;
1091 1080
}
1092 1081
1093 1082
/// Read a context start record and reserve the context under the calling context.
1094 1083
export fn reserveContext(
1095 1084
    shared: &mut state::Shared,
1389 1378
            return *result;
1390 1379
        }
1391 1380
    }
1392 1381
}
1393 1382
1394 -
/// Allocate pages: reserve under the lock, clear the frames unlocked, then publish.
1395 -
fn allocatePage(owner: abi::Ref, arguments: &[u64]) -> u64 throws (abi::Error) {
1383 +
/// Allocate pages or convert a Page to a heap: reserve under the lock, initialize the
1384 +
/// memory unlocked, then publish.
1385 +
fn allocatePage(owner: abi::Ref, operation: PageOperation, arguments: &[u64]) -> u64
1386 +
    throws (abi::Error)
1387 +
{
1396 1388
    let guard = sync::enter();
1397 1389
    let domain = try locked::lookup(&guard, owner) catch error {
1398 1390
        sync::leave(guard);
1399 1391
        throw error;
1400 1392
    };
1401 -
    let begun = try locked::beginPage(&guard, &domain, arguments) catch error {
1393 +
    let begun = try locked::beginPage(&guard, &domain, operation, arguments) catch error {
1402 1394
        sync::leave(guard);
1403 1395
        throw error;
1404 1396
    };
1405 1397
    sync::leave(guard);
1406 -
    match begun {
1398 +
    match &begun {
1407 1399
        case lifecycle::PageHeld::Held(lease, access) => {
1408 1400
            // The lease keeps this call's page frames private, and this
1409 1401
            // continuation is the only holder of their token.
1410 -
            physical::clear(&access);
1411 -
            let publicationGuard = sync::enter();
1412 -
            let result = try locked::publishPage(
1413 -
                &publicationGuard, &domain, lease, access
1414 -
            ) catch error {
1415 -
                sync::leave(publicationGuard);
1416 -
                throw error;
1417 -
            };
1418 -
            sync::leave(publicationGuard);
1419 -
            return *result;
1402 +
            physical::clear(access);
1403 +
        }
1404 +
        case lifecycle::PageHeld::Heap(lease, access) => {
1405 +
            // The reserved handle cannot be used, and the conditions of
1406 +
            // `pages::exclusiveExtent` keep the Page private. This continuation is the
1407 +
            // only holder of its token.
1408 +
            pages::initializeHeap(access);
1420 1409
        }
1421 1410
    }
1422 -
}
1423 -
1424 -
/// Convert a Page to a heap with private initialization outside the lock.
1425 -
fn createHeap(owner: abi::Ref, arguments: &[u64]) -> u64 throws (abi::Error) {
1426 -
    let guard = sync::enter();
1427 -
    let domain = try locked::lookup(&guard, owner) catch error {
1428 -
        sync::leave(guard);
1429 -
        throw error;
1430 -
    };
1431 -
    let begun = try locked::beginHeap(&guard, &domain, arguments) catch error {
1432 -
        sync::leave(guard);
1411 +
    let publicationGuard = sync::enter();
1412 +
    let result = try locked::publishPage(&publicationGuard, &domain, begun) catch error {
1413 +
        sync::leave(publicationGuard);
1433 1414
        throw error;
1434 1415
    };
1435 -
    sync::leave(guard);
1436 -
    match begun {
1437 -
        case lifecycle::PageHeld::Held(lease, access) => {
1438 -
            pages::initializeHeap(&access);
1439 -
            let publicationGuard = sync::enter();
1440 -
            let result = try locked::publishHeap(
1441 -
                &publicationGuard, &domain, lease, access
1442 -
            ) catch error {
1443 -
                sync::leave(publicationGuard);
1444 -
                throw error;
1445 -
            };
1446 -
            sync::leave(publicationGuard);
1447 -
            return result;
1448 -
        }
1449 -
    }
1416 +
    sync::leave(publicationGuard);
1417 +
    return result;
1450 1418
}
1451 1419
1452 1420
/// Create a context: reserve under the lock, clear its stack unlocked, then publish.
1453 1421
fn createContext(owner: abi::Ref, arguments: &[u64]) -> u64 throws (abi::Error) {
1454 1422
    let guard = sync::enter();
1529 1497
        }
1530 1498
        case abi::Operation::DomainCreate as u64 => {
1531 1499
            return access::Reply { value: try createDomain(owner, arguments), extra: 0 };
1532 1500
        }
1533 1501
        case abi::Operation::PageAllocate as u64 => {
1534 -
            return access::Reply { value: try allocatePage(owner, arguments), extra: 0 };
1502 +
            return access::Reply {
1503 +
                value: try allocatePage(owner, PageOperation::Allocate, arguments), extra: 0
1504 +
            };
1535 1505
        }
1536 1506
        case abi::Operation::PageHeap as u64 => {
1537 -
            return access::Reply { value: try createHeap(owner, arguments), extra: 0 };
1507 +
            return access::Reply {
1508 +
                value: try allocatePage(owner, PageOperation::Heap, arguments), extra: 0
1509 +
            };
1538 1510
        }
1539 1511
        case abi::Operation::ContextCreate as u64 => {
1540 1512
            return access::Reply { value: try createContext(owner, arguments), extra: 0 };
1541 1513
        }
1542 1514
        else => return try submitCall(owner, operation, arguments),
kernel/kernel/lifecycle.rad +5 -26
136 136
    set calls.active[context.index / 32] |= bit;
137 137
    set store.contexts[context.index].reservation = true;
138 138
    return Lease::Held(Claim { context });
139 139
}
140 140
141 -
/// A held page reservation: the lease, and the token to clear the frames with.
141 +
/// A held page reservation: the lease, and the token to initialize its memory with.
142 142
export union PageHeld: Once {
143 -
    /// The continuation keeps the token until it takes the page back.
143 +
    /// Page frames. The continuation keeps the token until it takes the page back.
144 144
    Held(Lease, physical::Access),
145 +
    /// An exclusive Page converted to a heap, with the token to initialize it with.
146 +
    Heap(Lease, physical::Access),
145 147
}
146 148
147 149
/// A held context reservation: the lease, and the token to clear the stack with.
148 150
export union ContextHeld: Once {
149 151
    /// The continuation keeps the token until it takes the context back.
178 180
            );
179 181
        }
180 182
    }
181 183
}
182 184
183 -
/// Check whether an active load retains a token for an extent.
184 -
export fn sourceBusy(calls: &Calls, start: u64, end: u64) -> bool {
185 -
    for word in 0 .. CONTEXT_WORDS {
186 -
        if calls.active[word] == 0 {
187 -
            continue;
188 -
        }
189 -
        for offset in 0 .. 32 as u32 {
190 -
            if (calls.active[word] & (1 << offset)) == 0 {
191 -
                continue;
192 -
            }
193 -
            match calls.records[word * 32 + offset].allocation {
194 -
                case Allocation::Load(loading) => {
195 -
                    if loader::sourceOverlaps(&loading.input, start, end) {
196 -
                        return true;
197 -
                    }
198 -
                }
199 -
                else => {}
200 -
            }
201 -
        }
202 -
    }
203 -
    return false;
204 -
}
205 -
206 185
/// Retain a heap conversion and its caller while the memory is initialized.
207 186
export fn holdHeap(
208 187
    calls: &mut Calls,
209 188
    store: &mut domains::Store,
210 189
    context: abi::Ref,
211 190
    reservation: pages::HeapReservation
212 191
) -> PageHeld {
213 192
    match reservation {
214 193
        case pages::HeapReservation::Held(allocation, access) =>
215 -
            return PageHeld::Held(
194 +
            return PageHeld::Heap(
216 195
                hold(calls, store, context, Allocation::Heap(allocation)), access
217 196
            ),
218 197
    }
219 198
}
220 199
kernel/kernel/loader.rad +6 -5
15 15
use super::physical;
16 16
use super::pages;
17 17
use super::backing;
18 18
use super::capability;
19 19
use super::registry;
20 +
use super::range;
20 21
use super::sync;
21 22
use std::lang::gen::labels;
22 23
use std::lang::gen::regalloc::liveness;
23 24
24 25
/// Number of elements reserved for decoded storage.
611 612
    let handle = try slots::reserve(&mut table.slots[..]);
612 613
    let lease = try acquire(state, &mut store.backings.pool, table.owner) catch err {
613 614
        try! slots::cancel(&mut table.slots[..], handle);
614 615
        throw err;
615 616
    };
617 +
    // `acquire` admits one load at a time, so no other load pins its source.
618 +
    assert store.pinned == nil;
619 +
    set store.pinned = range::new(address, request.length);
616 620
    match handle {
617 621
        case slots::Reservation::Held(handle) => match lease {
618 622
            case Lease::Held(run) => {
619 623
                // The lease was just acquired, so its frames are allocated and hold a complete
620 624
                // Workspace.
635 639
            }
636 640
        },
637 641
    }
638 642
}
639 643
640 -
/// Test whether a load's source overlaps a physical extent.
641 -
export fn sourceOverlaps(input: &Input, start: u64, end: u64) -> bool {
642 -
    return input.address < end and start < input.address + input.length as u64;
643 -
}
644 -
645 644
/// Domain that owns the load, which is kept live while the input is held.
646 645
export fn owner(input: &Input) -> abi::Ref {
647 646
    return input.owner;
648 647
}
649 648
681 680
    table: &mut capability::Table,
682 681
    input: Input,
683 682
    release: fn(&mut frames::Pool, frames::Run) throws (abi::Error)
684 683
) {
685 684
    require(state, table, &input);
685 +
    set store.pinned = nil;
686 686
    releaseUsing(state, &mut store.backings.pool, Lease::Held(input.frames), release);
687 687
    try! slots::cancel(&mut table.slots[..], slots::Reservation::Held(input.handle));
688 688
}
689 689
690 690
/// Install a resident package handle and return the workspace under serialization.
708 708
                slots::Reservation::Held(input.handle),
709 709
                capability::Entry {
710 710
                    kind: abi::Kind::Image, object, rights: abi::Rights(registry::IMAGE_RIGHTS)
711 711
                }
712 712
            );
713 +
            set store.pinned = nil;
713 714
            release(state, &mut store.backings.pool, Lease::Held(input.frames));
714 715
            return result;
715 716
        }
716 717
    }
717 718
}
kernel/kernel/locked.rad +7 -29
223 223
            &mut state::SHARED, &mut domain.memory.table, lease, access
224 224
        );
225 225
    }
226 226
}
227 227
228 -
/// Reserve zeroed pages. The result carries the token to clear them with.
228 +
/// Reserve zeroed pages or an exclusive heap Page. The result carries the token to
229 +
/// initialize them with.
229 230
export fn beginPage(
230 -
    guard: &sync::Guard, domain: &domains::Domain, arguments: &[u64]
231 +
    guard: &sync::Guard, domain: &domains::Domain, operation: calls::PageOperation, arguments: &[u64]
231 232
) -> lifecycle::PageHeld throws (abi::Error) {
232 233
    // The guard serializes the shared metadata, and the record came from `get`.
233 234
    unsafe {
234 235
        let shared = &mut state::SHARED;
235 236
        let table = &mut domain.memory.table;
236 237
        let current = dispatch::running(guard, &shared.budgets);
237 -
        return try calls::reservePage(shared, domain, table, arguments, current);
238 +
        return try calls::reservePage(shared, domain, table, operation, arguments, current);
238 239
    }
239 240
}
240 241
241 -
/// Publish cleared pages.
242 +
/// Publish initialized pages or a heap.
242 243
export fn publishPage(
243 -
    guard: &sync::Guard, domain: &domains::Domain, lease: lifecycle::Lease, access: physical::Access
244 -
) -> abi::Handle throws (abi::Error) {
245 -
    // The guard serializes the shared metadata, and the record came from `get`.
246 -
    unsafe {
247 -
        return try calls::publishPage(&mut state::SHARED, &mut domain.memory.table, lease, access);
248 -
    }
249 -
}
250 -
251 -
/// Reserve a Page for heap initialization.
252 -
export fn beginHeap(
253 -
    guard: &sync::Guard, domain: &domains::Domain, arguments: &[u64]
254 -
) -> lifecycle::PageHeld throws (abi::Error) {
255 -
    // The guard serializes the shared metadata, and the record came from `get`.
256 -
    unsafe {
257 -
        let shared = &mut state::SHARED;
258 -
        let table = &mut domain.memory.table;
259 -
        let current = dispatch::running(guard, &shared.budgets);
260 -
        return try calls::reserveHeap(shared, domain, table, arguments, current);
261 -
    }
262 -
}
263 -
264 -
/// Publish an initialized heap.
265 -
export fn publishHeap(
266 -
    guard: &sync::Guard, domain: &domains::Domain, lease: lifecycle::Lease, access: physical::Access
244 +
    guard: &sync::Guard, domain: &domains::Domain, held: lifecycle::PageHeld
267 245
) -> u64 throws (abi::Error) {
268 246
    // The guard serializes the shared metadata, and the record came from `get`.
269 247
    unsafe {
270 -
        return try calls::publishHeap(&mut state::SHARED, &mut domain.memory.table, lease, access);
248 +
        return try calls::publishPage(&mut state::SHARED, &mut domain.memory.table, held);
271 249
    }
272 250
}
273 251
274 252
/// Reserve a context. The result carries the token to clear its stack with.
275 253
export fn beginContext(
kernel/kernel/pages.rad +16 -12
36 36
    slots: [slots::Slot; limits::PAGES],
37 37
    /// Live page-object payloads.
38 38
    records: [Page; limits::PAGES],
39 39
    /// Backing allocations and domain exposures.
40 40
    backings: backing::Store,
41 +
    /// Extent that a kernel token reads outside metadata serialization, such as the
42 +
    /// source of an active image load. Pages that overlap it cannot be taken for private use.
43 +
    pinned: ?range::Range,
41 44
}
42 45
43 46
/// Initialize physical-memory metadata before creating domains or pages.
44 47
export fn initialize(store: &mut Store, machine: &platform::Platform) throws (abi::Error) {
45 48
    backing::initialize(&mut store.backings);
46 49
    try frames::initialize(&mut store.backings.pool, machine);
47 50
    slots::initialize(&mut store.slots[..]);
51 +
    set store.pinned = nil;
48 52
}
49 53
50 54
/// Read a live page object through its internal generation-bearing reference.
51 55
export fn get(store: &Store, object: abi::Ref) -> Page throws (abi::Error) {
52 56
    if not slots::matches(&store.slots[..], object, slots::State::Live) {
96 100
97 101
/// Check that a Page can be taken for private use as a stack or a heap, and return its extent.
98 102
///
99 103
/// The Page must be readable and writable, never reached through `page.slice`, and the only
100 104
/// handle to any frame of its allocation: a grant or a split sibling would let someone else
101 -
/// reach the memory.
105 +
/// reach the memory. It must not overlap the pinned extent, which a kernel token still reads.
102 106
export fn exclusiveExtent(
103 107
    store: &Store, table: &capability::Table, handle: abi::Handle
104 108
) -> range::Range throws (abi::Error) {
105 109
    let entry = try capability::lookup(table, handle, abi::Kind::Page, abi::Rights(
106 110
        abi::READ | abi::WRITE
110 114
        throw abi::Error::Busy;
111 115
    }
112 116
    if try backing::accessed(&store.backings, page.backing) {
113 117
        throw abi::Error::Denied;
114 118
    }
115 -
    return range::Range {
119 +
    let extent = range::Range {
116 120
        start: page.base, end: page.base + page.count as u64 * limits::FRAME_SIZE
117 121
    };
122 +
    if let pinned = store.pinned {
123 +
        if range::overlaps(pinned, extent) {
124 +
            throw abi::Error::Busy;
125 +
        }
126 +
    }
127 +
    return extent;
118 128
}
119 129
120 130
/// Take the memory of a Page for a stack, and consume its handle.
121 131
///
122 132
/// On success the handle is gone, so nothing can grant, transfer, split or access the memory
157 167
/// until conversion finishes. See [`exclusiveExtent`] for the conditions.
158 168
export fn reserveHeap(
159 169
    store: &Store, table: &mut capability::Table, handle: abi::Handle
160 170
) -> HeapReservation throws (abi::Error) {
161 171
    let extent = try exclusiveExtent(store, &*table, handle);
162 -
    let entry = try capability::get(&*table, handle);
163 -
    let slot = (try abi::decode(handle)).object;
172 +
    // `exclusiveExtent` found a live Page capability, so the handle decodes.
173 +
    let slot = (try! abi::decode(handle)).object;
174 +
    let object = table.entries[slot.index].object;
164 175
    let size = extent.end - extent.start;
165 176
    let access = try physical::access(&store.backings.pool, extent.start, size);
166 177
    set table.slots[slot.index].state = slots::State::Reserved;
167 178
    return HeapReservation::Held(
168 179
        HeapAllocation {
169 -
            handle: slot, page: entry.object, base: extent.start, size
180 +
            handle: slot, page: object, base: extent.start, size
170 181
        },
171 182
        access
172 183
    );
173 184
}
174 185
182 193
    try! physical::writeWordsAt(access, 0, &[
183 194
        0, size - HEAP_POOL_OFFSET, base + HEAP_POOL_OFFSET
184 195
    ]);
185 196
}
186 197
187 -
/// Initialize the memory of a heap reservation.
188 -
export fn clearHeap(reservation: &HeapReservation) {
189 -
    match reservation {
190 -
        case HeapReservation::Held(allocation, access) => initializeHeap(access),
191 -
    }
192 -
}
193 -
194 198
/// Release the retained capability and page under metadata serialization.
195 199
export fn releaseHeap(
196 200
    store: &mut Store, table: &mut capability::Table, allocation: HeapAllocation
197 201
) {
198 202
    assert slots::matches(&table.slots[..], allocation.handle, slots::State::Reserved);
kernel/kernel/platform.rad +3 -8
304 304
    }
305 305
    set platform.reserved[platform.reservedCount] = value;
306 306
    set platform.reservedCount += 1;
307 307
}
308 308
309 -
/// Test a physical extent for overlap.
310 -
fn overlaps(left: range::Range, right: range::Range) -> bool {
311 -
    return left.start < right.end and right.start < left.end;
312 -
}
313 -
314 309
/// Test whether one complete extent belongs to a RAM bank.
315 310
export fn inRam(platform: &Platform, value: range::Range) -> bool {
316 311
    for i in 0 .. platform.ramCount {
317 312
        if range::contains(platform.ram[i], value) {
318 313
            return true;
325 320
export fn available(platform: &Platform, value: range::Range) -> bool {
326 321
    if not inRam(platform, value) {
327 322
        return false;
328 323
    }
329 324
    for i in 0 .. platform.reservedCount {
330 -
        if overlaps(platform.reserved[i], value) {
325 +
        if range::overlaps(platform.reserved[i], value) {
331 326
            return false;
332 327
        }
333 328
    }
334 329
    return true;
335 330
}
369 364
            if memory {
370 365
                if platform.ramCount == RAM_BANKS {
371 366
                    throw Error::Capacity;
372 367
                }
373 368
                for i in 0 .. platform.ramCount {
374 -
                    if overlaps(platform.ram[i], value) {
369 +
                    if range::overlaps(platform.ram[i], value) {
375 370
                        throw Error::Invalid;
376 371
                    }
377 372
                }
378 373
                set platform.ram[platform.ramCount] = value;
379 374
                set platform.ramCount += 1;
584 579
        }
585 580
        if hart >= platform.stackCount or not inRam(platform, platform.stacks[hart]) {
586 581
            throw Error::Invalid;
587 582
        }
588 583
        for other in 0 .. hart {
589 -
            if (platform.harts & (1 << other)) <> 0 and overlaps(
584 +
            if (platform.harts & (1 << other)) <> 0 and range::overlaps(
590 585
                platform.stacks[hart], platform.stacks[other]
591 586
            )
592 587
            {
593 588
                throw Error::Invalid;
594 589
            }
kernel/kernel/range.rad +5 -0
19 19
20 20
/// Check that the complete nonempty interval is inside the outer interval.
21 21
export fn contains(outer: Range, inner: Range) -> bool {
22 22
    return outer.start <= inner.start and inner.start < inner.end and inner.end <= outer.end;
23 23
}
24 +
25 +
/// Check whether two nonempty intervals share any address.
26 +
export fn overlaps(left: Range, right: Range) -> bool {
27 +
    return left.start < right.end and right.start < left.end;
28 +
}
kernel/kernel/registers.rad +2 -1
18 18
//! Device ranges are fixed by the platform for the life of the kernel, so a
19 19
//! `Window` is a Copy value and never needs to be revoked.
20 20
21 21
use super::abi;
22 22
use super::platform;
23 +
use super::range;
23 24
24 25
/// Read a byte from a device register between full I/O barriers.
25 26
/// The address must be inside a window and tolerate a byte read.
26 27
unsafe fn load8(address: u64) -> u8;
27 28
/// Read a naturally aligned 32-bit device register between full I/O barriers.
71 72
        if extent.end < extent.start or extent.end - extent.start < minimum {
72 73
            throw abi::Error::InvalidArg;
73 74
        }
74 75
        for bank in 0 .. machine.ramCount {
75 76
            let ram = machine.ram[bank];
76 -
            if extent.start < ram.end and ram.start < extent.end {
77 +
            if range::overlaps(extent, ram) {
77 78
                throw abi::Error::InvalidArg;
78 79
            }
79 80
        }
80 81
        return Window { base: extent.start, length: extent.end - extent.start };
81 82
    }
kernel/kernel/tests/calls.rad +36 -19
445 445
/// Allocate pages through the reservation and publication stages of a call.
446 446
unsafe fn allocate(owner: abi::Ref, count: u64) -> u64 throws (abi::Error) {
447 447
    let shared = &mut state::SHARED;
448 448
    let domain = try domains::get(&shared.domains, owner);
449 449
    let held = try calls::reservePage(
450 -
        shared, &domain, &mut MEMORY.table, &[0, count, 0, 0], running()
450 +
        shared,
451 +
        &domain,
452 +
        &mut MEMORY.table,
453 +
        calls::PageOperation::Allocate,
454 +
        &[0, count, 0, 0],
455 +
        running()
451 456
    );
452 -
    match held {
453 -
        case lifecycle::PageHeld::Held(lease, access) => {
454 -
            physical::clear(&access);
455 -
            return *try calls::publishPage(shared, &mut MEMORY.table, lease, access);
456 -
        }
457 +
    match &held {
458 +
        case lifecycle::PageHeld::Held(lease, access) => physical::clear(access),
459 +
        case lifecycle::PageHeld::Heap(lease, access) => panic "allocate: heap reserved",
457 460
    }
461 +
    return try calls::publishPage(shared, &mut MEMORY.table, held);
458 462
}
459 463
460 464
/// Create a context through the validation, reservation, and publication stages of a call.
461 465
unsafe fn createContext(owner: abi::Ref, arguments: &[u64]) -> abi::Ref throws (abi::Error) {
462 466
    let shared = &mut state::SHARED;
475 479
    domains::initialize(&mut state::SHARED.domains);
476 480
    lifecycle::initialize(&mut state::SHARED.lifecycle);
477 481
    registry::initialize(&mut state::SHARED.registry);
478 482
    budgets::initialize(&mut state::SHARED.budgets);
479 483
    slots::initialize(&mut state::SHARED.pages.slots[..]);
484 +
    set state::SHARED.pages.pinned = nil;
480 485
    backing::initialize(&mut state::SHARED.pages.backings);
481 486
    let base = &RAM[0] as u64;
482 487
    let aligned = (base + 4095) & ~4095;
483 488
    set OFFSET = ((aligned - base) / 8) as u32;
484 489
    let tableBase = (&BASES[0] as u64 + 4095) & ~4095;
740 745
        and free() == before
741 746
        and not state::SHARED.domains.contexts[CALLER.index].reservation;
742 747
    let shared = &mut state::SHARED;
743 748
    let domain = try! domains::get(&shared.domains, owner);
744 749
    let held = try! calls::reservePage(
745 -
        shared, &domain, &mut MEMORY.table, &[0, 2, 0, 0], running()
750 +
        shared,
751 +
        &domain,
752 +
        &mut MEMORY.table,
753 +
        calls::PageOperation::Allocate,
754 +
        &[0, 2, 0, 0],
755 +
        running()
746 756
    );
747 757
    assert free() == before - 2 and shared.domains.contexts[CALLER.index].reservation;
748 758
    set shared.domains.records[owner.index].state = domains::Lifecycle::Dead;
749 759
    let mut cancelled = false;
750 -
    match held {
751 -
        case lifecycle::PageHeld::Held(lease, access) => {
752 -
            physical::clear(&access);
753 -
            try calls::publishPage(shared, &mut MEMORY.table, lease, access) catch error {
754 -
                assert error == abi::Error::BadHandle;
755 -
                set cancelled = true;
756 -
            };
757 -
        }
760 +
    match &held {
761 +
        case lifecycle::PageHeld::Held(lease, access) => physical::clear(access),
762 +
        case lifecycle::PageHeld::Heap(lease, access) => panic "pageReservation: heap reserved",
758 763
    }
764 +
    try calls::publishPage(shared, &mut MEMORY.table, held) catch error {
765 +
        assert error == abi::Error::BadHandle;
766 +
        set cancelled = true;
767 +
    };
759 768
    assert cancelled and not shared.domains.contexts[CALLER.index].reservation;
760 769
    while shared.pages.backings.pool.retiredCount > 0 {
761 770
        assert frames::reclaim(&mut shared.pages.backings.pool, 256) > 0;
762 771
    }
763 772
    assert free() == before and MEMORY.table.slots[1].state == slots::State::Free;
770 779
        let handle = abi::Handle(try! allocate(owner, 1));
771 780
        let shared = &mut state::SHARED;
772 781
        let domain = try! domains::get(&shared.domains, owner);
773 782
        let entry = try! capability::get(&MEMORY.table, handle);
774 783
        let page = try! pages::get(&shared.pages, entry.object);
775 -
        let held = try! calls::reserveHeap(
776 -
            shared, &domain, &mut MEMORY.table, &[*handle, 0, 0, 0], running()
784 +
        let held = try! calls::reservePage(
785 +
            shared,
786 +
            &domain,
787 +
            &mut MEMORY.table,
788 +
            calls::PageOperation::Heap,
789 +
            &[*handle, 0, 0, 0],
790 +
            running()
777 791
        );
778 792
        assert not pages::accessible(&shared.pages, &MEMORY.table, page.base, 8, abi::Rights(
779 793
            abi::READ
780 794
        ));
781 795
        set shared.domains.records[owner.index].state = domains::Lifecycle::Dead;
782 796
        assert not try! domains::quiescent(&shared.domains, owner);
783 797
        match held {
784 -
            case lifecycle::PageHeld::Held(lease, access) => {
798 +
            case lifecycle::PageHeld::Held(lease, access) => panic "heapReservation: page reserved",
799 +
            case lifecycle::PageHeld::Heap(lease, access) => {
785 800
                if stopped {
786 801
                    set shared.domains.contexts[CALLER.index].state =
787 802
                        domains::ContextState::Stopped;
788 803
                    set shared.domains.contexts[CALLER.index].hart = nil;
789 804
                    assert lifecycle::leaseContext(lease) == CALLER;
795 810
                        &mut shared.registry
796 811
                    );
797 812
                } else {
798 813
                    pages::initializeHeap(&access);
799 814
                    let mut failed = false;
800 -
                    try calls::publishHeap(shared, &mut MEMORY.table, lease, access) catch error {
815 +
                    try calls::publishPage(shared, &mut MEMORY.table, lifecycle::PageHeld::Heap(
816 +
                        lease, access
817 +
                    )) catch error {
801 818
                        assert error == abi::Error::BadHandle;
802 819
                        set failed = true;
803 820
                    };
804 821
                    assert failed;
805 822
                }
kernel/kernel/tests/domains.rad +4 -0
394 394
    let mut child = try! domains::get(&DOMAINS, target);
395 395
    let mut parent = try! domains::get(&DOMAINS, receiver);
396 396
    try! domains::reparent(&mut DOMAINS, &TABLE, handle, parentHandle);
397 397
    set PAGES.backings = BACKINGS;
398 398
    slots::initialize(&mut PAGES.slots[..]);
399 +
    set PAGES.pinned = nil;
399 400
    let authority = try! capability::install(&mut child.memory.table, capability::Entry {
400 401
        kind: abi::Kind::Domain, object: target, rights: abi::Rights(abi::ALLOCATE)
401 402
    });
402 403
    let page = try! pages::allocate(&mut PAGES, &mut child.memory.table, authority, 1);
403 404
    let shared = try! pages::grant(
780 781
/// Activation validates child authority before publishing its initial state, and consumes
781 782
/// the stack Page only when nothing else holds it.
782 783
@test unsafe fn activation() throws (testing::TestError) {
783 784
    initialize(abi::CREATE);
784 785
    slots::initialize(&mut PAGES.slots[..]);
786 +
    set PAGES.pinned = nil;
785 787
    let handle = try! domains::create(
786 788
        &mut DOMAINS, &mut BACKINGS, &PACKAGES, &mut TABLE, abi::Handle(0), IMAGE
787 789
    );
788 790
    let entry = try! capability::get(&TABLE, handle);
789 791
    let mut child = try! domains::get(&DOMAINS, entry.object);
876 878
877 879
/// A Page that was split has siblings, so neither half can be a stack.
878 880
@test unsafe fn splitStack() throws (testing::TestError) {
879 881
    initialize(abi::CREATE);
880 882
    slots::initialize(&mut PAGES.slots[..]);
883 +
    set PAGES.pinned = nil;
881 884
    let handle = try! domains::create(
882 885
        &mut DOMAINS, &mut BACKINGS, &PACKAGES, &mut TABLE, abi::Handle(0), IMAGE
883 886
    );
884 887
    let entry = try! capability::get(&TABLE, handle);
885 888
    let child = try! domains::get(&DOMAINS, entry.object);
907 910
908 911
/// Additional contexts share private package state and reserve distinct kernel stacks.
909 912
@test unsafe fn additionalContext() throws (testing::TestError) {
910 913
    initialize(abi::CREATE);
911 914
    slots::initialize(&mut PAGES.slots[..]);
915 +
    set PAGES.pinned = nil;
912 916
    let handle = try! domains::create(
913 917
        &mut DOMAINS, &mut BACKINGS, &PACKAGES, &mut TABLE, abi::Handle(0), IMAGE
914 918
    );
915 919
    let authority = try! capability::get(&TABLE, handle);
916 920
    let mut child = try! domains::get(&DOMAINS, authority.object);
kernel/kernel/tests/lifecycle.rad +4 -0
138 138
            assert MEMORY.slots[0].state == slots::State::Free;
139 139
            assert MEMORY.backings.slots[0].state == slots::State::Free;
140 140
            assert FIRST.table.slots[1].state == slots::State::Free and CALLS.active[0] == 0;
141 141
            assert not STORE.contexts[0].reservation;
142 142
        }
143 +
        else => panic "cancelPage: heap held",
143 144
    }
144 145
    set STORE.records[0].state = domains::Lifecycle::Active;
145 146
    let next = try! pages::reserve(&mut MEMORY, &mut FIRST.table, authority, 1);
146 147
    match lifecycle::holdPage(&mut CALLS, &mut STORE, owner, next) {
147 148
        case lifecycle::PageHeld::Held(lease, access) => {
150 151
            let handle = pages::publish(&mut MEMORY, &mut FIRST.table, ready);
151 152
            assert CALLS.active[0] == 0;
152 153
            let entry = try! capability::get(&FIRST.table, handle);
153 154
            assert (try! pages::get(&MEMORY, entry.object)).count == 1;
154 155
        }
156 +
        else => panic "cancelPage: heap held",
155 157
    }
156 158
}
157 159
158 160
/// A token pairs only with the allocation it was derived for, so a lease cannot take back another
159 161
/// call's token.
246 248
                        and not frames::available(&MEMORY.backings.pool, 1);
247 249
                    assert frames::reclaim(&mut MEMORY.backings.pool, 1) == 1;
248 250
                    assert frames::reclaim(&mut MEMORY.backings.pool, 1) == 1;
249 251
                    assert MEMORY.backings.pool.retiredCount == 0;
250 252
                }
253 +
                else => panic "cancellationBatch: heap held",
251 254
            }
252 255
        }
256 +
        else => panic "cancellationBatch: heap held",
253 257
    }
254 258
}
255 259
256 260
/// A context call belongs to its caller even when its target domain dies.
257 261
@test unsafe fn cancelContext() throws (testing::TestError) {
kernel/kernel/tests/loader.rad +26 -4
42 42
43 43
/// Initialize a live domain and one source page over actual mapped memory.
44 44
unsafe fn initialize() {
45 45
    slots::initialize(&mut PAGES.slots[..]);
46 46
    backing::initialize(&mut PAGES.backings);
47 +
    set PAGES.pinned = nil;
47 48
    registry::initialize(&mut PACKAGES);
48 49
    loader::initialize(&mut LOADER);
49 50
    let pointer = &RAM[0];
50 51
    let base = pointer as u64;
51 52
    let aligned = (base + 4095) & ~4095;
159 160
        set DOMAINS.contexts[0].state = domains::ContextState::Ready;
160 161
        set DOMAINS.contexts[0].hart = nil;
161 162
        let pending = try! loader::reserve(&mut LOADER, &mut PAGES, &mut MEMORY.table, request);
162 163
        match lifecycle::holdLoad(&mut CALLS, &mut DOMAINS, owner, pending) {
163 164
            case lifecycle::LoadHeld::Held(lease, held) => {
164 -
                let entry = try! capability::get(&MEMORY.table, SOURCE);
165 -
                let page = try! pages::get(&PAGES, entry.object);
166 -
                assert lifecycle::sourceBusy(&CALLS, page.base, page.base + 4096);
167 -
                assert not lifecycle::sourceBusy(&CALLS, page.base + 4096, page.base + 8192);
168 165
                let mut tokens = held;
169 166
                if stage > 0 {
170 167
                    let output = try! lifecycle::reserveOutput(
171 168
                        &mut CALLS, &lease, &mut PAGES, &mut PACKAGES
172 169
                    );
285 282
    assert LOADER.owner == nil and TABLE.slots[2].state == slots::State::Free;
286 283
    assert free() + 1 == before;
287 284
    assert (try! pages::get(&PAGES, (try! capability::get(&TABLE, other)).object)).count == 1;
288 285
}
289 286
287 +
/// A pending load keeps its source Page from private use until the load ends.
288 +
@test unsafe fn pinnedSource() throws (testing::TestError) {
289 +
    initialize();
290 +
    let request = input(43, false);
291 +
    let other = try! pages::allocate(&mut PAGES, &mut TABLE, abi::Handle(0), 1);
292 +
    let pending = try! loader::reserve(&mut LOADER, &mut PAGES, &mut TABLE, request);
293 +
    let mut busy = false;
294 +
    try pages::exclusiveExtent(&PAGES, &TABLE, SOURCE) catch error {
295 +
        assert error == abi::Error::Busy;
296 +
        set busy = true;
297 +
    };
298 +
    assert busy;
299 +
    set busy = false;
300 +
    try pages::consumeStack(&mut PAGES, &mut TABLE, SOURCE) catch error {
301 +
        assert error == abi::Error::Busy;
302 +
        set busy = true;
303 +
    };
304 +
    assert busy;
305 +
    try! pages::exclusiveExtent(&PAGES, &TABLE, other);
306 +
    loader::cancel(&mut LOADER, &mut PAGES, &mut TABLE, pending);
307 +
    try! pages::exclusiveExtent(&PAGES, &TABLE, SOURCE);
308 +
    try! loader::load(&mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, request);
309 +
    try! pages::exclusiveExtent(&PAGES, &TABLE, SOURCE);
310 +
}
311 +
290 312
/// Compiled output stays private until publication and cancellation restores capacity.
291 313
@test unsafe fn stagedOutput() throws (testing::TestError) {
292 314
    initialize();
293 315
    let request = input(43, false);
294 316
    let before = free();
kernel/kernel/tests/pages.rad +7 -2
29 29
    let pointer: *u8 = &RAM[0];
30 30
    let address = pointer as u64;
31 31
    let aligned = (address + 4095) & ~4095;
32 32
    set OFFSET = (aligned - address) as u32;
33 33
    slots::initialize(&mut STORE.slots[..]);
34 +
    set STORE.pinned = nil;
34 35
    backing::initialize(&mut STORE.backings);
35 36
    set STORE.backings.pool.count = 8;
36 37
    for i in 0 .. 8 {
37 38
        set STORE.backings.pool.addresses[i] = aligned + i as u64 * 4096;
38 39
        set STORE.backings.pool.free[i / 64] |= 1 << (i % 64) as u64;
458 459
}
459 460
460 461
/// Convert one test Page to a heap.
461 462
unsafe fn consumeHeap(handle: abi::Handle) -> u64 throws (abi::Error) {
462 463
    let pending = try pages::reserveHeap(&STORE, &mut TABLE, handle);
463 -
    pages::clearHeap(&pending);
464 +
    match &pending {
465 +
        case pages::HeapReservation::Held(allocation, access) => pages::initializeHeap(access),
466 +
    }
464 467
    return pages::finishHeap(&mut STORE, &mut TABLE, pending);
465 468
}
466 469
467 470
/// A heap consumes its handle, receives a header and a pool, and keeps its frames until the
468 471
/// domain that is exposed to them ends.
501 504
    let pending = try! pages::reserveHeap(&STORE, &mut TABLE, handle);
502 505
    assert not pages::accessible(&STORE, &TABLE, page.base, 8, abi::Rights(abi::READ));
503 506
    try capability::get(&TABLE, handle) catch error {
504 507
        assert error == abi::Error::BadHandle;
505 508
    };
506 -
    pages::clearHeap(&pending);
509 +
    match &pending {
510 +
        case pages::HeapReservation::Held(allocation, access) => pages::initializeHeap(access),
511 +
    }
507 512
    assert pages::finishHeap(&mut STORE, &mut TABLE, pending) == page.base;
508 513
    assert not frames::available(&STORE.backings.pool, 0);
509 514
}
510 515
511 516
/// A Page that the kernel wrote into, as it does for the buffer of a call, becomes a zeroed heap.
kernel/kernel/tests/range.rad +10 -0
23 23
    try testing::expect(not range::contains(outer, range::Range { start: 4095, end: 4097 }));
24 24
    try testing::expect(not range::contains(outer, range::Range { start: 8191, end: 8193 }));
25 25
    try testing::expect(not range::contains(outer, range::Range { start: 8192, end: 8193 }));
26 26
    try testing::expect(not range::contains(outer, range::Range { start: 4096, end: 4096 }));
27 27
}
28 +
29 +
/// Check overlap and touching interval boundaries.
30 +
@test fn overlap() throws (testing::TestError) {
31 +
    let span = range::Range { start: 10, end: 20 };
32 +
    assert range::overlaps(span, span);
33 +
    assert range::overlaps(span, range::Range { start: 19, end: 21 });
34 +
    assert range::overlaps(range::Range { start: 9, end: 11 }, span);
35 +
    assert not range::overlaps(span, range::Range { start: 20, end: 21 });
36 +
    assert not range::overlaps(range::Range { start: 9, end: 10 }, span);
37 +
}