perf(rmapi/uvm/pcie): batch sysmem pool reuse & UVM DMA drain, roll back PCIe target on retrain failure (#516)

* fix(pcie): restore link target after retrain register failures

Reuse the existing best-effort timeout rollback for every failure after the endpoint target write succeeds, preserving the original error. Fault injection exposes three failing tests on master; all eight targeted tests, workspace tests, clippy and offline codegen checks pass with the correction. No changes to link policy, capability gates or success path.

* perf(uvm): batch DMA mapping cleanup at node exit

Drain up to 16 live records per leaf-mutex acquisition, preserving bucket order and leaving DMA unmap/page/device releases outside the lock. No changes to insert/lookup/device detach, per-page unmap or mapping permissions. Seven paired CPU-only samples from 1 to 262144 records show 1.30x to 20.85x faster ledger cleanup. Workspace 1409 passed, 150 ignored; clippy, formatting, native codegen and Rust kernel object build pass. Full kernel module and physical/guest testing pending.

* perf(rmapi): batch hot system-page pool reuse

Take up to 32 hot pages per pool mutex acquisition, publish the count once, and clear all reused pages outside the mutex. Preserve LIFO order, partial/empty fallback, admission and cache policy, and allocation failure cleanup. Seven paired host benchmarks show up to 4.72x faster bookkeeping and 4.92x p99 improvement for 16384 fully pooled pages, with single-page and empty-pool parity. 1409 workspace tests pass, 150 ignored; strict clippy, codegen audit, Rust kernel object and offline kernel gates pass. Full C module/guest/physical validation pending.

---------

Co-authored-by: Nick <your-email@example.com>
This commit is contained in:
ThingsCouldGetDicey
2026-12-05 22:19:17 +00:00
committed by GitHub
parent c777e5cc67
commit 3e1bf7b8c8
8 changed files with 533 additions and 50 deletions

View File

@ -797,7 +797,7 @@ MODULE_PARM_DESC(strict_version_check,
#endif
extern bool nv_rs_sysmem_pool_push(void *page);
extern void *nv_rs_sysmem_pool_pop(void);
extern u32 nv_rs_sysmem_pool_pop_batch(struct page **out, u32 limit);
extern void *nv_rs_sysmem_pool_pop_for_trim(u64 retain_pages);
extern u64 nv_rs_sysmem_pool_len(void);
extern void nv_rs_sysmem_pool_release_storage(void);
@ -1727,16 +1727,16 @@ static inline void nv_rs_proc_init(void) {}
static inline void nv_rs_proc_exit(void) {}
#endif
static struct page *nv_rs_sysmem_pool_pop_page(void)
static u32 nv_rs_sysmem_pool_pop_pages(struct page **pages, u32 limit)
{
struct page *page;
u32 count, i;
mutex_lock(&nv_rs_sysmem_pool_lock);
page = (struct page *)nv_rs_sysmem_pool_pop();
count = nv_rs_sysmem_pool_pop_batch(pages, limit);
mutex_unlock(&nv_rs_sysmem_pool_lock);
if (page)
clear_highpage(page);
return page;
for (i = 0; i < count; i++)
clear_highpage(pages[i]);
return count;
}
static void nv_rs_sysmem_pool_push_page(struct page *page)
@ -2532,16 +2532,23 @@ u32 nv_rs_rmapi_os_alloc_pages(u64 count, u64 page, bool contiguous, u32 cache,
for (; index < total_order_pages; index++)
__free_page(head + index);
} else {
for (index = 0; index < count; index++) {
alloc->pages[index] = nv_rs_sysmem_pool_pop_page();
if (!alloc->pages[index])
alloc->pages[index] = alloc_page(GFP_KERNEL | __GFP_ZERO);
for (index = 0; index < count;) {
u32 limit = min_t(u64, count - index, 32);
u32 pooled = nv_rs_sysmem_pool_pop_pages(&alloc->pages[index], limit);
index += pooled;
if (pooled == limit)
continue;
/* The pool was exhausted at this acquisition. Allocate one fresh
* zeroed page, then retry the pool (it may refill concurrently). */
alloc->pages[index] = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!alloc->pages[index]) {
while (index--)
__free_page(alloc->pages[index]);
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
index++;
}
}
alloc->count = count;

View File

@ -174,7 +174,7 @@ extern int nv_rs_uvm_dma_insert(void *cpu_ptr, struct page *page, u32 gpu_id,
extern bool nv_rs_uvm_dma_pop_cpu(void *cpu_ptr, struct nv_rs_uvm_cpu_dma_record *out);
extern u32 nv_rs_uvm_dma_detach_dev(struct device *dev);
extern bool nv_rs_uvm_dma_pop_detached(u32 *head, struct nv_rs_uvm_cpu_dma_record *out);
extern bool nv_rs_uvm_dma_pop_any(struct nv_rs_uvm_cpu_dma_record *out);
extern u32 nv_rs_uvm_dma_pop_batch(struct nv_rs_uvm_cpu_dma_record *out, u32 capacity);
extern void nv_rs_uvm_dma_release_storage(void);
/* Leaf mutex serializing Rust's `UvmCpuDmaLedger` (never acquires uvm or rmapi locks). */
@ -707,19 +707,22 @@ int nv_rs_uvm_node_init(void)
static void nv_rs_uvm_drain_cpu_dma_ht(void)
{
struct nv_rs_uvm_cpu_dma_record rec;
struct nv_rs_uvm_cpu_dma_record records[16] = {};
for (;;) {
bool found;
u32 count, i;
mutex_lock(&nv_rs_uvm_cpu_dma_lock);
found = nv_rs_uvm_dma_pop_any(&rec);
count = nv_rs_uvm_dma_pop_batch(records, ARRAY_SIZE(records));
mutex_unlock(&nv_rs_uvm_cpu_dma_lock);
if (!found)
if (!count)
break;
dma_unmap_page(rec.dev, (dma_addr_t)rec.dma, PAGE_SIZE, DMA_BIDIRECTIONAL);
put_page(rec.page);
put_device(rec.dev);
for (i = 0; i < count; i++) {
dma_unmap_page(records[i].dev, (dma_addr_t)records[i].dma,
PAGE_SIZE, DMA_BIDIRECTIONAL);
put_page(records[i].page);
put_device(records[i].dev);
}
}
mutex_lock(&nv_rs_uvm_cpu_dma_lock);
nv_rs_uvm_dma_release_storage();

File diff suppressed because one or more lines are too long

View File

@ -974,14 +974,26 @@ pub unsafe extern "C" fn nv_rs_sysmem_pool_push(page: *mut c_void) -> bool {
}
}
/// Pops the hottest (most recently pooled) `struct page *`, or NULL if empty.
/// Transfers up to 32 hottest pages into caller-owned output storage.
/// The C caller holds the pool mutex and clears every returned page outside it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_sysmem_pool_pop() -> *mut c_void {
pub unsafe extern "C" fn nv_rs_sysmem_pool_pop_batch(
out: *mut *mut c_void,
limit: u32,
) -> u32 {
if out.is_null() || limit == 0 || limit > 32 {
return 0;
}
let pool = unsafe { &mut *ptr::addr_of_mut!(SYSMEM_POOL) };
let slots = unsafe { &mut *ptr::addr_of_mut!(SYSMEM_POOL_SLOTS) };
let page = pool.pop_hot(slots.as_mut_slice()).unwrap_or(0);
let mut written = 0;
let count = pool.pop_hot_batch(slots.as_mut_slice(), limit as usize, |page| {
// SAFETY: caller supplies limit writable page-pointer slots.
unsafe { out.add(written).write(page as *mut c_void) };
written += 1;
});
SYSMEM_POOL_LEN.store(pool.len() as u64, Ordering::Release);
page as *mut c_void
count as u32
}
/// Evicts one coldest `struct page *` while pooled count exceeds `retain_pages`, or NULL.
@ -1250,19 +1262,21 @@ pub unsafe extern "C" fn nv_rs_uvm_dma_pop_detached(
}
}
/// Drain a bounded batch of initialized output records under the existing
/// UVM DMA mutex. No allocation or DMA unmapping occurs in this function.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_uvm_dma_pop_any(out: *mut UvmCpuDmaRecord) -> bool {
pub unsafe extern "C" fn nv_rs_uvm_dma_pop_batch(
out: *mut UvmCpuDmaRecord,
capacity: u32,
) -> u32 {
if out.is_null() || capacity == 0 || capacity > 16 {
return 0;
}
let ledger = unsafe { &mut *ptr::addr_of_mut!(UVM_CPU_DMA_LEDGER) };
let slots = unsafe { &mut *ptr::addr_of_mut!(UVM_CPU_DMA_SLOTS) };
match ledger.pop_any(slots.as_mut_slice()) {
Some(rec) => {
if !out.is_null() {
unsafe { *out = rec };
}
true
}
None => false,
}
// SAFETY: the C caller supplies capacity initialized, exclusive records.
let out = unsafe { core::slice::from_raw_parts_mut(out, capacity as usize) };
ledger.pop_batch(slots.as_mut_slice(), out) as u32
}
#[unsafe(no_mangle)]

View File

@ -215,7 +215,7 @@ impl PcieBifState {
/// Forces a target PCIe generation (`#168`: mining card Gen1->Gen2 / legacy host Gen3),
/// clamping to `min(self.max_speed, upstream_max)`, polling `LINK_STATUS_TRAINING_BIT` to
/// completion, and rolling back to the original target speed if training times out.
/// completion, and attempting to restore the original target on subsequent failure.
pub fn force_link_speed_with_retrain(
&self,
io: &mut impl RegisterIo,
@ -233,24 +233,26 @@ impl PcieBifState {
NV_XVE_LINK_CONTROL_STATUS_2,
(orig_lcs2 & !0xf) | (effective as u32),
)?;
let cur1 = io.read32(NV_XVE_LINK_CONTROL_STATUS)?;
io.write32(NV_XVE_LINK_CONTROL_STATUS, cur1 | LINK_CTRL_RETRAIN_BIT)?;
let mut trained = false;
for _ in 0..200 {
let st = io.read32(NV_XVE_LINK_CONTROL_STATUS)?;
if (st & LINK_STATUS_TRAINING_BIT) == 0 {
trained = true;
break;
let result = (|| {
let cur1 = io.read32(NV_XVE_LINK_CONTROL_STATUS)?;
io.write32(NV_XVE_LINK_CONTROL_STATUS, cur1 | LINK_CTRL_RETRAIN_BIT)?;
for _ in 0..200 {
let st = io.read32(NV_XVE_LINK_CONTROL_STATUS)?;
if (st & LINK_STATUS_TRAINING_BIT) == 0 {
let after = self.read_link_status(io)?.speed;
return Ok((before, after));
}
delay_us(500);
}
delay_us(500);
}
if !trained {
// Roll back target link speed on training timeout.
Err(NvStatus(0x65)) // NV_ERR_TIMEOUT
})();
if result.is_err() {
// Once the target write succeeds, restore the original target on
// any subsequent error, not just a timeout. Preserve the original
// failure even if the best-effort restoration also fails.
let _ = io.write32(NV_XVE_LINK_CONTROL_STATUS_2, orig_lcs2);
return Err(NvStatus(0x65)); // NV_ERR_TIMEOUT
}
let after = self.read_link_status(io)?.speed;
Ok((before, after))
result
}
/// Configures PCIe ASPM mode while respecting `RMDisableGpuASPMFlags` and `RMAspmL1War3729821`.
@ -307,6 +309,127 @@ mod tests {
}
}
struct FaultBifRegs {
inner: MockBifRegs,
fail_at: usize,
calls: usize,
rollback_writes: usize,
fail_rollback: bool,
}
impl FaultBifRegs {
fn new(fail_at: usize) -> Self {
Self {
inner: MockBifRegs {
lcs: (16 << 20) | (1 << 16),
lcs2: 0xa1,
},
fail_at,
calls: 0,
rollback_writes: 0,
fail_rollback: false,
}
}
fn check(&mut self) -> Result<(), NvStatus> {
self.calls += 1;
if self.calls == self.fail_at {
Err(NvStatus(0x56))
} else {
Ok(())
}
}
}
impl RegisterIo for FaultBifRegs {
fn read32(&mut self, offset: u32) -> Result<u32, NvStatus> {
self.check()?;
self.inner.read32(offset)
}
fn write32(&mut self, offset: u32, value: u32) -> Result<(), NvStatus> {
self.check()?;
if offset == NV_XVE_LINK_CONTROL_STATUS_2 && value == 0xa1 {
self.rollback_writes += 1;
if self.fail_rollback {
return Err(NvStatus(0x1f));
}
}
self.inner.write32(offset, value)
}
}
#[test]
fn retrain_restores_endpoint_target_after_register_errors() {
let bif = PcieBifState::new(PcieSpeed::Gen3);
// LCS read, retrain write, first poll read, final status read.
for fail_at in 4..=7 {
let mut regs = FaultBifRegs::new(fail_at);
assert_eq!(
bif.force_link_speed_with_retrain(
&mut regs,
PcieSpeed::Gen3,
PcieSpeed::Gen3,
|_| {},
),
Err(NvStatus(0x56)),
);
assert_eq!(regs.inner.lcs2, 0xa1, "failure at operation {fail_at}");
assert_eq!(regs.rollback_writes, 1);
}
}
#[test]
fn retrain_preserves_original_error_if_rollback_also_fails() {
let bif = PcieBifState::new(PcieSpeed::Gen3);
let mut regs = FaultBifRegs::new(6);
regs.fail_rollback = true;
assert_eq!(
bif.force_link_speed_with_retrain(&mut regs, PcieSpeed::Gen3, PcieSpeed::Gen3, |_| {},),
Err(NvStatus(0x56)),
);
assert_eq!(regs.rollback_writes, 1);
}
#[test]
fn retrain_does_not_rollback_before_target_write_succeeds() {
let bif = PcieBifState::new(PcieSpeed::Gen3);
for fail_at in 1..=3 {
let mut regs = FaultBifRegs::new(fail_at);
assert_eq!(
bif.force_link_speed_with_retrain(
&mut regs,
PcieSpeed::Gen3,
PcieSpeed::Gen3,
|_| {},
),
Err(NvStatus(0x56)),
);
assert_eq!(regs.inner.lcs2, 0xa1);
assert_eq!(regs.rollback_writes, 0);
}
}
#[test]
fn retrain_register_failure_restores_endpoint_and_bridge_targets() {
let mut regs = FaultBifRegs::new(7);
let mut bridge_tls = 1u32;
let res = apply_pcie_gen_override_with_upstream(
3,
PcieSpeed::Gen3,
3,
|| 1,
|v| {
bridge_tls = v;
0
},
&mut regs,
|_| {},
);
assert_eq!(res, None);
assert_eq!(bridge_tls, 1);
assert_eq!(regs.inner.lcs2, 0xa1);
assert_eq!(regs.rollback_writes, 1);
}
#[test]
fn bif_reads_gen3_x16_switches_speed_and_applies_aspm_war() {
let mut regs = MockBifRegs {

View File

@ -584,6 +584,44 @@ mod tests {
assert!(ledger.is_live_gen(0, gen_reused));
}
#[test]
fn sysmem_batch_matches_single_pop_across_wrap_and_partial_batches() {
// Non-power-of-two capacity exercises both wrap directions.
let mut a = SysmemPagePool::new();
let mut b = SysmemPagePool::new();
let mut sa = [0usize; 7];
let mut sb = [0usize; 7];
for page in 1..=7 {
assert_eq!(a.push(&mut sa, page), b.push(&mut sb, page));
}
for _ in 0..3 {
assert_eq!(
a.pop_cold_for_trim(&mut sa, 0),
b.pop_cold_for_trim(&mut sb, 0)
);
}
for page in 8..=10 {
assert_eq!(a.push(&mut sa, page), b.push(&mut sb, page));
}
assert_eq!(b.pop_hot_batch(&mut sb, 0, |_| panic!("empty batch")), 0);
for limit in [1usize, 3, 32, 1] {
let mut taken = 0;
let count = b.pop_hot_batch(&mut sb, limit, |page| {
assert_eq!(a.pop_hot(&mut sa), Some(page));
taken += 1;
});
assert_eq!(count, taken);
assert_eq!(a.len(), b.len());
assert_eq!(sa, sb);
}
assert_eq!(a.len(), 0);
assert_eq!(a, b);
assert_eq!(b.push(&mut sb, 11), Ok(()));
assert_eq!(b.pop_hot_batch(&mut sb, 32, |page| assert_eq!(page, 11)), 1);
assert_eq!(b.len(), 0);
assert_eq!(b.pop_hot_batch(&mut [], 32, |_| panic!("empty pool")), 0);
}
#[test]
fn sysmem_page_pool_preserves_lifo_hot_pop_fifo_cold_trim_and_repack() {
let mut pool = SysmemPagePool::new();
@ -632,6 +670,76 @@ mod tests {
assert_eq!(pool.len(), 0);
}
#[test]
fn uvm_batch_drain_matches_single_drain_with_detached_records_and_reuse() {
extern crate alloc;
use alloc::vec::Vec;
let mut single = UvmCpuDmaLedger::new();
let mut batch = UvmCpuDmaLedger::new();
let mut a = Vec::new();
let mut b = Vec::new();
let insert = |l: &mut UvmCpuDmaLedger, slots: &mut Vec<UvmCpuDmaSlot>, r| match l
.insert_reusing(slots, r)
{
Ok(()) => {}
Err(None) => {
let idx = slots.len();
slots.push(UvmCpuDmaSlot::new_pending(r));
assert!(l.link_appended(slots, idx));
}
Err(Some(_)) => panic!("unexpected duplicate"),
};
for i in 1..=1031usize {
let r = UvmCpuDmaRecord {
cpu_ptr: i * 4096,
page: i,
gpu_id: (i % 3) as u32,
dev: i % 3 + 1,
dma: (i as u64) * 4096,
};
insert(&mut single, &mut a, r);
insert(&mut batch, &mut b, r);
}
let mut dead_a = single.detach_for_dev(&mut a, 2);
let mut dead_b = batch.detach_for_dev(&mut b, 2);
assert_eq!(batch.pop_batch(&mut b, &mut []), 0);
let mut out = [UvmCpuDmaRecord::default(); 16];
for pass in 0.. {
let count = batch.pop_batch(&mut b, &mut out);
if count == 0 {
assert_eq!(single.pop_any(&mut a), None);
break;
}
for r in &out[..count] {
assert_eq!(single.pop_any(&mut a), Some(*r));
assert_ne!(r.dev, 2);
}
assert_eq!(single.live_count(), batch.live_count());
if pass == 0 {
// An insertion between batches can land in an earlier bucket.
let r = UvmCpuDmaRecord {
cpu_ptr: 0x9000_0000,
page: 0x9000,
gpu_id: 4,
dev: 4,
dma: 0x9000_0000,
};
insert(&mut single, &mut a, r);
insert(&mut batch, &mut b, r);
}
}
assert_eq!(batch.live_count(), 0);
loop {
let x = single.pop_detached(&mut a, &mut dead_a);
let y = batch.pop_detached(&mut b, &mut dead_b);
assert_eq!(x, y);
if x.is_none() {
break;
}
}
assert_eq!(dead_b, 0);
}
#[test]
fn uvm_cpu_dma_ledger_handles_races_page_free_hot_unplug_and_drain() {
extern crate alloc;
@ -1250,6 +1358,34 @@ impl SysmemPagePool {
Some(page)
}
/// Takes at most limit hot pages, in the same LIFO order as pop_hot.
/// The callback consumes each owned page exactly once. The caller holds
/// the pool lock and clears the pages before exposing them to users.
pub fn pop_hot_batch(
&mut self,
slots: &mut [usize],
limit: usize,
mut take: impl FnMut(usize),
) -> usize {
let n = self.count.min(limit);
let cap = slots.len();
if n == 0 || cap == 0 {
return 0;
}
let mut idx = (self.head + self.count - 1) % cap;
for _ in 0..n {
let page = slots[idx];
slots[idx] = 0;
take(page);
idx = if idx == 0 { cap - 1 } else { idx - 1 };
}
self.count -= n;
if self.count == 0 {
self.head = 0;
}
n
}
/// Evicts one oldest (cold) page from the head while `self.count > retain`.
pub fn pop_cold_for_trim(&mut self, slots: &mut [usize], retain: usize) -> Option<usize> {
let cap = slots.len();
@ -2117,6 +2253,36 @@ impl UvmCpuDmaLedger {
None
}
/// Removes up to out.len() live mappings in the same bucket order as pop_any.
/// The caller owns each returned record and releases its DMA/page/device
/// references outside the ledger lock. Restart from bucket zero on every
/// call so insertions between batches cannot hide behind a persistent cursor.
pub fn pop_batch(&mut self, slots: &mut [UvmCpuDmaSlot], out: &mut [UvmCpuDmaRecord]) -> usize {
if self.live_count == 0 || out.is_empty() {
return 0;
}
let mut count = 0;
for bucket in 0..UVM_DMA_BUCKETS {
while self.buckets[bucket] != 0 {
let idx = (self.buckets[bucket] - 1) as usize;
let Some(slot) = slots.get(idx).copied() else {
self.buckets[bucket] = 0;
break;
};
self.buckets[bucket] = slot.next;
self.push_free(slots, idx);
if slot.occupied {
out[count] = slot.rec;
count += 1;
if count == out.len() || self.live_count == 0 {
return count;
}
}
}
}
count
}
/// Resets the hash index and free list when the backing slot slab is freed.
#[inline(never)]
pub fn reset(&mut self) {

View File

@ -0,0 +1,95 @@
// SPDX-License-Identifier: MIT
// CPU-only synthetic page-pool benchmark; no GPU or kernel page access.
// Copy this file into a temporary directory beside the exact baseline
// alloc_registry.rs renamed ledger.rs. Compile with:
// rustc --edition=2024 -C opt-level=3 -C overflow-checks=yes bench.rs -o baseline
// Repeat with candidate ledger.rs and --cfg batch -o candidate.
// Pin both processes to the same allowed CPU, alternate order, retain CSV.
// CSV: request size, pool fill percent, repetitions, aggregate ns,
// mutex acquisitions, p99 request ns. Measures host mutex and bookkeeping
// only; fresh allocation and clear_highpage are represented by synthetic tokens.
#![allow(dead_code)]
#[path = "ledger.rs"]
mod ledger;
use ledger::SysmemPagePool;
use std::{
hint::black_box,
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
time::Instant,
};
fn main() {
for n in [1usize, 8, 32, 128, 1024, 16384] {
let rounds = (262144 / n).max(16);
for fill in [0usize, 50, 100] {
let pooled = n * fill / 100;
let mut inner = Mutex::new((SysmemPagePool::new(), vec![0usize; n.max(1)]));
let published = AtomicUsize::new(0);
let mut total = 0u128;
let mut samples = Vec::with_capacity(rounds);
let mut output = vec![0usize; n];
let mut calls = 0usize;
for _ in 0..rounds {
{
let (pool, slots) = inner.get_mut().unwrap();
for page in 1..=pooled {
assert_eq!(pool.push(slots, page), Ok(()));
}
published.store(pool.len(), Ordering::Release);
}
let now = Instant::now();
let mut i = 0usize;
while i < n {
#[cfg(not(batch))]
{
let item = {
let mut guard = black_box(&inner).lock().unwrap();
let (pool, slots) = &mut *guard;
let p = pool.pop_hot(slots);
published.store(pool.len(), Ordering::Release);
p
};
calls += 1;
output[i] = item.unwrap_or(n + i + 1);
i += 1;
}
#[cfg(batch)]
{
let limit = (n - i).min(32);
let count = {
let mut guard = black_box(&inner).lock().unwrap();
let (pool, slots) = &mut *guard;
let mut written = 0usize;
let count = pool.pop_hot_batch(slots, limit, |page| {
output[i + written] = page;
written += 1;
});
published.store(pool.len(), Ordering::Release);
count
};
calls += 1;
i += count;
if count < limit {
output[i] = n + i + 1;
i += 1;
}
}
}
let elapsed = now.elapsed().as_nanos();
total += elapsed;
samples.push(elapsed);
assert_eq!(published.load(Ordering::Acquire), 0);
for (i, &p) in black_box(&output).iter().enumerate() {
assert_eq!(p, if i < pooled { pooled - i } else { n + i + 1 });
}
}
samples.sort_unstable();
println!(
"{n},{fill},{rounds},{total},{calls},{}",
samples[(samples.len() - 1) * 99 / 100]
);
}
}
}

View File

@ -0,0 +1,75 @@
// SPDX-License-Identifier: MIT
// Standalone CPU-side UVM drain benchmark. No GPU/device access.
// Compile from this source with the exact baseline ledger copied beside it
// as ledger.rs (no --cfg batch); repeat with candidate ledger and --cfg batch.
// rustc --edition=2024 -C opt-level=3 -C overflow-checks=yes [--cfg batch] bench.rs
// CSV: live mappings, repetitions, total timed nanoseconds, drain invocations.
// Setup, DMA unmapping, mutex acquisition and physical GPU work are not timed.
#![allow(dead_code)]
#[path = "ledger.rs"]
mod ledger;
use ledger::{UvmCpuDmaLedger, UvmCpuDmaRecord, UvmCpuDmaSlot};
use std::{hint::black_box, time::Instant};
fn main() {
for n in [1usize, 8, 16, 64, 1024, 16384, 65536, 262144] {
let rounds = (131072 / n).max(1);
let mut ledger = UvmCpuDmaLedger::new();
let mut slots = Vec::with_capacity(n);
let mut ns = 0u128;
let mut calls = 0usize;
for _ in 0..rounds {
for i in 1..=n {
let r = UvmCpuDmaRecord {
cpu_ptr: i * 4096,
page: i,
gpu_id: (i % 4) as u32,
dev: i % 4 + 1,
dma: (i as u64) * 4096,
};
match ledger.insert_reusing(&mut slots, r) {
Ok(()) => (),
Err(None) => {
let idx = slots.len();
slots.push(UvmCpuDmaSlot::new_pending(r));
assert!(ledger.link_appended(&mut slots, idx));
}
Err(Some(_)) => panic!("duplicate"),
}
}
let mut count = 0;
let mut sum = 0u64;
let now = Instant::now();
#[cfg(not(batch))]
loop {
calls += 1;
match ledger.pop_any(&mut slots) {
Some(r) => {
count += 1;
sum = sum.wrapping_add(black_box(r.dma));
}
None => break,
}
}
#[cfg(batch)]
{
let mut out = [UvmCpuDmaRecord::default(); 16];
loop {
calls += 1;
let k = ledger.pop_batch(&mut slots, &mut out);
if k == 0 {
break;
}
for r in &out[..k] {
count += 1;
sum = sum.wrapping_add(black_box(r.dma));
}
}
}
ns += now.elapsed().as_nanos();
assert_eq!(count, n);
assert_eq!(sum, (n as u64) * (n as u64 + 1) / 2 * 4096);
assert_eq!(ledger.live_count(), 0);
}
println!("{n},{rounds},{ns},{calls}");
}
}