Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144// SPDX-License-Identifier: GPL-2.0-or-later// Copyright (C) 2026 Tsiry Sandratraina
use crate::{Host, Ram};use anyhow::{Context, Result, ensure};use std::collections::HashMap;use wasmtime::{Caller, Extern, Func, Linker, Module, Ref, Table};
// Wasmtime retains instantiated code until the Store is dropped. Reuse// identical kwemu regions (their state lives in RAM and call arguments) and// bound distinct instances over the lifetime of each CPU, including evictions.const MAX_INSTANCES: usize = 4096;const MAX_SOURCE_BYTES: usize = 16 << 20;
#[derive(Default)]pub struct Jit { pub enabled: bool, originals: HashMap<u32, Func>, compiled: HashMap<Vec<u8>, Func>, instances: usize, source_bytes: usize, warned: bool, active: bool,}
impl Jit { pub fn new(enabled: bool) -> Self { Self { enabled, ..Self::default() } }}
fn table(c: &mut Caller<Host>) -> Option<Table> { c.get_export("__indirect_function_table")?.into_table()}
pub fn link(linker: &mut Linker<Host>) -> Result<()> { linker.func_wrap( "unkernel", "kw_host_jit_caps", |mut c: Caller<Host>| -> i32 { if !c.data().jit.enabled || table(&mut c).is_none() { return 0; } let ty = if let Some(machine) = &c.data().smp { machine.memory.ty() } else if let Some(memory) = c.data().memory { memory.ty(&c) } else { return 0; }; // Available, memory32, shared, env.table, fixed-width SIMD. 1 | (i32::from(!ty.is_64()) << 1) | (i32::from(ty.is_shared()) << 3) | 16 | 32 }, )?; linker.func_wrap( "unkernel", "kw_host_jit_compile", |mut c: Caller<Host>, ptr: i64, len: i64, slot: u32, _flags: u32| -> i32 { match install(&mut c, ptr, len, slot) { Ok(()) => 0, Err(e) => { if !c.data().jit.warned { eprintln!("CPU {} guest JIT declined a region: {e:#}", c.data().cpu); c.data_mut().jit.warned = true; } -1 } } }, )?; linker.func_wrap( "unkernel", "kw_host_jit_free", |mut c: Caller<Host>, slot: u32| -> wasmtime::Result<()> { if let Some(&original) = c.data().jit.originals.get(&slot) { let table = table(&mut c).ok_or_else(|| wasmtime::Error::msg("missing kernel table"))?; table.set(&mut c, slot.into(), Ref::Func(Some(original)))?; c.data_mut().jit.originals.remove(&slot); } Ok(()) }, )?; Ok(())}
fn install(c: &mut Caller<Host>, ptr: i64, len: i64, slot: u32) -> Result<()> { ensure!(c.data().jit.enabled && slot != 0, "invalid JIT request"); let table = table(c).context("missing kernel table")?; let Some(Ref::Func(Some(original))) = table.get(&mut *c, slot.into()) else { anyhow::bail!("invalid JIT slot {slot}") }; let ptr = usize::try_from(ptr)?; let len = usize::try_from(len)?; ensure!( (1..=32768).contains(&len), "invalid kwemu emit buffer length" ); let (memory, bytes) = if let Some(machine) = &c.data().smp { let ram = Ram::Shared(machine.memory.data()); ( Extern::SharedMemory(machine.memory.clone()), ram.bytes(ptr, len)?.into_owned(), ) } else { let mem = c.data().memory.context("missing RAM")?; let mut bytes = vec![0; len]; mem.read(&*c, ptr, &mut bytes)?; (Extern::Memory(mem), bytes) }; let f = if let Some(&f) = c.data().jit.compiled.get(&bytes) { f } else { let jit = &c.data().jit; ensure!( jit.instances < MAX_INSTANCES && jit.source_bytes + len <= MAX_SOURCE_BYTES, "per-CPU compiled code limit reached" ); let module = Module::from_binary(c.engine(), &bytes)?; let mut linker = Linker::new(c.engine()); linker.define(&*c, "env", "memory", memory)?; linker.define(&*c, "env", "table", table)?; // A failed start or export check can also leave a store-owned instance. c.data_mut().jit.instances += 1; c.data_mut().jit.source_bytes += len; let instance = linker.instantiate(&mut *c, &module)?; let f = *instance .get_typed_func::<(i64, i64, i64, i64), i64>(&mut *c, "f")? .func(); c.data_mut().jit.compiled.insert(bytes, f); f }; table.set(&mut *c, slot.into(), Ref::Func(Some(f)))?; c.data_mut().jit.originals.entry(slot).or_insert(original); if !c.data().jit.active { eprintln!("CPU {} guest JIT active", c.data().cpu); c.data_mut().jit.active = true; } Ok(())}