Commit graph

212 commits

Author SHA1 Message Date
tunnell
5e42a656cf Check for overflow in IncreaseHeap syscall
`process_inner.mem_heap_size + delta` can wrap on RV32 if a
client requests a `delta` close to `usize::MAX`. A wrapped
value can land below `mem_heap_max` and pass the cap check,
letting the call proceed with a bogus heap size.

Use `checked_add` and return `Error::OutOfMemory` on overflow.

Adds a hosted-mode behavioral test that sends `usize::MAX` as
`delta` and asserts the syscall rejects it. The test doesn't
cleanly distinguish patched from unpatched code on 64-bit hosted
(both paths reject absurd deltas, just at different layers), but
it locks in the expected behavior as regression coverage.

Signed-off-by: tunnell <tunnell@users.noreply.github.com>
Assisted-by: Claude Code (Opus 4.7)
2026-04-20 09:13:47 -05:00
bunnie
c23bed360f implement extraction of kernel analytics
this is gated behind the feature "debug-proc" because this could
leak attacker-useful information, and also it adds a primitive that
causes the kernel to write the debug information into any page
that the userspace already has access to. There are some checks
to ensure that the page is actually in RAM (so you can't use this
to trigger weird peripheral states, etc.) so hypothetically this
should just cause corruption in the userspace process if it is
abused, but still - more attack surface, more problems.

however, the feature is useful enough and the risk is small enough
that I think I'm going to leave it enabled for the foreseeable future.
It's definitely helpful to be able to see how much free memory
you have, and other resource allocation trackers like connection
limits and interrupt handler allocations.
2026-01-08 02:56:33 +08:00
bunnie
a3a566b240 add API calls for debugging kernel under baochip targets
also updated some really bit-rotted docs

we will deprecate the docs/ directory soon, they are wrong
and misleading at this point.
2025-12-09 16:19:04 +08:00
bunnie
bd48886cc1 fix small syntax errors from refactor 2025-07-29 17:27:26 +08:00
bunnie
4ba2b476d1 Merge branch 'more-opt' of github.com:betrusted-io/xous-core into more-opt 2025-07-29 17:24:26 +08:00
bunnie
c151688822 convert enums into named struct per @xobs suggestion 2025-07-29 17:23:08 +08:00
bunnie
2119413b7d
Update kernel/src/syscall.rs
Co-authored-by: Sean Cross <sean@xobs.io>
2025-07-29 17:20:50 +08:00
bunnie
126896bf54 optimize kernel message passing times
Based on this benchmark of elapsed_ms():

```rust
    pub fn elapsed_ms(&self) -> u64 {
        let response = send_message(
            self.conn,
            xous::Message::new_blocking_scalar(api::Opcode::ElapsedMs.to_usize().unwrap(), 0, 0, 0, 0),
        )
        .expect("Ticktimer: failure to send message to Ticktimer");
        if let xous::Result::Scalar2(upper, lower) = response {
            upper as u64 | ((lower as u64) << 32)
        } else {
            panic!("Ticktimer elapsed_ms(): unexpected return value.");
        }
    }
```

We find the following context switches:
    1. send_message -> kernel/src/syscall.rs @ 166 - ss.remember_server_message()
        - *context switch round trip* to enqueue the message into the target thread's space, then switch back.
        - takes 546ns just in the target context, out of 4430ns round-trip
          (measured as leave userspace of caller to enter userspace of callee) (12% of total time)
        - emplaces the message in the target queue
        - generates "sender_idx" which is the index in the message queue to find the message, which is put into Envelope
    2. send_message -> kernel/src/syscall.rs @ 222 - ss.activate_process_thread()
        - activates the thread to run
        - Total penalty is closer to 1us - 22% of total time - once pre/amble/post-amble overhead considered

This set of patches removes the context-switch round trip to emplace messages in the target's thread
space, as well as to set thread results, by passing them as arguments to `activate_process_thread`.

What then happens is that these items are emplaced after the activation privot to the target
process space occurs, saving a set of TLB-flushes and page table walks.

More testing is required, but at least on a reasonable set of cases the system seems to be stable
with these patcehs, and we get a 24% speedup on blocking scalar messages and 8% speedup on
mutable lends in the case that the target is waiting to receive messages.
2025-07-29 01:24:38 +08:00
bunnie
19455d1bc0 add block erase routine 2025-05-21 10:20:04 +08:00
bunnie
289028fa48 deprecate sync/dirty and emplace the writepage syscall 2025-05-18 04:25:18 +08:00
bunnie
1a5a0a1388 attempt to fix race conditions is dirty/flush loop in swapper
this ultimately failed, we're going to try a different approach
2025-05-17 16:27:17 +08:00
bunnie
ca61545ad4 implement syscall wrappers for marking dirty and sync of flash 2025-05-16 19:13:20 +08:00
bunnie
63e4319314 add partial support for memory mapped flash (alloc virt without phys backing) 2025-05-11 12:49:23 +08:00
bunnie
b59177176b raw pointer dance for the SWITCHTO_CALLER 2024-12-02 19:06:25 +08:00
bunnie
223e1995ef fix the fix :P 2024-06-13 15:56:37 +08:00
bunnie
242c682a74 cleanup warning that snuck in 2024-06-13 15:54:32 +08:00
bunnie
40651a37ea add RawTrng syscall implementation 2024-06-13 15:42:18 +08:00
bunnie
755265d290 quiet down debug on syscalls 2024-05-28 20:28:55 +08:00
bunnie
ed73dfb401 make retrievepage a re-entrant syscall: syscall abi 2024-05-28 02:49:00 +08:00
bunnie
fb502a8073 debug cleanup 2024-05-26 12:12:58 +08:00
bunnie
f1d5a015cc remove oom-doom path handler
in practice the hard-OOM only seems to happen, and oom-doom
takes up precious memory that could be used for preventing
OOMs. Just leave one path in, but make it a bit smarter.

The smarts are still in userland, so the kernel is minimal
dependencies.
2024-05-25 02:10:55 +08:00
bunnie
514afc2385 refine swapper OOM handler security checks
The Hard OOM re-entrant syscall can actually originate in
any process space, but only from inside the kernel. Modify the
checks so that the PID==2 check is applied only to all the other
calls; and that a supervisor mode check is applied to the hard OOM
call.
2024-05-25 00:04:59 +08:00
bunnie
641b6dbeb3 remove unused configurable OOM thresholds in the kernel
turns out that

- hard OOM has a clearly defined threshold: 0. we shouldn't
make it higher, because then it forces us to count free memory
on every allocation.

- it's better to have the tuning in userspace (I think) for
OOM, because that's where all the algorithms are
2024-05-21 03:46:54 +08:00
bunnie
cf6c084696 quite down debug in kernel 2024-05-21 02:56:08 +08:00
bunnie
efd65425b3 add syscalls for "inverse" OOM'er
These calls allow for a blocking context in a userspace handler
to evict memory, as would be needed in the case of a hard-OOM.
2024-05-21 01:03:42 +08:00
bunnie
27d7fb414c add debug on evictpage 2024-05-15 02:39:58 +08:00
bunnie
0847f99433 swapper abi fixes
- evict error checking - reject requests to swap kernel or swapper
- add target amount of pages to evict on oom handler
2024-05-13 19:19:50 +08:00
bunnie
74f75e1ef5 re-org swap code for readability, add oom_doom routine
some thought needs to go into when and how we call oom_doom
but let's test more core functionality of the swapper before we
worry about that. I can think of several places where we could
use that call, the main tricky bit is that oom_doom diverges
and so wherever we patch it has to be able to resume. If we put
it into e.g. somewhere in the main memory alloc loop, the trouble
is we would have to track all of the multiple places that we
could have arrived there...ideally we can find a single spot
to patch this, with a clean entry and exit path.
2024-05-13 17:24:35 +08:00
bunnie
9b89bde46a refactor alloc API
instead of sending scalar messages on every page alloc/free, which
is a lot of traffic, introduce an API where the swapper can request
a snapshot of the alloc status by mapping the kernel's alloc
table as a read-only structure into the swapper's memory space,
and then invoking the swapper in its interrupt context to read that out.

The structure is unmapped on return from the context.

additionally, a running tally of free space is now maintained
and this can be queried with a fast syscall.

Thus, the normal workflow is the swapper would have a timer that
periodically queries the kernel's free space level, and when it
falls below a critical amount, it will invoke the expensive snapshot.

this can also be extended so that the kernel can call into
the swapper's interrupt context with a "help, OOM imminent"
message down the road.
2024-05-13 13:59:17 +08:00
bunnie
a3e55834e9 checking in the corresponding kernel changes to the RPT type alias 2024-05-12 16:28:14 +08:00
bunnie
43c452bf97 add a call to get the free memory status from the kernel
this will be helpful for debugging our page tracker
2024-05-07 04:12:46 +08:00
bunnie
b1cc676345 absorb ABI changes 2024-05-07 00:56:35 +08:00
bunnie
d9a27ea3d7 remove unnecessary print 2024-04-01 18:11:22 +08:00
bunnie
46525eff04 add separate handling for unmap syscall
The unmap syscall is a little bit tricky, because it can de-allocate
several pages at once, which can trigger an advisory de-allocate
message to the swapper in the middle of the loop. The entire structure
has to be re-written to handle this case, so we patch this right at
the top level syscall point and handle it entirely with custom
logic in the swapper.
2024-04-01 14:03:43 +08:00
bunnie
9008452a36 add arguments to register syscall for handler and state 2024-03-23 11:59:31 +08:00
bunnie
bc91055307 add template for EvictPage
actual function is still a todo
2024-03-23 11:59:31 +08:00
bunnie
b0665c3412 implement RegisterSwapper syscall 2024-03-23 11:59:31 +08:00
Sean Cross
bf61ce5071 kernel: remove dead code
This code is commented-out and dead. It gets adjusted with `cargo fmt`,
so just remove it.

Signed-off-by: Sean Cross <sean@xobs.io>
2024-02-06 10:33:33 +08:00
Sean Cross
ed4ec01017 kernel: support riscv32imac-unknown-none-elf
With Rust 1.76.0, we no longer support building with `#![no_std]` or
`panic = "abort"`, both of which are required within the kernel. As a
workaround, go back to building the kernel under
`riscv32imac-unknown-none-elf`.

Signed-off-by: Sean Cross <sean@xobs.io>
2024-02-06 10:28:33 +08:00
bunnie
f9fc3d0d4b ok, format the kernel now that all in-line assembly has been checked 2024-01-14 19:27:14 +08:00
bunnie
710c45969f Revert "format the kernel"
This reverts commit 1f69e6aa39.

this has in-line assembly, let's fix that before we format
2024-01-14 19:24:33 +08:00
bunnie
1f69e6aa39 format the kernel 2024-01-14 19:11:19 +08:00
Sean Cross
006a50d206 kernel: mem: fix memory zeroing
Fix memory zeroing when requesting a physical pointer. Previously, only
the first 25% of a page was zeroed due to a bug when casting between
*mut u8 and *mut usize.

This now uses `write_volatile` to ensure the memory clear isn't
optimized out, and uses `usize` pointers everywhere.

Signed-off-by: Sean Cross <sean@xobs.io>
2023-12-25 23:30:26 +08:00
Sean Cross
d798962151 kernel: format some files
Format some files prior to patching them.

Signed-off-by: Sean Cross <sean@xobs.io>
2023-12-25 23:28:52 +08:00
eupn
05d7f6a286
Add virt_to_phys_pid syscall
This syscall allows to obtain a physical address from a mapping of a specific process
2023-05-23 19:43:53 +04:00
Sean Cross
787d77fcbd kernel: implement FreeInterrupt
This syscall is the opposite of ClaimInterrupt.

Signed-off-by: Sean Cross <sean@xobs.io>
2023-04-06 10:42:45 +08:00
eupn
7f5656445a
kernel: change some println!s to klog!s
Even when the print-debug feature isn't turned on, println! macro is still able to output some critical non-debug info to the console such as panics, process crashes and violations, etc. Debugging messages are printed with klog! macro that's disabled when debug-print feature is not set.
2023-03-14 18:47:57 +04:00
Sean Cross
c7f5ad25b1 kernel: syscall: fix restoring thread id
The previous patch didn't properly restore thread IDs when switching
contexts -- there were spots where we missed things, and spots where we
were double-borrowing.

Fix these corner cases.

Signed-off-by: Sean Cross <sean@xobs.io>
2023-02-01 20:43:45 +08:00
bunnie
680ddd1c58
Revert "Give servers their full quantum" 2023-02-01 14:08:16 +08:00
Sean Cross
63e6deae53 kernel: save current thread at context switch
Note the current thread in the original process when its quantum
expires. This will allow us to clean up after ourselves when a context
switch occurs, and will help to prevent thread starvation.

Signed-off-by: Sean Cross <sean@xobs.io>
2023-02-01 10:46:25 +08:00