use crate::sync::atomic::{AtomicU8, AtomicU32, AtomicUsize, Ordering};
use alloc::vec::Vec;
#[allow(unused_imports)]
use core::arch::asm;
use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
pub type TaskIndex = u32;
pub const CHUNK_SIZE: usize = 32;
pub const MAILBOX_CAPACITY: usize = 65_536;
pub const MAILBOX_MASK: usize = MAILBOX_CAPACITY - 1;
pub const LOCAL_QUEUE_CAPACITY: usize = 131_072;
pub const LOCAL_QUEUE_MASK: usize = LOCAL_QUEUE_CAPACITY - 1;
pub const LOCAL_QUEUE_HIGH_WATERMARK: usize = LOCAL_QUEUE_CAPACITY - LOCAL_QUEUE_CAPACITY / 8;
pub const WAREHOUSE_CAPACITY: usize = 32_768;
pub const WAREHOUSE_MASK: usize = WAREHOUSE_CAPACITY - 1;
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct TaskChunk {
pub tasks: [TaskIndex; CHUNK_SIZE],
pub count: u16,
pub hop_count: u8,
_flags: u8,
_pad: [u8; 12],
}
impl Default for TaskChunk {
#[inline(always)]
fn default() -> Self {
Self {
tasks: [0; CHUNK_SIZE],
count: 0,
hop_count: 0,
_flags: 0,
_pad: [0; 12],
}
}
}
#[allow(dead_code)]
pub struct HugeBuffer<T> {
ptr: *mut T,
size_bytes: usize,
is_mmap: bool,
}
unsafe impl<T> Send for HugeBuffer<T> {}
unsafe impl<T> Sync for HugeBuffer<T> {}
impl<T> Default for HugeBuffer<T> {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
impl<T> HugeBuffer<T> {
#[inline(never)]
#[must_use]
#[allow(clippy::useless_let_if_seq)]
pub fn new() -> Self {
let size_bytes = core::mem::size_of::<T>();
#[cfg(unix)]
unsafe {
let base_flags = libc::MAP_PRIVATE | libc::MAP_ANONYMOUS;
let mut ptr = libc::MAP_FAILED;
if size_bytes >= 2 * 1024 * 1024 {
ptr = libc::mmap(
core::ptr::null_mut(),
size_bytes,
libc::PROT_READ | libc::PROT_WRITE,
base_flags | 0x40000, -1,
0,
);
}
if ptr == libc::MAP_FAILED {
ptr = libc::mmap(
core::ptr::null_mut(),
size_bytes,
libc::PROT_READ | libc::PROT_WRITE,
base_flags | libc::MAP_NORESERVE,
-1,
0,
);
}
if ptr != libc::MAP_FAILED {
#[cfg(target_os = "linux")]
{
const MADV_HUGEPAGE: libc::c_int = 14;
libc::madvise(ptr, size_bytes, MADV_HUGEPAGE);
}
return Self {
ptr: ptr.cast::<T>(),
size_bytes,
is_mmap: true,
};
}
let layout = std::alloc::Layout::from_size_align(size_bytes, 64).unwrap();
let alloc_ptr = std::alloc::alloc_zeroed(layout);
assert!(!alloc_ptr.is_null(), "HugeBuffer std::alloc failed");
Self {
ptr: alloc_ptr.cast::<T>(),
size_bytes,
is_mmap: false,
}
}
#[cfg(windows)]
unsafe {
use windows_sys::Win32::System::Memory;
#[cfg(feature = "windows-root")]
{
let mut ptr = Memory::VirtualAlloc(
core::ptr::null_mut(),
size_bytes,
Memory::MEM_RESERVE | Memory::MEM_COMMIT | Memory::MEM_LARGE_PAGES,
Memory::PAGE_READWRITE,
);
if ptr.is_null() {
ptr = Memory::VirtualAlloc(
core::ptr::null_mut(),
size_bytes,
Memory::MEM_RESERVE | Memory::MEM_COMMIT,
Memory::PAGE_READWRITE,
);
assert!(!ptr.is_null(), "HugeBuffer VirtualAlloc failed");
}
Self {
ptr: ptr.cast::<T>(),
size_bytes,
is_mmap: false,
}
}
#[cfg(not(feature = "windows-root"))]
{
let ptr = Memory::VirtualAlloc(
core::ptr::null_mut(),
size_bytes,
Memory::MEM_RESERVE | Memory::MEM_COMMIT,
Memory::PAGE_READWRITE,
);
assert!(!ptr.is_null(), "HugeBuffer VirtualAlloc failed");
Self {
ptr: ptr.cast::<T>(),
size_bytes,
is_mmap: false,
}
}
}
}
}
impl<T> Drop for HugeBuffer<T> {
#[inline(never)]
fn drop(&mut self) {
#[cfg(unix)]
unsafe {
if self.is_mmap {
libc::munmap(self.ptr.cast::<libc::c_void>(), self.size_bytes);
} else {
let layout = std::alloc::Layout::from_size_align(self.size_bytes, 64).unwrap();
std::alloc::dealloc(self.ptr.cast::<u8>(), layout);
}
}
#[cfg(windows)]
unsafe {
windows_sys::Win32::System::Memory::VirtualFree(
self.ptr.cast::<core::ffi::c_void>(),
0,
windows_sys::Win32::System::Memory::MEM_RELEASE,
);
}
}
}
#[repr(C, align(64))]
pub struct Mailbox {
pub head: AtomicUsize,
_pad1: [u8; 64 - core::mem::size_of::<AtomicUsize>()],
pub tail: AtomicUsize,
_pad2: [u8; 64 - core::mem::size_of::<AtomicUsize>()],
pub buffer: HugeBuffer<UnsafeCell<[TaskChunk; MAILBOX_CAPACITY]>>,
}
unsafe impl Sync for Mailbox {}
unsafe impl Send for Mailbox {}
impl Default for Mailbox {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
impl Mailbox {
#[inline(never)]
#[must_use]
pub fn new() -> Self {
Self {
head: AtomicUsize::new(0),
_pad1: [0; 56],
tail: AtomicUsize::new(0),
_pad2: [0; 56],
buffer: HugeBuffer::new(),
}
}
#[inline(always)]
#[allow(clippy::result_large_err)]
pub fn push(&self, chunk: TaskChunk) -> Result<(), TaskChunk> {
let current_tail = self.tail.load(Ordering::Relaxed);
let next_tail = (current_tail + 1) & MAILBOX_MASK;
if next_tail == self.head.load(Ordering::Acquire) {
return Err(chunk);
}
unsafe {
let buffer_ptr = (*self.buffer.ptr).get().cast::<TaskChunk>();
*buffer_ptr.add(current_tail) = chunk;
}
self.tail.store(next_tail, Ordering::Release);
#[cfg(all(
feature = "hw-acceleration",
any(target_arch = "x86", target_arch = "x86_64")
))]
unsafe {
core::arch::asm!("cldemote [{}]", in(reg) &raw const self.tail);
}
#[cfg(all(feature = "hw-acceleration", target_arch = "aarch64"))]
unsafe {
core::arch::asm!("dc cvac, {}", in(reg) &self.tail);
}
#[cfg(all(feature = "hw-acceleration", target_arch = "riscv64"))]
unsafe {
core::arch::asm!("cbo.clean 0({0})", in(reg) &self.tail);
}
Ok(())
}
#[inline(always)]
pub fn pop(&self) -> Option<TaskChunk> {
let current_head = self.head.load(Ordering::Relaxed);
if current_head == self.tail.load(Ordering::Acquire) {
return None;
}
let chunk = unsafe {
let buffer_ptr = (*self.buffer.ptr).get().cast::<TaskChunk>();
core::ptr::read(buffer_ptr.add(current_head))
};
let next_head = (current_head + 1) & MAILBOX_MASK;
self.head.store(next_head, Ordering::Release);
Some(chunk)
}
}
#[repr(C, align(64))]
pub struct WarehouseSlot {
pub seq: AtomicUsize,
pub chunk: UnsafeCell<MaybeUninit<TaskChunk>>,
}
#[repr(C, align(64))]
pub struct Warehouse {
pub backlog: AtomicU32,
_pad0: [u8; 60],
pub tail: AtomicUsize,
_pad1: [u8; 56],
pub head: AtomicUsize,
_pad2: [u8; 56],
pub slots: HugeBuffer<[WarehouseSlot; WAREHOUSE_CAPACITY]>,
}
unsafe impl Sync for Warehouse {}
unsafe impl Send for Warehouse {}
impl Default for Warehouse {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
impl Warehouse {
#[must_use]
#[inline(never)]
pub fn new() -> Self {
let wh = Self {
backlog: AtomicU32::new(0),
_pad0: [0; 60],
tail: AtomicUsize::new(0),
_pad1: [0; 56],
head: AtomicUsize::new(0),
_pad2: [0; 56],
slots: HugeBuffer::new(),
};
unsafe {
let base = wh.slots.ptr.cast::<WarehouseSlot>();
for i in 0..WAREHOUSE_CAPACITY {
(*base.add(i)).seq.store(i, Ordering::Release);
}
}
wh
}
#[inline(always)]
#[allow(clippy::result_large_err)]
pub fn push(&self, chunk: TaskChunk) -> Result<(), TaskChunk> {
let base = self.slots.ptr.cast::<WarehouseSlot>();
let worker_id = crate::future_bridge::CURRENT_WORKER_ID.with(std::cell::Cell::get);
let mut pos = self.tail.load(Ordering::Relaxed);
let mut retry: u32 = 0;
loop {
let slot = unsafe { &*base.add(pos & WAREHOUSE_MASK) };
let seq = slot.seq.load(Ordering::Acquire);
let diff = (seq.cast_signed()).wrapping_sub(pos.cast_signed());
match diff.cmp(&0) {
std::cmp::Ordering::Equal => {
#[cfg(not(loom))]
let cas_result = self.tail.compare_exchange_weak(
pos,
pos + 1,
Ordering::Relaxed,
Ordering::Relaxed,
);
#[cfg(loom)]
let cas_result = self.tail.compare_exchange(
pos,
pos + 1,
Ordering::Relaxed,
Ordering::Relaxed,
);
if cas_result.is_ok() {
unsafe { (*slot.chunk.get()).write(chunk) };
slot.seq.store(pos + 1, Ordering::Release);
self.backlog.fetch_add(1, Ordering::Release);
return Ok(());
}
warehouse_backoff(worker_id, retry);
retry = retry.saturating_add(1);
pos = self.tail.load(Ordering::Relaxed);
}
std::cmp::Ordering::Less => {
return Err(chunk);
}
std::cmp::Ordering::Greater => {
warehouse_backoff(worker_id, retry);
retry = retry.saturating_add(1);
pos = self.tail.load(Ordering::Relaxed);
}
}
}
}
#[inline(always)]
pub fn pop(&self) -> Option<TaskChunk> {
let base = self.slots.ptr.cast::<WarehouseSlot>();
let worker_id = crate::future_bridge::CURRENT_WORKER_ID.with(std::cell::Cell::get);
let mut pos = self.head.load(Ordering::Relaxed);
let mut retry: u32 = 0;
loop {
let slot = unsafe { &*base.add(pos & WAREHOUSE_MASK) };
let seq = slot.seq.load(Ordering::Acquire);
let diff = (seq.cast_signed()).wrapping_sub((pos + 1).cast_signed());
match diff.cmp(&0) {
std::cmp::Ordering::Equal => {
#[cfg(not(loom))]
let cas_result = self.head.compare_exchange_weak(
pos,
pos + 1,
Ordering::Relaxed,
Ordering::Relaxed,
);
#[cfg(loom)]
let cas_result = self.head.compare_exchange(
pos,
pos + 1,
Ordering::Relaxed,
Ordering::Relaxed,
);
if cas_result.is_ok() {
let chunk = unsafe { (*slot.chunk.get()).assume_init_read() };
slot.seq.store(pos + WAREHOUSE_CAPACITY, Ordering::Release);
self.backlog.fetch_sub(1, Ordering::Release);
return Some(chunk);
}
warehouse_backoff(worker_id, retry);
retry = retry.saturating_add(1);
pos = self.head.load(Ordering::Relaxed);
}
std::cmp::Ordering::Less => {
return None;
}
std::cmp::Ordering::Greater => {
warehouse_backoff(worker_id, retry);
retry = retry.saturating_add(1);
pos = self.head.load(Ordering::Relaxed);
}
}
}
}
#[inline(always)]
#[must_use]
pub fn is_busy(&self) -> bool {
self.backlog.load(Ordering::Relaxed) != 0
}
}
#[cold]
#[inline(never)]
fn warehouse_backoff(worker_id: usize, retry: u32) {
let base = (worker_id.wrapping_mul(7) & 0x1F).wrapping_add(1) as u64;
let cycles = base << u64::from(retry.min(6));
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
core::arch::asm!(
"2:",
"nop",
"dec {n}",
"jnz 2b",
n = inout(reg) cycles => _,
options(nostack),
);
}
#[cfg(target_arch = "aarch64")]
unsafe {
core::arch::asm!(
"2:",
"nop",
"subs {n}, {n}, #1",
"b.ne 2b",
n = inout(reg) cycles => _,
options(nostack),
);
}
#[cfg(target_arch = "riscv64")]
unsafe {
core::arch::asm!(
"2:",
"nop",
"addi {n}, {n}, -1",
"bnez {n}, 2b",
n = inout(reg) cycles => _,
options(nostack),
);
}
#[cfg(not(any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
)))]
{
for i in 0_u64..cycles {
core::hint::black_box(i);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CpuLevel {
pub core_id: u16,
pub ccx_id: u16,
pub numa_id: u16,
}
pub use crate::common_types::TopologyMode;
#[repr(C, align(64))]
pub struct Worker {
pub cpu: CpuLevel,
pub load_level: AtomicU8,
pub deflection_threshold: AtomicU8,
pub local_head: AtomicUsize,
pub local_tail: AtomicUsize,
pub ticks: u64,
_pad0: [u8; 32],
pub event_signal: AtomicU32,
_pad1: [u8; 60],
pub local_queue: HugeBuffer<[TaskIndex; LOCAL_QUEUE_CAPACITY]>,
pub polling_order: Vec<usize>,
}
unsafe impl Sync for Worker {}
unsafe impl Send for Worker {}
impl Worker {
#[inline(never)]
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn new(cpu: CpuLevel, total_cores: usize) -> Self {
let mut polling_order = Vec::with_capacity(total_cores - 1);
let my_core = cpu.core_id as usize;
let my_ccx = cpu.ccx_id;
for i in 0..total_cores {
if i != my_core && (i / 8) as u16 == my_ccx {
polling_order.push(i);
}
}
for offset in 0..total_cores {
let i = (my_core + offset) % total_cores;
if i != my_core && (i / 8) as u16 != my_ccx {
polling_order.push(i);
}
}
Self {
cpu,
load_level: AtomicU8::new(0),
deflection_threshold: AtomicU8::new(80),
local_head: AtomicUsize::new(0),
local_tail: AtomicUsize::new(0),
ticks: 0,
_pad0: [0; 32],
event_signal: AtomicU32::new(0),
_pad1: [0; 60],
local_queue: HugeBuffer::new(),
polling_order,
}
}
#[inline(always)]
pub fn local_queue_len(&self) -> usize {
let head = self.local_head.load(Ordering::Relaxed);
let tail = self.local_tail.load(Ordering::Relaxed);
tail.wrapping_sub(head) & LOCAL_QUEUE_MASK
}
#[inline(always)]
pub fn update_load(&self) {
let queue_len = self.local_queue_len();
#[allow(clippy::cast_possible_truncation)]
let load = core::cmp::min((queue_len * 100) >> 13, 100) as u8;
self.load_level.store(load, Ordering::Relaxed);
}
#[inline(always)]
pub fn tick(&mut self) {
self.ticks = self.ticks.wrapping_add(1);
if self.ticks.trailing_zeros() >= 10 {
let load = self.load_level.load(Ordering::Relaxed);
let current_thresh = self.deflection_threshold.load(Ordering::Relaxed);
let new_thresh = if load > 90 {
current_thresh.saturating_sub(5).max(40)
} else if load < 30 {
current_thresh.saturating_add(5).min(95)
} else {
current_thresh
};
self.deflection_threshold
.store(new_thresh, Ordering::Relaxed);
}
}
#[inline(always)]
pub fn push_local(&self, task: TaskIndex) -> bool {
let tail = self.local_tail.load(Ordering::Relaxed);
if self.local_queue_len() >= LOCAL_QUEUE_CAPACITY - 1 {
return false;
}
unsafe {
let buffer_ptr = self.local_queue.ptr.cast::<TaskIndex>();
*buffer_ptr.add(tail) = task;
}
self.local_tail
.store((tail + 1) & LOCAL_QUEUE_MASK, Ordering::Relaxed);
true
}
#[inline]
pub fn push_batch(&mut self, chunk: &TaskChunk) {
let count = chunk.count as usize;
let tail = self.local_tail.load(Ordering::Relaxed);
let end_idx = tail.wrapping_add(count);
if end_idx <= LOCAL_QUEUE_CAPACITY {
unsafe {
core::ptr::copy_nonoverlapping(
chunk.tasks.as_ptr(),
(*self.local_queue.ptr).as_mut_ptr().add(tail),
count,
);
}
} else {
let first_part = LOCAL_QUEUE_CAPACITY - tail;
let second_part = count - first_part;
unsafe {
core::ptr::copy_nonoverlapping(
chunk.tasks.as_ptr(),
(*self.local_queue.ptr).as_mut_ptr().add(tail),
first_part,
);
core::ptr::copy_nonoverlapping(
chunk.tasks.as_ptr().add(first_part),
(*self.local_queue.ptr).as_mut_ptr(),
second_part,
);
}
}
self.local_tail
.store(end_idx & LOCAL_QUEUE_MASK, Ordering::Relaxed);
}
#[inline(always)]
pub unsafe fn dispatch_loop(&self, pool: &crate::memory_management::ContextPool) -> bool {
let mut head = self.local_head.load(Ordering::Relaxed);
if head == self.local_tail.load(Ordering::Relaxed) {
return false;
}
loop {
if head == self.local_tail.load(Ordering::Relaxed) {
break;
}
let task = unsafe {
let buffer_ptr = self.local_queue.ptr.cast::<TaskIndex>();
*buffer_ptr.add(head)
};
head = (head + 1) & LOCAL_QUEUE_MASK;
self.local_head.store(head, Ordering::Relaxed);
let target_ptr = pool.get_context_ptr(task);
#[cfg(target_arch = "x86_64")]
unsafe {
core::arch::x86_64::_mm_prefetch::<0>(target_ptr as *const i8);
}
#[cfg(target_arch = "aarch64")]
unsafe {
core::arch::asm!("prfm pldl1keep, [{0}]", in(reg) target_ptr, options(nostack, preserves_flags));
}
#[cfg(all(target_arch = "riscv64", feature = "hw-acceleration"))]
unsafe {
core::arch::asm!("prefetch.r 0({0})", in(reg) target_ptr, options(nostack, preserves_flags));
}
crate::future_bridge::CURRENT_FIBER.with(|c| c.set(target_ptr));
unsafe {
((*target_ptr).switch_fn)(
&raw mut (*target_ptr).executor_regs,
&raw const (*target_ptr).regs,
);
}
crate::future_bridge::CURRENT_FIBER.with(|c| c.set(core::ptr::null_mut()));
let post_state = unsafe { (*target_ptr).state.load(Ordering::Acquire) };
let mut final_state = post_state;
if post_state == crate::memory_management::FiberStatus::Suspending as u32 {
match unsafe {
(*target_ptr).state.compare_exchange(
crate::memory_management::FiberStatus::Suspending as u32,
crate::memory_management::FiberStatus::Yielded as u32,
Ordering::Release,
Ordering::Acquire,
)
} {
Ok(_) => final_state = crate::memory_management::FiberStatus::Yielded as u32,
Err(actual) => final_state = actual,
}
}
if final_state == crate::memory_management::FiberStatus::Finished as u32
|| final_state == crate::memory_management::FiberStatus::Panicked as u32
{
pool.free_context(task);
} else if final_state == crate::memory_management::FiberStatus::Notified as u32 {
let pushed = self.push_local(task);
debug_assert!(
pushed,
"DTA-V3 invariant: Notified re-enqueue must succeed (we just freed a slot by popping)"
);
return true;
}
}
true
}
}
pub struct DtaScheduler {
pub workers: Vec<UnsafeCell<Worker>>,
pub mailboxes: Vec<Vec<Mailbox>>,
pub external_mailboxes: Vec<Mailbox>,
pub external_locks: Vec<crate::utils::SpinLock>,
pub topology: TopologyMode,
pub max_hops: u8,
pub warehouse: Warehouse,
}
unsafe impl Sync for DtaScheduler {}
unsafe impl Send for DtaScheduler {}
impl DtaScheduler {
#[inline(never)]
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn new(num_workers: usize, topology: TopologyMode) -> Self {
let mut workers = Vec::with_capacity(num_workers);
let mut mailboxes = Vec::with_capacity(num_workers);
let mut external_mailboxes = Vec::with_capacity(num_workers);
let mut external_locks = Vec::with_capacity(num_workers);
for i in 0..num_workers {
workers.push(UnsafeCell::new(Worker::new(
CpuLevel {
core_id: i as u16,
ccx_id: (i / 8) as u16,
numa_id: (i / 64) as u16,
},
num_workers,
)));
let mut row = Vec::with_capacity(num_workers);
for _ in 0..num_workers {
row.push(Mailbox::new());
}
mailboxes.push(row);
external_mailboxes.push(Mailbox::new());
external_locks.push(crate::utils::SpinLock::new());
}
let max_hops = core::cmp::min(num_workers / 2, u8::MAX as usize) as u8;
Self {
workers,
mailboxes,
external_mailboxes,
external_locks,
topology,
max_hops,
warehouse: Warehouse::new(),
}
}
#[inline(always)]
pub(crate) fn signal_worker(&self, target_core: usize) {
let worker = unsafe { &*self.workers[target_core].get() };
worker.event_signal.fetch_add(1, Ordering::Release);
#[cfg(all(
feature = "hw-acceleration",
any(target_arch = "x86", target_arch = "x86_64")
))]
unsafe {
core::arch::asm!(
"mov rax, {}",
".byte 0xf3, 0x0f, 0xc7, 0xf0",
in(reg) target_core as u64,
out("rax") _,
options(nostack, preserves_flags),
);
}
#[cfg(all(feature = "hw-acceleration", target_arch = "aarch64"))]
unsafe {
core::arch::asm!("sev", options(nostack, preserves_flags));
}
#[cfg(all(feature = "hw-acceleration", target_arch = "riscv64"))]
unsafe {
core::arch::asm!("csrw uipi, {0}", in(reg) target_core);
}
}
#[inline(always)]
pub fn enqueue_pinned(&self, target_core: usize, task: TaskIndex) -> bool {
let n = self.workers.len();
let target = target_core % n;
let current = crate::future_bridge::CURRENT_WORKER_ID.with(std::cell::Cell::get);
if current == target {
let worker = unsafe { &*self.workers[target].get() };
return worker.push_local(task);
}
let mut chunk = TaskChunk::default();
chunk.tasks[0] = task;
chunk.count = 1;
let ok = if current < n {
self.mailboxes[current][target].push(chunk).is_ok()
} else {
self.external_locks[target].lock();
let r = self.external_mailboxes[target].push(chunk).is_ok();
self.external_locks[target].unlock();
r
};
if ok {
self.signal_worker(target);
}
ok
}
#[inline(always)]
pub fn enqueue_deflect(
&self,
source_core: usize,
flow_id: u64,
task: TaskIndex,
affinity: crate::api::topology::Affinity,
) -> bool {
if self.warehouse.is_busy() {
return self.divert_to_warehouse(task);
}
let n = self.workers.len();
let source = source_core % n;
let worker_ref = unsafe { &*self.workers[source].get() };
let threshold = worker_ref.deflection_threshold.load(Ordering::Relaxed);
let load = worker_ref.load_level.load(Ordering::Relaxed);
let deflect_mask = if load > threshold { usize::MAX } else { 0 };
#[allow(clippy::cast_possible_truncation)]
let h1 = (flow_id & 7) as usize;
#[allow(clippy::cast_possible_truncation)]
let h2 = ((flow_id >> 3) & 7 | 1) as usize;
let target = if self.topology == TopologyMode::Global
&& matches!(affinity, crate::api::topology::Affinity::Any)
{
(source + h1 + h2) % n
} else if matches!(affinity, crate::api::topology::Affinity::SameNUMA) {
let numa_base = source & !63;
let local_idx = source & 63;
let deflect_target = (local_idx + h1 + h2) % 64;
let target_idx = local_idx ^ ((local_idx ^ deflect_target) & deflect_mask);
(numa_base | target_idx) % n
} else {
let ccx_base = source & !7;
let local_idx = source & 7;
let deflect_target = (local_idx + h1 + h2) & 7;
let target_idx = local_idx ^ ((local_idx ^ deflect_target) & deflect_mask);
(ccx_base | target_idx) % n
};
let current = crate::future_bridge::CURRENT_WORKER_ID.with(std::cell::Cell::get);
if current == target {
let worker = unsafe { &*self.workers[target].get() };
if worker.push_local(task) {
return true;
}
}
let mut chunk = TaskChunk::default();
chunk.tasks[0] = task;
chunk.count = 1;
self.push_chunk_with_hop(current, target, &mut chunk)
}
fn push_chunk_with_hop(
&self,
producer: usize,
initial_target: usize,
chunk: &mut TaskChunk,
) -> bool {
let n = self.workers.len();
let mut target = initial_target;
if producer < n && n > 1 && target == producer {
target = (target + 1) % n;
}
loop {
let result = if producer < n {
self.mailboxes[producer][target].push(*chunk)
} else {
self.external_locks[target].lock();
let r = self.external_mailboxes[target].push(*chunk);
self.external_locks[target].unlock();
r
};
match result {
Ok(()) => {
self.signal_worker(target);
return true;
}
Err(c) => {
*chunk = c;
if chunk.hop_count >= self.max_hops {
return self.park_in_warehouse(*chunk);
}
chunk.hop_count = chunk.hop_count.saturating_add(1);
target = (producer.wrapping_add(1 + chunk.hop_count as usize * 7)) % n;
if producer < n && n > 1 && target == producer {
target = (target + 1) % n;
}
}
}
}
}
#[cold]
#[inline(never)]
fn divert_to_warehouse(&self, task: TaskIndex) -> bool {
let mut chunk = TaskChunk::default();
chunk.tasks[0] = task;
chunk.count = 1;
chunk.hop_count = u8::MAX;
self.park_in_warehouse(chunk)
}
#[cold]
#[inline(never)]
fn park_in_warehouse(&self, chunk: TaskChunk) -> bool {
assert!(
self.warehouse.push(chunk).is_ok(),
"DTA-V3: warehouse overflow — backlog exceeds {} chunks ({} tasks). \
Application has scheduled tasks faster than the runtime can drain, \
beyond emergency back-pressure capacity.",
WAREHOUSE_CAPACITY,
WAREHOUSE_CAPACITY * CHUNK_SIZE
);
true
}
#[cold]
#[inline(never)]
pub fn drain_warehouse(&self, current_core: usize) -> bool {
let worker = unsafe { &mut *self.workers[current_core].get() };
let cap = 64usize;
let mut drained = 0usize;
while drained < cap {
if worker.local_queue_len() + CHUNK_SIZE > LOCAL_QUEUE_HIGH_WATERMARK {
break;
}
match self.warehouse.pop() {
Some(chunk) => {
worker.push_batch(&chunk);
drained += 1;
}
None => break,
}
}
drained > 0
}
#[inline(always)]
pub fn poll_mailboxes(&self, current_core: usize) -> bool {
let worker = unsafe { &mut *self.workers[current_core].get() };
let fixed_head = worker.local_head.load(Ordering::Relaxed);
let mut received_any = false;
let num_polls = worker.polling_order.len();
for idx in 0..num_polls {
let i = worker.polling_order[idx];
let row = &self.mailboxes[i];
loop {
let cur_len = worker
.local_tail
.load(Ordering::Relaxed)
.wrapping_sub(fixed_head)
& LOCAL_QUEUE_MASK;
if cur_len + CHUNK_SIZE >= LOCAL_QUEUE_CAPACITY {
break;
}
match row[current_core].pop() {
Some(chunk) => {
received_any = true;
self.route_chunk(worker, current_core, chunk);
}
None => break,
}
}
}
loop {
let cur_len = worker
.local_tail
.load(Ordering::Relaxed)
.wrapping_sub(fixed_head)
& LOCAL_QUEUE_MASK;
if cur_len + CHUNK_SIZE >= LOCAL_QUEUE_CAPACITY {
break;
}
match self.external_mailboxes[current_core].pop() {
Some(chunk) => {
received_any = true;
self.route_chunk(worker, current_core, chunk);
}
None => break,
}
}
worker.update_load();
worker.tick();
received_any
}
#[inline(always)]
#[allow(clippy::items_after_statements)]
fn route_chunk(&self, worker: &mut Worker, current_core: usize, chunk: TaskChunk) {
let local_len = worker.local_queue_len();
let space_ok = (local_len + chunk.count as usize) <= LOCAL_QUEUE_HIGH_WATERMARK;
let hops_ok = chunk.hop_count < self.max_hops;
let idx = usize::from(space_ok) | (usize::from(hops_ok) << 1);
type RouteFn = fn(&DtaScheduler, &mut Worker, usize, TaskChunk);
const ROUTES: [RouteFn; 4] = [
DtaScheduler::route_park, DtaScheduler::route_local, DtaScheduler::route_deflect, DtaScheduler::route_local, ];
ROUTES[idx](self, worker, current_core, chunk);
}
#[inline(always)]
#[allow(clippy::unused_self)]
fn route_local(&self, worker: &mut Worker, _core: usize, chunk: TaskChunk) {
worker.push_batch(&chunk);
}
#[inline(always)]
fn route_park(&self, _worker: &mut Worker, _core: usize, chunk: TaskChunk) {
let _ = self.park_in_warehouse(chunk);
}
#[inline(always)]
fn route_deflect(&self, _worker: &mut Worker, current_core: usize, mut chunk: TaskChunk) {
chunk.hop_count = chunk.hop_count.saturating_add(1);
let n = self.workers.len();
let mut target = (current_core.wrapping_add(1 + chunk.hop_count as usize * 7)) % n;
if n > 1 && target == current_core {
target = (target + 1) % n;
}
match self.mailboxes[current_core][target].push(chunk) {
Ok(()) => self.signal_worker(target),
Err(c) => {
let _ = self.park_in_warehouse(c);
}
}
}
#[inline]
#[allow(clippy::too_many_lines)]
pub fn run_worker_static(
scheduler: &Self,
current_core: usize,
pool: &crate::memory_management::ContextPool,
shutdown: &crate::sync::atomic::AtomicBool,
) {
crate::future_bridge::CURRENT_WORKER_ID.with(|c| c.set(current_core));
let mut idle_count: u32 = 0;
loop {
if shutdown.load(Ordering::Acquire) {
return;
}
let warehouse_busy = scheduler.warehouse.is_busy();
let mut activity = if warehouse_busy {
scheduler.drain_warehouse(current_core)
} else {
false
};
unsafe {
let worker = &*scheduler.workers[current_core].get();
activity |= worker.dispatch_loop(pool);
}
if !warehouse_busy {
activity |= scheduler.poll_mailboxes(current_core);
}
if activity {
idle_count = 0;
continue;
}
idle_count = idle_count.saturating_add(1);
if idle_count < 256 {
core::hint::spin_loop();
continue;
}
if idle_count < 2048 {
#[cfg(target_arch = "aarch64")]
unsafe {
core::arch::asm!("yield", options(nostack, preserves_flags));
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
core::hint::spin_loop();
#[cfg(all(feature = "hw-acceleration", target_arch = "riscv64"))]
unsafe {
core::arch::asm!("pause", options(nostack, preserves_flags));
}
#[cfg(not(any(
target_arch = "aarch64",
target_arch = "x86",
target_arch = "x86_64",
all(feature = "hw-acceleration", target_arch = "riscv64")
)))]
for _ in 0..8 {
core::hint::spin_loop();
}
continue;
}
unsafe {
#[cfg(all(feature = "hw-acceleration", target_arch = "aarch64"))]
core::arch::asm!("wfe", options(nostack, preserves_flags));
#[cfg(all(feature = "hw-acceleration", target_arch = "riscv64"))]
core::arch::asm!("pause", options(nostack, preserves_flags));
#[cfg(all(
feature = "hw-acceleration",
any(target_arch = "x86_64", target_arch = "x86")
))]
{
let worker = &*scheduler.workers[current_core].get();
let signal_before = worker.event_signal.load(Ordering::Acquire);
let sig_ptr = &raw const worker.event_signal as *mut core::ffi::c_void;
let control = 1u32;
let timeout_low = 2_000_000u32;
let timeout_high = 0u32;
core::arch::asm!(
"umonitor {0}",
"cmp {1:e}, {2:e}",
"jne 2f",
"umwait {3:e}",
"2:",
in(reg) sig_ptr,
in(reg) signal_before,
in(reg) worker.event_signal.load(Ordering::Relaxed),
in(reg) control,
inout("eax") timeout_low => _,
inout("edx") timeout_high => _,
options(nostack, preserves_flags)
);
}
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
crate::sync::atomic::fence(Ordering::Acquire);
#[cfg(all(not(feature = "hw-acceleration"), feature = "cooperative-yield"))]
std::thread::yield_now();
#[cfg(all(not(feature = "hw-acceleration"), not(feature = "cooperative-yield")))]
for _ in 0..16 {
core::hint::spin_loop();
}
}
scheduler.poll_mailboxes(current_core);
}
}
}