shadow.rs 220 KB

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