shadow.rs 227 KB

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