fix(gpu): run a deferred compile in slices of about 2 ms that any processor resumes, and let a job's DRM call wait without the 300 ms withdraw, where a job ran whole for seconds in one host step and its DRM calls failed with ETIMEDOUT
This commit is contained in:
1 parent
4154af8402
commit
5df0579852
15 files changed
+869
-126
No files matched your search
@@ -27,6 +27,8 @@ mod kext {
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "nvk")]
|
||||
mod slice;
|
||||
#[cfg(feature = "nvk")]
|
||||
mod stack;
|
||||
#[cfg(feature = "nvk")]
|
||||
mod waiter;
|
||||
|
||||
@@ -961,6 +961,9 @@ static WITHDRAWN: AtomicU64 = AtomicU64::new(0);
|
||||
/// A call a task performs past that is reported and waited for, and one
|
||||
/// still running at [`posted_call::STOP_MS`] stops the boot, naming it.
|
||||
fn posted_wait(gpu: &Installed, request: &Request, code: u32) -> Option<i64> {
|
||||
if super::slice::can_end() {
|
||||
return job_wait(gpu, request, code);
|
||||
}
|
||||
let millis = (gpu.tsc_hz / 1000).max(1);
|
||||
let posted = request.posted;
|
||||
let ms = || host::rdtsc().wrapping_sub(posted) / millis;
|
||||
@@ -1006,6 +1009,56 @@ fn posted_wait(gpu: &Installed, request: &Request, code: u32) -> Option<i64> {
|
||||
Some(request.result.load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
/// [`posted_wait`] in a deferred job's slice, which no guest waits on: the
|
||||
/// slice gives its processor back while the call waits, and the call is not
|
||||
/// withdrawn for a wait a task would end, as a Linux process blocks in its
|
||||
/// ioctl. Only a call no task took by [`posted_call::STOP_MS`] is withdrawn,
|
||||
/// failing with ETIMEDOUT, and one a task still performs then stops the
|
||||
/// boot, naming it, as for a guest's call.
|
||||
fn job_wait(gpu: &Installed, request: &Request, code: u32) -> Option<i64> {
|
||||
let millis = (gpu.tsc_hz / 1000).max(1);
|
||||
let posted = request.posted;
|
||||
let stop_at = posted.saturating_add(posted_call::STOP_MS * millis);
|
||||
let done = || request.done.load(Ordering::Acquire) != 0;
|
||||
post(request);
|
||||
if let Err(error) = gpu.events.notify() {
|
||||
output::fatal(format_args!(
|
||||
"the host's Linux environment failed: {error:?}"
|
||||
));
|
||||
}
|
||||
while !done() {
|
||||
if host::rdtsc() >= stop_at {
|
||||
if request.withdrawable() && request.claim.withdraw() {
|
||||
output::arguments(format_args!(
|
||||
"GPU call {code:#x} withdrawn after {} ms in a deferred job on PE {}: \
|
||||
no task took it; answered ETIMEDOUT\n",
|
||||
host::rdtsc().wrapping_sub(posted) / millis,
|
||||
host::processor()
|
||||
));
|
||||
return None;
|
||||
}
|
||||
spin(gpu, request, stop_at.saturating_add(millis));
|
||||
if !done() {
|
||||
output::fatal(format_args!(
|
||||
"a GPU call ({code:#x}) of a deferred job still ran after {} ms",
|
||||
posted_call::STOP_MS
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
// The boot processor serves the call only from its run loop, so a
|
||||
// slice there gives it back at once; one that cannot runs Linux.
|
||||
if host::processor() == BOOT_CPU.load(Ordering::Relaxed) && !super::slice::can_end() {
|
||||
spin(gpu, request, stop_at);
|
||||
continue;
|
||||
}
|
||||
super::slice::wait_point();
|
||||
crate::native_mmio::shootdown::service();
|
||||
hint::spin_loop();
|
||||
}
|
||||
Some(request.result.load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
/// Requests posted to the service task since [`take_posted`] by request
|
||||
/// code: how many, and the TSC ticks their posters waited for them.
|
||||
static POSTED: Counts = [const { (AtomicU32::new(0), AtomicU64::new(0), AtomicU64::new(0)) }; 64];
|
||||
@@ -1469,7 +1522,7 @@ unsafe extern "C" fn stela_libc_log(pointer: *const u8, size: usize) {
|
||||
// SAFETY: the C library's live text.
|
||||
let bytes = unsafe { slice::from_raw_parts(pointer, size) };
|
||||
if let Ok(line) = str::from_utf8(bytes) {
|
||||
output::arguments(format_args!("{line}"));
|
||||
super::slice::without_yields(|| output::arguments(format_args!("{line}")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1499,9 +1552,10 @@ extern "C" fn stela_libc_now_ns() -> u64 {
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn stela_libc_core() -> c_uint {
|
||||
installed()
|
||||
.and_then(current_thread)
|
||||
.map_or_else(host::processor, |thread| thread.core)
|
||||
match installed().and_then(current_thread) {
|
||||
Some(thread) => thread.core,
|
||||
None => super::slice::job_core().unwrap_or_else(host::processor),
|
||||
}
|
||||
}
|
||||
|
||||
/// The core a thread of the platform's own runs as: past the C library's
|
||||
@@ -1541,6 +1595,8 @@ unsafe extern "C" fn stela_libc_wait(word: *const c_uint, value: c_uint, deadlin
|
||||
return hint::spin_loop();
|
||||
};
|
||||
let Some(thread) = current_thread(gpu) else {
|
||||
// A job's slice past its time gives its processor back here.
|
||||
super::slice::wait_point();
|
||||
return super::gate::relax();
|
||||
};
|
||||
let sleeping = &SLEEPING[thread.core as usize - PROCESSORS];
|
||||
|
||||
@@ -153,19 +153,22 @@ static TABLE: Locked = Locked {
|
||||
};
|
||||
|
||||
/// Runs `body` over the table. Page table work waits on other processors, so
|
||||
/// it stays outside.
|
||||
/// it stays outside. A job's slice does not end while it holds the table,
|
||||
/// whose allocations would otherwise be points to end at.
|
||||
fn with<T>(body: impl FnOnce(&mut Table) -> T) -> T {
|
||||
while TABLE
|
||||
.held
|
||||
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
core::hint::spin_loop();
|
||||
}
|
||||
// SAFETY: the held lock; nothing below re-enters it.
|
||||
let result = body(unsafe { &mut *TABLE.table.get() }.get_or_insert_default());
|
||||
TABLE.held.store(false, Ordering::Release);
|
||||
result
|
||||
super::slice::without_yields(|| {
|
||||
while TABLE
|
||||
.held
|
||||
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
core::hint::spin_loop();
|
||||
}
|
||||
// SAFETY: the held lock; nothing below re-enters it.
|
||||
let result = body(unsafe { &mut *TABLE.table.get() }.get_or_insert_default());
|
||||
TABLE.held.store(false, Ordering::Release);
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn install(window: &Window, address: u64, pages: &[u64]) -> bool {
|
||||
@@ -306,7 +309,8 @@ extern "C" fn stela_libc_file_mmap(
|
||||
size: usize,
|
||||
address: *mut c_void,
|
||||
) -> *mut c_void {
|
||||
let mapped = (|| {
|
||||
// Its page table work takes the window's locks.
|
||||
let mapped = super::slice::without_yields(|| {
|
||||
let gpu = installed().ok_or(ENODEV)?;
|
||||
let address = address as u64;
|
||||
if size == 0 || !offset.is_multiple_of(PAGE) || !address.is_multiple_of(PAGE) {
|
||||
@@ -318,7 +322,7 @@ extern "C" fn stela_libc_file_mmap(
|
||||
} else {
|
||||
map_fixed(gpu.window, fd, offset, address, count)
|
||||
}
|
||||
})();
|
||||
});
|
||||
match mapped {
|
||||
Ok(address) => address as *mut c_void,
|
||||
Err(error) => -(error as isize) as *mut c_void,
|
||||
@@ -327,7 +331,11 @@ extern "C" fn stela_libc_file_mmap(
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn stela_libc_file_munmap(address: *mut c_void, size: usize) -> c_int {
|
||||
let address = address as u64;
|
||||
// Its page table work takes the window's locks.
|
||||
super::slice::without_yields(|| unmap(address as u64, size))
|
||||
}
|
||||
|
||||
fn unmap(address: u64, size: usize) -> c_int {
|
||||
let Some(gpu) = installed() else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! compiler's own lock ([`run_job`]): a call that needs one is answered
|
||||
//! not ready, and its guest thread sleeps and calls again.
|
||||
use super::{
|
||||
BOOT_CPU, Bound, Installed, PAGE, client, installed, look_again, pump_waiting,
|
||||
BOOT_CPU, Bound, Installed, PAGE, client, installed, look_again, pump_waiting, slice,
|
||||
stack::{self, Stack},
|
||||
};
|
||||
use crate::{engine::host, output};
|
||||
@@ -26,7 +26,7 @@ use stela_contracts::gate::{BundleReport, GateService, MemoryRange, window};
|
||||
pub(in crate::engine) use stela_drivers::gpu::metal::deferred::Taker;
|
||||
use stela_drivers::gpu::metal::{
|
||||
compiler::{self, AirCompiler},
|
||||
deferred::busy_pause_millis,
|
||||
deferred::{busy_pause_after_slice, busy_pause_millis},
|
||||
device::{lifecycle::QuiesceStatus, pass_times},
|
||||
error::Error,
|
||||
native::{
|
||||
@@ -36,7 +36,7 @@ use stela_drivers::gpu::metal::{
|
||||
Attachment,
|
||||
open::{Gpu, OpenError, open, reopen},
|
||||
},
|
||||
service::{Served, ServiceHost, SharedService, identity::DeviceEpoch, wire::Status},
|
||||
service::{JobSlice, Served, ServiceHost, SharedService, identity::DeviceEpoch, wire::Status},
|
||||
timing::{ExitWatch, Totals},
|
||||
vulkan::physical::PciBusInfo,
|
||||
};
|
||||
@@ -49,7 +49,7 @@ use stela_loader::{apple_device_tree::DeviceTree, stela_gpu};
|
||||
type Shared = SharedService<NativeBackend, AirCompiler>;
|
||||
|
||||
/// A process's main stack, as big as the deepest compile LLVM bounds.
|
||||
const STACK_BYTES: usize = 16 << 20;
|
||||
pub(super) const STACK_BYTES: usize = 16 << 20;
|
||||
|
||||
/// How long a GPU's accepted work may go without progress as the PC stops:
|
||||
/// with the guest stopped, an event it waits on will never signal.
|
||||
@@ -96,10 +96,12 @@ fn run(stack: u64, body: &mut dyn FnMut()) {
|
||||
|
||||
/// A moment of a wait with no bound: on the boot processor it pumps, as the
|
||||
/// holder may wait for Linux, which only runs there; one Linux step can take
|
||||
/// tens of milliseconds.
|
||||
/// tens of milliseconds. It resumes a job waiting between slices, which may
|
||||
/// hold what this waits for: the compile lock, or a lock of Mesa's.
|
||||
pub(super) fn relax() {
|
||||
// What this waits for may be retiring a mapping, which waits for this.
|
||||
crate::native_mmio::shootdown::service();
|
||||
slice::help();
|
||||
if host::processor() == BOOT_CPU.load(Ordering::Relaxed) {
|
||||
pump_waiting();
|
||||
}
|
||||
@@ -203,24 +205,24 @@ static EXITS: ExitWatch = ExitWatch::new();
|
||||
/// phase: no turn should come near it.
|
||||
const LONG_TURN_MILLIS: u64 = 50;
|
||||
|
||||
/// A deferred job this long or longer is reported, each one longer than any
|
||||
/// before: its processor's guest took no interrupt meanwhile, and XNU
|
||||
/// panics when a processor stays out of its guest for about half a second.
|
||||
/// One host step of a deferred job this long or longer is reported, each
|
||||
/// one longer than any before: its processor's guest took no interrupt
|
||||
/// meanwhile, and XNU panics when a processor stays out of its guest for
|
||||
/// about half a second. A slice should end within a few milliseconds.
|
||||
const LONG_JOB_MILLIS: u64 = 100;
|
||||
|
||||
/// The longest deferred job reported so far, in TSC ticks.
|
||||
/// The longest step of a deferred job reported so far, in TSC ticks.
|
||||
static LONGEST_JOB: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Runs one deferred compilation, between two slices of a processor's guest
|
||||
/// and never inside a guest's call: a job runs whole, as the compilers have
|
||||
/// no point to stop at, so a processor with no guest work to do takes it
|
||||
/// first, and its guest's next interrupt waits for the job (a few to
|
||||
/// hundreds of milliseconds, a very large kernel seconds). Other processors'
|
||||
/// guests run meanwhile, and the guest clock does not wait for a processor
|
||||
/// whose guest waits. Off the boot processor the job runs with interrupts
|
||||
/// on; on it with only the doorbell and the TLB shootdown open ([`run`]), so
|
||||
/// a shootdown another processor sends is acknowledged at once rather than
|
||||
/// after the job. Whether one ran.
|
||||
/// Runs a slice of a deferred compilation, between two slices of a
|
||||
/// processor's guest and never inside a guest's call: a slice ends at the
|
||||
/// job's first allocation, wait or host call past [`slice::SLICE_MICROS`],
|
||||
/// so a job of seconds holds no processor out of its guest for long
|
||||
/// (`slice`). A processor with no guest work to do takes a job first.
|
||||
/// Off the boot processor a slice runs with interrupts on; on it with only
|
||||
/// the doorbell and the TLB shootdown open, so a shootdown another
|
||||
/// processor sends is acknowledged at once rather than after the slice.
|
||||
/// Whether one ran.
|
||||
pub(in crate::engine) fn run_job(taker: Taker) -> bool {
|
||||
let Some(gpu) = installed() else {
|
||||
return false;
|
||||
@@ -231,44 +233,79 @@ pub(in crate::engine) fn run_job(taker: Taker) -> bool {
|
||||
return false;
|
||||
}
|
||||
let older = millis * taker.after_millis();
|
||||
let ran = shared().iter().any(|service| {
|
||||
let resume_after = millis * taker.resume_after_millis();
|
||||
let mut ran = None;
|
||||
for service in shared().iter() {
|
||||
if !service.jobs_waiting() {
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
let run = || {
|
||||
if taker == Taker::Boot {
|
||||
service.run_job(older)
|
||||
service.run_job(older, resume_after)
|
||||
} else {
|
||||
// SAFETY: an AP's host work between slices, which holds nothing
|
||||
// its interrupts' handlers take; they save the vector state.
|
||||
unsafe { with_interrupts(|| service.run_job(older)) }
|
||||
unsafe { with_interrupts(|| service.run_job(older, resume_after)) }
|
||||
}
|
||||
};
|
||||
let began = host::rdtsc();
|
||||
let ran = measured_job(run);
|
||||
let took = host::rdtsc().wrapping_sub(began);
|
||||
if ran
|
||||
&& took >= LONG_JOB_MILLIS * millis
|
||||
&& LONGEST_JOB.fetch_max(took, Ordering::Relaxed) < took
|
||||
{
|
||||
output::arguments(format_args!(
|
||||
"GPU LONG JOB ms={} taker={taker:?} pe={}: its guest took no interrupt meanwhile\n",
|
||||
took / millis.max(1),
|
||||
host::processor()
|
||||
));
|
||||
if let Some(step) = measured_job(service.job_between_slices(), run) {
|
||||
note_long_step(step.ticks, millis, taker);
|
||||
ran = Some(step);
|
||||
break;
|
||||
}
|
||||
ran
|
||||
});
|
||||
if taker == Taker::Busy {
|
||||
// After a job, busy processors leave the next to a waiting one for
|
||||
// the spacing; with none due, they look again soon, so that the
|
||||
// spacing never adds to a job's wait.
|
||||
NEXT_BUSY_JOB.store(
|
||||
host::rdtsc().wrapping_add(millis * busy_pause_millis(ran)),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
}
|
||||
ran
|
||||
if taker == Taker::Busy {
|
||||
// After a slice, busy processors leave the next to a waiting one
|
||||
// for as long as it took; with none due, they look again soon, so
|
||||
// that the spacing never adds to a job's wait.
|
||||
let pause = match ran {
|
||||
Some(step) => busy_pause_after_slice(step.ticks, millis),
|
||||
None => millis * busy_pause_millis(false),
|
||||
};
|
||||
NEXT_BUSY_JOB.store(host::rdtsc().wrapping_add(pause), Ordering::Relaxed);
|
||||
}
|
||||
ran.is_some()
|
||||
}
|
||||
|
||||
/// Reports a job's host step of `ticks`, each one longer than any before
|
||||
/// once it reaches [`LONG_JOB_MILLIS`].
|
||||
fn note_long_step(ticks: u64, millis: u64, taker: Taker) {
|
||||
if ticks >= LONG_JOB_MILLIS * millis && LONGEST_JOB.fetch_max(ticks, Ordering::Relaxed) < ticks
|
||||
{
|
||||
output::arguments(format_args!(
|
||||
"GPU LONG JOB ms={} taker={taker:?} pe={}: its guest took no interrupt meanwhile\n",
|
||||
ticks / millis.max(1),
|
||||
host::processor()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Resumes a job that waits between slices, for a wait outside every job
|
||||
/// ([`slice::help`]); never starts one.
|
||||
pub(super) fn resume_job() {
|
||||
for service in shared().iter() {
|
||||
if service.job_between_slices() {
|
||||
if let Some(gpu) = installed() {
|
||||
let millis = gpu.tsc_hz / 1000;
|
||||
if let Some(step) = measured_job(true, || service.run_job(u64::MAX, 0)) {
|
||||
note_long_step(step.ticks, millis, Taker::Waiting);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The C library's core for the jobs on the compile stack at `top`: one
|
||||
/// past every processor's from the top of the processors' range, one for
|
||||
/// each compile stack, so that a job keeps its thread-local values on
|
||||
/// whichever processor resumes it ([`slice::job_core`]).
|
||||
pub(super) fn job_core(top: u64) -> core::ffi::c_uint {
|
||||
let index = COMPILE_STACKS
|
||||
.iter()
|
||||
.position(|stack| stack.load(Ordering::Relaxed) == top)
|
||||
.unwrap_or(COMPILE_STACKS.len());
|
||||
(slice::LIBC_PROCESSORS - 1 - index) as core::ffi::c_uint
|
||||
}
|
||||
|
||||
/// Whether a busy processor may look for a job ([`Taker::Busy`]) now: a
|
||||
@@ -281,31 +318,44 @@ pub(in crate::engine) fn busy_job_due() -> bool {
|
||||
/// `GPU JOBS` line, and the carved bytes that job started from.
|
||||
static JOB_RISE: AtomicU64 = AtomicU64::new(0);
|
||||
static JOB_RISE_FROM: AtomicU64 = AtomicU64::new(0);
|
||||
/// Set while a processor measures the job it runs.
|
||||
/// Set while a job is measured, from its first slice to its end.
|
||||
static MEASURING: AtomicBool = AtomicBool::new(false);
|
||||
/// Set while the measured job waits between slices, keeping the heap's mark.
|
||||
static MEASURED_BETWEEN: AtomicBool = AtomicBool::new(false);
|
||||
/// The carved bytes the measured job started from.
|
||||
static MEASURED_FROM: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Runs `run`, and when it ran a job, keeps how far the heap's carved
|
||||
/// bytes rose above where they were: a compile's own peak, as jobs run one
|
||||
/// at a time, with what other processors carved meanwhile. One processor
|
||||
/// measures at a time, as the heap keeps one mark.
|
||||
fn measured_job(run: impl FnOnce() -> bool) -> bool {
|
||||
if MEASURING
|
||||
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
return run();
|
||||
/// Runs `run`, and for a job it began, keeps how far the heap's carved
|
||||
/// bytes rose above where they were until the job ended: a compile's own
|
||||
/// peak, as jobs run one at a time, with what other processors carved
|
||||
/// meanwhile. One job is measured at a time, as the heap keeps one mark.
|
||||
/// `between`: a job waits between slices, which `run` may resume.
|
||||
fn measured_job(between: bool, run: impl FnOnce() -> Option<JobSlice>) -> Option<JobSlice> {
|
||||
let measure = !between
|
||||
&& MEASURING
|
||||
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok();
|
||||
if measure {
|
||||
MEASURED_FROM.store(crate::ALLOCATOR.mark() as u64, Ordering::Relaxed);
|
||||
}
|
||||
let from = crate::ALLOCATOR.mark();
|
||||
let ran = run();
|
||||
if ran {
|
||||
let rise = crate::ALLOCATOR.marked_peak().saturating_sub(from) as u64;
|
||||
let step = run();
|
||||
let began = measure && step.is_some_and(|step| step.started);
|
||||
let ended = step.is_some_and(|step| step.finished)
|
||||
&& (began || MEASURED_BETWEEN.swap(false, Ordering::AcqRel));
|
||||
if ended {
|
||||
let from = MEASURED_FROM.load(Ordering::Relaxed);
|
||||
let rise = (crate::ALLOCATOR.marked_peak() as u64).saturating_sub(from);
|
||||
if rise > JOB_RISE.load(Ordering::Relaxed) {
|
||||
JOB_RISE.store(rise, Ordering::Relaxed);
|
||||
JOB_RISE_FROM.store(from as u64, Ordering::Relaxed);
|
||||
JOB_RISE_FROM.store(from, Ordering::Relaxed);
|
||||
}
|
||||
MEASURING.store(false, Ordering::Release);
|
||||
} else if began {
|
||||
MEASURED_BETWEEN.store(true, Ordering::Release);
|
||||
} else if measure {
|
||||
MEASURING.store(false, Ordering::Release);
|
||||
}
|
||||
MEASURING.store(false, Ordering::Release);
|
||||
ran
|
||||
step
|
||||
}
|
||||
|
||||
/// Runs `body` with this processor's interrupts on.
|
||||
@@ -330,12 +380,14 @@ fn report(reason: &str) {
|
||||
}
|
||||
|
||||
/// Logs each distinct error or warning NVK reports, such as why a call failed
|
||||
/// with only a generic result.
|
||||
/// with only a generic result: in a job too, where no slice ends in it.
|
||||
fn driver_message(text: &str) {
|
||||
static SEEN: Seen<128> = Seen::new();
|
||||
if let Some(unheld) = SEEN.first_time(text) {
|
||||
output::arguments(format_args!("GPU DRIVER {text}{unheld}\n"));
|
||||
report_peaks();
|
||||
slice::without_yields(|| {
|
||||
output::arguments(format_args!("GPU DRIVER {text}{unheld}\n"));
|
||||
report_peaks();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -831,11 +883,13 @@ pub(in crate::engine) fn report_calls(tsc_hz: u64) {
|
||||
let jobs = service.take_job_report();
|
||||
if jobs.ran != 0 || jobs.deferred != 0 {
|
||||
output::arguments(format_args!(
|
||||
"GPU JOBS ran={} total_us={} longest_us={} longest_queued_us={} deferred={} \
|
||||
repeated={} waiting={} heap_rise={}M from={}M\n",
|
||||
"GPU JOBS ran={} total_us={} longest_us={} slices={} longest_slice_us={} \
|
||||
longest_queued_us={} deferred={} repeated={} waiting={} heap_rise={}M from={}M\n",
|
||||
jobs.ran,
|
||||
micros(jobs.ticks),
|
||||
micros(jobs.longest),
|
||||
jobs.slices,
|
||||
micros(jobs.longest_slice),
|
||||
micros(jobs.longest_queued),
|
||||
jobs.deferred,
|
||||
jobs.repeated,
|
||||
@@ -1162,6 +1216,9 @@ fn open_gpu(
|
||||
free.store(compiling.top(), Ordering::Relaxed);
|
||||
}
|
||||
service.set_compile_stack(compiling.top());
|
||||
// Jobs run in slices there; their allocations end them.
|
||||
service.set_job_slicer(slice::start);
|
||||
stela_boot_core::heap::set_allocation_hook(slice::allocation_point);
|
||||
core::mem::forget(compiling);
|
||||
// Imports' exports and driver imports run after their turn
|
||||
// on a stack of their own; without one they stay in it. So
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Deferred GPU jobs in bounded host steps.
|
||||
//!
|
||||
//! A shader compilation can run for seconds, and a processor kept from its
|
||||
//! guest for about half a second makes XNU panic. So each job runs as a
|
||||
//! fiber on its service's compile stack (`stela_boot_core::fiber`), and a
|
||||
//! slice of it gives its processor back at the first of these past
|
||||
//! [`SLICE_MICROS`]: an allocation, which NIR, NAK and LLVM make all the
|
||||
//! time ([`allocation_point`]); a C-library wait; a host call that is not
|
||||
//! done. Any processor resumes it later from its run loop, as it took the
|
||||
//! job; one that waits for the compile lock or a lock the job holds
|
||||
//! resumes it too ([`help`]). The job computes the same, only split in
|
||||
//! time, and holds the compile lock from its first slice to its end.
|
||||
//!
|
||||
//! A slice gives its processor back only where it may: in the job's own
|
||||
//! code with interrupts on (never in an interrupt handler), on the compile
|
||||
//! stack, and outside the host callbacks that take a lock of their own
|
||||
//! ([`without_yields`]). Elsewhere it runs on to the next such point.
|
||||
//!
|
||||
//! While a slice runs, the C library sees the job as a core of its own
|
||||
//! ([`job_core`]), so its thread-local values and lock owners stay the
|
||||
//! job's on whichever processor resumes it.
|
||||
use super::{BOOT_CPU, gate, installed};
|
||||
use crate::engine::host;
|
||||
use alloc::boxed::Box;
|
||||
use core::{
|
||||
ffi::c_uint,
|
||||
sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering},
|
||||
};
|
||||
use stela_boot_core::fiber::{Fiber, Handle, Step};
|
||||
use stela_drivers::gpu::metal::deferred::Sliced;
|
||||
|
||||
/// How long a slice runs before it gives its processor back at its next
|
||||
/// point: a guest interrupt on that processor waits about this long.
|
||||
pub(super) const SLICE_MICROS: u64 = 2000;
|
||||
|
||||
/// `STELA_LIBC_PROCESSORS`: the C library's cores for host processors.
|
||||
pub(super) const LIBC_PROCESSORS: usize = 256;
|
||||
|
||||
/// What a processor runs of a job now.
|
||||
struct Slot {
|
||||
/// The running fiber's [`Handle`] address, zero while it runs none.
|
||||
fiber: AtomicUsize,
|
||||
/// When its slice ends, in TSC ticks.
|
||||
deadline: AtomicU64,
|
||||
/// The compile stack's top.
|
||||
top: AtomicU64,
|
||||
/// The C library's core for it, `u32::MAX` for the processor's own.
|
||||
core: AtomicU32,
|
||||
/// Host callbacks entered that a slice may not end in.
|
||||
held: AtomicU32,
|
||||
}
|
||||
|
||||
static SLOTS: [Slot; LIBC_PROCESSORS] = [const {
|
||||
Slot {
|
||||
fiber: AtomicUsize::new(0),
|
||||
deadline: AtomicU64::new(0),
|
||||
top: AtomicU64::new(0),
|
||||
core: AtomicU32::new(u32::MAX),
|
||||
held: AtomicU32::new(0),
|
||||
}
|
||||
}; LIBC_PROCESSORS];
|
||||
|
||||
/// Processors running a slice now, so that an allocation elsewhere pays
|
||||
/// one load.
|
||||
static SLICING: AtomicU32 = AtomicU32::new(0);
|
||||
/// Jobs that ran a slice and wait to be resumed.
|
||||
static BETWEEN: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// A job on a compile stack, run in slices.
|
||||
struct Job {
|
||||
fiber: Fiber,
|
||||
top: u64,
|
||||
/// The C library's core for it.
|
||||
core: c_uint,
|
||||
/// It ran a slice and waits.
|
||||
between: bool,
|
||||
}
|
||||
|
||||
/// The platform's [`stela_drivers::gpu::metal::deferred::Slicer`]: `body`
|
||||
/// as a job on the compile stack below `top`, whose first slice begins it.
|
||||
pub(super) fn start(top: u64, body: Box<dyn FnOnce() + Send>) -> Box<dyn Sliced> {
|
||||
// SAFETY: a service's compile stack, which only its jobs use, one at a
|
||||
// time under the compile lock this job holds until it ends.
|
||||
let fiber = unsafe { Fiber::new(top, body) };
|
||||
Box::new(Job {
|
||||
fiber,
|
||||
top,
|
||||
core: gate::job_core(top),
|
||||
between: false,
|
||||
})
|
||||
}
|
||||
|
||||
impl Sliced for Job {
|
||||
fn resume(&mut self) -> bool {
|
||||
if core::mem::take(&mut self.between) {
|
||||
BETWEEN.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
let slot = SLOTS.get(host::processor() as usize);
|
||||
if let Some(slot) = slot {
|
||||
let tsc_hz = installed().map_or(0, |gpu| gpu.tsc_hz);
|
||||
slot.deadline.store(
|
||||
host::rdtsc().saturating_add(tsc_hz / 1_000_000 * SLICE_MICROS),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
slot.top.store(self.top, Ordering::Relaxed);
|
||||
// A core past every processor's, which no processor answers as.
|
||||
let own = self.core >= host::processors();
|
||||
slot.core
|
||||
.store(if own { self.core } else { u32::MAX }, Ordering::Relaxed);
|
||||
slot.fiber
|
||||
.store(self.fiber.handle().address(), Ordering::Relaxed);
|
||||
SLICING.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
// SAFETY: a job runs where long host work is allowed, from a run
|
||||
// loop or a wait that holds nothing the doorbell's or the
|
||||
// shootdown's handler takes; it leaves IF and CR8 as they were.
|
||||
let step = unsafe { crate::native_mmio::shootdown::job(|| self.fiber.resume()) };
|
||||
if let Some(slot) = slot {
|
||||
slot.fiber.store(0, Ordering::Relaxed);
|
||||
SLICING.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
match step {
|
||||
Step::Finished => true,
|
||||
Step::Suspended => {
|
||||
self.between = true;
|
||||
BETWEEN.fetch_add(1, Ordering::AcqRel);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot of the slice this processor runs, when its job may give the
|
||||
/// processor back here, with the job's handle.
|
||||
fn may_end() -> Option<(&'static Slot, Handle)> {
|
||||
if SLICING.load(Ordering::Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
let slot = SLOTS.get(host::processor() as usize)?;
|
||||
let fiber = slot.fiber.load(Ordering::Relaxed);
|
||||
if fiber == 0 || slot.held.load(Ordering::Relaxed) != 0 || !interrupts_on() {
|
||||
return None;
|
||||
}
|
||||
let top = slot.top.load(Ordering::Relaxed);
|
||||
let pointer = super::stack::pointer();
|
||||
if pointer >= top || top - pointer >= gate::STACK_BYTES as u64 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: set from the running fiber's handle, which lives while it runs.
|
||||
Some((slot, unsafe { Handle::from_address(fiber) }))
|
||||
}
|
||||
|
||||
fn interrupts_on() -> bool {
|
||||
let flags: u64;
|
||||
// SAFETY: reads RFLAGS through the stack, which the push and pop balance.
|
||||
unsafe { core::arch::asm!("pushfq", "pop {}", out(reg) flags, options(preserves_flags)) };
|
||||
flags & (1 << 9) != 0
|
||||
}
|
||||
|
||||
/// The heap's allocation hook: a slice past its time gives its processor
|
||||
/// back here, before the heap takes anything.
|
||||
pub(super) fn allocation_point() {
|
||||
let Some((slot, handle)) = may_end() else {
|
||||
return;
|
||||
};
|
||||
if host::rdtsc() >= slot.deadline.load(Ordering::Relaxed) {
|
||||
// SAFETY: the running job's own frame, on its stack, interrupts on.
|
||||
unsafe { handle.suspend() };
|
||||
}
|
||||
}
|
||||
|
||||
/// A moment of a wait in a job's slice: past the slice's time, or on the
|
||||
/// boot processor, whose run loop serves the Linux work the job may wait
|
||||
/// for, it gives the processor back. Whether this processor runs a slice.
|
||||
pub(super) fn wait_point() -> bool {
|
||||
let Some((slot, handle)) = may_end() else {
|
||||
return in_job();
|
||||
};
|
||||
if host::processor() == BOOT_CPU.load(Ordering::Relaxed)
|
||||
|| host::rdtsc() >= slot.deadline.load(Ordering::Relaxed)
|
||||
{
|
||||
// SAFETY: as in `allocation_point`.
|
||||
unsafe { handle.suspend() };
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether a slice that waits here can give its processor back.
|
||||
pub(super) fn can_end() -> bool {
|
||||
may_end().is_some()
|
||||
}
|
||||
|
||||
/// Whether this processor runs a job's slice.
|
||||
pub(super) fn in_job() -> bool {
|
||||
SLICING.load(Ordering::Relaxed) != 0
|
||||
&& SLOTS
|
||||
.get(host::processor() as usize)
|
||||
.is_some_and(|slot| slot.fiber.load(Ordering::Relaxed) != 0)
|
||||
}
|
||||
|
||||
/// The C library's core for the job this processor runs a slice of.
|
||||
pub(super) fn job_core() -> Option<c_uint> {
|
||||
if SLICING.load(Ordering::Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
let slot = SLOTS.get(host::processor() as usize)?;
|
||||
if slot.fiber.load(Ordering::Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
match slot.core.load(Ordering::Relaxed) {
|
||||
u32::MAX => None,
|
||||
core => Some(core),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `body`, a host callback that takes a lock of its own, with no slice
|
||||
/// ending inside it.
|
||||
pub(super) fn without_yields<R>(body: impl FnOnce() -> R) -> R {
|
||||
let slot = (SLICING.load(Ordering::Relaxed) != 0)
|
||||
.then(|| SLOTS.get(host::processor() as usize))
|
||||
.flatten();
|
||||
if let Some(slot) = slot {
|
||||
slot.held.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let result = body();
|
||||
// No slice ended in it, so it ends on the processor it began on.
|
||||
if let Some(slot) = slot {
|
||||
slot.held.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// A moment of a wait outside a job: resumes a job that waits between
|
||||
/// slices, as the wait may be for the compile lock or a lock the job
|
||||
/// holds. Never from a job's own slice, and only where the slice would
|
||||
/// run with interrupts on and can end.
|
||||
pub(super) fn help() {
|
||||
if BETWEEN.load(Ordering::Relaxed) == 0
|
||||
|| in_job()
|
||||
|| !crate::native_mmio::shootdown::job_opens()
|
||||
{
|
||||
return;
|
||||
}
|
||||
gate::resume_job();
|
||||
}
|
||||
@@ -83,9 +83,9 @@ use stela_boot_core::ram;
|
||||
mod translated;
|
||||
pub(crate) use local::activated_base;
|
||||
pub(crate) use local::context::RootIdentity;
|
||||
#[cfg(feature = "nvk")]
|
||||
pub(crate) use local::processor;
|
||||
use local::state;
|
||||
#[cfg(feature = "nvk")]
|
||||
pub(crate) use local::{processor, processors};
|
||||
|
||||
/// Calls `action` with each host run behind `bytes` of guest RAM at `guest`, as
|
||||
/// (host physical, bytes). False, partway, if part of it is not RAM.
|
||||
|
||||
@@ -279,6 +279,13 @@ pub(crate) unsafe fn configure_xstate(
|
||||
/// How many processors have become active.
|
||||
static ACTIVE: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// How many processors have become active: each one's [`processor`] is
|
||||
/// below it.
|
||||
#[cfg(feature = "nvk")]
|
||||
pub(crate) fn processors() -> u32 {
|
||||
ACTIVE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
unsafe fn set_base(base: u64) {
|
||||
// SAFETY: the executor owns this processor's GS, and its descriptor/IST
|
||||
// setup has already finished. The base remains mapped in every root.
|
||||
|
||||
@@ -218,6 +218,22 @@ pub(crate) unsafe fn job<R>(body: impl FnOnce() -> R) -> R {
|
||||
result
|
||||
}
|
||||
|
||||
/// Whether [`job`] here runs its body with interrupts on: they are on, or
|
||||
/// the task priority is no higher than the one it raises.
|
||||
#[cfg(feature = "nvk")]
|
||||
pub(crate) fn job_opens() -> bool {
|
||||
let flags: u64;
|
||||
// SAFETY: reads RFLAGS through the stack, which the push and pop balance.
|
||||
unsafe { asm!("pushfq", "pop {}", out(reg) flags, options(preserves_flags)) };
|
||||
if flags & RFLAGS_IF != 0 {
|
||||
return true;
|
||||
}
|
||||
let priority: u64;
|
||||
// SAFETY: CPL0 read of the task priority.
|
||||
unsafe { asm!("mov {}, cr8", out(reg) priority, options(nomem, nostack, preserves_flags)) };
|
||||
priority <= JOB_PRIORITY
|
||||
}
|
||||
|
||||
/// After the caller cleared the leaf entries of `retired` (all of them, or
|
||||
/// `None` when they are not one range) and flushed its own TLB: shoot them
|
||||
/// down on every other joined processor. Whether each acknowledged within
|
||||
|
||||
@@ -74,7 +74,7 @@ use core::{
|
||||
use triomphe::Arc;
|
||||
|
||||
use library_cache::{LoadedLibrary, ModuleSource, Selected};
|
||||
pub use nir_cache::{CompileGuard, CompileLock};
|
||||
pub use nir_cache::{CompileGuard, CompileLock, SharedHold};
|
||||
use nir_cache::{NirCache, ReflectionCache, ReflectionKey, Returned};
|
||||
|
||||
/// The shader stages the AIR frontend lowers completely; other constructs
|
||||
|
||||
@@ -274,6 +274,15 @@ impl CompileLock {
|
||||
.then(|| CompileGuard(self))
|
||||
}
|
||||
|
||||
/// Holds the lock unless another holds it, for as long as what owns
|
||||
/// the answer keeps it, on any processor: a job that runs in slices.
|
||||
pub fn try_hold_shared(self: &alloc::sync::Arc<Self>) -> Option<SharedHold> {
|
||||
self.held
|
||||
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
.then(|| SharedHold(self.clone()))
|
||||
}
|
||||
|
||||
/// Whether the call served now deferred a compilation.
|
||||
pub fn deferred(&self) -> bool {
|
||||
self.deferred.load(Ordering::Acquire)
|
||||
@@ -315,6 +324,16 @@ impl Drop for CompileGuard<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The compile lock, held by its owner until it drops this
|
||||
/// ([`CompileLock::try_hold_shared`]).
|
||||
pub struct SharedHold(alloc::sync::Arc<CompileLock>);
|
||||
|
||||
impl Drop for SharedHold {
|
||||
fn drop(&mut self) {
|
||||
self.0.held.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
//! which runs NIR to machine code. The job owns its inputs, so it runs on
|
||||
//! any processor while other calls take turns. Its [`Done`] goes back to its
|
||||
//! owner in a later turn, and the call, run again, finds what it made.
|
||||
//!
|
||||
//! A platform whose processors must return to their guests within a bound
|
||||
//! runs a job in slices ([`Sliced`]): the job gives its processor back at
|
||||
//! points the platform chooses and any processor resumes it later. It
|
||||
//! computes the same; it holds the compile lock from its first slice to its
|
||||
//! end.
|
||||
use super::compiler::CompileLock;
|
||||
use alloc::{boxed::Box, sync::Arc};
|
||||
use core::any::Any;
|
||||
@@ -42,6 +48,13 @@ impl Job {
|
||||
/// Runs the job. Jobs run one at a time, on the one compile stack,
|
||||
/// under the compile lock the caller holds.
|
||||
pub fn run(self, _held: &super::compiler::CompileGuard<'_>) -> Done {
|
||||
self.run_sliced()
|
||||
}
|
||||
|
||||
/// [`Self::run`], for a job run in slices, whose runner holds the
|
||||
/// compile lock with a [`SharedHold`](super::compiler::SharedHold)
|
||||
/// from its first slice until it took what the job made.
|
||||
pub fn run_sliced(self) -> Done {
|
||||
Done {
|
||||
key: self.key,
|
||||
owner: self.owner,
|
||||
@@ -66,6 +79,19 @@ pub struct Done {
|
||||
pub made: Made,
|
||||
}
|
||||
|
||||
/// A job a platform runs in slices: started on the compile stack by its
|
||||
/// [`Slicer`], it gives its processor back where the platform decides.
|
||||
pub trait Sliced: Send {
|
||||
/// Runs the job on until it gives its processor back or ends: whether
|
||||
/// it ended.
|
||||
fn resume(&mut self) -> bool;
|
||||
}
|
||||
|
||||
/// Starts a job's body on the compile stack whose top is the first
|
||||
/// argument, to run in slices; nothing of it runs before its first
|
||||
/// [`Sliced::resume`].
|
||||
pub type Slicer = fn(u64, Box<dyn FnOnce() + Send>) -> Box<dyn Sliced>;
|
||||
|
||||
/// The lock jobs run under, and what a waiter for it runs: a backend holds
|
||||
/// it while it destroys what its jobs use.
|
||||
#[derive(Clone)]
|
||||
@@ -103,6 +129,25 @@ impl Taker {
|
||||
Self::Busy => 20,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a job that ran a slice waits before this taker resumes it,
|
||||
/// in milliseconds: at once, but for the boot processor, whose Linux
|
||||
/// work a slice holds up. Busy processors are spaced by
|
||||
/// [`busy_pause_after_slice`].
|
||||
pub const fn resume_after_millis(self) -> u64 {
|
||||
match self {
|
||||
Self::Waiting | Self::Busy => 0,
|
||||
Self::Boot => 100,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long busy processors leave the queue after one of them ran a slice
|
||||
/// of `slice` ticks, with `millis` ticks to a millisecond: as long as the
|
||||
/// slice and at least a millisecond, so that a job in slices costs busy
|
||||
/// guests about half of one processor at most.
|
||||
pub const fn busy_pause_after_slice(slice: u64, millis: u64) -> u64 {
|
||||
if slice > millis { slice } else { millis }
|
||||
}
|
||||
|
||||
/// How long busy processors leave the queue after one of them looked, in
|
||||
@@ -123,7 +168,7 @@ pub const fn busy_wait_millis() -> u64 {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Taker, busy_pause_millis, busy_wait_millis};
|
||||
use super::{Taker, busy_pause_after_slice, busy_pause_millis, busy_wait_millis};
|
||||
|
||||
#[test]
|
||||
fn a_job_waits_about_a_frame_with_every_processor_busy() {
|
||||
@@ -134,4 +179,16 @@ mod tests {
|
||||
assert_eq!(busy_wait_millis(), 21);
|
||||
assert!(busy_pause_millis(false) < busy_pause_millis(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_job_in_slices_takes_half_a_busy_processor_and_the_boot_one_last() {
|
||||
assert_eq!(Taker::Waiting.resume_after_millis(), 0);
|
||||
assert_eq!(Taker::Busy.resume_after_millis(), 0);
|
||||
assert_eq!(
|
||||
Taker::Boot.resume_after_millis(),
|
||||
Taker::Boot.after_millis()
|
||||
);
|
||||
assert_eq!(busy_pause_after_slice(2_000, 1_000), 2_000);
|
||||
assert_eq!(busy_pause_after_slice(10, 1_000), 1_000);
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,17 @@ fn gated_job(key: u8, owner: Owner, gate: Arc<AtomicBool>) -> Job {
|
||||
})
|
||||
}
|
||||
|
||||
/// A deferred job that computes in `steps` steps, calling `pause` after
|
||||
/// each, as a long compilation its platform may suspend at each.
|
||||
fn stepped_job(key: u8, owner: Owner, steps: u32, pause: fn()) -> Job {
|
||||
Job::new([key; 32], owner, move || {
|
||||
for _ in 0..steps {
|
||||
pause();
|
||||
}
|
||||
Box::new(()) as Made
|
||||
})
|
||||
}
|
||||
|
||||
/// [`Outside`] of the mock: a preparation waits while `hold` is set, as the
|
||||
/// driver's import waits for the boot processor, and counts what it did.
|
||||
#[derive(Default)]
|
||||
@@ -659,6 +670,8 @@ pub(crate) struct MockCompiler {
|
||||
/// While a call may defer, the deferred compilation leaves a job that
|
||||
/// runs until this opens.
|
||||
pub(crate) job_gate: Option<Arc<AtomicBool>>,
|
||||
/// Or one that runs this many steps, calling the function after each.
|
||||
pub(crate) job_steps: Option<(u32, fn())>,
|
||||
deferring: bool,
|
||||
job: Option<Job>,
|
||||
/// Jobs adopted.
|
||||
@@ -908,6 +921,11 @@ impl Compiler for MockCompiler {
|
||||
{
|
||||
self.job = Some(gated_job(1, Owner::Compiler, gate));
|
||||
}
|
||||
if self.deferring
|
||||
&& let Some((steps, pause)) = self.job_steps.take()
|
||||
{
|
||||
self.job = Some(stepped_job(1, Owner::Compiler, steps, pause));
|
||||
}
|
||||
return Err(crate::metal::compiler::DEFERRED);
|
||||
}
|
||||
self.compiled.push(specialization.clone());
|
||||
|
||||
@@ -38,7 +38,10 @@ use core::{
|
||||
};
|
||||
use identity::{DeviceEpoch, ObjectHandle, ObjectTable, TableError};
|
||||
use libraries::LibraryNames;
|
||||
pub use shared::{IMPORT_AGAIN_OPERATION, IMPORT_OPERATION, Served, ServiceHost, SharedService};
|
||||
pub use shared::{
|
||||
IMPORT_AGAIN_OPERATION, IMPORT_OPERATION, JobReport, JobSlice, Served, ServiceHost,
|
||||
SharedService,
|
||||
};
|
||||
use stela_contracts::gate::MemoryRange;
|
||||
use wire::{Fault, Handle, NegotiateRequest, NegotiateResponse, Operation, Record, Span, Status};
|
||||
|
||||
|
||||
@@ -68,8 +68,8 @@ use super::{
|
||||
wire::{self, GateCall, NewLibraryRequest, Operation, Span, Status},
|
||||
};
|
||||
use crate::metal::{
|
||||
compiler::{self, AirCompiler, CompileLock},
|
||||
deferred::{Done, Job, JobLock, Owner},
|
||||
compiler::{self, AirCompiler, CompileLock, SharedHold},
|
||||
deferred::{Done, Job, JobLock, Owner, Sliced, Slicer},
|
||||
shader::Compiler,
|
||||
timing::CallPhases,
|
||||
vulkan::{
|
||||
@@ -130,6 +130,8 @@ pub struct SharedService<B: Backend, C: Compiler> {
|
||||
/// The stack jobs run on, zero while the platform runs none, and the
|
||||
/// lock they run under.
|
||||
compile_stack: AtomicU64,
|
||||
/// The platform's [`Slicer`], as an address, zero while jobs run whole.
|
||||
slicer: AtomicUsize,
|
||||
/// The longest a frontend call waits for the turn before it is answered
|
||||
/// `Pending`, in ticks; 0 waits for as long as the holder holds it.
|
||||
wait_bound: AtomicU64,
|
||||
@@ -176,6 +178,9 @@ struct Jobs {
|
||||
/// Jobs not yet run, each with when it was queued.
|
||||
queued: VecDeque<(Job, u64)>,
|
||||
running: Option<[u8; 32]>,
|
||||
/// The job that ran a slice and gave its processor back, while no
|
||||
/// processor resumes it.
|
||||
active: Option<Active>,
|
||||
/// Jobs that ran, for the next turn to adopt.
|
||||
done: Vec<Done>,
|
||||
/// Calls answered `Pending`, by the key they wait for.
|
||||
@@ -183,6 +188,34 @@ struct Jobs {
|
||||
report: JobReport,
|
||||
}
|
||||
|
||||
/// A job run in slices ([`SharedService::set_job_slicer`]), between them.
|
||||
struct Active {
|
||||
sliced: Box<dyn Sliced>,
|
||||
/// What it made, once it ended.
|
||||
made: Arc<Spin<Option<Done>>>,
|
||||
/// The compile lock, from its first slice until what it made is
|
||||
/// published.
|
||||
_held: SharedHold,
|
||||
/// From queueing to its first slice.
|
||||
waited: u64,
|
||||
/// When its last slice ended.
|
||||
last: u64,
|
||||
/// Its slices' ticks, and how many it ran.
|
||||
ticks: u64,
|
||||
slices: u64,
|
||||
}
|
||||
|
||||
/// What one [`SharedService::run_job`] ran.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct JobSlice {
|
||||
/// It began a job.
|
||||
pub started: bool,
|
||||
/// The job ended.
|
||||
pub finished: bool,
|
||||
/// Its ticks: one slice, or the whole job when it ran whole.
|
||||
pub ticks: u64,
|
||||
}
|
||||
|
||||
/// A call answered `Pending`: the same call made again is answered so
|
||||
/// until the job of `key` has run.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -204,6 +237,10 @@ pub struct JobReport {
|
||||
pub ran: u64,
|
||||
pub ticks: u64,
|
||||
pub longest: u64,
|
||||
/// The host steps jobs ran in, and the longest one: a job run whole is
|
||||
/// one step.
|
||||
pub slices: u64,
|
||||
pub longest_slice: u64,
|
||||
/// From queueing to running, the longest.
|
||||
pub longest_queued: u64,
|
||||
/// Calls answered `Pending`, with a turn and without one.
|
||||
@@ -307,6 +344,10 @@ struct Spin<T> {
|
||||
value: UnsafeCell<T>,
|
||||
}
|
||||
|
||||
// SAFETY: the flag gives one caller at a time the value, which may cross
|
||||
// processors.
|
||||
unsafe impl<T: Send> Sync for Spin<T> {}
|
||||
|
||||
impl<T> Spin<T> {
|
||||
fn new(value: T) -> Self {
|
||||
Self {
|
||||
@@ -701,6 +742,7 @@ impl<B: Backend, C: Compiler + 'static> SharedService<B, C> {
|
||||
publishable: AtomicBool::new(publishable),
|
||||
early: [const { (AtomicU64::new(0), AtomicU64::new(0)) }; PENDING],
|
||||
compile_stack: AtomicU64::new(0),
|
||||
slicer: AtomicUsize::new(0),
|
||||
wait_bound: AtomicU64::new(0),
|
||||
job_lock: JobLock {
|
||||
lock: compile_lock.unwrap_or_default(),
|
||||
@@ -731,6 +773,20 @@ impl<B: Backend, C: Compiler + 'static> SharedService<B, C> {
|
||||
self.compile_stack.store(stack, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Runs jobs in slices that `slicer` starts on the compile stack
|
||||
/// ([`Self::run_job`]), instead of whole.
|
||||
pub fn set_job_slicer(&self, slicer: Slicer) {
|
||||
self.slicer.store(slicer as usize, Ordering::Release);
|
||||
}
|
||||
|
||||
fn slicer(&self) -> Option<Slicer> {
|
||||
match self.slicer.load(Ordering::Acquire) {
|
||||
0 => None,
|
||||
// SAFETY: only `set_job_slicer` stores a nonzero value, a `Slicer`.
|
||||
address => Some(unsafe { core::mem::transmute::<usize, Slicer>(address) }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounds a frontend call's wait for the turn to `ticks`: a call that
|
||||
/// waited so long ran nothing, so it is answered `Pending` and the
|
||||
/// frontend makes it again with its processor back in the guest, which
|
||||
@@ -865,21 +921,27 @@ impl<B: Backend, C: Compiler + 'static> SharedService<B, C> {
|
||||
done
|
||||
}
|
||||
|
||||
/// Runs the oldest deferred job, when one has waited `older_than` ticks
|
||||
/// and no other runs: the platform calls it where long host work is
|
||||
/// allowed, between guest slices and never inside a guest's call, as a
|
||||
/// job runs whole, the compilers having no point to stop at. Whether
|
||||
/// one ran.
|
||||
pub fn run_job(&self, older_than: u64) -> bool {
|
||||
/// Runs deferred jobs a step: the platform calls it where long host
|
||||
/// work is allowed, between guest slices and never inside a guest's
|
||||
/// call. With a [`Slicer`], it resumes the job that ran a slice once
|
||||
/// `resume_after` ticks passed since that slice, else starts the oldest
|
||||
/// job that waited `older_than` ticks, for one slice; without one, it
|
||||
/// runs the oldest job whole. None when it ran nothing.
|
||||
pub fn run_job(&self, older_than: u64, resume_after: u64) -> Option<JobSlice> {
|
||||
let stack = self.compile_stack.load(Ordering::Acquire);
|
||||
if stack == 0 {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
let Some(held) = self.job_lock.lock.try_hold() else {
|
||||
return false;
|
||||
};
|
||||
let now = (self.host.ticks)();
|
||||
let taken = self.jobs.with(|jobs| {
|
||||
match self.slicer() {
|
||||
Some(slicer) => self.run_slice(stack, slicer, older_than, resume_after),
|
||||
None => self.run_whole(stack, older_than),
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the oldest job that waited `older_than` ticks at `now`, and
|
||||
/// marks it running.
|
||||
fn take_job(&self, now: u64, older_than: u64) -> Option<(Job, u64)> {
|
||||
self.jobs.with(|jobs| {
|
||||
let &(_, queued) = jobs.queued.front()?;
|
||||
if now.wrapping_sub(queued) < older_than {
|
||||
return None;
|
||||
@@ -887,10 +949,29 @@ impl<B: Backend, C: Compiler + 'static> SharedService<B, C> {
|
||||
let (job, queued) = jobs.queued.pop_front()?;
|
||||
jobs.running = Some(job.key);
|
||||
Some((job, queued))
|
||||
})
|
||||
}
|
||||
|
||||
/// Publishes what a job made, which ran `ticks` in `slices` steps after
|
||||
/// waiting `waited`: only then may another processor take the next job,
|
||||
/// which the caller's hold of the compile lock keeps from it.
|
||||
fn publish_done(&self, done: Option<Done>, ticks: u64, slices: u64, waited: u64) {
|
||||
self.jobs.with(|jobs| {
|
||||
jobs.running = None;
|
||||
jobs.done.extend(done);
|
||||
let report = &mut jobs.report;
|
||||
report.ran += 1;
|
||||
report.ticks += ticks;
|
||||
report.longest = report.longest.max(ticks);
|
||||
report.slices += slices;
|
||||
report.longest_queued = report.longest_queued.max(waited);
|
||||
});
|
||||
let Some((job, queued)) = taken else {
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
fn run_whole(&self, stack: u64, older_than: u64) -> Option<JobSlice> {
|
||||
let held = self.job_lock.lock.try_hold()?;
|
||||
let now = (self.host.ticks)();
|
||||
let (job, queued) = self.take_job(now, older_than)?;
|
||||
let mut job = Some(job);
|
||||
let mut done = None;
|
||||
(self.host.run)(stack, &mut || {
|
||||
@@ -898,23 +979,98 @@ impl<B: Backend, C: Compiler + 'static> SharedService<B, C> {
|
||||
});
|
||||
let ran = (self.host.ticks)().wrapping_sub(now);
|
||||
self.jobs.with(|jobs| {
|
||||
jobs.running = None;
|
||||
jobs.done.extend(done);
|
||||
let report = &mut jobs.report;
|
||||
report.ran += 1;
|
||||
report.ticks += ran;
|
||||
report.longest = report.longest.max(ran);
|
||||
report.longest_queued = report.longest_queued.max(now.wrapping_sub(queued));
|
||||
jobs.report.longest_slice = jobs.report.longest_slice.max(ran);
|
||||
});
|
||||
// Only now may another processor take the next job: it marks that
|
||||
// job running, which this one's completion must not clear.
|
||||
self.publish_done(done, ran, 1, now.wrapping_sub(queued));
|
||||
drop(held);
|
||||
true
|
||||
Some(JobSlice {
|
||||
started: true,
|
||||
finished: true,
|
||||
ticks: ran,
|
||||
})
|
||||
}
|
||||
|
||||
fn run_slice(
|
||||
&self,
|
||||
stack: u64,
|
||||
slicer: Slicer,
|
||||
older_than: u64,
|
||||
resume_after: u64,
|
||||
) -> Option<JobSlice> {
|
||||
let now = (self.host.ticks)();
|
||||
// One processor at a time takes the job between its slices; while
|
||||
// one does, the job's hold of the compile lock keeps others from
|
||||
// starting another.
|
||||
let (resumed, between) = self.jobs.with(|jobs| match &jobs.active {
|
||||
Some(active) if now.wrapping_sub(active.last) >= resume_after => {
|
||||
(jobs.active.take(), false)
|
||||
}
|
||||
Some(_) => (None, true),
|
||||
None => (None, false),
|
||||
});
|
||||
if between {
|
||||
return None;
|
||||
}
|
||||
let (mut active, started) = match resumed {
|
||||
Some(active) => (active, false),
|
||||
None => {
|
||||
let held = self.job_lock.lock.try_hold_shared()?;
|
||||
let (job, queued) = self.take_job(now, older_than)?;
|
||||
let made = Arc::new(Spin::new(None));
|
||||
let into = made.clone();
|
||||
let sliced = slicer(
|
||||
stack,
|
||||
Box::new(move || {
|
||||
let done = job.run_sliced();
|
||||
into.with(|made| *made = Some(done));
|
||||
}),
|
||||
);
|
||||
let active = Active {
|
||||
sliced,
|
||||
made,
|
||||
_held: held,
|
||||
waited: now.wrapping_sub(queued),
|
||||
last: now,
|
||||
ticks: 0,
|
||||
slices: 0,
|
||||
};
|
||||
(active, true)
|
||||
}
|
||||
};
|
||||
let began = (self.host.ticks)();
|
||||
let finished = active.sliced.resume();
|
||||
let ended = (self.host.ticks)();
|
||||
let ran = ended.wrapping_sub(began);
|
||||
active.ticks += ran;
|
||||
active.slices += 1;
|
||||
active.last = ended;
|
||||
self.jobs.with(|jobs| {
|
||||
jobs.report.longest_slice = jobs.report.longest_slice.max(ran);
|
||||
});
|
||||
if finished {
|
||||
let done = active.made.with(Option::take);
|
||||
self.publish_done(done, active.ticks, active.slices, active.waited);
|
||||
// The compile lock goes with it, after the publication.
|
||||
drop(active);
|
||||
} else {
|
||||
self.jobs.with(|jobs| jobs.active = Some(active));
|
||||
}
|
||||
Some(JobSlice {
|
||||
started,
|
||||
finished,
|
||||
ticks: ran,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a deferred job waits to run.
|
||||
pub fn jobs_waiting(&self) -> bool {
|
||||
self.jobs.with(|jobs| !jobs.queued.is_empty())
|
||||
self.jobs
|
||||
.with(|jobs| !jobs.queued.is_empty() || jobs.active.is_some())
|
||||
}
|
||||
|
||||
/// Whether a job ran a slice and waits to be resumed.
|
||||
pub fn job_between_slices(&self) -> bool {
|
||||
self.jobs.with(|jobs| jobs.active.is_some())
|
||||
}
|
||||
|
||||
/// What jobs did since the last call.
|
||||
@@ -2004,7 +2160,7 @@ mod tests {
|
||||
let shared = SHARED.get().unwrap().clone();
|
||||
let second = std::thread::spawn(move || {
|
||||
assert!(
|
||||
within(LONG, || shared.run_job(0)),
|
||||
within(LONG, || shared.run_job(0, 0).is_some()),
|
||||
"the second job never ran"
|
||||
);
|
||||
});
|
||||
@@ -2039,7 +2195,7 @@ mod tests {
|
||||
0,
|
||||
));
|
||||
});
|
||||
assert!(shared.run_job(0));
|
||||
assert!(shared.run_job(0, 0).is_some());
|
||||
assert!(
|
||||
within(LONG, || SECOND_RUNS.load(Ordering::Acquire)),
|
||||
"the second job never started"
|
||||
|
||||
@@ -196,7 +196,7 @@ fn run_deferred(
|
||||
// A processor whose guest waits runs the job, which blocks.
|
||||
let runner = {
|
||||
let shared = shared.clone();
|
||||
std::thread::spawn(move || shared.run_job(0))
|
||||
std::thread::spawn(move || shared.run_job(0, 0).is_some())
|
||||
};
|
||||
while shared.jobs_waiting() {
|
||||
std::thread::yield_now();
|
||||
@@ -302,7 +302,7 @@ fn a_texture_whose_memory_a_job_makes_holds_no_turn_meanwhile() {
|
||||
assert_eq!(status(&mut memory_a, texture_a), Status::Pending);
|
||||
let runner = {
|
||||
let shared = shared.clone();
|
||||
std::thread::spawn(move || shared.run_job(0))
|
||||
std::thread::spawn(move || shared.run_job(0, 0).is_some())
|
||||
};
|
||||
while shared.jobs_waiting() {
|
||||
std::thread::yield_now();
|
||||
@@ -348,7 +348,7 @@ fn a_job_never_runs_inside_its_callers_call_however_long_it_waits() {
|
||||
assert_eq!(shared.take_job_report().ran, 0);
|
||||
assert!(shared.jobs_waiting());
|
||||
// Host work between guest slices runs it; the call then completes.
|
||||
assert!(shared.run_job(0));
|
||||
assert!(shared.run_job(0, 0).is_some());
|
||||
shared.serve(a, commit, &mut memory).unwrap();
|
||||
assert_eq!(status(&mut memory, commit), Status::Ok);
|
||||
let report = shared.take_job_report();
|
||||
@@ -404,3 +404,102 @@ fn a_deferred_call_whose_record_takes_no_pending_fails_with_the_fault() {
|
||||
assert_eq!(call.status, u32::MAX);
|
||||
assert!(!shared.jobs_waiting());
|
||||
}
|
||||
|
||||
/// A job run in slices on a thread of its own, as a platform runs one on its
|
||||
/// compile stack: [`threaded::pause`] gives the processor back, and the next
|
||||
/// `resume` runs the job on.
|
||||
mod threaded {
|
||||
extern crate std;
|
||||
|
||||
use crate::metal::deferred::Sliced;
|
||||
use alloc::boxed::Box;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
sync::mpsc::{Receiver, Sender, channel},
|
||||
};
|
||||
|
||||
std::thread_local! {
|
||||
static BACK: RefCell<Option<(Receiver<()>, Sender<bool>)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Ends the slice the job runs in.
|
||||
pub(super) fn pause() {
|
||||
BACK.with(|back| {
|
||||
if let Some((go, ended)) = &*back.borrow() {
|
||||
ended.send(false).unwrap();
|
||||
go.recv().unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
struct Threaded {
|
||||
go: Sender<()>,
|
||||
ended: Receiver<bool>,
|
||||
}
|
||||
|
||||
impl Sliced for Threaded {
|
||||
fn resume(&mut self) -> bool {
|
||||
self.go.send(()).unwrap();
|
||||
self.ended.recv().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn start(_stack: u64, body: Box<dyn FnOnce() + Send>) -> Box<dyn Sliced> {
|
||||
let (go, go_job) = channel();
|
||||
let (ended_job, ended) = channel();
|
||||
std::thread::spawn(move || {
|
||||
go_job.recv().unwrap();
|
||||
let finished = ended_job.clone();
|
||||
BACK.with(|back| *back.borrow_mut() = Some((go_job, ended_job)));
|
||||
body();
|
||||
finished.send(true).unwrap();
|
||||
});
|
||||
Box::new(Threaded { go, ended })
|
||||
}
|
||||
}
|
||||
|
||||
/// A long compilation runs as bounded host steps: each `run_job` runs one
|
||||
/// slice and gives the processor back, the call stays a short `Pending`
|
||||
/// answer between slices, no taker that must wait resumes it early, and the
|
||||
/// call completes once the last slice ran, as with a job run whole.
|
||||
#[test]
|
||||
fn a_long_job_runs_in_bounded_slices_and_its_call_completes_as_before() {
|
||||
let mut service = service();
|
||||
let a = connect(&mut service);
|
||||
let (pipeline, buffer) = pipeline(&mut service, a);
|
||||
let compiler = service.device().compiler_mut();
|
||||
compiler.defer_next = true;
|
||||
compiler.job_steps = Some((5, threaded::pause));
|
||||
let shared = SharedService::new(service, host(|_| {}));
|
||||
shared.set_compile_stack(1);
|
||||
shared.set_job_slicer(threaded::start);
|
||||
let mut memory = Memory::default();
|
||||
let commit = dispatching(&mut memory, pipeline, buffer);
|
||||
shared.serve(a, commit, &mut memory).unwrap();
|
||||
assert_eq!(status(&mut memory, commit), Status::Pending);
|
||||
// A wait that only resumes starts nothing.
|
||||
assert_eq!(shared.run_job(u64::MAX, 0), None);
|
||||
let first = shared.run_job(0, 0).expect("the job starts");
|
||||
assert_eq!((first.started, first.finished), (true, false));
|
||||
for _ in 0..4 {
|
||||
assert!(shared.job_between_slices());
|
||||
shared.serve(a, commit, &mut memory).unwrap();
|
||||
assert_eq!(status(&mut memory, commit), Status::Pending);
|
||||
// The boot processor leaves a job another resumes.
|
||||
assert_eq!(shared.run_job(0, u64::MAX), None);
|
||||
let slice = shared.run_job(u64::MAX, 0).expect("a wait resumes it");
|
||||
assert_eq!((slice.started, slice.finished), (false, false));
|
||||
}
|
||||
let last = shared.run_job(0, 0).expect("the job ends");
|
||||
assert_eq!((last.started, last.finished), (false, true));
|
||||
assert!(!shared.jobs_waiting());
|
||||
assert_eq!(shared.run_job(0, 0), None);
|
||||
shared.serve(a, commit, &mut memory).unwrap();
|
||||
assert_eq!(status(&mut memory, commit), Status::Ok);
|
||||
let report = shared.take_job_report();
|
||||
assert_eq!((report.ran, report.slices), (1, 6));
|
||||
assert!(report.longest_slice <= report.longest);
|
||||
let mut turn = shared.try_turn().unwrap();
|
||||
assert_eq!(turn.device().compiler_mut().adopted, 1);
|
||||
assert!(submitted(&mut turn).contains(&Command::Dispatch([4, 1, 1])));
|
||||
}
|
||||
Reference in new issue
Block a user