| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744 |
- //! Which title memory the title wrote since a host copy took it (decision
- //! 0007, "Copies of title memory"). The runtime reserves title GPU memory
- //! with write watching (`victory-hle` xmem), so the kernel keeps a dirty bit
- //! per 4 KiB page; asking for a range's written pages also clears them. Host
- //! copies of the same memory can overlap (nested buffers, textures in
- //! buffers), so what one asks is kept here for the others: a journal of
- //! each page's last write, numbered by the asking.
- //!
- //! Physical-page views (xmem's sections) cannot be write-watched. There a
- //! copy leaves each 64 KiB block it took read-only, and our vectored handler
- //! takes the first write to it: it notes the block as written and gives the
- //! write access back. The runtime tells us when it maps or unmaps views
- //! ([`title_memory_remapped`]), which resets their protection. Blocks found
- //! wholly uncommitted are skipped while they remain so; one query can
- //! confirm a whole region, including ordinary reservations between views.
- //!
- //! shortcut: writes into physical pages through another view (xmem's
- //! `write_physical`, DirectStorage's page destinations) are not seen at
- //! the guarded addresses; they go to the texture pool, whose textures are
- //! hashed, not guarded. A system call writing into a guarded block fails
- //! (none is known to).
- use std::collections::{BTreeMap, BTreeSet};
- use std::sync::{Condvar, Mutex, RwLock};
- /// The unit tracked and copied: 64 KiB, the console's page (the kernel's
- /// 4 KiB pages fold into it). Finer units made the checks of the world's
- /// big buffers cost more than the copies they saved.
- pub(crate) const PAGE: usize = 64 << 10;
- /// The kernel's page, the unit of its answers.
- const KERNEL_PAGE: usize = 4096;
- /// Numbers the askings; 0 is "never". Counted up with the journal held
- /// (shared will do: what notes an answer holds it alone).
- static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- fn next_asking() -> u64 {
- ASKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
- }
- struct Journal {
- /// Page number → the asking that last found it written.
- written: BTreeMap<usize, u64>,
- /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`])
- /// and the asking that did: `writes` answers for a range inside one
- /// from the journal, without another kernel call.
- ahead: Vec<(usize, usize)>,
- ahead_asked: u64,
- /// The ahead asking stands for a whole submission ([`ask_once`]): no
- /// other ahead asking is made, and `ahead` stays, until
- /// [`ask_once_end`].
- kept: bool,
- }
- /// Read by many threads at once (a submission's refreshes run on several),
- /// written only to note an answer: the kernel is asked, and view memory
- /// guarded, with the range held in [`ASKING`] and not under this lock. Under
- /// one lock for all of it those threads ran one at a time: 22 of 96 looks at
- /// the submitting thread, and one in six of those at the six threads beside
- /// it, found it waiting for that lock (run pooloff1).
- static JOURNAL: RwLock<Journal> = RwLock::new(Journal {
- written: BTreeMap::new(),
- ahead: Vec::new(),
- ahead_asked: 0,
- kept: false,
- });
- fn journal() -> std::sync::RwLockReadGuard<'static, Journal> {
- JOURNAL.read().unwrap_or_else(|e| e.into_inner())
- }
- fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> {
- JOURNAL.write().unwrap_or_else(|e| e.into_inner())
- }
- /// The page ranges some thread is asking about: asking forgets what it
- /// answers, so until the answer is in the journal no other thread may ask
- /// about any of the same pages (it would be told they were not written).
- /// Taken before the journal's lock, never under it.
- static ASKING: (Mutex<Vec<(usize, usize)>>, Condvar) = (Mutex::new(Vec::new()), Condvar::new());
- /// Pages `[first, last)` held in [`ASKING`] until dropped.
- struct Asking(usize, usize);
- impl Asking {
- fn hold(first: usize, last: usize) -> Asking {
- let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner());
- while held.iter().any(|&(a, b)| a < last && first < b) {
- held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner());
- }
- held.push((first, last));
- Asking(first, last)
- }
- /// Everything: an asking for a whole submission.
- fn hold_all() -> Asking {
- Asking::hold(0, usize::MAX)
- }
- }
- impl Drop for Asking {
- fn drop(&mut self) {
- let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner());
- if let Some(i) = held.iter().position(|&r| r == (self.0, self.1)) {
- held.swap_remove(i);
- }
- drop(held);
- ASKING.1.notify_all();
- }
- }
- thread_local! {
- /// Room for the kernel's answer.
- static FOUND: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
- }
- /// The pages of `[first, last)` the kernel says were written since it was
- /// last asked, in order, each once; `None` if the range is not write-watched
- /// memory of one reservation. The caller holds the range ([`Asking`]).
- fn kernel_written(first: usize, last: usize) -> Option<Vec<usize>> {
- use windows_sys::Win32::System::Memory::GetWriteWatch;
- const WRITE_WATCH_FLAG_RESET: u32 = 1;
- FOUND.with(|found| {
- let mut found = found.borrow_mut();
- let mut count = (last - first) * PAGE / KERNEL_PAGE;
- if found.len() < count {
- found.resize(count, 0);
- }
- let mut granularity = 0;
- #[cfg(feature = "diagnostics")]
- let started = std::time::Instant::now();
- // SAFETY: the answer buffer holds `count` entries.
- let failed = unsafe {
- GetWriteWatch(
- WRITE_WATCH_FLAG_RESET,
- (first * PAGE) as *const _,
- (last - first) * PAGE,
- found.as_mut_ptr().cast(),
- &mut count,
- &mut granularity,
- )
- } != 0;
- #[cfg(feature = "diagnostics")]
- {
- tally(10, u64::from(failed));
- tally(11, started.elapsed().as_nanos() as u64);
- }
- if failed {
- return None;
- }
- #[cfg(feature = "diagnostics")]
- {
- tally(12, count as u64);
- use crate::copystat::{C, add};
- add(C::Watches, 1);
- add(C::WatchUs, started.elapsed().as_micros() as u64);
- slow(started.elapsed().as_micros() as u64);
- tally(0, 1);
- tally(1, ((last - first) * (PAGE >> 10)) as u64);
- }
- let mut pages: Vec<usize> = found[..count].iter().map(|&at| at / PAGE).collect();
- pages.dedup();
- Some(pages)
- })
- }
- /// Ranges of one submission closer than this are asked about together:
- /// walking the pages between them costs less than another kernel call (a
- /// call that resets written pages costs 30-70 microseconds whatever the
- /// range).
- const AHEAD_GAP: usize = (8 << 20) / PAGE;
- /// The most one asking covers (its answer needs 8 bytes per 4 KiB page).
- const AHEAD_MAX: usize = (1 << 30) / PAGE;
- /// Asks the kernel about many ranges `(start, end)` at once, before the
- /// [`writes`] of each: ranges close together are one asking, and `writes`
- /// then answers from the journal until [`ask_ahead_done`]. The world's
- /// submissions refresh thousands of host copies (6,664 askings a frame,
- /// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are
- /// left to `writes`.
- pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
- let mut pieces: Vec<(usize, usize)> = ranges
- .iter()
- // Not view memory known by its bits: the kernel would refuse the
- // asking (and, asked together with others, theirs).
- .filter(|r| r.0 < r.1 && !published(r.0, r.1))
- .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
- .collect();
- if pieces.len() < 2 {
- return;
- }
- pieces.sort_unstable();
- // The submission's one asking stands ([`ask_once`]): what it does not
- // hold is left to `writes`.
- if journal().kept {
- return;
- }
- let _all = Asking::hold_all();
- let (mut asked, mut written) = (Vec::new(), Vec::new());
- let mut i = 0;
- while i < pieces.len() {
- let first = pieces[i].0;
- let mut last = pieces[i].1;
- let mut k = i + 1;
- while k < pieces.len()
- && pieces[k].0 <= last + AHEAD_GAP
- && last.max(pieces[k].1) - first <= AHEAD_MAX
- {
- last = last.max(pieces[k].1);
- k += 1;
- }
- ask_run(&pieces[i..k], &mut asked, &mut written);
- i = k;
- }
- let mut j = journal_mut();
- j.ahead_asked = next_asking();
- j.ahead = asked;
- let now = j.ahead_asked;
- j.written.extend(written.into_iter().map(|page| (page, now)));
- }
- /// Since the last frame line: the kernel askings that took a millisecond
- /// or more, their microseconds, and the longest asking's. An asking walks
- /// page tables, some ten microseconds for most ranges; in run 75 the 2,644
- /// askings of a frame took 219 ms in the lines where the pass over the
- /// heap's views ran long, 25-50 ms in the others. These numbers say
- /// whether a few askings wait for something or all of them are slow.
- #[cfg(feature = "diagnostics")]
- static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
- #[cfg(feature = "diagnostics")]
- fn slow(us: u64) {
- use std::sync::atomic::Ordering::Relaxed;
- if us >= 1000 {
- SLOW[0].fetch_add(1, Relaxed);
- SLOW[1].fetch_add(us, Relaxed);
- }
- SLOW[2].fetch_max(us, Relaxed);
- }
- /// [`SLOW`], taken.
- #[cfg(feature = "diagnostics")]
- pub(crate) fn slow_asks() -> [u64; 3] {
- [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed))
- }
- /// The submission's refreshes are done: `writes` asks the kernel again.
- pub(crate) fn ask_ahead_done() {
- let mut j = journal_mut();
- if !j.kept {
- j.ahead.clear();
- }
- }
- /// Whether a submission asks the kernel once, before its first refresh,
- /// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by
- /// default).
- ///
- /// A submission's refreshes are done in groups, between the title's own
- /// buffer copies (each copy flushes the refreshes recorded before it), and
- /// every group asked the kernel again: 2,644 askings a frame, 70 a
- /// submission. With the switch the journal answers all of them from one
- /// asking made when the submission starts.
- ///
- /// What changes: memory the title's other threads write while the
- /// submission is being prepared is seen by the next submission's asking,
- /// not by this one's later groups. What this submission's lists read was
- /// written before they were submitted, so before the asking. Our own
- /// writes into title memory while preparing are told to the journal
- /// ([`wrote`]) or end the asking ([`ask_once_end`]).
- pub(crate) fn once() -> bool {
- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- // On by default since run 81 (with card buffers: 375-450 ms a frame
- // against 573-647, the picture unchanged over four minutes);
- // `VICTORY_ASK_ONCE=0` asks per range, as before.
- *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0"))
- }
- /// With [`once`]: asks about `ranges` (everything a submission's lists
- /// refresh) as [`ask_ahead`] does, and lets that asking stand until
- /// [`ask_once_end`].
- pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
- if !once() {
- return;
- }
- ask_once_end();
- ask_ahead(ranges);
- ask_rest(ranges);
- }
- /// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the
- /// asking stands.
- fn ask_rest(ranges: &[(usize, usize)]) {
- let _all = Asking::hold_all();
- let mut ahead = {
- let mut j = journal_mut();
- std::mem::take(&mut j.ahead)
- };
- // `ask_ahead` leaves a range that lies alone to `writes`, which asks
- // once per flush: with one asking for the submission that was every
- // such range asked again at each of its 70 flushes (run 76: 2,300
- // askings a frame with the switch on, as without it). They are asked
- // here, once; what is not write-watched stays with `writes`.
- let mut written = Vec::new();
- for &(start, end) in ranges {
- if start >= end || published(start, end) {
- continue;
- }
- let (first, last) = (start / PAGE, end.div_ceil(PAGE));
- if !ahead.iter().any(|&(a, b)| a <= first && last <= b)
- && let Some(pages) = kernel_written(first, last)
- {
- written.extend(pages);
- ahead.push((first, last));
- }
- }
- let mut j = journal_mut();
- // A number of its own, and the one this asking stands under: between
- // the two parts another thread may have asked about a range of the
- // second, copied it, and the title written it since. Under the first
- // part's number that write was older than the copy, and never copied.
- let now = next_asking();
- j.ahead_asked = now;
- j.written.extend(written.into_iter().map(|page| (page, now)));
- j.kept = !ahead.is_empty();
- j.ahead = ahead;
- }
- /// The submission's one asking stands no longer: its refreshes are done,
- /// or title memory was written in a way the journal was not told.
- pub(crate) fn ask_once_end() {
- let mut j = journal_mut();
- if j.kept {
- j.kept = false;
- j.ahead.clear();
- }
- }
- /// We wrote title memory `[at, at + len)` while a submission's one asking
- /// stands (the title's buffer copies, done at submission): its pages count
- /// as written after that asking, so the refreshes that follow copy them.
- pub(crate) fn wrote(at: usize, len: usize) {
- let mut j = journal_mut();
- if !j.kept || len == 0 {
- return;
- }
- let now = next_asking();
- // What is copied from now on counts as copied after these writes (fork
- // PR 410): answers older than the writes in them made every refresh
- // until the next asking copy the pages again.
- j.ahead_asked = now;
- for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
- j.written.insert(page, now);
- }
- }
- /// One kernel asking for `pieces` (page ranges in order); by halves if it
- /// fails, as a run across two reservations or into memory that is not
- /// write-watched does. A piece alone is left to [`writes`]. Adds what was
- /// asked to `asked` and the pages found written to `written`.
- fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<usize>) {
- if pieces.len() < 2 {
- return;
- }
- let first = pieces[0].0;
- let last = pieces.iter().map(|p| p.1).max().unwrap_or(first);
- if let Some(pages) = kernel_written(first, last) {
- written.extend(pages);
- asked.push((first, last));
- return;
- }
- let (a, b) = pieces.split_at(pieces.len() / 2);
- ask_run(a, asked, written);
- ask_run(b, asked, written);
- }
- /// What [`writes`] would say of `[start, end)` from the journal alone, if
- /// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the
- /// pages written since tracking began and the asking that last found each
- /// written, with the number of the asking that stands (as [`writes`] gives
- /// it). `None` if the kernel would have to be asked.
- pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
- let (first, last) = (start / PAGE, end.div_ceil(PAGE));
- let j = journal();
- j.ahead
- .iter()
- .any(|&(a, b)| a <= first && last <= b)
- .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()))
- }
- /// The pages of `[start, end)` (whole pages) as last written, for pages
- /// written since tracking began: `(page number, asking)` in page order, and
- /// this asking's number, which is higher than any in the list but those the
- /// kernel just reported. `None` if the memory is not write-watched (nor,
- /// with `guarded`, view memory, which is then guarded).
- pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
- let (first, last) = (start / PAGE, end.div_ceil(PAGE));
- let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() };
- // Asked ahead with the submission's other ranges: the journal has it.
- let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j)));
- if let Some(known) = ahead(&journal()) {
- return Some(known);
- }
- // Read-only since an asking noted it: the bits first, then the journal.
- if guarded && published(start, end) {
- #[cfg(feature = "diagnostics")]
- tally(2, 1);
- let j = journal();
- return Some((next_asking(), of(&j)));
- }
- // Asked, and the answer noted, with the range held: nothing else asks
- // about any of it in between.
- let _range = Asking::hold(first, last);
- if let Some(known) = ahead(&journal()) {
- return Some(known);
- }
- let mut guards_asked = false;
- let pages = match kernel_written(first, last) {
- Some(pages) => pages,
- None => {
- guards_asked = true;
- if !guarded {
- return None;
- }
- #[cfg(feature = "diagnostics")]
- let guarding = std::time::Instant::now();
- let written = guard(first * PAGE, last * PAGE);
- #[cfg(feature = "diagnostics")]
- {
- use crate::copystat::{C, add};
- let us = guarding.elapsed().as_micros() as u64;
- add(C::GuardUs, us);
- if written.is_some() {
- add(C::Watches, 1);
- add(C::WatchUs, us);
- slow(us);
- }
- }
- written?
- }
- };
- if pages.is_empty() {
- // Nothing to note: the others may go on reading.
- let j = journal();
- return Some((next_asking(), of(&j)));
- }
- let answer = {
- let mut j = journal_mut();
- let now = next_asking();
- j.written.extend(pages.iter().map(|&page| (page, now)));
- (now, of(&j))
- };
- // Noted: what the guards made clean of it is known by its bits from
- // now on. (The range is still held: no other asking of any of it came
- // between.)
- if guards_asked && light() {
- publish(&pages);
- }
- Some(answer)
- }
- /// Whether nothing of `[start, end)` was written that a copy with the notes
- /// `copied` (the asking after which each page from page `base` on was taken)
- /// and `ranged` (the asking after which a range that holds this one was
- /// taken whole, or 0) does not hold, as [`writes`] would answer with nothing
- /// asked: the submission's asking covers the range, or its blocks are known
- /// by their bits. `false` if something would have to be asked.
- pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool {
- let (first, last) = (start / PAGE, end.div_ceil(PAGE));
- // The bits first, then the journal, as in `writes`.
- let known = published(start, end);
- let j = journal();
- if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
- return false;
- }
- let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
- return false;
- };
- (ranged != 0 || taken.iter().all(|&at| at != 0))
- && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged))
- }
- /// Guarded blocks of view memory.
- const BLOCK: usize = PAGE;
- /// Whether the refreshes of host copies go the light way
- /// (`VICTORY_LIGHT_REFRESH=0`: as before): view memory nothing wrote since
- /// it was last asked about is known by its bits ([`PUBLISHED`]), a copy
- /// nothing of whose range changed is told so before any thread is woken
- /// for it (`crate::host`, `Shadow::nothing_new`), and the ends of a range,
- /// pages the range holds in part, are not copied again at every refresh
- /// (`Shadow::copy_stale`).
- ///
- /// A frame asked about view memory some 1,500 times, for nearly all of it
- /// to hear that nothing was written, on up to seven threads at once, each
- /// asking under the guards' one lock and behind [`ASKING`]'s: 94 ms a frame
- /// of all threads' time (run record-1), most of it waiting.
- pub(crate) fn light() -> bool {
- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *ON.get_or_init(|| std::env::var_os("VICTORY_LIGHT_REFRESH").is_none_or(|v| v != "0"))
- }
- /// A bit per block of the address space, in pieces made when first needed
- /// and never let go.
- struct Bits([std::sync::atomic::AtomicPtr<BitsPiece>; Bits::PIECES]);
- /// The bits of 4 GiB.
- type BitsPiece = [std::sync::atomic::AtomicU64; Bits::WORDS];
- impl Bits {
- const WORDS: usize = 1 << 10;
- /// 128 TiB, what a process has.
- const PIECES: usize = 1 << 15;
- const fn new() -> Bits {
- Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Bits::PIECES])
- }
- fn piece(&self, word: usize) -> Option<&BitsPiece> {
- let piece = self.0.get(word / Bits::WORDS)?.load(std::sync::atomic::Ordering::Acquire);
- // SAFETY: null, or a piece made by `set`, which is never freed.
- unsafe { piece.as_ref() }
- }
- /// One caller at a time (under the guards' lock).
- fn set(&self, block: usize) {
- use std::sync::atomic::Ordering::{Relaxed, Release};
- let word = block / 64;
- let Some(place) = self.0.get(word / Bits::WORDS) else {
- return;
- };
- if place.load(Relaxed).is_null() {
- let piece: Box<BitsPiece> = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]);
- place.store(Box::into_raw(piece), Release);
- }
- if let Some(piece) = self.piece(word) {
- piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release);
- }
- }
- fn clear(&self, block: usize) {
- let word = block / 64;
- if let Some(piece) = self.piece(word) {
- // Ahead of the protection's change, and seen by whoever the
- // writer tells of its write.
- piece[word % Bits::WORDS].fetch_and(!(1 << (block % 64)), std::sync::atomic::Ordering::SeqCst);
- }
- }
- /// Whether a bit of `[first, last)` is set.
- fn any(&self, first: usize, last: usize) -> bool {
- let mut block = first;
- while block < last {
- let word = block / 64;
- let until = ((word + 1) * 64).min(last);
- let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
- match self.piece(word) {
- Some(piece) => {
- if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 {
- return true;
- }
- block = until;
- }
- // None of the piece's.
- None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64,
- }
- }
- false
- }
- /// Whether the bits of all of `[first, last)` are set (not so of none).
- fn all(&self, first: usize, last: usize) -> bool {
- let mut block = first;
- while block < last {
- let word = block / 64;
- let until = ((word + 1) * 64).min(last);
- let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
- let Some(piece) = self.piece(word) else {
- return false;
- };
- if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != mask {
- return false;
- }
- block = until;
- }
- first < last
- }
- }
- /// The blocks that are read-only by our hand, not written since, and of
- /// which the journal holds every write from before that: for those, what
- /// [`writes`] answers is in the journal, and neither the kernel, nor the
- /// guards' lock, nor [`ASKING`] need be asked.
- ///
- /// Why that is so: a block's bit is set under the guards' lock while the
- /// block is clean, by the asking that made it clean, after that asking noted
- /// in the journal what it found ([`publish`]). It is cleared under the same
- /// lock, before the block becomes writable again ([`open`]) or is forgotten
- /// ([`title_memory_remapped`]). So while the bit is set nothing can have
- /// written the block through this address, and who sees the bit and looks
- /// at the journal after that finds every earlier write in it. A write that
- /// comes while the bit is looked at is no different from one that comes just
- /// after an asking: the next asking finds the block open.
- ///
- /// So too for the blocks of placeholders that were copied as zeros
- /// (`Guards::held`): nothing can be there before the runtime maps it, and
- /// it tells of that ([`title_memory_remapped`]) before the title is.
- static PUBLISHED: Bits = Bits::new();
- /// The blocks read-only by our hand, or about to be: set under the guards'
- /// lock ahead of the protection, cleared under it when the block is open
- /// again. Who finds none set has no guard to open and need not wait for the
- /// lock ([`writing`]): some 700 pieces a frame are landed in memory that is
- /// no view.
- static PROTECTED: Bits = Bits::new();
- /// An asking made blocks of `pages` clean and noted them in the journal.
- fn publish(pages: &[usize]) {
- let g = guards();
- for page in pages {
- if g.clean.contains(page) || g.held.contains(page) {
- PUBLISHED.set(*page);
- }
- }
- }
- /// Whether placeholders are known for what they are (`VICTORY_KNOWN_HOLES=0`:
- /// every hole is looked at at every asking, as before).
- ///
- /// Most ranges asked about have holes, reservations the title maps its pages
- /// into as it streams (231,000 regions, 1,125 of a frame's 1,530 asked view
- /// ranges, run next1-1). Such a range was never known whole: each asking put
- /// a question to Windows for each of its holes, under the guards' lock, and
- /// 111 ms a frame of all threads' time went into waiting for that lock.
- fn known_holes() -> bool {
- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *ON.get_or_init(|| std::env::var_os("VICTORY_KNOWN_HOLES").is_none_or(|v| v != "0") && light())
- }
- /// Whether `block` lies in a placeholder: a reservation in which pages come
- /// to be only by mapping a view (or an allocation) in its place, which an
- /// ordinary commit cannot do.
- fn placeholder(block: usize) -> bool {
- /// `MEMORY_REGION_INFORMATION` (ntddk).
- #[repr(C)]
- #[derive(Default)]
- struct Region {
- allocation_base: usize,
- allocation_protect: u32,
- region_type: u32,
- region_size: usize,
- commit_size: usize,
- partition_id: usize,
- node_preference: usize,
- }
- #[link(name = "ntdll", kind = "raw-dylib")]
- unsafe extern "system" {
- fn NtQueryVirtualMemory(
- process: *mut std::ffi::c_void,
- at: *const std::ffi::c_void,
- class: u32,
- out: *mut std::ffi::c_void,
- len: usize,
- returned: *mut usize,
- ) -> i32;
- }
- // (Class 3 answers with the kind of memory in that word, not the flags.)
- const MEMORY_REGION_INFORMATION_EX: u32 = 7;
- const PLACEHOLDER_RESERVATION: u32 = 1 << 8;
- let mut region = Region::default();
- // SAFETY: the answer's room and its size.
- let status = unsafe {
- NtQueryVirtualMemory(
- windows_sys::Win32::System::Threading::GetCurrentProcess(),
- (block * BLOCK) as *const _,
- MEMORY_REGION_INFORMATION_EX,
- (&raw mut region).cast(),
- size_of::<Region>(),
- std::ptr::null_mut(),
- )
- };
- status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0
- }
- /// The runtime gave the title memory at `[at, at + len)`, allocated or
- /// committed: what was known of holes there is asked again.
- pub fn title_memory_allocated(at: usize, len: usize) {
- if len == 0 || !known_holes() {
- return;
- }
- let mut g = guards();
- let blocks: Vec<usize> = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect();
- for block in blocks {
- g.held.remove(&block);
- PUBLISHED.clear(block);
- }
- }
- /// Once a frame: a hundredth of the known holes are looked at, in case one
- /// was filled with nobody telling ([`title_memory_allocated`],
- /// [`title_memory_remapped`]), which no title we know does.
- pub(crate) fn look_at_holes() {
- const PARTS: usize = 100;
- if !known_holes() {
- return;
- }
- static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
- let blocks: Vec<usize> = {
- let g = guards();
- let from = FROM.load(std::sync::atomic::Ordering::Relaxed);
- let part: Vec<usize> = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect();
- FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed);
- part
- };
- let mut until = 0;
- for block in blocks {
- if block >= until {
- until = uncommitted_end(block);
- }
- if block >= until {
- // (Or unmapped memory was mapped since the part was taken: told
- // already, and forgotten.)
- let mut g = guards();
- if g.held.remove(&block) {
- PUBLISHED.clear(block);
- static SAID: std::sync::Once = std::sync::Once::new();
- SAID.call_once(|| {
- tracing::warn!(
- address = format_args!("{:#x}", block * BLOCK),
- "a placeholder of the title's was filled with nobody telling (VICTORY_KNOWN_HOLES=0 asks every time)"
- );
- });
- }
- }
- }
- }
- /// Whether a block of `[start, end)` is view memory read-only by our hand:
- /// the kernel keeps no written pages of it and would refuse an asking.
- pub(crate) fn guarded(start: usize, end: usize) -> bool {
- PROTECTED.any(start / BLOCK, end.div_ceil(BLOCK))
- }
- /// Whether nothing of `[start, end)` can have been written since an asking
- /// noted it in the journal ([`PUBLISHED`]).
- fn published(start: usize, end: usize) -> bool {
- light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK))
- }
- /// Since the last frame line: what asking about title memory was. Kernel
- /// askings and the KiB they walked; view ranges answered by their bits, by
- /// the guards whole clean, and block by block; blocks made read-only; blocks
- /// opened by ourselves; nanoseconds waiting for the guards' lock and
- /// nanoseconds of changing protections (all threads); questions to Windows
- /// about holes; kernel askings refused; nanoseconds in kernel askings; the
- /// 4 KiB pages they found written.
- #[cfg(feature = "diagnostics")]
- static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13];
- #[cfg(feature = "diagnostics")]
- fn tally(what: usize, n: u64) {
- ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
- }
- /// [`ASKS`], taken.
- #[cfg(feature = "diagnostics")]
- pub(crate) fn asks() -> [u64; 13] {
- std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
- }
- /// The guards' lock, the wait for it counted.
- fn guards_timed() -> std::sync::MutexGuard<'static, Guards> {
- #[cfg(feature = "diagnostics")]
- let started = std::time::Instant::now();
- let g = guards();
- #[cfg(feature = "diagnostics")]
- tally(7, started.elapsed().as_nanos() as u64);
- g
- }
- struct Guards {
- /// Blocks we made read-only.
- protected: BTreeSet<usize>,
- /// Of those, the ones not written since a copy took them.
- clean: BTreeSet<usize>,
- /// Blocks already copied as zeros. While they remain wholly uncommitted,
- /// the copy can skip hundreds of MB of failing kernel reads per world frame.
- absent: BTreeSet<usize>,
- /// Of those, the ones in placeholders ([`known_holes`]).
- held: BTreeSet<usize>,
- /// Blocks that were absent and turned out to be other memory than views
- /// when something was there again: never guarded, copied every time.
- foreign: BTreeSet<usize>,
- /// Blocks (first, past the last) the kernel writes now
- /// ([`kernel_writing`]), and blocks the runtime has unmapped in a change
- /// not yet done ([`title_memory_unmapping`]). Not in the sets above, and
- /// left as they are by [`guard`], which reports them written.
- kernel: Vec<(usize, usize)>,
- changing: Vec<(usize, usize)>,
- }
- impl Guards {
- fn left_alone(&self, block: usize) -> bool {
- self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block))
- }
- }
- static GUARDS: Mutex<Guards> = Mutex::new(Guards {
- protected: BTreeSet::new(),
- clean: BTreeSet::new(),
- absent: BTreeSet::new(),
- held: BTreeSet::new(),
- foreign: BTreeSet::new(),
- kernel: Vec::new(),
- changing: Vec::new(),
- });
- fn guards() -> std::sync::MutexGuard<'static, Guards> {
- GUARDS.lock().unwrap_or_else(|e| e.into_inner())
- }
- /// The 4 KiB pages of title memory that what shaders wrote was put into,
- /// and the frame it last was.
- static LANDED: Mutex<Option<std::collections::HashMap<usize, u64, std::hash::BuildHasherDefault<PageHash>>>> = Mutex::new(None);
- /// A page's number, spread: some 20,000 a frame are noted in [`LANDED`].
- #[derive(Default)]
- struct PageHash(u64);
- impl std::hash::Hasher for PageHash {
- fn finish(&self) -> u64 {
- self.0
- }
- fn write(&mut self, bytes: &[u8]) {
- for &byte in bytes {
- self.write_u64(u64::from(byte));
- }
- }
- fn write_u64(&mut self, n: u64) {
- self.0 = (self.0 ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(26).wrapping_mul(0x9e37_79b9_7f4a_7c15);
- }
- fn write_usize(&mut self, n: usize) {
- self.write_u64(n as u64);
- }
- }
- /// What shaders wrote is about to go into title memory at `[at, at + len)`.
- pub(crate) fn landing(at: usize, len: usize) {
- {
- let frame = crate::frame::current();
- let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
- let landed = landed.get_or_insert_with(Default::default);
- for page in at / 4096..=(at + len.max(1) - 1) / 4096 {
- landed.insert(page, frame);
- }
- }
- writing(at, len);
- }
- /// What shaders wrote went into title memory through another view of the
- /// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number)
- /// hold some of it, all of them in `spans` (address, bytes).
- ///
- /// Nothing faulted and no guard was opened. A guarded block stays read-only,
- /// clean, and known by its bit ([`PUBLISHED`]), all of which say that the
- /// title wrote nothing there: our write is an entry of the journal, which
- /// every answer about the block comes from, the quick ones and the guards'
- /// alike (a block whose guard is off they report anyway). So neither the
- /// guards' lock nor a protection is touched here, or by the next refresh.
- /// Noted after the bytes are in, never before: a copy that read the block
- /// before they were did so with the number of an asking made before that,
- /// which is under the one given here, and takes it again; noted before, a
- /// copy could read the older bytes with a number above the note's.
- ///
- /// Returns the note's number, and for each 64 KiB block noted the number of
- /// the block's last write before (0: none is known).
- pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) {
- let mut before = Vec::with_capacity(spans.len());
- let noted;
- {
- let frame = crate::frame::current();
- let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
- let landed = landed.get_or_insert_with(Default::default);
- for &page in pages {
- landed.insert(page, frame);
- }
- }
- {
- let mut j = journal_mut();
- let now = next_asking();
- noted = now;
- let mut last = usize::MAX;
- for &page in pages {
- let block = page * KERNEL_PAGE / PAGE;
- if block != last {
- before.push((block, j.written.insert(block, now).unwrap_or(0)));
- last = block;
- }
- }
- }
- for &(at, len) in spans {
- // A placed texture there changes with no descriptor written.
- crate::descriptor::host::remapped(at, len);
- }
- (noted, before)
- }
- /// Whether every write of the title's to 64 KiB block `block` so far is in
- /// the journal ([`PUBLISHED`]).
- pub(crate) fn block_published(block: usize) -> bool {
- light() && PUBLISHED.all(block, block + 1)
- }
- /// Whether shaders' writes went into a page of `[at, at + len)` in the last
- /// `frames` frames.
- pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
- let since = crate::frame::current().saturating_sub(frames);
- let landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
- landed.as_ref().is_some_and(|landed| {
- (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| landed.get(&page).is_some_and(|&f| f >= since))
- })
- }
- /// Whether every block of `[at, at + len)` is view memory written since a
- /// host copy last took it: guarded then, and the guard is off. (Written by
- /// the title, or by us putting a flight's shader writes into it, if not
- /// beside the guard, [`landed_beside`].) Not for
- /// blocks no copy ever took, which were never guarded: the caller's range
- /// lies in a copy a flight was given, which took all of it.
- pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
- if len == 0 {
- return false;
- }
- let g = guards();
- (at / BLOCK..=(at + len - 1) / BLOCK)
- .all(|b| !g.clean.contains(&b) && !g.absent.contains(&b))
- }
- /// For view memory: the pages of `[start, end)`'s blocks written since
- /// they were last guarded (all of a block's pages), guarding them again
- /// before the caller copies them. `None` if the memory is not a view.
- fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
- // A range whose first block the guards hold already (read-only by our
- // hand, or noted absent) is a view: no question to Windows. The
- // question walks the page tables to the end of the pages that share the
- // first one's state, and a guarded view is one long run of read-only
- // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most
- // of the 68 ms a frame of "guards" (run 58).
- // `VICTORY_GUARD_ASK=1` asks every time, as before.
- static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
- let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1"))
- && (PROTECTED.any(first, first + 1) || {
- let g = guards_timed();
- g.protected.contains(&first) || g.absent.contains(&first)
- });
- if !known && !is_view(start, end) {
- return None;
- }
- install();
- // The holes that an ordinary commit may have filled, with no word of the
- // runtime's. Windows is asked with the lock not held (the range is, no
- // other thread asks about it: `ASKING`); what the runtime tells meanwhile
- // takes the block out of the set, and it is looked at as any other.
- let unsure: Vec<usize> = {
- let g = guards_timed();
- if g.clean.range(first..last).count() == last - first {
- // Nothing written, mapped or new since the range was last taken.
- #[cfg(feature = "diagnostics")]
- tally(3, 1);
- return Some(Vec::new());
- }
- g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect()
- };
- let mut came: Vec<(usize, bool)> = Vec::new();
- let mut uncommitted_until = first;
- for block in unsure {
- // One question for the blocks of a region.
- if block >= uncommitted_until {
- uncommitted_until = uncommitted_end(block);
- #[cfg(feature = "diagnostics")]
- tally(9, 1);
- }
- if block >= uncommitted_until {
- // The hole may have been given up, and its address be the
- // title's heap's, or code's, now: not ours to guard.
- came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK)));
- }
- }
- let mut g = guards_timed();
- #[cfg(feature = "diagnostics")]
- tally(4, 1);
- for &(block, view) in &came {
- if g.absent.remove(&block) && !view {
- g.foreign.insert(block);
- }
- }
- let mut written = Vec::new();
- let mut run: Option<usize> = None;
- // The range's clean blocks, and those known to be holes, in order: read
- // off the sets in one pass, not looked up one block at a time. A frame
- // asks about some 10 GB of view memory, 150,000 blocks, nearly all
- // clean: the lookups were most of the 60-90 ms a frame of "guards"
- // (run 54). What the loop adds to the sets meanwhile is the block it
- // stands at or ones before it.
- let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
- let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
- let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable());
- for block in first..=last {
- let is_clean = clean.next_if_eq(&block).is_some();
- let is_absent = absent.next_if_eq(&block).is_some();
- if block < last && !is_clean && !is_absent {
- written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
- if g.protected.contains(&block) {
- // Written through the runtime, still read-only.
- g.clean.insert(block);
- } else if !g.foreign.contains(&block) && !g.left_alone(block) {
- run.get_or_insert(block);
- continue;
- }
- }
- if let Some(from) = run.take() {
- protect(&mut g, from, block);
- }
- }
- Some(written)
- }
- /// Whether `[start, end)` is view memory. The title's views lie in
- /// placeholders, mapped and unmapped block by block as it streams, so a
- /// range can begin in a block that is not mapped right now: the first
- /// pages of the range that are there decide. A range with nothing there
- /// counts as a view (its blocks are noted absent, and looked at again when
- /// the runtime maps them).
- ///
- /// Looking at the first address only took such a range for "not a view":
- /// its copy was marked not watched for good and copied whole at every
- /// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB
- /// copied a frame for them, 255 copies a frame reading around holes).
- /// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before.
- fn is_view(start: usize, end: usize) -> bool {
- use windows_sys::Win32::System::Memory::{
- MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery,
- };
- static HOLES: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0"));
- let mut at = start;
- loop {
- // SAFETY: plain data filled in by the query.
- let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
- // SAFETY: a valid out pointer of the right size.
- let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
- if n == 0 {
- return false;
- }
- if info.Type == MEM_MAPPED {
- return true;
- }
- // Committed memory that is no view (the title's heaps, ours), or
- // the answer as it was before.
- if info.State == MEM_COMMIT || !holes {
- return false;
- }
- // A hole (a placeholder, or free): on to what follows it.
- let next = (info.BaseAddress as usize).saturating_add(info.RegionSize);
- if next <= at || next >= end {
- return true;
- }
- at = next;
- }
- }
- /// Makes blocks `[from, to)` read-only and notes them guarded and clean;
- /// block by block if they span views, leaving out any that fail, and
- /// noting those not committed (unmapped) absent.
- fn protect(g: &mut Guards, from: usize, to: usize) {
- use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
- let set = |from: usize, to: usize| {
- let mut old = 0;
- #[cfg(feature = "diagnostics")]
- let started = std::time::Instant::now();
- // SAFETY: title view memory; only its protection changes.
- let mut done = unsafe {
- VirtualProtect(
- (from * BLOCK) as *const _,
- (to - from) * BLOCK,
- PAGE_READONLY,
- &mut old,
- ) != 0
- };
- if done && !matches!(old, PAGE_READWRITE | PAGE_READONLY) {
- // What is there is not for us to guard (code, or memory the
- // title protects itself): as it was.
- // SAFETY: as above.
- unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, old, &mut old) };
- done = false;
- }
- #[cfg(feature = "diagnostics")]
- {
- tally(5, (to - from) as u64);
- tally(8, started.elapsed().as_nanos() as u64);
- }
- done
- };
- let note = |g: &mut Guards, from: usize, to: usize| {
- g.protected.extend(from..to);
- g.clean.extend(from..to);
- };
- // Ahead of the protection (`PROTECTED`).
- (from..to).for_each(|block| PROTECTED.set(block));
- if set(from, to) {
- note(g, from, to);
- return;
- }
- let mut uncommitted_until = from;
- for block in from..to {
- // (Not one question a block of a region that is not there.)
- if block >= uncommitted_until && set(block, block + 1) {
- note(g, block, block + 1);
- continue;
- }
- PROTECTED.clear(block);
- if block >= uncommitted_until {
- uncommitted_until = uncommitted_end(block);
- #[cfg(feature = "diagnostics")]
- tally(9, 1);
- }
- if block < uncommitted_until {
- g.absent.insert(block);
- if known_holes() && placeholder(block) {
- g.held.insert(block);
- }
- }
- }
- }
- /// The end (exclusive) of the whole uncommitted blocks starting at `block`.
- fn uncommitted_end(block: usize) -> usize {
- use windows_sys::Win32::System::Memory::{
- MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery,
- };
- // SAFETY: plain data filled in by the query.
- let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
- // SAFETY: a valid out pointer of the right size.
- let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) };
- if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) {
- (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK
- } else {
- block
- }
- }
- /// Gives write access back to the guarded blocks of `[start, end)` and
- /// notes them written; true if any was guarded.
- fn open(g: &mut Guards, start: usize, end: usize) -> bool {
- use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
- let blocks: Vec<usize> = g
- .protected
- .range(start / BLOCK..end.div_ceil(BLOCK))
- .copied()
- .collect();
- #[cfg(feature = "diagnostics")]
- let started = std::time::Instant::now();
- for &block in &blocks {
- g.protected.remove(&block);
- g.clean.remove(&block);
- // Before the block can be written.
- PUBLISHED.clear(block);
- let mut old = 0;
- // SAFETY: a block we made read-only.
- unsafe {
- if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0
- && !matches!(old, PAGE_READONLY | PAGE_READWRITE)
- {
- // Not what we left there: the address is other memory's
- // (code's, say), which keeps its protection.
- VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old);
- }
- }
- PROTECTED.clear(block);
- }
- #[cfg(feature = "diagnostics")]
- if !blocks.is_empty() {
- tally(8, started.elapsed().as_nanos() as u64);
- }
- !blocks.is_empty()
- }
- /// Before our own write into title memory `[at, at + len)` through the
- /// kernel (which does not fault into our handler): opens its guarded blocks.
- /// The runtime calls it (as `kernel_will_write`) before the title's kernel
- /// reads into its own memory.
- pub fn writing(at: usize, len: usize) {
- // The length is the title's (`fread`'s size times count, saturated).
- let last = at.saturating_add(len).div_ceil(BLOCK);
- if !light() || PROTECTED.any(at / BLOCK, last) {
- let mut g = guards_timed();
- #[cfg(feature = "diagnostics")]
- let held = g.protected.len();
- open(&mut g, at, at.saturating_add(len));
- #[cfg(feature = "diagnostics")]
- tally(6, (held - g.protected.len()) as u64);
- }
- // A placed texture there changes with no descriptor written.
- crate::descriptor::host::remapped(at, len);
- }
- /// The kernel writes title memory `[at, at + len)` until what this returns
- /// is dropped ([`kernel_writing`]).
- pub struct KernelWrite(usize, usize);
- /// The runtime is about to have the kernel write title memory
- /// `[at, at + len)` (a file read): its guarded blocks are opened, as by
- /// [`writing`], and no refresh guards them again before what this returns is
- /// dropped, at the end of that call. One that did would make the kernel's
- /// write fail (the kernel does not fault into our handler): a read cut
- /// short, which the title takes for what the file holds.
- pub fn kernel_writing(at: usize, len: usize) -> KernelWrite {
- let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK));
- {
- let mut g = guards_timed();
- open(&mut g, at, at.saturating_add(len));
- if len != 0 {
- // Nothing known of them stands while they are left alone.
- let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
- for block in absent {
- g.absent.remove(&block);
- if g.held.remove(&block) {
- PUBLISHED.clear(block);
- }
- }
- g.kernel.push((first, last));
- }
- }
- crate::descriptor::host::remapped(at, len);
- KernelWrite(first, if len == 0 { first } else { last })
- }
- impl Drop for KernelWrite {
- fn drop(&mut self) {
- if self.0 == self.1 {
- return;
- }
- let mut g = guards();
- if let Some(i) = g.kernel.iter().position(|&r| r == (self.0, self.1)) {
- g.kernel.swap_remove(i);
- }
- }
- }
- /// Held shared by a read of title memory in place, and alone by the runtime
- /// while it changes what title memory shows.
- ///
- /// The runtime does not change a mapping in one step. To unmap one page of
- /// a view it unmaps the whole view and maps what stays again
- /// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next
- /// call commits it (`map`, then `commit`). For that moment pages the title
- /// never gave up are "reserved, never committed", and a thread reading
- /// them in place takes an access violation: run 71 in `Layout::detile`,
- /// run 74 in the hash before it, both under `Staging::refresh_now`, which
- /// had asked whether the texture was all mapped and been told yes. Asking
- /// cannot help; not changing the mapping while such a read is under way
- /// does.
- static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
- /// What the runtime holds while it changes what title memory shows
- /// ([`title_memory_remapping`]).
- pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
- impl Drop for Remapping {
- fn drop(&mut self) {
- // The change is done: what is there now may be guarded.
- if CHANGING.replace((false, false)).1 {
- guards().changing.clear();
- }
- CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- }
- }
- /// How often the runtime began or ended a change of what title memory
- /// shows: odd while one is under way.
- static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- thread_local! {
- /// This thread holds [`Remapping`]; and put blocks in
- /// [`Guards::changing`].
- static CHANGING: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, false)) };
- }
- /// For [`again_after_change`]: to be asked before what may fail.
- pub(crate) fn changes() -> u64 {
- CHANGES.load(std::sync::atomic::Ordering::SeqCst)
- }
- /// `f` failed to read or write title memory, at some time since [`changes`]
- /// said `since`. If the runtime changed a mapping in that time, the pages
- /// may have been away for that moment only ([`MAPPING`]): again, when the
- /// change is done. Whether `f` did it.
- pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> bool {
- let mut since = since;
- for _ in 0..4 {
- let now = change_done();
- if now == since {
- return false;
- }
- since = now;
- if f() {
- return true;
- }
- }
- false
- }
- /// [`changes`], when no change is under way (or one has been for a second).
- fn change_done() -> u64 {
- let mut tries = 0;
- let mut started = None;
- loop {
- let now = changes();
- if now.is_multiple_of(2) {
- return now;
- }
- tries += 1;
- if tries < 100 {
- std::hint::spin_loop();
- continue;
- }
- if started.get_or_insert_with(std::time::Instant::now).elapsed().as_secs() >= 1 {
- return now;
- }
- // SAFETY: gives the processor to another thread.
- unsafe { windows_sys::Win32::System::Threading::Sleep(u32::from(tries > 200)) };
- }
- }
- /// Faults of title threads that met a change of mapping and went on after
- /// it ([`came_back`]).
- static MET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- /// A title thread's access to `at` (`write`: a write) faulted. Whether it
- /// can be made now: if a change of mapping is under way, after it.
- ///
- /// The console changes one page's mapping and no other's. Here the rest of
- /// a view is unmapped and mapped again ([`MAPPING`]), and a title thread that
- /// uses a page of it just then, which the title never gave up, faulted
- /// ("reserved, never committed", or read-only for the moment between our
- /// forgetting a guarded block and its unmapping). It waits here instead.
- /// Memory that is not there with no change under way is not waited for.
- fn came_back(at: usize, write: bool) -> bool {
- let there = || {
- if !write {
- return readable_view(at);
- }
- // (A refresh may have guarded the page that came back.)
- open(&mut guards(), at, at + 1) || writable(at)
- };
- let before = changes();
- if there() || again_after_change(before, there) {
- MET.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
- return true;
- }
- false
- }
- /// Whether `at` is in a committed page of a view that can be read.
- fn readable_view(at: usize) -> bool {
- use windows_sys::Win32::System::Memory::{
- MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery,
- };
- // SAFETY: plain data filled in by the query.
- let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
- // SAFETY: a valid out pointer of the right size.
- let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
- n != 0
- && info.State == MEM_COMMIT
- && info.Type == MEM_MAPPED
- && matches!(info.Protect, PAGE_READONLY | PAGE_READWRITE)
- }
- /// Title memory that could not be written with what was to go there (what a
- /// shader wrote, a title's copy): counted, and said at the 1st, 2nd, 4th, 8th
- /// and so on. A page the title unmapped loses nothing by it; a page that is
- /// there does.
- pub(crate) fn lost(what: &'static str, at: usize, len: usize) {
- static LOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- let n = LOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
- if n.is_power_of_two() {
- let there = writable(at);
- tracing::warn!(n, what, at = format_args!("{at:#x}"), len, there, "title memory not written");
- }
- }
- /// The runtime is about to map, unmap or move physical pages of title
- /// memory: until what it returns is dropped, no read of title memory in
- /// place is under way and none begins ([`title_memory_reading`]). Taken
- /// around the whole change, the unmapping and the mapping again.
- pub fn title_memory_remapping() -> Remapping {
- // For the title's own threads ([`came_back`]).
- install();
- let met = MET.load(std::sync::atomic::Ordering::Relaxed);
- if met != 0 {
- static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- if met >= 2 * SAID.load(std::sync::atomic::Ordering::Relaxed) {
- SAID.store(met, std::sync::atomic::Ordering::Relaxed);
- tracing::info!(met, "accesses of title threads that waited for a change of mapping");
- }
- }
- let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner());
- CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- CHANGING.set((true, false));
- Remapping(changing)
- }
- /// What a read of title memory in place holds ([`title_memory_reading`]).
- pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>);
- /// For reading title memory in place: until what it returns is dropped,
- /// the runtime changes no mapping, so memory found mapped stays mapped.
- /// Not to be taken twice by one thread, nor held across anything that
- /// maps title memory.
- pub fn title_memory_reading() -> Reading {
- Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner()))
- }
- /// [`title_memory_reading`] if it can be had at once: `None` while the
- /// runtime changes a mapping (or waits to), for a caller that has another
- /// way to read and would rather not wait.
- pub fn title_memory_reading_now() -> Option<Reading> {
- match MAPPING.try_read() {
- Ok(guard) => Some(Reading(guard)),
- Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())),
- Err(std::sync::TryLockError::WouldBlock) => None,
- }
- }
- /// The runtime mapped title memory `[at, at + len)`: what it shows is new,
- /// so it is no longer guarded (nor known unmapped), and read-write.
- ///
- /// The view is there before we are told of it, and a copy's refresh on
- /// another thread may have guarded its blocks in between (it finds blocks
- /// it knew absent committed, and holds [`GUARDS`], which we wait for).
- /// Forgetting such a block and leaving it read-only would make the title's
- /// next write to it an access violation nobody takes (`on_write` finds it
- /// neither guarded nor writable) and a kernel read into it fail, so the
- /// write access is given back.
- pub fn title_memory_remapped(at: usize, len: usize) {
- open(&mut title_memory_changed(at, len), at, at.saturating_add(len));
- }
- /// The runtime is about to unmap title memory `[at, at + len)`: it is
- /// nothing of ours any more. Its protection goes with it. Until the change
- /// is done ([`Remapping`]) no refresh guards what is there: one that did
- /// before the unmapping would leave the address guarded, clean and known by
- /// its bits ([`PUBLISHED`]) with no view behind it.
- pub fn title_memory_unmapping(at: usize, len: usize) {
- let mut g = title_memory_changed(at, len);
- if CHANGING.get().0 && len != 0 {
- CHANGING.set((true, true));
- let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK));
- match g.changing.last_mut() {
- Some(before) if before.1 == first => before.1 = last,
- _ => g.changing.push((first, last)),
- }
- }
- let blocks: Vec<usize> = g
- .protected
- .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
- .copied()
- .collect();
- for block in blocks {
- g.protected.remove(&block);
- g.clean.remove(&block);
- PUBLISHED.clear(block);
- PROTECTED.clear(block);
- }
- }
- /// The title is about to free or decommit memory of its own,
- /// `[at, at + len)`, or with no length the whole allocation at `at`: what
- /// was noted of its blocks (guarded, clean, absent) would be taken for true
- /// of the next memory at the address.
- pub fn title_memory_freed(at: usize, len: usize) {
- let mut g = guards();
- let first = at / BLOCK;
- let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next());
- let Some(noted) = noted.into_iter().flatten().min().copied() else {
- return;
- };
- let end = if len != 0 {
- at.saturating_add(len).div_ceil(BLOCK)
- } else {
- allocation_end(at, noted * BLOCK).div_ceil(BLOCK)
- };
- if noted >= end {
- return;
- }
- let absent: Vec<usize> = g.absent.range(first..end).copied().collect();
- for block in absent {
- g.absent.remove(&block);
- if g.held.remove(&block) {
- PUBLISHED.clear(block);
- }
- }
- let foreign: Vec<usize> = g.foreign.range(first..end).copied().collect();
- for block in foreign {
- g.foreign.remove(&block);
- }
- // (Memory that is still a view is not freed by that call, which fails:
- // it must not stay read-only.)
- open(&mut g, at, end * BLOCK);
- }
- /// The end of the allocation at `at`, if `inside` lies in it; else `at`.
- fn allocation_end(at: usize, inside: usize) -> usize {
- use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
- let ask = |address: usize| {
- // SAFETY: plain data filled in by the query.
- let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
- // SAFETY: a valid out pointer of the right size.
- let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) };
- (n != 0 && info.AllocationBase as usize == at)
- .then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize))
- };
- let mut end = at;
- let mut next = ask(inside.max(at));
- while let Some(to) = next {
- end = to;
- next = ask(to);
- }
- end
- }
- /// Tells what keeps track of what title memory shows; the guards, with no
- /// block of the range known unmapped.
- fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> {
- // A placed texture there arrives, goes or changes with no descriptor
- // written.
- crate::descriptor::host::remapped(at, len);
- // The views the runtime told us of there are no longer what it shows.
- crate::inplace::views_gone(at, len);
- // And nothing stays in place over it.
- crate::inplace::title_memory_freeing(at, len);
- let mut g = guards();
- let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
- let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
- for block in absent {
- g.absent.remove(&block);
- if g.held.remove(&block) {
- PUBLISHED.clear(block);
- }
- }
- let foreign: Vec<usize> = g.foreign.range(range).copied().collect();
- for block in foreign {
- g.foreign.remove(&block);
- }
- g
- }
- /// Registers the handler that takes writes to guarded blocks, once, ahead
- /// of the crash reporter's.
- pub(crate) fn install() {
- use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
- use windows_sys::Win32::System::Diagnostics::Debug::{
- AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
- EXCEPTION_POINTERS,
- };
- unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
- // SAFETY: the system passes the exception being dispatched.
- let r = unsafe { &*(*info).ExceptionRecord };
- const READ: usize = 0;
- const WRITE: usize = 1;
- // A fault of our own copies (`crate::safecopy`): whatever it is, if
- // it is not a block we guard, the copy fails and goes on from there.
- let ours = crate::safecopy::failing_exit(r.ExceptionAddress as usize);
- let fail = |exit: usize| {
- // SAFETY: the context the system passes, to go on from.
- unsafe { (*(*info).ContextRecord).Rip = exit as u64 };
- EXCEPTION_CONTINUE_EXECUTION
- };
- if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
- || r.NumberParameters < 2
- || r.ExceptionInformation[0] != WRITE
- {
- return match ours {
- Some(exit) => fail(exit),
- None if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS
- && r.NumberParameters >= 2
- && r.ExceptionInformation[0] == READ
- && came_back(r.ExceptionInformation[1], false) =>
- {
- EXCEPTION_CONTINUE_EXECUTION
- }
- None => EXCEPTION_CONTINUE_SEARCH,
- };
- }
- let at = r.ExceptionInformation[1];
- // Held across both checks: another thread may have opened the block
- // since this one faulted, and a copy may have guarded it again since
- // (then it is ours again, not read-only for some other reason).
- let mut g = guards();
- if open(&mut g, at, at + 1) {
- #[cfg(feature = "diagnostics")]
- crate::copystat::add(crate::copystat::C::GuardFaults, 1);
- return EXCEPTION_CONTINUE_EXECUTION;
- }
- if writable(at) {
- return EXCEPTION_CONTINUE_EXECUTION;
- }
- // (The runtime wants the guards to end a change.)
- drop(g);
- match ours {
- Some(exit) => fail(exit),
- None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION,
- None => EXCEPTION_CONTINUE_SEARCH,
- }
- }
- static ONCE: std::sync::Once = std::sync::Once::new();
- // SAFETY: the handler only touches our guard state and protections.
- ONCE.call_once(|| unsafe {
- AddVectoredExceptionHandler(1, Some(on_write));
- });
- }
- /// Whether `at` is committed read-write memory now.
- fn writable(at: usize) -> bool {
- use windows_sys::Win32::System::Memory::{
- MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
- };
- // SAFETY: plain data filled in by the query.
- let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
- // SAFETY: a valid out pointer of the right size.
- let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
- n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- use windows_sys::Win32::System::Memory::{
- MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
- };
- const MEM_WRITE_WATCH: u32 = 0x20_0000;
- #[test]
- fn written_pages_are_reported_to_every_asker() {
- // SAFETY: a fresh write-watched allocation, freed at the end.
- let p = unsafe {
- VirtualAlloc(
- std::ptr::null(),
- 4 * PAGE,
- MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
- PAGE_READWRITE,
- )
- } as usize;
- assert_ne!(p, 0);
- let (start, end) = (p, p + 4 * PAGE);
- // The journal may hold pages of another test's memory that was here.
- let (none, before) = writes(start, end, false).expect("watched");
- assert!(before.iter().all(|&(_, w)| w < none), "{before:?}");
- // SAFETY: committed pages of ours.
- unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
- let (now, after) = writes(start, end, false).expect("watched");
- let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::<Vec<_>>();
- assert_eq!(new(after), [(p / PAGE + 1, now)]);
- // Another asker after the kernel's bit was cleared still sees it.
- let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
- assert!(later > now);
- assert_eq!(new(again), [(p / PAGE + 1, now)]);
- let mut plain = vec![0u8; PAGE];
- assert!(
- writes(
- plain.as_mut_ptr() as usize,
- plain.as_ptr() as usize + PAGE,
- true
- )
- .is_none()
- );
- // SAFETY: our allocation.
- unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
- }
- /// A kernel read into a guarded view block fails; opened first, it
- /// lands and the block counts as written.
- #[test]
- fn kernel_reads_into_guarded_blocks_after_opening() {
- use std::io::{Read, Seek, Write};
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
- };
- // SAFETY: a pagefile section of two blocks, mapped read-write.
- let view = unsafe {
- let section = CreateFileMappingW(
- -1isize as _,
- std::ptr::null(),
- PAGE_READWRITE,
- 0,
- (2 * BLOCK) as u32,
- std::ptr::null(),
- );
- assert!(!section.is_null());
- MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
- };
- assert_ne!(view, 0);
- assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
- let mut file = tempfile::tempfile().unwrap();
- file.write_all(b"from the disk").unwrap();
- // `ReadFile` inside: the kernel writes the view.
- let read = |file: &mut std::fs::File| {
- file.rewind().unwrap();
- // SAFETY: 13 bytes of our view, nothing else refers to them.
- let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
- file.read(into).is_ok_and(|n| n == 13)
- };
- assert!(
- !read(&mut file),
- "the kernel does not fault into our handler"
- );
- writing(view + 100, 13);
- assert!(read(&mut file));
- // SAFETY: the bytes just read.
- let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) };
- assert_eq!(landed, b"from the disk");
- assert_eq!(
- guard(view, view + 2 * BLOCK),
- Some((view / PAGE..view / PAGE + 1).collect())
- );
- // Before the view goes, as the runtime does: the address may be
- // another test's the moment it is free.
- title_memory_unmapping(view, 2 * BLOCK);
- // SAFETY: our view.
- unsafe {
- UnmapViewOfFile(
- windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
- Value: view as *mut _,
- },
- )
- };
- }
- /// A placeholder of `blocks` blocks, each its own.
- fn placeholder(blocks: usize) -> usize {
- use windows_sys::Win32::System::Memory::{
- MEM_PRESERVE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, VirtualAlloc2,
- };
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- // SAFETY: a fresh placeholder, split.
- unsafe {
- let p = VirtualAlloc2(
- GetCurrentProcess(),
- std::ptr::null(),
- blocks * BLOCK,
- MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
- PAGE_NOACCESS,
- std::ptr::null_mut(),
- 0,
- ) as usize;
- assert_ne!(p, 0);
- for block in 0..blocks - 1 {
- assert_ne!(
- VirtualFree((p + block * BLOCK) as *mut _, BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER),
- 0
- );
- }
- p
- }
- }
- /// Private memory of `protect` in place of the placeholder of one block.
- fn private_at(at: usize, protect: u32) {
- use windows_sys::Win32::System::Memory::{MEM_REPLACE_PLACEHOLDER, VirtualAlloc2};
- // SAFETY: our placeholder.
- let got = unsafe {
- VirtualAlloc2(
- windows_sys::Win32::System::Threading::GetCurrentProcess(),
- at as *const _,
- BLOCK,
- MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER,
- protect,
- std::ptr::null_mut(),
- 0,
- )
- };
- assert_eq!(got as usize, at);
- }
- fn protection(at: usize) -> u32 {
- use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
- // SAFETY: plain data the query fills in.
- unsafe {
- let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
- VirtualQuery(at as *const _, &mut info, size_of_val(&info));
- info.Protect
- }
- }
- /// A refresh between the opening of a kernel read's destination and the
- /// read itself leaves it open: the read lands, and is seen.
- #[test]
- fn a_refresh_leaves_open_what_the_kernel_is_writing() {
- use std::io::{Read, Seek, Write};
- use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
- // SAFETY: a pagefile section of two blocks, mapped read-write.
- let view = unsafe {
- let section = CreateFileMappingW(
- -1isize as _,
- std::ptr::null(),
- PAGE_READWRITE,
- 0,
- (2 * BLOCK) as u32,
- std::ptr::null(),
- );
- assert!(!section.is_null());
- MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK)
- };
- let at = view.Value as usize;
- assert_ne!(at, 0);
- let pages = |block: usize| at / PAGE + block..at / PAGE + block + 1;
- assert!(writes(at, at + 2 * BLOCK, true).is_some());
- assert!(published(at, at + 2 * BLOCK) || !light());
- let mut file = tempfile::tempfile().unwrap();
- file.write_all(b"from the disk").unwrap();
- file.rewind().unwrap();
- let writing = kernel_writing(at + 100, 13);
- // The refresh: the block being written is new to it every time, and
- // stays open; the other is as it was.
- for _ in 0..2 {
- assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect()));
- let (now, found) = writes(at, at + BLOCK, true).expect("a view");
- assert!(found.contains(&(at / PAGE, now)));
- assert!(writable(at) && !writable(at + BLOCK));
- assert!(!published(at, at + BLOCK));
- }
- // SAFETY: 13 bytes of our view, nothing else refers to them.
- let into = unsafe { std::slice::from_raw_parts_mut((at + 100) as *mut u8, 13) };
- assert_eq!(file.read(into).expect("the kernel's write lands"), 13);
- assert_eq!(into, b"from the disk");
- drop(writing);
- // Seen by the next refresh, and guarded again.
- assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect()));
- assert!(!writable(at));
- assert_eq!(guard(at, at + 2 * BLOCK), Some(Vec::new()));
- title_memory_unmapping(at, 2 * BLOCK);
- // SAFETY: our view.
- unsafe { UnmapViewOfFile(view) };
- }
- /// A hole the kernel is to write is no known hole meanwhile, nor is one
- /// the runtime has begun to change; after that it is again.
- #[test]
- fn what_is_left_alone_is_no_known_hole() {
- let p = placeholder(3);
- let known = |block: usize| published(p + block * BLOCK, p + (block + 1) * BLOCK);
- let ask = || writes(p, p + 3 * BLOCK, true).expect("as a view");
- ask();
- let holes = known_holes();
- assert!((0..3).all(known) == holes);
- let writing = kernel_writing(p + BLOCK + 5, 100);
- for _ in 0..2 {
- assert!(known(0) == holes && !known(1) && known(2) == holes);
- let (now, written) = ask();
- assert!(written.contains(&(p / PAGE + 1, now)));
- assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now));
- }
- assert!(!guards().held.contains(&(p / BLOCK + 1)));
- drop(writing);
- ask();
- assert!((0..3).all(known) == holes);
- {
- let _changing = title_memory_remapping();
- title_memory_unmapping(p, BLOCK);
- ask();
- assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
- }
- ask();
- assert!((0..3).all(known) == holes);
- title_memory_freed(p, BLOCK);
- assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
- title_memory_unmapping(p, 3 * BLOCK);
- // SAFETY: our placeholders.
- unsafe {
- for block in 0..3 {
- VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
- }
- }
- }
- /// A refresh during a change of mapping guards nothing the runtime has
- /// begun to unmap: no note of it stays behind.
- #[test]
- fn nothing_is_guarded_between_our_forgetting_it_and_its_unmapping() {
- use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
- // SAFETY: a pagefile section of a block, mapped read-write.
- let view = unsafe {
- let section =
- CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null());
- assert!(!section.is_null());
- MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK)
- };
- let at = view.Value as usize;
- assert_ne!(at, 0);
- assert!(writes(at, at + BLOCK, true).is_some());
- let changing = title_memory_remapping();
- title_memory_unmapping(at, BLOCK);
- assert!(writes(at, at + BLOCK, true).is_some());
- {
- let g = guards();
- assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK)));
- }
- assert!(!published(at, at + BLOCK));
- // SAFETY: our view.
- unsafe { UnmapViewOfFile(view) };
- drop(changing);
- assert!(!guards().left_alone(at / BLOCK));
- }
- /// Memory at an address where blocks were guarded or absent is not
- /// taken for them: code stays code, private memory is not guarded.
- #[test]
- fn other_memory_at_a_guarded_address_keeps_its_protection() {
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MapViewOfFile3, PAGE_EXECUTE_READ,
- PAGE_EXECUTE_READWRITE, UnmapViewOfFile2,
- };
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- let p = placeholder(3);
- // SAFETY: a section's block in place of the first placeholder.
- let view = unsafe {
- let section =
- CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null());
- assert!(!section.is_null());
- MapViewOfFile3(
- section,
- GetCurrentProcess(),
- p as *const _,
- 0,
- BLOCK,
- MEM_REPLACE_PLACEHOLDER,
- PAGE_READWRITE,
- std::ptr::null_mut(),
- 0,
- )
- };
- assert_eq!(view.Value as usize, p);
- // One block guarded, two absent.
- assert_eq!(guard(p, p + 3 * BLOCK).map(|w| w.len()), Some(3));
- // Not told of what comes: the view goes, code is there; and private
- // memory in the holes.
- // SAFETY: our view.
- assert_ne!(unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, 0);
- private_at(p, PAGE_EXECUTE_READ);
- private_at(p + BLOCK, PAGE_READWRITE);
- private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE);
- // (The runtime's allocations it tells of, or the holes stay known.)
- title_memory_allocated(p + BLOCK, 2 * BLOCK);
- let as_made = || {
- assert_eq!(protection(p), PAGE_EXECUTE_READ);
- assert_eq!(protection(p + BLOCK), PAGE_READWRITE);
- assert_eq!(protection(p + 2 * BLOCK), PAGE_EXECUTE_READWRITE);
- };
- let holes = [p / PAGE + 1, p / PAGE + 2];
- for _ in 0..2 {
- let written = guard(p, p + 3 * BLOCK).expect("as a view");
- assert!(holes.iter().all(|page| written.contains(page)), "copied every time");
- as_made();
- let g = guards();
- assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block)));
- }
- writing(p, BLOCK);
- as_made();
- title_memory_unmapping(p, 3 * BLOCK);
- // SAFETY: our allocations.
- unsafe {
- for block in 0..3 {
- VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
- }
- }
- }
- /// Memory the title frees leaves no note of its blocks, whether it names
- /// its length or the allocation.
- #[test]
- fn freed_memory_leaves_no_notes() {
- let p = placeholder(3);
- let noted = |block: usize| {
- let g = guards();
- let block = p / BLOCK + block;
- g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block)
- };
- assert!(guard(p, p + 3 * BLOCK).is_some());
- assert!(noted(0) && noted(1) && noted(2));
- // The middle allocation.
- title_memory_freed(p + BLOCK, 0);
- assert!(noted(0) && !noted(1) && noted(2));
- title_memory_freed(p, BLOCK);
- assert!(!noted(0) && noted(2));
- // Nothing noted there: nothing to do, and nothing beside it.
- title_memory_freed(p + BLOCK, 0);
- assert!(noted(2));
- title_memory_freed(p + 2 * BLOCK, 0);
- assert!(!noted(2));
- // SAFETY: our placeholders.
- unsafe {
- for block in 0..3 {
- VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
- }
- }
- }
- /// A write between another thread's asking about a range and the second
- /// part of a submission's one asking is later than what that thread
- /// copied.
- #[test]
- fn the_rest_of_the_one_asking_has_a_number_of_its_own() {
- // SAFETY: a fresh write-watched allocation, freed at the end.
- let p = unsafe {
- VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
- } as usize;
- assert_ne!(p, 0);
- // One range: `ask_ahead` leaves it.
- let ranges = [(p, p + 4 * PAGE)];
- ask_ahead(&ranges);
- let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched");
- // SAFETY: committed pages of ours.
- unsafe { ((p + PAGE) as *mut u8).write_volatile(1) };
- ask_rest(&ranges);
- let last = journal().written.get(&(p / PAGE + 1)).copied();
- ask_once_end();
- assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}");
- // SAFETY: our allocation.
- unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
- }
- /// The runtime maps a view and then tells us; a copy's refresh on another
- /// thread can guard it in between. Told, it is the title's to write: a
- /// block left read-only and forgotten would be an access violation in
- /// title code.
- #[test]
- fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() {
- use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
- };
- // SAFETY: a pagefile section of two blocks, mapped read-write; the
- // view holds it.
- let view = unsafe {
- let section = CreateFileMappingW(
- INVALID_HANDLE_VALUE,
- std::ptr::null(),
- PAGE_READWRITE,
- 0,
- (2 * BLOCK) as u32,
- std::ptr::null(),
- );
- assert!(!section.is_null());
- let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK);
- CloseHandle(section);
- view
- };
- let at = view.Value as usize;
- assert_ne!(at, 0);
- // The refresh, then the runtime's word.
- assert!(guard(at, at + 2 * BLOCK).is_some());
- assert!(!writable(at) && !writable(at + BLOCK));
- title_memory_remapped(at, 2 * BLOCK);
- assert!(writable(at) && writable(at + BLOCK));
- // SAFETY: inside the view; a fault would end the process.
- unsafe { ((at + 8) as *mut u8).write_volatile(1) };
- // Looked at again as new, and guarded again.
- assert_eq!(
- guard(at, at + 2 * BLOCK),
- Some((at / PAGE..at / PAGE + 2).collect())
- );
- assert!(!writable(at));
- title_memory_unmapping(at, 2 * BLOCK);
- // SAFETY: our view.
- unsafe { UnmapViewOfFile(view) };
- }
- #[test]
- fn writes_in_partly_committed_view_blocks_are_reported() {
- use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
- SEC_RESERVE, UnmapViewOfFile,
- };
- const SIZE: usize = 3 * BLOCK;
- struct View(MEMORY_MAPPED_VIEW_ADDRESS);
- impl Drop for View {
- fn drop(&mut self) {
- title_memory_unmapping(self.0.Value as usize, SIZE);
- // SAFETY: our view is still mapped.
- unsafe { UnmapViewOfFile(self.0) };
- }
- }
- // SAFETY: a new reserved pagefile section. The view holds its own
- // reference after we close the handle, including on assertion failure.
- let view = unsafe {
- let section = CreateFileMappingW(
- INVALID_HANDLE_VALUE,
- std::ptr::null(),
- PAGE_READWRITE | SEC_RESERVE,
- 0,
- SIZE as u32,
- std::ptr::null(),
- );
- assert!(!section.is_null());
- let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE);
- CloseHandle(section);
- assert!(!view.Value.is_null());
- View(view)
- };
- let start = view.0.Value as usize;
- let commit = |at: usize, len| {
- // SAFETY: these pages belong to our reserved view.
- let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) };
- assert_eq!(committed as usize, at);
- };
- let early = start + BLOCK + 3 * KERNEL_PAGE;
- let late = start + 2 * BLOCK + 3 * KERNEL_PAGE;
- commit(start, BLOCK);
- commit(early, KERNEL_PAGE);
- let refresh = || guard(start, start + SIZE).unwrap();
- assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]);
- // The last block is still entirely reserved.
- assert!(!refresh().contains(&(late / PAGE)));
- commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification.
- for at in [early, late] {
- assert!(writable(at));
- // SAFETY: each address is inside its committed read-write page.
- unsafe { (at as *mut u8).write_volatile(1) };
- }
- assert_eq!(refresh(), [early / PAGE, late / PAGE]);
- }
- /// A range of view memory whose first block is not mapped is a view
- /// all the same: its blocks are reported once, then the ones written
- /// or mapped since.
- #[test]
- fn a_range_that_begins_in_an_unmapped_block_is_guarded() {
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
- MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
- VirtualAlloc2,
- };
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- // SAFETY: a fresh placeholder of three blocks and a pagefile
- // section of three; the middle block is mapped first.
- let (p, section) = unsafe {
- let p = VirtualAlloc2(
- GetCurrentProcess(),
- std::ptr::null(),
- 3 * BLOCK,
- MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
- PAGE_NOACCESS,
- std::ptr::null_mut(),
- 0,
- ) as usize;
- assert_ne!(p, 0);
- let section = CreateFileMappingW(
- -1isize as _,
- std::ptr::null(),
- PAGE_READWRITE,
- 0,
- (3 * BLOCK) as u32,
- std::ptr::null(),
- );
- assert!(!section.is_null());
- (p, section)
- };
- let map = |block: usize| {
- // SAFETY: splits the placeholder at the block and maps the
- // section's block there.
- let view = unsafe {
- VirtualFree(
- (p + block * BLOCK) as *mut _,
- BLOCK,
- MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
- );
- MapViewOfFile3(
- section,
- GetCurrentProcess(),
- (p + block * BLOCK) as *const _,
- (block * BLOCK) as u64,
- BLOCK,
- MEM_REPLACE_PLACEHOLDER,
- PAGE_READWRITE,
- std::ptr::null_mut(),
- 0,
- )
- };
- assert_eq!(view.Value as usize, p + block * BLOCK);
- view
- };
- let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
- let all: Vec<usize> = (0..3).flat_map(pages).collect();
- // Nothing mapped at all: a view with every block absent.
- assert!(is_view(p, p + 3 * BLOCK));
- let middle = map(1);
- title_memory_remapped(p + BLOCK, BLOCK);
- // The range begins in the placeholder, its middle block is a view.
- assert!(is_view(p, p + 3 * BLOCK));
- assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
- assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since");
- // SAFETY: inside the mapped middle block.
- unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) };
- assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
- let first = map(0);
- title_memory_remapped(p, BLOCK);
- assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect()));
- assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
- // Memory of ours that is no view stays none.
- let mut local = [0u8; 16];
- let at = local.as_mut_ptr() as usize;
- assert!(!is_view(at, at + local.len()));
- title_memory_unmapping(p, 3 * BLOCK);
- // SAFETY: our views and placeholder.
- unsafe {
- UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
- UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER);
- for block in 0..3 {
- VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
- }
- windows_sys::Win32::Foundation::CloseHandle(section);
- }
- }
- /// Blocks of a placeholder between views are reported once, then not
- /// again (they cannot be guarded) until the runtime maps them.
- #[test]
- fn unmapped_blocks_are_reported_once_until_mapped() {
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
- MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
- VirtualAlloc2,
- };
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- // SAFETY: a fresh placeholder of three blocks and a pagefile
- // section of two; block 0 shows the section's first block, as the
- // runtime maps physical pages.
- let (p, section) = unsafe {
- let p = VirtualAlloc2(
- GetCurrentProcess(),
- std::ptr::null(),
- 3 * BLOCK,
- MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
- PAGE_NOACCESS,
- std::ptr::null_mut(),
- 0,
- ) as usize;
- assert_ne!(p, 0);
- let section = CreateFileMappingW(
- -1isize as _,
- std::ptr::null(),
- PAGE_READWRITE,
- 0,
- (2 * BLOCK) as u32,
- std::ptr::null(),
- );
- assert!(!section.is_null());
- (p, section)
- };
- let map = |block: usize| {
- // SAFETY: splits the placeholder at the block and maps the
- // section's block there.
- let view = unsafe {
- VirtualFree(
- (p + block * BLOCK) as *mut _,
- BLOCK,
- MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
- );
- MapViewOfFile3(
- section,
- GetCurrentProcess(),
- (p + block * BLOCK) as *const _,
- (block * BLOCK) as u64,
- BLOCK,
- MEM_REPLACE_PLACEHOLDER,
- PAGE_READWRITE,
- std::ptr::null_mut(),
- 0,
- )
- };
- assert_eq!(view.Value as usize, p + block * BLOCK);
- view
- };
- let first = map(0);
- let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
- let all: Vec<usize> = (0..3).flat_map(pages).collect();
- assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
- assert_eq!(
- guard(p, p + 3 * BLOCK),
- Some(Vec::new()),
- "nothing written since"
- );
- let second = map(1);
- title_memory_remapped(p + BLOCK, BLOCK);
- assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
- assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
- title_memory_unmapping(p, 3 * BLOCK);
- // SAFETY: our views and placeholder.
- unsafe {
- UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
- UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER);
- for block in 0..3 {
- VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
- }
- windows_sys::Win32::Foundation::CloseHandle(section);
- }
- }
- /// A write or mapping that runs past the end of the address space (a
- /// title's `fread` with a huge count) covers up to the end; the sum used
- /// to overflow. Up there no test has guarded blocks.
- #[test]
- fn ranges_past_the_address_space_end_do_not_overflow() {
- let top = usize::MAX - 16;
- writing(top, PAGE);
- title_memory_remapped(top, usize::MAX);
- }
- }
- #[cfg(test)]
- mod mapping_tests {
- use super::{title_memory_reading, title_memory_remapping};
- use std::sync::atomic::{AtomicBool, Ordering};
- use std::sync::{Arc, mpsc};
- use std::time::Duration;
- /// A change of mapping waits for a read in place that is under way, and
- /// a read in place waits for a change of mapping.
- #[test]
- fn reads_in_place_and_remappings_wait_for_each_other() {
- // A reader holds; the change does not begin until it lets go.
- let changed = Arc::new(AtomicBool::new(false));
- let reading = title_memory_reading();
- let (began, wait) = mpsc::channel();
- let change = {
- let changed = changed.clone();
- std::thread::spawn(move || {
- began.send(()).unwrap();
- let _changing = title_memory_remapping();
- changed.store(true, Ordering::SeqCst);
- })
- };
- wait.recv().unwrap();
- std::thread::sleep(Duration::from_millis(100));
- assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place");
- drop(reading);
- change.join().unwrap();
- assert!(changed.load(Ordering::SeqCst));
- // A change holds; the read does not begin until it is done.
- let read = Arc::new(AtomicBool::new(false));
- let changing = title_memory_remapping();
- let (began, wait) = mpsc::channel();
- let reader = {
- let read = read.clone();
- std::thread::spawn(move || {
- began.send(()).unwrap();
- let _reading = title_memory_reading();
- read.store(true, Ordering::SeqCst);
- })
- };
- wait.recv().unwrap();
- std::thread::sleep(Duration::from_millis(100));
- assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping");
- drop(changing);
- reader.join().unwrap();
- assert!(read.load(Ordering::SeqCst));
- }
- }
- #[cfg(test)]
- mod many_askers_tests {
- use super::{PAGE, writes};
- use windows_sys::Win32::System::Memory::*;
- /// Threads that write pages and ask about overlapping ranges at the same
- /// time: whoever wrote a page before asking is told of that write (by
- /// its own asking or by one that took the kernel's answer before it).
- #[test]
- fn no_write_is_lost_between_askers() {
- const MEM_WRITE_WATCH: u32 = 0x20_0000;
- const PAGES: usize = 48;
- const THREADS: usize = 8;
- // SAFETY: a reservation of our own, freed at the end.
- let at = unsafe {
- VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
- } as usize;
- assert!(at != 0 && at.is_multiple_of(PAGE));
- std::thread::scope(|s| {
- for t in 0..THREADS {
- s.spawn(move || {
- let mut last = [0u64; PAGES];
- let mut seed = t as u64 * 7919 + 1;
- let mut next = |n: usize| {
- seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
- (seed >> 33) as usize % n
- };
- for _ in 0..4000 {
- let page = next(PAGES);
- let from = page - next(page.min(12) + 1);
- let to = page + 1 + next((PAGES - page).min(12));
- // SAFETY: committed memory of ours; what the racing
- // writers leave in it does not matter.
- unsafe { ((at + page * PAGE + t * 8) as *mut u64).write_volatile(1) };
- let (now, written) = writes(at + from * PAGE, at + to * PAGE, false).expect("write-watched");
- let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
- assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
- for l in &mut last[from..to] {
- *l = now;
- }
- }
- });
- }
- });
- // SAFETY: the reservation made above.
- unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) };
- }
- /// The same of view memory, which is guarded: what its bits answer
- /// misses no write either, however often blocks are opened and guarded
- /// again between.
- #[test]
- fn no_write_to_views_is_lost_between_askers() {
- const PAGES: usize = 12;
- const THREADS: usize = 8;
- // SAFETY: a view of a section of our own.
- let at = unsafe {
- let section = CreateFileMappingW(
- -1isize as _,
- std::ptr::null(),
- PAGE_READWRITE,
- 0,
- (PAGES * PAGE) as u32,
- std::ptr::null(),
- );
- let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize;
- crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true);
- super::title_memory_remapped(at, PAGES * PAGE);
- crate::title_memory_view(at, PAGES * PAGE, section as usize, 0);
- at
- };
- assert!(at != 0 && at.is_multiple_of(PAGE));
- let by_bits = std::sync::atomic::AtomicUsize::new(0);
- let past = std::sync::atomic::AtomicUsize::new(0);
- std::thread::scope(|s| {
- for t in 0..THREADS {
- let (by_bits, past) = (&by_bits, &past);
- s.spawn(move || {
- let mut last = [0u64; PAGES];
- let mut seed = t as u64 * 7919 + 1;
- let mut next = |n: usize| {
- seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
- (seed >> 33) as usize % n
- };
- for _ in 0..500 {
- let page = next(PAGES);
- let from = page - next(page.min(3) + 1);
- let to = page + 1 + next((PAGES - page).min(3));
- if next(4) != 0 {
- // As in the test above, or after a word of ours,
- // or past the guard.
- let word = at + page * PAGE + t * 8;
- // SAFETY (both): as above.
- // (Waited for: other tests hold changes of mapping.)
- let reading = (next(3) == 0).then(super::title_memory_reading);
- let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8));
- if let Some(to) = beside {
- unsafe { (to as *mut u64).write_volatile(2) };
- super::landed_beside(&[word / 4096], &[(word, 8)]);
- past.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
- assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere");
- } else {
- if next(4) == 0 {
- super::writing(word, 8);
- }
- unsafe { (word as *mut u64).write_volatile(1) };
- }
- } else {
- // Nothing written: what is asked counts as before.
- by_bits.fetch_add(
- usize::from(super::published(at + from * PAGE, at + to * PAGE)),
- std::sync::atomic::Ordering::Relaxed,
- );
- let (now, _) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
- for l in &mut last[from..to] {
- *l = now;
- }
- continue;
- }
- let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
- let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
- assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
- for l in &mut last[from..to] {
- *l = now;
- }
- }
- });
- }
- });
- assert!(by_bits.into_inner() > 0, "the bits answered none");
- assert!(past.into_inner() > 0, "nothing was put past the guards");
- // (The view stays: at its address other tests' memory would be told
- // of these writes.)
- }
- /// A range of a placeholder with views in it is known whole, its holes
- /// among it, until something is mapped into one, unmapped from it or
- /// allocated there. A hole that is no placeholder's is asked about.
- #[test]
- fn holes_are_known_until_the_runtime_tells() {
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- const BLOCKS: usize = 8;
- // SAFETY (all): a placeholder and a section of our own, which stay.
- let (at, section) = unsafe {
- let at = VirtualAlloc2(
- GetCurrentProcess(),
- std::ptr::null(),
- BLOCKS * PAGE,
- MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
- PAGE_NOACCESS,
- std::ptr::null_mut(),
- 0,
- ) as usize;
- let section =
- CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
- (at, section)
- };
- let map = |block: usize| unsafe {
- let to = at + block * PAGE;
- VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
- let view = MapViewOfFile3(
- section,
- GetCurrentProcess(),
- to as *const _,
- (block * PAGE) as u64,
- PAGE,
- MEM_REPLACE_PLACEHOLDER,
- PAGE_READWRITE,
- std::ptr::null_mut(),
- 0,
- );
- assert_eq!(view.Value as usize, to);
- super::title_memory_remapped(to, PAGE);
- };
- map(1);
- map(5);
- assert!(super::placeholder(at / PAGE) && super::placeholder(at / PAGE + 7) && !super::placeholder(at / PAGE + 5));
- let end = at + BLOCKS * PAGE;
- let ask = |since: u64| -> (u64, Vec<usize>) {
- let (now, written) = writes(at, end, true).expect("a view");
- (now, written.into_iter().filter(|w| w.1 > since).map(|w| w.0 - at / PAGE).collect())
- };
- let (first, all) = ask(0);
- assert_eq!(all, (0..BLOCKS).collect::<Vec<_>>());
- assert!(super::published(at, end), "with its holes");
- // Written; mapped into; unmapped.
- unsafe { ((at + 5 * PAGE) as *mut u8).write_volatile(1) };
- assert!(!super::published(at, end));
- let (second, all) = ask(first);
- assert_eq!(all, [5]);
- map(2);
- assert!(!super::published(at, end));
- let (third, all) = ask(second);
- assert_eq!(all, [2]);
- unsafe { ((at + 2 * PAGE) as *mut u8).write_volatile(1) };
- let (fourth, all) = ask(third);
- assert_eq!(all, [2]);
- super::title_memory_unmapping(at + 5 * PAGE, PAGE);
- unsafe {
- let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: (at + 5 * PAGE) as *mut _ };
- UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER);
- }
- let (fifth, all) = ask(fourth);
- assert_eq!(all, [5]);
- assert!(super::published(at, end));
- // Told of memory there, though there is none: asked about again.
- super::title_memory_allocated(at, PAGE);
- assert!(!super::published(at, end));
- let (_, all) = ask(fifth);
- assert_eq!(all, []);
- // A reservation of the ordinary kind is no placeholder.
- let plain = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize;
- assert!(!super::placeholder(plain / PAGE));
- super::look_at_holes();
- assert!(!super::published(at, end), "block 0 stays asked about");
- assert!(super::published(at + PAGE, end), "the others are as they were");
- super::title_memory_unmapping(at, BLOCKS * PAGE);
- }
- /// Pages mapped into a placeholder, written and unmapped again, each by a
- /// thread of its own as the runtime does it, while others ask about all
- /// of it: what was written, and that a page came or went, is told to
- /// whoever asks after it, and blocks are known by their bits meanwhile.
- #[test]
- fn no_mapping_is_lost_between_askers() {
- use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- const BLOCKS: usize = 12;
- // SAFETY (all): a placeholder and a section of our own, which stay.
- let (at, section) = unsafe {
- let at = VirtualAlloc2(
- GetCurrentProcess(),
- std::ptr::null(),
- BLOCKS * PAGE,
- MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
- PAGE_NOACCESS,
- std::ptr::null_mut(),
- 0,
- ) as usize;
- for block in 0..BLOCKS - 1 {
- VirtualFree((at + block * PAGE) as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
- }
- let section =
- CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
- (at, section as usize)
- };
- let end = at + BLOCKS * PAGE;
- let (stop, by_bits) = (AtomicBool::new(false), AtomicUsize::new(0));
- let number = |written: &[(usize, u64)], block: usize| written.iter().find(|w| w.0 == at / PAGE + block).map_or(0, |w| w.1);
- std::thread::scope(|s| {
- let mappers: Vec<_> = (0..4usize)
- .map(|t| {
- let number = &number;
- s.spawn(move || {
- for round in 0..120 {
- let block = t * 3 + round % 3;
- let to = at + block * PAGE;
- let (before, _) = writes(at, end, true).expect("a view");
- unsafe {
- let view = MapViewOfFile3(
- section as _,
- GetCurrentProcess(),
- to as *const _,
- (block * PAGE) as u64,
- PAGE,
- MEM_REPLACE_PLACEHOLDER,
- PAGE_READWRITE,
- std::ptr::null_mut(),
- 0,
- );
- assert_eq!(view.Value as usize, to);
- super::title_memory_remapped(to, PAGE);
- (to as *mut u8).write_volatile(round as u8);
- }
- let (mapped, written) = writes(at, end, true).expect("a view");
- assert!(number(&written, block) > before, "mapped and written: not told");
- unsafe { ((to + 9) as *mut u8).write_volatile(round as u8) };
- let (again, written) = writes(to, to + PAGE, true).expect("a view");
- assert!(number(&written, block) > mapped, "written again: not told");
- super::title_memory_unmapping(to, PAGE);
- unsafe {
- let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: to as *mut _ };
- assert_ne!(UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER), 0);
- }
- let _ = again;
- }
- })
- })
- .collect();
- for t in 0..3usize {
- let (stop, by_bits) = (&stop, &by_bits);
- s.spawn(move || {
- let mut k = t;
- while !stop.load(Ordering::Relaxed) {
- k = (k * 5 + 3) % 64;
- let (from, to) = (at + k % 6 * PAGE, end - k / 8 % 5 * PAGE);
- by_bits.fetch_add(usize::from(super::published(from, to)), Ordering::Relaxed);
- assert!(writes(from, to, true).is_some());
- }
- });
- }
- let failed = mappers.into_iter().map(|m| m.join()).filter(Result::is_err).count();
- stop.store(true, Ordering::Relaxed);
- assert_eq!(failed, 0);
- });
- assert!(by_bits.into_inner() > 0, "the bits answered none");
- // All unmapped: known whole, and nothing but holes.
- writes(at, end, true).expect("a view");
- assert!(super::published(at, end));
- super::title_memory_unmapping(at, BLOCKS * PAGE);
- }
- /// A block's bit goes with everything that makes it the title's to write,
- /// or forgets it.
- #[test]
- fn bits_go_with_the_guard() {
- // SAFETY: a view of a section of our own, which stays.
- let at = unsafe {
- let section =
- CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (2 * PAGE) as u32, std::ptr::null());
- MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * PAGE).Value as usize
- };
- let end = at + 2 * PAGE;
- let takes: [&dyn Fn(); 4] = [
- &|| super::title_memory_remapped(at, PAGE),
- // SAFETY: the view.
- &|| unsafe { ((at + 8) as *mut u8).write_volatile(1) },
- &|| super::writing(at, 1),
- // (Told again, as of a view mapped there next: it is read-only.)
- &|| {
- super::title_memory_unmapping(at, PAGE);
- assert!(!super::published(at, end), "forgotten");
- super::title_memory_remapped(at, PAGE);
- let mut old = 0;
- // SAFETY: the view.
- unsafe { VirtualProtect(at as *const _, PAGE, PAGE_READWRITE, &mut old) };
- },
- ];
- for (i, take) in takes.iter().enumerate() {
- writes(at, end, true).expect("a view");
- assert!(super::published(at, end), "{i}");
- take();
- assert!(!super::published(at, end), "{i}");
- assert!(super::published(at + PAGE, end), "{i}: the other block");
- }
- super::title_memory_unmapping(at, 2 * PAGE);
- }
- /// A range's bits are all of its blocks', whatever lies beside them.
- #[test]
- fn bits_of_ranges() {
- static BITS: super::Bits = super::Bits::new();
- let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1];
- for &b in &blocks {
- assert!(!BITS.all(b, b + 1));
- BITS.set(b);
- assert!(BITS.all(b, b + 1));
- }
- assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538));
- assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5));
- for b in 300..700 {
- BITS.set(b);
- }
- assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701));
- BITS.clear(511);
- assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700));
- assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space");
- }
- }
|