Merge fork main 8dd30ab: writes through one view of a page are seen at its other views

The fork's guard over every view of a physical page is kept on our own block
bits, known holes, kernel writes and changing blocks; what both had, ours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 00:38:57 -06:00
commit c45d109380
23 files changed
+4164 -221

No files matched your search

+264 -2
View File
@@ -61,6 +61,19 @@ pub(crate) struct Staging {
uploaded: std::sync::atomic::AtomicBool,
/// When a list last recorded a use of it (`crate::host::moment`).
used: std::sync::atomic::AtomicU64,
/// Levels on demand (`crate::tiles`): the texture's host copy was made
/// without memory of its own when the staging buffer was made.
on_demand: bool,
/// For such a texture: the levels that were the title's at the last
/// detiling (a bit a level; the staging buffer holds zeros for the
/// others), and what that was judged by ([`Staging::judgement`]).
detiled: std::sync::atomic::AtomicU32,
judged: [std::sync::atomic::AtomicU64; 2],
/// For such a texture: when an upload last left a held level without
/// tiles (`crate::host::moment`, never 0; 0: none did). The upload is
/// recorded again about a second later if the card has room by then
/// ([`upload`]).
waiting: std::sync::atomic::AtomicU64,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
@@ -255,6 +268,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
if !first && before.is_none() {
return true;
}
card_writes(list, placed, to, None);
crate::list::ensure_state(list, placed, COPY_DEST);
let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
@@ -606,6 +620,32 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
};
use std::sync::atomic::Ordering::Relaxed;
staging.used.store(crate::host::moment(), Relaxed);
// Levels on demand: a view of the texture now starts at another
// level, or another texture now starts inside its span, with no byte
// of its memory changed. The levels are judged anew: detiled again at
// this list's submission, and uploaded by this list.
if staging.on_demand && staging.judgement() != staging.judged() {
staging.forget();
staging.dirty.store(true, Relaxed);
}
// Levels on demand: the last upload left a held level without tiles
// (the card had no room, or no heap could be had), and nothing else
// would record an upload again until the title writes the texture: the
// level stayed empty, the texture blurred or black. Asked again about
// once a second, and only when the card has room; the staging buffer
// still holds the level's bytes.
if staging.on_demand {
let since = staging.waiting.load(Relaxed);
if since != 0 && crate::host::long_ago(since, 1000, 2) {
if crate::resource::room_lately() {
staging.waiting.store(0, Relaxed);
staging.dirty.store(true, Relaxed);
crate::tiles::STATS[10].fetch_add(1, Relaxed);
} else {
staging.waiting.store(crate::host::moment().max(1), Relaxed);
}
}
}
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
@@ -699,11 +739,207 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
staging.dirty.store(false, Relaxed);
});
}
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
// Levels on demand (`crate::tiles`): after the check below, in the
// order of this list's steps, and before the list is executed, the
// levels the staging buffer holds as the title's are given the card's
// memory if they have none. The list copies every level, so each one
// given here is written whole by it (the rest are copies into no
// memory, which the card drops).
let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None };
let Some(on_demand) = on_demand else {
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
return;
};
list.defer_texture(staging.clone());
list.defer_host(move || {
let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64);
staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed);
// A texture picked by index has no staging buffer after this
// upload: its slots are made due again by the texture pass.
if waiting {
crate::descriptor::host::levels_waiting(staging.memory as u64);
}
});
}
/// Levels on demand: the levels a list claimed for its zeros
/// (`crate::tiles::Tiled::claim`), held by the list's submission-time
/// step. A list that is reset without having been submitted gives the
/// claim up, or the next list that writes those levels would send no zeros
/// and what its write does not cover would be what the tiles' last owner
/// left.
struct Claimed {
on_demand: crate::resource::OnDemand,
fresh: u32,
ran: std::sync::atomic::AtomicBool,
}
impl Drop for Claimed {
fn drop(&mut self) {
if self.fresh != 0
&& !*self.ran.get_mut()
&& let Some(tiled) = self.on_demand.tiled()
{
tiled.unclaim(self.fresh);
}
}
}
/// Levels on demand (`crate::tiles`): the card itself is about to write
/// title texture `resource` in `list` (a copy or a resolve into level
/// `level`, or into every level). If its host copy `texture` was made
/// without memory, the levels written get theirs when the list is
/// submitted, ahead of it on the queue; the ones that have none yet are
/// first written with zeros, here in the same list, so that what the
/// card's write does not cover is not what the tiles' last owner left.
/// To be called before the list is brought to the state of that write.
/// shortcut: two lists that write the same new level, submitted in the
/// other order than recorded, lose the first one's write under the zeros
/// of the other; so does an upload recorded and not yet submitted.
pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option<u32>) {
let Some(on_demand) = crate::resource::host_tiled(resource) else {
return;
};
let Some(tiled) = on_demand.tiled() else {
return;
};
let levels = match level {
Some(level) => tiled.with_level(level),
None => tiled.every_level(),
};
if levels == 0 {
return;
}
let fresh = tiled.claim(levels);
// Of them, the ones whose zeros could not be recorded.
let mut unzeroed = if host().is_none() { fresh } else { 0 };
if fresh != 0
&& let Some(host) = host()
{
const COPY_DEST: u32 = 0x400;
crate::list::ensure_state(list, resource, COPY_DEST);
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) {
let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut bytes = 0u64;
// SAFETY: outputs for one subresource.
unsafe {
host.device
.GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes));
}
let Some((buffer, data)) = list.upload(host, bytes) else {
// (With the levels that share its tiles, if it is one of
// the small ones.)
unzeroed |= tiled.with_level(level);
continue;
};
// SAFETY: a mapped buffer of `bytes` bytes, just made.
unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above; the list holds the buffer until it is reset.
pResource: unsafe { std::mem::transmute_copy(&buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
}
// A new level without its zeros gets no tiles from this list: the
// card's write into it is lost (the level reads zeros, as before the
// write), which is less wrong than a part write over what the tiles'
// last owner left. The next list that writes it claims it again.
unzeroed &= fresh;
if unzeroed != 0 {
tiled.unclaim(unzeroed);
}
let levels = levels & !unzeroed;
if levels == 0 {
return;
}
let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64);
let step = Claimed {
on_demand,
fresh: fresh & !unzeroed,
ran: std::sync::atomic::AtomicBool::new(false),
};
list.defer_host(move || {
step.ran.store(true, std::sync::atomic::Ordering::Relaxed);
step.on_demand.card_wrote(levels, memory);
});
}
impl Staging {
/// Levels on demand: what says, beside the mapping, which levels of
/// the texture are the title's now. First the lowest level a live view
/// of the texture shows (0 without a view that says): the title's own
/// word, a texture it holds from level 3 on is viewed from level 3.
/// Then where the next texture placed in this one's span starts, in
/// bytes from this one's start (`u64::MAX`: none does): for a texture
/// viewed from level 0 although a neighbour sits where its large
/// levels would be.
fn judgement(&self) -> [u64; 2] {
let start = self.memory as u64;
let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from);
let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size))
.map_or(u64::MAX, |at| at - start);
[first, limit]
}
/// What [`Staging::judgement`] said at the last detiling.
fn judged(&self) -> [u64; 2] {
use std::sync::atomic::Ordering::Relaxed;
[self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)]
}
/// Levels on demand: the levels that are the title's now, a bit a
/// level. A level is held if no view starts above it, its bytes end
/// before the next texture starts, and all of them are mapped. The
/// smallest levels share the texture's first block and are held
/// together. (The console layout: that block first, then the other
/// levels from the smallest up, level 0 last:
/// `victory_formats::texture::Layout`.) A texture this cannot tell
/// the levels of holds them all.
fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 {
let mips = &self.layout.mips;
if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 {
return u32::MAX;
}
let tail = (self.layout.first_tail_mip as usize).min(mips.len());
let there = |from: u64, to: u64| {
to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize)
};
let mut held = 0u32;
for (level, m) in mips.iter().enumerate().take(tail) {
let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset };
if level as u64 >= first && there(m.offset, end) {
held |= 1 << level;
}
}
if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) {
for level in tail..mips.len() {
if level as u64 >= first {
held |= 1 << level;
}
}
}
held
}
/// Forgets what the staging buffer was last filled from: the next
/// refresh detiles anew, whether the memory changed or not.
fn forget(&self) {
*self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default();
}
/// The title memory the texture is read from: address and bytes.
pub(crate) fn memory(&self) -> (usize, usize) {
(self.memory as usize, self.layout.size as usize)
@@ -909,6 +1145,20 @@ impl Staging {
/// Detiles `tiled` (the texture's memory) into the staging buffer.
fn detile(&self, tiled: &[u8]) {
self.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
// Levels on demand: which levels are the title's is judged here,
// once, for what the staging buffer holds from now on. The step
// that gives levels their memory goes by this answer.
let held = if self.on_demand {
use std::sync::atomic::Ordering::Relaxed;
let judged = self.judgement();
self.judged[0].store(judged[0], Relaxed);
self.judged[1].store(judged[1], Relaxed);
let held = self.held_levels(judged);
self.detiled.store(held, Relaxed);
held
} else {
u32::MAX
};
#[cfg(feature = "diagnostics")]
if tiled.iter().all(|&b| b == 0) {
tracing::debug!(
@@ -926,6 +1176,11 @@ impl Staging {
let linear = unsafe {
std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
};
if mip < 32 && held & (1 << mip) == 0 {
// Not the title's: zeros, not what lies in that memory.
linear.fill(0);
continue;
}
if let Err(e) =
self.layout
.detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
@@ -1179,6 +1434,9 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
/// The staging state of a title texture, made on first use.
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
// Asked before the table is locked: the sweep lets go of a staging
// buffer with its texture's host side locked, in that order.
let on_demand = crate::resource::host_tiled(resource).is_some();
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(HashMap::new);
if let Some(s) = map.get(&(resource as usize)) {
@@ -1254,6 +1512,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
dirty: std::sync::atomic::AtomicBool::new(true),
uploaded: std::sync::atomic::AtomicBool::new(false),
used: std::sync::atomic::AtomicU64::new(crate::host::moment()),
on_demand,
detiled: std::sync::atomic::AtomicU32::new(0),
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
waiting: std::sync::atomic::AtomicU64::new(0),
});
map.insert(resource as usize, s.clone());
Some(s)