shadow.rs 230 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222
  1. //! Host copies of title buffers (decision 0007, step 3 and "Copies of title
  2. //! memory"). Title buffers are title memory, which the host GPU cannot
  3. //! read, so a buffer a draw uses gets a persistent host buffer of its size
  4. //! on first use (system memory shaders may also write), and the ranges each
  5. //! submission reads (vertex, index and constant data, buffer views) are
  6. //! brought up to date from title memory before it runs: the 64 KiB pages
  7. //! the title wrote since they were last copied ([`crate::watch`]: write
  8. //! watching, or read-only guards on physical-page views), all of it where
  9. //! neither works. A title GPU address inside the buffer is the same offset
  10. //! in its copy. Ranges shaders write go back to title memory after the
  11. //! submission ([`Shadow::gpu_writes`]).
  12. //!
  13. //! shortcut: only the ranges draws are known to read are brought up to
  14. //! date (vertex and index buffer views, constant buffers in tables, root
  15. //! descriptors, buffer views in tables); buffers read through directly
  16. //! indexed heaps keep what their first use copied.
  17. use std::collections::BTreeMap;
  18. use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
  19. use std::sync::{Arc, Mutex, RwLock};
  20. use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
  21. use crate::host::{HostList, host};
  22. use crate::watch::PAGE;
  23. /// A title buffer's host copy.
  24. pub(crate) struct Shadow {
  25. /// The bytes of `buffer`, once asked.
  26. width: std::sync::OnceLock<u64>,
  27. pub(crate) buffer: ID3D12Resource,
  28. data: *mut u8,
  29. gpu: u64,
  30. /// Where the title buffer starts and how long it is.
  31. start: u64,
  32. len: u64,
  33. /// Per page of title memory from `start`'s on: the write-watch asking
  34. /// after which it was last copied (0: never).
  35. copied: Mutex<Vec<u64>>,
  36. /// Two ranges of title memory taken whole, the last one and the longest,
  37. /// and the asking after which each was ([`Shadow::copy_stale`]). A page
  38. /// a range holds in part cannot say so in `copied`. Locked inside
  39. /// `copied`'s lock.
  40. ranged: Mutex<[(usize, usize, u64); 2]>,
  41. /// Whether the memory is write-watched: unknown, yes, no.
  42. watched: AtomicU8,
  43. /// Ranges shaders of a submission not yet copied back may be writing:
  44. /// title memory there is older than the copy.
  45. pending: Mutex<Vec<(usize, usize)>>,
  46. /// With [`relay`]: how many submissions not yet copied back declared
  47. /// each range of `pending` ([`Flights`]). Locked inside `pending`'s
  48. /// lock.
  49. flights: Mutex<Flights>,
  50. /// The copy's bytes before the submission ran, for the ranges its
  51. /// shaders write (`pending`), each at its offset in the copy: what the
  52. /// GPU wrote differs. Room for the whole copy; only those ranges' bytes
  53. /// are set (and read).
  54. before: Mutex<Option<Vec<u8>>>,
  55. /// Held shared while pieces of the copy are landed (`crate::land`), each
  56. /// its own bytes of it on several threads, and alone while title bytes
  57. /// go in under shader writes ([`Shadow::merge_under_writes`]), which
  58. /// takes `before`'s lock too. Taken ahead of that one.
  59. merging: RwLock<()>,
  60. /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot
  61. /// hold the copy's bytes as they are now, and whether the snapshot is
  62. /// counted in [`KEPT_BYTES`].
  63. kept: Mutex<(Vec<bool>, bool)>,
  64. /// When the copy was last asked for (`crate::host::moment`): a window
  65. /// outside buffers nothing asked for in a while, and nothing holds, is
  66. /// let go ([`let_go_idle`]).
  67. used: AtomicU64,
  68. /// The lowest and highest title address asked for in the copy (a
  69. /// window is 4 MiB whatever was asked: measured for the memory line).
  70. asked: [AtomicU64; 2],
  71. /// Asks for the copy that gave no length (root views: they read from
  72. /// their address to the copy's end, whatever lies there).
  73. unsized_asks: AtomicU64,
  74. /// Whether shaders were ever declared to write it.
  75. written: std::sync::atomic::AtomicBool,
  76. /// A number no other copy has had. Its address is no name for a copy:
  77. /// one let go and another made may share it.
  78. id: u64,
  79. /// With [`cards`], for a big title buffer: `buffer` is in the card's
  80. /// own memory, and this is the rest of the copy.
  81. card: Option<Card>,
  82. /// A window of title memory outside buffers, not a title buffer's copy.
  83. window: bool,
  84. /// Of a copy with two sides: only the dwords the title changed go up,
  85. /// as with [`send_changed`] ([`by_address`]).
  86. changes_only: std::sync::atomic::AtomicBool,
  87. /// A window in card memory the CPU maps ([`window_mapped_for`]).
  88. mapped: bool,
  89. /// With `crate::inplace`: not a copy at all. `buffer` is placed in a
  90. /// heap opened on the title memory itself, so shaders read and write
  91. /// the title's own bytes and nothing is copied either way. The heap,
  92. /// and the bytes from the buffer's first byte to `start` (the heap
  93. /// begins on a 64 KiB line; a title buffer need not).
  94. place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>,
  95. }
  96. /// What a copy in the card's memory ([`cards`]) has beside the buffer
  97. /// shaders see.
  98. struct Card {
  99. /// The CPU's side, in the PC's memory: what `data` maps. Title memory
  100. /// is copied into it as into any copy, and what changed in it goes to
  101. /// the card's side before the next submission.
  102. staging: ID3D12Resource,
  103. /// The card side's bytes as they were when the submission's shaders
  104. /// started, in the card's memory too: made when shader writes are
  105. /// first declared for the copy, and compared with the card's side, on
  106. /// the card, after each submission that declares some.
  107. before: Mutex<Option<ID3D12Resource>>,
  108. /// Offsets of the copy whose bytes changed on the CPU's side and have
  109. /// not gone to the card's side yet.
  110. dirty: Mutex<Vec<(usize, usize)>>,
  111. /// With [`relay`]: the offsets that went from `dirty` to the card's
  112. /// side, each with the number of the send that took it
  113. /// ([`card_dirty`]), kept until a fetch sent after it has been merged.
  114. /// Locked inside `dirty`'s lock.
  115. sent: Mutex<SentRuns>,
  116. /// Whether something was put into `dirty` since it was last taken.
  117. touched: std::sync::atomic::AtomicBool,
  118. /// The buffers' bytes (the title buffer's, rounded up to 64 KiB).
  119. size: u64,
  120. }
  121. /// Whether the host copies of big title buffers are in the card's own
  122. /// memory (on by default since run 75 showed it holds: the BVH skinning
  123. /// list went from 50.5 to 4.5 ms on the card; `VICTORY_CARD_BUFFERS=0`
  124. /// keeps every copy in the PC's memory, as before. Read when a copy is
  125. /// made, so it takes a fresh start).
  126. ///
  127. /// Every host copy was a buffer in the PC's memory that the card reads
  128. /// and writes over the bus, so that our code can fill it and compare it.
  129. /// The title's shaders read almost all their buffer data from a few big
  130. /// title buffers (in the gameplay frame of run 69, 190-330 MB of distinct
  131. /// ranges of the 174 MB heap per list against 0-13 MB elsewhere), and a
  132. /// skinning dispatch of ONE group of 32 threads took 1.8 ms on the card
  133. /// (run 70): the time of some 170 loads one after the other, not of the
  134. /// arithmetic.
  135. ///
  136. /// With the switch, a title buffer of [`card_limits`]' size or more has two
  137. /// sides. Shaders see `Shadow::buffer`, in the card's memory. The CPU's
  138. /// side (`Card::staging`, what `Shadow::data` maps) takes title memory as
  139. /// before, and the ranges that changed in it are copied to the card's side
  140. /// before each submission (`Host::card_before`). What shaders wrote is
  141. /// found on the card: after the submission's lists a compute pass of ours
  142. /// compares each declared range, by 64 KiB piece, with the card side's
  143. /// bytes from before (`Card::before`), and only the pieces that differ are
  144. /// fetched and merged into title memory, byte by byte as
  145. /// [`Shadow::copy_back`] does (`Host::card_back`, [`Shadow::card_merge`]).
  146. /// No snapshot is taken and nothing is compared on the CPU for such a copy.
  147. ///
  148. /// What it assumes is what [`keeps`] assumes: shaders write a copy only in
  149. /// ranges declared as written. A write outside them is seen by later
  150. /// shaders, as before, and goes back to the title the next time a declared
  151. /// range holds its piece (before: never).
  152. pub(crate) fn cards() -> bool {
  153. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  154. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_BUFFERS").is_none_or(|v| v != "0"))
  155. }
  156. /// Default `(min_mb, max_mb)` for [`card_limits`] chosen from the adapter's
  157. /// local VRAM budget (`DXGI_QUERY_VIDEO_MEMORY_INFO.Budget`), in bytes.
  158. ///
  159. /// - Unknown (`None`, e.g. WARP) or `<= 12 GiB` (8–12 GB cards, whose WDDM
  160. /// budget is below 12 GiB): `(16, 512)` MiB, matching the 12 GB baseline.
  161. /// - `> 12 GiB` and `< 20 GiB` (16 GB cards, whose WDDM budget is typically
  162. /// ~13.5–15.2 GiB): `(4, 2048)` MiB.
  163. /// - `>= 20 GiB` (24–32+ GB cards): `(1, (budget_mb / 4).min(8192))` MiB,
  164. /// capping at 25% of local budget (at most 8 GiB) so "before" twins (up to 2x)
  165. /// still leave headroom for textures and render targets.
  166. fn default_card_limits_mb(local_vram_budget: Option<u64>) -> (u64, u64) {
  167. let Some(budget_bytes) = local_vram_budget else {
  168. return (16, 512);
  169. };
  170. let budget_mb = budget_bytes >> 20;
  171. const TWELVE_GIB_MB: u64 = 12 * 1024;
  172. const TWENTY_GIB_MB: u64 = 20 * 1024;
  173. if budget_mb <= TWELVE_GIB_MB {
  174. (16, 512)
  175. } else if budget_mb < TWENTY_GIB_MB {
  176. (4, 2048)
  177. } else {
  178. (1, (budget_mb / 4).min(8192))
  179. }
  180. }
  181. /// Resolve `(min_bytes, max_bytes)` from the adapter's local VRAM budget and
  182. /// optional explicit MiB overrides from `VICTORY_CARD_BUFFERS_MIN_MB` /
  183. /// `VICTORY_CARD_BUFFERS_MB`.
  184. fn resolve_card_limits(
  185. local_vram_budget: Option<u64>,
  186. min_mb_override: Option<u64>,
  187. max_mb_override: Option<u64>,
  188. ) -> (u64, u64) {
  189. const MIB: u64 = 1 << 20;
  190. let (default_min_mb, default_max_mb) = default_card_limits_mb(local_vram_budget);
  191. let min_bytes = min_mb_override.unwrap_or(default_min_mb).saturating_mul(MIB).max(MIB);
  192. let max_bytes = max_mb_override.unwrap_or(default_max_mb).saturating_mul(MIB);
  193. (min_bytes, max_bytes)
  194. }
  195. /// The smallest title buffer whose copy goes to the card's memory, and the
  196. /// most bytes of such copies (their "before" twins not counted: a copy
  197. /// shaders write takes its size twice), both in bytes:
  198. /// `VICTORY_CARD_BUFFERS_MIN_MB` and `VICTORY_CARD_BUFFERS_MB`.
  199. /// Defaults scale with the adapter's local VRAM budget (16 MiB / 512 MiB on
  200. /// `<= 12 GiB` budgets, 4 MiB / 2048 MiB on 16 GB cards, 1 MiB / up to 8192 MiB
  201. /// on `>= 20 GiB` budgets), and explicit env vars always override.
  202. fn card_limits() -> (u64, u64) {
  203. static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
  204. *LIMITS.get_or_init(|| {
  205. let env_mb = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok());
  206. let vram_budget = crate::host::host().and_then(|h| h.video_memory()).map(|[budget, ..]| budget);
  207. let (mut min_bytes, max_bytes) = resolve_card_limits(
  208. vram_budget,
  209. env_mb("VICTORY_CARD_BUFFERS_MIN_MB"),
  210. env_mb("VICTORY_CARD_BUFFERS_MB"),
  211. );
  212. if card_all() {
  213. min_bytes = 0;
  214. }
  215. tracing::info!(
  216. vram_budget_mb = vram_budget.map(|b| b >> 20),
  217. card_buffers_min_mb = min_bytes >> 20,
  218. card_buffers_max_mb = max_bytes >> 20,
  219. "card buffer limits"
  220. );
  221. (min_bytes, max_bytes)
  222. })
  223. }
  224. /// Bytes alive of copies' card sides, and of their "before" twins.
  225. static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  226. /// Whether the texture queue leaves room on the card for the card copies
  227. /// of title buffers that are not made yet
  228. /// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default).
  229. ///
  230. /// The copies are made in one burst when the world loads (run 189: 94 of
  231. /// its 95 within two seconds, right before the first world frame), and
  232. /// [`card_for`] makes one only while the card is under eight tenths of its
  233. /// budget. That held as long as the textures picked by index filled the
  234. /// card after the burst. Since the texture queue keeps packed neighbours
  235. /// (52b8060) it fills the card while the world loads: 85% and more at the
  236. /// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked
  237. /// for shader writes in 600 to 720 MB a frame where it had been 30, and
  238. /// the frame went from about 240 to 370-470 ms.
  239. ///
  240. /// With the switch, the texture queue's rule (`resource::room`) counts the
  241. /// part of [`card_limits`]' second number that no copy has taken yet as
  242. /// used, and a copy may be made up to nine tenths of the budget: the room
  243. /// it takes was kept for it. After the burst what is kept is what the
  244. /// burst left of the limit (87 MB of 1,024 in run 189).
  245. ///
  246. /// On by default from the build after run 199
  247. /// (`VICTORY_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies
  248. /// and the world's render targets (+1,603 MB) arrive in the same first
  249. /// world frame and raced for the 448 MB left under the line, and a copy
  250. /// turned down is not asked for again (`lookup` asks once), while its room
  251. /// went on being kept (616 MB to the end of the run). So now: the texture
  252. /// queue also keeps room for the targets (`resource::targets_room_kept`),
  253. /// a copy is made up to 97 hundredths of the budget (its room was kept),
  254. /// and the room of a copy turned down is given up ([`CARD_REFUSED`]).
  255. fn card_room_kept_on() -> bool {
  256. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  257. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0"))
  258. }
  259. /// Title buffers big enough for a copy in the card's memory that were
  260. /// turned down for want of room, since the start, and their bytes: their
  261. /// copies stay in the PC's memory for as long as the title keeps the
  262. /// buffers, so no room is kept for them any more.
  263. static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  264. /// The bytes of the card's memory the texture queue leaves free for card
  265. /// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with
  266. /// the switch off or without card copies.
  267. pub(crate) fn card_room_kept() -> u64 {
  268. if !card_room_kept_on() || !cards() {
  269. return 0;
  270. }
  271. // Not more than such copies came to in any session, whatever they may
  272. // come to: on a card of 24 GB a quarter of its budget was kept for them,
  273. // 5 GB that never came (941 MB in 97 copies after fifteen minutes), and
  274. // no texture was made any more with 5 GB of the card free (session
  275. // play-1125-0127: 1,453 passes refused, the ground and people black).
  276. const SEEN: u64 = 1 << 30;
  277. card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed))
  278. }
  279. /// The copies in the card's memory.
  280. static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
  281. /// Since the last frame line: bytes copied to card sides and the ranges
  282. /// they were; pieces compared on the card, pieces fetched and their
  283. /// bytes; the waits for the card the fetches added and their microseconds.
  284. pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
  285. /// [`CARD_STATS`], taken; then the copies in the card's memory, their
  286. /// bytes and their "before" twins' bytes.
  287. pub(crate) fn card_stats() -> [u64; 10] {
  288. let mut out = [0u64; 10];
  289. for (i, stat) in CARD_STATS.iter().enumerate() {
  290. out[i] = stat.swap(0, Ordering::Relaxed);
  291. }
  292. out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64;
  293. out[8] = CARD_BYTES[0].load(Ordering::Relaxed)
  294. + WINDOW_CARD_BYTES.load(Ordering::Relaxed)
  295. + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed);
  296. out[9] = CARD_BYTES[1].load(Ordering::Relaxed);
  297. out
  298. }
  299. /// The bytes of the hashes kept on the card for a copy of `size` bytes: 16
  300. /// for each 64 KiB piece (a copy that does not start on a piece boundary
  301. /// has one piece more).
  302. pub(crate) fn card_hash_bytes(size: u64) -> u64 {
  303. (size / PIECE as u64 + 2) * 16
  304. }
  305. /// A buffer of `size` bytes in the card's memory for a title buffer's
  306. /// copy, if the copy is to be there: [`cards`] is on, the size is within
  307. /// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the
  308. /// host has what it takes (`Host::card_ready`).
  309. fn card_for(size: u64) -> Option<ID3D12Resource> {
  310. let there = card_room_for(size);
  311. if there.is_some() || !card_all() || size >= 1 << 30 {
  312. return there;
  313. }
  314. // Two sides all the same, the card's in the PC's memory.
  315. let host = host()?;
  316. if !cards() || !host.card_ready() {
  317. return None;
  318. }
  319. let (buffer, _) = host.shared_buffer(size)?;
  320. CARD_BYTES[0].fetch_add(size, Ordering::Relaxed);
  321. Some(buffer)
  322. }
  323. /// Whether every title buffer's copy has two sides, however small
  324. /// (`VICTORY_CARD_ALL=1`; off by default).
  325. ///
  326. /// A copy with one side, in the PC's memory, is what the card reads while
  327. /// our refreshes write it: a submission that is prepared changes it under
  328. /// the ones in the air ahead of it. The title's CPU does not write what they
  329. /// still read, but its own buffer copies are done by us at preparing
  330. /// (`crate::host::send` has the order of those right for copies with two
  331. /// sides), and so are the bytes put in beside shaders' writes.
  332. fn card_all() -> bool {
  333. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  334. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"))
  335. }
  336. /// [`card_for`] in the card's own memory.
  337. fn card_room_for(size: u64) -> Option<ID3D12Resource> {
  338. if !cards() {
  339. return None;
  340. }
  341. let (least, most) = card_limits();
  342. if size < least || size >= 1 << 30 {
  343. return None;
  344. }
  345. let host = host()?;
  346. if !host.card_ready() {
  347. return None;
  348. }
  349. // Only while the card has room: with this copy on it, a fifth of the
  350. // budget the system gives us must still be free. Copies are made when
  351. // the world loads, before the textures fill the card; the texture
  352. // queue's own rule (`resource::room`: nine tenths of the budget) counts
  353. // them, so the card's use stays where it was and the textures' share
  354. // shrinks by the copies' bytes, at most `card_limits`' second number.
  355. // (With `card_room_kept_on` the texture queue kept this copy's room
  356. // free, and the copy may go up to the queue's own line.)
  357. let hundredths = if card_room_kept_on() { 97 } else { 80 };
  358. if let Some([budget, used, ..]) = host.video_memory()
  359. && used + size > budget / 100 * hundredths
  360. {
  361. // Said, with the numbers it was decided by: run 193 made 31 copies
  362. // of 95 and no line named the others. The first 64, then every
  363. // 32nd.
  364. let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1;
  365. let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size;
  366. if n <= 64 || n.is_multiple_of(32) {
  367. tracing::info!(
  368. "no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \
  369. {} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}",
  370. size >> 10,
  371. used >> 20,
  372. budget >> 20,
  373. (budget / 100 * hundredths) >> 20,
  374. CARD_BYTES[0].load(Ordering::Relaxed) >> 20,
  375. most >> 20,
  376. n,
  377. bytes >> 20,
  378. crate::frame::current()
  379. );
  380. }
  381. return None;
  382. }
  383. if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most {
  384. CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
  385. return None;
  386. }
  387. let buffer = host.uav_buffer(size);
  388. if buffer.is_none() {
  389. CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
  390. }
  391. buffer
  392. }
  393. /// The most bytes of windows outside buffers whose copies go to the card's
  394. /// memory (`VICTORY_CARD_WINDOWS_MB`; 0, the default, none).
  395. ///
  396. /// Windows are two thirds of the PC memory the card shares (run 104: 861
  397. /// windows, 3,552 MB of 5,400), and every draw that takes vertices, indices
  398. /// or constants from the title's own allocator reads them over the bus.
  399. /// Shaders write none of them (run 91: "0.0 MB compared in 0 ranges of
  400. /// windows"), so a window on the card needs only what a card copy has
  401. /// already: the CPU's side takes title memory as before, and what changed
  402. /// in it goes up before each submission. No hashes, no compare, no fetch,
  403. /// unless a shader does declare a write to it one day.
  404. ///
  405. /// A window goes to the card while there is room under this number and
  406. /// while a fifth of the card's budget is free, as title buffers do
  407. /// (`card_for`): textures keep their room, and once they have filled the
  408. /// card later windows stay where they are. The CPU's side stays in the PC's
  409. /// memory, so the memory shared with the card does not shrink by this
  410. /// alone; what moves is what shaders read.
  411. fn window_card_most() -> u64 {
  412. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  413. *MOST.get_or_init(|| {
  414. std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20
  415. })
  416. }
  417. /// Bytes alive of windows' card sides ([`window_card_most`]).
  418. static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0);
  419. /// A buffer in the card's memory for a window of `size` bytes, if it is to
  420. /// be there ([`window_card_most`]).
  421. fn window_card_for(size: u64) -> Option<ID3D12Resource> {
  422. let there = window_room_for(size);
  423. if there.is_some() || !windows_own() || !cards() {
  424. return there;
  425. }
  426. // Two sides all the same, the card's in the PC's memory.
  427. let host = host()?;
  428. if !host.card_ready() {
  429. return None;
  430. }
  431. let (buffer, _) = host.shared_buffer(size)?;
  432. WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed);
  433. Some(buffer)
  434. }
  435. /// The most bytes of windows outside buffers that lie in the card's memory
  436. /// and are filled by the CPU through the bus (`VICTORY_WINDOWS_BAR_MB`; 0, the
  437. /// default, none): one buffer (`D3D12_HEAP_TYPE_GPU_UPLOAD`), no CPU's side, no
  438. /// copy to send and no list of changes, unlike [`window_card_most`]. The CPU
  439. /// only writes them, as no shader is declared to write a window; if one were,
  440. /// its snapshot and compare would read through the bus, right but slow. In a
  441. /// captured frame the lists take 26 ms of the card instead of 29, the frame 32
  442. /// instead of 36; filling them costs the CPU what it did.
  443. ///
  444. /// Windows go there while a fifth of the card's budget is free, as with
  445. /// [`window_room_for`], which this comes before.
  446. fn window_mapped_most() -> u64 {
  447. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  448. *MOST.get_or_init(|| {
  449. std::env::var("VICTORY_WINDOWS_BAR_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20
  450. })
  451. }
  452. /// Bytes alive of windows in card memory the CPU maps.
  453. static WINDOW_MAPPED_BYTES: AtomicU64 = AtomicU64::new(0);
  454. /// A buffer for a window of `size` bytes in card memory the CPU maps, if it is
  455. /// to be there ([`window_mapped_most`]).
  456. fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  457. let most = window_mapped_most();
  458. if most == 0 {
  459. return None;
  460. }
  461. let host = host()?;
  462. if let Some([budget, used, ..]) = host.video_memory()
  463. && used + size > budget / 10 * 8
  464. {
  465. return None;
  466. }
  467. if WINDOW_MAPPED_BYTES.fetch_add(size, Ordering::Relaxed) + size > most {
  468. WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed);
  469. return None;
  470. }
  471. let made = host.mapped_card_buffer(size, true);
  472. if made.is_none() {
  473. WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed);
  474. }
  475. made
  476. }
  477. /// Whether windows outside buffers have two sides too, so that submissions
  478. /// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`;
  479. /// off by default: it takes the windows' bytes again, 3.3 GB in capture
  480. /// replay2, and what changes in them under submissions in the air is what the
  481. /// title's CPU writes, which it does not while they read it).
  482. fn windows_own() -> bool {
  483. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  484. *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOWS_OWN").is_some_and(|v| v == "1"))
  485. }
  486. /// [`window_card_for`] in the card's own memory.
  487. fn window_room_for(size: u64) -> Option<ID3D12Resource> {
  488. let most = window_card_most();
  489. if most == 0 || !cards() {
  490. return None;
  491. }
  492. let host = host()?;
  493. if !host.card_ready() {
  494. return None;
  495. }
  496. if let Some([budget, used, ..]) = host.video_memory()
  497. && used + size > budget / 10 * 8
  498. {
  499. return None;
  500. }
  501. if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most {
  502. WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed);
  503. return None;
  504. }
  505. let buffer = host.uav_buffer(size);
  506. if buffer.is_none() {
  507. WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed);
  508. }
  509. buffer
  510. }
  511. /// What went up, by send: its number, and the offsets, in order and joined
  512. /// (a refresh sends thousands of runs of a few words).
  513. #[derive(Default)]
  514. struct SentRuns(Vec<(u64, Vec<(usize, usize)>)>);
  515. impl SentRuns {
  516. fn note(&mut self, number: u64, ranges: Vec<(usize, usize)>) {
  517. if ranges.is_empty() {
  518. return;
  519. }
  520. let ranges = joined(ranges);
  521. match self.0.iter_mut().find(|s| s.0 == number) {
  522. Some((_, all)) => *all = joined([std::mem::take(all), ranges].concat()),
  523. None => self.0.push((number, ranges)),
  524. }
  525. }
  526. /// Sends up to `number` are of no use any more.
  527. fn forget(&mut self, number: u64) {
  528. self.0.retain(|s| s.0 > number);
  529. }
  530. /// Adds to `out` what sends after `number` took of `[from, to)`.
  531. fn near(&self, number: u64, from: usize, to: usize, out: &mut Vec<(usize, usize)>) {
  532. for (_, ranges) in self.0.iter().filter(|s| s.0 > number) {
  533. let first = ranges.partition_point(|r| r.1 <= from);
  534. out.extend(ranges[first..].iter().take_while(|r| r.0 < to).copied());
  535. }
  536. }
  537. #[cfg(test)]
  538. fn of(all: &[(usize, usize, u64)]) -> SentRuns {
  539. let mut sent = SentRuns::default();
  540. for &(a, b, number) in all {
  541. sent.note(number, vec![(a, b)]);
  542. }
  543. sent
  544. }
  545. }
  546. /// The copies in the card's memory whose CPU side changed since they were
  547. /// last asked: each with the changed offsets, in order and joined where
  548. /// they touch. The ranges are taken: the caller copies them to the card's
  549. /// side (`Host::card_before`).
  550. ///
  551. /// With [`relay`], `sent_as` is the number of the send that takes them
  552. /// (`crate::host`'s order of the queue): each range is noted with it, in
  553. /// the same lock that took it, so that a merge of pieces fetched before
  554. /// that send knows the card did not hold these bytes yet
  555. /// ([`Shadow::card_merge_relay`]). Notes of sends that every fetch still to
  556. /// be merged came after are dropped.
  557. pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)> {
  558. let mut out = Vec::new();
  559. let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner());
  560. let fetched = RELAY_FETCHED.load(Ordering::Acquire);
  561. carded.retain(|weak| {
  562. let Some(shadow) = weak.upgrade() else {
  563. return false;
  564. };
  565. let ranges = shadow
  566. .card
  567. .as_ref()
  568. .filter(|c| c.touched.swap(false, Ordering::AcqRel))
  569. .map(|c| {
  570. let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner());
  571. let ranges = std::mem::take(&mut *dirty);
  572. if relay() {
  573. let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner());
  574. sent.forget(fetched);
  575. sent.note(sent_as, ranges.clone());
  576. }
  577. ranges
  578. })
  579. .unwrap_or_default();
  580. if !ranges.is_empty() {
  581. out.push((shadow, joined(ranges)));
  582. }
  583. true
  584. });
  585. out
  586. }
  587. /// Diagnostics (`crate::host::upcheck`, nothing in the air): copies whose
  588. /// pages the write watch and the guards hold for unchanged since they were
  589. /// taken, compared with title memory, `most` bytes a call in turn. `say` gets
  590. /// the copy, the title address of a page that is not the same, the words that
  591. /// differ and the first of them (its address, the copy's value, title
  592. /// memory's). Returns the bytes compared.
  593. pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize, (usize, u32, u32))) -> usize {
  594. static NEXT: AtomicU64 = AtomicU64::new(0);
  595. let mut all: Vec<Arc<Shadow>> = buffers_read().values().filter_map(|e| e.shadow.clone()).collect();
  596. all.extend(LOOSE.write().unwrap_or_else(|e| e.into_inner()).values().cloned());
  597. all.retain(|s| s.place.is_none() && s.watched.load(Ordering::Relaxed) == 1);
  598. all.sort_by_key(|s| s.id);
  599. let next = NEXT.load(Ordering::Relaxed);
  600. let turn = all.partition_point(|s| s.id < next);
  601. let mut done = 0;
  602. let mut title = vec![0u8; PAGE];
  603. for shadow in all[turn..].iter().chain(&all[..turn]) {
  604. if done >= most {
  605. NEXT.store(shadow.id, Ordering::Relaxed);
  606. break;
  607. }
  608. let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
  609. // (What it finds written stays noted for the next refresh.)
  610. let Some((_, written)) = crate::watch::writes(start, end, true) else {
  611. continue;
  612. };
  613. let written: std::collections::HashMap<usize, u64> = written.into_iter().collect();
  614. let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone();
  615. for (i, &at) in copied.iter().enumerate() {
  616. let page = start / PAGE + i;
  617. if at == 0 || written.get(&page).is_some_and(|&w| w > at) {
  618. continue;
  619. }
  620. let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end));
  621. let title = &mut title[..hi - lo];
  622. if !crate::host::read_into(lo as *const u8, title) {
  623. continue;
  624. }
  625. done += hi - lo;
  626. // SAFETY: inside the mapping; nothing is in the air and the
  627. // submission lock is held.
  628. let held = unsafe { std::slice::from_raw_parts(shadow.data.add(lo - start).cast_const(), hi - lo) };
  629. if held == title {
  630. continue;
  631. }
  632. let word = |b: &[u8], k: usize| u32::from_le_bytes([b[k], b[k + 1], b[k + 2], b[k + 3]]);
  633. let differ: Vec<usize> = (0..(hi - lo) & !3).step_by(4).filter(|&k| word(held, k) != word(title, k)).collect();
  634. // Written meanwhile: not stale, and the next refresh sees it.
  635. let again = crate::watch::writes(lo, hi, true).is_none_or(|(_, w)| w.iter().any(|&(p, w)| p == page && w > at));
  636. if let Some(&k) = differ.first()
  637. && !again
  638. {
  639. say(shadow, lo, differ.len(), (lo + k, word(held, k), word(title, k)));
  640. }
  641. }
  642. }
  643. done
  644. }
  645. /// Copies of memory (from, to, bytes: apart), on several threads if they are
  646. /// many.
  647. pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) {
  648. let bytes: usize = copies.iter().map(|c| c.2).sum();
  649. if bytes > 4 << 20 {
  650. wide(copy_jobs(copies));
  651. return;
  652. }
  653. for (src, dst, len) in copies {
  654. // SAFETY: the caller's ranges.
  655. unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) };
  656. }
  657. }
  658. /// A title buffer copy was done on the CPU into `[dst, dst + len)`: all of it
  659. /// goes up to the copies in the card's memory that hold it, whether their
  660. /// CPU side held the same before or not. Left out is what shaders in the air
  661. /// may be writing (such a copy waits for them, or is done on the card).
  662. pub(crate) fn send_copied(dst: usize, len: usize) {
  663. for shadow in carded_copies() {
  664. let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
  665. let (from, to) = (dst.max(start), (dst + len).min(end));
  666. if from >= to {
  667. continue;
  668. }
  669. let busy: Vec<(usize, usize)> =
  670. shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect();
  671. for (a, b) in outside(from, to, busy) {
  672. shadow.copy(a, b);
  673. }
  674. }
  675. }
  676. /// The copies in the card's memory (diagnostics: `crate::host::upcheck`).
  677. pub(crate) fn carded_copies() -> Vec<Arc<Shadow>> {
  678. CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect()
  679. }
  680. /// Ranges in order, those that overlap or touch as one.
  681. fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
  682. ranges.sort_unstable();
  683. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  684. for (from, to) in ranges {
  685. match out.last_mut() {
  686. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  687. _ => out.push((from, to)),
  688. }
  689. }
  690. out
  691. }
  692. /// Runs of pieces to hash again (`Host::card_before`), those that overlap
  693. /// or touch as one, in order: every piece of `runs` is in the result once
  694. /// and no other piece is. Ranges sent up lie close together (514 a frame
  695. /// for 87 MB in run 102), and each had a pass of its own over its pieces,
  696. /// so a piece that held several ranges was hashed once for each.
  697. pub(crate) fn joined_piece_runs(mut runs: Vec<CardSpan>) -> Vec<CardSpan> {
  698. runs.sort_unstable_by_key(|r| r.first);
  699. let mut out: Vec<CardSpan> = Vec::with_capacity(runs.len());
  700. for run in runs {
  701. match out.last_mut() {
  702. Some(last) if run.first <= last.first + last.pieces => {
  703. last.pieces = last.pieces.max(run.first + run.pieces - last.first);
  704. last.to = last.to.max(run.to);
  705. }
  706. _ => out.push(run),
  707. }
  708. }
  709. out
  710. }
  711. /// A declared range of a copy in the card's memory, as the compare on the
  712. /// card takes it: its offsets in the copy, its first 64 KiB piece (pieces
  713. /// are cut at multiples of 64 KiB of title memory; piece 0 holds offset
  714. /// 0), how many pieces hold it, and where the copy starts in piece 0.
  715. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  716. pub(crate) struct CardSpan {
  717. pub(crate) from: u32,
  718. pub(crate) to: u32,
  719. pub(crate) first: u32,
  720. pub(crate) pieces: u32,
  721. pub(crate) skew: u32,
  722. }
  723. /// [`CardSpan`] for offsets `[from, to)` (`from < to`) of a copy of title
  724. /// memory from `start` on.
  725. fn card_span_of(start: usize, from: usize, to: usize) -> CardSpan {
  726. let pieces = pieces_of(start, from, to);
  727. CardSpan {
  728. from: from as u32,
  729. to: to as u32,
  730. first: pieces.start as u32,
  731. pieces: pieces.len() as u32,
  732. skew: (start % PIECE) as u32,
  733. }
  734. }
  735. /// The offsets of piece `i` of `span` that lie in the span, for a copy of
  736. /// `len` bytes of title memory from `start` on: what is fetched and merged
  737. /// of a piece the compare found differing.
  738. fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, usize) {
  739. let (lo, hi) = piece_at(start, len, (span.first + i) as usize);
  740. (lo.max(span.from as usize), hi.min(span.to as usize))
  741. }
  742. /// The offsets [`Shadow::card_hashed`] gives, for a card's buffer of `size`
  743. /// bytes for title memory from `start` on.
  744. fn card_hashed_of(start: usize, size: usize, piece: usize) -> (usize, usize) {
  745. let (lo, hi) = piece_at(start, size, piece);
  746. (lo & !15, hi.next_multiple_of(16))
  747. }
  748. #[cfg(test)]
  749. mod card_tests {
  750. use super::{CardSpan, PIECE, card_hashed_of, card_piece_of, card_span_of, joined, joined_piece_runs};
  751. /// Joined runs hold every piece of the runs given, once, and no other.
  752. #[test]
  753. fn piece_runs_join_without_losing_or_adding_pieces() {
  754. let run = |first: u32, pieces: u32| CardSpan {
  755. from: first * 65536,
  756. to: (first + pieces) * 65536,
  757. first,
  758. pieces,
  759. skew: 7,
  760. };
  761. let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)];
  762. let mut wanted: Vec<u32> = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect();
  763. wanted.sort_unstable();
  764. wanted.dedup();
  765. let joined = joined_piece_runs(runs);
  766. let got: Vec<u32> = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect();
  767. assert_eq!(got, wanted);
  768. assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::<Vec<_>>(), [(3, 5), (9, 1), (40, 3), (100, 1)]);
  769. assert!(joined.iter().all(|r| r.skew == 7));
  770. assert!(joined_piece_runs(Vec::new()).is_empty());
  771. }
  772. /// The offsets the compare's shader takes for a piece (`CARD_COMPARE`
  773. /// in host.rs), before it widens them to 16 bytes.
  774. fn shader_piece(span: &CardSpan, i: u32) -> (u32, u32) {
  775. let piece = span.first + i;
  776. let lo = piece * 65536;
  777. let lo = if lo > span.skew { lo - span.skew } else { 0 };
  778. let hi = (piece + 1) * 65536 - span.skew;
  779. (lo.max(span.from), hi.min(span.to))
  780. }
  781. /// The pieces of a span cover it without gaps, and the shader's
  782. /// arithmetic names the same bytes as ours.
  783. #[test]
  784. fn the_shader_and_the_merge_cut_the_same_pieces() {
  785. for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] {
  786. let len = 5 * PIECE + 4096;
  787. for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] {
  788. let span = card_span_of(start, from, to);
  789. let mut at = from;
  790. for i in 0..span.pieces {
  791. let (lo, hi) = card_piece_of(start, len, &span, i);
  792. assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}");
  793. assert!(hi > lo && hi - lo <= PIECE);
  794. assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}");
  795. at = hi;
  796. }
  797. assert_eq!(at, to, "{start:#x} {from} {to}");
  798. }
  799. }
  800. }
  801. /// Changed ranges are joined where they overlap or touch, and only there.
  802. /// What is fetched of a piece to hash it is what the shader hashes.
  803. #[test]
  804. fn a_piece_is_hashed_here_as_on_the_card() {
  805. for start in [0usize, 0x10_0000, 0xd_5edb_c780, 0x12_3456_7008] {
  806. for size in [1usize << 16, 5 << 16, 0x20_0000] {
  807. let span = card_span_of(start, 0, size);
  808. for i in 0..span.pieces {
  809. // As `CARD_COMPARE` has it.
  810. let (piece, skew, size) = (span.first + i, span.skew, size as u32);
  811. let lo = (piece * 65536).saturating_sub(skew);
  812. let hi = ((piece + 1) * 65536 - skew).min(size);
  813. let shader = (lo & !15, (hi + 15) & !15);
  814. let here = card_hashed_of(start, size as usize, piece as usize);
  815. assert_eq!((here.0 as u32, here.1 as u32), shader, "start {start:#x} size {size:#x} piece {piece}");
  816. }
  817. }
  818. }
  819. }
  820. #[test]
  821. fn ranges_join_where_they_touch() {
  822. assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]);
  823. assert!(joined(Vec::new()).is_empty());
  824. }
  825. }
  826. /// Whether the copy-back of what shaders wrote runs on a thread of its own,
  827. /// beside the submitting thread and outside the submission lock
  828. /// (`VICTORY_RELAY=1` or `2`; off by default; not with kept snapshots,
  829. /// [`keeps`]). `crate::host::relay` says what it does; here it changes
  830. /// what a copy keeps:
  831. ///
  832. /// - the ranges shaders may be writing are counted per submission
  833. /// ([`Flights`]): a range two flights declared stays closed to refreshes
  834. /// until both have been copied back;
  835. /// - the merge of what the card wrote never stores into memory the card
  836. /// may be writing ([`merge_piece`]): what it learns goes into title
  837. /// memory and into the copy's reference (the snapshot, or the CPU's side
  838. /// of a copy in the card's memory), under that reference's lock;
  839. /// - what goes up to a copy in the card's memory is numbered
  840. /// ([`card_dirty`]), so that a merge can tell the title's bytes the card
  841. /// had not received from bytes the card wrote.
  842. pub(crate) fn relay() -> bool {
  843. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  844. // On by default (stage 2, `crate::host::relay_exact`); `VICTORY_RELAY=0`
  845. // turns it off, `=1` asks for the first stage.
  846. // The crate's own tests run without it unless they ask: several of
  847. // them look at title memory right after a submission, which the
  848. // relay's landing thread may still be writing.
  849. *ON.get_or_init(|| std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps())
  850. }
  851. /// The submission being prepared (its number among those started): what
  852. /// [`Shadow::writing`] counts a declared range for ([`Flights`]).
  853. static PREPARED: AtomicU64 = AtomicU64::new(0);
  854. /// A submission's preparing begins (`crate::host`, under the submission
  855. /// lock).
  856. pub(crate) fn preparing(number: u64) {
  857. PREPARED.store(number, Ordering::Relaxed);
  858. }
  859. /// With [`relay`]: the number of the last send of changed ranges to the
  860. /// card (`crate::host`'s order of the queue) that every fetch still to be
  861. /// merged came after. Notes of sends up to it are of no use any more.
  862. static RELAY_FETCHED: AtomicU64 = AtomicU64::new(0);
  863. /// A fetch sent after send `number` is the oldest one that may still be
  864. /// merged ([`RELAY_FETCHED`]).
  865. pub(crate) fn relay_fetched(number: u64) {
  866. RELAY_FETCHED.fetch_max(number, Ordering::AcqRel);
  867. }
  868. /// With [`relay`]: how many submissions that are not copied back yet
  869. /// declared each range shaders may be writing (range, count, the last
  870. /// submission that declared it).
  871. ///
  872. /// Without it a range declared by two flights was one entry, and the end
  873. /// of the first flight's copy-back removed it while the second was still
  874. /// writing: the next refresh would have put title bytes over what the
  875. /// second flight's shaders were writing.
  876. #[derive(Default)]
  877. struct Flights(std::collections::HashMap<(usize, usize), (u32, u64)>);
  878. impl Flights {
  879. /// Submission `number` declares `range`: counted once for it, however
  880. /// often it declares it.
  881. fn declare(&mut self, range: (usize, usize), number: u64) {
  882. let f = self.0.entry(range).or_insert((0, number));
  883. if f.0 == 0 || f.1 != number {
  884. *f = (f.0 + 1, number);
  885. }
  886. }
  887. /// One submission that declared `ranges` (each once) is copied back:
  888. /// the ranges no other submission still holds, in order.
  889. fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> {
  890. let mut free = Vec::new();
  891. for range in ranges {
  892. match self.0.get_mut(range) {
  893. Some(f) if f.0 > 1 => f.0 -= 1,
  894. Some(_) => {
  895. self.0.remove(range);
  896. free.push(*range);
  897. }
  898. // Not counted (declared before anything counted): free.
  899. None => free.push(*range),
  900. }
  901. }
  902. free.sort_unstable();
  903. free
  904. }
  905. }
  906. /// The relay's merge of a stretch of a copy ([`relay`]). `now` is what the
  907. /// card's memory holds, read once; `held` is the copy's reference for the
  908. /// stretch (its snapshot, or the CPU's side of a copy in the card's
  909. /// memory): what the card's memory held when it was last looked at;
  910. /// `title` is title memory as just read. Every byte the card changed
  911. /// (`now` differs from `held`) goes into `title` and into `held`; every
  912. /// other byte of both stays as it is, so a byte the title wrote and the
  913. /// card did not keeps the title's value. Whether `title` changed.
  914. ///
  915. /// Nothing is stored into `now`'s source: the card may be writing it for a
  916. /// later flight at this moment, and a store there, even of the value just
  917. /// read, could undo that write. (The merge of a waited-for submission
  918. /// stores every byte of a differing stretch back into the copy.)
  919. fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool {
  920. let mut differs = 0u8;
  921. for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) {
  922. let wrote = if *n != *h { 0xffu8 } else { 0 };
  923. let merged = (*t & !wrote) | (*n & wrote);
  924. differs |= merged ^ *t;
  925. *t = merged;
  926. *h = (*h & !wrote) | (*n & wrote);
  927. }
  928. differs != 0
  929. }
  930. /// `[from, to)` without the ranges of `skip`, in order.
  931. fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
  932. skip.sort_unstable();
  933. let mut out = Vec::new();
  934. let mut at = from;
  935. for (a, b) in skip {
  936. if b <= at {
  937. continue;
  938. }
  939. if a >= to {
  940. break;
  941. }
  942. if a > at {
  943. out.push((at, a));
  944. }
  945. at = at.max(b);
  946. }
  947. if at < to {
  948. out.push((at, to));
  949. }
  950. out
  951. }
  952. #[cfg(test)]
  953. mod relay_tests {
  954. use super::{Flights, changed_runs, merge_piece, outside};
  955. /// A range two flights declared is free only when both are done, in
  956. /// either order; a submission that declares it many times counts once.
  957. #[test]
  958. fn a_range_stays_closed_until_every_flight_that_declared_it_is_done() {
  959. let (a, b) = ((0x1000, 0x2000), (0x1800, 0x3000));
  960. let mut flights = Flights::default();
  961. for _ in 0..3 {
  962. flights.declare(a, 7);
  963. }
  964. flights.declare(b, 7);
  965. flights.declare(a, 8);
  966. // Flight 7 lands: `a` is still flight 8's, `b` was only flight 7's.
  967. assert_eq!(flights.done(&[a, b]), vec![b]);
  968. // Declared again meanwhile by a third.
  969. flights.declare(a, 9);
  970. assert_eq!(flights.done(&[a]), vec![]);
  971. assert_eq!(flights.done(&[a]), vec![a]);
  972. assert!(flights.0.is_empty());
  973. // The later flight first: the same.
  974. flights.declare(a, 1);
  975. flights.declare(a, 2);
  976. assert_eq!(flights.done(&[a]), vec![]);
  977. assert_eq!(flights.done(&[a]), vec![a]);
  978. // A range never counted is free at once.
  979. assert_eq!(flights.done(&[b]), vec![b]);
  980. }
  981. /// The merge moves exactly the bytes the card changed, into title
  982. /// memory and into the reference, and stores nothing else.
  983. #[test]
  984. fn the_merge_stores_only_what_the_card_changed() {
  985. let held0: Vec<u8> = (0..200u32).map(|i| (i * 5 + 1) as u8).collect();
  986. let mut now = held0.clone();
  987. for at in [0usize, 3, 4, 5, 64, 199] {
  988. now[at] ^= 0x33;
  989. }
  990. // The title wrote other bytes meanwhile, and one the card wrote too.
  991. let mut title = held0.clone();
  992. for at in [1usize, 5, 100] {
  993. title[at] = 0xee;
  994. }
  995. let title0 = title.clone();
  996. let mut held = held0.clone();
  997. assert!(merge_piece(&now, &mut held, &mut title));
  998. for at in 0..200 {
  999. if now[at] != held0[at] {
  1000. assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}");
  1001. } else {
  1002. assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}");
  1003. }
  1004. }
  1005. // Again with nothing new: nothing changes and nothing is reported.
  1006. let (title1, held1) = (title.clone(), held.clone());
  1007. assert!(!merge_piece(&now, &mut held, &mut title));
  1008. assert_eq!((title, held), (title1, held1));
  1009. }
  1010. #[test]
  1011. fn ranges_are_cut_out() {
  1012. assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]);
  1013. assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]);
  1014. assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]);
  1015. assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]);
  1016. }
  1017. /// A model of a copy in the PC's memory under the relay: the card
  1018. /// writes `copy` directly; `snap` is the snapshot; `title` is title
  1019. /// memory. Flight A and flight B declare overlapping ranges and both
  1020. /// are in the air; the title's CPU writes in between and its bytes are
  1021. /// put in beside the flights' (`merge_under_writes`: into the copy and
  1022. /// the snapshot); A lands while B is still writing; then B lands.
  1023. #[test]
  1024. fn two_flights_overlapping_ranges_and_a_cpu_write_in_between() {
  1025. const N: usize = 64;
  1026. let base: Vec<u8> = (0..N as u32).map(|i| i as u8).collect();
  1027. let (mut copy, mut title) = (base.clone(), base.clone());
  1028. // A declares [0, 40), B declares [24, 64): each byte's snapshot is
  1029. // taken when the first range that holds it is declared.
  1030. let (a, b) = ((0usize, 40usize), (24usize, 64usize));
  1031. let mut snap = base.clone();
  1032. // The card runs A: writes 4..12 and 30..34.
  1033. for at in (4..12).chain(30..34) {
  1034. copy[at] = 0xa0;
  1035. }
  1036. // The title's CPU writes 8..10 (over A's bytes), 20 and 50, after
  1037. // A's refresh: the next submission's preparing finds them against
  1038. // the snapshot and puts them in, into the copy and the snapshot.
  1039. for at in [8usize, 9, 20, 50] {
  1040. title[at] = 0x77;
  1041. }
  1042. for (at, n) in changed_runs(&title, &snap) {
  1043. copy[at..at + n].copy_from_slice(&title[at..at + n]);
  1044. snap[at..at + n].copy_from_slice(&title[at..at + n]);
  1045. }
  1046. // The card starts B: it has written 32..36 so far, over A's 32..34.
  1047. for at in 32..36 {
  1048. copy[at] = 0xb0;
  1049. }
  1050. // A lands (B still on the card): its range is merged. The copy is
  1051. // read once and not written.
  1052. let seen = copy.clone();
  1053. {
  1054. let mut t = title[a.0..a.1].to_vec();
  1055. assert!(merge_piece(&seen[a.0..a.1], &mut snap[a.0..a.1], &mut t));
  1056. title[a.0..a.1].copy_from_slice(&t);
  1057. }
  1058. assert_eq!(copy, seen, "the merge stores nothing into the copy");
  1059. // A's bytes are in title memory, except where the title wrote
  1060. // after A's shaders did (8, 9: the title's); B's first bytes came
  1061. // along; nothing of B's range beyond A's was touched.
  1062. for at in (4..8).chain(10..12).chain(30..32) {
  1063. assert_eq!(title[at], 0xa0, "A's byte at {at}");
  1064. }
  1065. assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77));
  1066. for at in 32..36 {
  1067. assert_eq!(title[at], 0xb0, "B's byte so far at {at}");
  1068. }
  1069. // The card finishes B: 36..44.
  1070. for at in 36..44 {
  1071. copy[at] = 0xb1;
  1072. }
  1073. // The title's CPU writes 40 after B's shader did: found against
  1074. // the snapshot at the next preparing, which is before B lands.
  1075. title[40] = 0x55;
  1076. for (at, n) in changed_runs(&title[b.0..b.1], &snap[b.0..b.1]) {
  1077. let at = at + b.0;
  1078. copy[at..at + n].copy_from_slice(&title[at..at + n]);
  1079. snap[at..at + n].copy_from_slice(&title[at..at + n]);
  1080. }
  1081. // B lands.
  1082. let seen = copy.clone();
  1083. {
  1084. let mut t = title[b.0..b.1].to_vec();
  1085. assert!(merge_piece(&seen[b.0..b.1], &mut snap[b.0..b.1], &mut t));
  1086. title[b.0..b.1].copy_from_slice(&t);
  1087. }
  1088. // B's results are there, never replaced by A's older ones.
  1089. for at in 32..36 {
  1090. assert_eq!(title[at], 0xb0);
  1091. }
  1092. for at in (36..40).chain(41..44) {
  1093. assert_eq!(title[at], 0xb1, "B's byte at {at}");
  1094. }
  1095. assert_eq!(title[40], 0x55, "the title wrote it last");
  1096. // In the declared ranges the copy, the snapshot and title memory
  1097. // now agree byte for byte: nothing is left to hand back, and
  1098. // nothing was lost.
  1099. assert_eq!(copy[a.0..b.1], title[a.0..b.1]);
  1100. assert_eq!(snap[a.0..b.1], title[a.0..b.1]);
  1101. // A third merge finds nothing.
  1102. let mut t = title.clone();
  1103. assert!(!merge_piece(&copy, &mut snap, &mut t));
  1104. }
  1105. /// A model of a copy in the card's memory under the relay: `card` is
  1106. /// the card's side, `cpu` the CPU's side, `title` title memory. The
  1107. /// title's changed bytes go into the CPU's side at once and up to the
  1108. /// card with a later send; pieces fetched before that send must not
  1109. /// take the card's older bytes there for something the card wrote.
  1110. #[test]
  1111. fn title_bytes_not_yet_on_the_card_are_not_taken_for_shader_writes() {
  1112. const N: usize = 48;
  1113. let base: Vec<u8> = (0..N as u32).map(|i| (i + 100) as u8).collect();
  1114. let (mut card, mut cpu, mut title) = (base.clone(), base.clone(), base.clone());
  1115. // Flight A's shaders write 10..14 on the card.
  1116. for at in 10..14 {
  1117. card[at] = 0xa0;
  1118. }
  1119. // The title's CPU writes 12 (over A's) and 30; the preparing of
  1120. // the next submission puts both into the CPU's side and notes them
  1121. // to go up (send 5). They are not on the card yet.
  1122. title[12] = 0x77;
  1123. title[30] = 0x78;
  1124. let mut noted = Vec::new();
  1125. for (at, n) in changed_runs(&title, &cpu) {
  1126. cpu[at..at + n].copy_from_slice(&title[at..at + n]);
  1127. noted.push((at, at + n, 5u64));
  1128. }
  1129. // A's pieces are fetched after send 4, before send 5: the fetch
  1130. // holds A's bytes and the card's old bytes at 12 and 30.
  1131. let fetched = card.clone();
  1132. let fetched_after = 4u64;
  1133. // Send 5 goes up behind it.
  1134. for &(a, b, _) in &noted {
  1135. card[a..b].copy_from_slice(&cpu[a..b]);
  1136. }
  1137. // The merge leaves out what went up after the fetch.
  1138. let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect();
  1139. let mut changed = false;
  1140. for (a, b) in outside(0, N, skip) {
  1141. let mut t = title[a..b].to_vec();
  1142. changed |= merge_piece(&fetched[a..b], &mut cpu[a..b], &mut t);
  1143. title[a..b].copy_from_slice(&t);
  1144. }
  1145. assert!(changed);
  1146. // A's bytes arrived; the title's two writes stand, in title memory
  1147. // and on both sides of the copy.
  1148. for at in [10usize, 11, 13] {
  1149. assert_eq!((title[at], cpu[at]), (0xa0, 0xa0));
  1150. }
  1151. assert_eq!((title[12], cpu[12], card[12]), (0x77, 0x77, 0x77));
  1152. assert_eq!((title[30], cpu[30], card[30]), (0x78, 0x78, 0x78));
  1153. assert_eq!(card, cpu);
  1154. assert_eq!(card, title);
  1155. // Without the leaving out, the card's old byte at 30 would have
  1156. // been taken for a shader write and put over the title's.
  1157. let mut wrong_title = title.clone();
  1158. let mut wrong_cpu = cpu.clone();
  1159. merge_piece(&fetched, &mut wrong_cpu, &mut wrong_title);
  1160. assert_eq!(wrong_title[30], base[30]);
  1161. }
  1162. }
  1163. /// Snapshot memory kept for reuse (already touched, so no page faults).
  1164. static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
  1165. /// An empty buffer with room for `n` bytes, from the pool if it has one
  1166. /// of about that size: a small copy's snapshot took the 174 MB buffer kept
  1167. /// for the big heap's, which then got another, until eight of them were
  1168. /// reserved (1.4 GB in run 24).
  1169. fn pooled(n: usize) -> Vec<u8> {
  1170. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  1171. let most = n.saturating_mul(4).max(1 << 20);
  1172. let fit = pool
  1173. .iter()
  1174. .enumerate()
  1175. .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most)
  1176. .min_by_key(|(_, v)| v.capacity())
  1177. .map(|(i, _)| i);
  1178. let mut v = match fit {
  1179. Some(i) => pool.swap_remove(i),
  1180. None => Vec::with_capacity(n),
  1181. };
  1182. v.clear();
  1183. v
  1184. }
  1185. /// How many snapshot buffers are kept (`VICTORY_SNAPSHOT_POOL`; `8`: as
  1186. /// before).
  1187. ///
  1188. /// A frame gives some 330 ranges of copies in the PC's memory to shaders, and
  1189. /// most are of copies of their own; with two or three frames in the air eight
  1190. /// buffers were the eight largest, and every other snapshot was memory fresh
  1191. /// from the kernel and given back to it: 11 % of the submitting thread in the
  1192. /// opening (profile cpu-1: `NtAllocateVirtualMemory` under
  1193. /// [`Shadow::writing`]), and the page faults of filling it.
  1194. fn snapshots_kept() -> usize {
  1195. static MOST: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  1196. *MOST.get_or_init(|| std::env::var("VICTORY_SNAPSHOT_POOL").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1024))
  1197. }
  1198. /// Returns a snapshot buffer to the pool: at most [`snapshots_kept`] kept,
  1199. /// the largest, and of those the largest one and the next ones up to `KEPT`
  1200. /// bytes in all.
  1201. fn give_back(v: Vec<u8>) {
  1202. const KEPT: usize = 512 << 20;
  1203. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  1204. pool.push(v);
  1205. pool.sort_by_key(|v| std::cmp::Reverse(v.capacity()));
  1206. let (mut kept, mut total) = (0, 0usize);
  1207. for v in pool.iter().take(snapshots_kept()) {
  1208. total = total.saturating_add(v.capacity());
  1209. if kept > 0 && total > KEPT {
  1210. break;
  1211. }
  1212. kept += 1;
  1213. }
  1214. // (Given back to the kernel without the lock: milliseconds.)
  1215. let gone = pool.split_off(kept);
  1216. drop(pool);
  1217. drop(gone);
  1218. }
  1219. const NOT_WATCHED: u8 = 2;
  1220. /// Watched, not by the kernel but by the guards, when last asked about.
  1221. const GUARDED: u8 = 3;
  1222. // Fixed-size equality compiles to two SIMD comparisons on Windows x64.
  1223. // Only the first or last unequal chunk needs a byte-wise search.
  1224. const DIFF_CHUNK: usize = 32;
  1225. /// Where `a` and `b` first differ within their common length.
  1226. fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> {
  1227. let len = a.len().min(b.len());
  1228. let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
  1229. let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
  1230. let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) {
  1231. Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]),
  1232. None => (len - a_tail.len(), a_tail, b_tail),
  1233. };
  1234. a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i)
  1235. }
  1236. /// Where `a` and `b` last differ within their common length.
  1237. fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> {
  1238. let len = a.len().min(b.len());
  1239. let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
  1240. let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
  1241. if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) {
  1242. return Some(len - a_tail.len() + i);
  1243. }
  1244. let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?;
  1245. a_chunks[chunk]
  1246. .iter()
  1247. .zip(&b_chunks[chunk])
  1248. .rposition(|(x, y)| x != y)
  1249. .map(|i| chunk * DIFF_CHUNK + i)
  1250. }
  1251. #[cfg(test)]
  1252. mod difference_tests {
  1253. use super::{first_difference, last_difference};
  1254. /// The chunk searches agree with a byte-wise scan across chunk boundaries.
  1255. #[test]
  1256. fn differences_are_found_as_byte_by_byte() {
  1257. let base: Vec<u8> = (0..98u32).map(|i| (i * 7 + 3) as u8).collect();
  1258. for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] {
  1259. let a = &base[1..1 + len];
  1260. let same = a.to_vec();
  1261. assert_eq!(first_difference(&same, a), None);
  1262. assert_eq!(last_difference(&same, a), None);
  1263. for at in 0..len {
  1264. for other in at..len {
  1265. let mut b = a.to_vec();
  1266. b[at] ^= 0x80;
  1267. b[other] ^= 0x01;
  1268. let first = a.iter().zip(&b).position(|(x, y)| x != y);
  1269. let last = a.iter().zip(&b).rposition(|(x, y)| x != y);
  1270. assert_eq!(first_difference(a, &b), first, "{len} {at} {other}");
  1271. assert_eq!(last_difference(a, &b), last, "{len} {at} {other}");
  1272. }
  1273. }
  1274. }
  1275. }
  1276. #[test]
  1277. fn differences_ignore_bytes_past_the_shorter_slice() {
  1278. let a = [0; 65];
  1279. let mut b = [0; 67];
  1280. b[65] = 1;
  1281. assert_eq!(first_difference(&a, &b), None);
  1282. assert_eq!(last_difference(&b, &a), None);
  1283. b[32] = 1;
  1284. b[64] = 1;
  1285. assert_eq!(first_difference(&b, &a), Some(32));
  1286. assert_eq!(last_difference(&a, &b), Some(64));
  1287. }
  1288. }
  1289. /// The unit shader writes are looked for and put back in.
  1290. const PIECE: usize = 64 << 10;
  1291. /// Calls `f` with `[from, to)` cut at multiples of [`PIECE`].
  1292. fn for_pieces_of(from: usize, to: usize, mut f: impl FnMut(usize, usize)) {
  1293. let mut at = from;
  1294. while at < to {
  1295. let next = ((at / PIECE + 1) * PIECE).min(to);
  1296. f(at, next);
  1297. at = next;
  1298. }
  1299. }
  1300. /// Copies `len` bytes, on several threads if they are many: a snapshot of
  1301. /// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and
  1302. /// one thread copies some 8 GB/s.
  1303. ///
  1304. /// # Safety
  1305. /// Both ranges are valid for `len` bytes and do not overlap.
  1306. unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) {
  1307. const PER_THREAD: usize = 16 << 20;
  1308. let threads = (len / PER_THREAD).clamp(1, 6);
  1309. if threads == 1 {
  1310. // SAFETY: the caller's.
  1311. unsafe { std::ptr::copy_nonoverlapping(src, dst, len) };
  1312. return;
  1313. }
  1314. let (src, dst, each) = (src as usize, dst as usize, len.div_ceil(threads));
  1315. std::thread::scope(|s| {
  1316. for i in 0..threads {
  1317. let at = (i * each).min(len);
  1318. let n = each.min(len - at);
  1319. s.spawn(move || {
  1320. // SAFETY: a part of the caller's ranges.
  1321. unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) };
  1322. });
  1323. }
  1324. });
  1325. }
  1326. /// Whether the snapshots of a submission's shader-written ranges, and the
  1327. /// compare that finds what the shaders wrote, run on several threads
  1328. /// across ranges (`VICTORY_WIDE_BACK=1`; off by default).
  1329. ///
  1330. /// Both ran range by range on the submitting thread, a range on several
  1331. /// threads only if it was 16 MiB or more. The ranges left on the CPU's side
  1332. /// since the big buffers went to the card are small and many: in run 86,
  1333. /// 7,024 declared ranges a frame, 375 MB of them compared after the card
  1334. /// ran in 563 pieces of work, none of 16 MiB: 51 ms a frame of snapshots
  1335. /// and 35 ms of comparing, one thread, bound by one core's memory speed.
  1336. ///
  1337. /// With the switch a submission's snapshots are noted as it is prepared
  1338. /// and taken together when its refreshes are done, just before it goes to
  1339. /// the card ([`take_snapshots`]), and the compares of everything declared
  1340. /// run together after the card ([`find_all`]), both cut into pieces of
  1341. /// work of about 1 MiB for a few threads that are kept ([`wide`]). The
  1342. /// bytes taken and the bytes compared are the same ones: a range's bytes
  1343. /// cannot change between the moment it is declared and the end of the
  1344. /// preparing (a declared range is left alone by every refresh, the title's
  1345. /// own copies write title memory and not the copy, and the card runs the
  1346. /// lists only afterwards).
  1347. pub(crate) fn wide_back() -> bool {
  1348. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1349. // On by default; `VICTORY_WIDE_BACK=0` turns it off.
  1350. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_none_or(|v| v != "0"))
  1351. }
  1352. type Job = Box<dyn FnOnce() + Send>;
  1353. /// Threads kept for [`wide`]: what they are to do, and the word that there
  1354. /// is something.
  1355. struct Workers {
  1356. jobs: Mutex<std::collections::VecDeque<Job>>,
  1357. more: std::sync::Condvar,
  1358. }
  1359. /// How many threads are kept for [`wide`].
  1360. fn wide_threads() -> usize {
  1361. std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6)
  1362. }
  1363. fn workers() -> &'static Workers {
  1364. static WORKERS: std::sync::OnceLock<Workers> = std::sync::OnceLock::new();
  1365. static STARTED: std::sync::Once = std::sync::Once::new();
  1366. let workers = WORKERS.get_or_init(|| Workers {
  1367. jobs: Mutex::new(std::collections::VecDeque::new()),
  1368. more: std::sync::Condvar::new(),
  1369. });
  1370. STARTED.call_once(|| {
  1371. for i in 0..wide_threads() {
  1372. let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || {
  1373. crate::cores::keep_helper_on_fast_cores("victory-wide");
  1374. let workers = WORKERS.get().expect("made above");
  1375. loop {
  1376. let job = {
  1377. let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
  1378. loop {
  1379. if let Some(job) = jobs.pop_front() {
  1380. break job;
  1381. }
  1382. jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
  1383. }
  1384. };
  1385. let _working = crate::timeline::span("a job for another thread");
  1386. job();
  1387. }
  1388. });
  1389. }
  1390. });
  1391. workers
  1392. }
  1393. /// Runs `jobs` on the kept threads and on this one, and returns when all
  1394. /// of them are done. The jobs copy and compare memory; they do not panic.
  1395. fn wide(jobs: Vec<Job>) {
  1396. if jobs.len() < 2 {
  1397. for job in jobs {
  1398. job();
  1399. }
  1400. return;
  1401. }
  1402. let workers = workers();
  1403. let _wide = crate::timeline::span("work spread over threads");
  1404. let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new()));
  1405. {
  1406. let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
  1407. for job in jobs {
  1408. let left = left.clone();
  1409. queue.push_back(Box::new(move || {
  1410. job();
  1411. let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
  1412. *n -= 1;
  1413. if *n == 0 {
  1414. left.1.notify_all();
  1415. }
  1416. }));
  1417. }
  1418. }
  1419. workers.more.notify_all();
  1420. loop {
  1421. let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
  1422. match job {
  1423. Some(job) => job(),
  1424. None => break,
  1425. }
  1426. }
  1427. let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
  1428. while *n > 0 {
  1429. n = left.1.wait(n).unwrap_or_else(|e| e.into_inner());
  1430. }
  1431. }
  1432. /// [`wide`], for the host's own work on host copies (a submission's
  1433. /// refreshes, the merge of what shaders wrote to card copies).
  1434. pub(crate) fn wide_run(jobs: Vec<Box<dyn FnOnce() + Send>>) {
  1435. wide(jobs);
  1436. }
  1437. /// Calls `work` with every number under `n`, on the kept threads and on
  1438. /// this one, the next number to whichever is free: for thousands of small
  1439. /// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue.
  1440. pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) {
  1441. let next = Arc::new(std::sync::atomic::AtomicUsize::new(0));
  1442. let work = Arc::new(work);
  1443. let threads = (wide_threads() + 1).min(n);
  1444. let jobs = (0..threads)
  1445. .map(|_| {
  1446. let (next, work) = (next.clone(), work.clone());
  1447. Box::new(move || {
  1448. loop {
  1449. let i = next.fetch_add(1, Ordering::Relaxed);
  1450. if i >= n {
  1451. break;
  1452. }
  1453. work(i);
  1454. }
  1455. }) as Job
  1456. })
  1457. .collect();
  1458. wide(jobs);
  1459. }
  1460. /// About this many bytes to a piece of work for [`wide`].
  1461. const WIDE_JOB: usize = 1 << 20;
  1462. /// With [`wide_back`]: the snapshots noted while a submission is prepared
  1463. /// (from, to, bytes), taken by [`take_snapshots`].
  1464. static SNAPS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new());
  1465. /// With [`wide_back`], when a submission's refreshes are done and before
  1466. /// its lists go to the card: takes the snapshots [`Shadow::writing`] noted.
  1467. /// Nothing to do without the switch.
  1468. pub(crate) fn take_snapshots() {
  1469. let snaps = std::mem::take(&mut *SNAPS.lock().unwrap_or_else(|e| e.into_inner()));
  1470. if snaps.is_empty() {
  1471. return;
  1472. }
  1473. wide(copy_jobs(snaps));
  1474. }
  1475. /// `copies` (from, to, bytes) as pieces of work of about [`WIDE_JOB`]
  1476. /// bytes each: long ones cut, short ones together.
  1477. fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec<Job> {
  1478. let mut jobs: Vec<Job> = Vec::new();
  1479. let mut group: Vec<(usize, usize, usize)> = Vec::new();
  1480. let mut bytes = 0;
  1481. let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec<Job>| {
  1482. let group = std::mem::take(group);
  1483. if !group.is_empty() {
  1484. jobs.push(Box::new(move || {
  1485. for (src, dst, len) in group {
  1486. // SAFETY: the caller's ranges: a host copy's mapping and
  1487. // its snapshot, which do not overlap.
  1488. unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) };
  1489. }
  1490. }));
  1491. }
  1492. };
  1493. for (src, dst, len) in copies {
  1494. let mut at = 0;
  1495. while at < len {
  1496. let n = (WIDE_JOB - bytes).min(len - at);
  1497. group.push((src + at, dst + at, n));
  1498. at += n;
  1499. bytes += n;
  1500. if bytes >= WIDE_JOB {
  1501. flush(&mut group, &mut jobs);
  1502. bytes = 0;
  1503. }
  1504. }
  1505. }
  1506. flush(&mut group, &mut jobs);
  1507. jobs
  1508. }
  1509. /// With [`wide_back`]: for each of `work` (a copy not in the card's memory
  1510. /// and a range `[address, end)` its shaders may have written, declared and
  1511. /// not yet done), the 64 KiB pieces that differ from the snapshot, as
  1512. /// [`Shadow::copy_back_with`] takes them; found on several threads.
  1513. pub(crate) fn find_all(work: &[(Arc<Shadow>, usize, usize)]) -> Vec<Vec<(usize, usize)>> {
  1514. let scans = work
  1515. .iter()
  1516. .map(|(shadow, address, end)| {
  1517. let (from, to) = shadow.inside(*address, end.saturating_sub(*address));
  1518. // The snapshot's memory stays until the range is done with
  1519. // (`copy_back_done`), which comes after this.
  1520. match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
  1521. Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to),
  1522. None => (0, 0, 0, 0, 0),
  1523. }
  1524. })
  1525. .collect();
  1526. find_pieces(scans)
  1527. }
  1528. /// For each of `scans` (where a copy's bytes are, where its snapshot's
  1529. /// are, the title address the copy starts at, offsets from and to): the
  1530. /// 64 KiB pieces (cut at multiples of 64 KiB of title memory, as
  1531. /// [`Shadow::differing`] cuts them) of `[from, to)` whose bytes differ, as
  1532. /// (offset, bytes) in order. On several threads ([`wide`]), in pieces of
  1533. /// work of about [`WIDE_JOB`] bytes that hold whole pieces.
  1534. fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec<Vec<(usize, usize)>> {
  1535. // What a job finds: (which scan, its place among that scan's jobs, the
  1536. // pieces).
  1537. type Found = Vec<(usize, usize, Vec<(usize, usize)>)>;
  1538. // A job's part of a scan: the scan, then which and place.
  1539. type Part = (usize, usize, usize, usize, usize, usize, usize);
  1540. let found: Arc<Mutex<Found>> = Arc::default();
  1541. let mut jobs: Vec<Job> = Vec::new();
  1542. let mut group: Vec<Part> = Vec::new();
  1543. let mut bytes = 0;
  1544. let flush = |group: &mut Vec<Part>, jobs: &mut Vec<Job>| {
  1545. let group = std::mem::take(group);
  1546. if group.is_empty() {
  1547. return;
  1548. }
  1549. let found = found.clone();
  1550. jobs.push(Box::new(move || {
  1551. let mut mine: Found = Vec::with_capacity(group.len());
  1552. for (data, before, start, from, to, which, place) in group {
  1553. let mut pieces = Vec::new();
  1554. let mut at = from;
  1555. while at < to {
  1556. let n = (PIECE - (start + at) % PIECE).min(to - at);
  1557. // SAFETY: inside the copy's mapping and its snapshot
  1558. // (which holds the copy's bytes at the copy's offsets);
  1559. // nothing writes either while a submission's results
  1560. // are compared.
  1561. let (now, old) = unsafe {
  1562. (
  1563. std::slice::from_raw_parts((data + at) as *const u8, n),
  1564. std::slice::from_raw_parts((before + at) as *const u8, n),
  1565. )
  1566. };
  1567. if now != old {
  1568. pieces.push((at, n));
  1569. }
  1570. at += n;
  1571. }
  1572. mine.push((which, place, pieces));
  1573. }
  1574. found.lock().unwrap_or_else(|e| e.into_inner()).extend(mine);
  1575. }));
  1576. };
  1577. let count = scans.len();
  1578. for (which, (data, before, start, from, to)) in scans.into_iter().enumerate() {
  1579. let (mut at, mut place) = (from, 0);
  1580. while at < to {
  1581. // Cut where pieces end, so that every job sees whole pieces.
  1582. let room = (WIDE_JOB - bytes).max(PIECE);
  1583. let mut next = (at + room).min(to);
  1584. if next < to {
  1585. next -= (start + next) % PIECE;
  1586. if next <= at {
  1587. next = (at + PIECE - (start + at) % PIECE).min(to);
  1588. }
  1589. }
  1590. group.push((data, before, start, at, next, which, place));
  1591. bytes += next - at;
  1592. place += 1;
  1593. at = next;
  1594. if bytes >= WIDE_JOB {
  1595. flush(&mut group, &mut jobs);
  1596. bytes = 0;
  1597. }
  1598. }
  1599. }
  1600. flush(&mut group, &mut jobs);
  1601. wide(jobs);
  1602. let mut found = std::mem::take(&mut *found.lock().unwrap_or_else(|e| e.into_inner()));
  1603. found.sort_unstable_by_key(|f| (f.0, f.1));
  1604. let mut out = vec![Vec::new(); count];
  1605. for (which, _, pieces) in found {
  1606. out[which].extend(pieces);
  1607. }
  1608. out
  1609. }
  1610. /// Since the last frame-rate line, of the shader-written ranges looked for
  1611. /// on the CPU (copies not in the card's memory): bytes snapshotted in
  1612. /// windows outside buffers and in title buffers' copies; bytes compared in
  1613. /// windows, in buffers' copies, and of those in copies of 1 MiB or more;
  1614. /// ranges compared in windows and in buffers' copies.
  1615. static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
  1616. /// For the frame-rate line: where the CPU's search for shader writes goes
  1617. /// (per frame). A copy of a title buffer can go to the card's memory,
  1618. /// where the card does the search (`VICTORY_CARD_BUFFERS_MIN_MB`); a
  1619. /// window outside buffers cannot as the code stands.
  1620. pub(crate) fn back_line(frames: f64) {
  1621. let c: Vec<f64> = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  1622. if c.iter().all(|&v| v == 0.0) {
  1623. return;
  1624. }
  1625. let mb = |v: f64| v / (1 << 20) as f64;
  1626. tracing::info!(
  1627. "shader writes looked for on the CPU per frame: {:.1} MB compared in {:.0} ranges of windows outside buffers ({:.1} MB \
  1628. snapshotted), {:.1} MB in {:.0} ranges of title buffers' copies ({:.1} MB snapshotted), of them {:.1} MB in copies \
  1629. of 1 MiB or more (VICTORY_CARD_BUFFERS_MIN_MB=1 would have the card look there)",
  1630. mb(c[2]),
  1631. c[5],
  1632. mb(c[0]),
  1633. mb(c[3]),
  1634. c[6],
  1635. mb(c[1]),
  1636. mb(c[4]),
  1637. );
  1638. }
  1639. #[cfg(test)]
  1640. mod wide_tests {
  1641. use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide};
  1642. use std::sync::Arc;
  1643. use std::sync::atomic::{AtomicUsize, Ordering};
  1644. /// Every job runs once, however many there are, and `wide` returns
  1645. /// only when all have.
  1646. #[test]
  1647. fn all_jobs_run_before_wide_returns() {
  1648. for n in [0usize, 1, 2, 7, 300] {
  1649. let ran = Arc::new(AtomicUsize::new(0));
  1650. let jobs: Vec<Job> = (0..n)
  1651. .map(|i| {
  1652. let ran = ran.clone();
  1653. Box::new(move || {
  1654. ran.fetch_add(i + 1, Ordering::Relaxed);
  1655. }) as Job
  1656. })
  1657. .collect();
  1658. wide(jobs);
  1659. assert_eq!(ran.load(Ordering::Relaxed), n * (n + 1) / 2, "{n} jobs");
  1660. }
  1661. }
  1662. /// Copies cut into jobs copy every byte once: long ones, short ones
  1663. /// and empty ones.
  1664. #[test]
  1665. fn copies_cut_into_jobs_copy_the_same_bytes() {
  1666. let len = 3 * WIDE_JOB + 12345;
  1667. let src: Vec<u8> = (0..len).map(|i| (i * 31 + i / 977) as u8).collect();
  1668. let mut dst = vec![0u8; len];
  1669. let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize);
  1670. // Ranges of the buffer, each to the same offsets of the other.
  1671. let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len];
  1672. let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect();
  1673. let jobs = copy_jobs(copies);
  1674. assert!(jobs.len() >= 3);
  1675. wide(jobs);
  1676. assert!(src == dst);
  1677. }
  1678. /// The pieces found on several threads are the ones a walk piece by
  1679. /// piece finds, for copies that start anywhere in a 64 KiB piece of
  1680. /// title memory and ranges that start and end anywhere.
  1681. #[test]
  1682. fn pieces_found_wide_are_those_found_one_by_one() {
  1683. let len = 5 * WIDE_JOB / 2 + 777;
  1684. let old: Vec<u8> = (0..len).map(|i| (i * 7 + i / 513) as u8).collect();
  1685. let mut now = old.clone();
  1686. // Changes: single bytes at piece edges, a run across two pieces,
  1687. // the last byte, and nothing in between.
  1688. for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] {
  1689. now[at] ^= 0x5a;
  1690. }
  1691. for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] {
  1692. *byte ^= 0x01;
  1693. }
  1694. let (data, before) = (now.as_ptr() as usize, old.as_ptr() as usize);
  1695. let mut scans = Vec::new();
  1696. let mut wanted = Vec::new();
  1697. for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] {
  1698. for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] {
  1699. scans.push((data, before, start, from, to));
  1700. let mut pieces = Vec::new();
  1701. let mut at = from;
  1702. while at < to {
  1703. let n = (PIECE - (start + at) % PIECE).min(to - at);
  1704. if now[at..at + n] != old[at..at + n] {
  1705. pieces.push((at, n));
  1706. }
  1707. at += n;
  1708. }
  1709. wanted.push(pieces);
  1710. }
  1711. }
  1712. // A scan of nothing (a range whose snapshot is gone).
  1713. scans.push((0, 0, 0, 0, 0));
  1714. wanted.push(Vec::new());
  1715. assert_eq!(find_pieces(scans), wanted);
  1716. }
  1717. }
  1718. /// What [`Shadow::copy_back`] does with a piece that differs from the
  1719. /// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From
  1720. /// the first byte that differs to the last, title memory is read into
  1721. /// `title` (scratch, sized to that stretch) by `read` (the stretch's offset
  1722. /// in the piece, where to), the GPU's bytes are put in and `host` takes the
  1723. /// result. The stretch's offset in the piece and its length if that changed
  1724. /// title memory; none if nothing differs or title memory is not there.
  1725. /// `runs` takes the runs of the stretch (offsets into `title`, lengths)
  1726. /// whose bytes are the GPU's and differ from the title's as read: only
  1727. /// those are to be written, so a title write that lands between the read
  1728. /// and the write elsewhere in the stretch stays (upstream VIctory #2009).
  1729. /// `mask` is scratch.
  1730. fn back_piece(
  1731. host: &mut [u8],
  1732. old: &[u8],
  1733. title: &mut Vec<u8>,
  1734. mask: &mut Vec<u8>,
  1735. runs: &mut Vec<(usize, usize)>,
  1736. read: impl FnOnce(usize, &mut [u8]) -> bool,
  1737. ) -> Option<(usize, usize)> {
  1738. runs.clear();
  1739. // From the first byte that differs to the last: title memory is read
  1740. // and written there only (a shader that sets a few words of a piece
  1741. // cost a read, a walk and a write of all 64 KiB of it).
  1742. let first = first_difference(host, old)?;
  1743. let last = last_difference(host, old).unwrap_or(first);
  1744. let n = last + 1 - first;
  1745. let (host, old) = (&mut host[first..=last], &old[first..=last]);
  1746. title.clear();
  1747. title.resize(n, 0);
  1748. if !read(first, title) {
  1749. return None;
  1750. }
  1751. // Title memory with the GPU's bytes put in; the copy takes the title's
  1752. // bytes in turn.
  1753. // Without a branch, so the loop runs many bytes at a time: the GPU's
  1754. // byte where the copy's byte is not what it was before the submission
  1755. // and the title left its byte as it was, else the title's. (With the
  1756. // two searches above this was 44 ms a frame for 970 pieces.)
  1757. // Where the shader and the title both changed a byte while the GPU ran,
  1758. // the title's stays: the shader computed its byte from the copy's older
  1759. // data (one cleared a bit of a record the title had already replaced,
  1760. // and copying it back broke the title's object: an access violation
  1761. // through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2).
  1762. mask.clear();
  1763. mask.resize(n, 0);
  1764. let mut differs = 0u8;
  1765. for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) {
  1766. let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 };
  1767. let merged = (*t & !gpu) | (*h & gpu);
  1768. *m = merged ^ *t;
  1769. differs |= *m;
  1770. *t = merged;
  1771. *h = merged;
  1772. }
  1773. if differs == 0 {
  1774. return None;
  1775. }
  1776. let mut i = 0;
  1777. while i < n {
  1778. while i < n && mask[i] == 0 {
  1779. i += 1;
  1780. }
  1781. let start = i;
  1782. while i < n && mask[i] != 0 {
  1783. i += 1;
  1784. }
  1785. if i > start {
  1786. runs.push((start, i - start));
  1787. }
  1788. }
  1789. Some((first, n))
  1790. }
  1791. /// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages
  1792. /// compared, changed runs put in, and their bytes.
  1793. static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  1794. /// Why [`Shadow::merge_under_writes`] last left the caller to wait.
  1795. static STALE_WHY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
  1796. fn note_stale(why: usize) {
  1797. STALE_WHY.store(why, Ordering::Relaxed);
  1798. }
  1799. /// [`STALE_WHY`] in words (diagnostics).
  1800. #[cfg(feature = "diagnostics")]
  1801. pub(crate) fn stale_why() -> &'static str {
  1802. const WHY: [&str; 4] = [
  1803. "the memory is not watched",
  1804. "the journal does not say what was written",
  1805. "more changed runs than a submission sends up",
  1806. "no snapshot",
  1807. ];
  1808. WHY[STALE_WHY.load(Ordering::Relaxed).min(3)]
  1809. }
  1810. /// [`MERGED`], taken.
  1811. pub(crate) fn merged_stats() -> [u64; 3] {
  1812. [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed))
  1813. }
  1814. /// The runs of bytes where `now` differs from `was` (of one length), as
  1815. /// (offset, bytes) in order: every differing byte is in a run and no equal
  1816. /// byte is.
  1817. fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
  1818. let n = now.len().min(was.len());
  1819. let mut runs = Vec::new();
  1820. let mut i = 0;
  1821. while i < n {
  1822. // Equal bytes, many at a time while they last (a page looked at
  1823. // under a flight's writes hardly ever differs at all).
  1824. while i + 512 <= n && now[i..i + 512] == was[i..i + 512] {
  1825. i += 512;
  1826. }
  1827. while i + 8 <= n && now[i..i + 8] == was[i..i + 8] {
  1828. i += 8;
  1829. }
  1830. while i < n && now[i] == was[i] {
  1831. i += 1;
  1832. }
  1833. if i >= n {
  1834. break;
  1835. }
  1836. let first = i;
  1837. while i < n && now[i] != was[i] {
  1838. i += 1;
  1839. }
  1840. runs.push((first, i - first));
  1841. }
  1842. runs
  1843. }
  1844. /// Whether a refresh of a copy in the card's memory takes, and sends up,
  1845. /// the dwords that title memory changed and no others
  1846. /// (`VICTORY_SEND_CHANGED=1`; off: the 64 KiB pages written since it last
  1847. /// took them, whole). Off since run tile1-0: the room lost its indirect light
  1848. /// and geometry exploded; run bis1-0, the same but for this, was right.
  1849. ///
  1850. /// A page that counts as written is mostly not the title's doing, or not all
  1851. /// of it: a word the title wrote, and around it what shaders wrote and the
  1852. /// title never touched; or only what the relay put into title memory, which
  1853. /// the card and the CPU's side hold already ([`Shadow::card_merge_relay`]).
  1854. /// Sent up whole, such a page goes over whatever the card holds there that
  1855. /// did not come back yet, or never will (a write through a view nobody
  1856. /// declared): what stood on the card, newer, was gone.
  1857. ///
  1858. /// What it rests on: the CPU's side is what the card's side was last known
  1859. /// to hold, for every range no shader may be writing (no refresh touches
  1860. /// the others). So a dword goes up only if title memory holds another value
  1861. /// of it than the CPU's side, which then holds it too; title memory is read
  1862. /// once, what is compared is what is stored and sent. Dwords, not bytes:
  1863. /// no shader writes less, and the title's bytes beside a changed one in its
  1864. /// dword are those the CPU's side holds.
  1865. ///
  1866. /// A page never taken goes up whole as long as no shader's write was ever
  1867. /// declared for the copy. After that it is compared as any other: the CPU's
  1868. /// side and the card's began as zeros, both.
  1869. ///
  1870. /// What it cannot know: that the title wrote a value over the same value.
  1871. /// Where a shader wrote in between, through a view nobody declared, the
  1872. /// shader's stays.
  1873. fn send_changed() -> bool {
  1874. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1875. *ON.get_or_init(|| {
  1876. #[cfg(feature = "diagnostics")]
  1877. if crate::copystat::mode() != 0 {
  1878. return false;
  1879. }
  1880. std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0")
  1881. })
  1882. }
  1883. /// Since the last frame-rate line, of pages taken into copies in the
  1884. /// card's memory ([`send_changed`]): bytes compared, those of pages that
  1885. /// held the same, bytes to go up, and the runs they are.
  1886. static SEND: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
  1887. /// [`SEND`], taken.
  1888. #[cfg(feature = "diagnostics")]
  1889. pub(crate) fn send_stats() -> [u64; 4] {
  1890. [0, 1, 2, 3].map(|i| SEND[i].swap(0, Ordering::Relaxed))
  1891. }
  1892. /// Whether what shaders wrote goes into title memory run by run
  1893. /// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole
  1894. /// stretch from the first changed byte to the last, as before).
  1895. pub(crate) fn exact_back() -> bool {
  1896. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1897. *ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0"))
  1898. }
  1899. /// Since the last frame-rate line: pieces put back by [`put_changed`], the
  1900. /// writes they took, the bytes written, and the pieces whose runs were
  1901. /// joined over bytes that had not changed.
  1902. pub(crate) static PUT: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
  1903. /// The dwords (of title memory from `at` on) where `merged` differs from
  1904. /// `title`, as (offset, bytes) in order, joined where at most `gap` bytes
  1905. /// lie between.
  1906. fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, usize)> {
  1907. let mut runs: Vec<(usize, usize)> = Vec::new();
  1908. for (from, n) in changed_runs(merged, title) {
  1909. // Shaders write dwords: the whole of each.
  1910. let lo = ((at + from) & !3).max(at) - at;
  1911. let hi = ((at + from + n + 3) & !3).min(at + title.len()) - at;
  1912. match runs.last_mut() {
  1913. Some((a, len)) if lo <= *a + *len + gap => *len = (*len).max(hi - *a),
  1914. _ => runs.push((lo, hi - lo)),
  1915. }
  1916. }
  1917. runs
  1918. }
  1919. /// What shaders wrote goes into title memory from `at` on: `title` is what
  1920. /// was read there, `merged` the same with their bytes put in. Only the
  1921. /// dwords that differ are written. The whole stretch from the first changed
  1922. /// byte to the last was: between the read and the write the title's own
  1923. /// threads, or data streamed in, may have written the bytes between (a heap
  1924. /// holds what shaders write beside what the CPU does), and those writes were
  1925. /// undone. Beside running title threads (the relay) that is a piece of
  1926. /// memory going back in time now and then: runs pool1, blame1 and seriess2
  1927. /// ended in the title decoding garbage.
  1928. ///
  1929. /// shortcut: a piece with very many runs has them joined over small gaps,
  1930. /// where the old race is left.
  1931. fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
  1932. crate::watch::landing(at, title.len());
  1933. if !exact_back() {
  1934. crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len());
  1935. return merged.len();
  1936. }
  1937. if crate::safecopy::on() {
  1938. PUT[0].fetch_add(1, Ordering::Relaxed);
  1939. PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed);
  1940. let since = crate::watch::changes();
  1941. // SAFETY: title memory; a page of it that is not there fails the
  1942. // put, and the rest is put page by page.
  1943. if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } {
  1944. return merged.len();
  1945. }
  1946. let mut from = 0;
  1947. while from < merged.len() {
  1948. let n = (4096 - (at + from) % 4096).min(merged.len() - from);
  1949. let (was, now) = (&title[from..from + n], &merged[from..from + n]);
  1950. // SAFETY: as above.
  1951. let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) };
  1952. // A page that is away only while the runtime changes a mapping
  1953. // beside it gets its bytes when that is done.
  1954. if !put() && !crate::watch::again_after_change(since, put) {
  1955. crate::watch::lost("what shaders wrote", at + from, n);
  1956. }
  1957. from += n;
  1958. }
  1959. return merged.len();
  1960. }
  1961. let mut runs = dword_runs(at, title, merged, 0);
  1962. if runs.len() > 64 {
  1963. runs = dword_runs(at, title, merged, 32);
  1964. PUT[3].fetch_add(1, Ordering::Relaxed);
  1965. }
  1966. let mut written = 0;
  1967. for &(from, n) in &runs {
  1968. crate::host::write_mapped((at + from) as *mut u8, merged[from..].as_ptr(), n);
  1969. written += n;
  1970. }
  1971. PUT[0].fetch_add(1, Ordering::Relaxed);
  1972. PUT[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
  1973. PUT[2].fetch_add(written as u64, Ordering::Relaxed);
  1974. written
  1975. }
  1976. /// For `crate::land`'s measurement: a piece as [`Shadow::card_merge_relay`]
  1977. /// lands it without `VICTORY_LAND`: `n` bytes at `now`, `held` what the CPU's
  1978. /// side held, both the caller's alone.
  1979. #[cfg(test)]
  1980. pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, title: &mut Vec<u8>) {
  1981. // SAFETY: the caller's.
  1982. let (gpu, held) = unsafe { (std::slice::from_raw_parts(now as *const u8, n), std::slice::from_raw_parts_mut(held as *mut u8, n)) };
  1983. let Some(first) = first_difference(gpu, held) else {
  1984. return;
  1985. };
  1986. let last = last_difference(gpu, held).unwrap_or(first);
  1987. let n = last + 1 - first;
  1988. title.clear();
  1989. title.resize(n, 0);
  1990. assert!(crate::host::read_into((start + first) as *const u8, title));
  1991. let was = title.clone();
  1992. if merge_piece(&gpu[first..=last], &mut held[first..=last], title) {
  1993. put_changed(start + first, &was, title);
  1994. }
  1995. }
  1996. #[cfg(test)]
  1997. mod merge_tests {
  1998. use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed};
  1999. /// A piece put back takes the GPU's bytes where the copy changed and
  2000. /// the title's everywhere else, reads and writes title memory only from
  2001. /// the first change to the last, and its scratch holds that stretch and
  2002. /// no more: not the 64 KiB per range it once was.
  2003. #[test]
  2004. fn a_piece_put_back_reads_only_its_stretch() {
  2005. let old: Vec<u8> = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect();
  2006. // The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5,
  2007. // 9 and 40,000 (the GPU's byte wins where both wrote).
  2008. let mut title_memory = old.clone();
  2009. title_memory[7] ^= 0x11;
  2010. title_memory[40_000] ^= 0x22;
  2011. let mut host = old.clone();
  2012. for at in [5, 9] {
  2013. host[at] ^= 0x33;
  2014. }
  2015. let gpu = host.clone();
  2016. let mut scratch = Vec::new();
  2017. let (mut mask, mut runs) = (Vec::new(), Vec::new());
  2018. let mut asked = None;
  2019. let read = |first: usize, into: &mut [u8]| {
  2020. asked = Some((first, into.len()));
  2021. into.copy_from_slice(&title_memory[first..first + into.len()]);
  2022. true
  2023. };
  2024. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5)));
  2025. assert_eq!(asked, Some((5, 5)));
  2026. let mut wanted = title_memory[5..10].to_vec();
  2027. wanted[0] = gpu[5];
  2028. wanted[4] = gpu[9];
  2029. assert_eq!(scratch, wanted);
  2030. assert_eq!(host[5..10], wanted);
  2031. // Only the GPU's two bytes are written back (upstream #2009).
  2032. assert_eq!(runs, [(0, 1), (4, 1)]);
  2033. // The copy outside the stretch is left as it was.
  2034. assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]);
  2035. assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity());
  2036. // Nothing differs: title memory is not read.
  2037. let mut same = old.clone();
  2038. assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None);
  2039. // Title memory not there: nothing to write, the copy unchanged.
  2040. let mut host = gpu.clone();
  2041. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None);
  2042. assert!(host == gpu);
  2043. // The GPU wrote what the title holds already: nothing to write.
  2044. let mut title_memory = old.clone();
  2045. title_memory[5] = gpu[5];
  2046. title_memory[9] = gpu[9];
  2047. let mut host = gpu.clone();
  2048. let read = |first: usize, into: &mut [u8]| {
  2049. into.copy_from_slice(&title_memory[first..first + into.len()]);
  2050. true
  2051. };
  2052. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None);
  2053. // A whole piece changed: the scratch grows to it.
  2054. let mut host: Vec<u8> = old.iter().map(|b| !b).collect();
  2055. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE)));
  2056. assert_eq!(scratch.len(), PIECE);
  2057. }
  2058. /// A byte the shader and the title both changed while the GPU ran keeps
  2059. /// the title's (the shader computed it from the copy's older data); a
  2060. /// byte only the shader changed goes back, and only such bytes are in
  2061. /// the runs to write (PalmVIDev e0b70476, upstream #2009).
  2062. #[test]
  2063. fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() {
  2064. let old = vec![1u8, 2, 3, 4, 5, 6];
  2065. let mut host = old.clone();
  2066. host[1] = 20; // the GPU alone
  2067. host[3] = 40; // both
  2068. host[4] = 50; // the GPU alone
  2069. let mut title_memory = old.clone();
  2070. title_memory[3] = 44;
  2071. title_memory[5] = 66; // the title alone
  2072. let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
  2073. let read = |first: usize, into: &mut [u8]| {
  2074. into.copy_from_slice(&title_memory[first..first + into.len()]);
  2075. true
  2076. };
  2077. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4)));
  2078. assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed");
  2079. assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result");
  2080. assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only");
  2081. }
  2082. /// What shaders wrote reaches a page that is away only while the runtime
  2083. /// changes a mapping; a page that stays away loses it, and nothing else.
  2084. #[test]
  2085. fn a_put_waits_for_a_change_of_mapping() {
  2086. use windows_sys::Win32::System::Memory::{
  2087. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  2088. };
  2089. // SAFETY: a reservation of ours, nothing of it committed.
  2090. let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize;
  2091. assert_ne!(at, 0);
  2092. put_changed(at, &[0; 64], &[3; 64]);
  2093. let (began, wait) = std::sync::mpsc::channel();
  2094. let change = std::thread::spawn(move || {
  2095. let _changing = crate::watch::title_memory_remapping();
  2096. began.send(()).unwrap();
  2097. std::thread::sleep(std::time::Duration::from_millis(50));
  2098. // SAFETY: the reservation's first page.
  2099. assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null());
  2100. });
  2101. wait.recv().unwrap();
  2102. put_changed(at, &[0; 64], &[1; 64]);
  2103. change.join().unwrap();
  2104. // SAFETY: committed by now.
  2105. assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]);
  2106. // SAFETY: our reservation.
  2107. unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
  2108. }
  2109. /// Whole dwords around every changed byte and no other, whatever the
  2110. /// alignment; small gaps joined only when asked.
  2111. #[test]
  2112. fn dword_runs_hold_the_dwords_that_changed() {
  2113. let title: Vec<u8> = (0..200u32).map(|i| (i * 7 + 3) as u8).collect();
  2114. for at in [0x1000usize, 0x1001, 0x1002, 0x1003] {
  2115. for changes in [vec![0], vec![199], vec![5, 6], vec![8, 12, 40, 41, 43, 120]] {
  2116. let mut merged = title.clone();
  2117. for &c in &changes {
  2118. merged[c] ^= 0x55;
  2119. }
  2120. let runs = dword_runs(at, &title, &merged, 0);
  2121. let held: Vec<usize> = runs.iter().flat_map(|&(a, n)| a..a + n).collect();
  2122. let mut expect: Vec<usize> = (0..200).filter(|i| changes.iter().any(|c| (at + c) / 4 == (at + i) / 4)).collect();
  2123. expect.dedup();
  2124. assert_eq!(held, expect, "{at:#x} {changes:?}");
  2125. let joined = dword_runs(at, &title, &merged, 32);
  2126. assert!(joined.len() <= runs.len());
  2127. assert!(runs.iter().all(|r| joined.iter().any(|j| j.0 <= r.0 && r.0 + r.1 <= j.0 + j.1)));
  2128. }
  2129. }
  2130. assert!(dword_runs(0, &title, &title, 0).is_empty());
  2131. }
  2132. /// The runs hold exactly the bytes that differ: putting them into the
  2133. /// old bytes gives the new ones, and no run holds an equal byte.
  2134. /// What looking at a page that did not change costs, against the look
  2135. /// eight bytes at a time that it was (a frame has some 250 of them, on
  2136. /// the submitting thread). Run with `--ignored --nocapture`.
  2137. #[test]
  2138. #[ignore]
  2139. fn runs_of_equal_pages() {
  2140. let (a, b) = (vec![7u8; 64 << 10], vec![7u8; 64 << 10]);
  2141. let eights = || {
  2142. let (now, was) = (std::hint::black_box(&a), std::hint::black_box(&b));
  2143. let mut i = 0;
  2144. while i + 8 <= now.len() && now[i..i + 8] == was[i..i + 8] {
  2145. i += 8;
  2146. }
  2147. std::hint::black_box(i);
  2148. };
  2149. let best = |f: &dyn Fn()| {
  2150. (0..500)
  2151. .map(|_| {
  2152. let t = std::time::Instant::now();
  2153. f();
  2154. t.elapsed().as_secs_f64() * 1e6
  2155. })
  2156. .fold(f64::MAX, f64::min)
  2157. };
  2158. let runs = || drop(std::hint::black_box(changed_runs(std::hint::black_box(&a), std::hint::black_box(&b))));
  2159. println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs));
  2160. }
  2161. #[test]
  2162. fn changed_runs_are_exactly_the_bytes_that_differ() {
  2163. let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect();
  2164. for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] {
  2165. let mut now = was.clone();
  2166. for &at in &changes {
  2167. now[at] ^= 0x41;
  2168. }
  2169. let runs = changed_runs(&now, &was);
  2170. let mut put = was.clone();
  2171. let mut held = Vec::new();
  2172. for &(at, n) in &runs {
  2173. assert!(n > 0);
  2174. put[at..at + n].copy_from_slice(&now[at..at + n]);
  2175. held.extend(at..at + n);
  2176. }
  2177. assert_eq!(put, now, "{changes:?}");
  2178. assert_eq!(held, changes, "{changes:?}");
  2179. // Runs do not touch: two that did would be one.
  2180. assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}");
  2181. }
  2182. assert!(changed_runs(&[], &[]).is_empty());
  2183. }
  2184. }
  2185. /// Host copies alive (also those only a list, a descriptor pass or a
  2186. /// snapshot still holds) and the bytes of title memory they copy.
  2187. static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2188. impl Drop for Shadow {
  2189. fn drop(&mut self) {
  2190. if self.place.is_some() {
  2191. // Never counted with the copies (`Shadow::placed`).
  2192. crate::inplace::gone(self.window, self.len);
  2193. return;
  2194. }
  2195. LIVE[0].fetch_sub(1, Ordering::Relaxed);
  2196. LIVE[1].fetch_sub(self.len, Ordering::Relaxed);
  2197. if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 {
  2198. KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed);
  2199. }
  2200. let window = self.window;
  2201. if self.mapped {
  2202. WINDOW_MAPPED_BYTES.fetch_sub(self.len, Ordering::Relaxed);
  2203. }
  2204. if let Some(card) = &mut self.card {
  2205. if window {
  2206. WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed);
  2207. } else {
  2208. CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed);
  2209. }
  2210. if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() {
  2211. CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. /// Whether a copy's snapshot is kept from one submission to the next and
  2217. /// only the pieces that changed in between are taken again
  2218. /// (`VICTORY_KEEP_SNAPSHOTS=1`; off by default).
  2219. ///
  2220. /// A snapshot is the copy's bytes before a submission, to find what its
  2221. /// shaders wrote. Taken anew for every submission it is 1,050 MB of copying
  2222. /// a frame (72-86 ms in gameplay, runs 61 and 62) for buffers of which
  2223. /// 100 MB changed. Kept, a piece of it is taken again only after something
  2224. /// changed the copy there: a refresh from title memory ([`Shadow::copy`]),
  2225. /// shader writes found after a submission, or the bytes put back then
  2226. /// ([`Shadow::copy_back`]).
  2227. ///
  2228. /// What it assumes, and why it is not on by default: that nothing else
  2229. /// writes a copy. A shader that writes a buffer through a view we did not
  2230. /// declare as written (we declare the unordered-access views of shaders
  2231. /// that can store) changes the copy unseen; with a fresh snapshot that
  2232. /// write is simply never put back, with a kept one it would be taken for a
  2233. /// write of a later submission and put back then, over whatever the title
  2234. /// wrote there since.
  2235. fn keeps() -> bool {
  2236. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2237. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_SNAPSHOTS").is_some_and(|v| v == "1"))
  2238. }
  2239. /// Bytes of the snapshots kept, and the most that may be.
  2240. static KEPT_BYTES: AtomicU64 = AtomicU64::new(0);
  2241. /// `VICTORY_KEEP_SNAPSHOTS_MB`, 256 unless set (it was 768: run 80, with
  2242. /// kept snapshots beside copies in the card's memory, ran the PC out of
  2243. /// memory in 27 s; kept snapshots are the PC's memory, all of it resident).
  2244. fn kept_most() -> u64 {
  2245. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  2246. *MOST.get_or_init(|| {
  2247. std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(256) << 20
  2248. })
  2249. }
  2250. /// The 64 KiB pieces, cut at multiples of 64 KiB of title memory, that
  2251. /// hold offsets `[from, to)` of a copy of memory from `start` on
  2252. /// (`from < to`); piece 0 holds offset 0.
  2253. fn pieces_of(start: usize, from: usize, to: usize) -> std::ops::Range<usize> {
  2254. let first = start / PIECE;
  2255. (start + from) / PIECE - first..(start + to - 1) / PIECE - first + 1
  2256. }
  2257. /// The offsets that piece `piece` holds of a copy of `len` bytes of memory
  2258. /// from `start` on.
  2259. fn piece_at(start: usize, len: usize, piece: usize) -> (usize, usize) {
  2260. let first = start / PIECE;
  2261. let lo = ((first + piece) * PIECE).saturating_sub(start);
  2262. let hi = ((first + piece + 1) * PIECE - start).min(len);
  2263. (lo, hi)
  2264. }
  2265. #[cfg(test)]
  2266. mod piece_tests {
  2267. use super::{PIECE, piece_at, pieces_of};
  2268. /// The pieces cover a copy without gaps, each cut where the compare
  2269. /// cuts (at multiples of 64 KiB of title memory).
  2270. #[test]
  2271. fn pieces_cover_the_copy_as_the_compare_cuts_it() {
  2272. for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] {
  2273. for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] {
  2274. let count = pieces_of(start, 0, len).end;
  2275. let mut at = 0;
  2276. for piece in 0..count {
  2277. let (lo, hi) = piece_at(start, len, piece);
  2278. assert_eq!(lo, at, "{start} {len} {piece}");
  2279. // As `Shadow::differing` cuts: to the next multiple.
  2280. let n = (PIECE - (start + at) % PIECE).min(len - at);
  2281. assert_eq!(hi, at + n, "{start} {len} {piece}");
  2282. assert_eq!(pieces_of(start, lo, hi), piece..piece + 1);
  2283. assert_eq!(pieces_of(start, hi - 1, hi), piece..piece + 1);
  2284. at = hi;
  2285. }
  2286. assert_eq!(at, len, "{start} {len}");
  2287. assert_eq!(pieces_of(start, 0, len), 0..count);
  2288. }
  2289. }
  2290. }
  2291. }
  2292. /// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose
  2293. /// first page is `base` must take from title memory before it holds the
  2294. /// title's bytes: those it never took (`copied` 0), whether or not the
  2295. /// title wrote them since tracking began, and those `written` (as
  2296. /// `crate::watch::writes` gives it, by page in order) shows written after
  2297. /// the copy took them. As [`Shadow::copy_stale`] decides it.
  2298. ///
  2299. /// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked
  2300. /// at `written` alone, so a page of a range shaders may be writing that the
  2301. /// copy never took, and the title had not written lately, was neither
  2302. /// merged nor a reason to settle; the refresh leaves such ranges alone, and
  2303. /// shaders read zeros there (fxceless/victory-fork#206: missing geometry
  2304. /// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`).
  2305. fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec<usize> {
  2306. (a / PAGE..e.div_ceil(PAGE))
  2307. .filter(|&page| page >= base)
  2308. .filter(|&page| match copied.get(page - base) {
  2309. None => false,
  2310. Some(0) => true,
  2311. Some(&at) => written
  2312. .binary_search_by_key(&page, |&(p, _)| p)
  2313. .is_ok_and(|i| written[i].1 > at),
  2314. })
  2315. .collect()
  2316. }
  2317. /// `runs` (from, to, whether the copy held it before), cut in those of pages
  2318. /// held before (`pages`: page number and asking, in order) to the parts of
  2319. /// each page that were written since (`parts`: a bit for each 4 KiB).
  2320. fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u16]) -> Vec<(usize, usize, bool)> {
  2321. const PART: usize = PAGE / 16;
  2322. if parts.iter().all(|&p| p == u16::MAX) {
  2323. return runs;
  2324. }
  2325. let mut out: Vec<(usize, usize, bool)> = Vec::with_capacity(runs.len() + pages.len());
  2326. let mut pages = pages.iter().zip(parts).peekable();
  2327. for (from, to, known) in runs {
  2328. if !known {
  2329. out.push((from, to, known));
  2330. continue;
  2331. }
  2332. while let Some((&(page, _), &parts)) = pages.next_if(|((page, _), _)| page * PAGE < to) {
  2333. for k in (0..16).filter(|k| parts >> k & 1 != 0) {
  2334. let (a, b) = ((page * PAGE + k * PART).max(from), (page * PAGE + (k + 1) * PART).min(to));
  2335. if a >= b {
  2336. continue;
  2337. }
  2338. match out.last_mut() {
  2339. Some((_, end, true)) if *end == a => *end = b,
  2340. _ => out.push((a, b, true)),
  2341. }
  2342. }
  2343. }
  2344. }
  2345. out
  2346. }
  2347. #[cfg(test)]
  2348. mod parts_tests {
  2349. use super::{PAGE, by_parts};
  2350. #[test]
  2351. fn runs_are_cut_to_the_parts_written() {
  2352. const P: usize = PAGE / 16;
  2353. let at = |page: usize, part: usize| page * PAGE + part * P;
  2354. // Pages 10 and 11 again (from the middle of 10's part 1 on), 12
  2355. // never taken, 14 again.
  2356. let runs = vec![
  2357. (at(10, 1) + 100, at(12, 0), true),
  2358. (at(12, 0), at(13, 0), false),
  2359. (at(14, 0), at(14, 9) + 7, true),
  2360. ];
  2361. let pages = [(10, 5), (11, 5), (14, 6)];
  2362. assert_eq!(by_parts(runs.clone(), &pages, &[u16::MAX; 3]), runs);
  2363. assert_eq!(
  2364. by_parts(runs, &pages, &[0b1000_0000_0000_0011, 0b11, 0b10_0000_0000]),
  2365. [
  2366. (at(10, 1) + 100, at(10, 2), true),
  2367. (at(10, 15), at(11, 2), true),
  2368. (at(12, 0), at(13, 0), false),
  2369. (at(14, 9), at(14, 9) + 7, true),
  2370. ]
  2371. );
  2372. }
  2373. }
  2374. #[cfg(test)]
  2375. mod stale_tests {
  2376. use super::*;
  2377. #[test]
  2378. fn pages_never_taken_are_stale_written_or_not() {
  2379. let base = 0x100;
  2380. let copied = [5, 0, 5, 5];
  2381. let at = |page: usize| page * PAGE;
  2382. // Page 0x101 was never taken; page 0x102 was written after it was
  2383. // taken, page 0x103 before.
  2384. let written = [(0x102, 6), (0x103, 4)];
  2385. assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]);
  2386. // Part of a page counts as the page; pages outside the copy do not.
  2387. assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]);
  2388. assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty());
  2389. }
  2390. }
  2391. /// Copies of windows outside buffers let go since the start, and their
  2392. /// bytes.
  2393. static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  2394. /// For the memory line: the windows let go since the start and their
  2395. /// bytes, and of the bytes of the windows alive, how many lie between the
  2396. /// lowest and the highest address ever asked for in each.
  2397. #[cfg(feature = "diagnostics")]
  2398. pub(crate) fn windows() -> [u64; 3] {
  2399. let asked: u64 = {
  2400. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2401. loose
  2402. .values()
  2403. .map(|s| {
  2404. let low = s.asked[0].load(Ordering::Relaxed);
  2405. let high = s.asked[1].load(Ordering::Relaxed);
  2406. high.saturating_sub(low)
  2407. })
  2408. .sum()
  2409. };
  2410. [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked]
  2411. }
  2412. /// For the memory line, of the windows alive: the bytes of their pages
  2413. /// ever copied from title memory (the rest of each window is memory the
  2414. /// host zeroed and nothing read: what a window made no bigger than what is
  2415. /// read would not hold); the windows a descriptor slot shows and their
  2416. /// bytes (they stay until the title writes the slot again); the windows a
  2417. /// list or a pass over the heap holds and their bytes; the windows asked
  2418. /// for without a length (root views, which keep the 4 MiB grid) and their
  2419. /// bytes; and the window grid in bytes ([`window`]).
  2420. #[cfg(feature = "diagnostics")]
  2421. pub(crate) fn window_use() -> [u64; 8] {
  2422. let mut out = [0u64; 8];
  2423. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2424. for s in loose.values() {
  2425. let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner());
  2426. let pages = copied.iter().filter(|&&at| at != 0).count() as u64;
  2427. out[0] += (pages * PAGE as u64).min(s.len);
  2428. if crate::host::references(&s.buffer) > 1 {
  2429. out[1] += 1;
  2430. out[2] += s.len;
  2431. }
  2432. if Arc::strong_count(s) > 1 {
  2433. out[3] += 1;
  2434. out[4] += s.len;
  2435. }
  2436. if s.unsized_asks.load(Ordering::Relaxed) > 0 {
  2437. out[5] += 1;
  2438. out[6] += s.len;
  2439. }
  2440. }
  2441. out[7] = window();
  2442. out
  2443. }
  2444. /// Lets go of the copies of windows outside buffers that nothing names any
  2445. /// more. They were never freed, and the world's streaming keeps asking for
  2446. /// new ones: 648 windows (2.8 GB) when the cutscene began, 974 (4.3 GB)
  2447. /// eight minutes later (run 24). A window goes when
  2448. /// - only the table of windows holds its copy: no list not yet reset reads
  2449. /// or writes it, no pass over the heap keeps its range, no submission is
  2450. /// comparing it;
  2451. /// - only the copy holds its host buffer: no descriptor slot views it (a
  2452. /// slot keeps the buffer it views, `HostHeap::kept`), so no draw can read
  2453. /// it through a slot made earlier;
  2454. /// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames.
  2455. ///
  2456. /// The next read of that memory makes a new copy and copies the window
  2457. /// again. Called before a submission starts, by the thread that submits.
  2458. pub(crate) fn let_go_idle() {
  2459. const IDLE_FRAMES: u64 = 4;
  2460. let gone: Vec<Arc<Shadow>> = {
  2461. // Held from the look to the removal: `loose` hands a copy out
  2462. // under the same lock, so none is handed out in between.
  2463. let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2464. if map.is_empty() {
  2465. return;
  2466. }
  2467. let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram());
  2468. let idle: Vec<(u64, u64)> = map
  2469. .iter()
  2470. .filter(|(_, s)| {
  2471. Arc::strong_count(s) == 1
  2472. && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES)
  2473. && crate::host::references(&s.buffer) == 1
  2474. })
  2475. .map(|(key, _)| *key)
  2476. .collect();
  2477. idle.into_iter().filter_map(|key| map.remove(&key)).collect()
  2478. };
  2479. if !gone.is_empty() {
  2480. let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::<u64>());
  2481. crate::host::trail(|| {
  2482. format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10)
  2483. });
  2484. }
  2485. for shadow in gone {
  2486. LET_GO[0].fetch_add(1, Ordering::Relaxed);
  2487. LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed);
  2488. // Nothing runs now and nothing names it: freed at once unless a
  2489. // submission is running after all.
  2490. crate::host::retire(shadow);
  2491. }
  2492. }
  2493. /// For the memory line: host copies alive and their bytes, of them the
  2494. /// windows of memory outside buffers and their bytes, and the snapshot
  2495. /// buffers kept for reuse and the bytes they reserve.
  2496. #[cfg(feature = "diagnostics")]
  2497. pub(crate) fn memory() -> [u64; 6] {
  2498. let (windows, window_bytes) = {
  2499. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2500. // Each copy once: a window may stand under several keys.
  2501. let mut seen = std::collections::HashSet::new();
  2502. let bytes: u64 = loose
  2503. .values()
  2504. .filter(|s| seen.insert(Arc::as_ptr(s) as usize))
  2505. .map(|s| s.len)
  2506. .sum();
  2507. (seen.len() as u64, bytes)
  2508. };
  2509. let (kept, kept_bytes) = {
  2510. let pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  2511. (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::<u64>())
  2512. };
  2513. [
  2514. LIVE[0].load(Ordering::Relaxed),
  2515. LIVE[1].load(Ordering::Relaxed),
  2516. windows,
  2517. window_bytes,
  2518. kept,
  2519. kept_bytes,
  2520. ]
  2521. }
  2522. // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping
  2523. // written only on the submitting thread.
  2524. unsafe impl Send for Shadow {}
  2525. // SAFETY: as above.
  2526. unsafe impl Sync for Shadow {}
  2527. impl Shadow {
  2528. /// The host GPU address of a title address inside the buffer.
  2529. pub(crate) fn gpu(&self, address: u64) -> u64 {
  2530. self.gpu + (address - self.start)
  2531. }
  2532. /// The title memory the copy is of: its start and length.
  2533. pub(crate) fn span(&self) -> (u64, u64) {
  2534. (self.start, self.len)
  2535. }
  2536. /// The offset of a title address in the copy, if it lies in it.
  2537. pub(crate) fn offset_in(&self, address: u64) -> Option<u64> {
  2538. address.checked_sub(self.start).filter(|&at| at < self.len)
  2539. }
  2540. /// Bytes from a title address to the buffer's end.
  2541. pub(crate) fn left(&self, address: u64) -> u64 {
  2542. (self.start + self.len).saturating_sub(address)
  2543. }
  2544. /// Whether the memory behind the copy turned out not to be write-watched:
  2545. /// every refresh then copies its whole range.
  2546. pub(crate) fn unwatched(&self) -> bool {
  2547. self.watched.load(Ordering::Relaxed) == NOT_WATCHED
  2548. }
  2549. /// Whether a submission asks the kernel about the copy's ranges ahead:
  2550. /// not of memory that is not watched, nor of view memory, which the
  2551. /// kernel would refuse (and with it the ranges asked about together).
  2552. pub(crate) fn asked_ahead(&self) -> bool {
  2553. let watched = self.watched.load(Ordering::Relaxed);
  2554. watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
  2555. }
  2556. /// The copy's own number (see the field).
  2557. pub(crate) fn id(&self) -> u64 {
  2558. self.id
  2559. }
  2560. /// Whether it is no copy but title memory in place (`crate::inplace`).
  2561. pub(crate) fn in_place(&self) -> bool {
  2562. self.place.is_some()
  2563. }
  2564. /// Offset of a title address from the buffer's start.
  2565. pub(crate) fn offset(&self, address: u64) -> u64 {
  2566. address - self.start + self.place.as_ref().map_or(0, |place| place.1)
  2567. }
  2568. /// Title memory `[start, start + len)` in place: `placed` is a buffer
  2569. /// over it in a heap opened on it. Shaped as a copy so that everything
  2570. /// that binds, views or keeps a copy works on it unchanged; what
  2571. /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]).
  2572. fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow {
  2573. crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place"));
  2574. let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len);
  2575. // Not a copy: not counted with them, and nothing asks what the
  2576. // title wrote there.
  2577. LIVE[0].fetch_sub(1, Ordering::Relaxed);
  2578. LIVE[1].fetch_sub(len, Ordering::Relaxed);
  2579. *shadow.watched.get_mut() = NOT_WATCHED;
  2580. shadow.window = window;
  2581. shadow.place = Some((placed.heap, placed.bias));
  2582. shadow
  2583. }
  2584. /// Brings `len` bytes at `address` up to date when `list` is submitted,
  2585. /// and keeps the copy alive until the list is reset.
  2586. pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
  2587. let len = len.min(self.start + self.len - address);
  2588. list.defer_refresh(self, address as usize, len as usize);
  2589. }
  2590. /// The bytes of the host buffer.
  2591. pub(crate) fn width(&self) -> u64 {
  2592. // SAFETY: a live buffer.
  2593. *self.width.get_or_init(|| unsafe { self.buffer.GetDesc() }.Width)
  2594. }
  2595. fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow {
  2596. let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64;
  2597. LIVE[0].fetch_add(1, Ordering::Relaxed);
  2598. LIVE[1].fetch_add(len, Ordering::Relaxed);
  2599. Shadow {
  2600. width: Default::default(),
  2601. buffer,
  2602. data,
  2603. gpu,
  2604. start,
  2605. len,
  2606. copied: Mutex::new(vec![0; pages as usize]),
  2607. ranged: Mutex::default(),
  2608. watched: AtomicU8::new(0),
  2609. pending: Mutex::default(),
  2610. flights: Mutex::default(),
  2611. before: Mutex::default(),
  2612. merging: RwLock::default(),
  2613. kept: Mutex::default(),
  2614. used: AtomicU64::new(crate::host::moment()),
  2615. asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)],
  2616. unsized_asks: AtomicU64::new(0),
  2617. written: Default::default(),
  2618. id: {
  2619. static NEXT: AtomicU64 = AtomicU64::new(1);
  2620. NEXT.fetch_add(1, Ordering::Relaxed)
  2621. },
  2622. card: None,
  2623. window: false,
  2624. changes_only: Default::default(),
  2625. mapped: false,
  2626. place: None,
  2627. }
  2628. }
  2629. /// `[address, address + len)` cut to the buffer, as offsets in the copy.
  2630. fn inside(&self, address: usize, len: usize) -> (usize, usize) {
  2631. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  2632. let from = address.clamp(start, end);
  2633. (from - start, (address + len).clamp(from, end) - start)
  2634. }
  2635. /// Shaders of `list` may write `[address, address + len)` of the copy
  2636. /// (unordered access): after the list's submission has run, the range
  2637. /// is copied back into title memory, where the title reads it; until
  2638. /// then no refresh copies title memory over it. Call after the
  2639. /// [`Shadow::refresh`] that gives the shaders the title's data.
  2640. ///
  2641. /// shortcut: what shaders wrote is found by keeping the range's bytes
  2642. /// before the submission (a copy per declared range and submission);
  2643. /// a GPU-side dirty mask would save that if big ranges make it slow.
  2644. pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
  2645. // In place the shaders write title memory itself: no snapshot, no
  2646. // compare, nothing to copy back, and no wait on its account.
  2647. // shortcut: another host copy of the same bytes (a title buffer
  2648. // inside this one with a copy of its own, a texture in it) is not
  2649. // told: the card's writes are not seen by write watching.
  2650. if self.place.is_some() {
  2651. return;
  2652. }
  2653. self.written.store(true, Ordering::Relaxed);
  2654. let len = len.min(self.left(address));
  2655. list.defer_gpu_write(self, address as usize, len as usize);
  2656. }
  2657. /// At submission, after the range's refresh: a submitted list's shaders
  2658. /// write this range. Its bytes are kept to tell later what the GPU wrote:
  2659. /// one snapshot per copy and submission, each byte taken once, when the
  2660. /// first range holding it is declared (the world declares overlapping
  2661. /// views of its 174 MB heap dozens of times, from different offsets: a
  2662. /// snapshot grown to cover each was copied whole every time), in reused
  2663. /// memory (fresh snapshots cost ~2.3 million page faults per world
  2664. /// frame).
  2665. pub(crate) fn writing(&self, address: usize, len: usize) {
  2666. if self.place.is_some() {
  2667. return;
  2668. }
  2669. let range = (address, address + len);
  2670. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  2671. // With the copy-back on its own thread: counted for this submission
  2672. // (once), whether or not an earlier one still holds the range.
  2673. if relay() {
  2674. self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed));
  2675. }
  2676. // Dispatches declare the same ranges thousands of times.
  2677. if pending.contains(&range) {
  2678. return;
  2679. }
  2680. // In the card's memory: no snapshot. What shaders wrote is found on
  2681. // the card (`Host::card_before` reads the declared ranges from the
  2682. // lists).
  2683. if self.card.is_some() {
  2684. pending.push(range);
  2685. return;
  2686. }
  2687. // The parts no declared range holds yet: their bytes are taken now,
  2688. // just after the range's refresh (a part declared earlier has not
  2689. // been refreshed since, and keeps the bytes taken then).
  2690. let mut parts = vec![self.inside(address, len)];
  2691. for &(a, e) in pending.iter() {
  2692. let (a, e) = self.inside(a, e - a);
  2693. let mut rest = Vec::with_capacity(parts.len() + 1);
  2694. for (from, to) in parts {
  2695. if e <= from || a >= to {
  2696. rest.push((from, to));
  2697. continue;
  2698. }
  2699. if from < a {
  2700. rest.push((from, a));
  2701. }
  2702. if e < to {
  2703. rest.push((e, to));
  2704. }
  2705. }
  2706. parts = rest;
  2707. }
  2708. pending.push(range);
  2709. let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum();
  2710. BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed);
  2711. let total = self.len as usize;
  2712. let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
  2713. let snapshot = before.get_or_insert_with(|| pooled(total));
  2714. if keeps() {
  2715. // Piece by piece, and only the pieces not known current. A
  2716. // piece the part holds whole is current from now on; of a
  2717. // piece it holds partly only the part's bytes are taken, as
  2718. // without the switch, and it is taken again next time (the
  2719. // rest of it may belong to a range declared earlier, whose
  2720. // bytes stay as they were taken).
  2721. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2722. if kept.0.is_empty() {
  2723. kept.0 = vec![false; self.pieces(0, total.max(1)).end];
  2724. }
  2725. for (from, to) in parts {
  2726. if from >= to {
  2727. continue;
  2728. }
  2729. for piece in self.pieces(from, to) {
  2730. if kept.0[piece] {
  2731. continue;
  2732. }
  2733. let (lo, hi) = self.piece(piece);
  2734. let whole = from <= lo && hi <= to;
  2735. let (lo, hi) = (lo.max(from), hi.min(to));
  2736. // SAFETY: as below; `hi <= total`.
  2737. unsafe {
  2738. std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo);
  2739. }
  2740. kept.0[piece] = whole;
  2741. }
  2742. }
  2743. return;
  2744. }
  2745. if wide_back() {
  2746. // Noted, and taken with the submission's other snapshots when
  2747. // its refreshes are done (`take_snapshots`): the range is
  2748. // declared from here on, so nothing changes its bytes before
  2749. // then. The snapshot's memory stays where it is until the
  2750. // range is done with (`copy_back_done`).
  2751. let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner());
  2752. let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize);
  2753. snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from)));
  2754. return;
  2755. }
  2756. for (from, to) in parts {
  2757. if from < to {
  2758. // SAFETY: the copy's mapping and the snapshot's allocation
  2759. // (`pooled`) both hold `total` bytes, and `to <= total`.
  2760. unsafe {
  2761. copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from);
  2762. }
  2763. }
  2764. }
  2765. }
  2766. /// After the submission ran: copies the bytes its shaders wrote back
  2767. /// into title memory (unmapped pages left alone), and only those: the
  2768. /// title's threads write the same buffers while the GPU runs (its
  2769. /// command memory shares the big GPU heap with what shaders write), and
  2770. /// putting back the copy's older bytes there broke the title's own
  2771. /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes
  2772. /// written. The range must lie in ranges declared with
  2773. /// [`Shadow::writing`] and not yet done: `Host::execute` passes the
  2774. /// union of a submission's ranges, each byte once, then calls
  2775. /// [`Shadow::copy_back_done`].
  2776. pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize {
  2777. self.copy_back_with(address, len, None)
  2778. }
  2779. /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range
  2780. /// that differ from the snapshot, found beforehand ([`find_all`]).
  2781. pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option<Vec<(usize, usize)>>) -> usize {
  2782. if self.place.is_some() {
  2783. return 0;
  2784. }
  2785. let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner());
  2786. let mut written = 0;
  2787. let (from, to) = self.inside(address, len);
  2788. let start = self.start as usize;
  2789. self.compared(from, to);
  2790. if let Some(before) = &*snapshot
  2791. && from < to
  2792. {
  2793. // SAFETY: `writing` set the snapshot's bytes of every declared
  2794. // range, at the copy's offsets.
  2795. let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) };
  2796. // By 64 KiB piece: the copy compared with its bytes before the
  2797. // submission (on several threads: gigabytes a frame, bound by
  2798. // memory speed), title memory read only where the GPU wrote.
  2799. #[cfg(feature = "diagnostics")]
  2800. let scanning = std::time::Instant::now();
  2801. let differing = match found {
  2802. Some(found) => found,
  2803. None => self.differing(from, to, before),
  2804. };
  2805. #[cfg(feature = "diagnostics")]
  2806. let syncing = {
  2807. use crate::copystat::{C, add};
  2808. add(C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2809. add(C::BackDiffer, differing.len() as u64);
  2810. std::time::Instant::now()
  2811. };
  2812. // Where the copy changes (the GPU wrote, and below the title's
  2813. // bytes come in), a kept snapshot is no longer current.
  2814. for &(at, n) in &differing {
  2815. self.changed(at, at + n);
  2816. }
  2817. // Sized to each stretch read (`back_piece`): a zeroed 64 KiB per
  2818. // range, most of whose ranges differ nowhere, was most of the
  2819. // work for small ranges.
  2820. let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
  2821. for (at, n) in differing {
  2822. // SAFETY: inside the mapping; only the submitting thread
  2823. // writes it.
  2824. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
  2825. let old = &before[at - from..at - from + n];
  2826. let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title);
  2827. let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else {
  2828. continue;
  2829. };
  2830. // Title memory as read, beside it with the card's bytes put
  2831. // in: only the dwords that differ are written.
  2832. let was: Vec<u8> = title.iter().zip(&mask).map(|(now, changed)| now ^ changed).collect();
  2833. if !runs.is_empty() {
  2834. written += put_changed(start + at + first, &was[..n], &title[..n]);
  2835. }
  2836. }
  2837. // Our write shows as a title write at the copy's next refresh,
  2838. // which copies those pages once more (some dozens of MB a
  2839. // frame). Asking about the whole range here, to note them
  2840. // current, cost more: 19-31 askings a frame over 110-174 MB of
  2841. // view memory, each a walk of its guards.
  2842. #[cfg(feature = "diagnostics")]
  2843. crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64);
  2844. }
  2845. written
  2846. }
  2847. /// Offsets `[from, to)` of the copy are compared with the snapshot: for
  2848. /// the frame line's counts.
  2849. fn compared(&self, from: usize, to: usize) {
  2850. #[cfg(feature = "diagnostics")]
  2851. crate::copystat::add(crate::copystat::C::BackCompared, (to - from) as u64);
  2852. let (bytes, ranges) = if self.window { (2, 5) } else { (3, 6) };
  2853. BACK_CLASS[bytes].fetch_add((to - from) as u64, Ordering::Relaxed);
  2854. BACK_CLASS[ranges].fetch_add(1, Ordering::Relaxed);
  2855. if !self.window && self.len >= 1 << 20 {
  2856. BACK_CLASS[4].fetch_add((to - from) as u64, Ordering::Relaxed);
  2857. }
  2858. }
  2859. /// [`relay`]: the declared range `[address, address + len)` of a copy
  2860. /// in the PC's memory is about to be looked through
  2861. /// (`crate::shadow::find_all`) by the thread that settles: counted as
  2862. /// [`Shadow::copy_back_with`] counts it.
  2863. pub(crate) fn relay_compared(&self, address: usize, len: usize) {
  2864. let (from, to) = self.inside(address, len);
  2865. self.compared(from, to);
  2866. }
  2867. /// [`relay`], for a copy in the PC's memory: offsets `[at, at + n)`
  2868. /// are a 64 KiB piece of a declared range that differed from the
  2869. /// snapshot when it was looked through. What the card wrote there
  2870. /// since the snapshot was last brought up goes into title memory, from
  2871. /// the first to the last such byte, and into the snapshot, so that the
  2872. /// next flight's merge finds only what the card writes from now on.
  2873. /// The copy is read once and never written: a later flight's shaders
  2874. /// may be writing it at this moment. Under the snapshot's lock, which
  2875. /// [`Shadow::merge_under_writes`] holds while it reads title memory
  2876. /// and puts the title's bytes into the copy and the snapshot: the two
  2877. /// never see each other half done. `now` and `title` are scratch
  2878. /// memory. Returns the bytes written to title memory.
  2879. pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec<u8>, title: &mut Vec<u8>) -> usize {
  2880. let start = self.start as usize;
  2881. if self.card.is_some() || n == 0 || at + n > self.len as usize {
  2882. return 0;
  2883. }
  2884. let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner());
  2885. let Some(before) = snapshot.as_mut() else {
  2886. return 0;
  2887. };
  2888. now.clear();
  2889. now.reserve(n);
  2890. // SAFETY: inside the copy's mapping (checked above), read into
  2891. // room just reserved; the card may write the mapping meanwhile, and
  2892. // each byte read is one it held at some moment.
  2893. unsafe {
  2894. std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n);
  2895. now.set_len(n);
  2896. }
  2897. // SAFETY: the snapshot's allocation holds the copy's length
  2898. // (`writing`), and these offsets are in a range declared and not
  2899. // done with, whose bytes it holds; nothing else touches them
  2900. // without the lock held here.
  2901. let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) };
  2902. let Some(first) = first_difference(now, held) else {
  2903. return 0;
  2904. };
  2905. let last = last_difference(now, held).unwrap_or(first);
  2906. let (at, n) = (at + first, last + 1 - first);
  2907. let (now, held) = (&now[first..=last], &mut held[first..=last]);
  2908. title.clear();
  2909. title.resize(n, 0);
  2910. // Title memory not there: looked at again when the next flight
  2911. // that declared the range lands (the snapshot stays as it is).
  2912. if !crate::host::read_into((start + at) as *const u8, title) {
  2913. return 0;
  2914. }
  2915. let was = title.clone();
  2916. if !merge_piece(now, held, title) {
  2917. return 0;
  2918. }
  2919. put_changed(start + at, &was, title)
  2920. }
  2921. /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of
  2922. /// `[from, to)` of the copy that differ from `before` (the bytes from
  2923. /// `from` on), as (offset, bytes) in order; compared on several threads
  2924. /// when the range is big.
  2925. fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> {
  2926. let (start, data) = (self.start as usize, self.data as usize);
  2927. let scan = |a: usize, b: usize| -> Vec<(usize, usize)> {
  2928. let mut found = Vec::new();
  2929. let mut at = a;
  2930. while at < b {
  2931. let n = (PIECE - (start + at) % PIECE).min(b - at);
  2932. // SAFETY: inside the mapping, which nothing writes while a
  2933. // submission's results are compared.
  2934. let host = unsafe { std::slice::from_raw_parts((data + at) as *const u8, n) };
  2935. if host != &before[at - from..at - from + n] {
  2936. found.push((at, n));
  2937. }
  2938. at += n;
  2939. }
  2940. found
  2941. };
  2942. const PER_THREAD: usize = 16 << 20;
  2943. let threads = ((to - from) / PER_THREAD).clamp(1, 8);
  2944. if threads == 1 {
  2945. return scan(from, to);
  2946. }
  2947. // Cut on piece boundaries, so that every thread sees whole pieces.
  2948. let cut = |i: usize| {
  2949. if i == threads {
  2950. return to;
  2951. }
  2952. let at = from + (to - from) / threads * i;
  2953. (at - (start + at) % PIECE).max(from)
  2954. };
  2955. let scan = &scan;
  2956. std::thread::scope(|s| {
  2957. let parts: Vec<_> = (0..threads)
  2958. .map(|i| {
  2959. let (a, b) = (cut(i), cut(i + 1));
  2960. s.spawn(move || scan(a, b))
  2961. })
  2962. .collect();
  2963. parts
  2964. .into_iter()
  2965. .flat_map(|part| match part.join() {
  2966. Ok(found) => found,
  2967. Err(panic) => std::panic::resume_unwind(panic),
  2968. })
  2969. .collect()
  2970. })
  2971. }
  2972. /// After [`Shadow::copy_back`] of a submission's ranges: every submitted
  2973. /// step that declared one of `ranges` (`(address, end)`, as declared) is
  2974. /// done with it (one submission runs at a time), and the snapshot with
  2975. /// the last range.
  2976. ///
  2977. /// With [`relay`] several submissions may hold a range: `ranges` are
  2978. /// those of one of them (each once), and a range is done with when the
  2979. /// last submission that declared it is ([`Flights`]).
  2980. pub(crate) fn copy_back_done(&self, ranges: &[(usize, usize)]) {
  2981. if self.place.is_some() {
  2982. return;
  2983. }
  2984. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  2985. if relay() {
  2986. let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges);
  2987. pending.retain(|r| free.binary_search(r).is_err());
  2988. } else {
  2989. pending.retain(|r| !ranges.contains(r));
  2990. }
  2991. if !pending.is_empty() || self.card.is_some() {
  2992. return;
  2993. }
  2994. if keeps() {
  2995. // Kept for the next submission, if it is worth it (a megabyte
  2996. // or more) and there is room.
  2997. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2998. if !kept.1 && self.len >= 1 << 20 {
  2999. if KEPT_BYTES.fetch_add(self.len, Ordering::Relaxed) + self.len <= kept_most() {
  3000. kept.1 = true;
  3001. } else {
  3002. KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed);
  3003. }
  3004. }
  3005. if kept.1 {
  3006. return;
  3007. }
  3008. // Given back: nothing of it is current next time. (The lock
  3009. // on the pieces ends here: `copy_back` takes it while it holds
  3010. // the snapshot's.)
  3011. kept.0.clear();
  3012. }
  3013. if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() {
  3014. give_back(bytes);
  3015. }
  3016. }
  3017. /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory, as
  3018. /// [`Shadow::differing`] cuts them) that hold offsets `[from, to)` of
  3019. /// the copy; `from < to`.
  3020. fn pieces(&self, from: usize, to: usize) -> std::ops::Range<usize> {
  3021. pieces_of(self.start as usize, from, to)
  3022. }
  3023. /// The offsets in the copy that piece `piece` holds.
  3024. fn piece(&self, piece: usize) -> (usize, usize) {
  3025. piece_at(self.start as usize, self.len as usize, piece)
  3026. }
  3027. /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is
  3028. /// not current there any more.
  3029. fn changed(&self, from: usize, to: usize) {
  3030. if !keeps() || from >= to {
  3031. return;
  3032. }
  3033. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  3034. if kept.0.is_empty() {
  3035. return;
  3036. }
  3037. for piece in self.pieces(from, to) {
  3038. kept.0[piece] = false;
  3039. }
  3040. }
  3041. /// Whether shaders of a submission not yet copied back may be writing
  3042. /// the copy.
  3043. pub(crate) fn writes_pending(&self) -> bool {
  3044. !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  3045. }
  3046. /// Whether one of those submissions may be writing in title memory
  3047. /// `[from, to)`.
  3048. pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool {
  3049. self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from)
  3050. }
  3051. /// Whether [`Shadow::update`] of `[address, address + len)` would leave
  3052. /// title bytes behind: a range shaders may be writing holds a page the
  3053. /// title wrote since the copy last took it. The answer comes from the
  3054. /// write-watch journal alone, as the submission's one asking left it
  3055. /// (`crate::watch::asked`); where the journal cannot say (memory not
  3056. /// write-watched, a range not asked about) it is yes. A page the copy
  3057. /// never took whole counts as written if the title ever wrote it.
  3058. ///
  3059. /// For submissions sent to the card without a wait
  3060. /// (`crate::host::late`): the ranges are those of flights in the air,
  3061. /// which are then settled before this refresh.
  3062. pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool {
  3063. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3064. let (from, to) = (address.max(start), (address + len).min(end));
  3065. if from >= to {
  3066. return false;
  3067. }
  3068. let busy: Vec<(usize, usize)> = self
  3069. .pending
  3070. .lock()
  3071. .unwrap_or_else(|e| e.into_inner())
  3072. .iter()
  3073. .filter(|&&(a, e)| a < to && e > from)
  3074. .map(|&(a, e)| (a.max(from), e.min(to)))
  3075. .collect();
  3076. if busy.is_empty() {
  3077. return false;
  3078. }
  3079. if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
  3080. return true;
  3081. }
  3082. let base = start / PAGE;
  3083. let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3084. busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) {
  3085. Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(),
  3086. None => true,
  3087. })
  3088. }
  3089. /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the
  3090. /// title changed into the copy, in the ranges shaders may be writing,
  3091. /// and only those bytes, so that what the shaders write beside them
  3092. /// stays (`crate::host::late_exact`). For each page of such a range
  3093. /// that the title wrote since the copy last took it, title memory as
  3094. /// it is now is compared with what the copy held when the range was
  3095. /// given to the shaders: the copy's CPU side for a copy in the card's
  3096. /// memory (the changed runs go up before the next submission, each a
  3097. /// copy of its own bytes, `runs_left` of them at most), the snapshot
  3098. /// for the others (the changed bytes go into the copy and into the
  3099. /// snapshot, so the compare after the card ran takes them for the
  3100. /// title's and not the shaders').
  3101. ///
  3102. /// Whether the caller must still settle the flights: the journal
  3103. /// cannot say what was written, a snapshot is missing, or `runs_left`
  3104. /// ran out. Pages done before that stay done.
  3105. pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool {
  3106. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3107. let (from, to) = (address.max(start), (address + len).min(end));
  3108. if from >= to {
  3109. return false;
  3110. }
  3111. let busy: Vec<(usize, usize)> = self
  3112. .pending
  3113. .lock()
  3114. .unwrap_or_else(|e| e.into_inner())
  3115. .iter()
  3116. .filter(|&&(a, e)| a < to && e > from)
  3117. .map(|&(a, e)| (a.max(from), e.min(to)))
  3118. .collect();
  3119. if busy.is_empty() {
  3120. return false;
  3121. }
  3122. if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
  3123. note_stale(0);
  3124. return true;
  3125. }
  3126. // The declared ranges overlap (views of the title's whole heap from
  3127. // dozens of offsets): as one range each page is asked about and
  3128. // compared once. Every byte of it is in a declared range, and of a
  3129. // copy in the PC's memory in the snapshot.
  3130. let busy = if crate::watch::light() { joined(busy) } else { busy };
  3131. let base = start / PAGE;
  3132. let mut title = vec![0u8; PAGE];
  3133. for (a, e) in busy {
  3134. // As the refresh itself asks (`update_free`): the journal if
  3135. // the submission's asking covered the range, else the kernel,
  3136. // else the guards. The journal alone said nothing for copies
  3137. // of view memory, which is guarded and not write-watched, and
  3138. // those were all of run 99's cases: the flights were settled
  3139. // 4-5 times a frame for "0 pages looked at".
  3140. let Some((now, written)) = crate::watch::writes(a, e, true) else {
  3141. note_stale(1);
  3142. return true;
  3143. };
  3144. let stale: Vec<usize> = {
  3145. let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3146. stale_pages_in(base, &copied, a, e, &written)
  3147. };
  3148. for page in stale {
  3149. let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
  3150. if lo >= hi {
  3151. continue;
  3152. }
  3153. let n = hi - lo;
  3154. let title = &mut title[..n];
  3155. // The lock of the copy's reference (the snapshot, or the
  3156. // CPU's side of a copy in the card's memory), from before
  3157. // title memory is read until the title's bytes are in: with
  3158. // the copy-back on its own thread ([`relay`]) that thread
  3159. // puts what the card wrote into title memory and into the
  3160. // reference under the same lock, and a page read before
  3161. // such a merge and compared after it would take the card's
  3162. // bytes for the title's.
  3163. let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
  3164. let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
  3165. // A page that is not there is left as it is, and looked at
  3166. // again next time.
  3167. if !crate::host::read_into(lo as *const u8, title) {
  3168. continue;
  3169. }
  3170. MERGED[0].fetch_add(1, Ordering::Relaxed);
  3171. let at = lo - start;
  3172. if self.card.is_some() {
  3173. // SAFETY: inside the mapping of the copy's CPU side,
  3174. // which only the submitting thread writes.
  3175. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
  3176. // Whole words go up as pairs, all of them in one
  3177. // dispatch: only what is a copy of its own counts.
  3178. let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) };
  3179. let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
  3180. let copies = runs.iter().filter(own).count();
  3181. if copies > *runs_left {
  3182. note_stale(2);
  3183. return true;
  3184. }
  3185. *runs_left -= copies;
  3186. let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
  3187. for &(r, m) in &runs {
  3188. held[r..r + m].copy_from_slice(&title[r..r + m]);
  3189. MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
  3190. }
  3191. MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3192. self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m)));
  3193. if let Some(was) = was {
  3194. crate::host::upcheck::note(self.id, at, &was, held);
  3195. }
  3196. } else {
  3197. let Some(snapshot) = before.as_mut() else {
  3198. note_stale(3);
  3199. return true;
  3200. };
  3201. // SAFETY: the snapshot's allocation holds the copy's
  3202. // bytes at the copy's offsets (`writing`), and these
  3203. // are in a declared range.
  3204. let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) };
  3205. for (r, m) in changed_runs(title, held) {
  3206. // SAFETY: inside the copy's mapping. The card may be
  3207. // writing the copy beside these bytes; they are
  3208. // written here and nothing around them.
  3209. unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
  3210. held[r..r + m].copy_from_slice(&title[r..r + m]);
  3211. MERGED[1].fetch_add(1, Ordering::Relaxed);
  3212. MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
  3213. }
  3214. }
  3215. drop(before);
  3216. drop(_merging);
  3217. // Taken, if the range holds all of the page that is in the
  3218. // copy; else the rest of it is the refresh's, which notes
  3219. // only whole pages, and the page is looked at again.
  3220. if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e {
  3221. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3222. if let Some(at) = copied.get_mut(page - base) {
  3223. *at = now;
  3224. }
  3225. }
  3226. }
  3227. }
  3228. false
  3229. }
  3230. /// At submission: copies what changed of `[address, address + len)`
  3231. /// since it was last copied (all of it if the memory is not
  3232. /// write-watched). Returns the bytes copied.
  3233. pub(crate) fn update(&self, address: usize, len: usize) -> usize {
  3234. // In place: the card reads title memory itself.
  3235. if self.place.is_some() {
  3236. return 0;
  3237. }
  3238. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3239. let (from, to) = (address.max(start), (address + len).min(end));
  3240. if from >= to {
  3241. return 0;
  3242. }
  3243. let mut busy: Vec<(usize, usize)> = self
  3244. .pending
  3245. .lock()
  3246. .unwrap_or_else(|e| e.into_inner())
  3247. .iter()
  3248. .copied()
  3249. .filter(|&(a, e)| a < to && e > from)
  3250. .collect();
  3251. if !busy.is_empty() {
  3252. // Around ranges shaders are writing: the gaps, each as below
  3253. // (in the world most submissions have such ranges; copying the
  3254. // gaps whole cost ~1 s per frame).
  3255. busy.sort_unstable();
  3256. let (mut at, mut bytes) = (from, 0);
  3257. for (a, e) in busy {
  3258. if a > at {
  3259. bytes += self.update_free(at, a);
  3260. }
  3261. at = at.max(e);
  3262. }
  3263. if at < to {
  3264. bytes += self.update_free(at, to);
  3265. }
  3266. return bytes;
  3267. }
  3268. self.update_free(from, to)
  3269. }
  3270. /// Whether [`Shadow::update`] of `[address, address + len)` would copy
  3271. /// nothing, and knows it without asking anything
  3272. /// (`crate::watch::nothing_new`). `false` if it would have to ask.
  3273. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool {
  3274. if self.place.is_some() {
  3275. return true;
  3276. }
  3277. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3278. let (from, to) = (address.max(start), (address + len).min(end));
  3279. if from >= to {
  3280. return true;
  3281. }
  3282. if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) {
  3283. return false;
  3284. }
  3285. // Around ranges shaders are writing the refresh asks gap by gap.
  3286. if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) {
  3287. return false;
  3288. }
  3289. let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3290. let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to));
  3291. #[cfg(feature = "diagnostics")]
  3292. if same {
  3293. use crate::copystat::{C, add};
  3294. add(C::Checked, (to - from) as u64);
  3295. add(C::Unchanged, (to - from) as u64);
  3296. }
  3297. same
  3298. }
  3299. /// The latest asking after which a range that holds `[from, to)` was
  3300. /// taken whole (0: none is known). The caller holds `copied`'s lock.
  3301. fn ranged(&self, from: usize, to: usize) -> u64 {
  3302. let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
  3303. ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0)
  3304. }
  3305. /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
  3306. /// shader writes.
  3307. fn update_free(&self, from: usize, to: usize) -> usize {
  3308. if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
  3309. if let Some((now, written)) = crate::watch::writes(from, to, true) {
  3310. let guarded = crate::watch::guarded(from, to);
  3311. self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
  3312. let copied = self.copy_stale(from, to, now, &written);
  3313. self.refresh_check(from, to);
  3314. #[cfg(feature = "diagnostics")]
  3315. {
  3316. use crate::copystat::{C, add};
  3317. add(C::Checked, (to - from) as u64);
  3318. add(C::Unchanged, (to - from).saturating_sub(copied) as u64);
  3319. }
  3320. return copied;
  3321. }
  3322. self.watched.store(NOT_WATCHED, Ordering::Relaxed);
  3323. }
  3324. #[cfg(feature = "diagnostics")]
  3325. crate::copystat::add(crate::copystat::C::WholeBytes, (to - from) as u64);
  3326. #[cfg(feature = "diagnostics")]
  3327. let started = std::time::Instant::now();
  3328. self.copy(from, to);
  3329. #[cfg(feature = "diagnostics")]
  3330. crate::copystat::whole(from, to - from, started.elapsed().as_micros() as u64);
  3331. to - from
  3332. }
  3333. /// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a
  3334. /// refresh of `[from, to)` that trusted the write watch or the guards,
  3335. /// the first 256 bytes of every 64 KiB block of it are read from title
  3336. /// memory and compared with the copy. A block that differs on three
  3337. /// refreshes in a row was changed with nothing to tell of it (a write
  3338. /// through another view of its pages, as DirectStorage's page
  3339. /// destinations make) and the card reads old bytes there: said with
  3340. /// the copy and the address. One that differs once is a write of the
  3341. /// title's that arrived between the refresh and the look.
  3342. fn refresh_check(&self, from: usize, to: usize) {
  3343. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  3344. if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) {
  3345. return;
  3346. }
  3347. const SAMPLE: usize = 256;
  3348. // Blocks found differing: how many refreshes in a row.
  3349. static DIFFERING: Mutex<Option<std::collections::HashMap<usize, u32>>> = Mutex::new(None);
  3350. static SAID: AtomicU64 = AtomicU64::new(0);
  3351. let start = self.start as usize;
  3352. let mut title = [0u8; SAMPLE];
  3353. let mut at = from;
  3354. while at < to {
  3355. let n = SAMPLE.min(to - at);
  3356. if crate::host::read_into(at as *const u8, &mut title[..n]) {
  3357. // SAFETY: `[from, to)` lies inside the buffer (`update`),
  3358. // so these bytes are inside the copy's mapping.
  3359. let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) };
  3360. let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner());
  3361. let map = map.get_or_insert_with(Default::default);
  3362. if copy == &title[..n] {
  3363. map.remove(&at);
  3364. } else {
  3365. let times = map.entry(at).or_insert(0);
  3366. *times += 1;
  3367. if *times == 3 {
  3368. let said = SAID.fetch_add(1, Ordering::Relaxed) + 1;
  3369. if said <= 64 || said.is_power_of_two() {
  3370. tracing::warn!(
  3371. said,
  3372. copy = self.id,
  3373. copy_start = format_args!("{start:#x}"),
  3374. copy_bytes = self.len,
  3375. address = format_args!("{at:#x}"),
  3376. refreshed = format_args!("{from:#x}..{to:#x}"),
  3377. on_the_card = self.card.is_some(),
  3378. window = self.window,
  3379. "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)"
  3380. );
  3381. }
  3382. }
  3383. }
  3384. }
  3385. // The first bytes of the next 64 KiB block.
  3386. at = (at / PAGE + 1) * PAGE;
  3387. }
  3388. }
  3389. /// Copies the pages of `[from, to)` written after their last copy
  3390. /// (`written`: last writes by page, in page order; `now`: this
  3391. /// asking), whole pages within the buffer.
  3392. fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize {
  3393. let base = self.start as usize / PAGE;
  3394. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3395. let mut writes = written.iter().peekable();
  3396. // Pages the range holds in part are never noted in `copied`, and
  3397. // were copied again at every refresh of the range, written or not:
  3398. // of the heap's buffer views alone two ends for each of 4,400
  3399. // copies, every frame. A range that was taken whole, and not written
  3400. // since, is as it was.
  3401. let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 };
  3402. let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>);
  3403. // Pages taken before and written since: in the order of their runs.
  3404. let mut again_at: Vec<(usize, u64)> = Vec::new();
  3405. let last = (to - 1) / PAGE;
  3406. for page in from / PAGE..=last {
  3407. let write = match writes.peek() {
  3408. Some(&&(p, w)) if p == page => {
  3409. writes.next();
  3410. w
  3411. }
  3412. _ => 0,
  3413. };
  3414. let at = &mut copied[page - base];
  3415. let taken = (*at).max(ranged);
  3416. if taken == 0 || write > taken {
  3417. // A page only partly in the range is copied in part: it
  3418. // stays stale for the rest.
  3419. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3420. if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to {
  3421. *at = now;
  3422. }
  3423. // Cut where pages taken before meet pages never taken.
  3424. let again = taken != 0;
  3425. if again {
  3426. again_at.push((page, taken));
  3427. }
  3428. if let Some((first, known)) = run
  3429. && known != again
  3430. {
  3431. runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known));
  3432. run = None;
  3433. }
  3434. run.get_or_insert((page, again));
  3435. } else if let Some((first, known)) = run.take() {
  3436. runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known));
  3437. }
  3438. }
  3439. // Cut to the range: next to it shaders may be writing the copy.
  3440. if let Some((first, known)) = run {
  3441. runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known));
  3442. }
  3443. let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at));
  3444. let bytes = self.take_all(runs);
  3445. if crate::watch::light() {
  3446. // All of the range is in the copy as of this asking.
  3447. let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
  3448. ranged[0] = (from, to, now);
  3449. if to - from >= ranged[1].1 - ranged[1].0 {
  3450. ranged[1] = (from, to, now);
  3451. }
  3452. }
  3453. bytes
  3454. }
  3455. /// [`Shadow::take`] of `runs` (from, to, known), on several threads if
  3456. /// they are long: the big heap's copy has some 4 MB of them in each of
  3457. /// 14 refreshes a frame, on one thread while the others had nothing.
  3458. fn take_all(&self, runs: Vec<(usize, usize, bool)>) -> usize {
  3459. const LONG: usize = 1 << 20;
  3460. const PART: usize = 256 << 10;
  3461. let bytes = runs.iter().map(|r| r.1 - r.0).sum();
  3462. if bytes < LONG || !crate::watch::light() {
  3463. for (from, to, known) in runs {
  3464. self.take(from, to, known);
  3465. }
  3466. return bytes;
  3467. }
  3468. let mut parts = Vec::with_capacity(bytes / PART + runs.len());
  3469. for (from, to, known) in runs {
  3470. let mut at = from;
  3471. while at < to {
  3472. // Whole pages to a part.
  3473. let next = ((at / PAGE) * PAGE + PART).min(to);
  3474. parts.push((at, next, known));
  3475. at = next;
  3476. }
  3477. }
  3478. let this = std::ptr::from_ref(self) as usize;
  3479. wide_each(parts.len(), move |i| {
  3480. // SAFETY: `wide_each` returns when every part is done, before
  3481. // the borrow of `self` ends. The parts lie apart.
  3482. let this = unsafe { &*(this as *const Shadow) };
  3483. let (from, to, known) = parts[i];
  3484. this.take(from, to, known);
  3485. });
  3486. bytes
  3487. }
  3488. /// Copies title memory `[from, to)` (inside the buffer) into the copy;
  3489. /// `known`: the copy held it before ([`send_changed`]).
  3490. fn take(&self, from: usize, to: usize, known: bool) -> usize {
  3491. thread_local! {
  3492. /// A page of title memory, as read.
  3493. static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
  3494. }
  3495. let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else {
  3496. return self.copy(from, to);
  3497. };
  3498. let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
  3499. let start = self.start as usize;
  3500. TITLE.with_borrow_mut(|title| {
  3501. title.resize(PAGE, 0);
  3502. let mut at = from;
  3503. while at < to {
  3504. let n = (PAGE - at % PAGE).min(to - at);
  3505. let title = &mut title[..n];
  3506. // (Pages that are not there read as zeros.)
  3507. crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false);
  3508. // SAFETY: inside the mapping of the copy's CPU side, which
  3509. // nothing else reads or writes there (the card copies from
  3510. // it): no shader's range holds it, and the parts of a
  3511. // refresh lie apart.
  3512. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) };
  3513. let was = crate::host::upcheck::on().then(|| held.to_vec());
  3514. let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) };
  3515. for &(a, len) in &runs {
  3516. held[a..a + len].copy_from_slice(&title[a..a + len]);
  3517. self.changed(at - start + a, at - start + a + len);
  3518. }
  3519. self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
  3520. if let Some(was) = was {
  3521. crate::host::upcheck::note(self.id, at - start, &was, held);
  3522. }
  3523. SEND[0].fetch_add(n as u64, Ordering::Relaxed);
  3524. if runs.is_empty() {
  3525. SEND[1].fetch_add(n as u64, Ordering::Relaxed);
  3526. }
  3527. SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
  3528. SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3529. at += n;
  3530. }
  3531. });
  3532. to - from
  3533. }
  3534. /// Copies title memory `[from, to)`, cut to the buffer, into the copy.
  3535. fn copy(&self, from: usize, to: usize) -> usize {
  3536. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3537. let (from, to) = (from.max(start), to.min(end));
  3538. // SAFETY: inside the mapping (`from` and `to` are within the buffer).
  3539. let at = unsafe { self.data.add(from - start) };
  3540. if self.card.is_some() && from < to && crate::host::upcheck::on() {
  3541. for_pieces_of(from - start, to - start, |a, b| {
  3542. let was = self.card_held(a, b - a);
  3543. // SAFETY: inside the mapping, as above.
  3544. crate::host::copy_mapped(unsafe { self.data.add(a) }, (start + a) as *const u8, b - a, false);
  3545. crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a));
  3546. });
  3547. } else {
  3548. crate::host::copy_mapped(at, from as *const u8, to - from, false);
  3549. }
  3550. // After the bytes are in: a snapshot taken meanwhile is not current.
  3551. self.changed(from - start, to - start);
  3552. self.card_changed(from - start, to - start);
  3553. to - from
  3554. }
  3555. /// Whether shaders read and write this copy in the card's own memory
  3556. /// ([`cards`]).
  3557. pub(crate) fn carded(&self) -> bool {
  3558. self.card.is_some()
  3559. }
  3560. /// Shaders store in it what is not declared: from here on only the dwords
  3561. /// the title changes go up ([`by_address`]).
  3562. pub(crate) fn keep_stores(&self) {
  3563. self.changes_only.store(true, Ordering::Relaxed);
  3564. }
  3565. /// Offsets `[from, to)` go up again whole, as the CPU's side has them.
  3566. pub(crate) fn resend(&self, from: usize, to: usize) {
  3567. self.card_changed(from, to);
  3568. }
  3569. /// The CPU side's bytes at offsets `[from, to)` changed: they go to the
  3570. /// card's side before the next submission.
  3571. fn card_changed(&self, from: usize, to: usize) {
  3572. self.card_changed_runs(std::iter::once((from, to)));
  3573. }
  3574. /// [`Shadow::card_changed`] of each of `runs`.
  3575. fn card_changed_runs(&self, runs: impl Iterator<Item = (usize, usize)>) {
  3576. let Some(card) = &self.card else {
  3577. return;
  3578. };
  3579. let mut runs = runs.filter(|r| r.0 < r.1).peekable();
  3580. if runs.peek().is_none() {
  3581. return;
  3582. }
  3583. let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
  3584. for (from, to) in runs {
  3585. match dirty.last_mut() {
  3586. Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)),
  3587. _ => dirty.push((from, to)),
  3588. }
  3589. }
  3590. // (Under the lock: what takes the list sees it or finds it set.)
  3591. card.touched.store(true, Ordering::Release);
  3592. }
  3593. /// Whether shaders were ever declared to write it.
  3594. pub(crate) fn written(&self) -> bool {
  3595. self.written.load(Ordering::Relaxed)
  3596. }
  3597. /// `bytes` were put into title memory at `address`, and the submission
  3598. /// being prepared copies the same to the copy at that copy's place in its
  3599. /// list: the reference (the CPU's side of a copy in the card's memory, the
  3600. /// snapshot) takes them and nothing is sent. What the card makes of them
  3601. /// is then what differs from them when the submission has run. The range
  3602. /// is declared written by it, and its sends are taken.
  3603. pub(crate) fn placed_copy(&self, address: usize, bytes: &[u8]) {
  3604. let (from, to) = self.inside(address, bytes.len());
  3605. if from >= to || self.place.is_some() {
  3606. return;
  3607. }
  3608. let bytes = &bytes[self.start as usize + from - address..][..to - from];
  3609. let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
  3610. if self.card.is_some() {
  3611. // SAFETY: inside the mapping of the CPU's side, in a range no
  3612. // refresh writes; the lock keeps the landing out.
  3613. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data.add(from), bytes.len()) };
  3614. } else if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
  3615. // SAFETY: the snapshot's allocation holds the copy's length.
  3616. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), snapshot.as_mut_ptr().add(from), bytes.len()) };
  3617. }
  3618. self.changed(from, to);
  3619. }
  3620. /// Of a copy in the card's memory: where its CPU side is.
  3621. pub(crate) fn card_data(&self) -> *const u8 {
  3622. self.data
  3623. }
  3624. /// Diagnostics: of a copy in the card's memory, what its CPU side holds
  3625. /// at offsets `[at, at + len)` (cut to the copy).
  3626. pub(crate) fn card_held(&self, at: usize, len: usize) -> Vec<u8> {
  3627. let to = (at + len).min(self.len as usize);
  3628. if self.card.is_none() || at >= to {
  3629. return Vec::new();
  3630. }
  3631. // SAFETY: inside the mapping; the caller holds the submission lock,
  3632. // under which it is written but for what is being landed.
  3633. unsafe { std::slice::from_raw_parts(self.data.add(at).cast_const(), to - at) }.to_vec()
  3634. }
  3635. /// Diagnostics: the offsets whose bytes have not gone to the card's side
  3636. /// yet.
  3637. pub(crate) fn card_dirty_now(&self) -> Vec<(usize, usize)> {
  3638. self.card.as_ref().map_or_else(Vec::new, |c| c.dirty.lock().unwrap_or_else(|e| e.into_inner()).clone())
  3639. }
  3640. /// Of a copy in the card's memory: the CPU's side (PC memory), the
  3641. /// card side's bytes from before if made yet, and their size.
  3642. pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> {
  3643. let card = self.card.as_ref()?;
  3644. let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone();
  3645. Some((&card.staging, before, card.size))
  3646. }
  3647. /// Shader writes are declared for a copy in the card's memory: makes
  3648. /// its "before" twin with `make` (bytes to buffer) if it has none.
  3649. /// Whether one was made now: the caller fills it, whole, from the
  3650. /// card's side before the submission's lists run. Without one (no
  3651. /// memory) every piece of a declared range is fetched.
  3652. pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option<ID3D12Resource>) -> bool {
  3653. let Some(card) = &self.card else {
  3654. return false;
  3655. };
  3656. let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner());
  3657. if before.is_some() {
  3658. return false;
  3659. }
  3660. *before = make(card.size);
  3661. if before.is_some() {
  3662. CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed);
  3663. }
  3664. before.is_some()
  3665. }
  3666. /// The declared range `[address, end)` as the compare on the card
  3667. /// takes it; `None` if none of it lies in the copy.
  3668. pub(crate) fn card_span(&self, address: usize, end: usize) -> Option<CardSpan> {
  3669. let (from, to) = self.inside(address, end.saturating_sub(address));
  3670. (from < to).then(|| card_span_of(self.start as usize, from, to))
  3671. }
  3672. /// The pieces that hold offsets `[from, to)` of the copy (cut to it),
  3673. /// as the card's hashing takes them.
  3674. pub(crate) fn card_run(&self, from: usize, to: usize) -> CardSpan {
  3675. let to = to.min(self.len as usize);
  3676. card_span_of(self.start as usize, from.min(to.saturating_sub(1)), to)
  3677. }
  3678. /// The offsets of piece `i` of `span` that lie in the span.
  3679. pub(crate) fn card_piece(&self, span: &CardSpan, i: u32) -> (usize, usize) {
  3680. card_piece_of(self.start as usize, self.len as usize, span, i)
  3681. }
  3682. /// The piece that holds offset `at`.
  3683. pub(crate) fn card_piece_of(&self, at: usize) -> u32 {
  3684. self.pieces(at, at + 1).start as u32
  3685. }
  3686. /// The offsets the compare on the card hashes of a piece: what lies of
  3687. /// it in the card's buffer (which may be longer than the copy), widened
  3688. /// to 16 bytes.
  3689. pub(crate) fn card_hashed(&self, piece: u32) -> (usize, usize) {
  3690. let size = self.card.as_ref().map_or(self.len, |c| c.size) as usize;
  3691. card_hashed_of(self.start as usize, size, piece as usize)
  3692. }
  3693. /// The walls trace (`crate::host::walls_trace`): a piece of `fetched`
  3694. /// bytes of this copy came back from the card and `written` of them
  3695. /// went into title memory. Summed per buffer and logged once a frame:
  3696. /// which shader-written buffers the title's CPU could see fresh in
  3697. /// that frame, and how much of each changed.
  3698. pub(crate) fn walls_merged(&self, fetched: usize, written: usize) {
  3699. if !crate::host::walls_trace() {
  3700. return;
  3701. }
  3702. static SEEN: Mutex<(u64, BTreeMap<u64, (u64, u32, u64, u64)>)> = Mutex::new((0, BTreeMap::new()));
  3703. let frame = crate::frame::current();
  3704. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  3705. if seen.0 != frame {
  3706. let buffers: Vec<String> = seen
  3707. .1
  3708. .iter()
  3709. .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3))
  3710. .take(32)
  3711. .collect();
  3712. if !buffers.is_empty() {
  3713. tracing::info!(
  3714. frame = seen.0,
  3715. count = seen.1.len(),
  3716. buffers = ?buffers,
  3717. "walls trace: shader-written card buffers merged into title memory in this frame"
  3718. );
  3719. }
  3720. seen.1.clear();
  3721. seen.0 = frame;
  3722. }
  3723. let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0));
  3724. entry.1 += 1;
  3725. entry.2 += fetched as u64;
  3726. entry.3 += written as u64;
  3727. }
  3728. /// After a submission, for a copy in the card's memory: `gpu` is what
  3729. /// the card's side holds at offset `at` on, in a piece the compare
  3730. /// found differing. The bytes shaders wrote (those that differ from the
  3731. /// CPU's side, which is what the card's side held when they started)
  3732. /// go into title memory, from the first to the last of them, as
  3733. /// [`Shadow::copy_back`] puts them; the CPU's side takes the result and
  3734. /// sends it up before the next submission. `title` is scratch memory.
  3735. /// Returns the bytes written to title memory.
  3736. pub(crate) fn card_merge(&self, at: usize, gpu: &[u8], title: &mut Vec<u8>) -> usize {
  3737. let start = self.start as usize;
  3738. if self.card.is_none() || at + gpu.len() > self.len as usize {
  3739. return 0;
  3740. }
  3741. // SAFETY: inside the mapping (checked above); only the submitting
  3742. // thread writes it.
  3743. let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) };
  3744. let Some(first) = first_difference(gpu, old) else {
  3745. return 0;
  3746. };
  3747. let last = last_difference(gpu, old).unwrap_or(first);
  3748. let (at, n) = (at + first, last + 1 - first);
  3749. let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]);
  3750. title.clear();
  3751. title.resize(n, 0);
  3752. let mut written = 0;
  3753. if crate::host::read_into((start + at) as *const u8, title) {
  3754. // The stretch as read: what the card did not change is the
  3755. // title's, and may have been written again since.
  3756. // As in `copy_back`: the card's byte where it is not what it
  3757. // was before the submission, else the title's.
  3758. let mut differs = 0u8;
  3759. let was = title.clone();
  3760. for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) {
  3761. let wrote = if *g != *o { 0xffu8 } else { 0 };
  3762. let merged = (*t & !wrote) | (*g & wrote);
  3763. differs |= merged ^ *t;
  3764. *t = merged;
  3765. *o = merged;
  3766. }
  3767. if differs != 0 {
  3768. written = put_changed(start + at, &was, title);
  3769. }
  3770. } else {
  3771. // Title memory is not mapped there: the copy keeps what the
  3772. // card wrote, as before.
  3773. old.copy_from_slice(gpu);
  3774. }
  3775. // The card's side and its "before" take the result.
  3776. self.card_changed(at, at + n);
  3777. written
  3778. }
  3779. /// [`relay`], for a copy in the card's memory: `gpu` is what the
  3780. /// card's side held at offset `at` on when a fetch sent after send
  3781. /// `fetched_after` (`crate::host`'s order of the queue) ran, in a piece
  3782. /// the compare found differing. The bytes that differ from the CPU's
  3783. /// side are what shaders wrote; they go into title memory, from the
  3784. /// first to the last of them, and into the CPU's side. Nothing is sent
  3785. /// up afterwards (the card holds these bytes or newer ones: sending
  3786. /// them up could undo a later flight's write), and the title's other
  3787. /// bytes are left to the refresh.
  3788. ///
  3789. /// Left out: bytes of the CPU's side that hold title bytes the card
  3790. /// had not received when the fetch ran, those still to go up and those
  3791. /// that went up with a later send. There the card's side is the older
  3792. /// one, and taking it for a shader's write would put it over what the
  3793. /// title wrote. Under the CPU side's lock (the snapshot's, which such
  3794. /// a copy has no other use for), as [`Shadow::merge_under_writes`].
  3795. /// `title` is scratch memory. Returns the bytes written to title
  3796. /// memory.
  3797. pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec<u8>) -> usize {
  3798. let start = self.start as usize;
  3799. let Some(card) = &self.card else {
  3800. return 0;
  3801. };
  3802. if at + gpu.len() > self.len as usize {
  3803. return 0;
  3804. }
  3805. let _side = self.before.lock().unwrap_or_else(|e| e.into_inner());
  3806. // SAFETY: inside the mapping (checked above). The offsets are in a
  3807. // range declared and not done with, which no refresh writes; what
  3808. // does write it (the title's bytes put in under shader writes)
  3809. // holds the lock held here.
  3810. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) };
  3811. let Some(first) = first_difference(gpu, held) else {
  3812. return 0;
  3813. };
  3814. let last = last_difference(gpu, held).unwrap_or(first);
  3815. let (at, n) = (at + first, last + 1 - first);
  3816. let (gpu, held) = (&gpu[first..=last], &mut held[first..=last]);
  3817. let skip: Vec<(usize, usize)> = {
  3818. let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
  3819. let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
  3820. let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < at + n && b > at).collect();
  3821. sent.near(fetched_after, at, at + n, &mut skip);
  3822. skip
  3823. };
  3824. title.clear();
  3825. title.resize(n, 0);
  3826. let mapped = crate::host::read_into((start + at) as *const u8, title);
  3827. let was = title.clone();
  3828. let mut changed = false;
  3829. for (a, b) in outside(at, at + n, skip) {
  3830. let (a, b) = (a - at, b - at);
  3831. // Title memory that is not mapped: the CPU's side keeps what
  3832. // the card wrote, as before; `title` is scratch then.
  3833. changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]);
  3834. }
  3835. if !mapped || !changed {
  3836. return 0;
  3837. }
  3838. put_changed(start + at, &was, title)
  3839. }
  3840. }
  3841. /// For tests: copies with no host buffer behind them.
  3842. #[cfg(test)]
  3843. impl Shadow {
  3844. /// A copy at `data` of title memory `[start, start + len)`, with a card
  3845. /// side if `card`. It is never let go: there is no buffer to release.
  3846. pub(crate) fn unbacked(start: u64, data: *mut u8, len: u64, card: bool) -> Arc<Shadow> {
  3847. // SAFETY: an interface pointer nothing calls.
  3848. let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) };
  3849. let mut shadow = Shadow::new(none(), data, 0, start, len);
  3850. if card {
  3851. shadow.card = Some(Card {
  3852. staging: none(),
  3853. before: Mutex::default(),
  3854. dirty: Mutex::default(),
  3855. sent: Mutex::default(),
  3856. touched: Default::default(),
  3857. size: len.next_multiple_of(PIECE as u64),
  3858. });
  3859. }
  3860. let shadow = Arc::new(shadow);
  3861. std::mem::forget(shadow.clone());
  3862. shadow
  3863. }
  3864. /// What shaders wrote goes into title memory ([`put_changed`]).
  3865. pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) {
  3866. put_changed(at, title, merged);
  3867. }
  3868. /// What is to go up to the card, noted as sent with `number`, as
  3869. /// [`card_dirty`] does; notes of sends up to `merged` go.
  3870. pub(crate) fn send_up(&self, number: u64, merged: u64) -> Vec<(usize, usize)> {
  3871. let card = self.card.as_ref().unwrap();
  3872. let mut dirty = card.dirty.lock().unwrap();
  3873. let ranges = std::mem::take(&mut *dirty);
  3874. let mut sent = card.sent.lock().unwrap();
  3875. sent.forget(merged);
  3876. sent.note(number, ranges.clone());
  3877. ranges
  3878. }
  3879. /// What is to go up to the card, taken.
  3880. pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> {
  3881. std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap())
  3882. }
  3883. }
  3884. impl Shadow {
  3885. /// [`Shadow::card_merge_relay`] of several pieces, each within one
  3886. /// 64 KiB block of title memory: from and to (offsets in the copy), and
  3887. /// where the fetched bytes are. On any thread: several may land pieces
  3888. /// of one copy, no two the same bytes. Returns the bytes put into title
  3889. /// memory.
  3890. ///
  3891. /// What is left out is as there, asked once for all of them: the notes
  3892. /// of bytes that went up (or are to go up) behind the fetch only move
  3893. /// from `dirty` to `sent`, with a later number, and grow only by
  3894. /// [`Shadow::merge_under_writes`], which the lock held here keeps out.
  3895. ///
  3896. /// # Safety
  3897. /// The third of each piece is the address of its bytes, which stay as
  3898. /// they are during the call.
  3899. pub(crate) unsafe fn land_card(&self, pieces: &[(usize, usize, usize)], fetched_after: u64, notes: &mut crate::land::Notes) -> u64 {
  3900. let Some(card) = &self.card else {
  3901. return 0;
  3902. };
  3903. let waiting = std::time::Instant::now();
  3904. let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
  3905. crate::land::spent(crate::land::stat::LOCK, waiting);
  3906. let (from, to) = pieces.iter().fold((usize::MAX, 0), |(a, b), p| (a.min(p.0), b.max(p.1)));
  3907. let skip: Vec<(usize, usize)> = {
  3908. let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
  3909. let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
  3910. let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < to && b > from).collect();
  3911. sent.near(fetched_after, from, to, &mut skip);
  3912. skip
  3913. };
  3914. let mut put = 0;
  3915. for &(lo, hi, now) in pieces {
  3916. if lo >= hi || hi > self.len as usize {
  3917. continue;
  3918. }
  3919. let near: Vec<(usize, usize)> = skip.iter().copied().filter(|&(a, b)| a < hi && b > lo).collect();
  3920. let parts: Vec<(usize, usize)> = outside(lo, hi, near).into_iter().map(|(a, b)| (a - lo, b - lo)).collect();
  3921. // SAFETY: inside the mapping (checked above), in a range
  3922. // declared and not done with, which no refresh writes; the
  3923. // title's bytes are kept out by the lock; the caller's.
  3924. // Where title memory is not mapped the CPU's side keeps what
  3925. // the card wrote, as before.
  3926. let merged =
  3927. unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) };
  3928. self.walls_merged(hi - lo, merged as usize);
  3929. put += merged;
  3930. }
  3931. put
  3932. }
  3933. /// [`Shadow::relay_merge`] of a piece `[at, at + n)` (within one 64 KiB
  3934. /// block of title memory) of a copy in the PC's memory; on any thread,
  3935. /// as [`Shadow::land_card`]. The copy is read once and never written.
  3936. /// Returns the bytes put into title memory.
  3937. pub(crate) fn land_back(&self, at: usize, n: usize, notes: &mut crate::land::Notes) -> u64 {
  3938. if self.card.is_some() || n == 0 || at + n > self.len as usize {
  3939. return 0;
  3940. }
  3941. let waiting = std::time::Instant::now();
  3942. let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
  3943. crate::land::spent(crate::land::stat::LOCK, waiting);
  3944. // The snapshot's memory stays where it is until the range is done
  3945. // with (`copy_back_done`), which comes after this.
  3946. let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else {
  3947. return 0;
  3948. };
  3949. // SAFETY: inside the copy's mapping (checked above), which only the
  3950. // card writes there, and inside the snapshot's allocation, which
  3951. // holds the copy's length (`writing`): these offsets are in a range
  3952. // declared and not done with, whose bytes it holds, and the lock
  3953. // keeps out what else writes them. Title memory that is not there
  3954. // is looked at again when the next flight that declared the range
  3955. // lands.
  3956. unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) }
  3957. }
  3958. /// What shaders wrote in 64 KiB block `block` (of title memory) of this
  3959. /// copy was put into title memory beside the guard, which was noted as a
  3960. /// write with number `now`, `before` the number of the block's last write
  3961. /// before. If the copy held title memory's bytes of the block ahead of
  3962. /// that it holds them still, and is noted to ([`crate::land`] says why);
  3963. /// whether it was.
  3964. ///
  3965. /// That it did: it took the whole block after that write, and no other
  3966. /// came that is not noted yet. Looked at after the note, whatever comes
  3967. /// later has a number above it: a write of the title's takes the block's
  3968. /// bit, until an asking has noted it.
  3969. pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool {
  3970. let Some(page) = block.checked_sub(self.start as usize / PAGE) else {
  3971. return false;
  3972. };
  3973. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3974. let Some(at) = copied.get_mut(page) else {
  3975. return false;
  3976. };
  3977. let held = *at != 0 && *at >= before && crate::watch::block_published(block);
  3978. if held {
  3979. *at = (*at).max(now);
  3980. }
  3981. held
  3982. }
  3983. }
  3984. #[cfg(test)]
  3985. mod land_tests {
  3986. use super::{Card, PIECE, Shadow};
  3987. use std::sync::Mutex;
  3988. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  3989. /// A copy in the card's memory of title memory at `title` (its card side
  3990. /// is never looked at here), all bytes 0 on the CPU's side.
  3991. fn copy_of(title: usize, len: usize) -> Option<Shadow> {
  3992. let (buffer, data) = crate::host::host()?.shared_buffer(len as u64)?;
  3993. // SAFETY: the mapping, `len` bytes.
  3994. unsafe { std::ptr::write_bytes(data, 0, len) };
  3995. let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64);
  3996. shadow.card = Some(Card {
  3997. staging: buffer,
  3998. before: Mutex::default(),
  3999. dirty: Mutex::default(),
  4000. sent: Mutex::default(),
  4001. touched: Default::default(),
  4002. size: len as u64,
  4003. });
  4004. Some(shadow)
  4005. }
  4006. /// Memory that stays (`crate::watch` knows its addresses): private, or a
  4007. /// view noted as the runtime notes the title's.
  4008. fn memory(len: usize, view: bool) -> usize {
  4009. use windows_sys::Win32::System::Memory as mem;
  4010. // SAFETY: plain allocations of our own.
  4011. unsafe {
  4012. if !view {
  4013. return mem::VirtualAlloc(std::ptr::null(), len, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize;
  4014. }
  4015. let section = mem::CreateFileMappingW(-1isize as _, std::ptr::null(), mem::PAGE_READWRITE, 0, len as u32, std::ptr::null());
  4016. let at = mem::MapViewOfFile(section, mem::FILE_MAP_WRITE, 0, 0, len).Value as usize;
  4017. crate::inplace::title_memory_section(section as usize, len as u64, true);
  4018. crate::title_memory_remapped(at, len);
  4019. crate::inplace::title_memory_view(at, len, section as usize, 0);
  4020. at
  4021. }
  4022. }
  4023. fn random(seed: &mut u64) -> usize {
  4024. *seed ^= *seed << 13;
  4025. *seed ^= *seed >> 7;
  4026. *seed ^= *seed << 17;
  4027. (*seed >> 8) as usize
  4028. }
  4029. /// [`Shadow::land_card`] leaves title memory and the CPU's side as
  4030. /// [`Shadow::card_merge_relay`] does, with title bytes that went up
  4031. /// behind the fetch, or have not gone up, left out.
  4032. #[test]
  4033. fn pieces_land_as_the_merge_one_by_one_lands_them() {
  4034. assert!(crate::safecopy::on());
  4035. const LEN: usize = 3 * PIECE;
  4036. let mut seed = 0x1234_5678_9abcu64;
  4037. for view in [false, true] {
  4038. let (a, b) = (memory(LEN, view), memory(LEN, view));
  4039. let (Some(one), Some(many)) = (copy_of(a, LEN), copy_of(b, LEN)) else {
  4040. return; // no host GPU
  4041. };
  4042. // SAFETY: the two memories and the two mappings.
  4043. let bytes = |at: usize| unsafe { std::slice::from_raw_parts_mut(at as *mut u8, LEN) };
  4044. for round in 0..40u32 {
  4045. let base: Vec<u8> = (0..LEN).map(|_| random(&mut seed) as u8).collect();
  4046. let (mut held, mut title, mut now) = (base.clone(), base.clone(), base);
  4047. let (mut dirty, mut sent) = (Vec::new(), Vec::new());
  4048. for k in 0..120 {
  4049. let at = random(&mut seed) % LEN / 4 * 4;
  4050. let n = (random(&mut seed) % 900 / 4 * 4).min(LEN - at);
  4051. match k % 4 {
  4052. 0 | 1 => now[at..at + n].fill(random(&mut seed) as u8),
  4053. 2 => title[at..at + n].fill(random(&mut seed) as u8),
  4054. // Title bytes put into the CPU's side meanwhile.
  4055. _ => {
  4056. let byte = random(&mut seed) as u8;
  4057. held[at..at + n].fill(byte);
  4058. title[at..at + n].fill(byte);
  4059. if k % 8 == 3 {
  4060. dirty.push((at, at + n));
  4061. } else {
  4062. sent.push((at, at + n, u64::from(round % 3) + (k as u64 / 16)));
  4063. }
  4064. }
  4065. }
  4066. }
  4067. let after = 4u64;
  4068. for (shadow, at) in [(&one, a), (&many, b)] {
  4069. crate::watch::writing(at, LEN);
  4070. bytes(at).copy_from_slice(&title);
  4071. bytes(shadow.data as usize).copy_from_slice(&held);
  4072. let card = shadow.card.as_ref().expect("made with one");
  4073. *card.dirty.lock().unwrap() = dirty.clone();
  4074. *card.sent.lock().unwrap() = super::SentRuns::of(&sent);
  4075. }
  4076. let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect();
  4077. let mut scratch = Vec::new();
  4078. for &(lo, hi) in &pieces {
  4079. one.card_merge_relay(lo, &now[lo..hi], after, &mut scratch);
  4080. }
  4081. let addressed: Vec<(usize, usize, usize)> =
  4082. pieces.iter().map(|&(lo, hi)| (lo, hi, now.as_ptr() as usize + lo)).collect();
  4083. let mut notes = crate::land::Notes::default();
  4084. // SAFETY: the fetched bytes are `now`'s.
  4085. unsafe { many.land_card(&addressed, after, &mut notes) };
  4086. notes.flush();
  4087. assert!(bytes(a) == bytes(b), "title memory, round {round}");
  4088. assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}");
  4089. }
  4090. }
  4091. }
  4092. /// Landings of one copy on several threads, the title writing dwords of
  4093. /// the same blocks, and the title's bytes put into the CPU's side under
  4094. /// the shaders' writes ([`Shadow::merge_under_writes`]), all at once. The
  4095. /// card has never received the title's bytes: what is fetched holds older
  4096. /// ones there, which must not be taken for shaders' writes.
  4097. #[test]
  4098. fn landings_and_title_bytes_going_in_keep_each_others_bytes() {
  4099. assert!(crate::safecopy::on());
  4100. const BLOCKS: usize = 16;
  4101. const LEN: usize = BLOCKS * PIECE;
  4102. let title = memory(LEN, true);
  4103. let Some(shadow) = copy_of(title, LEN) else {
  4104. return; // no host GPU
  4105. };
  4106. shadow.pending.lock().unwrap().push((title, title + LEN));
  4107. // SAFETY: committed, aligned; touched as atomics or by the landing's
  4108. // stores of whole dwords.
  4109. let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) };
  4110. let stop = AtomicBool::new(false);
  4111. std::thread::scope(|s| {
  4112. let writer = s.spawn(|| {
  4113. let mut value = 1u32;
  4114. while !stop.load(Ordering::Relaxed) {
  4115. for i in (1..LEN / 4).step_by(4 * 331) {
  4116. assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
  4117. }
  4118. value += 1;
  4119. std::thread::sleep(std::time::Duration::from_micros(200));
  4120. }
  4121. value - 1
  4122. });
  4123. s.spawn(|| {
  4124. while !stop.load(Ordering::Relaxed) {
  4125. let mut runs = usize::MAX;
  4126. assert!(!shadow.merge_under_writes(title, LEN, &mut runs));
  4127. // Sent up, as the preparing of a submission would: noted
  4128. // with a number behind the fetches'.
  4129. let card = shadow.card.as_ref().expect("made with one");
  4130. let mut dirty = card.dirty.lock().unwrap();
  4131. let mut sent = card.sent.lock().unwrap();
  4132. sent.note(9, std::mem::take(&mut *dirty));
  4133. }
  4134. });
  4135. let mut now = vec![0u8; LEN];
  4136. for round in 1..200u32 {
  4137. for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) {
  4138. for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) {
  4139. now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes());
  4140. }
  4141. }
  4142. let at = now.as_ptr() as usize;
  4143. crate::land::each(BLOCKS, &|b| {
  4144. let mut notes = crate::land::Notes::default();
  4145. let (lo, hi) = (b * PIECE, (b + 1) * PIECE);
  4146. // SAFETY: the fetched bytes are `now`'s; each block once.
  4147. unsafe { shadow.land_card(&[(lo, hi, at + lo)], 8, &mut notes) };
  4148. notes.flush();
  4149. });
  4150. for i in (3..LEN / 4).step_by(4 * 53) {
  4151. let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
  4152. assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
  4153. }
  4154. }
  4155. stop.store(true, Ordering::Relaxed);
  4156. let last = writer.join().expect("nothing undone");
  4157. assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last));
  4158. });
  4159. }
  4160. }
  4161. struct Entry {
  4162. end: u64,
  4163. shadow: Option<Arc<Shadow>>,
  4164. }
  4165. /// Title buffers by (start address, resource), with their copy once made.
  4166. ///
  4167. /// Read by every view a draw names, on all recording threads at once, and
  4168. /// written when a buffer comes, goes or gets its copy: readers share it.
  4169. static BUFFERS: std::sync::RwLock<BTreeMap<(u64, usize), Entry>> = std::sync::RwLock::new(BTreeMap::new());
  4170. fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> {
  4171. let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner());
  4172. // What threads remember of it ([`FOUND`]) is of before.
  4173. BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst);
  4174. map
  4175. }
  4176. /// How often [`BUFFERS`] was taken to be changed.
  4177. static BUFFERS_CHANGED: AtomicU64 = AtomicU64::new(1);
  4178. /// Answers a thread remembers.
  4179. const FOUND_MOST: usize = 1024;
  4180. /// An ask (address, bytes), the count of changes it was answered at, and the
  4181. /// answer.
  4182. type Found = (u64, u64, u64, std::sync::Weak<Shadow>);
  4183. thread_local! {
  4184. /// The last answers of [`lookup`] out of [`BUFFERS`], by a hash of the
  4185. /// ask: the same buffers are asked about draw after draw, from five
  4186. /// threads, each time through the map's lock and a dozen of its nodes
  4187. /// (7 % of the recording threads' time, profile waits-1).
  4188. static FOUND: std::cell::RefCell<Vec<Found>> = const { std::cell::RefCell::new(Vec::new()) };
  4189. }
  4190. /// Whether [`FOUND`] is kept (`VICTORY_QUICK_FIND=0`: not).
  4191. fn quick_find() -> bool {
  4192. crate::toggled!("VICTORY_QUICK_FIND")
  4193. }
  4194. fn found_at(address: u64, len: u64) -> usize {
  4195. let h = (address ^ len.rotate_left(32)).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  4196. (h >> 54) as usize % FOUND_MOST
  4197. }
  4198. /// What this thread remembers of an ask, if nothing changed since.
  4199. fn found(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4200. let changed = BUFFERS_CHANGED.load(Ordering::SeqCst);
  4201. let shadow = FOUND.with(|f| {
  4202. let f = f.borrow();
  4203. let (a, n, at, shadow) = f.get(found_at(address, len))?;
  4204. ((*a, *n, *at) == (address, len, changed)).then(|| shadow.upgrade()).flatten()
  4205. })?;
  4206. // Whoever takes the map to let a copy go that nobody holds finds it held
  4207. // now, or had counted before: then it is not handed out.
  4208. std::sync::atomic::fence(Ordering::SeqCst);
  4209. (BUFFERS_CHANGED.load(Ordering::SeqCst) == changed).then_some(shadow)
  4210. }
  4211. /// Remembers an answer given while `changed` was the count.
  4212. fn remember(address: u64, len: u64, changed: u64, shadow: &Arc<Shadow>) {
  4213. FOUND.with(|f| {
  4214. let mut f = f.borrow_mut();
  4215. if f.is_empty() {
  4216. f.resize_with(FOUND_MOST, || (0, 0, 0, std::sync::Weak::new()));
  4217. }
  4218. f[found_at(address, len)] = (address, len, changed, Arc::downgrade(shadow));
  4219. });
  4220. }
  4221. fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> {
  4222. BUFFERS.read().unwrap_or_else(|e| e.into_inner())
  4223. }
  4224. /// A title buffer exists at `start` (`len` bytes).
  4225. pub(crate) fn register(resource: usize, start: u64, len: u64) {
  4226. buffers().insert(
  4227. (start, resource),
  4228. Entry {
  4229. end: start + len,
  4230. shadow: None,
  4231. },
  4232. );
  4233. }
  4234. /// The title released it; lists that still hold its copy keep it alive.
  4235. pub(crate) fn unregister(resource: usize, start: u64) {
  4236. buffers().remove(&(start, resource));
  4237. }
  4238. /// The title buffer holding `address`, as (start, length), without making
  4239. /// its copy (diagnostics: which buffer a dropped program's root view names).
  4240. #[cfg(feature = "diagnostics")]
  4241. pub(crate) fn extent(address: u64) -> Option<(u64, u64)> {
  4242. buffers()
  4243. .range(..=(address, usize::MAX))
  4244. .rev()
  4245. .take(64)
  4246. .find(|(_, e)| e.end > address)
  4247. .map(|(k, e)| (k.0, e.end - k.0))
  4248. }
  4249. /// Title memory `[at, at + len)` is about to show something else or be
  4250. /// given up: what is in place there (`crate::inplace`) is taken out of the
  4251. /// tables, so that the next ask makes a copy or opens the memory anew, and
  4252. /// goes when no list and no slot holds it any more. Returns how many.
  4253. pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 {
  4254. let end = at.saturating_add(len);
  4255. let mut gone: Vec<Arc<Shadow>> = Vec::new();
  4256. {
  4257. let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4258. let keys: Vec<(u64, u64)> = map
  4259. .range((at.saturating_sub(WINDOW), 0)..(end, 0))
  4260. .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at)
  4261. .map(|(key, _)| *key)
  4262. .collect();
  4263. gone.extend(keys.into_iter().filter_map(|key| map.remove(&key)));
  4264. }
  4265. {
  4266. // As `lookup` finds a buffer: among the 256 that start below.
  4267. let mut map = buffers();
  4268. for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) {
  4269. if entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()) {
  4270. gone.extend(entry.shadow.take());
  4271. }
  4272. }
  4273. }
  4274. let n = gone.len() as u64;
  4275. for shadow in gone {
  4276. crate::host::retire(shadow);
  4277. }
  4278. n
  4279. }
  4280. /// For the in-place census (`crate::inplace`): the title buffers (start,
  4281. /// bytes, false) and the windows outside buffers that have a copy (start,
  4282. /// bytes, true).
  4283. pub(crate) fn spans() -> Vec<(u64, u64, bool)> {
  4284. let mut spans: Vec<(u64, u64, bool)> = buffers_read().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect();
  4285. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4286. spans.extend(loose.keys().map(|&(start, len)| (start, len, true)));
  4287. spans
  4288. }
  4289. /// The copy of the innermost title buffer holding `[address, address +
  4290. /// len)`, made on first use. A `len` of 0 or 1 is an ask without a length
  4291. /// (a root view: the caller reads on to the copy's end).
  4292. pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4293. lookup(address, len, false)
  4294. }
  4295. /// As [`find`], for an ask that is done with the copy when its list has
  4296. /// run (a draw's vertex and index buffers, indirect arguments): outside
  4297. /// buffer objects it takes a window that is there already and holds the
  4298. /// range ([`holder`]), and makes one of its own only if none does.
  4299. ///
  4300. /// [`find`] names a window by the ask alone, which a descriptor slot needs
  4301. /// (the slot shows the window its view found when it was made, and the
  4302. /// pass that brings it up to date must find the same one). A draw needs no
  4303. /// such thing: it binds the copy it found and brings that copy up to date.
  4304. /// Named by the ask alone, every draw's range was a window of its own
  4305. /// wherever the windows are cut finer than 4 MiB: draws that bind
  4306. /// different ranges of the same memory then each copied their range, and
  4307. /// windows nothing asked for again for ten seconds were let go and made
  4308. /// (and copied) anew. Run 71, on a 256 KiB grid: 350 MB copied per frame
  4309. /// against 120 MB, 7,087 write-watch askings against 2,600, and 5,263
  4310. /// windows (4.5 GB) let go in two minutes against 393 in a whole run.
  4311. pub(crate) fn find_any(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4312. // With whole windows (the default) there is one window to a cell and
  4313. // nothing to choose: exactly `find`.
  4314. if !fine() {
  4315. return find(address, len);
  4316. }
  4317. lookup(address, len, true)
  4318. }
  4319. /// The copy [`find`] gives for a range inside a title buffer, if it was made.
  4320. pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4321. let end = address.checked_add(len.max(1))?;
  4322. buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone())
  4323. }
  4324. fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
  4325. let quick = quick_find();
  4326. if quick && let Some(shadow) = found(address, len) {
  4327. return Some(shadow);
  4328. }
  4329. let end = address.checked_add(len.max(1))?;
  4330. {
  4331. let map = buffers_read();
  4332. match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) {
  4333. // The copy is made already (nearly always).
  4334. Some((_, Entry { shadow: Some(shadow), .. })) => {
  4335. if quick {
  4336. // (Nobody changes the map while this lock is held.)
  4337. remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow);
  4338. }
  4339. return Some(shadow.clone());
  4340. }
  4341. Some(_) => {}
  4342. None => {
  4343. drop(map);
  4344. return loose(address, end, len <= 1, any);
  4345. }
  4346. }
  4347. }
  4348. let mut map = buffers();
  4349. let key = map
  4350. .range(..=(address, usize::MAX))
  4351. .rev()
  4352. .take(64)
  4353. .find(|(_, e)| e.end >= end)
  4354. .map(|(k, _)| *k);
  4355. let Some(key) = key else {
  4356. drop(map);
  4357. return loose(address, end, len <= 1, any);
  4358. };
  4359. let entry = map.get_mut(&key)?;
  4360. if entry.shadow.is_none() {
  4361. let len = entry.end - key.0;
  4362. // Rounded up so that views ending in the buffer's last 256 bytes fit.
  4363. // Shaders write some buffers (unordered access), so not upload memory.
  4364. let size = len.next_multiple_of(1 << 16);
  4365. // In place, if asked for and the memory can be opened
  4366. // (`crate::inplace::place_for`): the buffer is the title's own
  4367. // memory. Not the big ones `cards` puts in the card's memory: those
  4368. // are read too often to stay in the PC's.
  4369. let big = cards() && (size >= card_limits().0 || card_all());
  4370. if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) {
  4371. entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false)));
  4372. return entry.shadow.clone();
  4373. }
  4374. let (buffer, data) = host()?.shared_buffer(size)?;
  4375. crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0));
  4376. // A big one, with `cards`: shaders get a buffer in the card's own
  4377. // memory, and the one just made is the CPU's side.
  4378. let (buffer, card) = match card_for(size) {
  4379. Some(on_card) => {
  4380. crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0));
  4381. tracing::info!(
  4382. start = format_args!("{:#x}", key.0),
  4383. len,
  4384. "a buffer's host copy is in the card's memory"
  4385. );
  4386. let card = Card {
  4387. staging: buffer,
  4388. before: Mutex::default(),
  4389. dirty: Mutex::default(),
  4390. sent: Mutex::default(),
  4391. touched: Default::default(),
  4392. size,
  4393. };
  4394. (on_card, Some(card))
  4395. }
  4396. None => (buffer, None),
  4397. };
  4398. // SAFETY: a live buffer.
  4399. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4400. if len >= 16 << 20 {
  4401. tracing::info!(
  4402. start = format_args!("{:#x}", key.0),
  4403. len,
  4404. "large buffer copied to the host"
  4405. );
  4406. } else {
  4407. tracing::debug!(
  4408. start = format_args!("{:#x}", key.0),
  4409. len,
  4410. "buffer copied to the host"
  4411. );
  4412. }
  4413. let mut shadow = Shadow::new(buffer, data, gpu, key.0, len);
  4414. shadow.card = card;
  4415. let shadow = Arc::new(shadow);
  4416. if shadow.card.is_some() {
  4417. CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
  4418. }
  4419. entry.shadow = Some(shadow);
  4420. }
  4421. entry.shadow.clone()
  4422. }
  4423. /// Titles also use memory outside any buffer object as GPU memory (
  4424. /// the title's interface vertices, from its own allocator). Such memory
  4425. /// gets copies of the aligned windows it touches.
  4426. /// A window nothing names any more is let go ([`let_go_idle`]).
  4427. /// shortcut: a window is 4 MiB however little of it is read (the memory
  4428. /// line says how much was ever asked for, and how much was ever copied);
  4429. /// [`window`] cuts the windows of asks that give a length on a finer grid.
  4430. const WINDOW: u64 = 4 << 20;
  4431. /// The grid the windows of asks with a length are cut on, in bytes: 4 MiB
  4432. /// unless `VICTORY_WINDOW_KB` names a smaller power of two (64 at least).
  4433. /// A window is the PC's memory, all of it, however little of it is read:
  4434. /// 803 windows held 3.3 GB in run 60's gameplay, and all that was ever
  4435. /// asked for in them lay within 1.6 GB. On a grid of 1 MiB or 256 KiB a
  4436. /// window ends nearer to what is read. An ask without a length keeps the
  4437. /// 4 MiB grid whatever is set: a root view reads from its address to its
  4438. /// window's end, and mesh streams bound that way reach megabytes.
  4439. /// shortcut: the default stays 4 MiB until a run with the memory line's
  4440. /// window counts has shown what the finer grids give; the same memory
  4441. /// asked for with different ranges then lies in more than one window.
  4442. fn window() -> u64 {
  4443. static GRID: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  4444. *GRID.get_or_init(|| {
  4445. let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::<u64>().ok());
  4446. grid(kb)
  4447. })
  4448. }
  4449. /// The window grid in bytes for a setting in KiB: a power of two from
  4450. /// 64 KiB to 4 MiB, 4 MiB for anything else.
  4451. fn grid(kb: Option<u64>) -> u64 {
  4452. match kb {
  4453. Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10,
  4454. _ => WINDOW,
  4455. }
  4456. }
  4457. /// The window (start, bytes) of title memory for an ask of `[address,
  4458. /// end)` on a grid of `grid` bytes.
  4459. fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) {
  4460. let start = address & !(grid - 1);
  4461. (start, end.next_multiple_of(grid) - start)
  4462. }
  4463. /// Whether the window of an ask without a length begins at the ask instead
  4464. /// of at the 4 MiB line below it. Such an ask (a root view) reads from its
  4465. /// address to the end of its 4 MiB cell; what lies below the lowest
  4466. /// address ever asked for in the cell is memory the host zeroed and nothing
  4467. /// reads (513 of run 65's 782 windows were asked for that way, 2,052 MB;
  4468. /// of all windows' 3,236 MB, 1,988 MB were ever copied). With this on, the
  4469. /// window is the cell's tail from the ask's step on ([`TAIL_STEP`]); an ask
  4470. /// lower in the cell later makes a longer tail, which every ask from then
  4471. /// on takes, and the shorter one goes when nothing holds it any more.
  4472. /// shortcut: off unless `VICTORY_WINDOW_TAILS=1`. A longer tail is another
  4473. /// host buffer than the shorter one: what was bound to the shorter stays
  4474. /// right only because every list brings up to date the copy it bound
  4475. /// (`draw.rs` keeps a root view's copy with its slot). It pays only
  4476. /// together with `VICTORY_WINDOW_KB` below 4096: on the 4 MiB grid an ask
  4477. /// with a length in the same cell makes the whole cell's window, and the
  4478. /// tail is that.
  4479. fn tails() -> bool {
  4480. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  4481. *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_TAILS").is_some_and(|v| v == "1"))
  4482. }
  4483. /// Tails begin on multiples of this. A longer tail is a new host buffer,
  4484. /// filled from title memory from its first byte to its last: begun on the
  4485. /// 64 KiB page of each ask, a cell whose asks came from the top down made
  4486. /// up to 63 of them, one after the other (part of run 71's copies). On
  4487. /// this step it is 15 at most, and a tail holds up to 192 KiB it did not
  4488. /// need.
  4489. const TAIL_STEP: u64 = 256 << 10;
  4490. /// The window (start, bytes) a tail ask at `address` makes: from the ask's
  4491. /// step ([`TAIL_STEP`]) to the end of its 4 MiB cell.
  4492. fn tail_of(address: u64, end: u64) -> (u64, u64) {
  4493. let (cell, len) = window_of(address, end, WINDOW);
  4494. let start = address & !(TAIL_STEP - 1);
  4495. (start, cell + len - start)
  4496. }
  4497. /// Of `windows` (start, bytes), the one an ask of `[address, end)` that
  4498. /// may take any window takes ([`find_any`]): the longest that holds the
  4499. /// whole range.
  4500. fn holder(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u64) -> Option<(u64, u64)> {
  4501. windows
  4502. .filter(|&(start, bytes)| start <= address && start + bytes >= end)
  4503. .max_by_key(|&(start, bytes)| (bytes, std::cmp::Reverse(start)))
  4504. }
  4505. /// Whether windows may be smaller than their 4 MiB cell (a finer grid, or
  4506. /// tails): only then is there more than one window to choose from.
  4507. fn fine() -> bool {
  4508. tails() || window() < WINDOW
  4509. }
  4510. /// For the memory line: the bytes of title memory the windows alive lie
  4511. /// over (each byte once), beside the windows' own bytes in
  4512. /// [`memory`]: the difference is memory that is in more than one window,
  4513. /// which is copied once for each.
  4514. #[cfg(feature = "diagnostics")]
  4515. pub(crate) fn window_cover() -> u64 {
  4516. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4517. cover(loose.keys().copied())
  4518. }
  4519. /// The bytes `windows` (start, bytes; in order of start) lie over, each
  4520. /// byte once.
  4521. #[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))]
  4522. fn cover(windows: impl Iterator<Item = (u64, u64)>) -> u64 {
  4523. let (mut covered, mut reached) = (0, 0);
  4524. for (start, bytes) in windows {
  4525. let end = start + bytes;
  4526. if end > reached {
  4527. covered += end - start.max(reached);
  4528. reached = end;
  4529. }
  4530. }
  4531. covered
  4532. }
  4533. /// Of `windows` (start, bytes; in order), the longest tail a tail ask at
  4534. /// `address` can take: the first that begins in the ask's cell at or below
  4535. /// the ask's page and ends where the cell ends.
  4536. fn longest_tail(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u64) -> Option<(u64, u64)> {
  4537. let (cell, len) = window_of(address, end, WINDOW);
  4538. let step = address & !(TAIL_STEP - 1);
  4539. windows
  4540. .filter(|&(start, bytes)| start >= cell && start <= step && start + bytes == cell + len)
  4541. .min()
  4542. }
  4543. /// Whether `[address, address + len)` lies in one title buffer.
  4544. pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> {
  4545. let end = address.checked_add(len)?;
  4546. let map = buffers_read();
  4547. let found = map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end);
  4548. found.map(|(k, e)| (k.0, e.end - k.0))
  4549. }
  4550. /// Whether a title buffer of at most `most` bytes lies in `[address, address
  4551. /// + len)`, all of it or in part.
  4552. pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool {
  4553. let map = buffers_read();
  4554. map.range((address.saturating_sub(most), 0)..(address + len, 0))
  4555. .any(|(key, entry)| entry.end > address && entry.end - key.0 <= most)
  4556. }
  4557. /// A copy of the memory `[start, start + len)` (an arena of
  4558. /// [`crate::memory`]'s, its directory, title memory around a small buffer)
  4559. /// for the programs that find memory by address, on the card: the structures
  4560. /// rays are traced through, read with every step of every ray.
  4561. ///
  4562. /// What shaders write there by address is not brought back, so the copy is
  4563. /// the only place that has it. The CPU's side holds the bytes as they were
  4564. /// last taken, and only dwords that changed since go up.
  4565. pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
  4566. let host = host()?;
  4567. if !cards() || !host.card_ready() {
  4568. return None;
  4569. }
  4570. // At most so much on the card's own memory (4 GiB unless
  4571. // `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past
  4572. // that the side shaders see is in the PC's memory.
  4573. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  4574. static USED: AtomicU64 = AtomicU64::new(0);
  4575. let most = *MOST.get_or_init(|| {
  4576. let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::<u64>().ok());
  4577. mb.unwrap_or(4096) << 20
  4578. });
  4579. let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97);
  4580. let (staging, data) = host.shared_buffer(len)?;
  4581. let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most {
  4582. host.uav_buffer(len)
  4583. } else {
  4584. None
  4585. };
  4586. let buffer = match on_card {
  4587. Some(buffer) => buffer,
  4588. None => host.shared_buffer(len)?.0,
  4589. };
  4590. crate::host::name(&staging, || format!("title memory {start:#x}+{len:#x} by address, the CPU's side"));
  4591. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} by address"));
  4592. // (Counted down with the windows' on the card when it goes.)
  4593. WINDOW_CARD_BYTES.fetch_add(len, Ordering::Relaxed);
  4594. // SAFETY: a live buffer.
  4595. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4596. let mut shadow = Shadow::new(buffer, data, gpu, start, len);
  4597. shadow.window = true;
  4598. shadow.changes_only.store(true, Ordering::Relaxed);
  4599. shadow.card = Some(Card {
  4600. staging,
  4601. before: Mutex::default(),
  4602. dirty: Mutex::default(),
  4603. sent: Mutex::default(),
  4604. touched: Default::default(),
  4605. size: len,
  4606. });
  4607. let shadow = Arc::new(shadow);
  4608. CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
  4609. Some(shadow)
  4610. }
  4611. /// Copies of title memory outside buffers, by (start, length).
  4612. static LOOSE: std::sync::RwLock<BTreeMap<(u64, u64), Arc<Shadow>>> = std::sync::RwLock::new(BTreeMap::new());
  4613. fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Shadow>> {
  4614. let (cell, _) = window_of(address, end, WINDOW);
  4615. let named = window_of(address, end, if unsized_ask { WINDOW } else { window() });
  4616. // Under the lock, with the handing out: see `let_go_idle`.
  4617. let note = |shadow: &Shadow| {
  4618. // (Read first: the lines are shared by all recording threads.)
  4619. let now = crate::host::moment();
  4620. if shadow.used.load(Ordering::Relaxed) != now {
  4621. shadow.used.store(now, Ordering::Relaxed);
  4622. }
  4623. if shadow.asked[0].load(Ordering::Relaxed) > address {
  4624. shadow.asked[0].fetch_min(address, Ordering::Relaxed);
  4625. }
  4626. if shadow.asked[1].load(Ordering::Relaxed) < end {
  4627. shadow.asked[1].fetch_max(end, Ordering::Relaxed);
  4628. }
  4629. if unsized_ask {
  4630. shadow.unsized_asks.fetch_add(1, Ordering::Relaxed);
  4631. }
  4632. };
  4633. // The window is there already (nearly always): readers share the lock.
  4634. if !(unsized_ask && tails()) && !(any && fine() && !unsized_ask) {
  4635. let map = LOOSE.read().unwrap_or_else(|e| e.into_inner());
  4636. if let Some(shadow) = map.get(&named) {
  4637. note(shadow);
  4638. return Some(shadow.clone());
  4639. }
  4640. }
  4641. let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4642. let (start, len) = if unsized_ask && tails() {
  4643. let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key);
  4644. longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end))
  4645. } else if any && fine() && !unsized_ask {
  4646. // The windows that begin in the ask's cell at or below the ask (one
  4647. // that begins in a cell below and reaches this far is passed over:
  4648. // the ask then makes its own).
  4649. let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key);
  4650. holder(there, address, end).unwrap_or(named)
  4651. } else {
  4652. named
  4653. };
  4654. if let Some(shadow) = map.get(&(start, len)) {
  4655. note(shadow);
  4656. return Some(shadow.clone());
  4657. }
  4658. // In place, if asked for and the window's memory can be opened: the
  4659. // window is the title's own memory, with nothing to copy.
  4660. if let Some(placed) = crate::inplace::place_for(start, len, true) {
  4661. let shadow = Arc::new(Shadow::placed(placed, start, len, true));
  4662. note(&shadow);
  4663. map.insert((start, len), shadow.clone());
  4664. return Some(shadow);
  4665. }
  4666. // One buffer in the card's memory, filled by the CPU through the bus.
  4667. if let Some((buffer, data)) = window_mapped_for(len) {
  4668. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} mapped on the card"));
  4669. // SAFETY: a live buffer.
  4670. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4671. let mut shadow = Shadow::new(buffer, data, gpu, start, len);
  4672. shadow.window = true;
  4673. shadow.mapped = true;
  4674. let shadow = Arc::new(shadow);
  4675. note(&shadow);
  4676. map.insert((start, len), shadow.clone());
  4677. return Some(shadow);
  4678. }
  4679. let (buffer, data) = host()?.shared_buffer(len)?;
  4680. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
  4681. // With room for windows on the card (`window_card_most`): shaders get a
  4682. // buffer there, and the one just made is the CPU's side.
  4683. let (buffer, card) = match window_card_for(len) {
  4684. Some(on_card) => {
  4685. crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card"));
  4686. let card = Card {
  4687. staging: buffer,
  4688. before: Mutex::default(),
  4689. dirty: Mutex::default(),
  4690. sent: Mutex::default(),
  4691. touched: Default::default(),
  4692. size: len,
  4693. };
  4694. (on_card, Some(card))
  4695. }
  4696. None => (buffer, None),
  4697. };
  4698. // SAFETY: a live buffer.
  4699. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4700. tracing::debug!(
  4701. start = format_args!("{start:#x}"),
  4702. len,
  4703. "loose memory copied to the host"
  4704. );
  4705. let mut shadow = Shadow::new(buffer, data, gpu, start, len);
  4706. shadow.window = true;
  4707. shadow.card = card;
  4708. let shadow = Arc::new(shadow);
  4709. if shadow.card.is_some() {
  4710. CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
  4711. }
  4712. note(&shadow);
  4713. map.insert((start, len), shadow.clone());
  4714. Some(shadow)
  4715. }
  4716. /// Copies of single buffer views' own bytes ([`exact`]), by (start,
  4717. /// bytes), each with the asking that last took it; and the askings so far.
  4718. #[allow(clippy::type_complexity)]
  4719. static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc<Shadow>, u64)>)> = Mutex::new((0, BTreeMap::new()));
  4720. /// Since the last frame line: askings for such copies, and copies made.
  4721. static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  4722. /// A copy of the title memory `[address, address + len)` that starts at
  4723. /// `address` itself: for a buffer view whose bytes do not start on an
  4724. /// element of the copy its buffer has (`descriptor/host.rs` `view_home`).
  4725. /// A host view counts its first element from its buffer's start; a console
  4726. /// view starts at any address, and the title places views at ring
  4727. /// positions inside its big GPU heap. Such a view was refused and its slot
  4728. /// read zeros ("buffer view not on an element of its host copy", in every
  4729. /// run; upstream VIctory 86a5ed6 found its meshlet culling constants and
  4730. /// colour-bake parameter blocks among them and gives each a copy of its
  4731. /// own bytes, as here).
  4732. ///
  4733. /// The copy is brought up to date and written back like any other (a list
  4734. /// refreshes the copy its view's slot shows, `buffer_copy`). Kept by
  4735. /// (start, bytes) for as long as a list or a slot holds it; of the others,
  4736. /// those not asked for lately go once there are many (ring positions
  4737. /// change every frame).
  4738. pub(crate) fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4739. /// Copies kept before the idle ones are looked for, and the askings an
  4740. /// idle one stays for.
  4741. const MANY: usize = 256;
  4742. const LATELY: u64 = 512;
  4743. /// The largest, and no view the title made on purpose: off its dwords.
  4744. const MOST: u64 = 64 << 20;
  4745. if len == 0 || len > MOST || !address.is_multiple_of(4) {
  4746. return None;
  4747. }
  4748. EXACT_STATS[0].fetch_add(1, Ordering::Relaxed);
  4749. let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner());
  4750. let (tick, map) = &mut *guard;
  4751. *tick += 1;
  4752. let now = *tick;
  4753. if let Some((shadow, used)) = map.get_mut(&(address, len)) {
  4754. *used = now;
  4755. shadow.used.store(crate::host::moment(), Ordering::Relaxed);
  4756. return Some(shadow.clone());
  4757. }
  4758. if map.len() >= MANY {
  4759. // Held by the map alone (no list), its buffer by the copy alone (no
  4760. // slot shows it), and not asked for lately.
  4761. map.retain(|_, (shadow, used)| {
  4762. Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now
  4763. });
  4764. }
  4765. let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?;
  4766. crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}"));
  4767. // SAFETY: a live buffer.
  4768. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4769. let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len));
  4770. map.insert((address, len), (shadow.clone(), now));
  4771. EXACT_STATS[1].fetch_add(1, Ordering::Relaxed);
  4772. OWN_MADE.fetch_add(1, Ordering::Relaxed);
  4773. Some(shadow)
  4774. }
  4775. /// Copies of single views' bytes made since the start.
  4776. pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0);
  4777. /// With the frame line: the buffer views that got a copy of their own
  4778. /// bytes ([`exact`]), per frame over `frames`, and the copies kept now.
  4779. /// Nothing while there are none.
  4780. pub(crate) fn exact_line(frames: f64) {
  4781. let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed));
  4782. if asked == 0 {
  4783. return;
  4784. }
  4785. let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len();
  4786. tracing::info!(
  4787. "buffer views off their copy's elements (they were refused and read zeros; VICTORY_VIEW_BYTES=0 refuses them again): \
  4788. {:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept",
  4789. asked as f64 / frames,
  4790. made as f64 / frames
  4791. );
  4792. }
  4793. #[cfg(test)]
  4794. mod window_tests {
  4795. use super::{
  4796. WINDOW, cover, default_card_limits_mb, grid, holder, longest_tail, resolve_card_limits,
  4797. tail_of, window_of,
  4798. };
  4799. #[test]
  4800. fn card_limits_scale_with_local_vram_budget() {
  4801. const GIB: u64 = 1 << 30;
  4802. const MIB: u64 = 1 << 20;
  4803. // Unknown (WARP / query failure) and <= 12 GiB keep the 12 GB baseline.
  4804. assert_eq!(default_card_limits_mb(None), (16, 512));
  4805. assert_eq!(default_card_limits_mb(Some(8 * GIB)), (16, 512));
  4806. assert_eq!(default_card_limits_mb(Some(11 * GIB)), (16, 512));
  4807. assert_eq!(default_card_limits_mb(Some(12 * GIB)), (16, 512));
  4808. // 16 GB tier (> 12 GiB, < 20 GiB), including WDDM budgets around 13.5–15 GiB.
  4809. assert_eq!(default_card_limits_mb(Some(13 * GIB)), (4, 2048));
  4810. assert_eq!(default_card_limits_mb(Some(14 * GIB)), (4, 2048));
  4811. assert_eq!(default_card_limits_mb(Some(15 * GIB)), (4, 2048));
  4812. assert_eq!(default_card_limits_mb(Some(16 * GIB)), (4, 2048));
  4813. // 24–32+ GB tier (>= 20 GiB): 1 MiB min, 25% of budget capped at 8192 MiB.
  4814. assert_eq!(default_card_limits_mb(Some(20 * GIB)), (1, 5120));
  4815. assert_eq!(default_card_limits_mb(Some(24 * GIB)), (1, 6144));
  4816. assert_eq!(default_card_limits_mb(Some(32 * GIB)), (1, 8192));
  4817. assert_eq!(default_card_limits_mb(Some(48 * GIB)), (1, 8192));
  4818. // Explicit env overrides always win, clamp min to >= 1 MiB, and saturate on overflow.
  4819. assert_eq!(resolve_card_limits(Some(32 * GIB), Some(8), Some(4096)), (8 * MIB, 4096 * MIB));
  4820. assert_eq!(resolve_card_limits(Some(12 * GIB), Some(0), Some(1024)), (MIB, 1024 * MIB));
  4821. assert_eq!(resolve_card_limits(None, Some(u64::MAX), Some(u64::MAX)), (u64::MAX, u64::MAX));
  4822. assert_eq!(resolve_card_limits(None, None, None), (16 * MIB, 512 * MIB));
  4823. }
  4824. /// An ask that may take any window takes the longest that holds all of
  4825. /// it, and none that holds only a part.
  4826. #[test]
  4827. fn an_ask_takes_the_longest_window_that_holds_it() {
  4828. let cell = 0xd_1200_0000u64;
  4829. let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000);
  4830. assert_eq!(holder([].into_iter(), ask, end), None);
  4831. let there = [
  4832. (cell, 0x4_0000), // ends below the ask
  4833. (cell + 0x8_0000, 0x2_0000), // holds its first half only
  4834. (cell + 0x8_0000, 0x4_0000), // holds it
  4835. (cell + 0x4_0000, 0x10_0000), // holds it, longer
  4836. (cell + 0xa_0000, 0x40_0000), // begins above it
  4837. ];
  4838. assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000)));
  4839. // Of two as long, the one that begins lower.
  4840. let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)];
  4841. assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000)));
  4842. }
  4843. /// What windows lie over counts each byte once.
  4844. #[test]
  4845. fn overlapping_windows_cover_their_memory_once() {
  4846. assert_eq!(cover([].into_iter()), 0);
  4847. let apart = [(0x10_0000u64, 0x4_0000u64), (0x20_0000, 0x4_0000)];
  4848. assert_eq!(cover(apart.into_iter()), 0x8_0000);
  4849. // One inside another, one overlapping its end, one touching.
  4850. let over = [
  4851. (0x10_0000u64, 0x10_0000u64),
  4852. (0x14_0000, 0x4_0000),
  4853. (0x1c_0000, 0x8_0000),
  4854. (0x24_0000, 0x4_0000),
  4855. ];
  4856. assert_eq!(cover(over.into_iter()), 0x18_0000);
  4857. }
  4858. /// A tail runs from the ask's page to the end of its 4 MiB cell, and an
  4859. /// ask takes the longest tail there is that holds it.
  4860. #[test]
  4861. fn tails_run_to_the_cells_end_and_the_longest_is_taken() {
  4862. let cell = 0xd_1200_0000u64;
  4863. let ask = cell + 0x12_3456;
  4864. assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000));
  4865. // The cell's first page: the whole cell, the window there always was.
  4866. assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW));
  4867. let end = cell + WINDOW;
  4868. let tail = |from: u64| (cell + from, WINDOW - from);
  4869. // Nothing there, or only tails that begin above the ask.
  4870. assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None);
  4871. assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None);
  4872. // The longest of those that hold the ask; windows that do not reach
  4873. // the cell's end (cut on a finer grid for asks with a length) and
  4874. // windows of other cells are not tails.
  4875. let there = [
  4876. (cell - WINDOW, WINDOW),
  4877. (cell, 0x4_0000),
  4878. tail(0x8_0000),
  4879. tail(0x10_0000),
  4880. (cell + 0x10_0000, 0x4_0000),
  4881. tail(0x20_0000),
  4882. ];
  4883. assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000)));
  4884. let (start, bytes) = tail(0x8_0000);
  4885. assert!(start <= ask && start + bytes == end);
  4886. // The whole cell's window is the longest tail of all.
  4887. let with_whole = [(cell, WINDOW), tail(0x8_0000)];
  4888. assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW)));
  4889. }
  4890. /// The setting takes powers of two from 64 KiB to 4 MiB; anything else
  4891. /// leaves the grid as it was.
  4892. #[test]
  4893. fn the_grid_is_a_power_of_two_or_the_default() {
  4894. assert_eq!(grid(None), WINDOW);
  4895. assert_eq!(grid(Some(4096)), WINDOW);
  4896. assert_eq!(grid(Some(1024)), 1 << 20);
  4897. assert_eq!(grid(Some(256)), 256 << 10);
  4898. assert_eq!(grid(Some(64)), 64 << 10);
  4899. for bad in [0, 32, 100, 1000, 8192] {
  4900. assert_eq!(grid(Some(bad)), WINDOW, "{bad}");
  4901. }
  4902. }
  4903. /// A window holds its ask and is cut on the grid; on the default grid
  4904. /// it is the window there always was.
  4905. #[test]
  4906. fn windows_hold_their_ask_on_the_grid() {
  4907. let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000);
  4908. assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20));
  4909. assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20));
  4910. assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10));
  4911. // An ask across a grid line takes both cells.
  4912. let end = address + 0x4_0000;
  4913. assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10));
  4914. for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] {
  4915. let (start, len) = window_of(address, end, g);
  4916. assert!(start <= address && start + len >= end);
  4917. assert!(start % g == 0 && len % g == 0);
  4918. }
  4919. }
  4920. }
  4921. /// For device-removed reports: the copy of title memory whose host range
  4922. /// starts closest below host GPU address `va`, and where `va` is in it.
  4923. pub(crate) fn near(va: u64) -> String {
  4924. let mut all: Vec<(u64, u64, u64)> = buffers()
  4925. .values()
  4926. .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len)))
  4927. .collect();
  4928. all.extend(
  4929. LOOSE
  4930. .read()
  4931. .unwrap_or_else(|e| e.into_inner())
  4932. .values()
  4933. .map(|s| (s.gpu, s.start, s.len)),
  4934. );
  4935. let below = all.iter().filter(|c| c.0 <= va).max();
  4936. let above = all.iter().filter(|c| c.0 > va).min();
  4937. let mut text = match below {
  4938. Some(&(gpu, start, len)) => format!(
  4939. "; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}",
  4940. va - gpu
  4941. ),
  4942. None => "; no title memory copy below it".into(),
  4943. };
  4944. if let Some(&(gpu, start, len)) = above {
  4945. text.push_str(&format!(
  4946. "; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)",
  4947. all.len()
  4948. ));
  4949. }
  4950. text
  4951. }